code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE RecursiveDo, RankNTypes, NamedFieldPuns, RecordWildCards #-}
module Distribution.Server.Features.Upload (
UploadFeature(..),
UploadResource(..),
initUploadFeature,
UploadResult(..),
) where
import Distribution.Server.Framework
import Distribution.Server.Framework.BackupDump
import Distribution.Server.Features.Upload.State
import Distribution.Server.Features.Upload.Backup
import Distribution.Server.Features.Core
import Distribution.Server.Features.Users
import Distribution.Server.Users.Backup
import Distribution.Server.Packages.Types
import qualified Distribution.Server.Users.Types as Users
import qualified Distribution.Server.Users.Group as Group
import Distribution.Server.Users.Group (UserGroup(..), GroupDescription(..), nullDescription)
import qualified Distribution.Server.Framework.BlobStorage as BlobStorage
import qualified Distribution.Server.Packages.Unpack as Upload
import Distribution.Server.Packages.PackageIndex (PackageIndex)
import qualified Distribution.Server.Packages.PackageIndex as PackageIndex
import Data.Maybe (fromMaybe)
import Data.Time.Clock (getCurrentTime)
import Data.Function (fix)
import Data.ByteString.Lazy (ByteString)
import Distribution.Package
import Distribution.PackageDescription (GenericPackageDescription)
import Distribution.Text (display)
import qualified Distribution.Server.Util.GZip as GZip
data UploadFeature = UploadFeature {
-- | The package upload `HackageFeature`.
uploadFeatureInterface :: HackageFeature,
-- | Upload resources.
uploadResource :: UploadResource,
-- | The main upload routine. This uses extractPackage on a multipart
-- request to get contextual information.
uploadPackage :: ServerPartE UploadResult,
--TODO: consider moving the trustee and/or per-package maintainer groups
-- lower down in the feature hierarchy; many other features want to
-- use the trustee group purely for auth decisions
-- | The group of Hackage trustees.
trusteesGroup :: UserGroup,
-- | The group of package uploaders.
uploadersGroup :: UserGroup,
-- | The group of maintainers for a given package.
maintainersGroup :: PackageName -> UserGroup,
-- | Requiring being logged in as the maintainer of a package.
guardAuthorisedAsMaintainer :: PackageName -> ServerPartE (),
-- | Requiring being logged in as the maintainer of a package or a trustee.
guardAuthorisedAsMaintainerOrTrustee :: PackageName -> ServerPartE (),
-- | Takes an upload request and, depending on the result of the
-- passed-in function, either commits the uploaded tarball to the blob
-- storage or throws it away and yields an error.
extractPackage :: (Users.UserId -> UploadResult -> IO (Maybe ErrorResponse))
-> ServerPartE (Users.UserId, UploadResult, PkgTarball)
}
instance IsHackageFeature UploadFeature where
getFeatureInterface = uploadFeatureInterface
data UploadResource = UploadResource {
-- | The page for uploading a package, the same as `corePackagesPage`.
uploadIndexPage :: Resource,
-- | The page for deleting a package, the same as `corePackagePage`.
--
-- This is fairly dangerous and is not currently used.
deletePackagePage :: Resource,
-- | The maintainers group for each package.
maintainersGroupResource :: GroupResource,
-- | The trustee group.
trusteesGroupResource :: GroupResource,
-- | The allowed-uploaders group.
uploadersGroupResource :: GroupResource,
-- | URI for `maintainersGroupResource` given a format and `PackageId`.
packageMaintainerUri :: String -> PackageId -> String,
-- | URI for `trusteesGroupResource` given a format.
trusteeUri :: String -> String,
-- | URI for `uploadersGroupResource` given a format.
uploaderUri :: String -> String
}
-- | The representation of an intermediate result in the upload process,
-- indicating a package which meets the requirements to go into Hackage.
data UploadResult = UploadResult {
-- The parsed Cabal file.
uploadDesc :: !GenericPackageDescription,
-- The text of the Cabal file.
uploadCabal :: !ByteString,
-- Any warnings from unpacking the tarball.
uploadWarnings :: ![String]
}
initUploadFeature :: ServerEnv
-> IO (UserFeature -> CoreFeature -> IO UploadFeature)
initUploadFeature env@ServerEnv{serverStateDir} = do
-- Canonical state
trusteesState <- trusteesStateComponent serverStateDir
uploadersState <- uploadersStateComponent serverStateDir
maintainersState <- maintainersStateComponent serverStateDir
return $ \user@UserFeature{..} core@CoreFeature{..} -> do
-- Recusively tie the knot: the feature contains new user group resources
-- but we make the functions needed to create those resources along with
-- the feature
rec let (feature,
trusteesGroupDescription, uploadersGroupDescription,
maintainersGroupDescription)
= uploadFeature env core user
trusteesState trusteesGroup trusteesGroupResource
uploadersState uploadersGroup uploadersGroupResource
maintainersState maintainersGroup maintainersGroupResource
(trusteesGroup, trusteesGroupResource) <-
groupResourceAt "/packages/trustees" trusteesGroupDescription
(uploadersGroup, uploadersGroupResource) <-
groupResourceAt "/packages/uploaders" uploadersGroupDescription
pkgNames <- PackageIndex.packageNames <$> queryGetPackageIndex
(maintainersGroup, maintainersGroupResource) <-
groupResourcesAt "/package/:package/maintainers"
maintainersGroupDescription
(\pkgname -> [("package", display pkgname)])
(packageInPath coreResource)
pkgNames
return feature
trusteesStateComponent :: FilePath -> IO (StateComponent AcidState HackageTrustees)
trusteesStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "HackageTrustees") initialHackageTrustees
return StateComponent {
stateDesc = "Trustees"
, stateHandle = st
, getState = query st GetHackageTrustees
, putState = update st . ReplaceHackageTrustees . trusteeList
, backupState = \_ (HackageTrustees trustees) -> [csvToBackup ["trustees.csv"] $ groupToCSV trustees]
, restoreState = HackageTrustees <$> groupBackup ["trustees.csv"]
, resetState = trusteesStateComponent
}
uploadersStateComponent :: FilePath -> IO (StateComponent AcidState HackageUploaders)
uploadersStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "HackageUploaders") initialHackageUploaders
return StateComponent {
stateDesc = "Uploaders"
, stateHandle = st
, getState = query st GetHackageUploaders
, putState = update st . ReplaceHackageUploaders . uploaderList
, backupState = \_ (HackageUploaders uploaders) -> [csvToBackup ["uploaders.csv"] $ groupToCSV uploaders]
, restoreState = HackageUploaders <$> groupBackup ["uploaders.csv"]
, resetState = uploadersStateComponent
}
maintainersStateComponent :: FilePath -> IO (StateComponent AcidState PackageMaintainers)
maintainersStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "PackageMaintainers") initialPackageMaintainers
return StateComponent {
stateDesc = "Package maintainers"
, stateHandle = st
, getState = query st AllPackageMaintainers
, putState = update st . ReplacePackageMaintainers
, backupState = \_ (PackageMaintainers mains) -> [maintToExport mains]
, restoreState = maintainerBackup
, resetState = maintainersStateComponent
}
uploadFeature :: ServerEnv
-> CoreFeature
-> UserFeature
-> StateComponent AcidState HackageTrustees -> UserGroup -> GroupResource
-> StateComponent AcidState HackageUploaders -> UserGroup -> GroupResource
-> StateComponent AcidState PackageMaintainers -> (PackageName -> UserGroup) -> GroupResource
-> (UploadFeature,
UserGroup,
UserGroup,
PackageName -> UserGroup)
uploadFeature ServerEnv{serverBlobStore = store}
CoreFeature{ coreResource
, queryGetPackageIndex
, updateAddPackage
}
UserFeature{..}
trusteesState trusteesGroup trusteesGroupResource
uploadersState uploadersGroup uploadersGroupResource
maintainersState maintainersGroup maintainersGroupResource
= ( UploadFeature {..}
, trusteesGroupDescription, uploadersGroupDescription, maintainersGroupDescription)
where
uploadFeatureInterface = (emptyHackageFeature "upload") {
featureDesc = "Support for package uploads, and define groups for trustees, uploaders, and package maintainers"
, featureResources =
[ uploadIndexPage uploadResource
, groupResource maintainersGroupResource
, groupUserResource maintainersGroupResource
, groupResource trusteesGroupResource
, groupUserResource trusteesGroupResource
, groupResource uploadersGroupResource
, groupUserResource uploadersGroupResource
]
, featureState = [
abstractAcidStateComponent trusteesState
, abstractAcidStateComponent uploadersState
, abstractAcidStateComponent maintainersState
]
}
uploadResource = UploadResource
{ uploadIndexPage = (extendResource (corePackagesPage coreResource)) { resourcePost = [] }
, deletePackagePage = (extendResource (corePackagePage coreResource)) { resourceDelete = [] }
, maintainersGroupResource = maintainersGroupResource
, trusteesGroupResource = trusteesGroupResource
, uploadersGroupResource = uploadersGroupResource
, packageMaintainerUri = \format pkgname -> renderResource
(groupResource maintainersGroupResource) [display pkgname, format]
, trusteeUri = \format -> renderResource (groupResource trusteesGroupResource) [format]
, uploaderUri = \format -> renderResource (groupResource uploadersGroupResource) [format]
}
--------------------------------------------------------------------------------
-- User groups and authentication
trusteesGroupDescription :: UserGroup
trusteesGroupDescription = UserGroup {
groupDesc = trusteeDescription,
queryUserGroup = queryState trusteesState GetTrusteesList,
addUserToGroup = updateState trusteesState . AddHackageTrustee,
removeUserFromGroup = updateState trusteesState . RemoveHackageTrustee,
groupsAllowedToAdd = [adminGroup],
groupsAllowedToDelete = [adminGroup]
}
uploadersGroupDescription :: UserGroup
uploadersGroupDescription = UserGroup {
groupDesc = uploaderDescription,
queryUserGroup = queryState uploadersState GetUploadersList,
addUserToGroup = updateState uploadersState . AddHackageUploader,
removeUserFromGroup = updateState uploadersState . RemoveHackageUploader,
groupsAllowedToAdd = [adminGroup],
groupsAllowedToDelete = [adminGroup]
}
maintainersGroupDescription :: PackageName -> UserGroup
maintainersGroupDescription name =
fix $ \thisgroup ->
UserGroup {
groupDesc = maintainerDescription name,
queryUserGroup = queryState maintainersState $ GetPackageMaintainers name,
addUserToGroup = updateState maintainersState . AddPackageMaintainer name,
removeUserFromGroup = updateState maintainersState . RemovePackageMaintainer name,
groupsAllowedToAdd = [thisgroup, adminGroup],
groupsAllowedToDelete = [thisgroup, adminGroup]
}
maintainerDescription :: PackageName -> GroupDescription
maintainerDescription pkgname = GroupDescription
{ groupTitle = "Maintainers"
, groupEntity = Just (pname, Just $ "/package/" ++ pname)
, groupPrologue = "Maintainers for a package can upload new versions and adjust other attributes in the package database."
}
where pname = display pkgname
trusteeDescription :: GroupDescription
trusteeDescription = nullDescription { groupTitle = "Package trustees", groupPrologue = "The role of trustees is to help to curate the whole package collection. Trustees have a limited ability to edit package information, for the entire package database (as opposed to package maintainers who have full control over individual packages). Trustees can edit .cabal files, edit other package metadata and upload documentation but they cannot upload new package versions." }
uploaderDescription :: GroupDescription
uploaderDescription = nullDescription { groupTitle = "Package uploaders", groupPrologue = "Package uploaders are allowed to upload packages. Note that if a package already exists then you also need to be in the maintainer group for that package." }
guardAuthorisedAsMaintainer :: PackageName -> ServerPartE ()
guardAuthorisedAsMaintainer pkgname =
guardAuthorised_ [InGroup (maintainersGroup pkgname)]
guardAuthorisedAsMaintainerOrTrustee :: PackageName -> ServerPartE ()
guardAuthorisedAsMaintainerOrTrustee pkgname =
guardAuthorised_ [InGroup (maintainersGroup pkgname), InGroup trusteesGroup]
----------------------------------------------------
-- This is the upload function. It returns a generic result for multiple formats.
uploadPackage :: ServerPartE UploadResult
uploadPackage = do
guardAuthorised_ [InGroup uploadersGroup]
pkgIndex <- queryGetPackageIndex
(uid, uresult, tarball) <- extractPackage $ \uid info ->
processUpload pkgIndex uid info
now <- liftIO getCurrentTime
let (UploadResult pkg pkgStr _) = uresult
pkgid = packageId pkg
cabalfile = CabalFileText pkgStr
uploadinfo = (now, uid)
success <- updateAddPackage pkgid cabalfile uploadinfo (Just tarball)
if success
then do
-- make package maintainers group for new package
let existedBefore = packageExists pkgIndex pkgid
when (not existedBefore) $
liftIO $ addUserToGroup (maintainersGroup (packageName pkgid)) uid
return uresult
-- this is already checked in processUpload, and race conditions are highly unlikely but imaginable
else errForbidden "Upload failed" [MText "Package already exists."]
-- This is a processing funtion for extractPackage that checks upload-specific requirements.
-- Does authentication, though not with requirePackageAuth, because it has to be IO.
-- Some other checks can be added, e.g. if a package with a later version exists
processUpload :: PackageIndex PkgInfo -> Users.UserId -> UploadResult -> IO (Maybe ErrorResponse)
processUpload state uid res = do
let pkg = packageId (uploadDesc res)
pkgGroup <- queryUserGroup (maintainersGroup (packageName pkg))
if packageIdExists state pkg
then uploadError versionExists --allow trustees to do this?
else if packageExists state pkg && not (uid `Group.member` pkgGroup)
then uploadError (notMaintainer pkg)
else return Nothing
where
uploadError = return . Just . ErrorResponse 403 [] "Upload failed" . return . MText
versionExists = "This version of the package has already been uploaded.\n\nAs a matter of "
++ "policy we do not allow package tarballs to be changed after a release "
++ "(so we can guarantee stable md5sums etc). The usual recommendation is "
++ "to upload a new version, and if necessary blacklist the existing one. "
++ "In extraordinary circumstances, contact the administrators."
notMaintainer pkg = "You are not authorised to upload new versions of this package. The "
++ "package '" ++ display (packageName pkg) ++ "' exists already and you "
++ "are not a member of the maintainer group for this package.\n\n"
++ "If you believe you should be a member of the maintainer group for this "
++ "package, then ask an existing maintainer to add you to the group. If "
++ "this is a package name clash, please pick another name or talk to the "
++ "maintainers of the existing package."
-- This function generically extracts a package, useful for uploading, checking,
-- and anything else in the standard user-upload pipeline.
extractPackage :: (Users.UserId -> UploadResult -> IO (Maybe ErrorResponse))
-> ServerPartE (Users.UserId, UploadResult, PkgTarball)
extractPackage processFunc =
withDataFn (lookInput "package") $ \input ->
case inputValue input of -- HS6 this has been updated to use the new file upload support in HS6, but has not been tested at all
(Right _) -> errBadRequest "Upload failed" [MText "package field in form data is not a file."]
(Left file) ->
let fileName = (fromMaybe "noname" $ inputFilename input)
in upload fileName file
where
upload name file =
do -- initial check to ensure logged in.
--FIXME: this should have been covered earlier
uid <- guardAuthenticated
now <- liftIO getCurrentTime
let processPackage :: ByteString -> IO (Either ErrorResponse (UploadResult, BlobStorage.BlobId))
processPackage content' = do
-- as much as it would be nice to do requirePackageAuth in here,
-- processPackage is run in a handle bracket
case Upload.unpackPackage now name content' of
Left err -> return . Left $ ErrorResponse 400 [] "Invalid package" [MText err]
Right ((pkg, pkgStr), warnings) -> do
let uresult = UploadResult pkg pkgStr warnings
res <- processFunc uid uresult
case res of
Nothing ->
do let decompressedContent = GZip.decompressNamed file content'
blobIdDecompressed <- BlobStorage.add store decompressedContent
return . Right $ (uresult, blobIdDecompressed)
Just err -> return . Left $ err
mres <- liftIO $ BlobStorage.consumeFileWith store file processPackage
case mres of
Left err -> throwError err
Right ((res, blobIdDecompressed), blobId) -> do
infoGz <- liftIO $ blobInfoFromId store blobId
let tarball = PkgTarball {
pkgTarballGz = infoGz
, pkgTarballNoGz = blobIdDecompressed
}
return (uid, res, tarball)
| ocharles/hackage-server | Distribution/Server/Features/Upload.hs | bsd-3-clause | 19,842 | 0 | 30 | 5,264 | 3,101 | 1,697 | 1,404 | 282 | 8 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hi-IN">
<title>Passive Scan Rules - Beta | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/pscanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesBeta/resources/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 986 | 78 | 67 | 162 | 420 | 212 | 208 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP Project, Glasgow University, 1992-2000
Defines basic functions for printing error messages.
It's hard to put these functions anywhere else without causing
some unnecessary loops in the module dependency graph.
-}
{-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
module Panic (
GhcException(..), showGhcException,
throwGhcException, throwGhcExceptionIO,
handleGhcException,
progName,
pgmError,
panic, sorry, assertPanic, trace,
panicDoc, sorryDoc, pgmErrorDoc,
Exception.Exception(..), showException, safeShowException, try, tryMost, throwTo,
installSignalHandlers,
pushInterruptTargetThread, popInterruptTargetThread
) where
#include "HsVersions.h"
import {-# SOURCE #-} Outputable (SDoc)
import Config
import Exception
import Control.Concurrent
import Data.Dynamic
import Debug.Trace ( trace )
import System.IO.Unsafe
import System.Environment
#ifndef mingw32_HOST_OS
import System.Posix.Signals
#endif
#if defined(mingw32_HOST_OS)
import GHC.ConsoleHandler
#endif
import GHC.Stack
import System.Mem.Weak ( Weak, deRefWeak )
-- | GHC's own exception type
-- error messages all take the form:
--
-- @
-- <location>: <error>
-- @
--
-- If the location is on the command line, or in GHC itself, then
-- <location>="ghc". All of the error types below correspond to
-- a <location> of "ghc", except for ProgramError (where the string is
-- assumed to contain a location already, so we don't print one).
data GhcException
-- | Some other fatal signal (SIGHUP,SIGTERM)
= Signal Int
-- | Prints the short usage msg after the error
| UsageError String
-- | A problem with the command line arguments, but don't print usage.
| CmdLineError String
-- | The 'impossible' happened.
| Panic String
| PprPanic String SDoc
-- | The user tickled something that's known not to work yet,
-- but we're not counting it as a bug.
| Sorry String
| PprSorry String SDoc
-- | An installation problem.
| InstallationError String
-- | An error in the user's code, probably.
| ProgramError String
| PprProgramError String SDoc
deriving (Typeable)
instance Exception GhcException
instance Show GhcException where
showsPrec _ e@(ProgramError _) = showGhcException e
showsPrec _ e@(CmdLineError _) = showString "<command line>: " . showGhcException e
showsPrec _ e = showString progName . showString ": " . showGhcException e
-- | The name of this GHC.
progName :: String
progName = unsafePerformIO (getProgName)
{-# NOINLINE progName #-}
-- | Short usage information to display when we are given the wrong cmd line arguments.
short_usage :: String
short_usage = "Usage: For basic information, try the `--help' option."
-- | Show an exception as a string.
showException :: Exception e => e -> String
showException = show
-- | Show an exception which can possibly throw other exceptions.
-- Used when displaying exception thrown within TH code.
safeShowException :: Exception e => e -> IO String
safeShowException e = do
-- ensure the whole error message is evaluated inside try
r <- try (return $! forceList (showException e))
case r of
Right msg -> return msg
Left e' -> safeShowException (e' :: SomeException)
where
forceList [] = []
forceList xs@(x : xt) = x `seq` forceList xt `seq` xs
-- | Append a description of the given exception to this string.
showGhcException :: GhcException -> String -> String
showGhcException exception
= case exception of
UsageError str
-> showString str . showChar '\n' . showString short_usage
CmdLineError str -> showString str
PprProgramError str _ ->
showGhcException (ProgramError (str ++ "\n<<details unavailable>>"))
ProgramError str -> showString str
InstallationError str -> showString str
Signal n -> showString "signal: " . shows n
PprPanic s _ ->
showGhcException (Panic (s ++ "\n<<details unavailable>>"))
Panic s
-> showString $
"panic! (the 'impossible' happened)\n"
++ " (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t"
++ s ++ "\n\n"
++ "Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug\n"
PprSorry s _ ->
showGhcException (Sorry (s ++ "\n<<details unavailable>>"))
Sorry s
-> showString $
"sorry! (unimplemented feature or known bug)\n"
++ " (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t"
++ s ++ "\n"
throwGhcException :: GhcException -> a
throwGhcException = Exception.throw
throwGhcExceptionIO :: GhcException -> IO a
throwGhcExceptionIO = Exception.throwIO
handleGhcException :: ExceptionMonad m => (GhcException -> m a) -> m a -> m a
handleGhcException = ghandle
-- | Panics and asserts.
panic, sorry, pgmError :: String -> a
panic x = unsafeDupablePerformIO $ do
stack <- ccsToStrings =<< getCurrentCCS x
if null stack
then throwGhcException (Panic x)
else throwGhcException (Panic (x ++ '\n' : renderStack stack))
sorry x = throwGhcException (Sorry x)
pgmError x = throwGhcException (ProgramError x)
panicDoc, sorryDoc, pgmErrorDoc :: String -> SDoc -> a
panicDoc x doc = throwGhcException (PprPanic x doc)
sorryDoc x doc = throwGhcException (PprSorry x doc)
pgmErrorDoc x doc = throwGhcException (PprProgramError x doc)
-- | Throw an failed assertion exception for a given filename and line number.
assertPanic :: String -> Int -> a
assertPanic file line =
Exception.throw (Exception.AssertionFailed
("ASSERT failed! file " ++ file ++ ", line " ++ show line))
-- | Like try, but pass through UserInterrupt and Panic exceptions.
-- Used when we want soft failures when reading interface files, for example.
-- TODO: I'm not entirely sure if this is catching what we really want to catch
tryMost :: IO a -> IO (Either SomeException a)
tryMost action = do r <- try action
case r of
Left se ->
case fromException se of
-- Some GhcException's we rethrow,
Just (Signal _) -> throwIO se
Just (Panic _) -> throwIO se
-- others we return
Just _ -> return (Left se)
Nothing ->
case fromException se of
-- All IOExceptions are returned
Just (_ :: IOException) ->
return (Left se)
-- Anything else is rethrown
Nothing -> throwIO se
Right v -> return (Right v)
-- | Install standard signal handlers for catching ^C, which just throw an
-- exception in the target thread. The current target thread is the
-- thread at the head of the list in the MVar passed to
-- installSignalHandlers.
installSignalHandlers :: IO ()
installSignalHandlers = do
main_thread <- myThreadId
pushInterruptTargetThread main_thread
let
interrupt_exn = (toException UserInterrupt)
interrupt = do
mt <- peekInterruptTargetThread
case mt of
Nothing -> return ()
Just t -> throwTo t interrupt_exn
--
#if !defined(mingw32_HOST_OS)
_ <- installHandler sigQUIT (Catch interrupt) Nothing
_ <- installHandler sigINT (Catch interrupt) Nothing
-- see #3656; in the future we should install these automatically for
-- all Haskell programs in the same way that we install a ^C handler.
let fatal_signal n = throwTo main_thread (Signal (fromIntegral n))
_ <- installHandler sigHUP (Catch (fatal_signal sigHUP)) Nothing
_ <- installHandler sigTERM (Catch (fatal_signal sigTERM)) Nothing
return ()
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
_ <- installHandler (Catch sig_handler)
return ()
#endif
{-# NOINLINE interruptTargetThread #-}
interruptTargetThread :: MVar [Weak ThreadId]
interruptTargetThread = unsafePerformIO (newMVar [])
pushInterruptTargetThread :: ThreadId -> IO ()
pushInterruptTargetThread tid = do
wtid <- mkWeakThreadId tid
modifyMVar_ interruptTargetThread $ return . (wtid :)
peekInterruptTargetThread :: IO (Maybe ThreadId)
peekInterruptTargetThread =
withMVar interruptTargetThread $ loop
where
loop [] = return Nothing
loop (t:ts) = do
r <- deRefWeak t
case r of
Nothing -> loop ts
Just t -> return (Just t)
popInterruptTargetThread :: IO ()
popInterruptTargetThread =
modifyMVar_ interruptTargetThread $
\tids -> return $! case tids of [] -> []
(_:ts) -> ts
| ml9951/ghc | compiler/utils/Panic.hs | bsd-3-clause | 9,492 | 0 | 18 | 2,593 | 1,798 | 927 | 871 | 155 | 10 |
{-# OPTIONS -fglasgow-exts #-}
-- Tests the "stupid theta" in pattern-matching
-- when there's an existential as well
module ShouldCompile where
data (Show a) => Obs a = forall b. LiftObs a b
f :: Show a => Obs a -> String
f (LiftObs _ _) = "yes"
| hvr/jhc | regress/tests/1_typecheck/2_pass/ghc/tc182.hs | mit | 271 | 0 | 7 | 72 | 68 | 38 | 30 | -1 | -1 |
module LayoutLet2 where
-- Simple let expression, rename xxx to something longer or shorter
-- and the let/in layout should adjust accordingly
-- In this case the tokens for xxx + a + b should also shift out
foo xxx = let a = 1
b = 2 in xxx + a + b
| mpickering/ghc-exactprint | tests/examples/transform/LayoutLet2.hs | bsd-3-clause | 266 | 0 | 8 | 71 | 39 | 22 | 17 | 3 | 1 |
-- In this example, adding 'main' to the export will fail as it is already exported.
module A1 where
import D1
import C1
import B1
main :: Tree Int ->Bool
main t = isSame (sumSquares (fringe t))
(sumSquares (B1.myFringe t)+sumSquares (C1.myFringe t))
| SAdams601/HaRe | old/testing/fromConcreteToAbstract/A1_TokOut.hs | bsd-3-clause | 285 | 0 | 11 | 74 | 80 | 42 | 38 | 7 | 1 |
{-# LANGUAGE MagicHash #-}
module Foo where
foo# = 'a'
| urbanslug/ghc | testsuite/tests/parser/should_compile/read047.hs | bsd-3-clause | 59 | 0 | 4 | 14 | 10 | 7 | 3 | 3 | 1 |
module Annfail01 where
-- Testing annotating things that don't exist
{-# ANN type Foo (1 :: Int) #-}
{-# ANN f (1 :: Int) #-} | urbanslug/ghc | testsuite/tests/annotations/should_fail/annfail01.hs | bsd-3-clause | 126 | 0 | 2 | 25 | 7 | 6 | 1 | 3 | 0 |
module Chapter8.Syntax.Number where
import Data.Monoid
import Data.Display
import Chapter8.Syntax.Type
data NumVal
= NumZero
| NumSucc NumVal
deriving (Eq, Show)
toRealNum :: NumVal -> Integer
toRealNum = walk 0
where
walk c nv = case nv of
NumZero -> c
NumSucc v -> walk (c + 1) v
instance Ord NumVal where
compare n1 n2 = toRealNum n1 `compare` toRealNum n2
instance Enum NumVal where
fromEnum = fromInteger . toRealNum
toEnum = walk NumZero
where
walk nv n
| n > 0 = walk (NumSucc nv) $ n - 1
| otherwise = nv
pred nv = case nv of
NumZero -> NumZero
NumSucc v -> v
instance Monoid NumVal where
mempty = NumZero
mappend nv1 nv2 = case (nv1, nv2) of
(NumZero, NumZero) -> NumZero
(NumZero, _) -> nv2
(_, NumZero) -> nv1
(NumSucc v, NumSucc w) -> NumSucc $ NumSucc $ mappend v w
instance Display NumVal where
toDisplay = toDisplay . fromEnum
instance HasType NumVal where
typeof _ = Right TyNat
| VoQn/tapl-hs | src/Chapter8/Syntax/Number.hs | mit | 1,016 | 0 | 13 | 284 | 372 | 193 | 179 | 35 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module CodeAdapter where
import Control.Monad.IfElse
import SoOSiM
import Code
import Node
data TransfomerState = TransfomerState
data CodeAdapterMsg = Compile BlockCode Architecture
deriving (Typeable)
instance ComponentIface TransfomerState where
initState = TransfomerState
componentName _ = "CodeAdapter"
componentBehaviour state (ComponentMsg caller contents)
| Just (Compile code node) <- adapterAction
-- To be completed
= return state
where adapterAction = fromDynamic contents
componentBehaviour state _ = return state
| christiaanb/SoOSiM | examples/Twente/CodeAdapter.hs | mit | 597 | 0 | 12 | 101 | 132 | 70 | 62 | 17 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : DataAssociation.Explore.UI.Web.Server
-- Copyright :
-- License : MIT
--
-- Maintainer : -
-- Stability :
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module DataAssociation.Explore.UI.Web.Server (
server
) where
import DataAssociation.Explore.UI.Web.Application
import DataAssociation.Explore.UI.State
import DataAssociation.Explore.UI.Web.Render
import Web.Spock
import Text.Blaze.Html.Renderer.Text
import Data.List (intercalate)
import qualified Data.Text as T
import qualified Data.Text.Lazy as ST
import Control.Monad.IO.Class
import System.FilePath
listenToReactiveElems :: (MonadIO m) => [SomeRenderableWebPage] -> SpockT m ()
listenToReactiveElems elems = sequence_ handlers
where handlers = do SomeRenderableWebPage e <- elems
return $ get (static . intercalate "/" $ reqPath e)
(html . ST.toStrict . renderHtml $ renderWebPage e)
server :: Int -> [SomeRenderableWebPage] -> [FilePath] -> IO ()
server port pages staticRoot = runSpock port . spockT id $ do
listenToReactiveElems pages
let getResource path name = get path $ file name $ joinPath (staticRoot ++ [T.unpack name])
getResource "static/apriori.css" "apriori.css"
getResource "static/apriori.js" "apriori.js"
| fehu/min-dat--a-priori | explore-web-backend/src/DataAssociation/Explore/UI/Web/Server.hs | mit | 1,484 | 0 | 17 | 268 | 330 | 184 | 146 | 24 | 1 |
{-# LANGUAGE TypeOperators, OverloadedStrings #-}
module Cypher.Actions where
import Cypher.Types
import Cypher.Utils
import Data.Monoid
import Control.Monad.Free
import Data.Text as T
commitTransaction :: Neo4jRequest ~> TransactionResponse
commitTransaction req = liftFn (CommitTransaction req)
root :: Neo4jAction RootResponse
root = liftF $ GetRoot id
authenticate :: T.Text -> T.Text ~> AuthResponse
authenticate user pass = liftFn (Authenticate user pass)
getNode :: Int ~> NodeResponse
getNode nodeId = liftFn (GetNode nodeId)
createNode :: Maybe Props ~> NodeResponse
createNode props = liftFn (CreateNode props)
-- NOTE: Nodes with relationships cannot be deleted.
deleteNode :: Int ~> ()
deleteNode nodeId = liftF (DeleteNode nodeId ())
listPropertyKeys :: Neo4jAction [T.Text]
listPropertyKeys = liftFn ListPropertyKeys
getRelationship :: Int ~> RelationshipResponse
getRelationship relId = liftFn (GetRelationship relId)
-- NOTE: This is a little weird, since the start node is encoded in the relationship itself.
createRelationship :: Int -> Relationship ~> RelationshipResponse
createRelationship nodeId rel = liftFn (CreateRelationship nodeId rel)
deleteRelationship :: Int ~> ()
deleteRelationship relId = liftF (DeleteRelationship relId ())
getRelationshipProperties :: Int ~> Props
getRelationshipProperties relId = liftFn (GetRelationshipProperties relId)
getRelationshipProperty :: Int -> Prop ~> Props
getRelationshipProperty relId prop = liftFn (GetRelationshipProperty relId prop)
setRelationshipProperties :: Int -> Props ~> ()
setRelationshipProperties relId props = liftF (SetRelationshipProperties relId props ())
setRelationshipProperty :: Int -> Prop -> Prop ~> ()
setRelationshipProperty relId propKey propVal = liftF (SetRelationshipProperty relId propKey propVal ())
getNodeRelationships :: Int -> RelType -> [T.Text] ~> [RelationshipResponse]
getNodeRelationships nodeId relType types = liftFn (GetNodeRelationships nodeId relType types)
getRelationshipTypes :: Neo4jAction [T.Text]
getRelationshipTypes = liftFn GetRelationshipTypes
setNodeProperty :: Id -> Prop -> Props ~> ()
setNodeProperty nodeId prop props = liftF (SetNodeProperty nodeId prop props ())
setNodeProperties :: Id -> Props ~> Props
setNodeProperties nodeId prop = liftFn (SetNodeProperties nodeId prop)
getNodeProperty :: Id -> Prop ~> Props
getNodeProperty nodeId prop = liftFn (GetNodeProperty nodeId prop)
deleteNodeProperty :: Id -> Prop ~> ()
deleteNodeProperty nodeId prop = liftF (DeleteNodeProperty nodeId prop ())
deleteNodeProperties :: Id ~> ()
deleteNodeProperties nodeId = liftF (DeleteNodeProperties nodeId ())
findNodesByProp :: T.Text -> T.Text -> Neo4jAction TransactionResponse
findNodesByProp key val = do
let stmt = "MATCH (n{ " <> key <> ":\"" <> val <> "\"}) RETURN n"
commitTransaction (Neo4jRequest [Statement stmt] Nothing)
| 5outh/cypher | src/Cypher/Actions.hs | mit | 2,943 | 0 | 13 | 454 | 803 | 408 | 395 | 53 | 1 |
import Utils
import qualified Data.Set as S
import Control.Monad.State
import Debug.Trace
import Data.List (foldl')
nmax = 1000000
sumSquareDigit :: Int -> Int
--sumSquareDigit n = sum $ map (^2) $ numberToDigitsBackwards n
sumSquareDigit n | n<10 = n^2
| otherwise = (n `mod` 10)^2 + sumSquareDigit (n `div` 10)
type SolutionSet1 = S.Set Int
type SolutionSet89 = S.Set Int
emptyState = (S.singleton 1, S.singleton 89)
--solveUpTo :: Int -> State (SolutionSet1, SolutionSet89) Int
--solveUpTo n = do
-- forM_ [1..n] $ \k -> do
-- (sol1, sol89) <- get
-- put $ update (sol1, sol89) k
-- (sol1'', sol89'') <- get
-- return $ length sol89''
solveUpTo :: Int -> (SolutionSet1, SolutionSet89)
solveUpTo n = foldl' update emptyState [2..n]
update :: (SolutionSet1, SolutionSet89) -> Int -> (SolutionSet1, SolutionSet89)
update (s1, s89) n = let pred k = k `S.member` s89 || k `S.member` s1
(ks, rest) = break pred $ iterate sumSquareDigit n
s = head rest
ins1 = s `S.member` s1
s1' = if ins1 then foldl' (flip S.insert) s1 ks else s1
s89' = if (not ins1) then foldl' (flip S.insert) s89 ks else s89
in (s1', s89')
target n = head $ dropWhile (\k -> k /= 1 && k /= 89) $ iterate sumSquareDigit n
solve n = length $ fst $ solveUpTo n
--solve n = runState (solveUpTo n) emptyState
--correct n = monadic == fp
-- where monadic = filter (<=n) $ S.toList $ snd $ snd $ solve n
-- fp = filter (\k -> k <= n && target k == 89) [1..n]
--
--answer n = fst $ solve n
answer = solve
main = print $ answer 1000000
| arekfu/project_euler | p0092/p0092.hs | mit | 1,704 | 0 | 13 | 487 | 467 | 259 | 208 | 26 | 3 |
module Import
( module Import
) where
import Prelude as Import hiding (head, init, last,
readFile, tail, writeFile)
import Yesod as Import hiding (Route (..))
import Yesod.Static as Import
import Yesod.Form.Bootstrap3 as Import
import Data.Text as Import (Text)
import Foundation as Import
import Model as Import
import Settings as Import
-- import Settings.Development as Import
import Settings.StaticFiles as Import
#if __GLASGOW_HASKELL__ >= 704
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat),
(<>))
#else
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat))
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
#endif
| collaborare/antikythera | src/Import.hs | mit | 1,088 | 0 | 6 | 529 | 129 | 95 | 34 | 17 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGAnimatedEnumeration
(js_setBaseVal, setBaseVal, js_getBaseVal, getBaseVal,
js_getAnimVal, getAnimVal, SVGAnimatedEnumeration,
castToSVGAnimatedEnumeration, gTypeSVGAnimatedEnumeration)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"baseVal\"] = $2;"
js_setBaseVal :: SVGAnimatedEnumeration -> Word -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedEnumeration.baseVal Mozilla SVGAnimatedEnumeration.baseVal documentation>
setBaseVal :: (MonadIO m) => SVGAnimatedEnumeration -> Word -> m ()
setBaseVal self val = liftIO (js_setBaseVal (self) val)
foreign import javascript unsafe "$1[\"baseVal\"]" js_getBaseVal ::
SVGAnimatedEnumeration -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedEnumeration.baseVal Mozilla SVGAnimatedEnumeration.baseVal documentation>
getBaseVal :: (MonadIO m) => SVGAnimatedEnumeration -> m Word
getBaseVal self = liftIO (js_getBaseVal (self))
foreign import javascript unsafe "$1[\"animVal\"]" js_getAnimVal ::
SVGAnimatedEnumeration -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedEnumeration.animVal Mozilla SVGAnimatedEnumeration.animVal documentation>
getAnimVal :: (MonadIO m) => SVGAnimatedEnumeration -> m Word
getAnimVal self = liftIO (js_getAnimVal (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGAnimatedEnumeration.hs | mit | 2,196 | 20 | 8 | 255 | 508 | 308 | 200 | 31 | 1 |
module Clavier.SortingAlgorithms (selection_sort, insertion_sort, merge_sort, quick_sort) where
import Data.List
selection_sort :: (Ord a) => [a] -> [a]
selection_sort (x : [])
= [x]
selection_sort []
= []
selection_sort li
= let
select_min min [] prev = (min, prev)
select_min min (x:xs) prev
| x < min = select_min x xs (min:prev)
| otherwise = select_min min xs (x:prev)
repeat_select [] = []
repeat_select (x:xs)
= let
(min, rest) = select_min x xs []
in min : repeat_select rest
in repeat_select li
insertion_sort :: (Ord a) => [a] -> [a]
insertion_sort (x : [])
= [x]
insertion_sort []
= []
insertion_sort li
= let
insert_into x []
= [x]
insert_into x li@(car:cdr)
| x >= car = car : (insert_into x cdr)
| otherwise = x : li
in foldl' (\ accum x -> insert_into x accum) [] li
merge_sort :: (Ord a) => [a] -> [a]
merge_sort (x : [])
= [x]
merge_sort []
= []
merge_sort li
= let
(left, right) = merge_sort_partition li [] [] 0
in merge_sort_merge (merge_sort left) (merge_sort right)
merge_sort_partition :: [a] -> [a] -> [a] -> Int -> ([a], [a])
merge_sort_partition [] left right _ = ((reverse left), (reverse right))
merge_sort_partition (x:xs) left right i
| (mod i 2) == 0 = merge_sort_partition xs (x:left) right (i + 1)
| otherwise = merge_sort_partition xs left (x:right) (i + 1)
merge_sort_merge :: (Ord a) => [a] -> [a] -> [a]
merge_sort_merge [] right = right
merge_sort_merge left [] = left
merge_sort_merge (l:ls) (r:rs)
| l <= r = l : (merge_sort_merge ls (r:rs))
| otherwise = r : (merge_sort_merge (l:ls) rs)
quick_sort :: (Ord a) => [a] -> [a]
quick_sort (x : [])
= [x]
quick_sort []
= []
quick_sort (pivot : xs)
= let
(left, right) = foldl' (\ (left, right) x -> if x <= pivot then ((x:left), right) else (left, (x:right))) ([], []) xs
in (quick_sort left) ++ (pivot : (quick_sort right)) | Raekye/The-Modern-Clavier | haskell/src/Clavier/SortingAlgorithms.hs | mit | 1,877 | 28 | 15 | 386 | 1,039 | 546 | 493 | 61 | 3 |
module HaskellRead where
import File
import System.FilePath.Posix (takeExtension)
import Text.Regex.Posix
import Util
isSupportedFilePath :: FilePath -> Bool
isSupportedFilePath = (==) ".hs" . takeExtension
isSupportedFile :: File -> Bool
isSupportedFile file =
(extension file) == ".hs"
extractDependencies :: File -> [String]
extractDependencies file =
Prelude.map (moduleToFilePath . captureModule) imports
where
imports = extractImportExpressions file
moduleToFilePath :: String -> FilePath
moduleToFilePath mod =
replaceSafe "." "/" mod ++ ".hs"
extractImportExpressions :: File -> [String]
extractImportExpressions file =
getAllTextMatches $ (contents file) =~ importRegex
importRegex :: String
importRegex = "import([\r\n\t\f\v ]+qualified)?[\r\n\t\f\v ]+([^\r\n\t\f\v ]+)"
captureModule :: String -> String
captureModule importLine = mod
where
match = importLine =~ importRegex :: (String, String, String, [String])
(_, _, _, captures) = match
mod = captures !! 1
| larioj/nemo | src/HaskellRead.hs | mit | 1,076 | 0 | 8 | 225 | 266 | 149 | 117 | 27 | 1 |
-- | Exercises for Chapter 6.
--
-- Implement the functions in this module using recursion.
module Chapter06 (and, concat, replicate, elem, (!!), merge, msort) where
import Prelude hiding (and, concat, elem, replicate, (!!))
-- * Exercise 1
-- | Decide if all logical values in a list are true.
and :: [Bool] -> Bool
and = undefined
-- | Concatenate a list of lists.
concat :: [[a]] -> [a]
concat = undefined
-- | Produce a list with identical @n@ elements.
replicate :: Int -> a -> [a]
replicate = undefined
-- | Select the nth element of a list.
(!!) :: [a] -> Int -> a
xs !! n = undefined
-- Note that you can also define @!!@ using prefix notation:
--
-- > (!!) xs n = ...
-- | Decide if a value is an element of a list.
elem :: Eq a => a -> [a] -> Bool
elem = undefined
-- * Exercise 2
-- | Merges two sorted lists of values to give a single sorted list. If any of
-- the two given lists are not sorted then the behavior is undefined.
merge :: Ord a => [a] -> [a] -> [a]
-- Remember to define @merge@ using recursion.
merge = undefined
-- * Exercise 3
msort :: Ord a => [a] -> [a]
msort = undefined
| EindhovenHaskellMeetup/meetup | courses/programming-in-haskell/pih-exercises/src/Chapter06.hs | mit | 1,126 | 0 | 8 | 248 | 248 | 154 | 94 | 16 | 1 |
module DecryptEnvironment () where
import Text.Read(readMaybe)
import Global(Error, Arg, Rounds, KeyFilename)
type DecryptEnv = () -- TODO
| tombusby/haskell-des | round/DecryptEnvironment.hs | mit | 142 | 0 | 5 | 20 | 43 | 28 | 15 | 4 | 0 |
-- There might be a clever way to work out the digits on paper
-- by counting the number sizes, but this is faster.
import Data.Char (ord)
digitToInt d = (ord d) - (ord '0')
frac = concat $ map show [0..]
digits = map (\i -> digitToInt $ frac !! (10^i)) [0..6]
answer = product digits
main = print answer | gumgl/project-euler | 40/40.hs | mit | 310 | 0 | 10 | 66 | 108 | 58 | 50 | 6 | 1 |
module Data.Set.Data where
import qualified Data.Set as Set
setTo :: Int -> Set.Set Int
setTo n = Set.fromList [1..n]
set1 :: Set.Set Int
set1 = setTo 10
set2 :: Set.Set Int
set2 = setTo 20
set3 :: Set.Set Int
set3 = setTo 30
set4 :: Set.Set Int
set4 = setTo 40
set5 :: Set.Set Int
set5 = setTo 50
| athanclark/sets | bench/Data/Set/Data.hs | mit | 307 | 0 | 7 | 68 | 137 | 72 | 65 | 14 | 1 |
{-# LANGUAGE BangPatterns #-}
module Main where
import System.Random (randomRIO)
import Control.Monad (replicateM)
import Debug.Trace
-- | Perceptron implementation in Haskell (dirty)
--
type Input = [Double]
type Data = [(Input, Double)]
type Weights = [Double]
type Rate = Double -- [0,1]
round' :: Int -> Double -> Double
round' n = (/10^n). fromInteger . round . (* 10^n)
f :: (Num a, Ord a) => a -> Double
f x
| x < 0 = 0
| otherwise = 1.0
runInput :: [Double] -> [Double] -> Double
runInput inputs ws = f $ sum $ zipWith (*) inputs ws
learn :: Rate -> Data -> Weights -> Weights
learn rate [] ws = ws
learn rate ((xs,y):ds) ws
| y == y_hat = learn rate ds ws
| otherwise = learn rate ds (update xs ws)
where
y_hat = runInput xs ws
update :: [Double] -> [Double] -> [Double]
update xs = map (\(x,w) -> round' 3 (w + rate * (y - y_hat) * x)) . zip xs
run :: Rate -> Data -> Weights -> Weights
run rate = go 0
where go :: Int -> Data -> Weights -> Weights
go n d w = let w' = learn rate d w
in case w == w' of
True -> trace ("Steps: " ++ show n) w
False -> trace (show w) $ go (n+1) d w'
test :: Weights -> Data -> IO ()
test weights dt = do
let f x
| runInput x weights == 1 = "True"
| otherwise = "False"
pretty (x,i) = putStrLn $ show i ++ " - " ++ f x
mapM_ pretty (zip (map fst dt) [0..])
-- | Data
--
odds :: Data
odds = [ (x0, 0) -- 0
, (x1, 1) -- 1
, (x2, 0) -- 2
, (x3, 1) -- 3
, (x4, 0) -- 4
, (x5, 1) -- 5
, (x6, 0) -- 6
, (x7, 1) -- 7
, (x8, 0) -- 8
, (x9, 1) -- 9
]
-- > run 0.1 odds weights
-- > rweights >>= return . run 0.1 odds
-- > test it odds
mul3 :: Data
mul3 = [ (x0, 0) -- 0
, (x1, 0) -- 1
, (x2, 0) -- 2
, (x3, 1) -- 3
, (x4, 0) -- 4
, (x5, 0) -- 5
, (x6, 1) -- 6
, (x7, 0) -- 7
, (x8, 0) -- 8
, (x9, 1) -- 9
]
-- > run 0.1 mul3 weights
-- > rweights >>= return . run 0.1 mul3
-- > test it mul3
ors :: Data
ors = [ ([1,0,0], 0)
, ([1,0,1], 1)
, ([1,1,0], 1)
, ([1,1,1], 1)
]
-- > run 0.1 ors (weightsc 3)
-- > test it ors
custom :: Data
custom = [ ([1, 2, 4 ], 1)
, ([1, 0.5, 1.5], 1)
, ([1, 1, 0.5], 0)
, ([1, 0, 0.5], 0)
]
-- > run 0.1 custom (weightsc 3)
-- > test it custom
weightsc :: Int -> [Double]
weightsc n = replicate n 0.0
weights :: [Double]
weights = replicate (length (xs !! 0)) 0.0
rweights :: IO [Double]
rweights = replicateM (length (xs !! 0)) $ randomRIO (-1.0,1.0)
xs :: [Input]
xs = [x0, x1, x2, x3, x4, x5, x6, x7, x8, x9]
x0 = [1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1] :: [Double] -- 0
x1 = [0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0] :: [Double] -- 1
x2 = [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1] :: [Double] -- 2
x3 = [1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1] :: [Double] -- 3
x4 = [1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1] :: [Double] -- 4
x5 = [1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1] :: [Double] -- 5
x6 = [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1] :: [Double] -- 6
x7 = [1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1] :: [Double] -- 7
x8 = [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1] :: [Double] -- 8
x9 = [1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1] :: [Double] -- 9 | cirquit/Personal-Repository | Haskell/machine-learning/perceptron/perceptron.hs | mit | 3,511 | 0 | 16 | 1,224 | 1,782 | 1,084 | 698 | 89 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Parse
import System.Environment
main = do
f <- readFile "prog.txt"
args <- getArgs
let command = if length args > 0 then prog else finish prog
case runParser command f of
xs -> do
mapM_ print $ take 5 xs
print $ length xs
| kovach/cards | src/Main.hs | mit | 310 | 0 | 13 | 80 | 105 | 50 | 55 | 12 | 2 |
{-# Language TemplateHaskell #-}
module Main where
-- base
import Data.Monoid
import Control.Applicative
-- linear
import Linear
-- lens
import Control.Lens
-- gloss
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
-- colour
import Data.Colour (Colour)
import Data.Colour.RGBSpace
import Data.Colour.RGBSpace.HSV
-- falling
import Falling
-- | The interface can be in two states: one, where everything
-- is just running by itself, and another, where we're adding
-- and changing things about one particular particle.
data Interface n
= Running
{ _particles :: [Particle n]
}
| Adding
{ _adding :: Particle n
, _particles :: [Particle n]
}
deriving
( Eq
, Ord
, Show
)
makeLenses ''Interface
makePrisms ''Interface
-- | Do something with input.
withInput :: Event -> Interface Float -> Interface Float
-- If we get a mouseclick down in 'Running', add a particle at the
-- place of the click and switch to 'Adding'; we'll be editing
-- it until the corresponding mouseclick up.
withInput (EventKey (MouseButton LeftButton) Down _ (x', y'))
(Running ps) = Adding (particle $ V3 x' y' 0) ps
-- If we get a mouse movement while in 'Adding', change the
-- velocity of the new particle to the new place of the mouse;
-- keep in mind the offset of particle.
withInput (EventKey (MouseButton LeftButton) _ _ _)
(Adding p ps) = Running (p : ps)
-- If we get a mouseclick up while in 'Adding', push the particle
-- into the list of particles and switch to 'Running'.
withInput (EventMotion (x', y')) (Adding p ps) = Adding
(velocity .~ view place p - V3 x' y' 0 $ p) ps
-- Otherwise just ignore the input.
withInput _ i = i
-- Draw an interface.
redraw :: Interface Float -> Picture
redraw i = foldMapOf (particles . traverse) single i
<> case i of
Running _ -> mempty
-- If we're in an 'Adding', draw the new particle
-- and a line indicating its velocity.
Adding p _ -> let
-- The vector being drawn from the particle.
d :: V3 Float
d = p ^. place - p ^. velocity
-- The color to draw the vector in.
c :: Color
c = uncurryRGB makeColor
(hsv (angle (d ^. _x) (d ^. _y)) 0.5 0.5) 1 in
-- Draw the particle we're adding and a line from it
-- to the mouse, representing the inverse of its
-- velocity.
single p <> Color c (Line
[ (p ^. place . _x, p ^. place . _y)
, (d ^. _x, d ^. _y)
])
where
-- Radians to degrees.
degrees :: Floating t => t -> t
degrees = (*) (180 / pi)
-- Angle of a vector, in degrees.
angle :: Floating t => t -> t -> t
angle x y = degrees . atan $ y / x
-- Draw a single particle as a white circle.
single :: Particle Float -> Picture
single = Translate <$> (^. place . _x)
<*> (^. place . _y)
?? Color white (circleSolid 2.0)
-- A massive particle at the origin.
sun :: Particle Float
sun = Particle 0 0 200
-- Iterate the world.
iteration :: Float -> Interface Float -> Interface Float
iteration t i = if has _Adding i then i
else particles %~ update . map (move t) $ i
main :: IO ()
main = play (InWindow "falling!" (300, 300) (100, 100))
black 40 (Running [sun]) redraw withInput iteration
| startling/falling | main.hs | mit | 3,241 | 0 | 19 | 791 | 848 | 460 | 388 | -1 | -1 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.List
type Coord = (Int, Int) -- (Row, Col), top left is (0, 0)
type Triangle = (Coord, Coord, Coord) -- (top, bot-left, bot-right)
numRows :: Int
numRows = 32
numCols :: Int
numCols = 63
lineToChars :: [Int] -> String
lineToChars os = map (\n -> if n`elem` os then '1' else '_') $ [1..numCols]
genIteration0 :: ([String], [Triangle])
genIteration0 =
let ss = take numRows . map lineToChars . ([[numRows]] ++ ) $ unfoldr (\rs -> let nrs = ((head rs - 1) : rs) ++ [last rs + 1] in Just (nrs, nrs)) [numRows]
ts = [((0, numRows-1), (numRows-1, 0), (numRows-1, numCols-1))]
in (ss, ts)
-- takes a triangle to further fractalize, and returns
-- (triangle-to-be-nullified, [new-triangles-in-fractal])
createNewTriangles :: Triangle -> (Triangle, [Triangle])
createNewTriangles ts@(top, botl, botr) =
let szc = ((snd botl + snd botr) `div` 2) + ((snd botl + snd botr) `mod` 2)
szcby14 = ((snd botl + szc - 1) `div` 2) + ((snd botl + szc - 1) `mod` 2)
szcby34 = ((snd botr + szc + 1) `div` 2) + ((snd botr + szc + 1) `mod` 2)
szr = ((fst top + fst botl) `div` 2) -- + ((fst top + fst botl) `mod` 2)
midbot = ((fst botl), szc)
midbotm1 = ((fst botl), (szc - 1))
midbotp1 = ((fst botl), (szc + 1))
midl = (szr+1, szcby14)
midlp1 = (szr+1, szcby14 + 1)
midlup = (szr, szcby14 + 1)
midr = (szr+1, szcby34)
midrm1 = (szr+1, szcby34 - 1)
midrup = (szr, szcby34 - 1)
in ((midlp1, midrm1, midbot), [(top, midlup, midrup), (midl, botl, midbotm1), (midr, midbotp1, botr)])
nullifyRow :: [String] -> (Coord, Coord) -> [String]
nullifyRow ss (left@(lr, lc), right@(rr, rc)) = priorRows ++ [thisRow] ++ restRows
where
priorRows = take (lr) ss
restRows = drop (lr+1) ss
myRow = last . take (lr+1) $ ss
thisRow = ((take (lc) myRow) ++ (take (rc - lc + 1) (repeat '_')) ++ (drop (rc+1) myRow) )
-- sets all the locations within this triangle to '_'
nullifyTriangle :: Triangle -> [String] -> [String]
nullifyTriangle tri@(tl, tr, bot) ss = foldl' (nullifyRow) ss $ rowCoords
where
rowCoords = take (fst bot - fst tl + 1) $ ((tl, tr) : (unfoldr (\ (l@(lr, lc), r@(rr, rc)) -> let nc = ((lr+1, lc+1), (rr+1, rc-1)) in Just (nc, nc)) $ (tl, tr)))
-- runs one more iteration of fractalization
iterateTri :: ([String], [Triangle]) -> ([String], [Triangle])
iterateTri (ss, ts) = foldl' (\acc@(ass, ats) t ->
let (nt, newts) = createNewTriangles t
newss = nullifyTriangle nt ass
in (newss, ats ++ newts)
)
(ss, []) $ ts
fractalize :: Int -> Int -> ([String], [Triangle]) -> ([String], [Triangle])
fractalize 0 times _ =
let initseq = genIteration0
in if times == 1 then initseq else fractalize 1 times initseq
fractalize inum times (ss, ts) =
let newseq = iterateTri (ss, ts)
in if inum == times - 1 then newseq else fractalize (inum+1) times newseq
main :: IO ()
main = do
nstr <- getLine
let css = fst $ fractalize 0 (1 + read nstr) ([], [])
putStrLn $ unlines css
| cbrghostrider/Hacking | HackerRank/FunctionalProgramming/Recursion/sierpinskiTriangleFractals.hs | mit | 3,648 | 3 | 22 | 968 | 1,495 | 849 | 646 | 57 | 3 |
module TestInternal
( runTests
, leftistHeapProperty
) where
import Data.Char
import HeapInternal as Heap
import qualified Data.List as List
import TestHeapCommon
import TestQuickCheck
runTests :: IO ()
runTests = do
qc "Eq" (eqProperty :: HeapT Int Char -> HeapT Int Char -> HeapT Int Char -> Bool)
qc "Ord" (ordProperty :: HeapT Int Char -> HeapT Int Char -> HeapT Int Char -> Bool)
qc "leftist heap" (leftistHeapProperty :: HeapT Int Char -> Bool)
qc "read/show" (readShowProperty :: [HeapT Int Char] -> Bool)
qc "Monoid" (monoidProperty :: HeapT Int Char -> HeapT Int Char -> HeapT Int Char -> Bool)
qc "union" (unionProperty :: HeapT Int Char -> HeapT Int Char -> Bool)
qc "Functor" (functorProperty (subtract 1000) (*42) :: HeapT Char Int -> Bool)
qc "fmap" (fmapProperty (subtract 1000) :: HeapT Char Int -> Bool)
qc "Foldable" (foldableProperty :: HeapT Char Int -> Bool)
qc "size" sizeProperty
qc "view" viewProperty
qc "singleton" (singletonProperty :: Char -> Int -> Bool)
qc "partition" (partitionProperty testProp :: HeapT Char Int -> Bool)
qc "splitAt" splitAtProperty
qc "span" spanProperty
qc "fromList/toList" (listProperty :: [Char] -> Bool)
qc "fromDescList/toAscList" (sortedListProperty :: [Char] -> Bool)
where
testProp :: Char -> Int -> Bool
testProp c i = even i && isLetter c
instance (Arbitrary prio, Arbitrary val, Ord prio) => Arbitrary (HeapT prio val) where
arbitrary = fmap (fromList . take 100) arbitrary
shrink = fmap fromList . shrink . toList
leftistHeapProperty :: (Ord prio) => HeapT prio val -> Bool
leftistHeapProperty Empty = True
leftistHeapProperty heap =
(maybe True (\(p, _, _) -> p >= _priority heap) (view (_left heap)))
&& (maybe True (\(p, _, _) -> p >= _priority heap) (view (_right heap)))
&& _rank heap == 1 + rank (_right heap) -- rank == length of right spine
&& rank (_left heap) >= rank (_right heap) -- leftist property
&& _size heap == 1 + size (_left heap) + size (_right heap)
&& leftistHeapProperty (_left heap)
&& leftistHeapProperty (_right heap)
unionProperty :: (Ord prio, Ord val) => HeapT prio val -> HeapT prio val -> Bool
unionProperty a b = let ab = a `union` b
in leftistHeapProperty ab && size ab == size a + size b
&& ab == ab `union` empty
&& ab == empty `union` ab
&& a == unions (fmap (uncurry singleton) (toList a))
fmapProperty :: (Ord prio) => (val -> val) -> HeapT prio val -> Bool
fmapProperty f = leftistHeapProperty . fmap f
sizeProperty :: Int -> Bool
sizeProperty n = let
n' = abs n `mod` 100
h = fromList (zip [1..n'] (repeat ())) :: HeapT Int ()
in
size h == n' && if n' == 0 then isEmpty h else not (isEmpty h)
viewProperty :: [Int] -> Bool
viewProperty [] = True
viewProperty list = let
heap = fromList (zip list (repeat ()))
m = minimum list
in case view heap of
Nothing -> False -- list is not empty
Just (p, (), hs) -> p == m
&& heap == union (singleton p ()) hs
&& viewProperty (tail list)
singletonProperty :: (Ord prio, Ord val) => prio -> val -> Bool
singletonProperty p v = let
heap = singleton p v
in
leftistHeapProperty heap && size heap == 1 && view heap == Just (p, v, empty)
partitionProperty :: (Ord prio, Ord val) => (prio -> val -> Bool) -> HeapT prio val -> Bool
partitionProperty p heap = let
(yes, no) = partition (uncurry p) heap
(yes', no') = List.partition (uncurry p) (toList heap)
in
(heap, empty) == partition (const True) heap
&& (empty, heap) == partition (const False) heap
&& yes == fromList yes'
&& no == fromList no'
&& yes `union` no == heap -- nothing gets lost
splitAtProperty :: Int -> Int -> Bool
splitAtProperty i n = let
i' = i `mod` 100
n' = n `mod` 100
ab = [1..n']
(a, b) = List.splitAt i' ab
heap = fromList $ zip ab (repeat ())
in
Heap.splitAt i' heap == (zip a (repeat ()), fromList (zip b (repeat ())))
spanProperty :: Int -> Int -> Bool
spanProperty i n = let
i' = i `mod` 100
n' = n `mod` 100
ab = [1..n']
(a, b) = List.span (<= i') ab
(a', h) = Heap.span ((<=i') . fst) $ fromList (zip ab (repeat ()))
in
a == (fmap fst a') && h == fromList (zip b (repeat ()))
listProperty :: (Ord prio) => [prio] -> Bool
listProperty xs = let
list = List.sort xs
heap = fromList (zip xs [(1 :: Int) ..])
in
list == fmap fst (List.sort (toList heap))
sortedListProperty :: (Ord prio) => [prio] -> Bool
sortedListProperty xs = let
list = List.sort xs
heap = fromDescList (zip (reverse list) [(1 :: Int) ..])
in
list == fmap fst (toAscList heap)
| PepeLui17/Proyecto_Lenguajes_De_Programacion_Segundo_Parcial | TestInternal.hs | gpl-2.0 | 4,828 | 0 | 22 | 1,262 | 2,077 | 1,052 | 1,025 | 104 | 2 |
{- |
Module : $Header$
Description : A parser for the SPASS Input Syntax
Copyright : (c) C. Immanuel Normann, Heng Jiang, C.Maeder, Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
A parser for the SPASS Input Syntax taken from
<http://spass.mpi-sb.mpg.de/download/binaries/spass-input-syntax15.pdf >.
-}
module SoftFOL.DFGParser (parseSPASS) where
import SoftFOL.Sign
import Text.ParserCombinators.Parsec
import Common.AS_Annotation
import Common.Id
import Common.Lexer
import Common.Parsec
import Control.Monad
import Data.Char (isSpace)
import Data.Maybe
import qualified Data.Map as Map
-- * lexical matter
wordChar :: Parser Char
wordChar = alphaNum <|> oneOf "_"
anyWord :: Parser String
anyWord = do
c <- wordChar
r <- many wordChar
whiteSpace
return $ c : r
reservedList :: [String]
reservedList = ["end_of_list", "sort", "subsort", "predicate"]
identifierS :: Parser String
identifierS = try $ anyWord >>=
(\ s -> if elem s reservedList then unexpected $ show s else return s)
identifierT :: Parser Token
identifierT = liftM2 (\ p s -> Token s (Range [p])) getPos identifierS
arityT :: Parser Int
arityT = fmap read $ many1 digit <|> try (string "-1" << notFollowedBy digit)
commentLine :: Parser ()
commentLine = char '%' >> manyTill anyChar newline >> return ()
whiteSpace :: Parser ()
whiteSpace = skipMany $ (satisfy isSpace >> return ()) <|> commentLine
symbolT :: String -> Parser String
symbolT = (<< whiteSpace) . tryString
keywordT :: String -> Parser String
keywordT s = try (string s << notFollowedBy wordChar) << whiteSpace
dot :: Parser String
dot = symbolT "."
comma :: Parser String
comma = symbolT ","
commaSep :: Parser a -> Parser [a]
commaSep p = sepBy1 p comma
parens :: Parser a -> Parser a
parens p = symbolT "(" >> p << symbolT ")"
squares :: Parser a -> Parser a
squares p = symbolT "[" >> p << symbolT "]"
parensDot :: Parser a -> Parser a
parensDot p = symbolT "(" >> p << symbolT ")."
squaresDot :: Parser a -> Parser a
squaresDot p = symbolT "[" >> p << symbolT "]."
text :: Parser String
text = fmap (reverse . dropWhile isSpace . reverse) $
symbolT "{*" >> manyTill anyChar (symbolT "*}")
listOf :: String -> Parser String
listOf = symbolT . ("list_of_" ++)
listOfDot :: String -> Parser String
listOfDot = listOf . (++ ".")
endOfList :: Parser String
endOfList = symbolT "end_of_list."
mapTokensToData :: [(String, a)] -> Parser a
mapTokensToData ls = choice (map tokenToData ls)
where tokenToData (s,t) = keywordT s >> return t
-- * SPASS Problem
{- |
This is the main function of the module
-}
parseSPASS :: Parser SPProblem
parseSPASS = whiteSpace >> problem
problem :: Parser SPProblem
problem = do
symbolT "begin_problem"
i <- parensDot identifierS
dl <- descriptionList
lp <- logicalPartP
s <- settingList
symbolT "end_problem."
many anyChar
eof
return SPProblem
{ identifier = i
, description = dl
, logicalPart = lp
, settings = s}
-- ** SPASS Descriptions
{- | A description is mandatory for a SPASS problem. It has to specify
at least a 'name', the name of the 'author', the 'status' (see also
'SPLogState' below), and a (verbose) description. -}
descriptionList :: Parser SPDescription
descriptionList = do
listOfDot "descriptions"
keywordT "name"
n <- parensDot text
keywordT "author"
a <- parensDot text
v <- optionMaybe (keywordT "version" >> parensDot text)
l <- optionMaybe (keywordT "logic" >> parensDot text)
s <- keywordT "status" >> parensDot (mapTokensToData
[ ("satisfiable", SPStateSatisfiable)
, ("unsatisfiable", SPStateUnsatisfiable)
, ("unknown", SPStateUnknown)])
keywordT "description"
de <- parensDot text
da <- optionMaybe (keywordT "date" >> parensDot text)
endOfList
return SPDescription
{ name = n
, author = a
, version = v
, logic = l
, status = s
, desc = de
, date = da }
-- ** SPASS Logical Parts
{- |
A SPASS logical part consists of a symbol list, a declaration list, and a
set of formula lists. Support for clause lists and proof lists hasn't
been implemented yet.
-}
logicalPartP :: Parser SPLogicalPart
logicalPartP = do
sl <- optionMaybe symbolListP
dl <- optionMaybe declarationListP
fs <- many formulaList
cl <- many clauseList
pl <- many proofList
return SPLogicalPart
{ symbolList = sl
, declarationList = dl
, formulaLists = fs
, clauseLists = cl
, proofLists = pl }
-- *** Symbol List
{- |
SPASS Symbol List
-}
symbolListP :: Parser SPSymbolList
symbolListP = do
listOfDot "symbols"
fs <- optionL (signSymFor "functions")
ps <- optionL (signSymFor "predicates")
ss <- optionL sortSymFor
endOfList
return emptySymbolList
{ functions = fs
, predicates = ps
, sorts = ss }
signSymFor :: String -> Parser [SPSignSym]
signSymFor kind = keywordT kind >> squaresDot
(commaSep $ parens signSym <|> fmap SPSimpleSignSym identifierT)
sortSymFor :: Parser [SPSignSym]
sortSymFor = keywordT "sorts" >> squaresDot
(commaSep $ fmap SPSimpleSignSym identifierT)
signSym :: Parser SPSignSym
signSym = do
s <- identifierT
comma
a <- arityT
return SPSignSym {sym = s, arity = a}
functList :: Parser [SPIdentifier]
functList = squaresDot $ commaSep identifierT
-- *** Formula List
{- |
SPASS Formula List
-}
formulaList :: Parser SPFormulaList
formulaList = do
listOf "formulae"
ot <- parensDot $ mapTokensToData
[ ("axioms", SPOriginAxioms)
, ("conjectures", SPOriginConjectures)]
fs <- many $ formula $ case ot of
SPOriginAxioms -> True
_ -> False
endOfList
return SPFormulaList { originType = ot, formulae = fs }
clauseList :: Parser SPClauseList
clauseList = do
listOf "clauses"
(ot, ct) <- parensDot $ do
ot <- mapTokensToData
[ ("axioms", SPOriginAxioms)
, ("conjectures", SPOriginConjectures)]
comma
ct <- mapTokensToData [("cnf", SPCNF), ("dnf", SPDNF)]
return (ot, ct)
fs <- many $ clause ct $ case ot of
SPOriginAxioms -> True
_ -> False
endOfList
return SPClauseList
{ coriginType = ot
, clauseType = ct
, clauses = fs }
clause :: SPClauseType -> Bool -> Parser SPClause
clause ct bool = keywordT "clause" >> parensDot (do
sen <- clauseFork ct
cname <- optionL (comma >> identifierS)
return (makeNamed cname sen) { isAxiom = bool })
clauseFork :: SPClauseType -> Parser NSPClause
clauseFork ct = do
termWsList1@(TWL ls b) <- termWsList
do symbolT "||"
termWsList2 <- termWsList
symbolT "->"
termWsList3 <- termWsList
return (BriefClause termWsList1 termWsList2 termWsList3)
<|> case ls of
[t] | not b -> toNSPClause ct t
_ -> unexpected "clause term"
toNSPClause :: Monad m => SPClauseType -> SPTerm -> m NSPClause
toNSPClause ct t = case t of
SPQuantTerm q vl l | q == SPForall && ct == SPCNF
|| q == SPExists && ct == SPDNF -> do
b <- toClauseBody ct l
return $ QuanClause vl b
_ -> do
b <- toClauseBody ct t
return $ SimpleClause b
termWsList :: Parser TermWsList
termWsList = do
twl <- many term
p <- optionMaybe (symbolT "+")
return $ TWL twl $ isJust p
formula :: Bool -> Parser (Named SoftFOL.Sign.SPTerm)
formula bool = keywordT "formula" >> parensDot (do
sen <- term
fname <- optionL (comma >> identifierS)
return (makeNamed fname sen) { isAxiom = bool })
declarationListP :: Parser [SPDeclaration]
declarationListP = do
listOfDot "declarations"
decl <- many declaration
endOfList
return decl
declaration :: Parser SPDeclaration
declaration = do
keywordT "sort"
sortName <- identifierT
maybeFreely <- option False (keywordT "freely" >> return True)
keywordT "generated by"
funList <- functList
return SPGenDecl
{ sortSym = sortName
, freelyGenerated = maybeFreely
, funcList = funList }
<|> do
keywordT "subsort"
(s1, s2) <- parensDot $ do
s1 <- identifierT
comma
s2 <- identifierT
return (s1, s2)
return SPSubsortDecl { sortSymA = s1, sortSymB = s2 }
<|> do
keywordT "predicate"
(pn, sl) <- parensDot $ do
pn <- identifierT
comma
sl <- commaSep identifierT
return (pn, sl)
return SPPredDecl { predSym = pn, sortSyms = sl }
<|> do
t <- term
dot
return $ case t of
SPQuantTerm SPForall tlist tb ->
SPTermDecl { termDeclTermList = tlist, termDeclTerm = tb }
_ -> SPSimpleTermDecl t
-- | SPASS Proof List
proofList :: Parser SPProofList
proofList = do
listOf "proof"
pa <- optionMaybe $ parensDot $ do
pt <- optionMaybe getproofType
assList <- option Map.empty (comma >> assocList)
return (pt, assList)
steps <- many proofStep
endOfList
return $ case pa of
Nothing -> SPProofList
{ proofType = Nothing
, plAssocList = Map.empty
, step = steps}
Just (pt, mal) -> SPProofList
{ proofType = pt
, plAssocList = mal
, step = steps}
getproofType :: Parser SPIdentifier
getproofType = identifierT
assocList :: Parser SPAssocList
assocList = fmap Map.fromList $ squares $ commaSep
$ pair getKey $ symbolT ":" >> getValue
getKey :: Parser SPKey
getKey = fmap PKeyTerm term
getValue :: Parser SPValue
getValue = fmap PValTerm term
proofStep :: Parser SPProofStep
proofStep = do
keywordT "step"
(ref, res, rule, pl, mal) <- parensDot takeStep
return SPProofStep
{ reference = ref
, result = res
, ruleAppl = rule
, parentList = pl
, stepAssocList = mal}
where takeStep = do
ref <- getReference
comma
res <- getResult
comma
rule <- getRuleAppl
comma
pl <- getParentList
mal <- option Map.empty (comma >> assocList)
return (ref, res, rule, pl, mal)
getReference = fmap PRefTerm term
getResult = fmap PResTerm term
getRuleAppl = do
t <- term
let r = PRuleTerm t
return $ case t of
SPComplexTerm (SPCustomSymbol ide) [] -> case lookup (tokStr ide)
$ map ( \ z -> (show z, z))
[GeR, SpL,
SpR, EqF,
Rew, Obv,
EmS, SoR,
EqR, Mpm,
SPm, OPm,
SHy, OHy,
URR, Fac,
Spt, Inp,
Con, RRE,
SSi, ClR,
UnC, Ter] of
Just u -> PRuleUser u
Nothing -> r
_ -> r
getParentList = squares $ commaSep getParent
getParent = fmap PParTerm term
-- SPASS Settings.
settingList :: Parser [SPSetting]
settingList = many setting
setting :: Parser SPSetting
setting = do
listOfDot "general_settings"
entriesList <- many settingEntry
endOfList
return SPGeneralSettings {entries = entriesList}
<|> do
listOf "settings"
slabel <- parensDot getLabel
symbolT "{*"
t <- many clauseFormulaRelation
symbolT "*}"
endOfList
return SPSettings {settingName = slabel, settingBody = t}
settingEntry :: Parser SPHypothesis
settingEntry = do
keywordT "hypothesis"
slabels <- squaresDot (commaSep identifierT)
return (SPHypothesis slabels)
getLabel :: Parser SPSettingLabel
getLabel = mapTokensToData $ map ( \ z -> (showSettingLabel z, z))
[KIV, LEM, OTTER, PROTEIN, SATURATE, ThreeTAP, SETHEO, SPASS]
-- SPASS Clause-Formula Relation
clauseFormulaRelation :: Parser SPSettingBody
clauseFormulaRelation = do
keywordT "set_ClauseFormulaRelation"
cfr <- parensDot $ flip sepBy comma $ parens $ do
i1 <- identifierS
comma
i2 <- identifierS
return $ SPCRBIND i1 i2
return (SPClauseRelation cfr)
<|> do
t' <- identifierS
al <- parensDot (commaSep identifierS)
return (SPFlag t' al)
-- *** Terms
{- |
A SPASS Term.
-}
term :: Parser SPTerm
term = do
i <- identifierT
let iStr = tokStr i
case lookup iStr [("true", SPTrue), ("false", SPFalse)] of
Just s -> return $ simpTerm s
Nothing -> do
let s = spSym i
option (simpTerm s) $ do
(ts, as@(a : _)) <- parens $ do
ts <- optionL (squares (commaSep term) << comma)
as <- if null ts then commaSep term
else fmap (: []) term
return (ts, as)
if null ts then if elem iStr [ "forall", "exists", "true", "false"]
then unexpected $ show iStr else return $ compTerm
(case lookup iStr $ map ( \ z -> (showSPSymbol z, z))
[ SPEqual
, SPOr
, SPAnd
, SPNot
, SPImplies
, SPImplied
, SPEquiv] of
Just ks -> ks
Nothing -> s) as
else return SPQuantTerm
{ quantSym = case lookup iStr
[("forall", SPForall), ("exists", SPExists)] of
Just q -> q
Nothing -> SPCustomQuantSym i
, variableList = ts, qFormula = a }
toClauseBody :: Monad m => SPClauseType -> SPTerm -> m NSPClauseBody
toClauseBody b t = case t of
SPComplexTerm n ts | b == SPCNF && n == SPOr || b == SPDNF && n == SPAnd ->
do ls <- mapM toLiteral ts
return $ NSPClauseBody b ls
_ -> fail $ "expected " ++ show b ++ "-application"
| nevrenato/Hets_Fork | SoftFOL/DFGParser.hs | gpl-2.0 | 13,931 | 0 | 26 | 4,057 | 4,221 | 2,105 | 2,116 | 393 | 7 |
-- Largest prime factor of 600,851,475,143
-- Test to see if n is divisible evenly by a number in [2..n]
-- if yes then return that number and factorise on n`div`x
primeFacts n [] = n:[]
primeFacts n (x:xs)
| n `mod` x == 0 = x:primeFacts (n`div`x) [2..(n`div`x) -1]
| otherwise = primeFacts n xs
main = do
return $ maximum $ primeFacts 600851475143 [2..600851475143-1]
| NaevaTheCat/Project-Euler-Haskell | P3.hs | gpl-2.0 | 378 | 1 | 11 | 74 | 133 | 71 | 62 | 6 | 1 |
ana :: Functor f => (a -> f a) -> a -> Fix f
ana coalg = Fix . fmap (ana coalg) . coalg | hmemcpy/milewski-ctfp-pdf | src/content/3.8/code/haskell/snippet25.hs | gpl-3.0 | 87 | 0 | 9 | 23 | 59 | 28 | 31 | 2 | 1 |
module Language.SMTLib2.Internals.Type.Struct where
import Language.SMTLib2.Internals.Type.Nat
import Language.SMTLib2.Internals.Type.List (List(..))
import qualified Language.SMTLib2.Internals.Type.List as List
import Prelude hiding (mapM,insert)
import Data.GADT.Compare
import Data.GADT.Show
import Data.Functor.Identity
data Tree a = Leaf a
| Node [Tree a]
data Struct e tp where
Singleton :: e t -> Struct e (Leaf t)
Struct :: List (Struct e) ts -> Struct e (Node ts)
type family Index (struct :: Tree a) (idx :: [Nat]) :: Tree a where
Index x '[] = x
Index (Node xs) (n ': ns) = Index (List.Index xs n) ns
type family ElementIndex (struct :: Tree a) (idx :: [Nat]) :: a where
ElementIndex (Leaf x) '[] = x
ElementIndex (Node xs) (n ': ns) = ElementIndex (List.Index xs n) ns
type family Insert (struct :: Tree a) (idx :: [Nat]) (el :: Tree a) :: Tree a where
Insert x '[] y = y
Insert (Node xs) (n ': ns) y = Node (List.Insert xs n
(Insert (List.Index xs n) ns y))
type family Remove (struct :: Tree a) (idx :: [Nat]) :: Tree a where
Remove (Node xs) '[n] = Node (List.Remove xs n)
Remove (Node xs) (n1 ': n2 ': ns) = Node (List.Insert xs n1
(Remove (List.Index xs n1) (n2 ': ns)))
type family Size (struct :: Tree a) :: Nat where
Size (Leaf x) = S Z
Size (Node '[]) = Z
Size (Node (x ': xs)) = (Size x) + (Size (Node xs))
access :: Monad m => Struct e tp -> List Natural idx
-> (e (ElementIndex tp idx) -> m (a,e (ElementIndex tp idx)))
-> m (a,Struct e tp)
access (Singleton x) Nil f = do
(res,nx) <- f x
return (res,Singleton nx)
access (Struct xs) (n ::: ns) f = do
(res,nxs) <- List.access' xs n (\x -> access x ns f)
return (res,Struct nxs)
accessElement :: Monad m => Struct e tp -> List Natural idx
-> (e (ElementIndex tp idx) -> m (a,e ntp))
-> m (a,Struct e (Insert tp idx (Leaf ntp)))
accessElement (Singleton x) Nil f = do
(res,nx) <- f x
return (res,Singleton nx)
accessElement (Struct xs) (n ::: ns) f = do
(res,nxs) <- List.access xs n (\x -> accessElement x ns f)
return (res,Struct nxs)
index :: Struct e tp -> List Natural idx -> Struct e (Index tp idx)
index x Nil = x
index (Struct xs) (n ::: ns) = index (List.index xs n) ns
elementIndex :: Struct e tp -> List Natural idx -> e (ElementIndex tp idx)
elementIndex (Singleton x) Nil = x
elementIndex (Struct xs) (n ::: ns)
= elementIndex (List.index xs n) ns
insert :: Struct e tps -> List Natural idx -> Struct e tp
-> Struct e (Insert tps idx tp)
insert x Nil y = y
insert (Struct xs) (n ::: ns) y
= Struct (List.insert xs n (insert (List.index xs n) ns y))
remove :: Struct e tps -> List Natural idx -> Struct e (Remove tps idx)
remove (Struct xs) (n ::: Nil) = Struct (List.remove xs n)
remove (Struct xs) (n1 ::: n2 ::: ns)
= Struct (List.insert xs n1
(remove (List.index xs n1) (n2 ::: ns)))
mapM :: Monad m => (forall x. e x -> m (e' x)) -> Struct e tps -> m (Struct e' tps)
mapM f (Singleton x) = do
nx <- f x
return (Singleton nx)
mapM f (Struct xs) = do
nxs <- List.mapM (mapM f) xs
return (Struct nxs)
mapIndexM :: Monad m
=> (forall idx.
List Natural idx
-> e (ElementIndex tps idx)
-> m (e' (ElementIndex tps idx)))
-> Struct e tps
-> m (Struct e' tps)
mapIndexM f (Singleton x) = do
nx <- f Nil x
return (Singleton nx)
mapIndexM f (Struct xs) = do
nxs <- List.mapIndexM (\n -> mapIndexM (\ns -> f (n ::: ns))) xs
return (Struct nxs)
map :: (forall x. e x -> e' x) -> Struct e tps -> Struct e' tps
map f = runIdentity . (mapM (return.f))
size :: Struct e tps -> Natural (Size tps)
size (Singleton x) = Succ Zero
size (Struct Nil) = Zero
size (Struct (x ::: xs)) = naturalAdd (size x) (size (Struct xs))
flatten :: Monad m => (forall x. e x -> m a) -> ([a] -> m a) -> Struct e tps -> m a
flatten f _ (Singleton x) = f x
flatten f g (Struct xs) = do
nxs <- List.toList (flatten f g) xs
g nxs
flattenIndex :: Monad m => (forall idx. List Natural idx
-> e (ElementIndex tps idx)
-> m a)
-> ([a] -> m a)
-> Struct e tps -> m a
flattenIndex f _ (Singleton x) = f Nil x
flattenIndex f g (Struct xs) = do
nxs <- List.toListIndex (\n x -> flattenIndex (\idx -> f (n ::: idx)) g x) xs
g nxs
zipWithM :: Monad m => (forall x. e1 x -> e2 x -> m (e3 x))
-> Struct e1 tps -> Struct e2 tps -> m (Struct e3 tps)
zipWithM f (Singleton x) (Singleton y) = do
z <- f x y
return (Singleton z)
zipWithM f (Struct xs) (Struct ys) = do
zs <- List.zipWithM (zipWithM f) xs ys
return (Struct zs)
zipFlatten :: Monad m => (forall x. e1 x -> e2 x -> m a)
-> ([a] -> m a)
-> Struct e1 tps -> Struct e2 tps -> m a
zipFlatten f _ (Singleton x) (Singleton y) = f x y
zipFlatten f g (Struct xs) (Struct ys) = do
zs <- List.zipToListM (zipFlatten f g) xs ys
g zs
instance GEq e => Eq (Struct e tps) where
(==) (Singleton x) (Singleton y) = case geq x y of
Just Refl -> True
Nothing -> False
(==) (Struct xs) (Struct ys) = xs==ys
instance GEq e => GEq (Struct e) where
geq (Singleton x) (Singleton y) = do
Refl <- geq x y
return Refl
geq (Struct xs) (Struct ys) = do
Refl <- geq xs ys
return Refl
geq _ _ = Nothing
instance GCompare e => Ord (Struct e tps) where
compare (Singleton x) (Singleton y) = case gcompare x y of
GEQ -> EQ
GLT -> LT
GGT -> GT
compare (Struct xs) (Struct ys) = compare xs ys
instance GCompare e => GCompare (Struct e) where
gcompare (Singleton x) (Singleton y) = case gcompare x y of
GEQ -> GEQ
GLT -> GLT
GGT -> GGT
gcompare (Singleton _) _ = GLT
gcompare _ (Singleton _) = GGT
gcompare (Struct xs) (Struct ys) = case gcompare xs ys of
GEQ -> GEQ
GLT -> GLT
GGT -> GGT
instance GShow e => Show (Struct e tps) where
showsPrec p (Singleton x) = gshowsPrec p x
showsPrec p (Struct xs) = showParen (p>10) $
showString "Struct " .
showsPrec 11 xs
instance GShow e => GShow (Struct e) where
gshowsPrec = showsPrec
| hguenther/smtlib2 | Language/SMTLib2/Internals/Type/Struct.hs | gpl-3.0 | 6,285 | 0 | 16 | 1,746 | 3,281 | 1,640 | 1,641 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable, RecordWildCards #-}
-- |Encoder for any kind of streaming content with some kind of
-- separators.
module Main where
import qualified Data.ByteString.Char8 as BS
import Network
import System.Console.CmdArgs.Implicit
import System.IO
data Args = Args { socket :: String
} deriving (Show, Data, Typeable)
synopsis =
Args { socket = def &= argPos 0 &= typ "SOCKET"
}
&= program "kryptoradio-streamer"
&= summary "Kryptoradio Streamer v0.0.1"
&= help "Listens to incoming data in standard input and sends it to \
\Kryptoradio Encoder"
main = do
Args{..} <- cmdArgs synopsis
out <- connectTo undefined $ UnixSocket socket
hSetBuffering stdin LineBuffering
let loop queue = do
bs <- BS.getLine
left <- update out (bs:queue)
loop left
in loop []
-- |Updates data in encoder and returns remaining buffer.
update :: Handle -> [BS.ByteString] -> IO [BS.ByteString]
update h queue = do
-- Try to delete last and get report
deleted <- isDeleted h
let sendList = case deleted of
True -> queue
False -> [head queue]
newStuff = BS.intercalate "\n" $ reverse sendList
-- Send to socket
hPrint h $ BS.length newStuff
BS.hPut h newStuff
-- Return remaining buffer
return sendList
-- |Returns True if previously sent element was dequeued or False
-- otherwise. Blocks until it gets a response from main thread.
isDeleted :: Handle -> IO Bool
isDeleted h = do
BS.hPut h "D"
loop
where loop = do
c <- BS.hGet h 1
case c of
"R" -> return False
"D" -> return True
_ -> loop
| koodilehto/kryptoradio | data_sources/streaming/Main.hs | agpl-3.0 | 1,692 | 0 | 16 | 440 | 427 | 210 | 217 | 42 | 3 |
module Main where
import Tokenizer
import Types
import Grammar
import FP_ParserGen -- Touching this file leaves you at your own devices
import ASTBuilder
import Checker
import CodeGen
-- import Simulation
import System.FilePath
import Sprockell
main :: IO()
main = do
putStrLn "What file do you want to run? Please provide the relative path excluding the extension."
fileName <- getLine :: IO String
putStrLn "How many Sprockells do you want to use to run this file?"
sprockells <- getLine :: IO String
putStrLn $ "Running: " ++ fileName ++ ".shl"
putStrLn $ "On " ++ sprockells ++ " Sprockells"
file <- readFile $ fileName ++ ".shl"
run $
replicate (read sprockells :: Int) $
codeGen' (read sprockells :: Int) $
checker $
pTreeToAst $
parse grammar Program $
toTokenList $
tokenizer file
| wouwouwou/2017_module_8 | src/haskell/PP-project-2017/Main.hs | apache-2.0 | 897 | 0 | 16 | 239 | 196 | 99 | 97 | 27 | 1 |
{-# language DataKinds #-}
{-# language FlexibleContexts #-}
{-# language PartialTypeSignatures #-}
{-# language OverloadedLabels #-}
{-# language OverloadedStrings #-}
{-# language TypeApplications #-}
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
module Main where
import Data.Conduit
import qualified Data.Conduit.Combinators as C
import Data.Monoid as M
import Data.Text as T
( Text )
import Mu.GRpc.Server
import Mu.Server
import Mu.Schema.Optics
import ProtobufProtocol
main :: IO ()
main = runGRpcApp msgProtoBuf 9123 server
ping :: (MonadServer m) => m ()
ping = return ()
getForecast :: (MonadServer m) => GetForecastRequest -> m GetForecastResponse
getForecast req = return resp
where
days = fromIntegral $ req ^. #days_required
forecasts = sunnyDays days
resp = record (lastUpdated, forecasts)
lastUpdated :: T.Text
lastUpdated = "2020-03-20T12:00:00Z"
sunnyDays :: Int -> [Weather]
sunnyDays n = replicate n (enum @"SUNNY")
publishRainEvents
:: (MonadServer m) => ConduitT () RainEvent m () -> m RainSummaryResponse
publishRainEvents source = toResponse <$> countRainStartedEvents
where
toResponse count = record1 $ fromIntegral (M.getSum count)
countRainStartedEvents = runConduit $ source .| C.foldMap countMsg
countMsg msg = countEvent $ msg ^. #event_type
countEvent (Just x) | x == started = M.Sum 1
countEvent Nothing = M.Sum 1
countEvent _ = M.Sum 0
subscribeToRainEvents
:: (MonadServer m)
=> SubscribeToRainEventsRequest
-> ConduitT RainEvent Void m ()
-> m ()
subscribeToRainEvents req sink = runConduit $ C.yieldMany events .| sink
where
events = toRainEvent <$> [started, stopped, started, stopped, started]
toRainEvent x = record (city, Just x)
city = req ^. #city
server :: (MonadServer m) => SingleServerT info WeatherService m _
server = singleService
( method @"ping" ping
, method @"getForecast" getForecast
, method @"publishRainEvents" publishRainEvents
, method @"subscribeToRainEvents" subscribeToRainEvents
)
| frees-io/freestyle-rpc | modules/haskell-integration-tests/mu-haskell-client-server/protobuf-server/Main.hs | apache-2.0 | 2,250 | 0 | 11 | 566 | 576 | 306 | 270 | 54 | 3 |
module Coins.A263135Spec (main, spec) where
import Test.Hspec
import Coins.A263135 (a263135)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A263135" $
it "correctly computes the first 20 elements" $
map a263135 [0..20] `shouldBe` expectedValue where
expectedValue = [0,0,1,2,3,4,6,7,8,9,11,12,13,15,16,17,19,20,21,23,24]
| peterokagey/haskellOEIS | test/Coins/A263135Spec.hs | apache-2.0 | 354 | 0 | 8 | 61 | 157 | 94 | 63 | 10 | 1 |
-- Copyright 2012-2014 Samplecount S.L.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Development.Shake.Language.C.Host.Linux (
getHostToolChain
) where
import Development.Shake
import Development.Shake.Language.C.Target
import Development.Shake.Language.C.Target.Linux
import Development.Shake.Language.C.ToolChain
import System.Process (readProcess)
-- | Get host architecture.
getHostArch :: IO Arch
getHostArch = do
arch <- fmap (head.lines) $ readProcess "uname" ["-m"] ""
return $ case arch of
"i386" -> X86 I386
"i686" -> X86 I686
"x86_64" -> X86 X86_64
"armv7l" -> Arm Armv7
_ -> error $ "Unknown host architecture " ++ arch
-- | Get host toolchain.
getHostToolChain :: IO (Target, Action ToolChain)
getHostToolChain = do
t <- fmap target getHostArch
return (t, return $ toolChain GCC)
| samplecount/shake-language-c | src/Development/Shake/Language/C/Host/Linux.hs | apache-2.0 | 1,375 | 0 | 12 | 255 | 226 | 129 | 97 | 20 | 5 |
module Sol1 where
import GS
-- 1.9
maxInt :: [Int] -> Int
maxInt [] = error "empty list"
maxInt [x] = x
maxInt (x:xs) = max x (maxInt xs)
-- 1.10
removeFst :: [Int] -> Int -> [Int]
removeFst [] y = []
removeFst (x:xs) y | x == y = xs
| otherwise = x:removeFst xs y
-- 1.13
count :: Char -> String -> Int
count x [] = 0
count x (y:ys) | x == y = 1 + count x ys
| otherwise = count x ys
-- 1.14
blowup :: String -> String
blowup [] = []
blowup x = blowup (init x) ++ replicate (length x) (last x)
-- 1.15 (simple sort)
srtStringS :: [String] -> [String]
srtStringS [] = []
srtStringS [x] = [x]
srtStringS (x:y:xs) | x > y = srtStringS(y:x:xs)
| otherwise = x : srtStringS(y:xs)
-- 1.15 alternative, quicksort (faster)
srtStringQ :: [String] -> [String]
srtStringQ [] = []
srtStringQ (x:xs) = (srtStringQ lesser) ++ [x] ++ (srtStringQ greater)
where
lesser = filter (< x) xs
greater = filter (>= x) xs
-- 1.15 routing
srtString = srtStringQ
-- prefix
prefix :: String -> String -> Bool
prefix [] ys = True
prefix (x:xs) [] = False
prefix (x:xs) (y:ys) = (x == y) && prefix xs ys
-- 1.17
substring :: String -> String -> Bool
substring [] ys = True
substring xs [] = False
substring (x:xs) (y:ys) = prefix (x:xs) (y:ys) || substring (x:xs) ys
-- 1.20
lengths :: [[a]] -> [Int]
lengths x = map length x
-- 1.21
sumLengths :: [[a]] -> Int
sumLengths x = sum (lengths x)
| bartolkaruza/software-testing-2014-group-W1 | week1/week_1_group_w1/Sol1.hs | apache-2.0 | 1,655 | 0 | 9 | 565 | 742 | 390 | 352 | 40 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGLFramebufferObject.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:36
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Opengl.QGLFramebufferObject (
Attachment, eNoAttachment, eCombinedDepthStencil, eDepth
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CAttachment a = CAttachment a
type Attachment = QEnum(CAttachment Int)
ieAttachment :: Int -> Attachment
ieAttachment x = QEnum (CAttachment x)
instance QEnumC (CAttachment Int) where
qEnum_toInt (QEnum (CAttachment x)) = x
qEnum_fromInt x = QEnum (CAttachment x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> Attachment -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eNoAttachment :: Attachment
eNoAttachment
= ieAttachment $ 0
eCombinedDepthStencil :: Attachment
eCombinedDepthStencil
= ieAttachment $ 1
eDepth :: Attachment
eDepth
= ieAttachment $ 2
| keera-studios/hsQt | Qtc/Enums/Opengl/QGLFramebufferObject.hs | bsd-2-clause | 2,489 | 0 | 18 | 532 | 612 | 313 | 299 | 55 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Setup
-- Copyright : Isaac Jones 2003-2004
-- Duncan Coutts 2007
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is a big module, but not very complicated. The code is very regular
-- and repetitive. It defines the command line interface for all the Cabal
-- commands. For each command (like @configure@, @build@ etc) it defines a type
-- that holds all the flags, the default set of flags and a 'CommandUI' that
-- maps command line flags to and from the corresponding flags type.
--
-- All the flags types are instances of 'Monoid', see
-- <http://www.haskell.org/pipermail/cabal-devel/2007-December/001509.html>
-- for an explanation.
--
-- The types defined here get used in the front end and especially in
-- @cabal-install@ which has to do quite a bit of manipulating sets of command
-- line flags.
--
-- This is actually relatively nice, it works quite well. The main change it
-- needs is to unify it with the code for managing sets of fields that can be
-- read and written from files. This would allow us to save configure flags in
-- config files.
module Distribution.Simple.Setup (
GlobalFlags(..), emptyGlobalFlags, defaultGlobalFlags, globalCommand,
ConfigFlags(..), emptyConfigFlags, defaultConfigFlags, configureCommand,
configPrograms,
RelaxDeps(..), RelaxedDep(..), isRelaxDeps,
AllowNewer(..), AllowOlder(..),
configAbsolutePaths, readPackageDbList, showPackageDbList,
CopyFlags(..), emptyCopyFlags, defaultCopyFlags, copyCommand,
InstallFlags(..), emptyInstallFlags, defaultInstallFlags, installCommand,
HaddockTarget(..),
HaddockFlags(..), emptyHaddockFlags, defaultHaddockFlags, haddockCommand,
HscolourFlags(..), emptyHscolourFlags, defaultHscolourFlags, hscolourCommand,
BuildFlags(..), emptyBuildFlags, defaultBuildFlags, buildCommand,
buildVerbose,
ReplFlags(..), defaultReplFlags, replCommand,
CleanFlags(..), emptyCleanFlags, defaultCleanFlags, cleanCommand,
RegisterFlags(..), emptyRegisterFlags, defaultRegisterFlags, registerCommand,
unregisterCommand,
SDistFlags(..), emptySDistFlags, defaultSDistFlags, sdistCommand,
TestFlags(..), emptyTestFlags, defaultTestFlags, testCommand,
TestShowDetails(..),
BenchmarkFlags(..), emptyBenchmarkFlags,
defaultBenchmarkFlags, benchmarkCommand,
CopyDest(..),
configureArgs, configureOptions, configureCCompiler, configureLinker,
buildOptions, haddockOptions, installDirsOptions,
programDbOptions, programDbPaths',
programConfigurationOptions, programConfigurationPaths',
splitArgs,
defaultDistPref, optionDistPref,
Flag(..),
toFlag,
fromFlag,
fromFlagOrDefault,
flagToMaybe,
flagToList,
BooleanFlag(..),
boolOpt, boolOpt', trueArg, falseArg,
optionVerbosity, optionNumJobs, readPToMaybe ) where
import Prelude ()
import Distribution.Compat.Prelude hiding (get)
import Distribution.Compiler
import Distribution.ReadE
import Distribution.Text
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import Distribution.Package
import Distribution.PackageDescription hiding (Flag)
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import qualified Distribution.Simple.Command as Command
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Simple.Utils
import Distribution.Simple.Program
import Distribution.Simple.InstallDirs
import Distribution.Verbosity
import Distribution.Utils.NubList
import Distribution.Compat.Semigroup (Last' (..))
import Data.Function (on)
-- FIXME Not sure where this should live
defaultDistPref :: FilePath
defaultDistPref = "dist"
-- ------------------------------------------------------------
-- * Flag type
-- ------------------------------------------------------------
-- | All flags are monoids, they come in two flavours:
--
-- 1. list flags eg
--
-- > --ghc-option=foo --ghc-option=bar
--
-- gives us all the values ["foo", "bar"]
--
-- 2. singular value flags, eg:
--
-- > --enable-foo --disable-foo
--
-- gives us Just False
-- So this Flag type is for the latter singular kind of flag.
-- Its monoid instance gives us the behaviour where it starts out as
-- 'NoFlag' and later flags override earlier ones.
--
data Flag a = Flag a | NoFlag deriving (Eq, Generic, Show, Read)
instance Binary a => Binary (Flag a)
instance Functor Flag where
fmap f (Flag x) = Flag (f x)
fmap _ NoFlag = NoFlag
instance Monoid (Flag a) where
mempty = NoFlag
mappend = (<>)
instance Semigroup (Flag a) where
_ <> f@(Flag _) = f
f <> NoFlag = f
instance Bounded a => Bounded (Flag a) where
minBound = toFlag minBound
maxBound = toFlag maxBound
instance Enum a => Enum (Flag a) where
fromEnum = fromEnum . fromFlag
toEnum = toFlag . toEnum
enumFrom (Flag a) = map toFlag . enumFrom $ a
enumFrom _ = []
enumFromThen (Flag a) (Flag b) = toFlag `map` enumFromThen a b
enumFromThen _ _ = []
enumFromTo (Flag a) (Flag b) = toFlag `map` enumFromTo a b
enumFromTo _ _ = []
enumFromThenTo (Flag a) (Flag b) (Flag c) = toFlag `map` enumFromThenTo a b c
enumFromThenTo _ _ _ = []
toFlag :: a -> Flag a
toFlag = Flag
fromFlag :: Flag a -> a
fromFlag (Flag x) = x
fromFlag NoFlag = error "fromFlag NoFlag. Use fromFlagOrDefault"
fromFlagOrDefault :: a -> Flag a -> a
fromFlagOrDefault _ (Flag x) = x
fromFlagOrDefault def NoFlag = def
flagToMaybe :: Flag a -> Maybe a
flagToMaybe (Flag x) = Just x
flagToMaybe NoFlag = Nothing
flagToList :: Flag a -> [a]
flagToList (Flag x) = [x]
flagToList NoFlag = []
allFlags :: [Flag Bool] -> Flag Bool
allFlags flags = if all (\f -> fromFlagOrDefault False f) flags
then Flag True
else NoFlag
-- | Types that represent boolean flags.
class BooleanFlag a where
asBool :: a -> Bool
instance BooleanFlag Bool where
asBool = id
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
-- In fact since individual flags types are monoids and these are just sets of
-- flags then they are also monoids pointwise. This turns out to be really
-- useful. The mempty is the set of empty flags and mappend allows us to
-- override specific flags. For example we can start with default flags and
-- override with the ones we get from a file or the command line, or both.
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool,
globalNumericVersion :: Flag Bool
} deriving (Generic)
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False,
globalNumericVersion = Flag False
}
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI
{ commandName = ""
, commandSynopsis = ""
, commandUsage = \pname ->
"This Setup program uses the Haskell Cabal Infrastructure.\n"
++ "See http://www.haskell.org/cabal/ for more information.\n"
++ "\n"
++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n"
, commandDescription = Just $ \pname ->
let
commands' = commands ++ [commandAddAction helpCommandUI undefined]
cmdDescs = getNormalCommandDescriptions commands'
maxlen = maximum $ [length name | (name, _) <- cmdDescs]
align str = str ++ replicate (maxlen - length str) ' '
in
"Commands:\n"
++ unlines [ " " ++ align name ++ " " ++ descr
| (name, descr) <- cmdDescs ]
++ "\n"
++ "For more information about a command use\n"
++ " " ++ pname ++ " COMMAND --help\n\n"
++ "Typical steps for installing Cabal packages:\n"
++ concat [ " " ++ pname ++ " " ++ x ++ "\n"
| x <- ["configure", "build", "install"]]
, commandNotes = Nothing
, commandDefaultFlags = defaultGlobalFlags
, commandOptions = \_ ->
[option ['V'] ["version"]
"Print version information"
globalVersion (\v flags -> flags { globalVersion = v })
trueArg
,option [] ["numeric-version"]
"Print just the version number"
globalNumericVersion (\v flags -> flags { globalNumericVersion = v })
trueArg
]
}
emptyGlobalFlags :: GlobalFlags
emptyGlobalFlags = mempty
instance Monoid GlobalFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup GlobalFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Config flags
-- ------------------------------------------------------------
-- | Generic data type for policy when relaxing bounds in dependencies.
-- Don't use this directly: use 'AllowOlder' or 'AllowNewer' depending
-- on whether or not you are relaxing an lower or upper bound
-- (respectively).
data RelaxDeps =
-- | Default: honor the upper bounds in all dependencies, never choose
-- versions newer than allowed.
RelaxDepsNone
-- | Ignore upper bounds in dependencies on the given packages.
| RelaxDepsSome [RelaxedDep]
-- | Ignore upper bounds in dependencies on all packages.
| RelaxDepsAll
deriving (Eq, Read, Show, Generic)
-- | 'RelaxDeps' in the context of upper bounds (i.e. for @--allow-newer@ flag)
newtype AllowNewer = AllowNewer { unAllowNewer :: RelaxDeps }
deriving (Eq, Read, Show, Generic)
-- | 'RelaxDeps' in the context of lower bounds (i.e. for @--allow-older@ flag)
newtype AllowOlder = AllowOlder { unAllowOlder :: RelaxDeps }
deriving (Eq, Read, Show, Generic)
-- | Dependencies can be relaxed either for all packages in the install plan, or
-- only for some packages.
data RelaxedDep = RelaxedDep PackageName
| RelaxedDepScoped PackageName PackageName
deriving (Eq, Read, Show, Generic)
instance Text RelaxedDep where
disp (RelaxedDep p0) = disp p0
disp (RelaxedDepScoped p0 p1) = disp p0 Disp.<> Disp.colon Disp.<> disp p1
parse = scopedP Parse.<++ normalP
where
scopedP = RelaxedDepScoped `fmap` parse <* Parse.char ':' <*> parse
normalP = RelaxedDep `fmap` parse
instance Binary RelaxDeps
instance Binary RelaxedDep
instance Binary AllowNewer
instance Binary AllowOlder
instance Semigroup RelaxDeps where
RelaxDepsNone <> r = r
l@RelaxDepsAll <> _ = l
l@(RelaxDepsSome _) <> RelaxDepsNone = l
(RelaxDepsSome _) <> r@RelaxDepsAll = r
(RelaxDepsSome a) <> (RelaxDepsSome b) = RelaxDepsSome (a ++ b)
instance Monoid RelaxDeps where
mempty = RelaxDepsNone
mappend = (<>)
instance Semigroup AllowNewer where
AllowNewer x <> AllowNewer y = AllowNewer (x <> y)
instance Semigroup AllowOlder where
AllowOlder x <> AllowOlder y = AllowOlder (x <> y)
instance Monoid AllowNewer where
mempty = AllowNewer mempty
mappend = (<>)
instance Monoid AllowOlder where
mempty = AllowOlder mempty
mappend = (<>)
-- | Convert 'RelaxDeps' to a boolean.
isRelaxDeps :: RelaxDeps -> Bool
isRelaxDeps RelaxDepsNone = False
isRelaxDeps (RelaxDepsSome _) = True
isRelaxDeps RelaxDepsAll = True
relaxDepsParser :: Parse.ReadP r (Maybe RelaxDeps)
relaxDepsParser =
(Just . RelaxDepsSome) `fmap` Parse.sepBy1 parse (Parse.char ',')
relaxDepsPrinter :: (Maybe RelaxDeps) -> [Maybe String]
relaxDepsPrinter Nothing = []
relaxDepsPrinter (Just RelaxDepsNone) = []
relaxDepsPrinter (Just RelaxDepsAll) = [Nothing]
relaxDepsPrinter (Just (RelaxDepsSome pkgs)) = map (Just . display) $ pkgs
-- | Flags to @configure@ command.
--
-- IMPORTANT: every time a new flag is added, 'D.C.Setup.filterConfigureFlags'
-- should be updated.
-- IMPORTANT: every time a new flag is added, it should be added to the Eq instance
data ConfigFlags = ConfigFlags {
-- This is the same hack as in 'buildArgs' and 'copyArgs'.
-- TODO: Stop using this eventually when 'UserHooks' gets changed
configArgs :: [String],
--FIXME: the configPrograms is only here to pass info through to configure
-- because the type of configure is constrained by the UserHooks.
-- when we change UserHooks next we should pass the initial
-- ProgramDb directly and not via ConfigFlags
configPrograms_ :: Last' ProgramDb, -- ^All programs that
-- @cabal@ may run
configProgramPaths :: [(String, FilePath)], -- ^user specified programs paths
configProgramArgs :: [(String, [String])], -- ^user specified programs args
configProgramPathExtra :: NubList FilePath, -- ^Extend the $PATH
configHcFlavor :: Flag CompilerFlavor, -- ^The \"flavor\" of the
-- compiler, such as GHC or
-- JHC.
configHcPath :: Flag FilePath, -- ^given compiler location
configHcPkg :: Flag FilePath, -- ^given hc-pkg location
configVanillaLib :: Flag Bool, -- ^Enable vanilla library
configProfLib :: Flag Bool, -- ^Enable profiling in the library
configSharedLib :: Flag Bool, -- ^Build shared library
configDynExe :: Flag Bool, -- ^Enable dynamic linking of the
-- executables.
configProfExe :: Flag Bool, -- ^Enable profiling in the
-- executables.
configProf :: Flag Bool, -- ^Enable profiling in the library
-- and executables.
configProfDetail :: Flag ProfDetailLevel, -- ^Profiling detail level
-- in the library and executables.
configProfLibDetail :: Flag ProfDetailLevel, -- ^Profiling detail level
-- in the library
configConfigureArgs :: [String], -- ^Extra arguments to @configure@
configOptimization :: Flag OptimisationLevel, -- ^Enable optimization.
configProgPrefix :: Flag PathTemplate, -- ^Installed executable prefix.
configProgSuffix :: Flag PathTemplate, -- ^Installed executable suffix.
configInstallDirs :: InstallDirs (Flag PathTemplate), -- ^Installation
-- paths
configScratchDir :: Flag FilePath,
configExtraLibDirs :: [FilePath], -- ^ path to search for extra libraries
configExtraFrameworkDirs :: [FilePath], -- ^ path to search for extra
-- frameworks (OS X only)
configExtraIncludeDirs :: [FilePath], -- ^ path to search for header files
configIPID :: Flag String, -- ^ explicit IPID to be used
configCID :: Flag ComponentId, -- ^ explicit CID to be used
configDistPref :: Flag FilePath, -- ^"dist" prefix
configCabalFilePath :: Flag FilePath, -- ^ Cabal file to use
configVerbosity :: Flag Verbosity, -- ^verbosity level
configUserInstall :: Flag Bool, -- ^The --user\/--global flag
configPackageDBs :: [Maybe PackageDB], -- ^Which package DBs to use
configGHCiLib :: Flag Bool, -- ^Enable compiling library for GHCi
configSplitObjs :: Flag Bool, -- ^Enable -split-objs with GHC
configStripExes :: Flag Bool, -- ^Enable executable stripping
configStripLibs :: Flag Bool, -- ^Enable library stripping
configConstraints :: [Dependency], -- ^Additional constraints for
-- dependencies.
configDependencies :: [(PackageName, ComponentId)],
-- ^The packages depended on.
configConfigurationsFlags :: FlagAssignment,
configTests :: Flag Bool, -- ^Enable test suite compilation
configBenchmarks :: Flag Bool, -- ^Enable benchmark compilation
configCoverage :: Flag Bool, -- ^Enable program coverage
configLibCoverage :: Flag Bool, -- ^Enable program coverage (deprecated)
configExactConfiguration :: Flag Bool,
-- ^All direct dependencies and flags are provided on the command line by
-- the user via the '--dependency' and '--flags' options.
configFlagError :: Flag String,
-- ^Halt and show an error message indicating an error in flag assignment
configRelocatable :: Flag Bool, -- ^ Enable relocatable package built
configDebugInfo :: Flag DebugInfoLevel, -- ^ Emit debug info.
configAllowOlder :: Maybe AllowOlder, -- ^ dual to 'configAllowNewer'
configAllowNewer :: Maybe AllowNewer
-- ^ Ignore upper bounds on all or some dependencies. Wrapped in 'Maybe' to
-- distinguish between "default" and "explicitly disabled".
}
deriving (Generic, Read, Show)
instance Binary ConfigFlags
-- | More convenient version of 'configPrograms'. Results in an
-- 'error' if internal invariant is violated.
configPrograms :: ConfigFlags -> ProgramDb
configPrograms = maybe (error "FIXME: remove configPrograms") id . getLast' . configPrograms_
instance Eq ConfigFlags where
(==) a b =
-- configPrograms skipped: not user specified, has no Eq instance
equal configProgramPaths
&& equal configProgramArgs
&& equal configProgramPathExtra
&& equal configHcFlavor
&& equal configHcPath
&& equal configHcPkg
&& equal configVanillaLib
&& equal configProfLib
&& equal configSharedLib
&& equal configDynExe
&& equal configProfExe
&& equal configProf
&& equal configProfDetail
&& equal configProfLibDetail
&& equal configConfigureArgs
&& equal configOptimization
&& equal configProgPrefix
&& equal configProgSuffix
&& equal configInstallDirs
&& equal configScratchDir
&& equal configExtraLibDirs
&& equal configExtraIncludeDirs
&& equal configIPID
&& equal configDistPref
&& equal configVerbosity
&& equal configUserInstall
&& equal configPackageDBs
&& equal configGHCiLib
&& equal configSplitObjs
&& equal configStripExes
&& equal configStripLibs
&& equal configConstraints
&& equal configDependencies
&& equal configConfigurationsFlags
&& equal configTests
&& equal configBenchmarks
&& equal configCoverage
&& equal configLibCoverage
&& equal configExactConfiguration
&& equal configFlagError
&& equal configRelocatable
&& equal configDebugInfo
where
equal f = on (==) f a b
configAbsolutePaths :: ConfigFlags -> NoCallStackIO ConfigFlags
configAbsolutePaths f =
(\v -> f { configPackageDBs = v })
`liftM` traverse (maybe (return Nothing) (liftM Just . absolutePackageDBPath))
(configPackageDBs f)
defaultConfigFlags :: ProgramDb -> ConfigFlags
defaultConfigFlags progDb = emptyConfigFlags {
configArgs = [],
configPrograms_ = pure progDb,
configHcFlavor = maybe NoFlag Flag defaultCompilerFlavor,
configVanillaLib = Flag True,
configProfLib = NoFlag,
configSharedLib = NoFlag,
configDynExe = Flag False,
configProfExe = NoFlag,
configProf = NoFlag,
configProfDetail = NoFlag,
configProfLibDetail= NoFlag,
configOptimization = Flag NormalOptimisation,
configProgPrefix = Flag (toPathTemplate ""),
configProgSuffix = Flag (toPathTemplate ""),
configDistPref = NoFlag,
configCabalFilePath = NoFlag,
configVerbosity = Flag normal,
configUserInstall = Flag False, --TODO: reverse this
#if defined(mingw32_HOST_OS)
-- See #1589.
configGHCiLib = Flag True,
#else
configGHCiLib = NoFlag,
#endif
configSplitObjs = Flag False, -- takes longer, so turn off by default
configStripExes = Flag True,
configStripLibs = Flag True,
configTests = Flag False,
configBenchmarks = Flag False,
configCoverage = Flag False,
configLibCoverage = NoFlag,
configExactConfiguration = Flag False,
configFlagError = NoFlag,
configRelocatable = Flag False,
configDebugInfo = Flag NoDebugInfo,
configAllowNewer = Nothing
}
configureCommand :: ProgramDb -> CommandUI ConfigFlags
configureCommand progDb = CommandUI
{ commandName = "configure"
, commandSynopsis = "Prepare to build the package."
, commandDescription = Just $ \_ -> wrapText $
"Configure how the package is built by setting "
++ "package (and other) flags.\n"
++ "\n"
++ "The configuration affects several other commands, "
++ "including build, test, bench, run, repl.\n"
, commandNotes = Just $ \_pname -> programFlagsDescription progDb
, commandUsage = \pname ->
"Usage: " ++ pname ++ " configure [FLAGS]\n"
, commandDefaultFlags = defaultConfigFlags progDb
, commandOptions = \showOrParseArgs ->
configureOptions showOrParseArgs
++ programDbPaths progDb showOrParseArgs
configProgramPaths (\v fs -> fs { configProgramPaths = v })
++ programDbOption progDb showOrParseArgs
configProgramArgs (\v fs -> fs { configProgramArgs = v })
++ programDbOptions progDb showOrParseArgs
configProgramArgs (\v fs -> fs { configProgramArgs = v })
}
configureOptions :: ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions showOrParseArgs =
[optionVerbosity configVerbosity
(\v flags -> flags { configVerbosity = v })
,optionDistPref
configDistPref (\d flags -> flags { configDistPref = d })
showOrParseArgs
,option [] ["compiler"] "compiler"
configHcFlavor (\v flags -> flags { configHcFlavor = v })
(choiceOpt [ (Flag GHC, ("g", ["ghc"]), "compile with GHC")
, (Flag GHCJS, ([] , ["ghcjs"]), "compile with GHCJS")
, (Flag JHC, ([] , ["jhc"]), "compile with JHC")
, (Flag LHC, ([] , ["lhc"]), "compile with LHC")
, (Flag UHC, ([] , ["uhc"]), "compile with UHC")
-- "haskell-suite" compiler id string will be replaced
-- by a more specific one during the configure stage
, (Flag (HaskellSuite "haskell-suite"), ([] , ["haskell-suite"]),
"compile with a haskell-suite compiler")])
,option "" ["cabal-file"]
"use this Cabal file"
configCabalFilePath (\v flags -> flags { configCabalFilePath = v })
(reqArgFlag "PATH")
,option "w" ["with-compiler"]
"give the path to a particular compiler"
configHcPath (\v flags -> flags { configHcPath = v })
(reqArgFlag "PATH")
,option "" ["with-hc-pkg"]
"give the path to the package tool"
configHcPkg (\v flags -> flags { configHcPkg = v })
(reqArgFlag "PATH")
]
++ map liftInstallDirs installDirsOptions
++ [option "" ["program-prefix"]
"prefix to be applied to installed executables"
configProgPrefix
(\v flags -> flags { configProgPrefix = v })
(reqPathTemplateArgFlag "PREFIX")
,option "" ["program-suffix"]
"suffix to be applied to installed executables"
configProgSuffix (\v flags -> flags { configProgSuffix = v } )
(reqPathTemplateArgFlag "SUFFIX")
,option "" ["library-vanilla"]
"Vanilla libraries"
configVanillaLib (\v flags -> flags { configVanillaLib = v })
(boolOpt [] [])
,option "p" ["library-profiling"]
"Library profiling"
configProfLib (\v flags -> flags { configProfLib = v })
(boolOpt "p" [])
,option "" ["shared"]
"Shared library"
configSharedLib (\v flags -> flags { configSharedLib = v })
(boolOpt [] [])
,option "" ["executable-dynamic"]
"Executable dynamic linking"
configDynExe (\v flags -> flags { configDynExe = v })
(boolOpt [] [])
,option "" ["profiling"]
"Executable and library profiling"
configProf (\v flags -> flags { configProf = v })
(boolOpt [] [])
,option "" ["executable-profiling"]
"Executable profiling (DEPRECATED)"
configProfExe (\v flags -> flags { configProfExe = v })
(boolOpt [] [])
,option "" ["profiling-detail"]
("Profiling detail level for executable and library (default, " ++
"none, exported-functions, toplevel-functions, all-functions).")
configProfDetail (\v flags -> flags { configProfDetail = v })
(reqArg' "level" (Flag . flagToProfDetailLevel)
showProfDetailLevelFlag)
,option "" ["library-profiling-detail"]
"Profiling detail level for libraries only."
configProfLibDetail (\v flags -> flags { configProfLibDetail = v })
(reqArg' "level" (Flag . flagToProfDetailLevel)
showProfDetailLevelFlag)
,multiOption "optimization"
configOptimization (\v flags -> flags { configOptimization = v })
[optArg' "n" (Flag . flagToOptimisationLevel)
(\f -> case f of
Flag NoOptimisation -> []
Flag NormalOptimisation -> [Nothing]
Flag MaximumOptimisation -> [Just "2"]
_ -> [])
"O" ["enable-optimization","enable-optimisation"]
"Build with optimization (n is 0--2, default is 1)",
noArg (Flag NoOptimisation) []
["disable-optimization","disable-optimisation"]
"Build without optimization"
]
,multiOption "debug-info"
configDebugInfo (\v flags -> flags { configDebugInfo = v })
[optArg' "n" (Flag . flagToDebugInfoLevel)
(\f -> case f of
Flag NoDebugInfo -> []
Flag MinimalDebugInfo -> [Just "1"]
Flag NormalDebugInfo -> [Nothing]
Flag MaximalDebugInfo -> [Just "3"]
_ -> [])
"" ["enable-debug-info"]
"Emit debug info (n is 0--3, default is 0)",
noArg (Flag NoDebugInfo) []
["disable-debug-info"]
"Don't emit debug info"
]
,option "" ["library-for-ghci"]
"compile library for use with GHCi"
configGHCiLib (\v flags -> flags { configGHCiLib = v })
(boolOpt [] [])
,option "" ["split-objs"]
"split library into smaller objects to reduce binary sizes (GHC 6.6+)"
configSplitObjs (\v flags -> flags { configSplitObjs = v })
(boolOpt [] [])
,option "" ["executable-stripping"]
"strip executables upon installation to reduce binary sizes"
configStripExes (\v flags -> flags { configStripExes = v })
(boolOpt [] [])
,option "" ["library-stripping"]
"strip libraries upon installation to reduce binary sizes"
configStripLibs (\v flags -> flags { configStripLibs = v })
(boolOpt [] [])
,option "" ["configure-option"]
"Extra option for configure"
configConfigureArgs (\v flags -> flags { configConfigureArgs = v })
(reqArg' "OPT" (\x -> [x]) id)
,option "" ["user-install"]
"doing a per-user installation"
configUserInstall (\v flags -> flags { configUserInstall = v })
(boolOpt' ([],["user"]) ([], ["global"]))
,option "" ["package-db"]
( "Append the given package database to the list of package"
++ " databases used (to satisfy dependencies and register into)."
++ " May be a specific file, 'global' or 'user'. The initial list"
++ " is ['global'], ['global', 'user'], or ['global', $sandbox],"
++ " depending on context. Use 'clear' to reset the list to empty."
++ " See the user guide for details.")
configPackageDBs (\v flags -> flags { configPackageDBs = v })
(reqArg' "DB" readPackageDbList showPackageDbList)
,option "f" ["flags"]
"Force values for the given flags in Cabal conditionals in the .cabal file. E.g., --flags=\"debug -usebytestrings\" forces the flag \"debug\" to true and \"usebytestrings\" to false."
configConfigurationsFlags (\v flags -> flags { configConfigurationsFlags = v })
(reqArg' "FLAGS" readFlagList showFlagList)
,option "" ["extra-include-dirs"]
"A list of directories to search for header files"
configExtraIncludeDirs (\v flags -> flags {configExtraIncludeDirs = v})
(reqArg' "PATH" (\x -> [x]) id)
,option "" ["ipid"]
"Installed package ID to compile this package as"
configIPID (\v flags -> flags {configIPID = v})
(reqArgFlag "IPID")
,option "" ["cid"]
"Installed component ID to compile this component as"
(fmap display . configCID) (\v flags -> flags {configCID = fmap ComponentId v})
(reqArgFlag "CID")
,option "" ["extra-lib-dirs"]
"A list of directories to search for external libraries"
configExtraLibDirs (\v flags -> flags {configExtraLibDirs = v})
(reqArg' "PATH" (\x -> [x]) id)
,option "" ["extra-framework-dirs"]
"A list of directories to search for external frameworks (OS X only)"
configExtraFrameworkDirs
(\v flags -> flags {configExtraFrameworkDirs = v})
(reqArg' "PATH" (\x -> [x]) id)
,option "" ["extra-prog-path"]
"A list of directories to search for required programs (in addition to the normal search locations)"
configProgramPathExtra (\v flags -> flags {configProgramPathExtra = v})
(reqArg' "PATH" (\x -> toNubList [x]) fromNubList)
,option "" ["constraint"]
"A list of additional constraints on the dependencies."
configConstraints (\v flags -> flags { configConstraints = v})
(reqArg "DEPENDENCY"
(readP_to_E (const "dependency expected") ((\x -> [x]) `fmap` parse))
(map (\x -> display x)))
,option "" ["dependency"]
"A list of exact dependencies. E.g., --dependency=\"void=void-0.5.8-177d5cdf20962d0581fe2e4932a6c309\""
configDependencies (\v flags -> flags { configDependencies = v})
(reqArg "NAME=CID"
(readP_to_E (const "dependency expected") ((\x -> [x]) `fmap` parseDependency))
(map (\x -> display (fst x) ++ "=" ++ display (snd x))))
,option "" ["tests"]
"dependency checking and compilation for test suites listed in the package description file."
configTests (\v flags -> flags { configTests = v })
(boolOpt [] [])
,option "" ["coverage"]
"build package with Haskell Program Coverage. (GHC only)"
configCoverage (\v flags -> flags { configCoverage = v })
(boolOpt [] [])
,option "" ["library-coverage"]
"build package with Haskell Program Coverage. (GHC only) (DEPRECATED)"
configLibCoverage (\v flags -> flags { configLibCoverage = v })
(boolOpt [] [])
,option [] ["allow-older"]
("Ignore upper bounds in all dependencies or DEPS")
(fmap unAllowOlder . configAllowOlder)
(\v flags -> flags { configAllowOlder = fmap AllowOlder v})
(optArg "DEPS"
(readP_to_E ("Cannot parse the list of packages: " ++) relaxDepsParser)
(Just RelaxDepsAll) relaxDepsPrinter)
,option [] ["allow-newer"]
("Ignore upper bounds in all dependencies or DEPS")
(fmap unAllowNewer . configAllowNewer)
(\v flags -> flags { configAllowNewer = fmap AllowNewer v})
(optArg "DEPS"
(readP_to_E ("Cannot parse the list of packages: " ++) relaxDepsParser)
(Just RelaxDepsAll) relaxDepsPrinter)
,option "" ["exact-configuration"]
"All direct dependencies and flags are provided on the command line."
configExactConfiguration
(\v flags -> flags { configExactConfiguration = v })
trueArg
,option "" ["benchmarks"]
"dependency checking and compilation for benchmarks listed in the package description file."
configBenchmarks (\v flags -> flags { configBenchmarks = v })
(boolOpt [] [])
,option "" ["relocatable"]
"building a package that is relocatable. (GHC only)"
configRelocatable (\v flags -> flags { configRelocatable = v})
(boolOpt [] [])
]
where
readFlagList :: String -> FlagAssignment
readFlagList = map tagWithValue . words
where tagWithValue ('-':fname) = (FlagName (lowercase fname), False)
tagWithValue fname = (FlagName (lowercase fname), True)
showFlagList :: FlagAssignment -> [String]
showFlagList fs = [ if not set then '-':fname else fname
| (FlagName fname, set) <- fs]
liftInstallDirs =
liftOption configInstallDirs (\v flags -> flags { configInstallDirs = v })
reqPathTemplateArgFlag title _sf _lf d get set =
reqArgFlag title _sf _lf d
(fmap fromPathTemplate . get) (set . fmap toPathTemplate)
readPackageDbList :: String -> [Maybe PackageDB]
readPackageDbList "clear" = [Nothing]
readPackageDbList "global" = [Just GlobalPackageDB]
readPackageDbList "user" = [Just UserPackageDB]
readPackageDbList other = [Just (SpecificPackageDB other)]
showPackageDbList :: [Maybe PackageDB] -> [String]
showPackageDbList = map showPackageDb
where
showPackageDb Nothing = "clear"
showPackageDb (Just GlobalPackageDB) = "global"
showPackageDb (Just UserPackageDB) = "user"
showPackageDb (Just (SpecificPackageDB db)) = db
showProfDetailLevelFlag :: Flag ProfDetailLevel -> [String]
showProfDetailLevelFlag NoFlag = []
showProfDetailLevelFlag (Flag dl) = [showProfDetailLevel dl]
parseDependency :: Parse.ReadP r (PackageName, ComponentId)
parseDependency = do
x <- parse
_ <- Parse.char '='
y <- parse
return (x, y)
installDirsOptions :: [OptionField (InstallDirs (Flag PathTemplate))]
installDirsOptions =
[ option "" ["prefix"]
"bake this prefix in preparation of installation"
prefix (\v flags -> flags { prefix = v })
installDirArg
, option "" ["bindir"]
"installation directory for executables"
bindir (\v flags -> flags { bindir = v })
installDirArg
, option "" ["libdir"]
"installation directory for libraries"
libdir (\v flags -> flags { libdir = v })
installDirArg
, option "" ["libsubdir"]
"subdirectory of libdir in which libs are installed"
libsubdir (\v flags -> flags { libsubdir = v })
installDirArg
, option "" ["libexecdir"]
"installation directory for program executables"
libexecdir (\v flags -> flags { libexecdir = v })
installDirArg
, option "" ["datadir"]
"installation directory for read-only data"
datadir (\v flags -> flags { datadir = v })
installDirArg
, option "" ["datasubdir"]
"subdirectory of datadir in which data files are installed"
datasubdir (\v flags -> flags { datasubdir = v })
installDirArg
, option "" ["docdir"]
"installation directory for documentation"
docdir (\v flags -> flags { docdir = v })
installDirArg
, option "" ["htmldir"]
"installation directory for HTML documentation"
htmldir (\v flags -> flags { htmldir = v })
installDirArg
, option "" ["haddockdir"]
"installation directory for haddock interfaces"
haddockdir (\v flags -> flags { haddockdir = v })
installDirArg
, option "" ["sysconfdir"]
"installation directory for configuration files"
sysconfdir (\v flags -> flags { sysconfdir = v })
installDirArg
]
where
installDirArg _sf _lf d get set =
reqArgFlag "DIR" _sf _lf d
(fmap fromPathTemplate . get) (set . fmap toPathTemplate)
emptyConfigFlags :: ConfigFlags
emptyConfigFlags = mempty
instance Monoid ConfigFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup ConfigFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Copy flags
-- ------------------------------------------------------------
-- | Flags to @copy@: (destdir, copy-prefix (backwards compat), verbosity)
data CopyFlags = CopyFlags {
copyDest :: Flag CopyDest,
copyDistPref :: Flag FilePath,
copyVerbosity :: Flag Verbosity,
copyAssumeDepsUpToDate :: Flag Bool,
-- This is the same hack as in 'buildArgs'. But I (ezyang) don't
-- think it's a hack, it's the right way to make hooks more robust
-- TODO: Stop using this eventually when 'UserHooks' gets changed
copyArgs :: [String]
}
deriving (Show, Generic)
defaultCopyFlags :: CopyFlags
defaultCopyFlags = CopyFlags {
copyDest = Flag NoCopyDest,
copyDistPref = NoFlag,
copyVerbosity = Flag normal,
copyAssumeDepsUpToDate = Flag False,
copyArgs = []
}
copyCommand :: CommandUI CopyFlags
copyCommand = CommandUI
{ commandName = "copy"
, commandSynopsis = "Copy the files of all/specific components to install locations."
, commandDescription = Just $ \_ -> wrapText $
"Components encompass executables and libraries."
++ "Does not call register, and allows a prefix at install time. "
++ "Without the --destdir flag, configure determines location.\n"
, commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " build "
++ " All the components in the package\n"
++ " " ++ pname ++ " build foo "
++ " A component (i.e. lib, exe, test suite)"
, commandUsage = usageAlternatives "copy" $
[ "[FLAGS]"
, "COMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultCopyFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity copyVerbosity (\v flags -> flags { copyVerbosity = v })
,optionDistPref
copyDistPref (\d flags -> flags { copyDistPref = d })
showOrParseArgs
, option "" ["assume-deps-up-to-date"]
"One-shot copy"
copyAssumeDepsUpToDate (\c flags -> flags { copyAssumeDepsUpToDate = c })
trueArg
,option "" ["destdir"]
"directory to copy files to, prepended to installation directories"
copyDest (\v flags -> flags { copyDest = v })
(reqArg "DIR" (succeedReadE (Flag . CopyTo))
(\f -> case f of Flag (CopyTo p) -> [p]; _ -> []))
]
}
emptyCopyFlags :: CopyFlags
emptyCopyFlags = mempty
instance Monoid CopyFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup CopyFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------
-- | Flags to @install@: (package db, verbosity)
data InstallFlags = InstallFlags {
installPackageDB :: Flag PackageDB,
installDistPref :: Flag FilePath,
installUseWrapper :: Flag Bool,
installInPlace :: Flag Bool,
installVerbosity :: Flag Verbosity
}
deriving (Show, Generic)
defaultInstallFlags :: InstallFlags
defaultInstallFlags = InstallFlags {
installPackageDB = NoFlag,
installDistPref = NoFlag,
installUseWrapper = Flag False,
installInPlace = Flag False,
installVerbosity = Flag normal
}
installCommand :: CommandUI InstallFlags
installCommand = CommandUI
{ commandName = "install"
, commandSynopsis =
"Copy the files into the install locations. Run register."
, commandDescription = Just $ \_ -> wrapText $
"Unlike the copy command, install calls the register command."
++ "If you want to install into a location that is not what was"
++ "specified in the configure step, use the copy command.\n"
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " install [FLAGS]\n"
, commandDefaultFlags = defaultInstallFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity installVerbosity (\v flags -> flags { installVerbosity = v })
,optionDistPref
installDistPref (\d flags -> flags { installDistPref = d })
showOrParseArgs
,option "" ["inplace"]
"install the package in the install subdirectory of the dist prefix, so it can be used without being installed"
installInPlace (\v flags -> flags { installInPlace = v })
trueArg
,option "" ["shell-wrappers"]
"using shell script wrappers around executables"
installUseWrapper (\v flags -> flags { installUseWrapper = v })
(boolOpt [] [])
,option "" ["package-db"] ""
installPackageDB (\v flags -> flags { installPackageDB = v })
(choiceOpt [ (Flag UserPackageDB, ([],["user"]),
"upon configuration register this package in the user's local package database")
, (Flag GlobalPackageDB, ([],["global"]),
"(default) upon configuration register this package in the system-wide package database")])
]
}
emptyInstallFlags :: InstallFlags
emptyInstallFlags = mempty
instance Monoid InstallFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup InstallFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * SDist flags
-- ------------------------------------------------------------
-- | Flags to @sdist@: (snapshot, verbosity)
data SDistFlags = SDistFlags {
sDistSnapshot :: Flag Bool,
sDistDirectory :: Flag FilePath,
sDistDistPref :: Flag FilePath,
sDistListSources :: Flag FilePath,
sDistVerbosity :: Flag Verbosity
}
deriving (Show, Generic)
defaultSDistFlags :: SDistFlags
defaultSDistFlags = SDistFlags {
sDistSnapshot = Flag False,
sDistDirectory = mempty,
sDistDistPref = NoFlag,
sDistListSources = mempty,
sDistVerbosity = Flag normal
}
sdistCommand :: CommandUI SDistFlags
sdistCommand = CommandUI
{ commandName = "sdist"
, commandSynopsis =
"Generate a source distribution file (.tar.gz)."
, commandDescription = Nothing
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " sdist [FLAGS]\n"
, commandDefaultFlags = defaultSDistFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity sDistVerbosity (\v flags -> flags { sDistVerbosity = v })
,optionDistPref
sDistDistPref (\d flags -> flags { sDistDistPref = d })
showOrParseArgs
,option "" ["list-sources"]
"Just write a list of the package's sources to a file"
sDistListSources (\v flags -> flags { sDistListSources = v })
(reqArgFlag "FILE")
,option "" ["snapshot"]
"Produce a snapshot source distribution"
sDistSnapshot (\v flags -> flags { sDistSnapshot = v })
trueArg
,option "" ["output-directory"]
("Generate a source distribution in the given directory, "
++ "without creating a tarball")
sDistDirectory (\v flags -> flags { sDistDirectory = v })
(reqArgFlag "DIR")
]
}
emptySDistFlags :: SDistFlags
emptySDistFlags = mempty
instance Monoid SDistFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup SDistFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Register flags
-- ------------------------------------------------------------
-- | Flags to @register@ and @unregister@: (user package, gen-script,
-- in-place, verbosity)
data RegisterFlags = RegisterFlags {
regPackageDB :: Flag PackageDB,
regGenScript :: Flag Bool,
regGenPkgConf :: Flag (Maybe FilePath),
regInPlace :: Flag Bool,
regDistPref :: Flag FilePath,
regPrintId :: Flag Bool,
regVerbosity :: Flag Verbosity,
-- | If this is true, we don't register all libraries,
-- only directly referenced library in 'regArgs'.
regAssumeDepsUpToDate :: Flag Bool,
-- Same as in 'buildArgs' and 'copyArgs'
regArgs :: [String]
}
deriving (Show, Generic)
defaultRegisterFlags :: RegisterFlags
defaultRegisterFlags = RegisterFlags {
regPackageDB = NoFlag,
regGenScript = Flag False,
regGenPkgConf = NoFlag,
regInPlace = Flag False,
regDistPref = NoFlag,
regPrintId = Flag False,
regVerbosity = Flag normal,
regAssumeDepsUpToDate = Flag False,
regArgs = []
}
registerCommand :: CommandUI RegisterFlags
registerCommand = CommandUI
{ commandName = "register"
, commandSynopsis =
"Register this package with the compiler."
, commandDescription = Nothing
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " register [FLAGS]\n"
, commandDefaultFlags = defaultRegisterFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity regVerbosity (\v flags -> flags { regVerbosity = v })
,optionDistPref
regDistPref (\d flags -> flags { regDistPref = d })
showOrParseArgs
,option "" ["packageDB"] ""
regPackageDB (\v flags -> flags { regPackageDB = v })
(choiceOpt [ (Flag UserPackageDB, ([],["user"]),
"upon registration, register this package in the user's local package database")
, (Flag GlobalPackageDB, ([],["global"]),
"(default)upon registration, register this package in the system-wide package database")])
,option "" ["inplace"]
"register the package in the build location, so it can be used without being installed"
regInPlace (\v flags -> flags { regInPlace = v })
trueArg
,option "" ["assume-deps-up-to-date"]
"One-shot registration"
regAssumeDepsUpToDate (\c flags -> flags { regAssumeDepsUpToDate = c })
trueArg
,option "" ["gen-script"]
"instead of registering, generate a script to register later"
regGenScript (\v flags -> flags { regGenScript = v })
trueArg
,option "" ["gen-pkg-config"]
"instead of registering, generate a package registration file/directory"
regGenPkgConf (\v flags -> flags { regGenPkgConf = v })
(optArg' "PKG" Flag flagToList)
,option "" ["print-ipid"]
"print the installed package ID calculated for this package"
regPrintId (\v flags -> flags { regPrintId = v })
trueArg
]
}
unregisterCommand :: CommandUI RegisterFlags
unregisterCommand = CommandUI
{ commandName = "unregister"
, commandSynopsis =
"Unregister this package with the compiler."
, commandDescription = Nothing
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " unregister [FLAGS]\n"
, commandDefaultFlags = defaultRegisterFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity regVerbosity (\v flags -> flags { regVerbosity = v })
,optionDistPref
regDistPref (\d flags -> flags { regDistPref = d })
showOrParseArgs
,option "" ["user"] ""
regPackageDB (\v flags -> flags { regPackageDB = v })
(choiceOpt [ (Flag UserPackageDB, ([],["user"]),
"unregister this package in the user's local package database")
, (Flag GlobalPackageDB, ([],["global"]),
"(default) unregister this package in the system-wide package database")])
,option "" ["gen-script"]
"Instead of performing the unregister command, generate a script to unregister later"
regGenScript (\v flags -> flags { regGenScript = v })
trueArg
]
}
emptyRegisterFlags :: RegisterFlags
emptyRegisterFlags = mempty
instance Monoid RegisterFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup RegisterFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * HsColour flags
-- ------------------------------------------------------------
data HscolourFlags = HscolourFlags {
hscolourCSS :: Flag FilePath,
hscolourExecutables :: Flag Bool,
hscolourTestSuites :: Flag Bool,
hscolourBenchmarks :: Flag Bool,
hscolourDistPref :: Flag FilePath,
hscolourVerbosity :: Flag Verbosity
}
deriving (Show, Generic)
emptyHscolourFlags :: HscolourFlags
emptyHscolourFlags = mempty
defaultHscolourFlags :: HscolourFlags
defaultHscolourFlags = HscolourFlags {
hscolourCSS = NoFlag,
hscolourExecutables = Flag False,
hscolourTestSuites = Flag False,
hscolourBenchmarks = Flag False,
hscolourDistPref = NoFlag,
hscolourVerbosity = Flag normal
}
instance Monoid HscolourFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup HscolourFlags where
(<>) = gmappend
hscolourCommand :: CommandUI HscolourFlags
hscolourCommand = CommandUI
{ commandName = "hscolour"
, commandSynopsis =
"Generate HsColour colourised code, in HTML format."
, commandDescription = Just (\_ -> "Requires the hscolour program.\n")
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " hscolour [FLAGS]\n"
, commandDefaultFlags = defaultHscolourFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity hscolourVerbosity
(\v flags -> flags { hscolourVerbosity = v })
,optionDistPref
hscolourDistPref (\d flags -> flags { hscolourDistPref = d })
showOrParseArgs
,option "" ["executables"]
"Run hscolour for Executables targets"
hscolourExecutables (\v flags -> flags { hscolourExecutables = v })
trueArg
,option "" ["tests"]
"Run hscolour for Test Suite targets"
hscolourTestSuites (\v flags -> flags { hscolourTestSuites = v })
trueArg
,option "" ["benchmarks"]
"Run hscolour for Benchmark targets"
hscolourBenchmarks (\v flags -> flags { hscolourBenchmarks = v })
trueArg
,option "" ["all"]
"Run hscolour for all targets"
(\f -> allFlags [ hscolourExecutables f
, hscolourTestSuites f
, hscolourBenchmarks f])
(\v flags -> flags { hscolourExecutables = v
, hscolourTestSuites = v
, hscolourBenchmarks = v })
trueArg
,option "" ["css"]
"Use a cascading style sheet"
hscolourCSS (\v flags -> flags { hscolourCSS = v })
(reqArgFlag "PATH")
]
}
-- ------------------------------------------------------------
-- * Haddock flags
-- ------------------------------------------------------------
-- | When we build haddock documentation, there are two cases:
--
-- 1. We build haddocks only for the current development version,
-- intended for local use and not for distribution. In this case,
-- we store the generated documentation in @<dist>/doc/html/<package name>@.
--
-- 2. We build haddocks for intended for uploading them to hackage.
-- In this case, we need to follow the layout that hackage expects
-- from documentation tarballs, and we might also want to use different
-- flags than for development builds, so in this case we store the generated
-- documentation in @<dist>/doc/html/<package id>-docs@.
data HaddockTarget = ForHackage | ForDevelopment deriving (Eq, Show, Generic)
data HaddockFlags = HaddockFlags {
haddockProgramPaths :: [(String, FilePath)],
haddockProgramArgs :: [(String, [String])],
haddockHoogle :: Flag Bool,
haddockHtml :: Flag Bool,
haddockHtmlLocation :: Flag String,
haddockForHackage :: Flag HaddockTarget,
haddockExecutables :: Flag Bool,
haddockTestSuites :: Flag Bool,
haddockBenchmarks :: Flag Bool,
haddockInternal :: Flag Bool,
haddockCss :: Flag FilePath,
haddockHscolour :: Flag Bool,
haddockHscolourCss :: Flag FilePath,
haddockContents :: Flag PathTemplate,
haddockDistPref :: Flag FilePath,
haddockKeepTempFiles:: Flag Bool,
haddockVerbosity :: Flag Verbosity
}
deriving (Show, Generic)
defaultHaddockFlags :: HaddockFlags
defaultHaddockFlags = HaddockFlags {
haddockProgramPaths = mempty,
haddockProgramArgs = [],
haddockHoogle = Flag False,
haddockHtml = Flag False,
haddockHtmlLocation = NoFlag,
haddockForHackage = Flag ForDevelopment,
haddockExecutables = Flag False,
haddockTestSuites = Flag False,
haddockBenchmarks = Flag False,
haddockInternal = Flag False,
haddockCss = NoFlag,
haddockHscolour = Flag False,
haddockHscolourCss = NoFlag,
haddockContents = NoFlag,
haddockDistPref = NoFlag,
haddockKeepTempFiles= Flag False,
haddockVerbosity = Flag normal
}
haddockCommand :: CommandUI HaddockFlags
haddockCommand = CommandUI
{ commandName = "haddock"
, commandSynopsis = "Generate Haddock HTML documentation."
, commandDescription = Just $ \_ ->
"Requires the program haddock, version 2.x.\n"
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " haddock [FLAGS]\n"
, commandDefaultFlags = defaultHaddockFlags
, commandOptions = \showOrParseArgs ->
haddockOptions showOrParseArgs
++ programDbPaths progDb ParseArgs
haddockProgramPaths (\v flags -> flags { haddockProgramPaths = v})
++ programDbOption progDb showOrParseArgs
haddockProgramArgs (\v fs -> fs { haddockProgramArgs = v })
++ programDbOptions progDb ParseArgs
haddockProgramArgs (\v flags -> flags { haddockProgramArgs = v})
}
where
progDb = addKnownProgram haddockProgram
$ addKnownProgram ghcProgram
$ emptyProgramDb
haddockOptions :: ShowOrParseArgs -> [OptionField HaddockFlags]
haddockOptions showOrParseArgs =
[optionVerbosity haddockVerbosity
(\v flags -> flags { haddockVerbosity = v })
,optionDistPref
haddockDistPref (\d flags -> flags { haddockDistPref = d })
showOrParseArgs
,option "" ["keep-temp-files"]
"Keep temporary files"
haddockKeepTempFiles (\b flags -> flags { haddockKeepTempFiles = b })
trueArg
,option "" ["hoogle"]
"Generate a hoogle database"
haddockHoogle (\v flags -> flags { haddockHoogle = v })
trueArg
,option "" ["html"]
"Generate HTML documentation (the default)"
haddockHtml (\v flags -> flags { haddockHtml = v })
trueArg
,option "" ["html-location"]
"Location of HTML documentation for pre-requisite packages"
haddockHtmlLocation (\v flags -> flags { haddockHtmlLocation = v })
(reqArgFlag "URL")
,option "" ["for-hackage"]
"Collection of flags to generate documentation suitable for upload to hackage"
haddockForHackage (\v flags -> flags { haddockForHackage = v })
(noArg (Flag ForHackage))
,option "" ["executables"]
"Run haddock for Executables targets"
haddockExecutables (\v flags -> flags { haddockExecutables = v })
trueArg
,option "" ["tests"]
"Run haddock for Test Suite targets"
haddockTestSuites (\v flags -> flags { haddockTestSuites = v })
trueArg
,option "" ["benchmarks"]
"Run haddock for Benchmark targets"
haddockBenchmarks (\v flags -> flags { haddockBenchmarks = v })
trueArg
,option "" ["all"]
"Run haddock for all targets"
(\f -> allFlags [ haddockExecutables f
, haddockTestSuites f
, haddockBenchmarks f])
(\v flags -> flags { haddockExecutables = v
, haddockTestSuites = v
, haddockBenchmarks = v })
trueArg
,option "" ["internal"]
"Run haddock for internal modules and include all symbols"
haddockInternal (\v flags -> flags { haddockInternal = v })
trueArg
,option "" ["css"]
"Use PATH as the haddock stylesheet"
haddockCss (\v flags -> flags { haddockCss = v })
(reqArgFlag "PATH")
,option "" ["hyperlink-source","hyperlink-sources"]
"Hyperlink the documentation to the source code (using HsColour)"
haddockHscolour (\v flags -> flags { haddockHscolour = v })
trueArg
,option "" ["hscolour-css"]
"Use PATH as the HsColour stylesheet"
haddockHscolourCss (\v flags -> flags { haddockHscolourCss = v })
(reqArgFlag "PATH")
,option "" ["contents-location"]
"Bake URL in as the location for the contents page"
haddockContents (\v flags -> flags { haddockContents = v })
(reqArg' "URL"
(toFlag . toPathTemplate)
(flagToList . fmap fromPathTemplate))
]
emptyHaddockFlags :: HaddockFlags
emptyHaddockFlags = mempty
instance Monoid HaddockFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup HaddockFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Clean flags
-- ------------------------------------------------------------
data CleanFlags = CleanFlags {
cleanSaveConf :: Flag Bool,
cleanDistPref :: Flag FilePath,
cleanVerbosity :: Flag Verbosity
}
deriving (Show, Generic)
defaultCleanFlags :: CleanFlags
defaultCleanFlags = CleanFlags {
cleanSaveConf = Flag False,
cleanDistPref = NoFlag,
cleanVerbosity = Flag normal
}
cleanCommand :: CommandUI CleanFlags
cleanCommand = CommandUI
{ commandName = "clean"
, commandSynopsis = "Clean up after a build."
, commandDescription = Just $ \_ ->
"Removes .hi, .o, preprocessed sources, etc.\n"
, commandNotes = Nothing
, commandUsage = \pname ->
"Usage: " ++ pname ++ " clean [FLAGS]\n"
, commandDefaultFlags = defaultCleanFlags
, commandOptions = \showOrParseArgs ->
[optionVerbosity cleanVerbosity (\v flags -> flags { cleanVerbosity = v })
,optionDistPref
cleanDistPref (\d flags -> flags { cleanDistPref = d })
showOrParseArgs
,option "s" ["save-configure"]
"Do not remove the configuration file (dist/setup-config) during cleaning. Saves need to reconfigure."
cleanSaveConf (\v flags -> flags { cleanSaveConf = v })
trueArg
]
}
emptyCleanFlags :: CleanFlags
emptyCleanFlags = mempty
instance Monoid CleanFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup CleanFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------
data BuildFlags = BuildFlags {
buildProgramPaths :: [(String, FilePath)],
buildProgramArgs :: [(String, [String])],
buildDistPref :: Flag FilePath,
buildVerbosity :: Flag Verbosity,
buildNumJobs :: Flag (Maybe Int),
-- | If this is true, we don't build the dependencies of
-- 'buildArgs': only the directly referenced components.
buildAssumeDepsUpToDate :: Flag Bool,
-- TODO: this one should not be here, it's just that the silly
-- UserHooks stop us from passing extra info in other ways
buildArgs :: [String]
}
deriving (Show, Generic)
{-# DEPRECATED buildVerbose "Use buildVerbosity instead" #-}
buildVerbose :: BuildFlags -> Verbosity
buildVerbose = fromFlagOrDefault normal . buildVerbosity
defaultBuildFlags :: BuildFlags
defaultBuildFlags = BuildFlags {
buildProgramPaths = mempty,
buildProgramArgs = [],
buildDistPref = mempty,
buildVerbosity = Flag normal,
buildNumJobs = mempty,
buildAssumeDepsUpToDate = Flag False,
buildArgs = []
}
buildCommand :: ProgramDb -> CommandUI BuildFlags
buildCommand progDb = CommandUI
{ commandName = "build"
, commandSynopsis = "Compile all/specific components."
, commandDescription = Just $ \_ -> wrapText $
"Components encompass executables, tests, and benchmarks.\n"
++ "\n"
++ "Affected by configuration options, see `configure`.\n"
, commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " build "
++ " All the components in the package\n"
++ " " ++ pname ++ " build foo "
++ " A component (i.e. lib, exe, test suite)\n\n"
++ programFlagsDescription progDb
--TODO: re-enable once we have support for module/file targets
-- ++ " " ++ pname ++ " build Foo.Bar "
-- ++ " A module\n"
-- ++ " " ++ pname ++ " build Foo/Bar.hs"
-- ++ " A file\n\n"
-- ++ "If a target is ambiguous it can be qualified with the component "
-- ++ "name, e.g.\n"
-- ++ " " ++ pname ++ " build foo:Foo.Bar\n"
-- ++ " " ++ pname ++ " build testsuite1:Foo/Bar.hs\n"
, commandUsage = usageAlternatives "build" $
[ "[FLAGS]"
, "COMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBuildFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity
buildVerbosity (\v flags -> flags { buildVerbosity = v })
, optionDistPref
buildDistPref (\d flags -> flags { buildDistPref = d }) showOrParseArgs
]
++ buildOptions progDb showOrParseArgs
}
buildOptions :: ProgramDb -> ShowOrParseArgs
-> [OptionField BuildFlags]
buildOptions progDb showOrParseArgs =
[ optionNumJobs
buildNumJobs (\v flags -> flags { buildNumJobs = v })
, option "" ["assume-deps-up-to-date"]
"One-shot build"
buildAssumeDepsUpToDate (\c flags -> flags { buildAssumeDepsUpToDate = c })
trueArg
]
++ programDbPaths progDb showOrParseArgs
buildProgramPaths (\v flags -> flags { buildProgramPaths = v})
++ programDbOption progDb showOrParseArgs
buildProgramArgs (\v fs -> fs { buildProgramArgs = v })
++ programDbOptions progDb showOrParseArgs
buildProgramArgs (\v flags -> flags { buildProgramArgs = v})
emptyBuildFlags :: BuildFlags
emptyBuildFlags = mempty
instance Monoid BuildFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup BuildFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * REPL Flags
-- ------------------------------------------------------------
data ReplFlags = ReplFlags {
replProgramPaths :: [(String, FilePath)],
replProgramArgs :: [(String, [String])],
replDistPref :: Flag FilePath,
replVerbosity :: Flag Verbosity,
replReload :: Flag Bool
}
deriving (Show, Generic)
defaultReplFlags :: ReplFlags
defaultReplFlags = ReplFlags {
replProgramPaths = mempty,
replProgramArgs = [],
replDistPref = NoFlag,
replVerbosity = Flag normal,
replReload = Flag False
}
instance Monoid ReplFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup ReplFlags where
(<>) = gmappend
replCommand :: ProgramDb -> CommandUI ReplFlags
replCommand progDb = CommandUI
{ commandName = "repl"
, commandSynopsis =
"Open an interpreter session for the given component."
, commandDescription = Just $ \pname -> wrapText $
"If the current directory contains no package, ignores COMPONENT "
++ "parameters and opens an interactive interpreter session; if a "
++ "sandbox is present, its package database will be used.\n"
++ "\n"
++ "Otherwise, (re)configures with the given or default flags, and "
++ "loads the interpreter with the relevant modules. For executables, "
++ "tests and benchmarks, loads the main module (and its "
++ "dependencies); for libraries all exposed/other modules.\n"
++ "\n"
++ "The default component is the library itself, or the executable "
++ "if that is the only component.\n"
++ "\n"
++ "Support for loading specific modules is planned but not "
++ "implemented yet. For certain scenarios, `" ++ pname
++ " exec -- ghci :l Foo` may be used instead. Note that `exec` will "
++ "not (re)configure and you will have to specify the location of "
++ "other modules, if required.\n"
, commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " repl "
++ " The first component in the package\n"
++ " " ++ pname ++ " repl foo "
++ " A named component (i.e. lib, exe, test suite)\n"
++ " " ++ pname ++ " repl --ghc-options=\"-lstdc++\""
++ " Specifying flags for interpreter\n"
--TODO: re-enable once we have support for module/file targets
-- ++ " " ++ pname ++ " repl Foo.Bar "
-- ++ " A module\n"
-- ++ " " ++ pname ++ " repl Foo/Bar.hs"
-- ++ " A file\n\n"
-- ++ "If a target is ambiguous it can be qualified with the component "
-- ++ "name, e.g.\n"
-- ++ " " ++ pname ++ " repl foo:Foo.Bar\n"
-- ++ " " ++ pname ++ " repl testsuite1:Foo/Bar.hs\n"
, commandUsage = \pname -> "Usage: " ++ pname ++ " repl [COMPONENT] [FLAGS]\n"
, commandDefaultFlags = defaultReplFlags
, commandOptions = \showOrParseArgs ->
optionVerbosity replVerbosity (\v flags -> flags { replVerbosity = v })
: optionDistPref
replDistPref (\d flags -> flags { replDistPref = d })
showOrParseArgs
: programDbPaths progDb showOrParseArgs
replProgramPaths (\v flags -> flags { replProgramPaths = v})
++ programDbOption progDb showOrParseArgs
replProgramArgs (\v flags -> flags { replProgramArgs = v})
++ programDbOptions progDb showOrParseArgs
replProgramArgs (\v flags -> flags { replProgramArgs = v})
++ case showOrParseArgs of
ParseArgs ->
[ option "" ["reload"]
"Used from within an interpreter to update files."
replReload (\v flags -> flags { replReload = v })
trueArg
]
_ -> []
}
-- ------------------------------------------------------------
-- * Test flags
-- ------------------------------------------------------------
data TestShowDetails = Never | Failures | Always | Streaming | Direct
deriving (Eq, Ord, Enum, Bounded, Show)
knownTestShowDetails :: [TestShowDetails]
knownTestShowDetails = [minBound..maxBound]
instance Text TestShowDetails where
disp = Disp.text . lowercase . show
parse = maybe Parse.pfail return . classify =<< ident
where
ident = Parse.munch1 (\c -> isAlpha c || c == '_' || c == '-')
classify str = lookup (lowercase str) enumMap
enumMap :: [(String, TestShowDetails)]
enumMap = [ (display x, x)
| x <- knownTestShowDetails ]
--TODO: do we need this instance?
instance Monoid TestShowDetails where
mempty = Never
mappend = (<>)
instance Semigroup TestShowDetails where
a <> b = if a < b then b else a
data TestFlags = TestFlags {
testDistPref :: Flag FilePath,
testVerbosity :: Flag Verbosity,
testHumanLog :: Flag PathTemplate,
testMachineLog :: Flag PathTemplate,
testShowDetails :: Flag TestShowDetails,
testKeepTix :: Flag Bool,
-- TODO: think about if/how options are passed to test exes
testOptions :: [PathTemplate]
} deriving (Generic)
defaultTestFlags :: TestFlags
defaultTestFlags = TestFlags {
testDistPref = NoFlag,
testVerbosity = Flag normal,
testHumanLog = toFlag $ toPathTemplate $ "$pkgid-$test-suite.log",
testMachineLog = toFlag $ toPathTemplate $ "$pkgid.log",
testShowDetails = toFlag Failures,
testKeepTix = toFlag False,
testOptions = []
}
testCommand :: CommandUI TestFlags
testCommand = CommandUI
{ commandName = "test"
, commandSynopsis =
"Run all/specific tests in the test suite."
, commandDescription = Just $ \pname -> wrapText $
"If necessary (re)configures with `--enable-tests` flag and builds"
++ " the test suite.\n"
++ "\n"
++ "Remember that the tests' dependencies must be installed if there"
++ " are additional ones; e.g. with `" ++ pname
++ " install --only-dependencies --enable-tests`.\n"
++ "\n"
++ "By defining UserHooks in a custom Setup.hs, the package can"
++ " define actions to be executed before and after running tests.\n"
, commandNotes = Nothing
, commandUsage = usageAlternatives "test"
[ "[FLAGS]"
, "TESTCOMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultTestFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity testVerbosity (\v flags -> flags { testVerbosity = v })
, optionDistPref
testDistPref (\d flags -> flags { testDistPref = d })
showOrParseArgs
, option [] ["log"]
("Log all test suite results to file (name template can use "
++ "$pkgid, $compiler, $os, $arch, $test-suite, $result)")
testHumanLog (\v flags -> flags { testHumanLog = v })
(reqArg' "TEMPLATE"
(toFlag . toPathTemplate)
(flagToList . fmap fromPathTemplate))
, option [] ["machine-log"]
("Produce a machine-readable log file (name template can use "
++ "$pkgid, $compiler, $os, $arch, $result)")
testMachineLog (\v flags -> flags { testMachineLog = v })
(reqArg' "TEMPLATE"
(toFlag . toPathTemplate)
(flagToList . fmap fromPathTemplate))
, option [] ["show-details"]
("'always': always show results of individual test cases. "
++ "'never': never show results of individual test cases. "
++ "'failures': show results of failing test cases. "
++ "'streaming': show results of test cases in real time."
++ "'direct': send results of test cases in real time; no log file.")
testShowDetails (\v flags -> flags { testShowDetails = v })
(reqArg "FILTER"
(readP_to_E (\_ -> "--show-details flag expects one of "
++ intercalate ", "
(map display knownTestShowDetails))
(fmap toFlag parse))
(flagToList . fmap display))
, option [] ["keep-tix-files"]
"keep .tix files for HPC between test runs"
testKeepTix (\v flags -> flags { testKeepTix = v})
trueArg
, option [] ["test-options"]
("give extra options to test executables "
++ "(name templates can use $pkgid, $compiler, "
++ "$os, $arch, $test-suite)")
testOptions (\v flags -> flags { testOptions = v })
(reqArg' "TEMPLATES" (map toPathTemplate . splitArgs)
(const []))
, option [] ["test-option"]
("give extra option to test executables "
++ "(no need to quote options containing spaces, "
++ "name template can use $pkgid, $compiler, "
++ "$os, $arch, $test-suite)")
testOptions (\v flags -> flags { testOptions = v })
(reqArg' "TEMPLATE" (\x -> [toPathTemplate x])
(map fromPathTemplate))
]
}
emptyTestFlags :: TestFlags
emptyTestFlags = mempty
instance Monoid TestFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup TestFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Benchmark flags
-- ------------------------------------------------------------
data BenchmarkFlags = BenchmarkFlags {
benchmarkDistPref :: Flag FilePath,
benchmarkVerbosity :: Flag Verbosity,
benchmarkOptions :: [PathTemplate]
} deriving (Generic)
defaultBenchmarkFlags :: BenchmarkFlags
defaultBenchmarkFlags = BenchmarkFlags {
benchmarkDistPref = NoFlag,
benchmarkVerbosity = Flag normal,
benchmarkOptions = []
}
benchmarkCommand :: CommandUI BenchmarkFlags
benchmarkCommand = CommandUI
{ commandName = "bench"
, commandSynopsis =
"Run all/specific benchmarks."
, commandDescription = Just $ \pname -> wrapText $
"If necessary (re)configures with `--enable-benchmarks` flag and"
++ " builds the benchmarks.\n"
++ "\n"
++ "Remember that the benchmarks' dependencies must be installed if"
++ " there are additional ones; e.g. with `" ++ pname
++ " install --only-dependencies --enable-benchmarks`.\n"
++ "\n"
++ "By defining UserHooks in a custom Setup.hs, the package can"
++ " define actions to be executed before and after running"
++ " benchmarks.\n"
, commandNotes = Nothing
, commandUsage = usageAlternatives "bench"
[ "[FLAGS]"
, "BENCHCOMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBenchmarkFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity benchmarkVerbosity
(\v flags -> flags { benchmarkVerbosity = v })
, optionDistPref
benchmarkDistPref (\d flags -> flags { benchmarkDistPref = d })
showOrParseArgs
, option [] ["benchmark-options"]
("give extra options to benchmark executables "
++ "(name templates can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATES" (map toPathTemplate . splitArgs)
(const []))
, option [] ["benchmark-option"]
("give extra option to benchmark executables "
++ "(no need to quote options containing spaces, "
++ "name template can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATE" (\x -> [toPathTemplate x])
(map fromPathTemplate))
]
}
emptyBenchmarkFlags :: BenchmarkFlags
emptyBenchmarkFlags = mempty
instance Monoid BenchmarkFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup BenchmarkFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Shared options utils
-- ------------------------------------------------------------
programFlagsDescription :: ProgramDb -> String
programFlagsDescription progDb =
"The flags --with-PROG and --PROG-option(s) can be used with"
++ " the following programs:"
++ (concatMap (\line -> "\n " ++ unwords line) . wrapLine 77 . sort)
[ programName prog | (prog, _) <- knownPrograms progDb ]
++ "\n"
-- | For each known program @PROG@ in 'progDb', produce a @with-PROG@
-- 'OptionField'.
programDbPaths
:: ProgramDb
-> ShowOrParseArgs
-> (flags -> [(String, FilePath)])
-> ([(String, FilePath)] -> (flags -> flags))
-> [OptionField flags]
programDbPaths progDb showOrParseArgs get set =
programDbPaths' ("with-" ++) progDb showOrParseArgs get set
{-# DEPRECATED programConfigurationPaths' "Use programDbPaths' instead" #-}
-- | Like 'programDbPaths', but allows to customise the option name.
programDbPaths', programConfigurationPaths'
:: (String -> String)
-> ProgramDb
-> ShowOrParseArgs
-> (flags -> [(String, FilePath)])
-> ([(String, FilePath)] -> (flags -> flags))
-> [OptionField flags]
programConfigurationPaths' = programDbPaths'
programDbPaths' mkName progDb showOrParseArgs get set =
case showOrParseArgs of
-- we don't want a verbose help text list so we just show a generic one:
ShowArgs -> [withProgramPath "PROG"]
ParseArgs -> map (withProgramPath . programName . fst)
(knownPrograms progDb)
where
withProgramPath prog =
option "" [mkName prog]
("give the path to " ++ prog)
get set
(reqArg' "PATH" (\path -> [(prog, path)])
(\progPaths -> [ path | (prog', path) <- progPaths, prog==prog' ]))
-- | For each known program @PROG@ in 'progDb', produce a @PROG-option@
-- 'OptionField'.
programDbOption
:: ProgramDb
-> ShowOrParseArgs
-> (flags -> [(String, [String])])
-> ([(String, [String])] -> (flags -> flags))
-> [OptionField flags]
programDbOption progDb showOrParseArgs get set =
case showOrParseArgs of
-- we don't want a verbose help text list so we just show a generic one:
ShowArgs -> [programOption "PROG"]
ParseArgs -> map (programOption . programName . fst)
(knownPrograms progDb)
where
programOption prog =
option "" [prog ++ "-option"]
("give an extra option to " ++ prog ++
" (no need to quote options containing spaces)")
get set
(reqArg' "OPT" (\arg -> [(prog, [arg])])
(\progArgs -> concat [ args
| (prog', args) <- progArgs, prog==prog' ]))
{-# DEPRECATED programConfigurationOptions "Use programDbOptions instead" #-}
-- | For each known program @PROG@ in 'progDb', produce a @PROG-options@
-- 'OptionField'.
programDbOptions, programConfigurationOptions
:: ProgramDb
-> ShowOrParseArgs
-> (flags -> [(String, [String])])
-> ([(String, [String])] -> (flags -> flags))
-> [OptionField flags]
programConfigurationOptions = programDbOptions
programDbOptions progDb showOrParseArgs get set =
case showOrParseArgs of
-- we don't want a verbose help text list so we just show a generic one:
ShowArgs -> [programOptions "PROG"]
ParseArgs -> map (programOptions . programName . fst)
(knownPrograms progDb)
where
programOptions prog =
option "" [prog ++ "-options"]
("give extra options to " ++ prog)
get set
(reqArg' "OPTS" (\args -> [(prog, splitArgs args)]) (const []))
-- ------------------------------------------------------------
-- * GetOpt Utils
-- ------------------------------------------------------------
boolOpt :: SFlags -> SFlags
-> MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a
boolOpt = Command.boolOpt flagToMaybe Flag
boolOpt' :: OptFlags -> OptFlags
-> MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a
boolOpt' = Command.boolOpt' flagToMaybe Flag
trueArg, falseArg :: MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a
trueArg sfT lfT = boolOpt' (sfT, lfT) ([], []) sfT lfT
falseArg sfF lfF = boolOpt' ([], []) (sfF, lfF) sfF lfF
reqArgFlag :: ArgPlaceHolder -> SFlags -> LFlags -> Description ->
(b -> Flag String) -> (Flag String -> b -> b) -> OptDescr b
reqArgFlag ad = reqArg ad (succeedReadE Flag) flagToList
optionDistPref :: (flags -> Flag FilePath)
-> (Flag FilePath -> flags -> flags)
-> ShowOrParseArgs
-> OptionField flags
optionDistPref get set = \showOrParseArgs ->
option "" (distPrefFlagName showOrParseArgs)
( "The directory where Cabal puts generated build files "
++ "(default " ++ defaultDistPref ++ ")")
get set
(reqArgFlag "DIR")
where
distPrefFlagName ShowArgs = ["builddir"]
distPrefFlagName ParseArgs = ["builddir", "distdir", "distpref"]
optionVerbosity :: (flags -> Flag Verbosity)
-> (Flag Verbosity -> flags -> flags)
-> OptionField flags
optionVerbosity get set =
option "v" ["verbose"]
"Control verbosity (n is 0--3, default verbosity level is 1)"
get set
(optArg "n" (fmap Flag flagToVerbosity)
(Flag verbose) -- default Value if no n is given
(fmap (Just . showForCabal) . flagToList))
optionNumJobs :: (flags -> Flag (Maybe Int))
-> (Flag (Maybe Int) -> flags -> flags)
-> OptionField flags
optionNumJobs get set =
option "j" ["jobs"]
"Run NUM jobs simultaneously (or '$ncpus' if no NUM is given)."
get set
(optArg "NUM" (fmap Flag numJobsParser)
(Flag Nothing)
(map (Just . maybe "$ncpus" show) . flagToList))
where
numJobsParser :: ReadE (Maybe Int)
numJobsParser = ReadE $ \s ->
case s of
"$ncpus" -> Right Nothing
_ -> case reads s of
[(n, "")]
| n < 1 -> Left "The number of jobs should be 1 or more."
| otherwise -> Right (Just n)
_ -> Left "The jobs value should be a number or '$ncpus'"
-- ------------------------------------------------------------
-- * Other Utils
-- ------------------------------------------------------------
readPToMaybe :: Parse.ReadP a a -> String -> Maybe a
readPToMaybe p str = listToMaybe [ r | (r,s) <- Parse.readP_to_S p str
, all isSpace s ]
-- | Arguments to pass to a @configure@ script, e.g. generated by
-- @autoconf@.
configureArgs :: Bool -> ConfigFlags -> [String]
configureArgs bcHack flags
= hc_flag
++ optFlag "with-hc-pkg" configHcPkg
++ optFlag' "prefix" prefix
++ optFlag' "bindir" bindir
++ optFlag' "libdir" libdir
++ optFlag' "libexecdir" libexecdir
++ optFlag' "datadir" datadir
++ optFlag' "sysconfdir" sysconfdir
++ configConfigureArgs flags
where
hc_flag = case (configHcFlavor flags, configHcPath flags) of
(_, Flag hc_path) -> [hc_flag_name ++ hc_path]
(Flag hc, NoFlag) -> [hc_flag_name ++ display hc]
(NoFlag,NoFlag) -> []
hc_flag_name
--TODO kill off thic bc hack when defaultUserHooks is removed.
| bcHack = "--with-hc="
| otherwise = "--with-compiler="
optFlag name config_field = case config_field flags of
Flag p -> ["--" ++ name ++ "=" ++ p]
NoFlag -> []
optFlag' name config_field = optFlag name (fmap fromPathTemplate
. config_field
. configInstallDirs)
configureCCompiler :: Verbosity -> ProgramDb
-> IO (FilePath, [String])
configureCCompiler verbosity progdb = configureProg verbosity progdb gccProgram
configureLinker :: Verbosity -> ProgramDb -> IO (FilePath, [String])
configureLinker verbosity progdb = configureProg verbosity progdb ldProgram
configureProg :: Verbosity -> ProgramDb -> Program
-> IO (FilePath, [String])
configureProg verbosity programDb prog = do
(p, _) <- requireProgram verbosity prog programDb
let pInv = programInvocation p []
return (progInvokePath pInv, progInvokeArgs pInv)
-- | Helper function to split a string into a list of arguments.
-- It's supposed to handle quoted things sensibly, eg:
--
-- > splitArgs "--foo=\"C:\Program Files\Bar\" --baz"
-- > = ["--foo=C:\Program Files\Bar", "--baz"]
--
splitArgs :: String -> [String]
splitArgs = space []
where
space :: String -> String -> [String]
space w [] = word w []
space w ( c :s)
| isSpace c = word w (space [] s)
space w ('"':s) = string w s
space w s = nonstring w s
string :: String -> String -> [String]
string w [] = word w []
string w ('"':s) = space w s
string w ( c :s) = string (c:w) s
nonstring :: String -> String -> [String]
nonstring w [] = word w []
nonstring w ('"':s) = string w s
nonstring w ( c :s) = space (c:w) s
word [] s = s
word w s = reverse w : s
-- The test cases kinda have to be rewritten from the ground up... :/
--hunitTests :: [Test]
--hunitTests =
-- let m = [("ghc", GHC), ("nhc98", NHC), ("hugs", Hugs)]
-- (flags, commands', unkFlags, ers)
-- = getOpt Permute options ["configure", "foobar", "--prefix=/foo", "--ghc", "--nhc98", "--hugs", "--with-compiler=/comp", "--unknown1", "--unknown2", "--install-prefix=/foo", "--user", "--global"]
-- in [TestLabel "very basic option parsing" $ TestList [
-- "getOpt flags" ~: "failed" ~:
-- [Prefix "/foo", GhcFlag, NhcFlag, HugsFlag,
-- WithCompiler "/comp", InstPrefix "/foo", UserFlag, GlobalFlag]
-- ~=? flags,
-- "getOpt commands" ~: "failed" ~: ["configure", "foobar"] ~=? commands',
-- "getOpt unknown opts" ~: "failed" ~:
-- ["--unknown1", "--unknown2"] ~=? unkFlags,
-- "getOpt errors" ~: "failed" ~: [] ~=? ers],
--
-- TestLabel "test location of various compilers" $ TestList
-- ["configure parsing for prefix and compiler flag" ~: "failed" ~:
-- (Right (ConfigCmd (Just comp, Nothing, Just "/usr/local"), []))
-- ~=? (parseArgs ["--prefix=/usr/local", "--"++name, "configure"])
-- | (name, comp) <- m],
--
-- TestLabel "find the package tool" $ TestList
-- ["configure parsing for prefix comp flag, withcompiler" ~: "failed" ~:
-- (Right (ConfigCmd (Just comp, Just "/foo/comp", Just "/usr/local"), []))
-- ~=? (parseArgs ["--prefix=/usr/local", "--"++name,
-- "--with-compiler=/foo/comp", "configure"])
-- | (name, comp) <- m],
--
-- TestLabel "simpler commands" $ TestList
-- [flag ~: "failed" ~: (Right (flagCmd, [])) ~=? (parseArgs [flag])
-- | (flag, flagCmd) <- [("build", BuildCmd),
-- ("install", InstallCmd Nothing False),
-- ("sdist", SDistCmd),
-- ("register", RegisterCmd False)]
-- ]
-- ]
{- Testing ideas:
* IO to look for hugs and hugs-pkg (which hugs, etc)
* quickCheck to test permutations of arguments
* what other options can we over-ride with a command-line flag?
-}
| sopvop/cabal | Cabal/Distribution/Simple/Setup.hs | bsd-3-clause | 86,958 | 0 | 47 | 23,247 | 17,601 | 9,888 | 7,713 | 1,650 | 10 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module Aws.SimpleDb.Model
where
import Aws.SimpleDb.Response
import Aws.Util
import Aws.Xml
import Control.Monad
import Text.XML.Cursor (($/), (&|))
import qualified Control.Failure as F
import qualified Data.ByteString as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Text.XML.Cursor as Cu
data Attribute a
= ForAttribute { attributeName :: T.Text, attributeData :: a }
deriving (Show)
readAttribute :: F.Failure XmlException m => Cu.Cursor -> m (Attribute T.Text)
readAttribute cursor = do
name <- forceM "Missing Name" $ cursor $/ Cu.laxElement "Name" &| decodeBase64
value <- forceM "Missing Value" $ cursor $/ Cu.laxElement "Value" &| decodeBase64
return $ ForAttribute name value
data SetAttribute
= SetAttribute { setAttribute :: T.Text, isReplaceAttribute :: Bool }
deriving (Show)
attributeQuery :: (a -> [(B.ByteString, B.ByteString)]) -> Attribute a -> [(B.ByteString, B.ByteString)]
attributeQuery f (ForAttribute name x) = ("Name", T.encodeUtf8 name) : f x
addAttribute :: T.Text -> T.Text -> Attribute SetAttribute
addAttribute name value = ForAttribute name (SetAttribute value False)
replaceAttribute :: T.Text -> T.Text -> Attribute SetAttribute
replaceAttribute name value = ForAttribute name (SetAttribute value True)
setAttributeQuery :: SetAttribute -> [(B.ByteString, B.ByteString)]
setAttributeQuery (SetAttribute value replace)
= ("Value", T.encodeUtf8 value) : [("Replace", awsTrue) | replace]
data DeleteAttribute
= DeleteAttribute
| ValuedDeleteAttribute { deleteAttributeValue :: T.Text }
deriving (Show)
deleteAttributeQuery :: DeleteAttribute -> [(B.ByteString, B.ByteString)]
deleteAttributeQuery DeleteAttribute = []
deleteAttributeQuery (ValuedDeleteAttribute value) = [("Value", T.encodeUtf8 value)]
data ExpectedAttribute
= ExpectedValue { expectedAttributeValue :: T.Text }
| ExpectedExists { expectedAttributeExists :: Bool }
deriving (Show)
expectedValue :: T.Text -> T.Text -> Attribute ExpectedAttribute
expectedValue name value = ForAttribute name (ExpectedValue value)
expectedExists :: T.Text -> Bool -> Attribute ExpectedAttribute
expectedExists name exists = ForAttribute name (ExpectedExists exists)
expectedAttributeQuery :: ExpectedAttribute -> [(B.ByteString, B.ByteString)]
expectedAttributeQuery (ExpectedValue value) = [("Value", T.encodeUtf8 value)]
expectedAttributeQuery (ExpectedExists exists) = [("Exists", awsBool exists)]
data Item a
= Item { itemName :: T.Text, itemData :: a }
deriving (Show)
readItem :: F.Failure XmlException m => Cu.Cursor -> m (Item [Attribute T.Text])
readItem cursor = do
name <- force "Missing Name" <=< sequence $ cursor $/ Cu.laxElement "Name" &| decodeBase64
attributes <- sequence $ cursor $/ Cu.laxElement "Attribute" &| readAttribute
return $ Item name attributes
itemQuery :: (a -> [(B.ByteString, B.ByteString)]) -> Item a -> [(B.ByteString, B.ByteString)]
itemQuery f (Item name x) = ("ItemName", T.encodeUtf8 name) : f x
| jgm/aws | Aws/SimpleDb/Model.hs | bsd-3-clause | 3,217 | 0 | 12 | 581 | 1,002 | 544 | 458 | 60 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
module Bertrand.Parser
(parse
)where
import Prelude hiding (null)
import Control.Applicative
import Control.Monad
-- import Control.Monad.Trans.Maybe
-- import Control.Monad.State
import Data.Char
import qualified Data.Map as M
import Data.Maybe
-- import Debug.Trace
import Bertrand.Data
import Bertrand.System (systemIds)
--------------------------------------------------------------------------------
-- type Parser a = MaybeT (State ParserState) a
-- runParser = runMaybeT
newtype Parser a = Parser {runParser :: ParserState -> (Maybe a, ParserState)}
instance Functor Parser where
f `fmap` p = Parser $ \s -> let (m, s') = runParser p s
in (f `fmap` m, s')
instance Applicative Parser where
pure = return
(<*>) = ap
instance Monad Parser where
return x = Parser $ \s -> (return x, s)
p >>= f = Parser $ \s -> let (m, s') = runParser p s
in maybe (empty, s) (\a -> runParser (f a) s') m
instance Alternative Parser where
empty = Parser $ \s -> (empty, s)
p <|> q = Parser $ \s -> let a@(m, s') = runParser p s
in maybe (runParser q s) (const a) m
instance MonadPlus Parser
get :: Parser ParserState
get = Parser $ \s -> (return s, s)
put :: ParserState -> Parser ()
put s = Parser $ const (return (), s)
data ParserState = ParserState (Int, Int) String
purePS :: String -> ParserState
purePS = ParserState (1, 1)
pop :: ParserState -> (Char, ParserState)
pop (ParserState (i, j) s) = case s of
[] -> ('\0', ParserState (i, j) s)
'\n':cs -> ('\n', ParserState (i + 1, j) cs)
c :cs -> (c, ParserState (i, j + 1) cs)
null :: ParserState -> Bool
null (ParserState _ s)
| s == "" = True
| otherwise = False
item :: Parser Char
item = do
s <- get
if null s
then mzero
else let (c, s') = pop s
in do
put s'
return c
sat :: (Char -> Bool) -> Parser Char
sat f = do
s <- get
c <- item
if f c
then return c
else do
put s
mzero
test :: Parser a -> Parser a
test p = do
s <- get
a <- p
put s
return a
notp :: Parser a -> Parser ()
notp p = Parser $ \s -> let (m, s') = runParser p s
in maybe (return (), s) (const (mzero, s)) m
eof :: Parser ()
eof = do
s <- get
unless (null s) mzero
--------------------------------------------------------------------------------
parse :: [ParseOption] -> Int -> String -> Either (Int, Int) Envir
parse os i cs = let (m, ParserState p _) = runParser (parser os i) (purePS cs)
in maybe (Left p) Right m
--------------------------------------------------------------------------------
type OpeParser = Parser Expr -> Parser Expr
parser :: [ParseOption] -> Int -> Parser Envir
parser ops i = emap (env $ i + 1) <$> statement <* eof
where
env :: Int -> Expr -> Expr
env i = \case
App a b -> App (env i a) (env i b)
Lambda a b -> Lambda (env (i + 1) a) (env (i + 1) b)
Env e a -> Env (emap (env $ i + 1) e {depth = i}) $ env (i + 1) a
a -> a
expr :: Parser Expr
expr = foldr id apply opeparsers
-- expr = apply $ head opeparsers $ term expr
statement :: Parser Envir
statement = variable
<|> constraint
-- <|> bind
<|> declare
variable :: Parser Envir
variable = (\s ss -> mempty{vars = case s of
"var" -> (ss, [])
"cons" -> ([], ss)}) <$>
oneof string ["var", "cons"] <*> some identifier'
constraint :: Parser Envir
constraint = (\ss e -> mempty{cstrs = M.fromList $ map (, [e]) ss,
decls = [(ss, e)]}) <$>
some identifier' <* sign "." <*> expr
-- bind :: Parser Envir
-- bind = (,) <$> expr <*> (sign "=" *> expr) >>= f
-- where
-- f (a, e) = let x:es = toList a in case detach x of
-- Id s -> return mempty{binds = M.singleton s [foldr Lambda e es]}
-- _ -> mzero
declare :: Parser Envir
declare = expr >>= f
where
f e = case toList e of
[a, b, c] | isName "=" a ->
let x:es = toList b
in case detach x of
Id s -> return mempty{binds =
M.singleton s [foldr Lambda c es]}
_ -> mzero
_ -> return mempty{decls = [([], e)]}
opeparsers :: [OpeParser]
opeparsers = envir : lambda : map opeparser opers
opers = operators ops
lambda :: OpeParser
lambda p = (f <$> (sign "\\" *> some term) <* sign "->" <*> p)
<|> p
where
f es e = foldr1 Lambda $ es ++ [e]
envir :: OpeParser
envir p = f <$> p <*> option (sign "!" *>
((:) <$> statement <*> many (sign ";" *> statement)))
where
f a Nothing = a
f a (Just es) = Env (mconcat es) a
apply :: Parser Expr
apply = foldl App <$> (term <|> operator) <*> many term
-- termop :: OpeParser
-- termop p = term <|> operator
term :: Parser Expr
term = sign "(" *> expr <* sign ")"
<|> App (Id "~") <$> (sign "~" *> term)
<|> list
<|> ifelse
<|> caseof
<|> float
<|> number
<|> systemId
<|> Id <$> (identifier <|> wildcard <|> sign "()")
signs :: [String]
signs = "!":";":"\\":"->":",":"if":"then":"else":"case":"of":
foldr (\(is, ils, irs, ifs) s -> is ++ ils ++ irs ++ ifs ++ s) [] opers
operator :: Parser Expr
operator = Id <$> oneof sign signs
identifier :: Parser String
identifier = token ((:) <$> (letter <|> char '#') <*>
many (letter <|> digit))
>>= \s -> if s `elem` signs
then mzero
else return s
identifier' :: Parser String
identifier' = token ((:) <$> (letter <|> char '#') <*>
many (letter <|> digit))
wildcard :: Parser String
wildcard = token ((:) <$> char '_' <*> many (letter <|> digit))
list :: Parser Expr
list = (makeList .) . (++) <$>
(sign "[" *> optionL expr) <*> many (sign "," *> expr) <* sign "]"
ifelse :: Parser Expr
ifelse = (\c a b -> App (App (App (Id "#if") c) a) b) <$>
(sign "if" *> expr) <*> (sign "then" *> expr) <*> (sign "else" *> expr)
caseof :: Parser Expr
caseof = (\e cs -> App (App (Id "comma") $ makeList cs) e) <$>
(sign "case" *> expr) <* sign "of" <*>
((:) <$> clause <*> many (sign ";" *> clause))
where
clause :: Parser Expr
clause = Lambda . foldr1 App <$> some term <* sign "->" <*> expr
makeList :: [Expr] -> Expr
makeList = foldr (app2 (Id ":")) (Id "[]")
operators :: [ParseOption] -> [([String], [String], [String], [String])]
operators = M.elems . foldr f M.empty
where
f :: ParseOption -> M.Map Int ([String], [String], [String], [String]) -> M.Map Int ([String], [String], [String], [String])
f (Infix i s) = M.insertWith (const $ map1st (s:)) i ([s], [], [], [])
f (Infixl i s) = M.insertWith (const $ map2nd (s:)) i ([], [s], [], [])
f (Infixr i s) = M.insertWith (const $ map3rd (s:)) i ([], [], [s], [])
f (Infixf i s) = M.insertWith (const $ map4th (s:)) i ([], [], [], [s])
map1st f (a, b, c, d) = (f a, b, c, d)
map2nd f (a, b, c, d) = (a, f b, c, d)
map3rd f (a, b, c, d) = (a, b, f c, d)
map4th f (a, b, c, d) = (a, b, c, f d)
-- infix infixl infixr infixf
opeparser :: ([String], [String], [String], [String]) -> OpeParser
opeparser (is, ils, irs, ifs) p = infixp $ infixlp $ infixrp $ infixfp p
where
infixp :: OpeParser
infixp p = f <$> p <*> option ((,) <$> oper is <*> option p)
where
f a Nothing = a
f a (Just (o, Nothing)) = App o a
f a (Just (o, Just b)) = App (App o a) b
infixlp :: OpeParser
infixlp p = f <$> g
where
f :: [Expr] -> Expr
f [a] = a
f [a, o] = App o a
f (a:o:b:x) = f $ App (App o a) b : x
g :: Parser [Expr]
g = (:) <$> p <*> (concat <$> optionL ((:) <$> oper ils <*> (concat <$> optionL g)))
infixrp :: OpeParser
infixrp p = f <$> p <*> option ((,) <$> oper irs <*> option (infixrp p))
where
f a Nothing = a
f a (Just (o, Nothing)) = App o a
f a (Just (o, Just b)) = App (App o a) b
infixfp :: OpeParser
infixfp p = f <$> g
where
f :: [Expr] -> Expr
f [a] = a
f [a, o] = App o a
f [a, o, b] = App (App o a) b
f (a:o:b:x) = App (App (Id "and") $ f [a, o, b]) $ f (b:x)
g :: Parser [Expr]
g = (:) <$> p <*> (concat <$> optionL ((:) <$> oper ifs <*> g))
oper s = Id <$> oneof sign s <* notp symbol
systemId :: Parser Expr
systemId = token (char '#' *> many letter) >>=
(\s -> maybe mzero return $ System <$> lookup s systemIds)
float :: Parser Expr
float = token (toFraction <$> some digit <* char '.' <*> some digit)
where
toFraction xs ys = app2 (Id "/") (System . Int . read $ xs ++ ys)
(System . Int $ 10 ^ length ys)
number :: Parser Expr
number = System . Int . read <$> token (some digit)
sign :: String -> Parser String
sign s = token $ string s
token :: Parser a -> Parser a
token p = spaces *> p <* spaces
digit :: Parser Char
digit = sat isDigit
letter :: Parser Char
letter = sat isLetter
upper :: Parser Char
upper = sat isUpper
symbol :: Parser Char
symbol = oneof char "!$%&*+./<=>?@\\^|-~:"
spaces :: Parser String
spaces = many space
space :: Parser Char
space = sat isSeparator
string :: String -> Parser String
string "" = return ""
string (c : "") = (:[]) <$> char c
string (c : cs) = (:) <$> char c <*> string cs
char :: Char -> Parser Char
char c = sat (c ==)
option :: Parser a -> Parser (Maybe a)
option p = (Just <$> p) <|> return Nothing
optionL :: Parser a -> Parser [a]
optionL p = maybeToList <$> option p
oneof :: (a -> Parser b) -> [a] -> Parser b
oneof p = foldl (\q a -> q <|> p a) mzero
app2 :: Expr -> Expr -> Expr -> Expr
app2 a b = App (App a b)
-- or :: (a -> Bool) -> (a -> Bool) -> a -> Bool
-- f `or` g = \a -> f a || g a
| fujiy00/bertrand | src/Bertrand/Parser.hs | bsd-3-clause | 11,294 | 1 | 22 | 4,243 | 4,537 | 2,380 | 2,157 | 246 | 10 |
module Generate.Functions where
import Data.Char
import Data.Maybe
import Control.Applicative
import Control.Exception(assert)
import Data.XCB
import HaskellCombinators
import Generate(valueParamName,mapAlt,xImport,mapIdents,fieldName,fieldType)
import Generate.Monad
import Generate.Facts
import Generate.Util
import Control.Monad.Reader
import Control.Monad.Trans.Maybe
-- Builds a function for every request in the module
-- Hopefully I'm not duplicating too much between here
-- and the types generation module.
-- | Returns the name of the Haskell module containing the type
-- declarations for a given XCB module.
typesModName :: GenXHeader a -> String
typesModName = typesModuleName . interCapsName
-- | Returns the name of the Haskell module containing the function
-- definitions for a given XCB module.
functionsModName :: GenXHeader a -> String
functionsModName = functionsModuleName . interCapsName
-- | Returns the name of an X module in InterCaps.
interCapsName :: GenXHeader a -> String
interCapsName xhd = case xheader_name xhd of
Nothing -> ensureUpper $ xheader_header xhd
Just name -> name
ensureLower [] = []
ensureLower (x:xs) = toLower x : xs
-- | Given a list of X modules, returns a list of generated Haskell modules
-- which contain the developer friendly functions for using XHB.
functionsModules :: [XHeader] -> [HsModule]
functionsModules xs = map go transed
where transed = standardTranslations xs
go :: HXHeader -> HsModule
go xhd = functionsModule transed xhd
-- | Generates the Haskell functions for using the functionality
-- of the passed in X module.
functionsModule :: [HXHeader] -> HXHeader -> HsModule
functionsModule xs xhd | isCoreModule xhd = buildCore xhd
| otherwise = buildExtension xs xhd
-- | Retuns 'True' if the X module is NOT for an extension.
isCoreModule = isNothing . xheader_xname
buildExtension :: [HXHeader] -> HXHeader -> HsModule
buildExtension xs xhd =
let emptyModule = newExtensionModule xhd
rs = requests xhd
fns = declareFunctions xhd rs
extId = declareExtensionId xhd
imFns = doImports xs xhd
in moveExports $ applyMany (extId ++ fns ++ imFns) emptyModule
declareExtensionId :: HXHeader -> [HsModule -> HsModule]
declareExtensionId xhd =
[addDecl $ mkTypeSig extFnName [] (mkTyCon "ExtensionId")
,addDecl $ mkSimpleFun extFnName [] $
mkStringLit $ fromJust $ xheader_xname xhd
,addExport $ mkExportVar extFnName
]
where extFnName = "extension"
doImports :: [HXHeader] -> HXHeader -> [HsModule -> HsModule]
doImports xs xhd =
let decs = xheader_decls xhd
in mapMaybe go decs
where go :: HXDecl -> Maybe (HsModule -> HsModule)
go (XImport name) = return $ xImport xs xhd name
go _ = Nothing
-- | Builds a haskel functions module for the passed in xml
-- description. Assumes it is not for extension requests.
buildCore :: HXHeader -> HsModule
buildCore xhd =
let emptyModule = newCoreModule xhd
rs = requests xhd
fns = declareFunctions xhd rs
in moveExports $ applyMany fns emptyModule
-- | moves entire-module exports to end of export list
moveExports :: HsModule -> HsModule
moveExports =
modifyExports $ \exports ->
let (modExports, otherExports) = filterAccum isModExport exports
in otherExports ++ modExports
modifyExports f mod =
case getExports mod of
Nothing -> mod
(Just exs) -> setExports (Just $ f exs) mod
applyMany = foldr (flip (.)) id
-- Creates a nearly empty Haskell module for the passed-in
-- X module. Also inserts standard Haskell imports.
newCoreModule :: HXHeader -> HsModule
newCoreModule xhd =
let name = functionsModName xhd
mod = mkModule name
in exportTypesMod xhd $ doQualImports $ doImports mod
where doImports = applyMany $ map (addImport . mkImport) $
[typesModName xhd
, packagePrefix ++ ".Connection.Internal"
, packagePrefix ++ ".Shared"
,"Data.Binary.Put"
,"Control.Concurrent.STM"
,"Foreign.C.Types"
,"Data.Word"
,"Data.Int"
,"Data.Binary.Get"
]
doQualImports = addImport $ mkQualImport $
packagePrefix ++ ".Connection.Types"
newExtensionModule :: HXHeader -> HsModule
newExtensionModule xhd =
let name = functionsModName xhd
mod = mkModule name
in exportTypesMod xhd $ doHidingImports $ doSomeImports $ doImports mod
where doImports = applyMany $ map (addImport . mkImport) $
[typesModName xhd
, packagePrefix ++ ".Connection.Internal"
, packagePrefix ++ ".Connection.Extension"
, packagePrefix ++ ".Connection.Types"
, "Control.Concurrent.STM"
, "Foreign.C.Types"
, "Data.Word"
, "Data.Int"
, "Data.Binary.Get"
]
doSomeImports = addImport $ mkSomeImport "Data.Binary.Put" ["runPut"]
doHidingImports = addImport $ mkHidingImport (packagePrefix ++ ".Shared") ["Event", "Error"]
exportTypesMod = addExport . mkExportModule . typesModName
connTyName = packagePrefix ++ ".Connection.Types.Connection"
makeReceipt :: RequestInfo -> [HsStmt]
makeReceipt req
| not (hasReply req) = empty
| unaryReply req = return $ mkBinding $
hsApp (mkVar "newEmptyReceipt") $ hsParen $
hsApp (mkVar "runGet") $ hsParen $
hsInfixApp (mkVar unaryReplyAccessorName)
(mkQOpIdent "fmap")
(mkVar "deserialize")
| otherwise = return $ mkBinding $
mkVar "newDeserReceipt"
where
mkBinding = mkGenerator (hsPTuple [mkPVar "receipt", mkPVar "rReceipt"])
unaryReplyAccessorName = accessor elemName name
where name = replyName (request_name req)
elemName = maybe (error $ "Failure in mkReceiptForReply! " ++ show req) id $
firstReplyElem req >>= fieldName
-- send rReceipt, bu still return receipt
sendRequest :: RequestInfo -> [HsStmt]
sendRequest req | hasReply req = map hsQualifier
[foldl1 hsApp $ map mkVar $
["sendRequestWithReply"
,"c"
,"chunk"
,"rReceipt"
]
,mkVar "return" `hsApp` mkVar "receipt"
]
| otherwise = map hsQualifier $
return $ (mkVar "sendRequest" `hsApp` mkVar "c")
`hsApp` mkVar "chunk"
-- account for unary/nullary reply case
resultType :: RequestInfo -> HsType
resultType req | unaryReply req =
receiptType $ fromJust $ fieldType $ fromJust $ firstReplyElem req
| hasReply req = receiptType $ replyType req
| otherwise = foldr1 hsTyApp $
[mkTyCon "IO"
,unit_tycon
]
receiptType :: HsType -> HsType
receiptType typ = foldr1 hsTyApp $
[mkTyCon "IO"
,mkTyCon "Receipt"
,typ]
replyType :: RequestInfo -> HsType
replyType = mkTyCon . replyNameFromInfo
-- | Declares Haskell functions for an X module.
declareFunctions :: HXHeader -> [RequestInfo] -> [HsModule -> HsModule]
declareFunctions xhd rInfos =
map (declareFunction (not $ isCoreModule xhd)) rInfos
-- for core requests, we can do the short form and long form
-- because we don't have to import any other modules
-- | Handles a single request in the core functions module.
declareFunction :: Bool -> RequestInfo -> (HsModule -> HsModule)
declareFunction ext req =
applyMany
[addDecl typDeclaration
,addDecl fnDeclaration
,addExport $ mkExportAbs fnName
]
where fnName = fnNameFromRequest req
fields = requestFields req
fieldCount = length fields
bigCount = 3
shortMode = fieldCount < bigCount
typDeclaration :: HsDecl
typDeclaration | shortMode = shortTypDec
| otherwise = longTypDec
fnDeclaration :: HsDecl
fnDeclaration | shortMode = shortFnDec
| otherwise = longFnDec
shortTypDec, longTypDec :: HsDecl
shortTypDec = mkTypeSig fnName [] shortTyp
longTypDec = mkTypeSig fnName [] longType
shortTyp =
let fieldTypes = fieldsToTypes fields
in foldr1 hsTyFun $
mkTyCon connTyName : fieldTypes ++ [resultType req]
longType =
foldr1 hsTyFun $
[mkTyCon connTyName
,mkTyCon $ request_name req
,resultType req
]
shortFnDec = mkSimpleFun fnName
(map mkPVar shortArgs)
(hsDo fnBody)
longFnDec = mkSimpleFun fnName
(map mkPVar ["c", "req"])
(hsDo fnBody)
shortArgs = "c" : fieldsToArgNames fields
-- constructor plus args
shortRequestExpr :: HsExp
shortRequestExpr =
foldl1 hsApp $ constructor : map mkVar (fieldsToArgNames fields)
-- TODO: share constructor name between
-- generation condebases.
constructor :: HsExp
constructor = hsCon . mkUnQName $ "Mk" ++ request_name req
fnBody :: [HsStmt]
fnBody = concat
[ makeReceipt req
, buildRequest
, serializeRequest
, sendRequest req
]
buildRequest | shortMode = return $ mkLetStmt
(mkPVar "req")
shortRequestExpr
| otherwise = empty
serializeRequest
| ext = [ mkGenerator (mkPVar "putAction")
(foldl1 hsApp $ map mkVar $
["serializeExtensionRequest"
,"c"
,"req"
]
)
, mkLetStmt (mkPVar "chunk")
(mkVar "runPut" `hsApp` mkVar "putAction")
]
| otherwise = [mkLetStmt (mkPVar "chunk")
(applyManyExp
[mkVar "runPut"
,mkVar "serialize" `hsApp` mkVar "req"
])
]
-- | Fold Haskell expressions together in a right-fold fashion
applyManyExp [] = undefined
applyManyExp [x] = x
applyManyExp (x:xs) = hsApp x $ hsParen $ applyManyExp xs
-- | Maps the fields of a X-struct into argument names to be used
-- in an arg-list for a Haskell function
fieldsToArgNames :: [HStructElem] -> [String]
fieldsToArgNames = map mapIdents . mapMaybe fieldToArgName
fieldToArgName :: HStructElem -> Maybe String
fieldToArgName = fieldName
-- | The types corresponding to the args from "fieldsToArgNames".
fieldsToTypes :: [HStructElem] -> [HsType]
fieldsToTypes = mapMaybe fieldType
-- | Extracts the requests from an X module.
requests :: HXHeader -> [RequestInfo]
requests = mapMaybe go . xheader_decls
where go (XRequest name code elems reply) = return $
RequestInfo name code elems reply
go _ = empty
data RequestInfo = RequestInfo
{request_name :: Name
,request_code :: Int
,request_elems :: [HStructElem]
,request_reply :: Maybe HXReply
} deriving Show
-- | Extracts only the fields in a request that must be specified
-- by the library end-user. That is, padding and such is excluded.
requestFields :: RequestInfo -> [HStructElem]
requestFields = filter go . request_elems
where go List{} = True
go SField{} = True
go ValueParam{} = True
go _ = False
-- | Returns true if a request has a reply
hasReply :: RequestInfo -> Bool
hasReply = not . isNothing . request_reply
-- | Return true if the reply is a unary reply - as in, has
-- on one element
unaryReply :: RequestInfo -> Bool
unaryReply RequestInfo{request_reply = Just xs}
= 1 == length (filter interestingField xs)
unaryReply _ = False
-- | Returns the first StructElem in the reply, if there is
-- one.
firstReplyElem :: RequestInfo -> Maybe HStructElem
firstReplyElem = listToMaybe . filter interestingField
. maybe [] id . request_reply
interestingField :: GenStructElem a -> Bool
interestingField Pad{} = False
interestingField ExprField{} = False
interestingField _ = True
-- | For a request, returns what the end-user Haskell function
-- is to be named
fnNameFromRequest :: RequestInfo -> String
fnNameFromRequest = ensureLower . request_name
-- | For a request, returns the name of the Haskell type constructor
-- corresponding to its reply.
replyNameFromInfo :: RequestInfo -> String
replyNameFromInfo req = assert (hasReply req) $
replyName $ request_name req
| aslatter/xhb | build-utils/src/Generate/Functions.hs | bsd-3-clause | 13,073 | 0 | 14 | 3,958 | 2,811 | 1,458 | 1,353 | 257 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
module Game.Monsters.MTank where
import Control.Lens (use, preuse, ix, zoom, (^.), (.=), (%=), (&), (.~), (%~))
import Control.Monad (void, when, unless, liftM)
import Data.Bits ((.&.), (.|.), complement)
import Linear (V3(..), normalize)
import qualified Data.Vector as V
import {-# SOURCE #-} Game.GameImportT
import Game.LevelLocalsT
import Game.GameLocalsT
import Game.CVarT
import Game.SpawnTempT
import Game.EntityStateT
import Game.EdictT
import Game.MMoveT
import Game.GClientT
import Game.MoveInfoT
import Game.ClientPersistantT
import Game.ClientRespawnT
import Game.MonsterInfoT
import Game.PlayerStateT
import Types
import QuakeRef
import QuakeState
import CVarVariables
import Game.Adapters
import qualified Constants
import qualified Game.GameAI as GameAI
import qualified Game.GameMisc as GameMisc
import qualified Game.GameUtil as GameUtil
import qualified Game.Monster as Monster
import qualified Game.Monsters.MFlash as MFlash
import qualified Util.Lib as Lib
import qualified Util.Math3D as Math3D
frameStand01 :: Int
frameStand01 = 0
frameStand30 :: Int
frameStand30 = 29
frameWalk01 :: Int
frameWalk01 = 30
frameWalk04 :: Int
frameWalk04 = 33
frameWalk05 :: Int
frameWalk05 = 34
frameWalk20 :: Int
frameWalk20 = 49
frameWalk21 :: Int
frameWalk21 = 50
frameWalk25 :: Int
frameWalk25 = 54
frameAttack101 :: Int
frameAttack101 = 55
frameAttack110 :: Int
frameAttack110 = 64
frameAttack111 :: Int
frameAttack111 = 65
frameAttack113 :: Int
frameAttack113 = 67
frameAttack116 :: Int
frameAttack116 = 70
frameAttack117 :: Int
frameAttack117 = 71
frameAttack122 :: Int
frameAttack122 = 76
frameAttack201 :: Int
frameAttack201 = 77
frameAttack238 :: Int
frameAttack238 = 114
frameAttack301 :: Int
frameAttack301 = 115
frameAttack321 :: Int
frameAttack321 = 135
frameAttack322 :: Int
frameAttack322 = 136
frameAttack324 :: Int
frameAttack324 = 138
frameAttack327 :: Int
frameAttack327 = 141
frameAttack330 :: Int
frameAttack330 = 144
frameAttack331 :: Int
frameAttack331 = 145
frameAttack353 :: Int
frameAttack353 = 167
frameAttack401 :: Int
frameAttack401 = 168
frameAttack429 :: Int
frameAttack429 = 196
framePain101 :: Int
framePain101 = 197
framePain104 :: Int
framePain104 = 200
framePain201 :: Int
framePain201 = 201
framePain205 :: Int
framePain205 = 205
framePain301 :: Int
framePain301 = 206
framePain316 :: Int
framePain316 = 221
frameDeath101 :: Int
frameDeath101 = 222
frameDeath132 :: Int
frameDeath132 = 253
tankSight :: EntInteract
tankSight =
GenericEntInteract "tank_sight" $ \selfRef _ -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundSight <- use $ mTankGlobals.mTankSoundSight
sound (Just selfRef) Constants.chanVoice soundSight 1 Constants.attnNorm 0
return True
tankFootStep :: EntThink
tankFootStep =
GenericEntThink "tank_footstep" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundStep <- use $ mTankGlobals.mTankSoundStep
sound (Just selfRef) Constants.chanBody soundStep 1 Constants.attnNorm 0
return True
tankThud :: EntThink
tankThud =
GenericEntThink "tank_thud" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundThud <- use $ mTankGlobals.mTankSoundThud
sound (Just selfRef) Constants.chanBody soundThud 1 Constants.attnNorm 0
return True
tankWindUp :: EntThink
tankWindUp =
GenericEntThink "tank_windup" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundWindUp <- use $ mTankGlobals.mTankSoundWindUp
sound (Just selfRef) Constants.chanWeapon soundWindUp 1 Constants.attnNorm 0
return True
tankIdle :: EntThink
tankIdle =
GenericEntThink "tank_idle" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundIdle <- use $ mTankGlobals.mTankSoundIdle
sound (Just selfRef) Constants.chanVoice soundIdle 1 Constants.attnIdle 0
return True
tankFramesStand :: V.Vector MFrameT
tankFramesStand =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
tankMoveStand :: MMoveT
tankMoveStand = MMoveT "tankMoveStand" frameStand01 frameStand30 tankFramesStand Nothing
tankStand :: EntThink
tankStand =
GenericEntThink "tank_stand" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just tankMoveStand)
return True
tankRun :: EntThink
tankRun =
GenericEntThink "tank_run" $ \selfRef -> do
self <- readRef selfRef
case self^.eEnemy of
Nothing ->
modifyRef selfRef (\v -> v & eMonsterInfo.miAIFlags %~ (.&. (complement Constants.aiBrutal)))
Just enemyRef -> do
enemy <- readRef enemyRef
case enemy^.eClient of
Nothing -> modifyRef selfRef (\v -> v & eMonsterInfo.miAIFlags %~ (.&. (complement Constants.aiBrutal)))
Just _ -> modifyRef selfRef (\v -> v & eMonsterInfo.miAIFlags %~ (.|. Constants.aiBrutal))
self' <- readRef selfRef
if (self'^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0
then do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just tankMoveStand)
else do
let currentMove = case self'^.eMonsterInfo.miCurrentMove of
Nothing -> tankMoveStartRun
Just move -> if (move^.mmId) == "tankMoveWalk" || (move^.mmId) == "tankMoveStartRun"
then tankMoveRun
else tankMoveStartRun
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just currentMove)
return True
tankWalk :: EntThink
tankWalk =
GenericEntThink "tank_walk" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just tankMoveWalk)
return True
tankFramesStartWalk :: V.Vector MFrameT
tankFramesStartWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 0 Nothing
, MFrameT (Just GameAI.aiWalk) 6 Nothing
, MFrameT (Just GameAI.aiWalk) 6 Nothing
, MFrameT (Just GameAI.aiWalk) 11 (Just tankFootStep)
]
tankMoveStartWalk :: MMoveT
tankMoveStartWalk = MMoveT "tankMoveStartWalk" frameWalk01 frameWalk04 tankFramesStartWalk (Just tankWalk)
tankFramesWalk :: V.Vector MFrameT
tankFramesWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 4 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 3 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 4 Nothing
, MFrameT (Just GameAI.aiWalk) 4 (Just tankFootStep)
, MFrameT (Just GameAI.aiWalk) 3 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 4 Nothing
, MFrameT (Just GameAI.aiWalk) 5 Nothing
, MFrameT (Just GameAI.aiWalk) 7 Nothing
, MFrameT (Just GameAI.aiWalk) 7 Nothing
, MFrameT (Just GameAI.aiWalk) 6 Nothing
, MFrameT (Just GameAI.aiWalk) 6 (Just tankFootStep)
]
tankMoveWalk :: MMoveT
tankMoveWalk = MMoveT "tankMoveWalk" frameWalk05 frameWalk20 tankFramesWalk Nothing
tankFramesStopWalk :: V.Vector MFrameT
tankFramesStopWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 3 Nothing
, MFrameT (Just GameAI.aiWalk) 3 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 4 (Just tankFootStep)
]
tankMoveStopWalk :: MMoveT
tankMoveStopWalk = MMoveT "tankMoveStopWalk" frameWalk21 frameWalk25 tankFramesStopWalk (Just tankStand)
tankFramesStartRun :: V.Vector MFrameT
tankFramesStartRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 0 Nothing
, MFrameT (Just GameAI.aiRun) 6 Nothing
, MFrameT (Just GameAI.aiRun) 6 Nothing
, MFrameT (Just GameAI.aiRun) 11 (Just tankFootStep)
]
tankMoveStartRun :: MMoveT
tankMoveStartRun = MMoveT "tankMoveStartRun" frameWalk01 frameWalk04 tankFramesStartRun (Just tankRun)
tankFramesRun :: V.Vector MFrameT
tankFramesRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 4 Nothing
, MFrameT (Just GameAI.aiRun) 5 Nothing
, MFrameT (Just GameAI.aiRun) 3 Nothing
, MFrameT (Just GameAI.aiRun) 2 Nothing
, MFrameT (Just GameAI.aiRun) 5 Nothing
, MFrameT (Just GameAI.aiRun) 5 Nothing
, MFrameT (Just GameAI.aiRun) 4 Nothing
, MFrameT (Just GameAI.aiRun) 4 (Just tankFootStep)
, MFrameT (Just GameAI.aiRun) 3 Nothing
, MFrameT (Just GameAI.aiRun) 5 Nothing
, MFrameT (Just GameAI.aiRun) 4 Nothing
, MFrameT (Just GameAI.aiRun) 5 Nothing
, MFrameT (Just GameAI.aiRun) 7 Nothing
, MFrameT (Just GameAI.aiRun) 7 Nothing
, MFrameT (Just GameAI.aiRun) 6 Nothing
, MFrameT (Just GameAI.aiRun) 6 (Just tankFootStep)
]
tankMoveRun :: MMoveT
tankMoveRun = MMoveT "tankMoveRun" frameWalk05 frameWalk20 tankFramesRun Nothing
tankFramesStopRun :: V.Vector MFrameT
tankFramesStopRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 3 Nothing
, MFrameT (Just GameAI.aiRun) 3 Nothing
, MFrameT (Just GameAI.aiRun) 2 Nothing
, MFrameT (Just GameAI.aiRun) 2 Nothing
, MFrameT (Just GameAI.aiRun) 4 (Just tankFootStep)
]
tankMoveStopRun :: MMoveT
tankMoveStopRun = MMoveT "tankMoveStopRun" frameWalk21 frameWalk25 tankFramesStopRun (Just tankWalk)
tankFramesPain1 :: V.Vector MFrameT
tankFramesPain1 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
tankMovePain1 :: MMoveT
tankMovePain1 = MMoveT "tankMovePain1" framePain101 framePain104 tankFramesPain1 (Just tankRun)
tankFramesPain2 :: V.Vector MFrameT
tankFramesPain2 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
tankMovePain2 :: MMoveT
tankMovePain2 = MMoveT "tankMovePain2" framePain201 framePain205 tankFramesPain2 (Just tankRun)
tankFramesPain3 :: V.Vector MFrameT
tankFramesPain3 =
V.fromList [ MFrameT (Just GameAI.aiMove) (-7) Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 3 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 (Just tankFootStep)
]
tankMovePain3 :: MMoveT
tankMovePain3 = MMoveT "tankMovePain3" framePain301 framePain316 tankFramesPain3 (Just tankRun)
tankPain :: EntPain
tankPain =
GenericEntPain "tank_pain" $ \selfRef _ _ damage -> do
self <- readRef selfRef
when ((self^.eHealth) < (self^.eMaxHealth) `div` 2) $
modifyRef selfRef (\v -> v & eEntityState.esSkinNum .~ 1)
levelTime <- use $ gameBaseGlobals.gbLevel.llTime
r <- Lib.randomF
let done = if damage <= 10 || levelTime < (self^.ePainDebounceTime) || damage <= 30 && r > 0.2
then True
else False
unless done $ do
-- If hard or nightmare, don't go into pain while attacking
skillValue <- liftM (^.cvValue) skillCVar
let frame = self^.eEntityState.esFrame
skip = if skillValue >= 2 && (frame >= frameAttack301 && frame <= frameAttack330 || frame >= frameAttack101 && frame <= frameAttack116)
then True
else False
unless skip $ do
modifyRef selfRef (\v -> v & ePainDebounceTime .~ levelTime + 3)
soundPain <- use $ mTankGlobals.mTankSoundPain
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanVoice soundPain 1 Constants.attnNorm 0
unless (skillValue == 3) $ do -- no pain anims in nightmare
let currentMove = if | damage <= 30 -> tankMovePain1
| damage <= 60 -> tankMovePain2
| otherwise -> tankMovePain3
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just currentMove)
tankBlaster :: EntThink
tankBlaster =
GenericEntThink "TankBlaster" $ \selfRef -> do
self <- readRef selfRef
let flashNumber = if | (self^.eEntityState.esFrame) == frameAttack110 -> Constants.mz2TankBlaster1
| (self^.eEntityState.esFrame) == frameAttack113 -> Constants.mz2TankBlaster2
| otherwise -> Constants.mz2TankBlaster3
(Just forward, Just right, _) = Math3D.angleVectors (self^.eEntityState.esAngles) True True False
start = Math3D.projectSource (self^.eEntityState.esOrigin) (MFlash.monsterFlashOffset V.! flashNumber) forward right
Just enemyRef = self^.eEnemy
enemy <- readRef enemyRef
let V3 a b c = enemy^.eEntityState.esOrigin
end = V3 a b (c + fromIntegral (enemy^.eViewHeight))
dir = end - start
Monster.monsterFireBlaster selfRef start dir 30 800 flashNumber Constants.efBlaster
return True
tankStrike :: EntThink
tankStrike =
GenericEntThink "TankStrike" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundStrike <- use $ mTankGlobals.mTankSoundStrike
sound (Just selfRef) Constants.chanWeapon soundStrike 1 Constants.attnNorm 0
return True
tankRocket :: EntThink
tankRocket =
GenericEntThink "TankRocket" $ \selfRef -> do
self <- readRef selfRef
let flashNumber = if | (self^.eEntityState.esFrame) == frameAttack324 -> Constants.mz2TankRocket1
| (self^.eEntityState.esFrame) == frameAttack327 -> Constants.mz2TankRocket2
| otherwise -> Constants.mz2TankRocket3
(Just forward, Just right, _) = Math3D.angleVectors (self^.eEntityState.esAngles) True True False
start = Math3D.projectSource (self^.eEntityState.esOrigin) (MFlash.monsterFlashOffset V.! flashNumber) forward right
Just enemyRef = self^.eEnemy
enemy <- readRef enemyRef
let V3 a b c = enemy^.eEntityState.esOrigin
vec = V3 a b (c + fromIntegral (enemy^.eViewHeight))
dir = normalize (vec - start)
Monster.monsterFireRocket selfRef start dir 50 550 flashNumber
return True
tankMachineGun :: EntThink
tankMachineGun =
GenericEntThink "TankMachineGun" $ \_ -> do
io (putStrLn "MTank.tankMachineGun") >> undefined -- TODO
tankReAttackBlaster :: EntThink
tankReAttackBlaster =
GenericEntThink "tank_reattack_blaster" $ \_ -> do
io (putStrLn "MTank.tankReAttackBlaster") >> undefined -- TODO
tankFramesAttackBlast :: V.Vector MFrameT
tankFramesAttackBlast =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-1) Nothing
, MFrameT (Just GameAI.aiCharge) (-2) Nothing
, MFrameT (Just GameAI.aiCharge) (-1) Nothing
, MFrameT (Just GameAI.aiCharge) (-1) Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just tankBlaster) -- 10
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just tankBlaster)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just tankBlaster) -- 16
]
tankMoveAttackBlast :: MMoveT
tankMoveAttackBlast = MMoveT "tankMoveAttackBlast" frameAttack101 frameAttack116 tankFramesAttackBlast (Just tankReAttackBlaster)
tankFramesReAttackBlast :: V.Vector MFrameT
tankFramesReAttackBlast =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just tankBlaster)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just tankBlaster) -- 16
]
tankMoveReAttackBlast :: MMoveT
tankMoveReAttackBlast = MMoveT "tankMoveReAttackBlast" frameAttack111 frameAttack116 tankFramesReAttackBlast (Just tankReAttackBlaster)
tankFramesAttackPostBlast :: V.Vector MFrameT
tankFramesAttackPostBlast =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing -- 17
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 3 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) (-2) (Just tankFootStep) -- 22
]
tankMoveAttackPostBlast :: MMoveT
tankMoveAttackPostBlast = MMoveT "tankMoveAttackPostBlast" frameAttack117 frameAttack122 tankFramesAttackPostBlast (Just tankRun)
tankPostStrike :: EntThink
tankPostStrike =
GenericEntThink "tank_poststrike" $ \selfRef -> do
modifyRef selfRef (\v -> v & eEnemy .~ Nothing)
void $ think tankRun selfRef
return True
tankDoAttackRocket :: EntThink
tankDoAttackRocket =
GenericEntThink "tank_doattack_rocket" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just tankMoveAttackFireRocket)
return True
tankReFireRocket :: EntThink
tankReFireRocket =
GenericEntThink "tank_refire_rocket" $ \_ -> do
io (putStrLn "MTank.tankReFireRocket") >> undefined -- TODO
tankFramesAttackStrike :: V.Vector MFrameT
tankFramesAttackStrike =
V.fromList [ MFrameT (Just GameAI.aiMove) 3 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) 6 Nothing
, MFrameT (Just GameAI.aiMove) 7 Nothing
, MFrameT (Just GameAI.aiMove) 9 (Just tankFootStep)
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 2 (Just tankFootStep)
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) 0 (Just tankWindUp)
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 (Just tankStrike)
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-1) Nothing
, MFrameT (Just GameAI.aiMove) (-1) Nothing
, MFrameT (Just GameAI.aiMove) (-1) Nothing
, MFrameT (Just GameAI.aiMove) (-1) Nothing
, MFrameT (Just GameAI.aiMove) (-1) Nothing
, MFrameT (Just GameAI.aiMove) (-3) Nothing
, MFrameT (Just GameAI.aiMove) (-10) Nothing
, MFrameT (Just GameAI.aiMove) (-10) Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) (-3) Nothing
, MFrameT (Just GameAI.aiMove) (-2) (Just tankFootStep)
]
tankMoveAttackStrike :: MMoveT
tankMoveAttackStrike = MMoveT "tankMoveAttackStrike" frameAttack201 frameAttack238 tankFramesAttackStrike (Just tankPostStrike)
tankFramesAttackPreRocket :: V.Vector MFrameT
tankFramesAttackPreRocket =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- 10
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 1 Nothing
, MFrameT (Just GameAI.aiCharge) 2 Nothing
, MFrameT (Just GameAI.aiCharge) 7 Nothing
, MFrameT (Just GameAI.aiCharge) 7 Nothing
, MFrameT (Just GameAI.aiCharge) 7 (Just tankFootStep)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- 20)
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
]
tankMoveAttackPreRocket :: MMoveT
tankMoveAttackPreRocket = MMoveT "tankMoveAttackPreRocket" frameAttack301 frameAttack321 tankFramesAttackPreRocket (Just tankDoAttackRocket)
tankFramesAttackFireRocket :: V.Vector MFrameT
tankFramesAttackFireRocket =
V.fromList [ MFrameT (Just GameAI.aiCharge) (-3) Nothing -- Loop Start 22
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just tankRocket) -- 24
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just tankRocket)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-1) (Just tankRocket) -- 30 Loop End
]
tankMoveAttackFireRocket :: MMoveT
tankMoveAttackFireRocket = MMoveT "tankMoveAttackFireRocket" frameAttack322 frameAttack330 tankFramesAttackFireRocket (Just tankReFireRocket)
tankFramesAttackPostRocket :: V.Vector MFrameT
tankFramesAttackPostRocket =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing -- 31
, MFrameT (Just GameAI.aiCharge) (-1) Nothing
, MFrameT (Just GameAI.aiCharge) (-1) Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 2 Nothing
, MFrameT (Just GameAI.aiCharge) 3 Nothing
, MFrameT (Just GameAI.aiCharge) 4 Nothing
, MFrameT (Just GameAI.aiCharge) 2 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- 40
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-9) Nothing
, MFrameT (Just GameAI.aiCharge) (-8) Nothing
, MFrameT (Just GameAI.aiCharge) (-7) Nothing
, MFrameT (Just GameAI.aiCharge) (-1) Nothing
, MFrameT (Just GameAI.aiCharge) (-1) (Just tankFootStep)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- 50
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
]
tankMoveAttackPostRocket :: MMoveT
tankMoveAttackPostRocket = MMoveT "tankMoveAttackPostRocket" frameAttack331 frameAttack353 tankFramesAttackPostRocket (Just tankRun)
tankFramesAttackChain :: V.Vector MFrameT
tankFramesAttackChain =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT Nothing 0 (Just tankMachineGun)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
]
tankMoveAttackChain :: MMoveT
tankMoveAttackChain = MMoveT "tankMoveAttackChain" frameAttack401 frameAttack429 tankFramesAttackChain (Just tankRun)
tankAttack :: EntThink
tankAttack =
GenericEntThink "tank_attack" $ \_ -> do
io (putStrLn "MTank.tankAttack") >> undefined -- TODO
tankDead :: EntThink
tankDead =
GenericEntThink "tank_dead" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMins .~ V3 (-16) (-16) (-16)
& eMaxs .~ V3 16 16 0
& eMoveType .~ Constants.moveTypeToss
& eSvFlags %~ (.|. Constants.svfDeadMonster)
& eNextThink .~ 0)
linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity
linkEntity selfRef
return True
tankFramesDeath1 :: V.Vector MFrameT
tankFramesDeath1 =
V.fromList [ MFrameT (Just GameAI.aiMove) (-7) Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) 3 Nothing
, MFrameT (Just GameAI.aiMove) 6 Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-3) Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-4) Nothing
, MFrameT (Just GameAI.aiMove) (-6) Nothing
, MFrameT (Just GameAI.aiMove) (-4) Nothing
, MFrameT (Just GameAI.aiMove) (-5) Nothing
, MFrameT (Just GameAI.aiMove) (-7) Nothing
, MFrameT (Just GameAI.aiMove) (-15) (Just tankThud)
, MFrameT (Just GameAI.aiMove) (-5) Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
tankMoveDeath :: MMoveT
tankMoveDeath = MMoveT "tankMoveDeath" frameDeath101 frameDeath132 tankFramesDeath1 (Just tankDead)
tankDie :: EntDie
tankDie =
GenericEntDie "tank_die" $ \_ _ _ _ _ -> do
io (putStrLn "MTank.tankDie") >> undefined -- TODO
{-
- QUAKED monster_tank (1 .5 0) (-32 -32 -16) (32 32 72) Ambush
- Trigger_Spawn Sight
-}
{-
- QUAKED monster_tank_commander (1 .5 0) (-32 -32 -16) (32 32 72) Ambush
- Trigger_Spawn Sight
-}
spMonsterTank :: EntThink
spMonsterTank =
GenericEntThink "SP_monster_tank" $ \_ -> do
io (putStrLn "MTank.spMonsterTank") >> undefined -- TODO
| ksaveljev/hake-2 | src/Game/Monsters/MTank.hs | bsd-3-clause | 32,835 | 0 | 25 | 9,752 | 9,471 | 4,838 | 4,633 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[PatSyntax]{Abstract Haskell syntax---patterns}
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
module HsPat (
Pat(..), InPat, OutPat, LPat,
HsConPatDetails, hsConPatArgs,
HsRecFields(..), HsRecField'(..), LHsRecField',
HsRecField, LHsRecField,
HsRecUpdField, LHsRecUpdField,
hsRecFields, hsRecFieldSel, hsRecFieldId, hsRecFieldsArgs,
hsRecUpdFieldId, hsRecUpdFieldOcc, hsRecUpdFieldRdr,
mkPrefixConPat, mkCharLitPat, mkNilPat,
isUnliftedHsBind, looksLazyPatBind,
isUnliftedLPat, isBangedLPat, isBangedPatBind,
hsPatNeedsParens,
isIrrefutableHsPat,
collectEvVarsPats,
pprParendLPat, pprConArgs
) where
import {-# SOURCE #-} HsExpr (SyntaxExpr, LHsExpr, HsSplice, pprLExpr, pprSplice)
-- friends:
import HsBinds
import HsLit
import PlaceHolder
import HsTypes
import TcEvidence
import BasicTypes
-- others:
import PprCore ( {- instance OutputableBndr TyVar -} )
import TysWiredIn
import Var
import RdrName ( RdrName )
import ConLike
import DataCon
import TyCon
import Outputable
import Type
import SrcLoc
import Bag -- collect ev vars from pats
import DynFlags( gopt, GeneralFlag(..) )
import Maybes
-- libraries:
import Data.Data hiding (TyCon,Fixity)
type InPat id = LPat id -- No 'Out' constructors
type OutPat id = LPat id -- No 'In' constructors
type LPat id = Located (Pat id)
-- | Pattern
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang'
-- For details on above see note [Api annotations] in ApiAnnotation
data Pat id
= ------------ Simple patterns ---------------
WildPat (PostTc id Type) -- ^ Wildcard Pattern
-- The sole reason for a type on a WildPat is to
-- support hsPatType :: Pat Id -> Type
| VarPat (Located id) -- ^ Variable Pattern
-- See Note [Located RdrNames] in HsExpr
| LazyPat (LPat id) -- ^ Lazy Pattern
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
-- For details on above see note [Api annotations] in ApiAnnotation
| AsPat (Located id) (LPat id) -- ^ As pattern
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
-- For details on above see note [Api annotations] in ApiAnnotation
| ParPat (LPat id) -- ^ Parenthesised pattern
-- See Note [Parens in HsSyn] in HsExpr
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| BangPat (LPat id) -- ^ Bang pattern
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang'
-- For details on above see note [Api annotations] in ApiAnnotation
------------ Lists, tuples, arrays ---------------
| ListPat [LPat id]
(PostTc id Type) -- The type of the elements
(Maybe (PostTc id Type, SyntaxExpr id)) -- For rebindable syntax
-- For OverloadedLists a Just (ty,fn) gives
-- overall type of the pattern, and the toList
-- function to convert the scrutinee to a list value
-- ^ Syntactic List
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
-- 'ApiAnnotation.AnnClose' @']'@
-- For details on above see note [Api annotations] in ApiAnnotation
| TuplePat [LPat id] -- Tuple sub-patterns
Boxity -- UnitPat is TuplePat []
[PostTc id Type] -- [] before typechecker, filled in afterwards
-- with the types of the tuple components
-- You might think that the PostTc id Type was redundant, because we can
-- get the pattern type by getting the types of the sub-patterns.
-- But it's essential
-- data T a where
-- T1 :: Int -> T Int
-- f :: (T a, a) -> Int
-- f (T1 x, z) = z
-- When desugaring, we must generate
-- f = /\a. \v::a. case v of (t::T a, w::a) ->
-- case t of (T1 (x::Int)) ->
-- Note the (w::a), NOT (w::Int), because we have not yet
-- refined 'a' to Int. So we must know that the second component
-- of the tuple is of type 'a' not Int. See selectMatchVar
-- (June 14: I'm not sure this comment is right; the sub-patterns
-- will be wrapped in CoPats, no?)
-- ^ Tuple sub-patterns
--
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnOpen' @'('@ or @'(#'@,
-- 'ApiAnnotation.AnnClose' @')'@ or @'#)'@
| SumPat (LPat id) -- Sum sub-pattern
ConTag -- Alternative (one-based)
Arity -- Arity
(PostTc id [Type]) -- PlaceHolder before typechecker, filled in
-- afterwards with the types of the
-- alternative
-- ^ Anonymous sum pattern
--
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnOpen' @'(#'@,
-- 'ApiAnnotation.AnnClose' @'#)'@
-- For details on above see note [Api annotations] in ApiAnnotation
| PArrPat [LPat id] -- Syntactic parallel array
(PostTc id Type) -- The type of the elements
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
-- 'ApiAnnotation.AnnClose' @':]'@
-- For details on above see note [Api annotations] in ApiAnnotation
------------ Constructor patterns ---------------
| ConPatIn (Located id)
(HsConPatDetails id)
-- ^ Constructor Pattern In
| ConPatOut {
pat_con :: Located ConLike,
pat_arg_tys :: [Type], -- The universal arg types, 1-1 with the universal
-- tyvars of the constructor/pattern synonym
-- Use (conLikeResTy pat_con pat_arg_tys) to get
-- the type of the pattern
pat_tvs :: [TyVar], -- Existentially bound type variables
-- in correctly-scoped order e.g. [k:*, x:k]
pat_dicts :: [EvVar], -- Ditto *coercion variables* and *dictionaries*
-- One reason for putting coercion variable here, I think,
-- is to ensure their kinds are zonked
pat_binds :: TcEvBinds, -- Bindings involving those dictionaries
pat_args :: HsConPatDetails id,
pat_wrap :: HsWrapper -- Extra wrapper to pass to the matcher
-- Only relevant for pattern-synonyms;
-- ignored for data cons
}
-- ^ Constructor Pattern Out
------------ View patterns ---------------
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| ViewPat (LHsExpr id)
(LPat id)
(PostTc id Type) -- The overall type of the pattern
-- (= the argument type of the view function)
-- for hsPatType.
-- ^ View Pattern
------------ Pattern splices ---------------
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| SplicePat (HsSplice id) -- ^ Splice Pattern (Includes quasi-quotes)
------------ Literal and n+k patterns ---------------
| LitPat HsLit -- ^ Literal Pattern
-- Used for *non-overloaded* literal patterns:
-- Int#, Char#, Int, Char, String, etc.
| NPat -- Natural Pattern
-- Used for all overloaded literals,
-- including overloaded strings with -XOverloadedStrings
(Located (HsOverLit id)) -- ALWAYS positive
(Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative
-- patterns, Nothing otherwise
(SyntaxExpr id) -- Equality checker, of type t->t->Bool
(PostTc id Type) -- Overall type of pattern. Might be
-- different than the literal's type
-- if (==) or negate changes the type
-- ^ Natural Pattern
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVal' @'+'@
-- For details on above see note [Api annotations] in ApiAnnotation
| NPlusKPat (Located id) -- n+k pattern
(Located (HsOverLit id)) -- It'll always be an HsIntegral
(HsOverLit id) -- See Note [NPlusK patterns] in TcPat
-- NB: This could be (PostTc ...), but that induced a
-- a new hs-boot file. Not worth it.
(SyntaxExpr id) -- (>=) function, of type t1->t2->Bool
(SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName)
(PostTc id Type) -- Type of overall pattern
-- ^ n+k pattern
------------ Pattern type signatures ---------------
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
-- For details on above see note [Api annotations] in ApiAnnotation
| SigPatIn (LPat id) -- Pattern with a type signature
(LHsSigWcType id) -- Signature can bind both
-- kind and type vars
-- ^ Pattern with a type signature
| SigPatOut (LPat id)
Type
-- ^ Pattern with a type signature
------------ Pattern coercions (translation only) ---------------
| CoPat HsWrapper -- Coercion Pattern
-- If co :: t1 ~ t2, p :: t2,
-- then (CoPat co p) :: t1
(Pat id) -- Why not LPat? Ans: existing locn will do
Type -- Type of whole pattern, t1
-- During desugaring a (CoPat co pat) turns into a cast with 'co' on
-- the scrutinee, followed by a match on 'pat'
-- ^ Coercion Pattern
deriving instance (DataId id) => Data (Pat id)
-- | Haskell Constructor Pattern Details
type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id))
hsConPatArgs :: HsConPatDetails id -> [LPat id]
hsConPatArgs (PrefixCon ps) = ps
hsConPatArgs (RecCon fs) = map (hsRecFieldArg . unLoc) (rec_flds fs)
hsConPatArgs (InfixCon p1 p2) = [p1,p2]
-- | Haskell Record Fields
--
-- HsRecFields is used only for patterns and expressions (not data type
-- declarations)
data HsRecFields id arg -- A bunch of record fields
-- { x = 3, y = True }
-- Used for both expressions and patterns
= HsRecFields { rec_flds :: [LHsRecField id arg],
rec_dotdot :: Maybe Int } -- Note [DotDot fields]
deriving (Functor, Foldable, Traversable)
deriving instance (DataId id, Data arg) => Data (HsRecFields id arg)
-- Note [DotDot fields]
-- ~~~~~~~~~~~~~~~~~~~~
-- The rec_dotdot field means this:
-- Nothing => the normal case
-- Just n => the group uses ".." notation,
--
-- In the latter case:
--
-- *before* renamer: rec_flds are exactly the n user-written fields
--
-- *after* renamer: rec_flds includes *all* fields, with
-- the first 'n' being the user-written ones
-- and the remainder being 'filled in' implicitly
-- | Located Haskell Record Field
type LHsRecField' id arg = Located (HsRecField' id arg)
-- | Located Haskell Record Field
type LHsRecField id arg = Located (HsRecField id arg)
-- | Located Haskell Record Update Field
type LHsRecUpdField id = Located (HsRecUpdField id)
-- | Haskell Record Field
type HsRecField id arg = HsRecField' (FieldOcc id) arg
-- | Haskell Record Update Field
type HsRecUpdField id = HsRecField' (AmbiguousFieldOcc id) (LHsExpr id)
-- | Haskell Record Field
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual',
--
-- For details on above see note [Api annotations] in ApiAnnotation
data HsRecField' id arg = HsRecField {
hsRecFieldLbl :: Located id,
hsRecFieldArg :: arg, -- ^ Filled in by renamer when punning
hsRecPun :: Bool -- ^ Note [Punning]
} deriving (Data, Functor, Foldable, Traversable)
-- Note [Punning]
-- ~~~~~~~~~~~~~~
-- If you write T { x, y = v+1 }, the HsRecFields will be
-- HsRecField x x True ...
-- HsRecField y (v+1) False ...
-- That is, for "punned" field x is expanded (in the renamer)
-- to x=x; but with a punning flag so we can detect it later
-- (e.g. when pretty printing)
--
-- If the original field was qualified, we un-qualify it, thus
-- T { A.x } means T { A.x = x }
-- Note [HsRecField and HsRecUpdField]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- A HsRecField (used for record construction and pattern matching)
-- contains an unambiguous occurrence of a field (i.e. a FieldOcc).
-- We can't just store the Name, because thanks to
-- DuplicateRecordFields this may not correspond to the label the user
-- wrote.
--
-- A HsRecUpdField (used for record update) contains a potentially
-- ambiguous occurrence of a field (an AmbiguousFieldOcc). The
-- renamer will fill in the selector function if it can, but if the
-- selector is ambiguous the renamer will defer to the typechecker.
-- After the typechecker, a unique selector will have been determined.
--
-- The renamer produces an Unambiguous result if it can, rather than
-- just doing the lookup in the typechecker, so that completely
-- unambiguous updates can be represented by 'DsMeta.repUpdFields'.
--
-- For example, suppose we have:
--
-- data S = MkS { x :: Int }
-- data T = MkT { x :: Int }
--
-- f z = (z { x = 3 }) :: S
--
-- The parsed HsRecUpdField corresponding to the record update will have:
--
-- hsRecFieldLbl = Unambiguous "x" PlaceHolder :: AmbiguousFieldOcc RdrName
--
-- After the renamer, this will become:
--
-- hsRecFieldLbl = Ambiguous "x" PlaceHolder :: AmbiguousFieldOcc Name
--
-- (note that the Unambiguous constructor is not type-correct here).
-- The typechecker will determine the particular selector:
--
-- hsRecFieldLbl = Unambiguous "x" $sel:x:MkS :: AmbiguousFieldOcc Id
--
-- See also Note [Disambiguating record fields] in TcExpr.
hsRecFields :: HsRecFields id arg -> [PostRn id id]
hsRecFields rbinds = map (unLoc . hsRecFieldSel . unLoc) (rec_flds rbinds)
-- Probably won't typecheck at once, things have changed :/
hsRecFieldsArgs :: HsRecFields id arg -> [arg]
hsRecFieldsArgs rbinds = map (hsRecFieldArg . unLoc) (rec_flds rbinds)
hsRecFieldSel :: HsRecField name arg -> Located (PostRn name name)
hsRecFieldSel = fmap selectorFieldOcc . hsRecFieldLbl
hsRecFieldId :: HsRecField Id arg -> Located Id
hsRecFieldId = hsRecFieldSel
hsRecUpdFieldRdr :: HsRecUpdField id -> Located RdrName
hsRecUpdFieldRdr = fmap rdrNameAmbiguousFieldOcc . hsRecFieldLbl
hsRecUpdFieldId :: HsRecField' (AmbiguousFieldOcc Id) arg -> Located Id
hsRecUpdFieldId = fmap selectorFieldOcc . hsRecUpdFieldOcc
hsRecUpdFieldOcc :: HsRecField' (AmbiguousFieldOcc Id) arg -> LFieldOcc Id
hsRecUpdFieldOcc = fmap unambiguousFieldOcc . hsRecFieldLbl
{-
************************************************************************
* *
* Printing patterns
* *
************************************************************************
-}
instance (OutputableBndrId name) => Outputable (Pat name) where
ppr = pprPat
pprPatBndr :: OutputableBndr name => name -> SDoc
pprPatBndr var -- Print with type info if -dppr-debug is on
= getPprStyle $ \ sty ->
if debugStyle sty then
parens (pprBndr LambdaBind var) -- Could pass the site to pprPat
-- but is it worth it?
else
pprPrefixOcc var
pprParendLPat :: (OutputableBndrId name) => LPat name -> SDoc
pprParendLPat (L _ p) = pprParendPat p
pprParendPat :: (OutputableBndrId name) => Pat name -> SDoc
pprParendPat p = sdocWithDynFlags $ \ dflags ->
if need_parens dflags p
then parens (pprPat p)
else pprPat p
where
need_parens dflags p
| CoPat {} <- p = gopt Opt_PrintTypecheckerElaboration dflags
| otherwise = hsPatNeedsParens p
-- For a CoPat we need parens if we are going to show it, which
-- we do if -fprint-typechecker-elaboration is on (c.f. pprHsWrapper)
-- But otherwise the CoPat is discarded, so it
-- is the pattern inside that matters. Sigh.
pprPat :: (OutputableBndrId name) => Pat name -> SDoc
pprPat (VarPat (L _ var)) = pprPatBndr var
pprPat (WildPat _) = char '_'
pprPat (LazyPat pat) = char '~' <> pprParendLPat pat
pprPat (BangPat pat) = char '!' <> pprParendLPat pat
pprPat (AsPat name pat) = hcat [pprPrefixOcc (unLoc name), char '@', pprParendLPat pat]
pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat]
pprPat (ParPat pat) = parens (ppr pat)
pprPat (LitPat s) = ppr s
pprPat (NPat l Nothing _ _) = ppr l
pprPat (NPat l (Just _) _ _) = char '-' <> ppr l
pprPat (NPlusKPat n k _ _ _ _)= hcat [ppr n, char '+', ppr k]
pprPat (SplicePat splice) = pprSplice splice
pprPat (CoPat co pat _) = pprHsWrapper co (\parens -> if parens
then pprParendPat pat
else pprPat pat)
pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty
pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty
pprPat (ListPat pats _ _) = brackets (interpp'SP pats)
pprPat (PArrPat pats _) = paBrackets (interpp'SP pats)
pprPat (TuplePat pats bx _) = tupleParens (boxityTupleSort bx) (pprWithCommas ppr pats)
pprPat (SumPat pat alt arity _) = sumParens (pprAlternative ppr pat alt arity)
pprPat (ConPatIn con details) = pprUserCon (unLoc con) details
pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts,
pat_binds = binds, pat_args = details })
= sdocWithDynFlags $ \dflags ->
-- Tiresome; in TcBinds.tcRhs we print out a
-- typechecked Pat in an error message,
-- and we want to make sure it prints nicely
if gopt Opt_PrintTypecheckerElaboration dflags then
ppr con
<> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts))
, ppr binds])
<+> pprConArgs details
else pprUserCon (unLoc con) details
pprUserCon :: (OutputableBndr con, OutputableBndrId id)
=> con -> HsConPatDetails id -> SDoc
pprUserCon c (InfixCon p1 p2) = ppr p1 <+> pprInfixOcc c <+> ppr p2
pprUserCon c details = pprPrefixOcc c <+> pprConArgs details
pprConArgs :: (OutputableBndrId id) => HsConPatDetails id -> SDoc
pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats)
pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2]
pprConArgs (RecCon rpats) = ppr rpats
instance (Outputable arg)
=> Outputable (HsRecFields id arg) where
ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing })
= braces (fsep (punctuate comma (map ppr flds)))
ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n })
= braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot])))
where
dotdot = text ".." <+> ifPprDebug (ppr (drop n flds))
instance (Outputable id, Outputable arg)
=> Outputable (HsRecField' id arg) where
ppr (HsRecField { hsRecFieldLbl = f, hsRecFieldArg = arg,
hsRecPun = pun })
= ppr f <+> (ppUnless pun $ equals <+> ppr arg)
{-
************************************************************************
* *
* Building patterns
* *
************************************************************************
-}
mkPrefixConPat :: DataCon -> [OutPat id] -> [Type] -> OutPat id
-- Make a vanilla Prefix constructor pattern
mkPrefixConPat dc pats tys
= noLoc $ ConPatOut { pat_con = noLoc (RealDataCon dc), pat_tvs = [], pat_dicts = [],
pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats,
pat_arg_tys = tys, pat_wrap = idHsWrapper }
mkNilPat :: Type -> OutPat id
mkNilPat ty = mkPrefixConPat nilDataCon [] [ty]
mkCharLitPat :: String -> Char -> OutPat id
mkCharLitPat src c = mkPrefixConPat charDataCon
[noLoc $ LitPat (HsCharPrim src c)] []
{-
************************************************************************
* *
* Predicates for checking things about pattern-lists in EquationInfo *
* *
************************************************************************
\subsection[Pat-list-predicates]{Look for interesting things in patterns}
Unlike in the Wadler chapter, where patterns are either ``variables''
or ``constructors,'' here we distinguish between:
\begin{description}
\item[unfailable:]
Patterns that cannot fail to match: variables, wildcards, and lazy
patterns.
These are the irrefutable patterns; the two other categories
are refutable patterns.
\item[constructor:]
A non-literal constructor pattern (see next category).
\item[literal patterns:]
At least the numeric ones may be overloaded.
\end{description}
A pattern is in {\em exactly one} of the above three categories; `as'
patterns are treated specially, of course.
The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are.
-}
isUnliftedLPat :: LPat id -> Bool
isUnliftedLPat (L _ (ParPat p)) = isUnliftedLPat p
isUnliftedLPat (L _ (TuplePat _ Unboxed _)) = True
isUnliftedLPat (L _ (SumPat _ _ _ _)) = True
isUnliftedLPat _ = False
isUnliftedHsBind :: HsBind id -> Bool
-- A pattern binding with an outermost bang or unboxed tuple or sum must be
-- matched strictly.
-- Defined in this module because HsPat is above HsBinds in the import graph
isUnliftedHsBind (PatBind { pat_lhs = p }) = isUnliftedLPat p
isUnliftedHsBind _ = False
isBangedPatBind :: HsBind id -> Bool
isBangedPatBind (PatBind {pat_lhs = pat}) = isBangedLPat pat
isBangedPatBind _ = False
isBangedLPat :: LPat id -> Bool
isBangedLPat (L _ (ParPat p)) = isBangedLPat p
isBangedLPat (L _ (BangPat {})) = True
isBangedLPat _ = False
looksLazyPatBind :: HsBind id -> Bool
-- Returns True of anything *except*
-- a StrictHsBind (as above) or
-- a VarPat
-- In particular, returns True of a pattern binding with a compound pattern, like (I# x)
looksLazyPatBind (PatBind { pat_lhs = p }) = looksLazyLPat p
looksLazyPatBind _ = False
looksLazyLPat :: LPat id -> Bool
looksLazyLPat (L _ (ParPat p)) = looksLazyLPat p
looksLazyLPat (L _ (AsPat _ p)) = looksLazyLPat p
looksLazyLPat (L _ (BangPat {})) = False
looksLazyLPat (L _ (TuplePat _ Unboxed _)) = False
looksLazyLPat (L _ (SumPat _ _ _ _)) = False
looksLazyLPat (L _ (VarPat {})) = False
looksLazyLPat (L _ (WildPat {})) = False
looksLazyLPat _ = True
isIrrefutableHsPat :: (OutputableBndrId id) => LPat id -> Bool
-- (isIrrefutableHsPat p) is true if matching against p cannot fail,
-- in the sense of falling through to the next pattern.
-- (NB: this is not quite the same as the (silly) defn
-- in 3.17.2 of the Haskell 98 report.)
--
-- WARNING: isIrrefutableHsPat returns False if it's in doubt.
-- Specifically on a ConPatIn, which is what it sees for a
-- (LPat Name) in the renamer, it doesn't know the size of the
-- constructor family, so it returns False. Result: only
-- tuple patterns are considered irrefuable at the renamer stage.
--
-- But if it returns True, the pattern is definitely irrefutable
isIrrefutableHsPat pat
= go pat
where
go (L _ pat) = go1 pat
go1 (WildPat {}) = True
go1 (VarPat {}) = True
go1 (LazyPat {}) = True
go1 (BangPat pat) = go pat
go1 (CoPat _ pat _) = go1 pat
go1 (ParPat pat) = go pat
go1 (AsPat _ pat) = go pat
go1 (ViewPat _ pat _) = go pat
go1 (SigPatIn pat _) = go pat
go1 (SigPatOut pat _) = go pat
go1 (TuplePat pats _ _) = all go pats
go1 (SumPat pat _ _ _) = go pat
go1 (ListPat {}) = False
go1 (PArrPat {}) = False -- ?
go1 (ConPatIn {}) = False -- Conservative
go1 (ConPatOut{ pat_con = L _ (RealDataCon con), pat_args = details })
= isJust (tyConSingleDataCon_maybe (dataConTyCon con))
-- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because
-- the latter is false of existentials. See Trac #4439
&& all go (hsConPatArgs details)
go1 (ConPatOut{ pat_con = L _ (PatSynCon _pat) })
= False -- Conservative
go1 (LitPat {}) = False
go1 (NPat {}) = False
go1 (NPlusKPat {}) = False
-- Both should be gotten rid of by renamer before
-- isIrrefutablePat is called
go1 (SplicePat {}) = urk pat
urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat)
hsPatNeedsParens :: Pat a -> Bool
hsPatNeedsParens (NPlusKPat {}) = True
hsPatNeedsParens (SplicePat {}) = False
hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds
hsPatNeedsParens p@(ConPatOut {}) = conPatNeedsParens (pat_args p)
hsPatNeedsParens (SigPatIn {}) = True
hsPatNeedsParens (SigPatOut {}) = True
hsPatNeedsParens (ViewPat {}) = True
hsPatNeedsParens (CoPat _ p _) = hsPatNeedsParens p
hsPatNeedsParens (WildPat {}) = False
hsPatNeedsParens (VarPat {}) = False
hsPatNeedsParens (LazyPat {}) = False
hsPatNeedsParens (BangPat {}) = False
hsPatNeedsParens (ParPat {}) = False
hsPatNeedsParens (AsPat {}) = False
hsPatNeedsParens (TuplePat {}) = False
hsPatNeedsParens (SumPat {}) = False
hsPatNeedsParens (ListPat {}) = False
hsPatNeedsParens (PArrPat {}) = False
hsPatNeedsParens (LitPat {}) = False
hsPatNeedsParens (NPat {}) = False
conPatNeedsParens :: HsConDetails a b -> Bool
conPatNeedsParens (PrefixCon args) = not (null args)
conPatNeedsParens (InfixCon {}) = True
conPatNeedsParens (RecCon {}) = True
{-
% Collect all EvVars from all constructor patterns
-}
-- May need to add more cases
collectEvVarsPats :: [Pat id] -> Bag EvVar
collectEvVarsPats = unionManyBags . map collectEvVarsPat
collectEvVarsLPat :: LPat id -> Bag EvVar
collectEvVarsLPat (L _ pat) = collectEvVarsPat pat
collectEvVarsPat :: Pat id -> Bag EvVar
collectEvVarsPat pat =
case pat of
LazyPat p -> collectEvVarsLPat p
AsPat _ p -> collectEvVarsLPat p
ParPat p -> collectEvVarsLPat p
BangPat p -> collectEvVarsLPat p
ListPat ps _ _ -> unionManyBags $ map collectEvVarsLPat ps
TuplePat ps _ _ -> unionManyBags $ map collectEvVarsLPat ps
SumPat p _ _ _ -> collectEvVarsLPat p
PArrPat ps _ -> unionManyBags $ map collectEvVarsLPat ps
ConPatOut {pat_dicts = dicts, pat_args = args}
-> unionBags (listToBag dicts)
$ unionManyBags
$ map collectEvVarsLPat
$ hsConPatArgs args
SigPatOut p _ -> collectEvVarsLPat p
CoPat _ p _ -> collectEvVarsPat p
ConPatIn _ _ -> panic "foldMapPatBag: ConPatIn"
SigPatIn _ _ -> panic "foldMapPatBag: SigPatIn"
_other_pat -> emptyBag
| mettekou/ghc | compiler/hsSyn/HsPat.hs | bsd-3-clause | 29,415 | 0 | 18 | 9,004 | 4,987 | 2,714 | 2,273 | 321 | 21 |
module CNC.GParser(module CNC.GTypes, parseIsoFile) where
import CNC.GTypes
import Data.Attoparsec.Text
import qualified Data.Text as T
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import Data.Char
import Control.Applicative
import Data.Maybe
instrP = do
c <- toUpper <$> letter
val <- iso_double
return $ case elem c "GMNT" of
True -> GInstrI c (round val)
_ -> GInstrF c (realToFrac val)
frameP = GFrame <$> many1 instrP
frames = many $ do f <- frameP
skipComment
return f
iso7 = do
char '%'
skipSpace
char 'O'
prog <- many1 digit
skipComment
fs <- frames
char '%'
skipComment
endOfInput
return $ GProgram {gpName = prog, gpCode = fs}
skipComment = do
skipHorSpace
optional $ char ';'
res <- optional $ do
char '('
many $ notChar ')'
char ')'
skipHorSpace
res2 <- optional $ satisfy isEndOfLine
case isJust res || isJust res2 of
False -> return ()
True -> skipComment
skipHorSpace = many $ satisfy isHorizontalSpace
iso_double = do minus <- optional $ char '-'
case minus of
Nothing -> iso_pos_double
Just _ -> negate <$> iso_pos_double
iso_pos_double = leading_dot <|> (double >>= \d -> optional (char '.') >> return d)
leading_dot = do char '.'
n <- number
case n of
I i -> let len = length (show i)
in return $ fromIntegral i / (10^len)
_ -> fail "strange number with leading dot"
parseIsoFile file = do
prog <- T.readFile file
return $ parseOnly iso7 $ T.toStrict prog
| akamaus/gcodec | src/CNC/GParser.hs | bsd-3-clause | 1,681 | 0 | 16 | 513 | 569 | 274 | 295 | 57 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
-- | The general Stack configuration that starts everything off. This should
-- be smart to falback if there is no stack.yaml, instead relying on
-- whatever files are available.
--
-- If there is no stack.yaml, and there is a cabal.config, we
-- read in those constraints, and if there's a cabal.sandbox.config,
-- we read any constraints from there and also find the package
-- database from there, etc. And if there's nothing, we should
-- probably default to behaving like cabal, possibly with spitting out
-- a warning that "you should run `stk init` to make things better".
module Stack.Config
(loadConfig
,packagesParser
) where
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Compression.GZip as GZip
import Control.Applicative
import Control.Concurrent (getNumCapabilities)
import Control.Exception (IOException)
import Control.Monad
import Control.Monad.Catch (Handler(..), MonadCatch, MonadThrow, catches, throwM)
import Control.Monad.IO.Class
import Control.Monad.Logger hiding (Loc)
import Control.Monad.Reader (MonadReader, ask, runReaderT)
import Control.Monad.Trans.Control (MonadBaseControl)
import qualified Crypto.Hash.SHA256 as SHA256
import Data.Aeson.Extended
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Lazy as L
import qualified Data.IntMap as IntMap
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import qualified Data.Yaml as Yaml
import Distribution.System (OS (..), Platform (..), buildPlatform)
import qualified Distribution.Text
import Distribution.Version (simplifyVersionRange)
import Network.HTTP.Client.Conduit (HasHttpManager, getHttpManager, Manager, parseUrl)
import Network.HTTP.Download (download)
import Options.Applicative (Parser, strOption, long, help)
import Path
import Path.IO
import qualified Paths_stack as Meta
import Stack.BuildPlan
import Stack.Constants
import qualified Stack.Docker as Docker
import qualified Stack.Image as Image
import Stack.Init
import Stack.Types
import Stack.Types.Internal
import System.Directory (getAppUserDataDirectory, createDirectoryIfMissing, canonicalizePath)
import System.Environment
import System.IO
import System.Process.Read (getEnvOverride, EnvOverride, unEnvOverride, readInNull)
-- | Get the latest snapshot resolver available.
getLatestResolver
:: (MonadIO m, MonadThrow m, MonadReader env m, HasConfig env, HasHttpManager env, MonadLogger m)
=> m Resolver
getLatestResolver = do
snapshots <- getSnapshots
let mlts = do
(x,y) <- listToMaybe (reverse (IntMap.toList (snapshotsLts snapshots)))
return (LTS x y)
snap =
case mlts of
Nothing -> Nightly (snapshotsNightly snapshots)
Just lts -> lts
return (ResolverSnapshot snap)
-- | Note that this will be @Nothing@ on Windows, which is by design.
defaultStackGlobalConfig :: Maybe (Path Abs File)
defaultStackGlobalConfig = parseAbsFile "/etc/stack/config"
-- Interprets ConfigMonoid options.
configFromConfigMonoid
:: (MonadLogger m, MonadIO m, MonadCatch m, MonadReader env m, HasHttpManager env)
=> Path Abs Dir -- ^ stack root, e.g. ~/.stack
-> Maybe Project
-> ConfigMonoid
-> m Config
configFromConfigMonoid configStackRoot mproject configMonoid@ConfigMonoid{..} = do
let configDocker = Docker.dockerOptsFromMonoid mproject configStackRoot configMonoidDockerOpts
configConnectionCount = fromMaybe 8 configMonoidConnectionCount
configHideTHLoading = fromMaybe True configMonoidHideTHLoading
configLatestSnapshotUrl = fromMaybe
"https://s3.amazonaws.com/haddock.stackage.org/snapshots.json"
configMonoidLatestSnapshotUrl
configPackageIndices = fromMaybe
[PackageIndex
{ indexName = IndexName "Hackage"
, indexLocation = ILGitHttp
"https://github.com/commercialhaskell/all-cabal-hashes.git"
"https://s3.amazonaws.com/hackage.fpcomplete.com/00-index.tar.gz"
, indexDownloadPrefix = "https://s3.amazonaws.com/hackage.fpcomplete.com/package/"
, indexGpgVerify = False
, indexRequireHashes = False
}]
configMonoidPackageIndices
configSystemGHC = fromMaybe True configMonoidSystemGHC
configInstallGHC = fromMaybe False configMonoidInstallGHC
configSkipGHCCheck = fromMaybe False configMonoidSkipGHCCheck
configSkipMsys = fromMaybe False configMonoidSkipMsys
configExtraIncludeDirs = configMonoidExtraIncludeDirs
configExtraLibDirs = configMonoidExtraLibDirs
-- Only place in the codebase where platform is hard-coded. In theory
-- in the future, allow it to be configured.
(Platform defArch defOS) = buildPlatform
arch = fromMaybe defArch
$ configMonoidArch >>= Distribution.Text.simpleParse
os = fromMaybe defOS
$ configMonoidOS >>= Distribution.Text.simpleParse
configPlatform = Platform arch os
configRequireStackVersion = simplifyVersionRange configMonoidRequireStackVersion
configConfigMonoid = configMonoid
configImage = Image.imgOptsFromMonoid configMonoidImageOpts
origEnv <- getEnvOverride configPlatform
let configEnvOverride _ = return origEnv
platform <- runReaderT platformRelDir configPlatform
configLocalPrograms <-
case configPlatform of
Platform _ Windows -> do
progsDir <- getWindowsProgsDir configStackRoot origEnv
return $ progsDir </> $(mkRelDir stackProgName) </> platform
_ -> return $ configStackRoot </> $(mkRelDir "programs") </> platform
configLocalBin <-
case configMonoidLocalBinPath of
Nothing -> do
localDir <- liftIO (getAppUserDataDirectory "local") >>= parseAbsDir
return $ localDir </> $(mkRelDir "bin")
Just userPath ->
(liftIO $ canonicalizePath userPath >>= parseAbsDir)
`catches`
[Handler (\(_ :: IOException) -> throwM $ NoSuchDirectory userPath)
,Handler (\(_ :: PathParseException) -> throwM $ NoSuchDirectory userPath)
]
configJobs <-
case configMonoidJobs of
Nothing -> liftIO getNumCapabilities
Just i -> return i
let configConcurrentTests = fromMaybe True configMonoidConcurrentTests
return Config {..}
-- | Get the directory on Windows where we should install extra programs. For
-- more information, see discussion at:
-- https://github.com/fpco/minghc/issues/43#issuecomment-99737383
getWindowsProgsDir :: MonadThrow m
=> Path Abs Dir
-> EnvOverride
-> m (Path Abs Dir)
getWindowsProgsDir stackRoot m =
case Map.lookup "LOCALAPPDATA" $ unEnvOverride m of
Just t -> do
lad <- parseAbsDir $ T.unpack t
return $ lad </> $(mkRelDir "Programs")
Nothing -> return $ stackRoot </> $(mkRelDir "Programs")
data MiniConfig = MiniConfig Manager Config
instance HasConfig MiniConfig where
getConfig (MiniConfig _ c) = c
instance HasStackRoot MiniConfig
instance HasHttpManager MiniConfig where
getHttpManager (MiniConfig man _) = man
instance HasPlatform MiniConfig
-- | Load the configuration, using current directory, environment variables,
-- and defaults as necessary.
loadConfig :: (MonadLogger m,MonadIO m,MonadCatch m,MonadThrow m,MonadBaseControl IO m,MonadReader env m,HasHttpManager env,HasTerminal env)
=> ConfigMonoid
-- ^ Config monoid from parsed command-line arguments
-> Maybe (Path Abs File)
-- ^ Override stack.yaml
-> m (LoadConfig m)
loadConfig configArgs mstackYaml = do
stackRoot <- determineStackRoot
extraConfigs <- getExtraConfigs stackRoot >>= mapM loadYaml
mproject <- loadProjectConfig mstackYaml
config <- configFromConfigMonoid stackRoot (fmap (\(proj, _, _) -> proj) mproject) $ mconcat $
case mproject of
Nothing -> configArgs : extraConfigs
Just (_, _, projectConfig) -> configArgs : projectConfig : extraConfigs
unless (fromCabalVersion Meta.version `withinRange` configRequireStackVersion config)
(throwM (BadStackVersionException (configRequireStackVersion config)))
menv <- runReaderT getMinimalEnvOverride config
return $ LoadConfig
{ lcConfig = config
, lcLoadBuildConfig = loadBuildConfig menv mproject config stackRoot
, lcProjectRoot = fmap (\(_, fp, _) -> parent fp) mproject
}
-- | Load the build configuration, adds build-specific values to config loaded by @loadConfig@.
-- values.
loadBuildConfig :: (MonadLogger m, MonadIO m, MonadCatch m, MonadReader env m, HasHttpManager env, MonadBaseControl IO m, HasTerminal env)
=> EnvOverride
-> Maybe (Project, Path Abs File, ConfigMonoid)
-> Config
-> Path Abs Dir
-> Maybe Resolver -- override resolver
-> NoBuildConfigStrategy
-> m BuildConfig
loadBuildConfig menv mproject config stackRoot mresolver noConfigStrat = do
env <- ask
let miniConfig = MiniConfig (getHttpManager env) config
(project', stackYamlFP) <- case mproject of
Just (project, fp, _) -> return (project, fp)
Nothing -> case noConfigStrat of
ThrowException -> do
currDir <- getWorkingDir
cabalFiles <- findCabalFiles True currDir
throwM $ NoProjectConfigFound currDir
$ Just $ if null cabalFiles then "new" else "init"
ExecStrategy -> do
let dest :: Path Abs File
dest = destDir </> stackDotYaml
destDir = implicitGlobalDir stackRoot
dest' :: FilePath
dest' = toFilePath dest
createTree destDir
exists <- fileExists dest
if exists
then do
ProjectAndConfigMonoid project _ <- loadYaml dest
when (getTerminal env) $
case mresolver of
Nothing ->
$logInfo ("Using resolver: " <> renderResolver (projectResolver project) <>
" from global config file: " <> T.pack dest')
Just resolver ->
$logInfo ("Using resolver: " <> renderResolver resolver <>
" specified on command line")
return (project, dest)
else do
r <- runReaderT getLatestResolver miniConfig
$logInfo ("Using latest snapshot resolver: " <> renderResolver r)
$logInfo ("Writing global (non-project-specific) config file to: " <> T.pack dest')
$logInfo "Note: You can change the snapshot via the resolver field there."
let p = Project
{ projectPackages = mempty
, projectExtraDeps = mempty
, projectFlags = mempty
, projectResolver = r
}
liftIO $ Yaml.encodeFile dest' p
return (p, dest)
let project = project'
{ projectResolver = fromMaybe (projectResolver project') mresolver
}
ghcVersion <-
case projectResolver project of
ResolverSnapshot snapName -> do
mbp <- runReaderT (loadMiniBuildPlan snapName) miniConfig
return $ mbpGhcVersion mbp
ResolverGhc m -> return $ fromMajorVersion m
let root = parent stackYamlFP
packages' <- mapM (resolvePackageEntry menv root) (projectPackages project)
let packages = Map.fromList $ concat packages'
return BuildConfig
{ bcConfig = config
, bcResolver = projectResolver project
, bcGhcVersionExpected = ghcVersion
, bcPackages = packages
, bcExtraDeps = projectExtraDeps project
, bcRoot = root
, bcStackYaml = stackYamlFP
, bcFlags = projectFlags project
}
-- | Resolve a PackageEntry into a list of paths, downloading and cloning as
-- necessary.
resolvePackageEntry
:: (MonadIO m, MonadThrow m, MonadReader env m, HasHttpManager env, MonadLogger m, MonadCatch m
,MonadBaseControl IO m)
=> EnvOverride
-> Path Abs Dir -- ^ project root
-> PackageEntry
-> m [(Path Abs Dir, Bool)]
resolvePackageEntry menv projRoot pe = do
entryRoot <- resolvePackageLocation menv projRoot (peLocation pe)
paths <-
case peSubdirs pe of
[] -> return [entryRoot]
subs -> mapM (resolveDir entryRoot) subs
case peValidWanted pe of
Nothing -> return ()
Just _ -> $logWarn "Warning: you are using the deprecated valid-wanted field. You should instead use extra-dep. See: https://github.com/commercialhaskell/stack/wiki/stack.yaml#packages"
return $ map (, not $ peExtraDep pe) paths
-- | Resolve a PackageLocation into a path, downloading and cloning as
-- necessary.
resolvePackageLocation
:: (MonadIO m, MonadThrow m, MonadReader env m, HasHttpManager env, MonadLogger m, MonadCatch m
,MonadBaseControl IO m)
=> EnvOverride
-> Path Abs Dir -- ^ project root
-> PackageLocation
-> m (Path Abs Dir)
resolvePackageLocation _ projRoot (PLFilePath fp) = resolveDir projRoot fp
resolvePackageLocation _ projRoot (PLHttpTarball url) = do
let name = T.unpack $ decodeUtf8 $ B16.encode $ SHA256.hash $ encodeUtf8 url
root = projRoot </> workDirRel </> $(mkRelDir "downloaded")
fileRel <- parseRelFile $ name ++ ".tar.gz"
dirRel <- parseRelDir name
dirRelTmp <- parseRelDir $ name ++ ".tmp"
let file = root </> fileRel
dir = root </> dirRel
dirTmp = root </> dirRelTmp
exists <- dirExists dir
unless exists $ do
req <- parseUrl $ T.unpack url
_ <- download req file
removeTreeIfExists dirTmp
liftIO $ withBinaryFile (toFilePath file) ReadMode $ \h -> do
lbs <- L.hGetContents h
let entries = Tar.read $ GZip.decompress lbs
Tar.unpack (toFilePath dirTmp) entries
renameDir dirTmp dir
x <- listDirectory dir
case x of
([dir'], []) -> return dir'
(dirs, files) -> do
removeFileIfExists file
removeTreeIfExists dir
throwM $ UnexpectedTarballContents dirs files
resolvePackageLocation menv projRoot (PLGit url commit) = do
let name = T.unpack $ decodeUtf8 $ B16.encode $ SHA256.hash $ encodeUtf8 $ T.unwords [url, commit]
root = projRoot </> workDirRel </> $(mkRelDir "downloaded")
dirRel <- parseRelDir $ name ++ ".git"
dirRelTmp <- parseRelDir $ name ++ ".git.tmp"
let dir = root </> dirRel
dirTmp = root </> dirRelTmp
exists <- dirExists dir
unless exists $ do
removeTreeIfExists dirTmp
createTree (parent dirTmp)
readInNull (parent dirTmp) "git" menv
[ "clone"
, T.unpack url
, toFilePath dirTmp
]
Nothing
readInNull dirTmp "git" menv
[ "reset"
, "--hard"
, T.unpack commit
]
Nothing
renameDir dirTmp dir
return dir
-- | Get the stack root, e.g. ~/.stack
determineStackRoot :: (MonadIO m, MonadThrow m) => m (Path Abs Dir)
determineStackRoot = do
env <- liftIO getEnvironment
case lookup stackRootEnvVar env of
Nothing -> do
x <- liftIO $ getAppUserDataDirectory stackProgName
parseAbsDir x
Just x -> do
y <- liftIO $ do
createDirectoryIfMissing True x
canonicalizePath x
parseAbsDir y
-- | Determine the extra config file locations which exist.
--
-- Returns most local first
getExtraConfigs :: MonadIO m
=> Path Abs Dir -- ^ stack root
-> m [Path Abs File]
getExtraConfigs stackRoot = liftIO $ do
env <- getEnvironment
mstackConfig <-
maybe (return Nothing) (fmap Just . parseAbsFile)
$ lookup "STACK_CONFIG" env
mstackGlobalConfig <-
maybe (return Nothing) (fmap Just . parseAbsFile)
$ lookup "STACK_GLOBAL_CONFIG" env
filterM fileExists
$ fromMaybe (stackRoot </> stackDotYaml) mstackConfig
: maybe [] return (mstackGlobalConfig <|> defaultStackGlobalConfig)
-- | Load and parse YAML from the given file.
loadYaml :: (FromJSON a,MonadIO m) => Path Abs File -> m a
loadYaml path =
liftIO $ Yaml.decodeFileEither (toFilePath path)
>>= either (throwM . ParseConfigFileException path) return
-- | Get the location of the project config file, if it exists.
getProjectConfig :: (MonadIO m, MonadThrow m, MonadLogger m)
=> Maybe (Path Abs File)
-- ^ Override stack.yaml
-> m (Maybe (Path Abs File))
getProjectConfig (Just stackYaml) = return $ Just stackYaml
getProjectConfig Nothing = do
env <- liftIO getEnvironment
case lookup "STACK_YAML" env of
Just fp -> do
$logInfo "Getting project config file from STACK_YAML environment"
liftM Just $ case parseAbsFile fp of
Left _ -> do
currDir <- getWorkingDir
resolveFile currDir fp
Right path -> return path
Nothing -> do
currDir <- getWorkingDir
search currDir
where
search dir = do
let fp = dir </> stackDotYaml
fp' = toFilePath fp
$logDebug $ "Checking for project config at: " <> T.pack fp'
exists <- fileExists fp
if exists
then return $ Just fp
else do
let dir' = parent dir
if dir == dir'
-- fully traversed, give up
then return Nothing
else search dir'
-- | Find the project config file location, respecting environment variables
-- and otherwise traversing parents. If no config is found, we supply a default
-- based on current directory.
loadProjectConfig :: (MonadIO m, MonadThrow m, MonadLogger m)
=> Maybe (Path Abs File)
-- ^ Override stack.yaml
-> m (Maybe (Project, Path Abs File, ConfigMonoid))
loadProjectConfig mstackYaml = do
mfp <- getProjectConfig mstackYaml
case mfp of
Just fp -> do
currDir <- getWorkingDir
$logDebug $ "Loading project config file " <>
T.pack (maybe (toFilePath fp) toFilePath (stripDir currDir fp))
load fp
Nothing -> do
$logDebug $ "No project config file found, using defaults."
return Nothing
where
load fp = do
ProjectAndConfigMonoid project config <- loadYaml fp
return $ Just (project, fp, config)
packagesParser :: Parser [String]
packagesParser = many (strOption (long "package" <> help "Additional packages that must be installed"))
| GaloisInc/stack | src/Stack/Config.hs | bsd-3-clause | 20,212 | 0 | 30 | 5,960 | 4,472 | 2,248 | 2,224 | 393 | 7 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import GHC.IO.Exception (ExitCode(..))
import System.Exit (die)
import Data.Monoid ((<>))
import Control.Applicative (empty)
import Data.Aeson
import Turtle.Prelude (procStrictWithErr, shell)
import qualified Data.ByteString.Lazy as BS
import System.Directory (getAppUserDataDirectory)
import System.FilePath ((</>))
import Data.Text (unpack, Text)
import qualified Data.Text.IO as T
data Packages = Packages {
patched :: [Text],
vanilla :: [Text]
} deriving (Show, Eq, Ord)
instance FromJSON Packages where
parseJSON (Object v) = Packages <$> v.: "patched" <*> v.: "vanilla"
parseJSON _ = empty
parsePackagesFile :: FilePath -> IO (Maybe Packages)
parsePackagesFile fname = do
contents <- BS.readFile fname
let packages = decode contents
return packages
packagesFilePath :: IO FilePath
packagesFilePath = (</> "patches" </> "packages.json") <$> getAppUserDataDirectory "epm"
buildPackage :: Text -> IO ()
buildPackage pkg = do
let args = ["install", pkg]
(exitCode, out, err) <- procStrictWithErr "epm" args empty
case exitCode of
ExitSuccess -> T.putStr out
ExitFailure x -> T.putStr err >> die ("error in building " <> unpack pkg)
return ()
main :: IO ()
main = do
let vmUpdateCmd = "epm update"
shell vmUpdateCmd ""
epmPkgs <- packagesFilePath
pkg <- parsePackagesFile epmPkgs
case pkg of
Nothing -> die "Problem parsing your packages.json file"
Just pkg' ->
let packages = (patched pkg') <> (vanilla pkg')
in mapM_ buildPackage packages
| alexander-at-github/eta | tests/packages/Test.hs | bsd-3-clause | 1,599 | 0 | 16 | 313 | 518 | 273 | 245 | 46 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Init.Heuristics
-- Copyright : (c) Benedikt Huber 2009
-- License : BSD-like
--
-- Maintainer : cabal-devel@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Heuristics for creating initial cabal files.
--
-----------------------------------------------------------------------------
module Distribution.Client.Init.Heuristics (
guessPackageName,
scanForModules, SourceFileEntry(..),
neededBuildPrograms,
guessMainFileCandidates,
guessAuthorNameMail,
knownCategories,
) where
import Distribution.Text (simpleParse)
import Distribution.Simple.Setup (Flag(..), flagToMaybe)
import Distribution.ModuleName
( ModuleName, toFilePath )
import Distribution.Client.PackageIndex
( allPackagesByName )
import qualified Distribution.Package as P
import qualified Distribution.PackageDescription as PD
( category, packageDescription )
import Distribution.Simple.Utils
( intercalate )
import Distribution.Client.Utils
( tryCanonicalizePath )
import Language.Haskell.Extension ( Extension )
import Distribution.Client.Types ( packageDescription, SourcePackageDb(..) )
import Control.Applicative ( pure, (<$>), (<*>) )
import Control.Arrow ( first )
import Control.Monad ( liftM )
import Data.Char ( isAlphaNum, isNumber, isUpper, isLower, isSpace )
import Data.Either ( partitionEithers )
import Data.List ( isInfixOf, isPrefixOf, isSuffixOf, sortBy )
import Data.Maybe ( mapMaybe, catMaybes, maybeToList )
import Data.Monoid ( mempty, mappend, mconcat, )
import Data.Ord ( comparing )
import qualified Data.Set as Set ( fromList, toList )
import System.Directory ( getCurrentDirectory, getDirectoryContents,
doesDirectoryExist, doesFileExist, getHomeDirectory, )
import Distribution.Compat.Environment ( getEnvironment )
import System.FilePath ( takeExtension, takeBaseName, dropExtension,
(</>), (<.>), splitDirectories, makeRelative )
import Distribution.Client.Init.Types ( InitFlags(..) )
import Distribution.Client.Compat.Process ( readProcessWithExitCode )
import System.Exit ( ExitCode(..) )
-- | Return a list of candidate main files for this executable: top-level
-- modules including the word 'Main' in the file name. The list is sorted in
-- order of preference, shorter file names are preferred. 'Right's are existing
-- candidates and 'Left's are those that do not yet exist.
guessMainFileCandidates :: InitFlags -> IO [Either FilePath FilePath]
guessMainFileCandidates flags = do
dir <-
maybe getCurrentDirectory return (flagToMaybe $ packageDir flags)
files <- getDirectoryContents dir
let existingCandidates = filter isMain files
-- We always want to give the user at least one default choice. If either
-- Main.hs or Main.lhs has already been created, then we don't want to
-- suggest the other; however, if neither has been created, then we
-- suggest both.
newCandidates =
if any (`elem` existingCandidates) ["Main.hs", "Main.lhs"]
then []
else ["Main.hs", "Main.lhs"]
candidates =
sortBy (\x y -> comparing (length . either id id) x y
`mappend` compare x y)
(map Left newCandidates ++ map Right existingCandidates)
return candidates
where
isMain f = (isInfixOf "Main" f || isInfixOf "main" f)
&& (isSuffixOf ".hs" f || isSuffixOf ".lhs" f)
-- | Guess the package name based on the given root directory.
guessPackageName :: FilePath -> IO P.PackageName
guessPackageName = liftM (P.PackageName . repair . last . splitDirectories)
. tryCanonicalizePath
where
-- Treat each span of non-alphanumeric characters as a hyphen. Each
-- hyphenated component of a package name must contain at least one
-- alphabetic character. An arbitrary character ('x') will be prepended if
-- this is not the case for the first component, and subsequent components
-- will simply be run together. For example, "1+2_foo-3" will become
-- "x12-foo3".
repair = repair' ('x' :) id
repair' invalid valid x = case dropWhile (not . isAlphaNum) x of
"" -> repairComponent ""
x' -> let (c, r) = first repairComponent $ break (not . isAlphaNum) x'
in c ++ repairRest r
where
repairComponent c | all isNumber c = invalid c
| otherwise = valid c
repairRest = repair' id ('-' :)
-- |Data type of source files found in the working directory
data SourceFileEntry = SourceFileEntry
{ relativeSourcePath :: FilePath
, moduleName :: ModuleName
, fileExtension :: String
, imports :: [ModuleName]
, extensions :: [Extension]
} deriving Show
sfToFileName :: FilePath -> SourceFileEntry -> FilePath
sfToFileName projectRoot (SourceFileEntry relPath m ext _ _)
= projectRoot </> relPath </> toFilePath m <.> ext
-- |Search for source files in the given directory
-- and return pairs of guessed Haskell source path and
-- module names.
scanForModules :: FilePath -> IO [SourceFileEntry]
scanForModules rootDir = scanForModulesIn rootDir rootDir
scanForModulesIn :: FilePath -> FilePath -> IO [SourceFileEntry]
scanForModulesIn projectRoot srcRoot = scan srcRoot []
where
scan dir hierarchy = do
entries <- getDirectoryContents (projectRoot </> dir)
(files, dirs) <- liftM partitionEithers (mapM (tagIsDir dir) entries)
let modules = catMaybes [ guessModuleName hierarchy file
| file <- files
, isUpper (head file) ]
modules' <- mapM (findImportsAndExts projectRoot) modules
recMods <- mapM (scanRecursive dir hierarchy) dirs
return $ concat (modules' : recMods)
tagIsDir parent entry = do
isDir <- doesDirectoryExist (parent </> entry)
return $ (if isDir then Right else Left) entry
guessModuleName hierarchy entry
| takeBaseName entry == "Setup" = Nothing
| ext `elem` sourceExtensions =
SourceFileEntry <$> pure relRoot <*> modName <*> pure ext <*> pure [] <*> pure []
| otherwise = Nothing
where
relRoot = makeRelative projectRoot srcRoot
unqualModName = dropExtension entry
modName = simpleParse
$ intercalate "." . reverse $ (unqualModName : hierarchy)
ext = case takeExtension entry of '.':e -> e; e -> e
scanRecursive parent hierarchy entry
| isUpper (head entry) = scan (parent </> entry) (entry : hierarchy)
| isLower (head entry) && not (ignoreDir entry) =
scanForModulesIn projectRoot $ foldl (</>) srcRoot (reverse (entry : hierarchy))
| otherwise = return []
ignoreDir ('.':_) = True
ignoreDir dir = dir `elem` ["dist", "_darcs"]
findImportsAndExts :: FilePath -> SourceFileEntry -> IO SourceFileEntry
findImportsAndExts projectRoot sf = do
s <- readFile (sfToFileName projectRoot sf)
let modules = mapMaybe
( getModName
. drop 1
. filter (not . null)
. dropWhile (/= "import")
. words
)
. filter (not . ("--" `isPrefixOf`)) -- poor man's comment filtering
. lines
$ s
-- XXX we should probably make a better attempt at parsing
-- comments above. Unfortunately we can't use a full-fledged
-- Haskell parser since cabal's dependencies must be kept at a
-- minimum.
-- A poor man's LANGUAGE pragma parser.
exts = mapMaybe simpleParse
. concatMap getPragmas
. filter isLANGUAGEPragma
. map fst
. drop 1
. takeWhile (not . null . snd)
. iterate (takeBraces . snd)
$ ("",s)
takeBraces = break (== '}') . dropWhile (/= '{')
isLANGUAGEPragma = ("{-# LANGUAGE " `isPrefixOf`)
getPragmas = map trim . splitCommas . takeWhile (/= '#') . drop 13
splitCommas "" = []
splitCommas xs = x : splitCommas (drop 1 y)
where (x,y) = break (==',') xs
return sf { imports = modules
, extensions = exts
}
where getModName :: [String] -> Maybe ModuleName
getModName [] = Nothing
getModName ("qualified":ws) = getModName ws
getModName (ms:_) = simpleParse ms
-- Unfortunately we cannot use the version exported by Distribution.Simple.Program
knownSuffixHandlers :: [(String,String)]
knownSuffixHandlers =
[ ("gc", "greencard")
, ("chs", "chs")
, ("hsc", "hsc2hs")
, ("x", "alex")
, ("y", "happy")
, ("ly", "happy")
, ("cpphs", "cpp")
]
sourceExtensions :: [String]
sourceExtensions = "hs" : "lhs" : map fst knownSuffixHandlers
neededBuildPrograms :: [SourceFileEntry] -> [String]
neededBuildPrograms entries =
[ handler
| ext <- nubSet (map fileExtension entries)
, handler <- maybeToList (lookup ext knownSuffixHandlers)
]
-- | Guess author and email using darcs and git configuration options. Use
-- the following in decreasing order of preference:
--
-- 1. vcs env vars ($DARCS_EMAIL, $GIT_AUTHOR_*)
-- 2. Local repo configs
-- 3. Global vcs configs
-- 4. The generic $EMAIL
--
-- Name and email are processed separately, so the guess might end up being
-- a name from DARCS_EMAIL and an email from git config.
--
-- Darcs has preference, for tradition's sake.
guessAuthorNameMail :: IO (Flag String, Flag String)
guessAuthorNameMail = fmap authorGuessPure authorGuessIO
-- Ordered in increasing preference, since Flag-as-monoid is identical to
-- Last.
authorGuessPure :: AuthorGuessIO -> AuthorGuess
authorGuessPure (AuthorGuessIO env darcsLocalF darcsGlobalF gitLocal gitGlobal)
= mconcat
[ emailEnv env
, gitGlobal
, darcsCfg darcsGlobalF
, gitLocal
, darcsCfg darcsLocalF
, gitEnv env
, darcsEnv env
]
authorGuessIO :: IO AuthorGuessIO
authorGuessIO = AuthorGuessIO
<$> getEnvironment
<*> (maybeReadFile $ "_darcs" </> "prefs" </> "author")
<*> (maybeReadFile =<< liftM (</> (".darcs" </> "author")) getHomeDirectory)
<*> gitCfg Local
<*> gitCfg Global
-- Types and functions used for guessing the author are now defined:
type AuthorGuess = (Flag String, Flag String)
type Enviro = [(String, String)]
data GitLoc = Local | Global
data AuthorGuessIO = AuthorGuessIO
Enviro -- ^ Environment lookup table
(Maybe String) -- ^ Contents of local darcs author info
(Maybe String) -- ^ Contents of global darcs author info
AuthorGuess -- ^ Git config --local
AuthorGuess -- ^ Git config --global
darcsEnv :: Enviro -> AuthorGuess
darcsEnv = maybe mempty nameAndMail . lookup "DARCS_EMAIL"
gitEnv :: Enviro -> AuthorGuess
gitEnv env = (name, mail)
where
name = maybeFlag "GIT_AUTHOR_NAME" env
mail = maybeFlag "GIT_AUTHOR_EMAIL" env
darcsCfg :: Maybe String -> AuthorGuess
darcsCfg = maybe mempty nameAndMail
emailEnv :: Enviro -> AuthorGuess
emailEnv env = (mempty, mail)
where
mail = maybeFlag "EMAIL" env
gitCfg :: GitLoc -> IO AuthorGuess
gitCfg which = do
name <- gitVar which "user.name"
mail <- gitVar which "user.email"
return (name, mail)
gitVar :: GitLoc -> String -> IO (Flag String)
gitVar which = fmap happyOutput . gitConfigQuery which
happyOutput :: (ExitCode, a, t) -> Flag a
happyOutput v = case v of
(ExitSuccess, s, _) -> Flag s
_ -> mempty
gitConfigQuery :: GitLoc -> String -> IO (ExitCode, String, String)
gitConfigQuery which key =
fmap trim' $ readProcessWithExitCode "git" ["config", w, key] ""
where
w = case which of
Local -> "--local"
Global -> "--global"
trim' (a, b, c) = (a, trim b, c)
maybeFlag :: String -> Enviro -> Flag String
maybeFlag k = maybe mempty Flag . lookup k
-- | Read the first non-comment, non-trivial line of a file, if it exists
maybeReadFile :: String -> IO (Maybe String)
maybeReadFile f = do
exists <- doesFileExist f
if exists
then fmap getFirstLine $ readFile f
else return Nothing
where
getFirstLine content =
let nontrivialLines = dropWhile (\l -> (null l) || ("#" `isPrefixOf` l)) . lines $ content
in case nontrivialLines of
[] -> Nothing
(l:_) -> Just l
-- |Get list of categories used in Hackage. NOTE: Very slow, needs to be cached
knownCategories :: SourcePackageDb -> [String]
knownCategories (SourcePackageDb sourcePkgIndex _) = nubSet
[ cat | pkg <- map head (allPackagesByName sourcePkgIndex)
, let catList = (PD.category . PD.packageDescription . packageDescription) pkg
, cat <- splitString ',' catList
]
-- Parse name and email, from darcs pref files or environment variable
nameAndMail :: String -> (Flag String, Flag String)
nameAndMail str
| all isSpace nameOrEmail = mempty
| null erest = (mempty, Flag $ trim nameOrEmail)
| otherwise = (Flag $ trim nameOrEmail, Flag mail)
where
(nameOrEmail,erest) = break (== '<') str
(mail,_) = break (== '>') (tail erest)
trim :: String -> String
trim = removeLeadingSpace . reverse . removeLeadingSpace . reverse
where
removeLeadingSpace = dropWhile isSpace
-- split string at given character, and remove whitespace
splitString :: Char -> String -> [String]
splitString sep str = go str where
go s = if null s' then [] else tok : go rest where
s' = dropWhile (\c -> c == sep || isSpace c) s
(tok,rest) = break (==sep) s'
nubSet :: (Ord a) => [a] -> [a]
nubSet = Set.toList . Set.fromList
{-
test db testProjectRoot = do
putStrLn "Guessed package name"
(guessPackageName >=> print) testProjectRoot
putStrLn "Guessed name and email"
guessAuthorNameMail >>= print
mods <- scanForModules testProjectRoot
putStrLn "Guessed modules"
mapM_ print mods
putStrLn "Needed build programs"
print (neededBuildPrograms mods)
putStrLn "List of known categories"
print $ knownCategories db
-}
| plumlife/cabal | cabal-install/Distribution/Client/Init/Heuristics.hs | bsd-3-clause | 14,315 | 0 | 20 | 3,520 | 3,416 | 1,845 | 1,571 | 251 | 4 |
{-# LANGUAGE DeriveGeneric #-}
module Competition where
import Data.Aeson
import GHC.Generics
data Competition = Competition
{ id :: Int
, caption :: String
, league :: String
, year :: String
, currentMatchday :: Int
, numberOfMatchdays :: Int
, numberOfTeams :: Int
, numberOfGames :: Int
, lastUpdated :: String
, _links :: Links
} deriving (Show, Generic)
data Links = Links
{ self :: Link
, teams :: Link
, fixtures :: Link
, leagueTable :: Link
} deriving (Show, Generic)
data Link = Link
{ href :: String
} deriving (Show, Generic)
instance FromJSON Competition
instance FromJSON Links
instance FromJSON Link
| julienXX/football-data-client | src/Competition.hs | bsd-3-clause | 658 | 0 | 8 | 146 | 186 | 112 | 74 | 28 | 0 |
module Arp (doArp, main) where
import Control.Concurrent
import qualified Data.Map as Map
import Data.ByteString.Lazy (ByteString)
import Data.Word
import Frenetic.NetCore
import Frenetic.NetworkFrames (arpReply)
import MacLearning (learningSwitch)
import System.Log.Logger
type IpMap = Map.Map IPAddress EthernetAddress
-- See RFC 826 for ARP specification
-- Note that the OpenFlow spec uses the Nw* fields for both IP packets and ARP
-- packets, which is how nwProto matches the ARP query/reply field.
-- Ethertype for ARP packets
isArp = DlTyp 0x0806
-- Numbers from ARP protocol
isQuery = isArp <&&> NwProto 1
isReply = isArp <&&> NwProto 2
known ips = prOr . map (\ip -> NwDst (IPAddressPrefix ip 32)) $ Map.keys ips
-- |Maybe produce a reply packet from an ARP request.
-- Try to look up the IP address in the lookup table. If there's an associated
-- MAC address, build an ARP reply packet, otherwise return Nothing. It's
-- possible that we get a malformed packet that doesn't have one or more of the
-- IP src or dst fields, in which case also return Nothing.
handleQuery :: LocPacket -> IpMap -> Maybe (Loc, ByteString)
handleQuery (Loc switch port, Packet {..}) ips =
case pktNwDst of
Nothing -> Nothing
Just toIp ->
case Map.lookup toIp ips of
Nothing -> Nothing
Just toMac ->
case pktNwSrc of
Nothing -> Nothing
Just fromIp -> Just (Loc switch port,
arpReply toMac
(ipAddressToWord32 toIp)
pktDlSrc
(ipAddressToWord32 fromIp))
-- |Maybe produce a new IP address map from an ARP reply.
-- Try to parse the packet, and if you can, and it's a new mapping, return the
-- new map. Otherwise, return Nothing to signal that we didn't learn something
-- new so it's not necessary to update the policy.
handleReply :: LocPacket -> IpMap -> Maybe IpMap
handleReply (Loc switch _, packet) ips =
let fromMac = pktDlSrc packet in
case pktNwSrc packet of
Nothing -> Nothing
Just fromIp ->
-- If we already know about the MAC address of the reply, do nothing.
if Map.member fromIp ips then Nothing
-- Otherwise, update the IP address map
else Just (Map.insert fromIp fromMac ips)
-- |Use the controller as an ARP cache with an underlying routing policy.
-- This is parameterized on a channel that yields policies that provide basic
-- host-to-host connectivity. The simplest implementation simplhy floods
-- packets, but more sophisticated options might include a learning switch, or a
-- topology-based shortest path approach.
doArp :: Chan Policy -> IO (Chan Policy)
doArp routeChan = do
(queryChan, queryAction) <- getPkts
(replyChan, replyAction) <- getPkts
dataChan <- select queryChan replyChan
allChan <- select routeChan dataChan
packetOutChan <- newChan
policyOutChan <- newChan
-- The overall architecture of the loop:
-- * allChan aggregates everything that may cause us to update. It's either
-- ** A new routing policy for the underlying connectivity,
-- ** An ARP query packet, or
-- ** An ARP reply packet.
--
-- During the loop, we need to track two pieces of data:
-- * The current underlying connectivity policy, which may be Nothing if we
-- haven't learned one yet, and
-- * A map from IP addresses to MAC addresses, which stores the ARP lookups
-- which we already know about.
--
-- Ultimately, we need to generate a new routing and packet query policy that
-- routes the ARP packets we're not going to handle, plus installs the packet
-- receiving actions to query the packets we want to either reply to or learn
-- from.
let buildPolicy route ips = route' <+> query <+> reply <+>
SendPackets packetOutChan
where
-- First, we define whether we can reply to a particular packet as
-- whether it is an ARP query (thus, it wants a reply) for an IP address
-- which we've already learned the MAC address for.
canReply = isQuery <&&> known ips
-- We want to provide connectivity for all packets except the ones we're
-- going to reply to directly. We want to drop those because we're
-- going to handle them, so there's no use in them reaching other hosts.
route' = route <%> Not canReply
-- The corollary to this is that we need to query all the packets that
-- we can reply to so that the controller can send an ARP packet their
-- way.
query = canReply ==> queryAction
-- We also want to spy on (but not impede forwarding of) ARP reply
-- packets so that we can learn the sender's IP and MAC addresses,
-- letting us reply from the controller next time.
reply = isReply <&&> Not (known ips) ==> replyAction
let loop mRoute ips = do
update <- readChan allChan
case update of
Left route -> do
-- If we get a new connectivity policy in, we recompile our overall
-- policy, send that out, and recurse on the new route.
infoM "ARP" "Got new routing policy for ARP"
writeChan policyOutChan (buildPolicy route ips)
loop (Just route) ips
Right arpData ->
case mRoute of
-- If we don't have a routing policy yet, we're not even providing
-- connectivity, so it's probably a spurious packet and we can just
-- ignore it.
Nothing -> loop Nothing ips
Just route ->
case arpData of
Left query ->
-- If we get an ARP query, try to form a response to it. If
-- we can, send the packet out, otherwise do nothing. Either
-- way, recurse.
case handleQuery query ips of
Nothing -> loop mRoute ips
Just packet -> do
infoM "ARP" $ "Sending ARP reply: " ++ show packet
writeChan packetOutChan packet
loop mRoute ips
Right reply ->
-- If we get an ARP reply, try to learn from it. If we
-- learned a new mapping, update the routing and query policy
-- to reflect the fact that we're going to handle these
-- packets in the future and recurse on the new mapping.
-- Otherwise, just recurse.
case handleReply reply ips of
Nothing -> loop mRoute ips
Just ips' -> do
infoM "ARP" $ "Learned ARP route from " ++ show reply
writeChan policyOutChan (buildPolicy route ips')
loop mRoute ips'
forkIO (loop Nothing Map.empty)
return policyOutChan
-- |Runs ARP on top of a learning switch to gradually learn both routes and the
-- ARP table. Provides both regular connectivity and synthetic ARP replies.
main addr = do
lsChan <- learningSwitch
policyChan <- doArp lsChan
dynController addr policyChan
| frenetic-lang/netcore-1.0 | examples/Arp.hs | bsd-3-clause | 7,162 | 0 | 28 | 2,139 | 972 | 499 | 473 | -1 | -1 |
{-# LANGUAGE GADTs, DataKinds, TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell#-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module QueryAlgebras where
import Types
import Control.Error
import Control.Monad.Free
import Data.Singletons.TH
data VFCrudable = UserCrud
| MediaCrud
| VfileCrud
| MediaVfileCrud
| CommentCrud CommentType
deriving (Show)
genSingletons [ ''VFCrudable ]
type family NewData (c :: VFCrudable) :: * where
NewData 'UserCrud = UserNew
NewData 'MediaCrud = MediaNew
NewData 'VfileCrud = VfileNew
NewData 'MediaVfileCrud = MediaVfileNew
NewData ('CommentCrud ct) = CommentNew ct
type family BaseData (c :: VFCrudable) :: * where
BaseData 'UserCrud = UserBase
BaseData 'MediaCrud = MediaBase 'DB
BaseData 'VfileCrud = VfileBase 'DB
BaseData 'MediaVfileCrud = MediaVfileBase 'DB
BaseData ('CommentCrud ct) = CommentBase ct 'DB
type family ReadData (c :: VFCrudable) :: * where
ReadData 'UserCrud = UserId
ReadData 'MediaCrud = MediaId
ReadData 'VfileCrud = VfileId
ReadData 'MediaVfileCrud = MVFIdentifier
ReadData ('CommentCrud ct) = CommentIdentifier ct
--------------------------------------------------------------------------------
-- | Basic PG-CRUD operations
--------------------------------------------------------------------------------
data PGCrudF next :: * where
CreatePG :: Sing (c :: VFCrudable)
-> NewData c
-> (Either VfilesError (BaseData c) -> next)
-> PGCrudF next
ReadPG :: Sing (c :: VFCrudable)
-> ReadData c
-> (Either VfilesError (BaseData c) -> next)
-> PGCrudF next
UpdatePG :: Sing (c :: VFCrudable)
-> BaseData c
-> (Either VfilesError () -> next)
-> PGCrudF next
DeletePG :: Sing (c :: VFCrudable)
-> ReadData c
-> (Either VfilesError () -> next)
-> PGCrudF next
instance Functor PGCrudF where
fmap f (CreatePG c n next) = CreatePG c n $ f . next
fmap f (ReadPG c i next) = ReadPG c i $ f . next
fmap f (UpdatePG c b next) = UpdatePG c b $ f . next
fmap f (DeletePG c i next) = DeletePG c i $ f . next
type PGCrud = ExceptT VfilesError (Free PGCrudF)
--------------------------------------------------------------------------------
-- | Smart PG-CRUD Constructors
--------------------------------------------------------------------------------
createPG :: Sing (c :: VFCrudable) -> NewData c -> PGCrud (BaseData c)
createPG c n = ExceptT . Free $ CreatePG c n Pure
readPG :: Sing (c :: VFCrudable) -> ReadData c -> PGCrud (BaseData c)
readPG c n = ExceptT . Free $ ReadPG c n Pure
updatePG :: Sing (c :: VFCrudable) -> BaseData c -> PGCrud ()
updatePG c n = ExceptT . Free $ UpdatePG c n Pure
deletePG :: Sing (c :: VFCrudable) -> ReadData c -> PGCrud ()
deletePG c n = ExceptT . Free $ DeletePG c n Pure
--------------------------------------------------------------------------------
-- | PG-CRUD Permissions
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- | Basic Neo-CRUD operations
--------------------------------------------------------------------------------
data NeoCrudF next :: * where
CreateNeo :: Sing (c :: VFCrudable)
-> BaseData c
-> (Either VfilesError () -> next)
-> NeoCrudF next
UpdateNeo :: Sing (c :: VFCrudable)
-> BaseData c
-> (Either VfilesError () -> next)
-> NeoCrudF next
DeleteNeo :: Sing (c :: VFCrudable)
-> ReadData c
-> (Either VfilesError () -> next)
-> NeoCrudF next
instance Functor NeoCrudF where
fmap f (CreateNeo c n next) = CreateNeo c n $ f . next
fmap f (UpdateNeo c b next) = UpdateNeo c b $ f . next
fmap f (DeleteNeo c i next) = DeleteNeo c i $ f . next
type NeoCrud = ExceptT VfilesError (Free NeoCrudF)
--------------------------------------------------------------------------------
-- | Smart Neo-CRUD Constructors
--------------------------------------------------------------------------------
createNeo :: Sing (c :: VFCrudable) -> BaseData c -> NeoCrud ()
createNeo c n = ExceptT . Free $ CreateNeo c n Pure
updateNeo :: Sing (c :: VFCrudable) -> BaseData c -> NeoCrud ()
updateNeo c n = ExceptT . Free $ UpdateNeo c n Pure
deleteNeo :: Sing (c :: VFCrudable) -> ReadData c -> NeoCrud ()
deleteNeo c n = ExceptT . Free $ DeleteNeo c n Pure
--------------------------------------------------------------------------------
-- | Composite Query Algebra
--------------------------------------------------------------------------------
data VFCrudF a = InPGCrud (PGCrudF a)
| InNeoCrud (NeoCrudF a)
instance Functor VFCrudF where
fmap f (InPGCrud a) = InPGCrud (fmap f a)
fmap f (InNeoCrud a) = InNeoCrud (fmap f a)
type VFCrud = ExceptT VfilesError (Free VFCrudF)
class Monad m => MonadPGCrud m where
liftPG :: forall a. PGCrud a -> m a
instance MonadPGCrud VFCrud where
liftPG = mapExceptT $ hoistFree InPGCrud
class Monad m => MonadNeoCrud m where
liftNeo :: forall a. NeoCrud a -> m a
instance MonadNeoCrud VFCrud where
liftNeo = mapExceptT $ hoistFree InNeoCrud
| martyall/freeapi | src/QueryAlgebras.hs | bsd-3-clause | 5,384 | 0 | 13 | 1,156 | 1,568 | 805 | 763 | 104 | 1 |
-- The @FamInst@ type: family instance heads
{-# LANGUAGE CPP, GADTs #-}
module FamInst (
FamInstEnvs, tcGetFamInstEnvs,
checkFamInstConsistency, tcExtendLocalFamInstEnv,
tcLookupFamInst,
tcLookupDataFamInst, tcLookupDataFamInst_maybe,
tcInstNewTyCon_maybe, tcTopNormaliseNewTypeTF_maybe,
newFamInst
) where
import HscTypes
import FamInstEnv
import InstEnv( roughMatchTcs )
import Coercion hiding ( substTy )
import TcEvidence
import LoadIface
import TcRnMonad
import TyCon
import CoAxiom
import DynFlags
import Module
import Outputable
import UniqFM
import FastString
import Util
import RdrName
import DataCon ( dataConName )
import Maybes
import TcMType
import TcType
import Name
import Control.Monad
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Arrow ( first, second )
#include "HsVersions.h"
{-
************************************************************************
* *
Making a FamInst
* *
************************************************************************
-}
-- All type variables in a FamInst must be fresh. This function
-- creates the fresh variables and applies the necessary substitution
-- It is defined here to avoid a dependency from FamInstEnv on the monad
-- code.
newFamInst :: FamFlavor -> CoAxiom Unbranched -> TcRnIf gbl lcl FamInst
-- Freshen the type variables of the FamInst branches
-- Called from the vectoriser monad too, hence the rather general type
newFamInst flavor axiom@(CoAxiom { co_ax_branches = FirstBranch branch
, co_ax_tc = fam_tc })
| CoAxBranch { cab_tvs = tvs
, cab_lhs = lhs
, cab_rhs = rhs } <- branch
= do { (subst, tvs') <- freshenTyVarBndrs tvs
; return (FamInst { fi_fam = tyConName fam_tc
, fi_flavor = flavor
, fi_tcs = roughMatchTcs lhs
, fi_tvs = tvs'
, fi_tys = substTys subst lhs
, fi_rhs = substTy subst rhs
, fi_axiom = axiom }) }
{-
************************************************************************
* *
Optimised overlap checking for family instances
* *
************************************************************************
For any two family instance modules that we import directly or indirectly, we
check whether the instances in the two modules are consistent, *unless* we can
be certain that the instances of the two modules have already been checked for
consistency during the compilation of modules that we import.
Why do we need to check? Consider
module X1 where module X2 where
data T1 data T2
type instance F T1 b = Int type instance F a T2 = Char
f1 :: F T1 a -> Int f2 :: Char -> F a T2
f1 x = x f2 x = x
Now if we import both X1 and X2 we could make (f2 . f1) :: Int -> Char.
Notice that neither instance is an orphan.
How do we know which pairs of modules have already been checked? Any pair of
modules where both modules occur in the `HscTypes.dep_finsts' set (of the
`HscTypes.Dependencies') of one of our directly imported modules must have
already been checked. Everything else, we check now. (So that we can be
certain that the modules in our `HscTypes.dep_finsts' are consistent.)
-}
-- The optimisation of overlap tests is based on determining pairs of modules
-- whose family instances need to be checked for consistency.
--
data ModulePair = ModulePair Module Module
-- canonical order of the components of a module pair
--
canon :: ModulePair -> (Module, Module)
canon (ModulePair m1 m2) | m1 < m2 = (m1, m2)
| otherwise = (m2, m1)
instance Eq ModulePair where
mp1 == mp2 = canon mp1 == canon mp2
instance Ord ModulePair where
mp1 `compare` mp2 = canon mp1 `compare` canon mp2
instance Outputable ModulePair where
ppr (ModulePair m1 m2) = angleBrackets (ppr m1 <> comma <+> ppr m2)
-- Sets of module pairs
--
type ModulePairSet = Map ModulePair ()
listToSet :: [ModulePair] -> ModulePairSet
listToSet l = Map.fromList (zip l (repeat ()))
checkFamInstConsistency :: [Module] -> [Module] -> TcM ()
checkFamInstConsistency famInstMods directlyImpMods
= do { dflags <- getDynFlags
; (eps, hpt) <- getEpsAndHpt
; let { -- Fetch the iface of a given module. Must succeed as
-- all directly imported modules must already have been loaded.
modIface mod =
case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of
Nothing -> panic "FamInst.checkFamInstConsistency"
Just iface -> iface
; hmiModule = mi_module . hm_iface
; hmiFamInstEnv = extendFamInstEnvList emptyFamInstEnv
. md_fam_insts . hm_details
; hpt_fam_insts = mkModuleEnv [ (hmiModule hmi, hmiFamInstEnv hmi)
| hmi <- eltsUFM hpt]
; groups = map (dep_finsts . mi_deps . modIface)
directlyImpMods
; okPairs = listToSet $ concatMap allPairs groups
-- instances of okPairs are consistent
; criticalPairs = listToSet $ allPairs famInstMods
-- all pairs that we need to consider
; toCheckPairs = Map.keys $ criticalPairs `Map.difference` okPairs
-- the difference gives us the pairs we need to check now
}
; mapM_ (check hpt_fam_insts) toCheckPairs
}
where
allPairs [] = []
allPairs (m:ms) = map (ModulePair m) ms ++ allPairs ms
check hpt_fam_insts (ModulePair m1 m2)
= do { env1 <- getFamInsts hpt_fam_insts m1
; env2 <- getFamInsts hpt_fam_insts m2
; mapM_ (checkForConflicts (emptyFamInstEnv, env2))
(famInstEnvElts env1) }
getFamInsts :: ModuleEnv FamInstEnv -> Module -> TcM FamInstEnv
getFamInsts hpt_fam_insts mod
| Just env <- lookupModuleEnv hpt_fam_insts mod = return env
| otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod)
; eps <- getEps
; return (expectJust "checkFamInstConsistency" $
lookupModuleEnv (eps_mod_fam_inst_env eps) mod) }
where
doc = ppr mod <+> ptext (sLit "is a family-instance module")
{-
************************************************************************
* *
Lookup
* *
************************************************************************
Look up the instance tycon of a family instance.
The match may be ambiguous (as we know that overlapping instances have
identical right-hand sides under overlapping substitutions - see
'FamInstEnv.lookupFamInstEnvConflicts'). However, the type arguments used
for matching must be equal to or be more specific than those of the family
instance declaration. We pick one of the matches in case of ambiguity; as
the right-hand sides are identical under the match substitution, the choice
does not matter.
Return the instance tycon and its type instance. For example, if we have
tcLookupFamInst 'T' '[Int]' yields (':R42T', 'Int')
then we have a coercion (ie, type instance of family instance coercion)
:Co:R42T Int :: T [Int] ~ :R42T Int
which implies that :R42T was declared as 'data instance T [a]'.
-}
tcLookupFamInst :: FamInstEnvs -> TyCon -> [Type] -> Maybe FamInstMatch
tcLookupFamInst fam_envs tycon tys
| not (isOpenFamilyTyCon tycon)
= Nothing
| otherwise
= case lookupFamInstEnv fam_envs tycon tys of
match : _ -> Just match
[] -> Nothing
-- | If @co :: T ts ~ rep_ty@ then:
--
-- > instNewTyCon_maybe T ts = Just (rep_ty, co)
--
-- Checks for a newtype, and for being saturated
-- Just like Coercion.instNewTyCon_maybe, but returns a TcCoercion
tcInstNewTyCon_maybe :: TyCon -> [TcType] -> Maybe (TcType, TcCoercion)
tcInstNewTyCon_maybe tc tys = fmap (second TcCoercion) $
instNewTyCon_maybe tc tys
-- | Like 'tcLookupDataFamInst_maybe', but returns the arguments back if
-- there is no data family to unwrap.
-- Returns a Representational coercion
tcLookupDataFamInst :: FamInstEnvs -> TyCon -> [TcType]
-> (TyCon, [TcType], Coercion)
tcLookupDataFamInst fam_inst_envs tc tc_args
| Just (rep_tc, rep_args, co)
<- tcLookupDataFamInst_maybe fam_inst_envs tc tc_args
= (rep_tc, rep_args, co)
| otherwise
= (tc, tc_args, mkReflCo Representational (mkTyConApp tc tc_args))
tcLookupDataFamInst_maybe :: FamInstEnvs -> TyCon -> [TcType]
-> Maybe (TyCon, [TcType], Coercion)
-- ^ Converts a data family type (eg F [a]) to its representation type (eg FList a)
-- and returns a coercion between the two: co :: F [a] ~R FList a
tcLookupDataFamInst_maybe fam_inst_envs tc tc_args
| isDataFamilyTyCon tc
, match : _ <- lookupFamInstEnv fam_inst_envs tc tc_args
, FamInstMatch { fim_instance = rep_fam
, fim_tys = rep_args } <- match
, let ax = famInstAxiom rep_fam
rep_tc = dataFamInstRepTyCon rep_fam
co = mkUnbranchedAxInstCo Representational ax rep_args
= Just (rep_tc, rep_args, co)
| otherwise
= Nothing
-- | 'tcTopNormaliseNewTypeTF_maybe' gets rid of top-level newtypes,
-- potentially looking through newtype instances.
--
-- It is only used by the type inference engine (specifically, when
-- soliving 'Coercible' instances), and hence it is careful to unwrap
-- only if the relevant data constructor is in scope. That's why
-- it get a GlobalRdrEnv argument.
--
-- It is careful not to unwrap data/newtype instances if it can't
-- continue unwrapping. Such care is necessary for proper error
-- messages.
--
-- It does not look through type families.
-- It does not normalise arguments to a tycon.
--
-- Always produces a representational coercion.
tcTopNormaliseNewTypeTF_maybe :: FamInstEnvs
-> GlobalRdrEnv
-> Type
-> Maybe (TcCoercion, Type)
tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty
-- cf. FamInstEnv.topNormaliseType_maybe and Coercion.topNormaliseNewType_maybe
= fmap (first TcCoercion) $ topNormaliseTypeX_maybe stepper ty
where
stepper = unwrap_newtype `composeSteppers` unwrap_newtype_instance
-- For newtype instances we take a double step or nothing, so that
-- we don't return the reprsentation type of the newtype instance,
-- which would lead to terrible error messages
unwrap_newtype_instance rec_nts tc tys
| Just (tc', tys', co) <- tcLookupDataFamInst_maybe faminsts tc tys
= modifyStepResultCo (co `mkTransCo`) $
unwrap_newtype rec_nts tc' tys'
| otherwise = NS_Done
unwrap_newtype rec_nts tc tys
| data_cons_in_scope tc
= unwrapNewTypeStepper rec_nts tc tys
| otherwise
= NS_Done
data_cons_in_scope :: TyCon -> Bool
data_cons_in_scope tc
= isWiredInName (tyConName tc) ||
(not (isAbstractTyCon tc) && all in_scope data_con_names)
where
data_con_names = map dataConName (tyConDataCons tc)
in_scope dc = not $ null $ lookupGRE_Name rdr_env dc
{-
************************************************************************
* *
Extending the family instance environment
* *
************************************************************************
-}
-- Add new locally-defined family instances
tcExtendLocalFamInstEnv :: [FamInst] -> TcM a -> TcM a
tcExtendLocalFamInstEnv fam_insts thing_inside
= do { env <- getGblEnv
; (inst_env', fam_insts') <- foldlM addLocalFamInst
(tcg_fam_inst_env env, tcg_fam_insts env)
fam_insts
; let env' = env { tcg_fam_insts = fam_insts'
, tcg_fam_inst_env = inst_env' }
; setGblEnv env' thing_inside
}
-- Check that the proposed new instance is OK,
-- and then add it to the home inst env
-- This must be lazy in the fam_inst arguments, see Note [Lazy axiom match]
-- in FamInstEnv.hs
addLocalFamInst :: (FamInstEnv,[FamInst]) -> FamInst -> TcM (FamInstEnv, [FamInst])
addLocalFamInst (home_fie, my_fis) fam_inst
-- home_fie includes home package and this module
-- my_fies is just the ones from this module
= do { traceTc "addLocalFamInst" (ppr fam_inst)
; isGHCi <- getIsGHCi
; mod <- getModule
; traceTc "alfi" (ppr mod $$ ppr isGHCi)
-- In GHCi, we *override* any identical instances
-- that are also defined in the interactive context
-- See Note [Override identical instances in GHCi] in HscTypes
; let home_fie'
| isGHCi = deleteFromFamInstEnv home_fie fam_inst
| otherwise = home_fie
-- Load imported instances, so that we report
-- overlaps correctly
; eps <- getEps
; let inst_envs = (eps_fam_inst_env eps, home_fie')
home_fie'' = extendFamInstEnv home_fie fam_inst
-- Check for conflicting instance decls
; no_conflict <- checkForConflicts inst_envs fam_inst
; if no_conflict then
return (home_fie'', fam_inst : my_fis)
else
return (home_fie, my_fis) }
{-
************************************************************************
* *
Checking an instance against conflicts with an instance env
* *
************************************************************************
Check whether a single family instance conflicts with those in two instance
environments (one for the EPS and one for the HPT).
-}
checkForConflicts :: FamInstEnvs -> FamInst -> TcM Bool
checkForConflicts inst_envs fam_inst
= do { let conflicts = lookupFamInstEnvConflicts inst_envs fam_inst
no_conflicts = null conflicts
; traceTc "checkForConflicts" $
vcat [ ppr (map fim_instance conflicts)
, ppr fam_inst
-- , ppr inst_envs
]
; unless no_conflicts $ conflictInstErr fam_inst conflicts
; return no_conflicts }
conflictInstErr :: FamInst -> [FamInstMatch] -> TcRn ()
conflictInstErr fam_inst conflictingMatch
| (FamInstMatch { fim_instance = confInst }) : _ <- conflictingMatch
= addFamInstsErr (ptext (sLit "Conflicting family instance declarations:"))
[fam_inst, confInst]
| otherwise
= panic "conflictInstErr"
addFamInstsErr :: SDoc -> [FamInst] -> TcRn ()
addFamInstsErr herald insts
= ASSERT( not (null insts) )
setSrcSpan srcSpan $ addErr $
hang herald
2 (vcat [ pprCoAxBranchHdr (famInstAxiom fi) 0
| fi <- sorted ])
where
getSpan = getSrcLoc . famInstAxiom
sorted = sortWith getSpan insts
fi1 = head sorted
srcSpan = coAxBranchSpan (coAxiomSingleBranch (famInstAxiom fi1))
-- The sortWith just arranges that instances are dislayed in order
-- of source location, which reduced wobbling in error messages,
-- and is better for users
tcGetFamInstEnvs :: TcM FamInstEnvs
-- Gets both the external-package inst-env
-- and the home-pkg inst env (includes module being compiled)
tcGetFamInstEnvs
= do { eps <- getEps; env <- getGblEnv
; return (eps_fam_inst_env eps, tcg_fam_inst_env env) }
| urbanslug/ghc | compiler/typecheck/FamInst.hs | bsd-3-clause | 16,229 | 0 | 14 | 4,715 | 2,539 | 1,349 | 1,190 | 206 | 3 |
module Main(main) where
import System.Environment
import System.IO
import CCodeGen
import Lexer
import Parser
import Program
main :: IO ()
main = do
(fileName:rest) <- getArgs
fileHandle <- openFile fileName ReadMode
programText <- hGetContents fileHandle
putStrLn programText
let compiledProg = compile programText
outFileName = cFileName fileName
writeFile outFileName compiledProg
hClose fileHandle
putStrLn compiledProg
compile :: String -> String
compile = show . toCProgram . parseProgram . strToToks
parsedProg = parseProgram . strToToks
cFileName :: String -> String
cFileName name = (takeWhile (/='.') name) ++ ".c" | dillonhuff/IntLang | src/Main.hs | bsd-3-clause | 654 | 0 | 10 | 113 | 196 | 99 | 97 | 23 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilyDependencies #-}
module Data.Diverse.WhichSpec (main, spec) where
import Data.Diverse
import Data.Int
import Data.Tagged
import Data.Typeable
import Test.Hspec
data Foo
data Bar
data Hi
data Bye
-- `main` is here so that this module can be run from GHCi on its own. It is
-- not needed for automatic spec discovery.
main :: IO ()
main = hspec spec
-- | Utility to convert Either to Maybe
hush :: Either a b -> Maybe b
hush = either (const Nothing) Just
spec :: Spec
spec = do
describe "Which" $ do
it "is a Show" $ do
let x = pickN @0 5 :: Which '[Int, Bool]
show x `shouldBe` "pickN @0 5"
it "is a Read and Show" $ do
let s1 = "pickN @0 5"
x1 = read s1 :: Which '[Int, Bool]
show x1 `shouldBe` s1
let s2 = "pickN @1 True"
x2 = read s2 :: Which '[Int, Bool]
show x2 `shouldBe` s2
-- "zilch" `shouldBe` show zilch
-- "zilch" `shouldBe` show (read "zilch" :: Which '[])
it "is an Eq" $ do
let y = pick (5 :: Int) :: Which '[Int, Bool]
let y' = pick (5 :: Int) :: Which '[Int, Bool]
y `shouldBe` y'
it "is an Ord" $ do
let y5 = pick (5 :: Int) :: Which '[Int, Bool]
let y6 = pick (6 :: Int) :: Which '[Int, Bool]
compare y5 y5 `shouldBe` EQ
compare y5 y6 `shouldBe` LT
compare y6 y5 `shouldBe` GT
it "can be constructed by type with 'pick' and destructed with 'trial'" $ do
let y = pick (5 :: Int) :: Which '[Bool, Int, Char]
x = hush $ trial @Int y
x `shouldBe` (Just 5)
it "can be constructed by label with 'pickL' and destructed with 'trialL'" $ do
let y = pickL @Foo (Tagged (5 :: Int)) :: Which '[Bool, Tagged Foo Int, Tagged Bar Char]
x = hush $ trialL @Foo y
x `shouldBe` (Just (Tagged 5))
it "may contain possiblities of duplicate types" $ do
let y = pick (5 :: Int) :: Which '[Bool, Int, Char, Bool, Char]
x = hush $ trial @Int y
x `shouldBe` (Just 5)
it "can be constructed conveniently with 'pick'' and destructed with 'trial0'" $ do
let y = pickOnly (5 :: Int)
x = hush $ trial0 y
x `shouldBe` (Just 5)
it "can be constructed by index with 'pickN' and destructed with 'trialN" $ do
let y = pickN @4 (5 :: Int) :: Which '[Bool, Int, Char, Bool, Int, Char]
x = hush $ trialN @4 y
x `shouldBe` (Just 5)
it "can be 'trial'led until its final 'obvious' value" $ do
let a = pick @_ @'[Char, Int, Bool, String] (5 :: Int)
b = pick @_ @'[Char, Int, String] (5 :: Int)
c = pick @_ @'[Int, String] (5 :: Int)
d = pick @_ @'[Int] (5 :: Int)
trial @Int a `shouldBe` Right 5
trial @Bool a `shouldBe` Left b
trial @Int b `shouldBe` Right 5
trial @Char b `shouldBe` Left c
trial @Int c `shouldBe` Right 5
trial @String c `shouldBe` Left d
trial @Int d `shouldBe` Right 5
-- trial @Int d `shouldNotBe` Left zilch
obvious d `shouldBe` 5
it "can be 'trialN'led until its final 'obvious' value" $ do
let a = pickN @2 @_ @'[Char, Bool, Int, Bool, Char, String] (5 :: Int)
b = pickN @2 @_ @'[Char, Bool, Int, Char, String] (5 :: Int)
c = pickN @2 @_ @'[Char, Bool, Int, String] (5 :: Int)
d = pickN @1 @_ @'[Bool, Int, String] (5 :: Int)
e = pickN @1 @_ @'[Bool, Int] (5 :: Int)
f = pickN @0 @_ @'[Int] (5 :: Int)
trial @Int a `shouldBe` Right 5
trialN @2 a `shouldBe` Right 5
trialN @3 a `shouldBe` Left b
trial @Int b `shouldBe` Right 5
trialN @2 b `shouldBe` Right 5
trialN @3 b `shouldBe` Left c
trial @Int c `shouldBe` Right 5
trialN @2 c `shouldBe` Right 5
trial0 c `shouldBe` Left d
trialN @0 c `shouldBe` Left d
trial @Int d `shouldBe` Right 5
trialN @1 d `shouldBe` Right 5
trialN @2 d `shouldBe` Left e
trial @Int e `shouldBe` Right 5
trialN @1 e `shouldBe` Right 5
trialN @0 e `shouldBe` Left f
trial0 e `shouldBe` Left f
trial @Int f `shouldBe` Right 5
-- trial @Int f `shouldNotBe` Left zilch
trial0 f `shouldBe` Right 5
obvious f `shouldBe` 5
it "can be extended and rearranged by type with 'diversify'" $ do
let y = pickOnly (5 :: Int)
y' = diversify @_ @[Int, Bool] y
y'' = diversify @_ @[Bool, Int] y'
switch y'' (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Int"
it "can be extended and rearranged by type with 'diversify'" $ do
let y = pickOnly (5 :: Tagged Bar Int)
y' = diversifyL @'[Bar] y :: Which '[Tagged Bar Int, Tagged Foo Bool]
y'' = diversifyL @'[Bar, Foo] y' :: Which '[Tagged Foo Bool, Tagged Bar Int]
switch y'' (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Tagged * Bar Int"
it "can be extended and rearranged by index with 'diversifyN'" $ do
let y = pickOnly (5 :: Int)
y' = diversifyN @'[0] @_ @[Int, Bool] y
y'' = diversifyN @[1,0] @_ @[Bool, Int] y'
switch y'' (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Int"
it "the 'diversify'ed type can contain multiple fields if they aren't in the original 'Many'" $ do
let y = pick @_ @[Int, Char] (5 :: Int)
x = diversify @_ @[String, String, Char, Bool, Int] y
-- Compile error: Char is a duplicate
-- z = diversify @[String, String, Char, Bool, Int, Char] y
x `shouldBe` pick (5 :: Int)
it "the 'diversify'ed type can't use indistinct fields from the original 'Many'" $ do
let y = pickN @0 @_ @[Int, Char, Int] (5 :: Int) -- duplicate Int
-- Compile error: Int is a duplicate
-- x = diversify @[String, String, Char, Bool, Int] y
y `shouldBe` y
it "can be 'reinterpret'ed by type into a totally different Which" $ do
let y = pick @_ @[Int, Char] (5 :: Int)
a = reinterpret @[String, Bool] y
a `shouldBe` Left y
let b = reinterpret @[String, Char] y
b `shouldBe` Left (pick (5 :: Int))
let c = reinterpret @[String, Int] y
c `shouldBe` Right (pick (5 :: Int))
it "can be 'reinterpretL'ed by label into a totally different Which" $ do
let y = pick @_ @[Tagged Bar Int, Tagged Foo Bool, Tagged Hi Char, Tagged Bye Bool] (5 :: Tagged Bar Int)
y' = reinterpretL @[Foo, Bar] y
x = pick @_ @[Tagged Foo Bool, Tagged Bar Int] (5 :: Tagged Bar Int)
y' `shouldBe` Right x
it "the 'reinterpret' type can contain indistinct fields if they aren't in the original 'Many'" $ do
let y = pick @_ @[Int, Char] (5 :: Int)
x = reinterpret @[String, String, Char, Bool] y
-- Compile error: Char is a duplicate
-- z = reinterpret @[String, Char, Char, Bool] y
x `shouldBe` Left (pick (5 :: Int))
it "the 'reinterpret'ed from type can't indistinct fields'" $ do
let y = pickN @0 @_ @[Int, Char, Int] (5 :: Int) -- duplicate Int
-- Compile error: Int is a duplicate
-- x = reinterpret @[String, String, Char, Bool] y
y `shouldBe` y
it "the 'reinterpret' type can't use indistinct fields from the original 'Many'" $ do
let y = pickN @0 @_ @[Int, Char, Int] (5 :: Int) -- duplicate Int
-- Compile error: Int is a duplicate
-- x = reinterpret @[String, String, Char, Bool, Int] y
y `shouldBe` y
it "can be 'reinterpretN'ed by index into a subset Which" $ do
let y = pick @_ @[Char, String, Int, Bool] (5 :: Int)
a = reinterpretN' @[2, 0] @[Int, Char] y
a' = reinterpretN' @[3, 0] @[Bool, Char] y
a `shouldBe` Just (pick (5 :: Int))
a' `shouldBe` Nothing
it "can be 'switch'ed with 'Many' handlers in any order" $ do
let y = pickN @0 (5 :: Int) :: Which '[Int, Bool, Bool, Int]
switch y (
cases $ show @Bool
./ show @Int
./ nil) `shouldBe` "5"
it "can be 'switch'ed with 'Many' handlers with extraneous content" $ do
let y = pick (5 :: Int) :: Which '[Int, Bool]
switch y (
-- contrast with lowercase 'cases' which disallows extraneous content
cases' $ show @Int
./ show @Bool
./ show @Char
./ show @(Maybe Char)
./ show @(Maybe Int)
./ nil
) `shouldBe` "5"
it "can be 'switchN'ed with 'Many' handlers in index order" $ do
let y = pickN @0 (5 :: Int) :: Which '[Int, Bool, Bool, Int]
switchN y (
casesN $ show @Int
./ show @Bool
./ show @Bool
./ show @Int
./ nil) `shouldBe` "5"
it "can be switched with a polymorphic 'CaseFunc' handler" $ do
let y = pick (5 :: Int) :: Which '[Int, Bool]
switch y (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Int"
#if __GLASGOW_HASKELL__ >= 802
let expected = "Which (': * Int (': * Bool ('[] *)))"
#else
let expected = "Which (': * Int (': * Bool '[]))"
#endif
(show . typeRep . (pure @Proxy) $ y) `shouldBe` expected
-- it "is a compile error to 'trial', 'diversify', 'reinterpret from non-zilch to 'zilch'" $ do
-- let a = diversify @[Int, Bool] zilch
-- let a = trial @Int zilch
-- let a = trialN @0 zilch
-- let a = reinterpret @[Int, Bool] zilch
-- let a = reinterpretN @'[0] zilch
-- zilch `shouldBe` zilch
it "is ok to 'reinterpret' and 'diversity' from Which '[]" $ do
let x = pick @_ @'[Int] (5 :: Int)
case trial @Int x of
Right y -> y `shouldBe` y
Left z -> do
-- Which '[] can be diversified into anything
-- This is safe because Which '[] is uninhabited like Data.Void
-- and so like Data.Void.absurd, "if given a falsehood, anything follows"
diversify @'[] @'[Int, Bool] z `shouldBe` impossible z
reinterpret' @'[] z `shouldBe` Just z
reinterpret @'[] z `shouldBe` Right z
diversify @'[] z `shouldBe` z
compare z z `shouldBe` EQ
reinterpret' @'[] x `shouldBe` Nothing
reinterpret @'[] x `shouldBe` Left x
it "'impossible' is just like 'absurd'. Once given an impossible Which '[], anything follows" $ do
let x = pick @_ @'[Int] (5 :: Int)
case trial @Int x of
Right y -> y `shouldBe` y
Left z -> impossible z
it "every possibility can be mapped into a different type in a Functor-like fashion with using 'afmap'" $ do
let x = pick (5 :: Int8) :: Which '[Int, Int8, Int16]
y = pick (15 :: Int8) :: Which '[Int, Int8, Int16]
z = pickN @1 ("5" :: String) :: Which '[String, String, String]
mx = pick (Just 5 :: Maybe Int8) :: Which '[Maybe Int, Maybe Int8, Maybe Int16]
my = pick (Just 15 :: Maybe Int8) :: Which '[Maybe Int, Maybe Int8, Maybe Int16]
mz = pickN @1 (Just "5" :: Maybe String) :: Which '[Maybe String, Maybe String, Maybe String]
mz' = pickN @1 (Just ("5", "5") :: Maybe (String, String)) :: Which '[Maybe (String, String), Maybe (String, String), Maybe (String, String)]
afmap (CaseFunc' @Num (+10)) x `shouldBe` y
afmap (CaseFunc @Show @String show) x `shouldBe` z
afmap (CaseFunc1' @C0 @Functor @Num (fmap (+10))) mx `shouldBe` my
afmap (CaseFunc1 @C0 @Functor @Show @String (fmap show)) mx `shouldBe` mz
afmap (CaseFunc1_ @C0 @Functor @C0 @(String, String) (fmap (\i -> (i, i)))) mz `shouldBe` mz'
| louispan/data-diverse | test/Data/Diverse/WhichSpec.hs | bsd-3-clause | 13,143 | 0 | 23 | 4,838 | 4,320 | 2,237 | 2,083 | -1 | -1 |
{-# LANGUAGE
MultiParamTypeClasses
, DefaultSignatures
, FlexibleInstances
, TypeSynonymInstances
, OverlappingInstances
#-}
-- |Used as the context for diagrams-ghci
module MyPrelude () where
import Prelude
import Data.List (intersperse)
import Data.Ratio
import Diagrams.Prelude
import Diagrams.Backend.Cairo
import Diagrams.TwoD.Path.Turtle
import Diagrams.TwoD.Text
import Graphics.UI.Toy.Gtk.Prelude
class GhcdiShow a where
-- First parameter is animation time
ghcdiShow :: a -> Double -> CairoDiagram
default ghcdiShow :: Show a => a -> Double -> CairoDiagram
ghcdiShow x _ = preText $ show x
-- You'd better be using cairo diagrams... :)
instance GhcdiShow CairoDiagram where
ghcdiShow d _ = d
listLike' :: String -> String -> String
-> [CairoDiagram] -> CairoDiagram
listLike' s m e = listLike (preText s) (preText m) (preText e)
listLike :: CairoDiagram -> CairoDiagram -> CairoDiagram
-> [CairoDiagram] -> CairoDiagram
listLike s m e xs = centerY (scale_it s) ||| inner ||| centerY (scale_it e)
where
inner = hcat . intersperse (m # translateY (max_height / (-2))) $ map centerY xs
max_height = maximum $ map height xs
ratio = max_height / height s
scale_it = scaleX (1 - (1 - ratio) / 5) . scaleY (ratio * 1.2)
instance GhcdiShow a => GhcdiShow [a] where
ghcdiShow xs t = listLike' "[" ", " "]" $ map (`ghcdiShow` t) xs
instance (GhcdiShow a, GhcdiShow b) => GhcdiShow (a, b) where
ghcdiShow (x, y) t
= listLike' "(" ", " ")" [ghcdiShow x t, ghcdiShow y t]
instance (GhcdiShow a, GhcdiShow b, GhcdiShow c)
=> GhcdiShow (a, b, c) where
ghcdiShow (x, y, u) t
= listLike' "(" ", " ")" [ghcdiShow x t, ghcdiShow y t, ghcdiShow u t]
instance (GhcdiShow a, GhcdiShow b, GhcdiShow c, GhcdiShow d)
=> GhcdiShow (a, b, c, d) where
ghcdiShow (x, y, u, v) t
= listLike' "(" ", " ")" [ghcdiShow x t, ghcdiShow y t, ghcdiShow u t, ghcdiShow v t]
ctxt = centerY . preText
cgs x = centerY . ghcdiShow x
instance GhcdiShow a => GhcdiShow (Maybe a) where
ghcdiShow Nothing _ = ctxt "Nothing"
ghcdiShow (Just x) t = ctxt "Just " ||| cgs x t
instance (GhcdiShow a, GhcdiShow b) => GhcdiShow (Either a b) where
ghcdiShow (Left x) t = ctxt "Right " ||| cgs x t
ghcdiShow (Right x) t = ctxt "Left " ||| cgs x t
instance (GhcdiShow a, Integral a) => GhcdiShow (Ratio a) where
ghcdiShow r t = centerX above === centerX (hrule bar_width) === centerX below
where
bar_width = max (width above) (width below)
above = ghcdiShow (numerator r) t
below = ghcdiShow (denominator r) t
instance GhcdiShow Int where
instance GhcdiShow Integer where
instance GhcdiShow Rational where
instance GhcdiShow Float where
instance GhcdiShow Char where
instance GhcdiShow Double where
instance GhcdiShow Bool where
instance GhcdiShow String where
| mgsloan/diagrams-ghci | MyPrelude.hs | bsd-3-clause | 2,872 | 0 | 16 | 613 | 1,051 | 544 | 507 | 65 | 1 |
import System.Nemesis
import System.Nemesis.Utils ((-))
import Prelude hiding ((-))
main = run - do
-- desc is optional, it gives some description to the task
-- task syntax: task "keyword: space seperated dependencies" io-action
desc "Hunter attack macro"
task "attack: pet-attack auto-attack" (putStrLn "attack macro done!")
desc "Pet attack"
task "pet-attack: mark" - do
sh "echo 'pet attack'"
desc "Hunter's mark"
task "mark" - do
sh "echo \"casting hunter's mark\""
desc "Auto attack"
task "auto-attack" - do
sh "echo 'auto shoot'"
| nfjinjing/nemesis | test/N2.hs | bsd-3-clause | 574 | 0 | 11 | 118 | 127 | 59 | 68 | 15 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.FMList
-- Copyright : (c) Sjoerd Visscher 2009
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : sjoerd@w3future.com
-- Stability : experimental
-- Portability : portable
--
-- FoldMap lists: lists represented by their 'foldMap' function.
--
-- Examples:
--
-- > -- A right-infinite list
-- > c = 1 `cons` c
--
-- > -- A left-infinite list
-- > d = d `snoc` 2
--
-- > -- A middle-infinite list ??
-- > e = c `append` d
--
-- > *> head e
-- > 1
-- > *> last e
-- > 2
-----------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
module Data.FMList (
FMList(..)
, transform
-- * Construction
, empty
, singleton
, cons
, snoc
, viewl
, viewr
, pair
, append
, fromList
, fromFoldable
-- * Basic functions
, null
, length
, genericLength
, head
, tail
, last
, init
, reverse
-- * Folding
, toList
, flatten
, foldMapA
, filter
, filterM
, take
, drop
, takeWhile
, dropWhile
, zip
, zipWith
-- * Unfolding
, iterate
, repeat
, cycle
, unfold
, unfoldr
-- * Transforming
, mapMaybe
, wither
) where
import Prelude
( (.), ($), ($!), flip, const, error, otherwise
, Either(..), either
, Bool(..), (&&)
, Ord(..), Num(..), Int
, Show(..), String, (++)
)
import qualified Prelude as P
import Data.Maybe (Maybe(..), maybe, fromMaybe, isNothing)
import Data.Monoid (Monoid, mempty, mappend, Dual(..), First(..), Last(..), Sum(..))
#if MIN_VERSION_base(4,9,0)
import Data.Semigroup (Semigroup)
import qualified Data.Semigroup as S
#endif
import Data.Foldable (Foldable, foldMap, foldr, toList)
import Data.Traversable (Traversable, traverse)
import Control.Monad hiding (filterM)
import Control.Monad.Fail as MF
import Control.Applicative
-- | 'FMList' is a 'foldMap' function wrapped up in a newtype.
--
newtype FMList a = FM { unFM :: forall m . Monoid m => (a -> m) -> m }
infixr 6 <>
-- We define our own (<>) instead of using the one from Data.Semigroup
-- or Data.Monoid. This has two advantages:
--
-- 1. It avoids certain annoying compatibility issues in constraints.
-- 2. In the situation (sadly common in this context) where things
-- don't specialize and we actually pass a Monoid dictionary, it's
-- faster to extract mempty from that dictionary than to first
-- extract the Semigroup superclass dictionary and then extract its
-- (<>) method.
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
{-# INLINE (<>) #-}
-- | The function 'transform' transforms a list by changing
-- the map function that is passed to 'foldMap'.
--
-- It has the following property:
--
-- @transform a . transform b = transform (b . a)@
--
-- For example:
--
-- * @ m >>= g@
--
-- * @= flatten (fmap g m)@
--
-- * @= flatten . fmap g $ m@
--
-- * @= transform foldMap . transform (. g) $ m@
--
-- * @= transform ((. g) . foldMap) m@
--
-- * @= transform (\\f -> foldMap f . g) m@
--
transform :: (forall m. Monoid m => (a -> m) -> (b -> m)) -> FMList b -> FMList a
transform t (FM l) = FM (l . t)
-- shorthand constructors
nil :: FMList a
nil = FM mempty
one :: a -> FMList a
one x = FM ($ x)
(><) :: FMList a -> FMList a -> FMList a
FM l >< FM r = FM (l `mappend` r)
-- exported constructors
singleton :: a -> FMList a
singleton = one
cons :: a -> FMList a -> FMList a
cons x l = one x >< l
snoc :: FMList a -> a -> FMList a
snoc l x = l >< one x
pair :: a -> a -> FMList a
pair l r = one l >< one r
append :: FMList a -> FMList a -> FMList a
append = (><)
fromList :: [a] -> FMList a
fromList = fromFoldable
fromFoldable :: Foldable f => f a -> FMList a
fromFoldable l = FM $ flip foldMap l
mhead :: FMList a -> Maybe a
mhead l = getFirst (unFM l (First . Just))
null :: FMList a -> Bool
null = isNothing . mhead
length :: FMList a -> Int
length = genericLength
genericLength :: Num b => FMList a -> b
genericLength l = getSum $ unFM l (const $ Sum 1)
infixl 5 :<
data ViewL a
= EmptyL
| a :< FMList a
deriving (Show, Functor, Foldable, Traversable)
unviewl :: ViewL a -> FMList a
unviewl EmptyL = nil
unviewl (x :< xs) = cons x xs
#if MIN_VERSION_base(4,9,0)
instance Semigroup (ViewL a) where
EmptyL <> v = v
(x :< xs) <> v = x :< (xs >< unviewl v)
#endif
instance Monoid (ViewL a) where
mempty = EmptyL
#if MIN_VERSION_base(4,9,0)
mappend = (S.<>)
#else
EmptyL `mappend` v = v
(x :< xs) `mappend` v = x :< (xs >< unviewl v)
#endif
infixr 5 :>
data ViewR a
= EmptyR
| FMList a :> a
deriving (Show, Functor, Foldable, Traversable)
unviewr :: ViewR a -> FMList a
unviewr EmptyR = nil
unviewr (xs :> x) = xs `snoc` x
#if MIN_VERSION_base(4,9,0)
instance Semigroup (ViewR a) where
v <> EmptyR = v
v <> (xs :> x) = (unviewr v >< xs) :> x
#endif
instance Monoid (ViewR a) where
mempty = EmptyR
#if MIN_VERSION_base(4,9,0)
mappend = (S.<>)
#else
v `mappend` EmptyR = v
v `mappend` (xs :> x) =(unviewr v >< xs) :> x
#endif
viewl :: FMList a -> ViewL a
viewl = foldMap (:< nil)
viewr :: FMList a -> ViewR a
viewr = foldMap (nil :>)
head :: FMList a -> a
head l = mhead l `fromMaybeOrError` "Data.FMList.head: empty list"
tail :: FMList a -> FMList a
tail l = case viewl l of
EmptyL -> error "Data.FMList.tail: empty list"
_ :< l' -> l'
last :: FMList a -> a
last l = getLast (unFM l (Last . Just)) `fromMaybeOrError` "Data.FMList.last: empty list"
init :: FMList a -> FMList a
init l = case viewr l of
EmptyR -> error "Data.FMList.init: empty list"
l' :> _ -> l'
reverse :: FMList a -> FMList a
reverse l = FM $ getDual . unFM l . (Dual .)
flatten :: Foldable t => FMList (t a) -> FMList a
flatten = transform foldMap
filter :: (a -> Bool) -> FMList a -> FMList a
filter p = transform (\f x -> if p x then f x else mempty)
mapMaybe :: (a -> Maybe b) -> FMList a -> FMList b
mapMaybe p = transform (\f x -> maybe mempty f (p x))
filterM :: Applicative m => (a -> m Bool) -> FMList a -> m (FMList a)
filterM p l = unWrapApp $ unFM l $ \a ->
let
go pr
| pr = one a
| otherwise = nil
in WrapApp $ fmap go (p a)
wither :: Applicative m => (a -> m (Maybe b)) -> FMList a -> m (FMList b)
wither p l = unWrapApp $ unFM l $ \a -> WrapApp $ fmap (maybe nil one) (p a)
-- transform the foldMap to foldr with state.
transformCS :: (forall m. Monoid m => (b -> m) -> a -> (m -> s -> m) -> s -> m) -> s -> FMList a -> FMList b
transformCS t s0 l = FM $ \f -> foldr (\e r -> t f e (\a -> mappend a . r)) mempty l s0
take :: (Ord n, Num n) => n -> FMList a -> FMList a
take = transformCS (\f e c i -> if i > 0 then c (f e) (i-1) else mempty)
takeWhile :: (a -> Bool) -> FMList a -> FMList a
takeWhile p = transformCS (\f e c _ -> if p e then c (f e) True else mempty) True
drop :: (Ord n, Num n) => n -> FMList a -> FMList a
drop = transformCS (\f e c i -> if i > 0 then c mempty (i-1) else c (f e) 0)
dropWhile :: (a -> Bool) -> FMList a -> FMList a
dropWhile p = transformCS (\f e c ok -> if ok && p e then c mempty True else c (f e) False) True
zipWith :: (a -> b -> c) -> FMList a -> FMList b -> FMList c
zipWith t xs ys = fromList $ P.zipWith t (toList xs) (toList ys)
zip :: FMList a -> FMList b -> FMList (a,b)
zip = zipWith (,)
iterate :: (a -> a) -> a -> FMList a
iterate f x = x `cons` iterate f (f x)
-- | 'repeat' buids an infinite list of a single value.
-- While infinite, the result is still accessible from both the start and end.
repeat :: a -> FMList a
repeat = cycle . one
-- | 'cycle' repeats a list to create an infinite list.
-- It is also accessible from the end, where @last (cycle l)@ equals @last l@.
--
-- Caution: @cycle 'empty'@ is an infinite loop.
cycle :: FMList a -> FMList a
cycle l = l >< cycle l >< l
-- | 'unfoldr' builds an 'FMList' from a seed value from left to right.
-- The function takes the element and returns 'Nothing'
-- if it is done producing the list or returns 'Just' @(a,b)@, in which
-- case, @a@ is a appended to the result and @b@ is used as the next
-- seed value in a recursive call.
--
-- A simple use of 'unfoldr':
--
-- > *> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
-- > fromList [10,9,8,7,6,5,4,3,2,1]
--
unfoldr :: (b -> Maybe (a, b)) -> b -> FMList a
unfoldr g = go
where
go b = maybe nil (\(a, b') -> cons a (go b')) (g b)
-- | 'unfold' builds a list from a seed value.
-- The function takes the seed and returns an 'FMList' of values.
-- If the value is 'Right' @a@, then @a@ is appended to the result, and if the
-- value is 'Left' @b@, then @b@ is used as seed value in a recursive call.
--
-- A simple use of 'unfold' (simulating unfoldl):
--
-- > *> unfold (\b -> if b == 0 then empty else Left (b-1) `pair` Right b) 10
-- > fromList [1,2,3,4,5,6,7,8,9,10]
--
unfold :: (b -> FMList (Either b a)) -> b -> FMList a
unfold g = transform (\f -> either (foldMap f . unfold g) f) . g
-- | This is essentially the same as 'Data.Monoid.Ap'. We include it here
-- partly for compatibility with older base versions. But as discussed at the
-- local definition of '<>', it can be slightly better for performance to have
-- 'mappend' for this type defined in terms of 'mappend' for the underlying
-- 'Monoid' rather than 'S.<>' for the underlying 'Semigroup'.
newtype WrapApp f m = WrapApp { unWrapApp :: f m }
#if MIN_VERSION_base(4,9,0)
instance (Applicative f, Monoid m) => Semigroup (WrapApp f m) where
WrapApp a <> WrapApp b = WrapApp $ liftA2 (<>) a b
instance (Applicative f, Monoid m) => Monoid (WrapApp f m) where
mempty = WrapApp $ pure mempty
mappend = (S.<>)
#else
instance (Applicative f, Monoid m) => Monoid (WrapApp f m) where
mempty = WrapApp $ pure mempty
mappend (WrapApp a) (WrapApp b) = WrapApp $ liftA2 mappend a b
#endif
-- | Map each element of a structure to an action, evaluate these actions from left to right,
-- and concat the monoid results.
foldMapA
:: ( Foldable t, Applicative f, Monoid m)
=> (a -> f m) -> t a -> f m
foldMapA f = unWrapApp . foldMap (WrapApp . f)
instance Functor FMList where
fmap g = transform (\f -> f . g)
a <$ l = transform (\f -> const (f a)) l
instance Foldable FMList where
foldMap m f = unFM f m
instance Traversable FMList where
traverse f = foldMapA (fmap one . f)
instance Monad FMList where
return = pure
m >>= g = transform (\f -> foldMap f . g) m
(>>) = (*>)
instance MF.MonadFail FMList where
fail _ = nil
instance Applicative FMList where
pure = one
gs <*> xs = transform (\f g -> unFM xs (f . g)) gs
as <* bs = transform (\f a -> unFM bs (const (f a))) as
as *> bs = transform (\f -> const (unFM bs f)) as
#if MIN_VERSION_base (4,10,0)
liftA2 g xs ys = transform (\f x -> unFM ys (\y -> f (g x y))) xs
#endif
#if MIN_VERSION_base(4,9,0)
instance Semigroup (FMList a) where
(<>) = (><)
#endif
instance Monoid (FMList a) where
mempty = nil
#if MIN_VERSION_base(4,9,0)
mappend = (S.<>)
#else
mappend = (><)
#endif
instance MonadPlus FMList where
mzero = nil
mplus = (><)
instance Alternative FMList where
empty = nil
(<|>) = (><)
instance Show a => Show (FMList a) where
show l = "fromList " ++ (show $! toList l)
fromMaybeOrError :: Maybe a -> String -> a
fromMaybeOrError ma e = fromMaybe (error e) ma
| sjoerdvisscher/fmlist | Data/FMList.hs | bsd-3-clause | 11,902 | 0 | 14 | 3,064 | 3,644 | 1,979 | 1,665 | 214 | 2 |
module Main where
import Criterion.Main
import GenStrat
import CoreS.Parse
import CoreS.AST
import qualified CoreS.ASTUnitype as AST
import AlphaR
import NormalizationStrategies hiding ((<>))
import EvaluationMonad
import SolutionContext
normalizations :: Normalizer CompilationUnit
normalizations = [ alphaRenaming ]
normalize :: CompilationUnit -> CompilationUnit
normalize = executeNormalizer normalizations
normalizeUAST :: AST.AST -> AST.AST
normalizeUAST = AST.inCore normalize
makeBench :: FilePath -> IO Benchmarkable
makeBench stud = do
let paths = Ctx stud []
(Ctx (Right stud) []) <- resultEvalM ((fmap parseConv) <$> readRawContents paths)
return $ nf normalize stud
main :: IO ()
main = do
wide <- makeBench "bench/Programs/wideStudent.java"
defaultMain
[ bench "wide" wide
]
| Centril/DATX02-17-26 | bench/BenchAlpha.hs | gpl-2.0 | 814 | 0 | 12 | 127 | 235 | 124 | 111 | 26 | 1 |
module Snap.Snaplet.HandleIt.Router where
import Snap(Handler, Initializer, addRoutes)
import Snap.Snaplet.HandleIt.Header
import Snap.Snaplet.HandleIt.Internal.Router
import Snap.Snaplet.Heist(HasHeist(..))
import qualified Data.ByteString.Char8 as BS
import Control.Monad.State(put, get)
-- | resources adds all restful actions to State
resources :: Handling s => s -> Router ()
resources a = mapM (setSingle a)
[ IndexR , ShowR
, NewR , EditR
, CreateR , UpdateR
, DestroyR ] >> return ()
-- | setSingle adds a single
setSingle :: Handling s => s -> Restful -> Router ()
setSingle a r = get >>= put . ((r, HDL a):)
-- | This function takes the state result and adds the paths to the Snap app
manageRouting :: HasHeist b => Routing ->
Initializer b c [(BS.ByteString, Handler b c ())]
manageRouting routes = do
let newRoutes = map routePath routes
addRoutes newRoutes
return newRoutes
handleRoutes :: HasHeist b => Router () ->
Initializer b c [(BS.ByteString, Handler b c ())]
handleRoutes routes = do
let newRoutes = map routePath $ routing routes
addRoutes newRoutes
return newRoutes
| AtticHacker/snaplet-handle-it | src/Snap/Snaplet/HandleIt/Router.hs | gpl-3.0 | 1,216 | 0 | 11 | 295 | 368 | 197 | 171 | 27 | 1 |
module HplProducts.Test where
import CK.Types
import CK.Parsers.XML.XmlConfigurationKnowledge
import CK.Parsers.XML.XmlConfigurationParser
import FeatureModel.Types hiding (Success, Fail)
import FeatureModel.Parsers.Expression
import FeatureModel.Parsers.GenericParser
import qualified BasicTypes as Core
import System.Directory
import System.FilePath
import Data.Maybe
import Data.Generics
import BasicTypes
import Text.ParserCombinators.Parsec
import HplAssets.DTMC.Parsers.Dot
import HplAssets.DTMC.Types
import HplAssets.DTMC
import HplAssets.DTMC.PrettyPrinter.DotPP
data SPLModel = SPLModel{featureModel :: FeatureModel,
splDtmc :: DtmcModel}
data InstanceModel = InstanceModel{featureConfiguration ::
FeatureConfiguration,
dtmc :: DtmcModel}
deriving Typeable
data TransformationModel = DtmcTransformation DtmcTransformation
data ExportModel = ExportDtmcDot
lstExport :: [ExportModel]
lstExport = [ExportDtmcDot]
xml2Transformation ::
String -> [String] -> ParserResult TransformationModel
xml2Transformation "composeDTMC" [id,startpoint,endpoint]
= Success (DtmcTransformation (ComposeDTMC id startpoint endpoint))
xml2Transformation "appendDTMC" [id,point]
= Success (DtmcTransformation (AppendDTMC id point))
xml2Transformation "selectDtmc" ids
= Success (DtmcTransformation (SelectDTMC ids))
instance Transformation TransformationModel SPLModel InstanceModel
where
applyT t spl im = transform t spl (features im) im
transform ::
TransformationModel ->
SPLModel -> FeatureConfiguration -> InstanceModel -> InstanceModel
transform (DtmcTransformation x0) x1 x2 x3
= x3{dtmc = transformDtmc x0 (splDtmc x1) (id x2) (dtmc x3)}
instance SPL SPLModel InstanceModel where
makeEmptyInstance fc spl = mkEmptyInstance fc spl
instance Product InstanceModel where
features im = featureConfiguration im
mkEmptyInstance ::
FeatureConfiguration -> SPLModel -> InstanceModel
mkEmptyInstance fc spl
= InstanceModel{featureConfiguration = fc,
dtmc = emptyDtmc (splDtmc spl)}
export :: ExportModel -> FilePath -> InstanceModel -> IO ()
export (ExportDtmcDot) x1 x2 = exportDtmcDot (x1 ++ "") (dtmc x2)
readProperties ps
= (fromJust (findPropertyValue "name" ps),
fromJust (findPropertyValue "feature-model" ps),
fromJust (findPropertyValue "instance-model" ps))
main :: IO ()
main
= do ns <- fmap normalizedSchema getCurrentDirectory
input <- getLine
contents <- readFile input
let ls = lines contents
let ps = map fromJust (filter (isJust) (map readPropertyValue ls))
let name = fromJust (findPropertyValue "name" ps)
let fModel = fromJust (findPropertyValue "feature-model" ps)
let iModel = fromJust (findPropertyValue "instance-model" ps)
let cModel = fromJust (findPropertyValue "configuration-model" ps)
let targetDir = fromJust (findPropertyValue "target-dir" ps)
let dtmcModel = fromJust (findPropertyValue "dtmc-model" ps)
(Core.Success fm) <- parseFeatureModel ((ns fmSchema), snd fModel)
FMPlugin
(Core.Success cm) <- parseConfigurationKnowledge
(ns ckSchema) (snd cModel)
(Core.Success im) <- parseInstanceModel (ns fcSchema) (snd iModel)
(Core.Success dtmcpl) <- parseDtmcModel (snd dtmcModel)
let fc = FeatureConfiguration im
let spl = SPLModel{featureModel = fm, splDtmc = dtmcpl}
let product = build fm fc cm spl
let out = (outputFile (snd targetDir) (snd name))
sequence_ [export x out product | x <- lstExport]
print $ "Ok, the output file was genarated at: " ++ out
return ()
fmSchema :: String
fmSchema = "schema_feature-model.rng"
fcSchema :: String
fcSchema = "schema_feature-configuration.rng"
ckSchema :: String
ckSchema = "schema-configuration-knowledge.rng"
normalizedSchema :: FilePath -> String -> FilePath
normalizedSchema cDir sch = cDir </> sch
outputFile :: FilePath -> String -> FilePath
outputFile f n = f </> n
xml2ConfigurationKnowledge ::
XmlConfigurationKnowledge ->
ParserResult (ConfigurationKnowledge TransformationModel)
xml2ConfigurationKnowledge ck
= let cs = xmlConfigurations ck
mcs = map xml2Configuration cs
in
if and [isSuccess c | c <- mcs] then
Success [ci | (Success ci) <- mcs] else
Fail (unwords [showError e | e <- mcs, isSuccess e == False])
xml2Configuration ::
XmlConfiguration ->
ParserResult (ConfigurationItem TransformationModel)
xml2Configuration c
= let pe = parse parseExpression "" (xmlExpression c)
ts
= [xml2Transformation (tName t) (splitAndTrim ',' (tArgs t)) |
t <- (xmlTransformations c)]
pr = parseConstraint (xmlRequired c)
pp = parseConstraint (xmlProvided c)
pl = [pe, pr, pp]
in
if and [isSuccess t | t <- ts] then
let pts = [a | (Success a) <- ts] in
case pl of
[Right exp, Right req, Right prov]
-> Success
(ConstrainedConfigurationItem{expression = exp,
transformations = pts, required = req,
provided = prov})
[Right exp, _, _]
-> Success
(ConfigurationItem{expression = exp, transformations = pts})
otherwise
-> Fail
("Error parsing configuration item with " ++ " expression " ++
(show $ xmlExpression c)
++ ", required "
++ (show $ xmlRequired c)
++ ", provided "
++ (show $ xmlProvided c)
++ ". ")
else Fail (unwords [showError e | e <- ts, isSuccess e == False])
where
parseConstraint ::
Maybe String -> Either ParseError FeatureExpression
parseConstraint (Nothing) = parse pzero "" ""
parseConstraint (Just s) = parse parseExpression "" s
parseConfigurationKnowledge ::
String ->
String ->
IO (ParserResult (ConfigurationKnowledge TransformationModel))
parseConfigurationKnowledge schema fileName
= do result <- parseXmlConfigurationKnowledge schema fileName
case result of
(Core.Success xml) -> return $ xml2ConfigurationKnowledge xml
(Core.Fail err) -> return $ Core.Fail err | alessandroleite/hephaestus-pl | src/meta-hephaestus/HplProducts/Test.hs | lgpl-3.0 | 6,872 | 0 | 23 | 2,022 | 1,836 | 939 | 897 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Test.Pos.Cbor.Arbitrary.UserSecret
(
) where
import Universum
import Test.QuickCheck (Arbitrary (..))
import Test.QuickCheck.Arbitrary.Generic (genericArbitrary,
genericShrink)
import Pos.Util.UserSecret (UserSecret, WalletUserSecret)
import System.FileLock (FileLock)
instance Arbitrary WalletUserSecret where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary (Maybe FileLock) => Arbitrary UserSecret where
arbitrary = genericArbitrary
shrink = genericShrink
| input-output-hk/cardano-sl | lib/test/Test/Pos/Cbor/Arbitrary/UserSecret.hs | apache-2.0 | 633 | 0 | 8 | 157 | 118 | 72 | 46 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Home/landing page.
module HL.View.Home where
import HL.View
import HL.View.Code
import HL.View.Home.Features
import HL.View.Template
-- | Home view.
homeV :: [(Text, Text, Text)] -> FromLucid App
homeV vids =
skeleton
"Haskell Language"
(\_ _ ->
linkcss "https://fonts.googleapis.com/css?family=Ubuntu:700")
(\cur url ->
do navigation True [] Nothing url
header url
try url
community url vids
features
sponsors
transition
events
div_ [class_ "mobile"] $
(navigation False [] cur url))
(\_ url ->
scripts url
[js_jquery_console_js
,js_tryhaskell_js
,js_tryhaskell_pages_js])
-- | Top header section with the logo and code sample.
header :: (Route App -> Text) -> Html ()
header url =
div_ [class_ "header"] $
(container_
(row_ (do span6_ [class_ "col-md-6"]
(div_ [class_ "branding"]
(do branding
summation))
span6_ [class_ "col-md-6"]
(div_ [class_ "branding"]
(do tag
sample)))))
where branding =
span_ [class_ "name",background url img_logo_png] "Haskell"
summation =
span_ [class_ "summary"] "An advanced purely-functional programming language"
tag =
span_ [class_ "tag"] "Declarative, statically typed code."
sample =
div_ [class_ "code-sample",title_ "This example is contrived in order to demonstrate what Haskell looks like, including: (1) where syntax, (2) enumeration syntax, (3) pattern matching, (4) consing as an operator, (5) list comprehensions, (6) infix functions. Don't take it seriously as an efficient prime number generator."]
(haskellPre codeSample)
-- | Code sample.
-- TODO: should be rotatable and link to some article.
codeSample :: Text
codeSample =
"primes = filterPrime [2..] \n\
\ where filterPrime (p:xs) = \n\
\ p : filterPrime [x | x <- xs, x `mod` p /= 0]"
-- | Try Haskell section.
try :: (Route App -> Text) -> Html ()
try _ =
div_ [class_ "try",onclick_ "tryhaskell.controller.inner.click()"]
(container_
(row_ (do span6_ [class_ "col-md-6"] repl
span6_ [class_ "col-md-6",id_ "guide"]
(return ()))))
where repl =
do h2_ "Try it"
noscript_ (span6_ (div_ [class_ "alert alert-warning"]
"Try haskell requires Javascript to be enabled."))
span6_ [hidden_ "", id_ "cookie-warning"]
(div_ [class_ "alert alert-warning"]
"Try haskell requires cookies to be enabled.")
div_ [id_ "console"]
(return ())
-- | Community section.
-- TOOD: Should contain a list of thumbnail videos. See mockup.
community :: (Route App -> Text) -> [(Text, Text, Text)] -> Html ()
community url vids =
div_ [id_ "community-wrapper"]
(do div_ [class_ "community",background url img_community_jpg]
(do container_
[id_ "tagline"]
(row_ (span8_ [class_ "col-md-8"]
(do h1_ "An open source community effort for over 20 years"
p_ [class_ "learn-more"]
(a_ [href_ (url CommunityR)] "Learn more"))))
container_
[id_ "video-description"]
(row_ (span8_ [class_ "col-md-8"]
(do h1_ (a_ [id_ "video-anchor"] "<title here>")
p_ (a_ [id_ "video-view"] "View the video now \8594")))))
div_ [class_ "videos"]
(container_ (row_ (span12_ [class_ "col-md-12"]
(ul_ (forM_ vids vid))))))
where vid :: (Text,Text,Text) -> Html ()
vid (n,u,thumb) =
li_ (a_ [class_ "vid-thumbnail",href_ u,title_ n]
(img_ [src_ thumb]))
-- | Information for people to help transition from the old site to the new locations.
transition :: Html ()
transition =
div_ [class_ "transition"]
(container_
(row_ (span6_ [class_ "col-md-6"]
(do h1_ "Psst! Looking for the wiki?"
p_ (do "This is the new Haskell home page! The wiki has moved to "
a_ [href_ "https://wiki.haskell.org"] "wiki.haskell.org.")))))
-- | Events section.
-- TODO: Take events section from Haskell News?
events :: Html ()
events =
return ()
-- | List of sponsors.
sponsors :: Html ()
sponsors =
div_ [class_ "sponsors"] $
container_ $
do row_ (span6_ [class_ "col-md-6"] (h1_ "Sponsors"))
row_ (do span6_ [class_ "col-md-6"]
(p_ (do strong_ (a_ [href_ "https://www.datadoghq.com"] "DataDog")
" provides powerful, customizable 24/7 metrics and monitoring \
\integration for all of Haskell.org, and complains loudly for \
\us when things go wrong."))
span6_ [class_ "col-md-6"]
(p_ (do strong_ (a_ [href_ "https://www.fastly.com"] "Fastly")
"'s Next Generation CDN provides low latency access for all of \
\Haskell.org's downloads and highest traffic services, including \
\the primary Hackage server, Haskell Platform downloads, and more." )))
row_ (do span6_ [class_ "col-md-6"]
(p_ (do strong_ (a_ [href_ "https://www.rackspace.com"] "Rackspace")
" provides compute, storage, and networking resources, powering \
\almost all of Haskell.org in several regions around the world."))
span6_ [class_ "col-md-6"]
(p_ (do strong_ (a_ [href_ "https://www.status.io"] "Status.io")
" powers "
a_ [href_ "https://status.haskell.org"] "https://status.haskell.org"
", and lets us easily tell you \
\when we broke something." )))
row_ (do span6_ [class_ "col-md-6"]
(p_ (do strong_ (a_ [href_ "http://www.galois.com"] "Galois")
" provides infrastructure, funds, administrative resources and \
\has historically hosted critical Haskell.org infrastructure, \
\as well as helping the Haskell community at large with their work." ))
span6_ [class_ "col-md-6"]
(p_ (do strong_ (a_ [href_ "https://www.dreamhost.com"] "DreamHost")
" has teamed up to provide Haskell.org with redundant, scalable object-storage \
\through their Dream Objects service." )))
row_ (do span6_ [class_ "col-md-6"]
(p_ (do strong_ (a_ [href_ "https://webmon.com"] "Webmon")
" provides monitoring and escalation for core haskell.org infrastructure." )))
| josefs/hl | src/HL/View/Home.hs | bsd-3-clause | 7,563 | 0 | 27 | 2,855 | 1,559 | 759 | 800 | 129 | 1 |
-- |
-- Module : Data.ASN1.Types
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE BangPatterns #-}
module Data.ASN1.Types
(
-- * Raw types
ASN1Class(..)
, ASN1Tag
, ASN1Length(..)
, ASN1Header(..)
-- * Errors types
, ASN1Error(..)
-- * Events types
, ASN1Event(..)
) where
import Control.Exception (Exception)
import Data.Typeable
import Data.ByteString (ByteString)
-- | Element class
data ASN1Class = Universal
| Application
| Context
| Private
deriving (Show,Eq,Ord,Enum)
-- | ASN1 Tag
type ASN1Tag = Int
-- | ASN1 Length with all different formats
data ASN1Length = LenShort Int -- ^ Short form with only one byte. length has to be < 127.
| LenLong Int Int -- ^ Long form of N bytes
| LenIndefinite -- ^ Length is indefinite expect an EOC in the stream to finish the type
deriving (Show,Eq)
-- | ASN1 Header with the class, tag, constructed flag and length.
data ASN1Header = ASN1Header !ASN1Class !ASN1Tag !Bool !ASN1Length
deriving (Show,Eq)
-- | represent one event from an asn1 data stream
data ASN1Event = Header ASN1Header -- ^ ASN1 Header
| Primitive !ByteString -- ^ Primitive
| ConstructionBegin -- ^ Constructed value start
| ConstructionEnd -- ^ Constructed value end
deriving (Show,Eq)
-- | Possible errors during parsing operations
data ASN1Error = StreamUnexpectedEOC -- ^ Unexpected EOC in the stream.
| StreamInfinitePrimitive -- ^ Invalid primitive with infinite length in a stream.
| StreamConstructionWrongSize -- ^ A construction goes over the size specified in the header.
| StreamUnexpectedSituation String -- ^ An unexpected situation has come up parsing an ASN1 event stream.
| ParsingHeaderFail String -- ^ Parsing an invalid header.
| ParsingPartial -- ^ Parsing is not finished, there is construction unended.
| TypeNotImplemented String -- ^ Decoding of a type that is not implemented. Contribution welcome.
| TypeDecodingFailed String -- ^ Decoding of a knowed type failed.
| PolicyFailed String String -- ^ Policy failed including the name of the policy and the reason.
deriving (Typeable, Show, Eq)
instance Exception ASN1Error
| mboes/hs-asn1 | data/Data/ASN1/Types.hs | bsd-3-clause | 2,624 | 0 | 7 | 774 | 304 | 192 | 112 | 51 | 0 |
{-# OPTIONS -O #-}
--- {-# OPTIONS_GHC -XFlexibleContexts #-} see Makefile
-- Author: Pawel Bulkowski (pawelb16@gmail.com)
-- Thanks to Michal Palka for teaching me Haskell
-- Photos by: Magdalena Niedziela
-- based on other gtk2hs example applications
-- the code is public domain
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.EventM
import Data.Array.MArray
import Data.Array.IO
--import Data.Array.IO.Internals
import Data.Array.Storable
import Data.Bits
import Data.Word
import Data.Maybe
import Data.IORef
import Data.Ord
import Control.Monad ( when, unless, liftM )
import Control.Monad.Trans ( liftIO )
import Control.Monad.ST
import Data.Array.Base ( unsafeWrite, unsafeRead )
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade
import Graphics.UI.Gtk.ModelView as New
import Graphics.UI.Gtk.Gdk.GC (gcNew)
import System.CPUTime
import System.Environment ( getArgs )
import System.Directory ( doesFileExist )
type ArrayType = IOUArray
--type ArrayType = StorableArray
-- The state and GUI
data ImageState = Empty|NonEmpty
data State = State {
pb :: Pixbuf,
is :: ImageState
}
main = do
args <- getArgs
case args of
[fName] -> do
exists <- doesFileExist fName
if exists then runGUI fName else
putStrLn ("File "++fName++" not found.")
_ -> putStrLn "Usage: scaling <image.jpg>"
runGUI fName = do
initGUI
window <- windowNew
window `onDestroy` mainQuit
set window [ windowTitle := "Scaling"
, windowResizable := True ]
label <- labelNew (Just "Content Aware Image Scaling")
vboxOuter <- vBoxNew False 0
vboxInner <- vBoxNew False 5
(mb,miOpen,miSave,miScale, miGradient, miSeamCarve, miQuit) <- makeMenuBar
canvas <- drawingAreaNew
containerAdd vboxInner canvas
-- Assemble the bits
set vboxOuter [ containerChild := mb
, containerChild := vboxInner ]
set vboxInner [ containerChild := label
, containerBorderWidth := 10 ]
set window [ containerChild := vboxOuter ]
-- create the Pixbuf
pb <- pixbufNew ColorspaceRgb False 8 256 256
-- Initialize the state
state <- newIORef State { pb = pb, is = Empty }
let modifyState f = readIORef state >>= f >>= writeIORef state
canvas `onSizeRequest` return (Requisition 256 256)
-- Add action handlers
onActivateLeaf miQuit mainQuit
-- onActivateLeaf miOpen $ modifyState $ reset gui
onActivateLeaf miOpen $ modifyState $ loadImageDlg canvas window
onActivateLeaf miSave $ modifyState $ saveImageDlg canvas window
onActivateLeaf miScale $ modifyState $ scaleImageDlg canvas window
onActivateLeaf miGradient $ modifyState $ gradientImageDlg canvas window
onActivateLeaf miSeamCarve $ modifyState $ seamCarveImageDlg canvas window
modifyState (loadImage canvas window fName)
canvas `on` exposeEvent $ updateCanvas state
boxPackStartDefaults vboxInner canvas
widgetShowAll window
mainGUI
return ()
--uncomment for ghc < 6.8.3
--instance Show Rectangle where
-- show (Rectangle x y w h) = "x="++show x++", y="++show y++
-- ", w="++show w++", h="++show h++";"
updateCanvas :: IORef State -> EventM EExpose Bool
updateCanvas rstate = do
region <- eventRegion
win <- eventWindow
liftIO $ do
state <- readIORef rstate
let (State pb is) = state
gc <- gcNew win
width <- pixbufGetWidth pb
height <- pixbufGetHeight pb
pbregion <- regionRectangle (Rectangle 0 0 width height)
regionIntersect region pbregion
rects <- regionGetRectangles region
putStrLn ("redrawing: "++show rects)
(flip mapM_) rects $ \(Rectangle x y w h) -> do
drawPixbuf win gc pb x y x y w h RgbDitherNone 0 0
return True
{-# INLINE doFromTo #-}
-- do the action for [from..to], ie it's inclusive.
doFromTo :: Int -> Int -> (Int -> IO ()) -> IO ()
doFromTo from to action =
let loop n | n > to = return ()
| otherwise = do action n
loop (n+1)
in loop from
-- do the action for [to..from], ie it's inclusive.
{-# INLINE doFromToDown #-}
doFromToDown :: Int -> Int -> (Int -> IO ()) -> IO ()
doFromToDown from to action =
let loop n | n < to = return ()
| otherwise = do action n
loop (n-1)
in loop from
-- do the action for [from..to] with step, ie it's inclusive.
{-# INLINE doFromToStep #-}
doFromToStep :: Int -> Int -> Int -> (Int -> IO ()) -> IO ()
doFromToStep from to step action =
let loop n | n > to = return ()
| otherwise = do action n
loop (n+step)
in loop from
--forM = flip mapM
makeMenuBar = do
mb <- menuBarNew
fileMenu <- menuNew
open <- menuItemNewWithMnemonic "_Open"
save <- menuItemNewWithMnemonic "_Save"
scale <- menuItemNewWithMnemonic "_Scale"
gradient <- menuItemNewWithMnemonic "_Gradient"
seamCarve <- menuItemNewWithMnemonic "Seam _Carve"
quit <- menuItemNewWithMnemonic "_Quit"
file <- menuItemNewWithMnemonic "_File"
menuShellAppend fileMenu open
menuShellAppend fileMenu save
menuShellAppend fileMenu scale
menuShellAppend fileMenu gradient
menuShellAppend fileMenu seamCarve
menuShellAppend fileMenu quit
menuItemSetSubmenu file fileMenu
containerAdd mb file
return (mb,open,save,scale,gradient,seamCarve,quit)
loadImageDlg canvas window (State pb is) = do
putStrLn ("loadImage")
ret <- openFileDialog window
case ret of
Just (filename) -> (loadImage canvas window filename (State pb is))
Nothing -> return (State pb is)
loadImage canvas window filename (State pb is) = do
putStrLn ("loadImage")
pxb <- pixbufNewFromFile filename
width <- pixbufGetWidth pxb
height <- pixbufGetHeight pxb
widgetSetSizeRequest canvas width height
widgetQueueDraw canvas
-- updateCanvas canvas pxb
return (State pxb NonEmpty)
saveImageDlg canvas window (State pb is) = do
putStrLn ("saveImage")
ret <- openFileDialog window
case ret of
Just (filename) -> do
pixbufSave pb filename "png" []
return (State pb is)
Nothing -> return (State pb is)
scaleImageDlg canvas window (State pb is) = do
putStrLn ("scaleImage")
origWidth <- pixbufGetWidth pb
origHeight <- pixbufGetHeight pb
ret <- scaleDialog window origWidth origHeight
let update w h = do
putStrLn ("seamCarveImage::update w: "++show w++" h: "++show h)
--scalePixbuf :: Pixbuf -> Int -> Int -> IO Pixbuf
pxb <- scalePixbuf pb w h
width <- pixbufGetWidth pxb
height <- pixbufGetHeight pxb
widgetSetSizeRequest canvas width height
widgetQueueDraw canvas
--updateCanvas canvas pxb
return (State pxb NonEmpty)
case ret of
Nothing -> return (State pb NonEmpty)
Just (w,h) -> (update w h)
gradientImageDlg canvas window (State pb is) = do
putStrLn ("gradientImageDlg")
--scalePixbuf :: Pixbuf -> Int -> Int -> IO Pixbuf
pxb <- gradientPixbuf pb
width <- pixbufGetWidth pxb
height <- pixbufGetHeight pxb
widgetSetSizeRequest canvas width height
widgetQueueDraw canvas
-- updateCanvas canvas pxb
return (State pxb NonEmpty)
seamCarveImageDlg canvas window (State pb is) = do
origWidth <- pixbufGetWidth pb
origHeight <- pixbufGetHeight pb
ret <- seamCarveDialog window origWidth origHeight 2
let update w h grdCnt = do
putStrLn ("seamCarveImageDlg::update w: "++show w++" h: "++show h)
--scalePixbuf :: Pixbuf -> Int -> Int -> IO Pixbuf
--pxb <- scalePixbuf pb w h
cpuStart <- getCPUTime
pxb <- seamCarvePixbuf pb w h grdCnt
cpuEnd <- getCPUTime
putStrLn ("seamCarveImageDlg::cpu time: "++show ((fromIntegral (cpuEnd-cpuStart) :: Double) /1e12))
width <- pixbufGetWidth pxb
height <- pixbufGetHeight pxb
widgetSetSizeRequest canvas width height
widgetQueueDraw canvas
--updateCanvas canvas pxb
return (State pxb NonEmpty)
case ret of
Nothing -> return (State pb NonEmpty)
Just (w,h,grdCnt) -> (update w h grdCnt)
scaleDialog :: Window -> Int -> Int-> IO (Maybe (Int, Int))
scaleDialog parent width height = do
Just xml <- xmlNew "scaling.glade"
dia <- xmlGetWidget xml castToDialog "dialogScale"
dialogAddButton dia stockCancel ResponseCancel
dialogAddButton dia stockOk ResponseOk
entryWidth <- xmlGetWidget xml castToEntry "entryScalingWidth"
entryHeight <- xmlGetWidget xml castToEntry "entryScalingHeight"
entrySetText entryWidth (show width)
entrySetText entryHeight (show height)
res <- dialogRun dia
widthStr <- entryGetText entryWidth
heightStr <- entryGetText entryHeight
widgetDestroy dia
putStrLn ("scaleDialog width: "++show width++" height: "++show height)
case res of
ResponseOk -> return (Just (read widthStr,read heightStr))
_ -> return Nothing
seamCarveDialog :: Window -> Int -> Int -> Int -> IO (Maybe (Int, Int, Int))
seamCarveDialog parent width height grdCnt= do
Just xml <- xmlNew "scaling.glade"
dia <- xmlGetWidget xml castToDialog "dialogSeamCarve"
dialogAddButton dia stockCancel ResponseCancel
dialogAddButton dia stockOk ResponseOk
entryWidth <- xmlGetWidget xml castToEntry "entryWidth"
entryHeight <- xmlGetWidget xml castToEntry "entryHeight"
entryGrdCnt <- xmlGetWidget xml castToEntry "entryGrdCnt"
entrySetText entryWidth (show width)
entrySetText entryHeight (show height)
entrySetText entryGrdCnt (show grdCnt)
res <- dialogRun dia
widthStr <- entryGetText entryWidth
heightStr <- entryGetText entryHeight
grdCntStr <- entryGetText entryGrdCnt
widgetDestroy dia
putStrLn ("scaleDialog width: "++show width++" height: "++show height++" grdCnt: "++show grdCnt)
case res of
ResponseOk -> return (Just (read widthStr,read heightStr, read grdCntStr))
_ -> return Nothing
openFileDialog :: Window -> IO (Maybe String)
openFileDialog parentWindow = do
dialog <- fileChooserDialogNew
(Just "Open Profile... ")
(Just parentWindow)
FileChooserActionOpen
[("gtk-cancel", ResponseCancel)
,("gtk-open", ResponseAccept)]
widgetShow dialog
response <- dialogRun dialog
widgetHide dialog
case response of
ResponseAccept -> fileChooserGetFilename dialog
_ -> return Nothing
--simple pixbuf scaling
scalePixbuf :: Pixbuf -> Int -> Int -> IO Pixbuf
scalePixbuf pb newWidth newHeight = do
width <- pixbufGetWidth pb
height <- pixbufGetHeight pb
row <- pixbufGetRowstride pb
chan <- pixbufGetNChannels pb
bits <- pixbufGetBitsPerSample pb
pbData <- (pixbufGetPixels pb :: IO (PixbufData Int Word8))
pbn <- pixbufNew ColorspaceRgb False 8 newWidth newHeight
pbnData <- (pixbufGetPixels pbn :: IO (PixbufData Int Word8))
newRow <- pixbufGetRowstride pbn
putStrLn ("bytes per row: "++show row++", channels per pixel: "++show chan++
", bits per sample: "++show bits)
putStrLn ("width: "++show width++", height: "++show height++", newWidth: "++show newWidth++", newHeight: "++show newHeight++" bytes per row new: "++show newRow)
let stepX = (fromIntegral width) / (fromIntegral newWidth) :: Double
let stepY = (fromIntegral height) / (fromIntegral newHeight) :: Double
doFromTo 0 (newHeight-1) $ \y -> do
let y1 = truncate ((fromIntegral y) * stepY)
doFromTo 0 (newWidth-1) $ \x -> do
let x1 = truncate ((fromIntegral x) * stepX)
let off = (x1*chan+y1*row)
let offNew = (x*chan+y*newRow)
--putStrLn ("x: "++show x++", y: "++show y++" x1: "++show x1++", y1: "++show y1++" off:"++show off++" offNew:"++show offNew)
r <- unsafeRead pbData (off)
g <- unsafeRead pbData (1+off)
b <- unsafeRead pbData (2+off)
unsafeWrite pbnData (offNew) r
unsafeWrite pbnData (1+offNew) g
unsafeWrite pbnData (2+offNew) b
return pbn
{-# INLINE arrmove #-}
arrmove :: (Ix i, MArray a e IO) => a i e -> Int -> Int -> Int -> IO ()
arrmove arr src dst size = do
--putStrLn("arrmove "++show src++" "++show dst++" "++show size)
doFromTo 0 (size-1) $ \x -> do
--forM [0..(size-1)] $ \x -> do
v <- unsafeRead arr (src+x)
unsafeWrite arr (dst+x) v
--putStrLn("arrmove2 "++show src++" "++show dst++" "++show size)
return ()
{-# INLINE arrmovesd #-}
arrmovesd :: (Ix b, MArray a c IO) => a b c -> a b c -> Int -> Int -> Int -> IO ()
arrmovesd arrsrc arrdst src dst size = do
doFromTo 0 (size-1) $ \x -> do
--forM [0..(size-1)] $ \x -> do
v <- unsafeRead arrsrc (src+x)
unsafeWrite arrdst (dst+x) v
return ()
{-# INLINE arrmoven #-}
arrmoven :: (Ix i, MArray a e IO) => a i e -> Int -> Int -> Int -> Int -> Int -> IO ()
arrmoven arr src dst size w n = do
--putStrLn("arrmoven "++show src++" "++show dst++" "++show size++" "++show w++" "++show n)
doFromToStep 0 ((n-1)*w) w $ \yoff -> do
arrmove arr (src+yoff) (dst+yoff) size
return ()
-- content Aware scaling
--TODO!
seamCarvePixbuf :: Pixbuf -> Int -> Int -> Int -> IO Pixbuf
seamCarvePixbuf pb newWidth newHeight grdCnt = do
width <- pixbufGetWidth pb
height <- pixbufGetHeight pb
row <- pixbufGetRowstride pb
chan <- pixbufGetNChannels pb
bits <- pixbufGetBitsPerSample pb
pbData <- (pixbufGetPixels pb :: IO (PixbufData Int Word8))
--pbn <- pixbufNew ColorspaceRgb False 8 newWidth newHeight
pbn <- pixbufNew ColorspaceRgb False 8 newWidth newHeight
pbnData <- (pixbufGetPixels pbn :: IO (PixbufData Int Word8))
newRow <- pixbufGetRowstride pbn
putStrLn ("bytes per row: "++show row++", channels per pixel: "++show chan++
", bits per sample: "++show bits)
putStrLn ("width: "++show width++", height: "++show height++", newWidth: "++show newWidth++", newHeight: "++show newHeight++" bytes per row new: "++show newRow)
tmpPB <- pixbufCopy pb
tmpData <- (pixbufGetPixels tmpPB) :: IO (PixbufData Int Word8)
----double gradient
let computeSrcPic pb cnt | cnt <= 0 = do pixbufCopy pb
| cnt > 0 = do
pb <- computeSrcPic pb (cnt-1)
gradientPixbuf pb
--computing gradient but one more gradient
--will be compute later by gradientArray function
tmpPB2 <- computeSrcPic tmpPB (grdCnt-1)
tmpData2 <- (pixbufGetPixels tmpPB2) :: IO (PixbufData Int Word8)
-- array to store x coord of removed pixels
coordArr <- newArray (0, (max width height)) 0 :: IO (ArrayType Int Int)
let removeVPixel pixData x y w = do
--unsafeWrite pixData (0+x*chan+y*row) 255
--unsafeWrite pixData (1+x*chan+y*row) 255
--unsafeWrite pixData (2+x*chan+y*row) 255
--store x-coord of removed pixel
unsafeWrite coordArr y x
arrmove pixData ((x+1)*chan+y*row) (x*chan+y*row) ((w-x-1)*chan)
return ()
let removeHPixel pixData x y h = do
--putStrLn("removeHPixel "++show x++" "++show y++" "++show h)
--store y-coord of removed pixel
unsafeWrite coordArr y x
--putStrLn("removeHPixel1.5 "++show x++" "++show y++" "++show h)
arrmoven pixData (y*chan+(x+1)*row) (y*chan+x*row) chan row (h-x-1)
--putStrLn("removeHPixel2 "++show x++" "++show y++" "++show h)
return ()
let removeVGrdPixel grdData x y w = do
arrmove grdData (x+1+y*width) (x+y*width) (w-x-1)
return ()
let removeHGrdPixel grdData x y h = do
--putStrLn("removeHGrdPixel "++show x++" "++show y++" "++show h)
arrmoven grdData (y+(x+1)*width) (y+x*width) 1 width (h-x-1)
--putStrLn("removeHGrdPixel2 "++show x++" "++show y++" "++show h)
return ()
let vPixIndex x y chan row = (x*chan)+(y*row)
let hPixIndex x y chan row = (y*chan)+(x*row)
-- possibly it can be made shorted
let removeSeam pixIndex rmPixel rmGrdPixel seamArr grdArr x y w = do
rmPixel tmpData x y w
rmPixel tmpData2 x y w
rmGrdPixel grdArr x y w
unless (y == 0) $ do
v0 <- if x==0 then return 0x7fffffff else unsafeRead seamArr (pixIndex (x-1) y 1 width)
v1 <- unsafeRead seamArr (pixIndex x y 1 width)
v2 <- if x==(w-1) then return 0x7fffffff else unsafeRead seamArr (pixIndex (x+1) y 1 width)
let nextX | v0 < v1 && v0 < v2 = (x-1)
| v2 < v1 = (x+1)
| True = x
removeSeam pixIndex rmPixel rmGrdPixel seamArr grdArr nextX (y-1) w
-- possibly it can be update to be more general
let updateGradientArray pixIndex grdArr y w h = unless (y == -1) $ do
x <- unsafeRead coordArr y
unless (x == 0) $ do
g <- pixelGradient pixIndex tmpData2 row chan w h (x-1) y
unsafeWrite grdArr (pixIndex (x-1) y 1 width) g
unless (y == 0) $ do
g <- pixelGradient pixIndex tmpData2 row 1 w h (x-1) (y-1)
unsafeWrite grdArr (pixIndex (x-1) (y-1) 1 width) g
unless (y == (h-1)) $ do
g <- pixelGradient pixIndex tmpData2 row 1 w h (x-1) (y+1)
unsafeWrite grdArr (pixIndex (x-1) (y+1) 1 width) g
g <- pixelGradient pixIndex tmpData2 row 1 w h x y
unsafeWrite grdArr (pixIndex x y 1 width) g
unless (y == 0) $ do
g <- pixelGradient pixIndex tmpData2 row 1 w h x (y-1)
unsafeWrite grdArr (pixIndex x (y-1) 1 width) g
g <- pixelGradient pixIndex tmpData2 row 1 w h x (y+1)
unless (y == (h-1)) $ do
g <- pixelGradient pixIndex tmpData2 row 1 w h x (y+1)
unsafeWrite grdArr (pixIndex x (y+1) 1 width) g
updateGradientArray pixIndex grdArr (y-1) w h
return ()
let findMinVal pixIndex seamArr w h = do
v <- unsafeRead seamArr (pixIndex 0 (h-1) 1 width)
xRef <- newIORef (v :: Int, 0 :: Int)
--let modifyState f = readIORef state >>= f >>= writeIORef state
doFromTo 1 (w-1) $ \x -> do
--putStrLn("findMinVal loop x: "++show x++" (h-1): "++show (h-1))
v <- unsafeRead seamArr (pixIndex x (h-1) 1 width)
(mval, m) <- readIORef xRef
writeIORef xRef (if v < mval then (v, x) else (mval, m))
(mval, m) <- readIORef xRef
putStrLn("w: " ++show w++ " minSeam: " ++ show mval ++ " at: "++show m)
return m
grdArr <- gradientArray tmpPB2 width height
let removeVSeam w = do
seamArr <- (computeVSeamArray grdArr width height w)
m <- findMinVal vPixIndex seamArr w (height-1)
removeSeam vPixIndex removeVPixel removeVGrdPixel seamArr grdArr m (height-1) w
updateGradientArray vPixIndex grdArr (height-1) w height
return ()
let removeHSeam h = do
seamArr <- (computeHSeamArray grdArr width height h)
m <- findMinVal hPixIndex seamArr h (width-1)
removeSeam hPixIndex removeHPixel removeHGrdPixel seamArr grdArr m (width-1) h
updateGradientArray hPixIndex grdArr (width-1) h width
return ()
--let nextX | v0 < v1 && v0 < v2 = (x-1)
-- | v2 < v1 = (x+1)
-- | True = x
let grdSeam w h | w > newWidth && h > newHeight = do
--putStrLn("grdSeam: "++show w++" "++show h)
vSeamArr <- (computeVSeamArray grdArr width height w)
mv <- findMinVal vPixIndex vSeamArr w (height-1)
hSeamArr <- (computeHSeamArray grdArr width height h)
mh <- findMinVal hPixIndex hSeamArr h (width-1)
if mv < mh
then do
removeSeam vPixIndex removeVPixel removeVGrdPixel vSeamArr grdArr mv (height-1) w
updateGradientArray vPixIndex grdArr (height-1) w height
grdSeam (w-1) h
else do
removeSeam hPixIndex removeHPixel removeHGrdPixel hSeamArr grdArr mh (width-1) h
updateGradientArray hPixIndex grdArr (width-1) h width
grdSeam w (h-1)
| w > newWidth = do
--putStrLn("grdSeam2: "++show w++" "++show h)
removeVSeam w
grdSeam (w-1) h
| h > newHeight = do
--putStrLn("grdSeam3: "++show w++" "++show h)
removeHSeam h
grdSeam w (h-1)
| True = do
return ()
-- remove/add seams
--doFromToDown width (newWidth+1) $ \w -> do
-- removeVSeam w
--doFromToDown height (newHeight+1) $ \h -> do
-- removeHSeam h
grdSeam width height
doFromTo 0 (newHeight-1) $ \y -> do
arrmovesd tmpData pbnData (y*row) (y*newRow) newRow
return pbn
-- compute the gradient map
gradientPixbuf :: Pixbuf -> IO Pixbuf
gradientPixbuf pb = do
width <- pixbufGetWidth pb
height <- pixbufGetHeight pb
row <- pixbufGetRowstride pb
chan <- pixbufGetNChannels pb
bits <- pixbufGetBitsPerSample pb
pbData <- (pixbufGetPixels pb :: IO (PixbufData Int Word8))
pbn <- pixbufNew ColorspaceRgb False 8 width height
pbnData <- (pixbufGetPixels pbn :: IO (PixbufData Int Word8))
putStrLn ("bytes per row: "++show row++", channels per pixel: "++show chan++", bits per sample: "++show bits)
putStrLn ("width: "++show width++", height: "++show height)
let getpix x y c = do
case (x < 1 || x >= width || y < 1 || y >= height) of
True -> return 0
False -> (unsafeRead pbData (c+x*chan+y*row))
let gradient x y c = do
let convM = liftM fromIntegral
blah a b = convM (getpix a b c)
v00 <- blah (x-1) (y-1)
v10 <- blah x (y-1)
v20 <- blah (x+1) (y-1)
v01 <- blah (x-1) y
v21 <- blah (x+1) y
v02 <- blah (x-1) (y+1)
v12 <- blah x (y+1)
v22 <- blah (x+1) (y+1)
let gx = abs ((v20-v00)+2*(v21-v01)+(v22-v02))
let gy = abs ((v02-v00)+2*(v12-v10)+(v22-v20))
let g = (gx + gy)::Int
--let g8 = (shiftR g 3)
let g8 = if g > 255 then 255 else g
return (fromIntegral(g8) :: Word8)
let totalGradient x y = do
rg <- gradient x y 0
gg <- gradient x y 1
bg <- gradient x y 2
let g = rg + gg + bg
return ((fromIntegral g)::Word8)
doFromTo 0 (height-1) $ \y -> do
let offY = y*row
doFromTo 0 (width-1) $ \x -> do
let offX = x*chan
doFromTo 0 2 $ \c -> do
let off = offY+offX + c
--putStrLn ("x: "++show x++", y: "++show y++" off:"++show off)
--v <- (totalGradient x y)
v <- (gradient x y c)
unsafeWrite pbnData (off) v
return pbn
-- compute gradient fo single pixel
{-# INLINE pixelGradient #-}
pixelGradient :: (Int -> Int -> Int -> Int -> Int) -> (PixbufData Int Word8) -> Int -> Int -> Int -> Int -> Int -> Int -> (IO Word16)
pixelGradient pixIndex pbData row chan w h x y = do
let getpix x y c = do
case (x < 0 || x >= w || y < 0 || y >= h) of
True -> return 0
False -> (unsafeRead pbData (c+(pixIndex x y chan row)))
--False -> (unsafeRead pbData (c+x*chan+y*row))
let gradient x y c = do
let convM = liftM fromIntegral
blah a b = convM (getpix a b c)
v00 <- blah (x-1) (y-1)
v10 <- blah x (y-1)
v20 <- blah (x+1) (y-1)
v01 <- blah (x-1) y
v21 <- blah (x+1) y
v02 <- blah (x-1) (y+1)
v12 <- blah x (y+1)
v22 <- blah (x+1) (y+1)
let gx = abs ((v20-v00)+2*(v21-v01)+(v22-v02))
let gy = abs ((v02-v00)+2*(v12-v10)+(v22-v20))
let g = (gx + gy)::Int
--let g8 = (shiftR g 3)
let g8 = if g > 255 then 255 else g
return (fromIntegral(g8) :: Word8)
let gradient x y c = do
let convM = liftM fromIntegral
blah a b = convM (getpix a b c)
v00 <- blah (x-1) (y-1)
v10 <- blah x (y-1)
v20 <- blah (x+1) (y-1)
v01 <- blah (x-1) y
v21 <- blah (x+1) y
v02 <- blah (x-1) (y+1)
v12 <- blah x (y+1)
v22 <- blah (x+1) (y+1)
let gx = abs ((v20-v00)+2*(v21-v01)+(v22-v02))
let gy = abs ((v02-v00)+2*(v12-v10)+(v22-v20))
let g = gx + gy
return (g :: Int)
rg <- gradient x y 0
gg <- gradient x y 1
bg <- gradient x y 2
let g = rg + gg + bg
return ((fromIntegral g) :: Word16)
-- compute the gradient map
gradientArray :: Pixbuf -> Int -> Int -> IO (ArrayType Int Word16)
gradientArray pb w h = do
width <- pixbufGetWidth pb
height <- pixbufGetHeight pb
row <- pixbufGetRowstride pb
chan <- pixbufGetNChannels pb
bits <- pixbufGetBitsPerSample pb
pbData <- (pixbufGetPixels pb :: IO (PixbufData Int Word8))
grdArr <- newArray (0, width * height) 0
putStrLn ("bytes per row: "++show row++", channels per pixel: "++show chan++", bits per sample: "++show bits)
putStrLn ("width: "++show width++", height: "++show height)
let vPixIndex x y chan row = x*chan+y*row
doFromTo 0 (h-1) $ \y -> do
let offY = y*width
doFromTo 0 (w-1) $ \x -> do
let off = x + offY
--v <- (totalGradient x y)
v <- (pixelGradient vPixIndex pbData row chan w h x y)
unsafeWrite grdArr (off) v
--putStrLn ("x: "++show x++" y: "++show y++" v: "++show v)
return grdArr
computeVSeamArray :: (ArrayType Int Word16) -> Int -> Int -> Int -> IO (ArrayType Int Int)
computeVSeamArray grdArr width height currentWidth = do
seamArr <- newArray (0, width * height) 0
--grdArr <- gradientArr
doFromTo 0 (currentWidth-1) $ \x -> do
v <- unsafeRead grdArr x
unsafeWrite seamArr x (fromIntegral v :: Int)
doFromTo 1 (height-1) $ \y -> do
let offY = y*width
let prevOffY = offY-width
doFromTo 1 (currentWidth-2) $ \x -> do
p1 <- unsafeRead seamArr ((x-1)+prevOffY)
p2 <- unsafeRead seamArr (x+prevOffY)
p3 <- unsafeRead seamArr ((x+1)+prevOffY)
v <- unsafeRead grdArr (x+offY)
unsafeWrite seamArr (x+offY) ((fromIntegral v :: Int) +(min(min p1 p2) p3))
p2l <- unsafeRead seamArr (0+prevOffY)
p3l <- unsafeRead seamArr (1+prevOffY)
vl <- unsafeRead grdArr (0+offY)
unsafeWrite seamArr (0+offY) ((fromIntegral vl)+(min p2l p3l))
p1r <- unsafeRead seamArr (currentWidth-2+prevOffY)
p2r <- unsafeRead seamArr (currentWidth-1+prevOffY)
vr <- unsafeRead grdArr (currentWidth-1+offY)
unsafeWrite seamArr (currentWidth-1+offY) ((fromIntegral vr :: Int) +(min p1r p2r))
return seamArr
computeHSeamArray :: (ArrayType Int Word16) -> Int -> Int -> Int -> IO (ArrayType Int Int)
computeHSeamArray grdArr width height currentHeight = do
seamArr <- newArray (0, width * height) 0
--grdArr <- gradientArr
doFromTo 0 (currentHeight-1) $ \y -> do
v <- unsafeRead grdArr (y*width)
unsafeWrite seamArr (y*width) (fromIntegral v :: Int)
doFromTo 1 (width-1) $ \x -> do
doFromTo 1 (currentHeight-2) $ \y -> do
let offY = y*width
let prevOffY = offY-width
let nextOffY = offY+width
p1 <- unsafeRead seamArr (x-1+prevOffY)
p2 <- unsafeRead seamArr (x-1+offY)
p3 <- unsafeRead seamArr (x-1+nextOffY)
v <- unsafeRead grdArr (x+offY)
unsafeWrite seamArr (x+offY) ((fromIntegral v :: Int) +(min(min p1 p2) p3))
p2l <- unsafeRead seamArr (x-1+0)
p3l <- unsafeRead seamArr (x-1+width)
vl <- unsafeRead grdArr (x+0)
unsafeWrite seamArr (x+0) ((fromIntegral vl)+(min p2l p3l))
p1r <- unsafeRead seamArr (x-1+((currentHeight-2)*width))
p2r <- unsafeRead seamArr (x-1+((currentHeight-1)*width))
vr <- unsafeRead grdArr (x+((currentHeight-1)*width))
unsafeWrite seamArr (x+((currentHeight-1)*width)) ((fromIntegral vr :: Int) +(min p1r p2r))
return seamArr
| mariefarrell/Hets | glade-0.12.5.0/demo/scaling/Scaling.hs | gpl-2.0 | 27,522 | 0 | 23 | 7,067 | 10,197 | 4,889 | 5,308 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP #-}
module VarSet (
-- * Var, Id and TyVar set types
VarSet, IdSet, TyVarSet, CoVarSet, TyCoVarSet,
-- ** Manipulating these sets
emptyVarSet, unitVarSet, mkVarSet,
extendVarSet, extendVarSetList, extendVarSet_C,
elemVarSet, varSetElems, subVarSet,
unionVarSet, unionVarSets, mapUnionVarSet,
intersectVarSet, intersectsVarSet, disjointVarSet,
isEmptyVarSet, delVarSet, delVarSetList, delVarSetByKey,
minusVarSet, foldVarSet, filterVarSet,
transCloVarSet, fixVarSet,
lookupVarSet, lookupVarSetByName,
mapVarSet, sizeVarSet, seqVarSet,
elemVarSetByKey, partitionVarSet,
-- * Deterministic Var set types
DVarSet, DIdSet, DTyVarSet, DTyCoVarSet,
-- ** Manipulating these sets
emptyDVarSet, unitDVarSet, mkDVarSet,
extendDVarSet, extendDVarSetList,
elemDVarSet, dVarSetElems, subDVarSet,
unionDVarSet, unionDVarSets, mapUnionDVarSet,
intersectDVarSet, intersectsDVarSet, disjointDVarSet,
isEmptyDVarSet, delDVarSet, delDVarSetList,
minusDVarSet, foldDVarSet, filterDVarSet,
transCloDVarSet,
sizeDVarSet, seqDVarSet,
partitionDVarSet,
) where
#include "HsVersions.h"
import Var ( Var, TyVar, CoVar, TyCoVar, Id )
import Unique
import Name ( Name )
import UniqSet
import UniqDSet
import UniqFM( disjointUFM )
import UniqDFM( disjointUDFM )
-- | A non-deterministic set of variables.
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why it's not
-- deterministic and why it matters. Use DVarSet if the set eventually
-- gets converted into a list or folded over in a way where the order
-- changes the generated code, for example when abstracting variables.
type VarSet = UniqSet Var
type IdSet = UniqSet Id
type TyVarSet = UniqSet TyVar
type CoVarSet = UniqSet CoVar
type TyCoVarSet = UniqSet TyCoVar
emptyVarSet :: VarSet
intersectVarSet :: VarSet -> VarSet -> VarSet
unionVarSet :: VarSet -> VarSet -> VarSet
unionVarSets :: [VarSet] -> VarSet
mapUnionVarSet :: (a -> VarSet) -> [a] -> VarSet
-- ^ map the function over the list, and union the results
varSetElems :: VarSet -> [Var]
unitVarSet :: Var -> VarSet
extendVarSet :: VarSet -> Var -> VarSet
extendVarSetList:: VarSet -> [Var] -> VarSet
elemVarSet :: Var -> VarSet -> Bool
delVarSet :: VarSet -> Var -> VarSet
delVarSetList :: VarSet -> [Var] -> VarSet
minusVarSet :: VarSet -> VarSet -> VarSet
isEmptyVarSet :: VarSet -> Bool
mkVarSet :: [Var] -> VarSet
foldVarSet :: (Var -> a -> a) -> a -> VarSet -> a
lookupVarSet :: VarSet -> Var -> Maybe Var
-- Returns the set element, which may be
-- (==) to the argument, but not the same as
lookupVarSetByName :: VarSet -> Name -> Maybe Var
mapVarSet :: (Var -> Var) -> VarSet -> VarSet
sizeVarSet :: VarSet -> Int
filterVarSet :: (Var -> Bool) -> VarSet -> VarSet
extendVarSet_C :: (Var->Var->Var) -> VarSet -> Var -> VarSet
delVarSetByKey :: VarSet -> Unique -> VarSet
elemVarSetByKey :: Unique -> VarSet -> Bool
partitionVarSet :: (Var -> Bool) -> VarSet -> (VarSet, VarSet)
emptyVarSet = emptyUniqSet
unitVarSet = unitUniqSet
extendVarSet = addOneToUniqSet
extendVarSetList= addListToUniqSet
intersectVarSet = intersectUniqSets
intersectsVarSet:: VarSet -> VarSet -> Bool -- True if non-empty intersection
disjointVarSet :: VarSet -> VarSet -> Bool -- True if empty intersection
subVarSet :: VarSet -> VarSet -> Bool -- True if first arg is subset of second
-- (s1 `intersectsVarSet` s2) doesn't compute s2 if s1 is empty;
-- ditto disjointVarSet, subVarSet
unionVarSet = unionUniqSets
unionVarSets = unionManyUniqSets
varSetElems = uniqSetToList
elemVarSet = elementOfUniqSet
minusVarSet = minusUniqSet
delVarSet = delOneFromUniqSet
delVarSetList = delListFromUniqSet
isEmptyVarSet = isEmptyUniqSet
mkVarSet = mkUniqSet
foldVarSet = foldUniqSet
lookupVarSet = lookupUniqSet
lookupVarSetByName = lookupUniqSet
mapVarSet = mapUniqSet
sizeVarSet = sizeUniqSet
filterVarSet = filterUniqSet
extendVarSet_C = addOneToUniqSet_C
delVarSetByKey = delOneFromUniqSet_Directly
elemVarSetByKey = elemUniqSet_Directly
partitionVarSet = partitionUniqSet
mapUnionVarSet get_set xs = foldr (unionVarSet . get_set) emptyVarSet xs
-- See comments with type signatures
intersectsVarSet s1 s2 = not (s1 `disjointVarSet` s2)
disjointVarSet s1 s2 = disjointUFM s1 s2
subVarSet s1 s2 = isEmptyVarSet (s1 `minusVarSet` s2)
fixVarSet :: (VarSet -> VarSet) -- Map the current set to a new set
-> VarSet -> VarSet
-- (fixVarSet f s) repeatedly applies f to the set s,
-- until it reaches a fixed point.
fixVarSet fn vars
| new_vars `subVarSet` vars = vars
| otherwise = fixVarSet fn new_vars
where
new_vars = fn vars
transCloVarSet :: (VarSet -> VarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> VarSet -> VarSet
-- (transCloVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
-- The function fn could be (Var -> VarSet), but we use (VarSet -> VarSet)
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
-- Use fixVarSet if the function needs to see the whole set all at once
transCloVarSet fn seeds
= go seeds seeds
where
go :: VarSet -- Accumulating result
-> VarSet -- Work-list; un-processed subset of accumulating result
-> VarSet
-- Specification: go acc vs = acc `union` transClo fn vs
go acc candidates
| isEmptyVarSet new_vs = acc
| otherwise = go (acc `unionVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusVarSet` acc
seqVarSet :: VarSet -> ()
seqVarSet s = sizeVarSet s `seq` ()
-- Deterministic VarSet
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
-- DVarSet.
type DVarSet = UniqDSet Var
type DIdSet = UniqDSet Id
type DTyVarSet = UniqDSet TyVar
type DTyCoVarSet = UniqDSet TyCoVar
emptyDVarSet :: DVarSet
emptyDVarSet = emptyUniqDSet
unitDVarSet :: Var -> DVarSet
unitDVarSet = unitUniqDSet
mkDVarSet :: [Var] -> DVarSet
mkDVarSet = mkUniqDSet
extendDVarSet :: DVarSet -> Var -> DVarSet
extendDVarSet = addOneToUniqDSet
elemDVarSet :: Var -> DVarSet -> Bool
elemDVarSet = elementOfUniqDSet
dVarSetElems :: DVarSet -> [Var]
dVarSetElems = uniqDSetToList
subDVarSet :: DVarSet -> DVarSet -> Bool
subDVarSet s1 s2 = isEmptyDVarSet (s1 `minusDVarSet` s2)
unionDVarSet :: DVarSet -> DVarSet -> DVarSet
unionDVarSet = unionUniqDSets
unionDVarSets :: [DVarSet] -> DVarSet
unionDVarSets = unionManyUniqDSets
-- | Map the function over the list, and union the results
mapUnionDVarSet :: (a -> DVarSet) -> [a] -> DVarSet
mapUnionDVarSet get_set xs = foldr (unionDVarSet . get_set) emptyDVarSet xs
intersectDVarSet :: DVarSet -> DVarSet -> DVarSet
intersectDVarSet = intersectUniqDSets
-- | True if empty intersection
disjointDVarSet :: DVarSet -> DVarSet -> Bool
disjointDVarSet s1 s2 = disjointUDFM s1 s2
-- | True if non-empty intersection
intersectsDVarSet :: DVarSet -> DVarSet -> Bool
intersectsDVarSet s1 s2 = not (s1 `disjointDVarSet` s2)
isEmptyDVarSet :: DVarSet -> Bool
isEmptyDVarSet = isEmptyUniqDSet
delDVarSet :: DVarSet -> Var -> DVarSet
delDVarSet = delOneFromUniqDSet
minusDVarSet :: DVarSet -> DVarSet -> DVarSet
minusDVarSet = minusUniqDSet
foldDVarSet :: (Var -> a -> a) -> a -> DVarSet -> a
foldDVarSet = foldUniqDSet
filterDVarSet :: (Var -> Bool) -> DVarSet -> DVarSet
filterDVarSet = filterUniqDSet
sizeDVarSet :: DVarSet -> Int
sizeDVarSet = sizeUniqDSet
-- | Partition DVarSet according to the predicate given
partitionDVarSet :: (Var -> Bool) -> DVarSet -> (DVarSet, DVarSet)
partitionDVarSet = partitionUniqDSet
-- | Delete a list of variables from DVarSet
delDVarSetList :: DVarSet -> [Var] -> DVarSet
delDVarSetList = delListFromUniqDSet
seqDVarSet :: DVarSet -> ()
seqDVarSet s = sizeDVarSet s `seq` ()
-- | Add a list of variables to DVarSet
extendDVarSetList :: DVarSet -> [Var] -> DVarSet
extendDVarSetList = addListToUniqDSet
-- | transCloVarSet for DVarSet
transCloDVarSet :: (DVarSet -> DVarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> DVarSet -> DVarSet
-- (transCloDVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
-- The function fn could be (Var -> DVarSet), but we use (DVarSet -> DVarSet)
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
transCloDVarSet fn seeds
= go seeds seeds
where
go :: DVarSet -- Accumulating result
-> DVarSet -- Work-list; un-processed subset of accumulating result
-> DVarSet
-- Specification: go acc vs = acc `union` transClo fn vs
go acc candidates
| isEmptyDVarSet new_vs = acc
| otherwise = go (acc `unionDVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusDVarSet` acc
| oldmanmike/ghc | compiler/basicTypes/VarSet.hs | bsd-3-clause | 9,744 | 0 | 10 | 2,188 | 1,844 | 1,062 | 782 | 173 | 1 |
module Turbinado.Database.ORM.Types where
import qualified Data.Map as M
import Database.HDBC
type TypeName = String
--
-- * Types for the Table descriptions
--
type Tables = M.Map TableName (Columns, PrimaryKey)
type TableName = String
type Columns = M.Map ColumnName ColumnDesc
type ColumnName = String
type PrimaryKey = [ColumnName]
type ColumnDesc = (SqlColDesc, ForeignKeyReferences, HasDefault)
type HasDefault = Bool
type ForeignKeyReferences = [(TableName, ColumnName)] -- all columns which are targets of foreign keys
| alsonkemp/turbinado-website | Turbinado/Database/ORM/Types.hs | bsd-3-clause | 532 | 0 | 6 | 77 | 120 | 79 | 41 | 12 | 0 |
{-# OPTIONS -fglasgow-exts #-}
module BinaryDerive where
import Data.Generics
import Data.List
deriveM :: (Typeable a, Data a) => a -> IO ()
deriveM (a :: a) = mapM_ putStrLn . lines $ derive (undefined :: a)
derive :: (Typeable a, Data a) => a -> String
derive x =
"instance " ++ context ++ "Binary " ++ inst ++ " where\n" ++
concat putDefs ++ getDefs
where
context
| nTypeChildren > 0 =
wrap (join ", " (map ("Binary "++) typeLetters)) ++ " => "
| otherwise = ""
inst = wrap $ tyConString typeName ++ concatMap (" "++) typeLetters
wrap x = if nTypeChildren > 0 then "("++x++")" else x
join sep lst = concat $ intersperse sep lst
nTypeChildren = length typeChildren
typeLetters = take nTypeChildren manyLetters
manyLetters = map (:[]) ['a'..'z']
(typeName,typeChildren) = splitTyConApp (typeOf x)
constrs :: [(Int, (String, Int))]
constrs = zip [0..] $ map gen $ dataTypeConstrs (dataTypeOf x)
gen con = ( showConstr con
, length $ gmapQ undefined $ fromConstr con `asTypeOf` x
)
putDefs = map ((++"\n") . putDef) constrs
putDef (n, (name, ps)) =
let wrap = if ps /= 0 then ("("++) . (++")") else id
pattern = name ++ concatMap (' ':) (take ps manyLetters)
in
" put " ++ wrap pattern ++" = "
++ concat [ "putWord8 " ++ show n | length constrs > 1 ]
++ concat [ " >> " | length constrs > 1 && ps > 0 ]
++ concat [ "return ()" | length constrs == 1 && ps == 0 ]
++ join " >> " (map ("put "++) (take ps manyLetters))
getDefs =
(if length constrs > 1
then " get = do\n tag_ <- getWord8\n case tag_ of\n"
else " get =")
++ concatMap ((++"\n")) (map getDef constrs) ++
(if length constrs > 1
then " _ -> fail \"no parse\""
else ""
)
getDef (n, (name, ps)) =
let wrap = if ps /= 0 then ("("++) . (++")") else id
in
concat [ " " ++ show n ++ " ->" | length constrs > 1 ]
++ concatMap (\x -> " get >>= \\"++x++" ->") (take ps manyLetters)
++ " return "
++ wrap (name ++ concatMap (" "++) (take ps manyLetters))
| beni55/binary | tools/derive/BinaryDerive.hs | bsd-3-clause | 2,264 | 4 | 18 | 739 | 863 | 454 | 409 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="it-IT">
<title>Alert Filters | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/alertFilters/src/main/javahelp/org/zaproxy/zap/extension/alertFilters/resources/help_it_IT/helpset_it_IT.hs | apache-2.0 | 974 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
{-# LANGUAGE CPP, GADTs #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, (b) the type signatures, and
-- (c) the #if blah_TARGET_ARCH} things, the
-- structure should not be too overwhelming.
module PPC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import CodeGen.Platform
import PPC.Instr
import PPC.Cond
import PPC.Regs
import CPrim
import NCGMonad
import Instruction
import PIC
import Format
import RegClass
import Reg
import TargetReg
import Platform
-- Our intermediate code:
import BlockId
import PprCmm ( pprExpr )
import Cmm
import CmmUtils
import CmmSwitch
import CLabel
import Hoopl
-- The rest:
import OrdList
import Outputable
import Unique
import DynFlags
import Control.Monad ( mapAndUnzipM, when )
import Data.Bits
import Data.Word
import BasicTypes
import FastString
import Util
-- -----------------------------------------------------------------------------
-- Top-level of the instruction selector
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal (pre-order?) yields the insns in the correct
-- order.
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
arch = platformArch $ targetPlatform dflags
case arch of
ArchPPC -> do
picBaseMb <- getPicBaseMaybeNat
case picBaseMb of
Just picBase -> initializePicBase_ppc arch os picBase tops
Nothing -> return tops
ArchPPC_64 ELF_V1 -> return tops
-- generating function descriptor is handled in
-- pretty printer
ArchPPC_64 ELF_V2 -> return tops
-- generating function prologue is handled in
-- pretty printer
_ -> panic "PPC.cmmTopCodeGen: unknown arch"
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
basicBlockCodeGen
:: Block CmmNode C C
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode format reg src
| target32Bit (targetPlatform dflags) &&
isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode format reg src
where ty = cmmRegType dflags reg
format = cmmTypeFormat ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode format addr src
| target32Bit (targetPlatform dflags) &&
isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode format addr src
where ty = cmmExprType dflags src
format = cmmTypeFormat ty
CmmUnsafeForeignCall target result_regs args
-> genCCall target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false _ -> do
b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg } -> genJump arg
_ ->
panic "stmtToInstrs: statement should have been cps'd away"
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Format Reg InstrBlock
| Any Format (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Format -> Register
swizzleRegisterRep (Fixed _ reg code) format = Fixed format reg code
swizzleRegisterRep (Any _ codefn) format = Any format codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> CmmReg -> Reg
getRegisterReg _ (CmmLocal (LocalReg u pk))
= RegVirtual $ mkVirtualReg u (cmmTypeFormat pk)
getRegisterReg platform (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr
mangleIndexTree dflags (CmmRegOff reg off)
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
mangleIndexTree _ _
= panic "PPC.CodeGen.mangleIndexTree: no match"
-- -----------------------------------------------------------------------------
-- Code gen for 64-bit arithmetic on 32-bit platforms
{-
Simple support for generating 64-bit code (ie, 64 bit values and 64
bit assignments) on 32-bit platforms. Unlike the main code generator
we merely shoot for generating working code as simply as possible, and
pay little attention to code quality. Specifically, there is no
attempt to deal cleverly with the fixed-vs-floating register
distinction; all values are generated into (pairs of) floating
registers, even if this would mean some redundant reg-reg moves as a
result. Only one of the VRegUniques is returned, since it will be
of the VRegUniqueLo form, and the upper-half VReg can be determined
by applying getHiVRegFromLo to it.
-}
data ChildCode64 -- a.k.a "Register64"
= ChildCode64
InstrBlock -- code
Reg -- the lower 32-bit temporary which contains the
-- result; use getHiVRegFromLo to find the other
-- VRegUnique. Rules of this simplified insn
-- selection game are therefore that the returned
-- Reg may be modified
-- | Compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock)
getI64Amodes addrTree = do
Amode hi_addr addr_code <- getAmode D addrTree
case addrOffset hi_addr 4 of
Just lo_addr -> return (hi_addr, lo_addr, addr_code)
Nothing -> do (hi_ptr, code) <- getSomeReg addrTree
return (AddrRegImm hi_ptr (ImmInt 0),
AddrRegImm hi_ptr (ImmInt 4),
code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Big-endian store
mov_hi = ST II32 rhi hi_addr
mov_lo = ST II32 rlo lo_addr
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MR r_dst_lo r_src_lo
mov_hi = MR r_dst_hi r_src_hi
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(powerpc): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LD II32 rhi hi_addr
mov_lo = LD II32 rlo lo_addr
return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
half0 = fromIntegral (fromIntegral i :: Word16)
half1 = fromIntegral (fromIntegral (i `shiftR` 16) :: Word16)
half2 = fromIntegral (fromIntegral (i `shiftR` 32) :: Word16)
half3 = fromIntegral (fromIntegral (i `shiftR` 48) :: Word16)
code = toOL [
LIS rlo (ImmInt half1),
OR rlo rlo (RIImm $ ImmInt half0),
LIS rhi (ImmInt half3),
OR rhi rhi (RIImm $ ImmInt half2)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ ADDC rlo r1lo r2lo,
ADDE rhi r1hi r2hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Sub _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ SUBFC rlo r2lo r1lo,
SUBFE rhi r2hi r1hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv W32 W64) [expr]) = do
(expr_reg,expr_code) <- getSomeReg expr
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LI rhi (ImmInt 0)
mov_lo = MR rlo expr_reg
return $ ChildCode64 (expr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 expr
= pprPanic "iselExpr64(powerpc)" (pprExpr expr)
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
getRegister' dflags e
getRegister' :: DynFlags -> CmmExpr -> NatM Register
getRegister' dflags (CmmReg (CmmGlobal PicBaseReg))
| target32Bit (targetPlatform dflags) = do
reg <- getPicBaseNat $ archWordFormat (target32Bit (targetPlatform dflags))
return (Fixed (archWordFormat (target32Bit (targetPlatform dflags)))
reg nilOL)
| otherwise = return (Fixed II64 toc nilOL)
getRegister' dflags (CmmReg reg)
= return (Fixed (cmmTypeFormat (cmmRegType dflags reg))
(getRegisterReg (targetPlatform dflags) reg) nilOL)
getRegister' dflags tree@(CmmRegOff _ _)
= getRegister' dflags (mangleIndexTree dflags tree)
-- for 32-bit architectuers, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmLoad mem pk)
| not (isWord64 pk) = do
let platform = targetPlatform dflags
Amode addr addr_code <- getAmode D mem
let code dst = ASSERT((targetClassOfReg platform dst == RcDouble) == isFloatType pk)
addr_code `snocOL` LD format dst addr
return (Any format code)
| not (target32Bit (targetPlatform dflags)) = do
Amode addr addr_code <- getAmode DS mem
let code dst = addr_code `snocOL` LD II64 dst addr
return (Any II64 code)
where format = cmmTypeFormat pk
-- catch simple cases of zero- or sign-extended load
getRegister' _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II8 dst addr))
-- Note: there is no Load Byte Arithmetic instruction, so no signed case here
getRegister' _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LD II16 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LA II16 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II16 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LA II16 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II32 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LA II32 dst addr))
getRegister' dflags (CmmMachOp mop [x]) -- unary MachOps
= case mop of
MO_Not rep -> triv_ucode_int rep NOT
MO_F_Neg w -> triv_ucode_float w FNEG
MO_S_Neg w -> triv_ucode_int w NEG
MO_FF_Conv W64 W32 -> trivialUCode FF32 FRSP x
MO_FF_Conv W32 W64 -> conversionNop FF64 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_SS_Conv from to
| from == to -> conversionNop (intFormat to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_SS_Conv W64 to
| arch32 -> panic "PPC.CodeGen.getRegister no 64 bit int register"
| otherwise -> conversionNop (intFormat to) x
MO_SS_Conv W32 to
| arch32 -> conversionNop (intFormat to) x
| otherwise -> case to of
W64 -> triv_ucode_int to (EXTS II32)
W16 -> conversionNop II16 x
W8 -> conversionNop II8 x
_ -> panic "PPC.CodeGen.getRegister: no match"
MO_SS_Conv W16 W8 -> conversionNop II8 x
MO_SS_Conv W8 to -> triv_ucode_int to (EXTS II8)
MO_SS_Conv W16 to -> triv_ucode_int to (EXTS II16)
MO_UU_Conv from to
| from == to -> conversionNop (intFormat to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_UU_Conv W64 to
| arch32 -> panic "PPC.CodeGen.getRegister no 64 bit target"
| otherwise -> conversionNop (intFormat to) x
MO_UU_Conv W32 to
| arch32 -> conversionNop (intFormat to) x
| otherwise ->
case to of
W64 -> trivialCode to False AND x (CmmLit (CmmInt 4294967295 W64))
W16 -> conversionNop II16 x
W8 -> conversionNop II8 x
_ -> panic "PPC.CodeGen.getRegister: no match"
MO_UU_Conv W16 W8 -> conversionNop II8 x
MO_UU_Conv W8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 W32))
MO_UU_Conv W16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 W32))
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_ucode_int width instr = trivialUCode (intFormat width) instr x
triv_ucode_float width instr = trivialUCode (floatFormat width) instr x
conversionNop new_format expr
= do e_code <- getRegister' dflags expr
return (swizzleRegisterRep e_code new_format)
arch32 = target32Bit $ targetPlatform dflags
getRegister' dflags (CmmMachOp mop [x, y]) -- dyadic PrimOps
= case mop of
MO_F_Eq _ -> condFltReg EQQ x y
MO_F_Ne _ -> condFltReg NE x y
MO_F_Gt _ -> condFltReg GTT x y
MO_F_Ge _ -> condFltReg GE x y
MO_F_Lt _ -> condFltReg LTT x y
MO_F_Le _ -> condFltReg LE x y
MO_Eq rep -> condIntReg EQQ (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_Ne rep -> condIntReg NE (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_S_Gt rep -> condIntReg GTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Ge rep -> condIntReg GE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Lt rep -> condIntReg LTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Le rep -> condIntReg LE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Gt rep -> condIntReg GU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Ge rep -> condIntReg GEU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Lt rep -> condIntReg LU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Le rep -> condIntReg LEU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_F_Add w -> triv_float w FADD
MO_F_Sub w -> triv_float w FSUB
MO_F_Mul w -> triv_float w FMUL
MO_F_Quot w -> triv_float w FDIV
-- optimize addition with 32-bit immediate
-- (needed for PIC)
MO_Add W32 ->
case y of
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate W32 True (-imm)
-> trivialCode W32 True ADD x (CmmLit $ CmmInt imm immrep)
CmmLit lit
-> do
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
code dst = srcCode `appOL` toOL [
ADDIS dst src (HA imm),
ADD dst dst (RIImm (LO imm))
]
return (Any II32 code)
_ -> trivialCode W32 True ADD x y
MO_Add rep -> trivialCode rep True ADD x y
MO_Sub rep ->
case y of -- subfi ('substract from' with immediate) doesn't exist
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm)
-> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep)
_ -> trivialCodeNoImm' (intFormat rep) SUBF y x
MO_Mul rep
| arch32 -> trivialCode rep True MULLW x y
| otherwise -> trivialCode rep True MULLD x y
MO_S_MulMayOflo W32 -> trivialCodeNoImm' II32 MULLW_MayOflo x y
MO_S_MulMayOflo W64 -> trivialCodeNoImm' II64 MULLD_MayOflo x y
MO_S_MulMayOflo _ -> panic "S_MulMayOflo: (II8/16) not implemented"
MO_U_MulMayOflo _ -> panic "U_MulMayOflo: not implemented"
MO_S_Quot rep
| arch32 -> trivialCodeNoImm' (intFormat rep) DIVW
(extendSExpr dflags rep x) (extendSExpr dflags rep y)
| otherwise -> trivialCodeNoImm' (intFormat rep) DIVD
(extendSExpr dflags rep x) (extendSExpr dflags rep y)
MO_U_Quot rep
| arch32 -> trivialCodeNoImm' (intFormat rep) DIVWU
(extendUExpr dflags rep x) (extendUExpr dflags rep y)
| otherwise -> trivialCodeNoImm' (intFormat rep) DIVDU
(extendUExpr dflags rep x) (extendUExpr dflags rep y)
MO_S_Rem rep
| arch32 -> remainderCode rep DIVW (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
| otherwise -> remainderCode rep DIVD (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Rem rep
| arch32 -> remainderCode rep DIVWU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
| otherwise -> remainderCode rep DIVDU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_And rep -> trivialCode rep False AND x y
MO_Or rep -> trivialCode rep False OR x y
MO_Xor rep -> trivialCode rep False XOR x y
MO_Shl rep -> shiftCode rep SL x y
MO_S_Shr rep -> shiftCode rep SRA (extendSExpr dflags rep x) y
MO_U_Shr rep -> shiftCode rep SR (extendUExpr dflags rep x) y
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_float :: Width -> (Format -> Reg -> Reg -> Reg -> Instr) -> NatM Register
triv_float width instr = trivialCodeNoImm (floatFormat width) instr x y
arch32 = target32Bit $ targetPlatform dflags
getRegister' _ (CmmLit (CmmInt i rep))
| Just imm <- makeImmediate rep True i
= let
code dst = unitOL (LI dst imm)
in
return (Any (intFormat rep) code)
getRegister' _ (CmmLit (CmmFloat f frep)) = do
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let format = floatFormat frep
code dst =
LDATA (Section ReadOnlyData lbl)
(Statics lbl [CmmStaticLit (CmmFloat f frep)])
`consOL` (addr_code `snocOL` LD format dst addr)
return (Any format code)
getRegister' dflags (CmmLit lit)
| target32Bit (targetPlatform dflags)
= let rep = cmmLitType dflags lit
imm = litToImm lit
code dst = toOL [
LIS dst (HA imm),
ADD dst dst (RIImm (LO imm))
]
in return (Any (cmmTypeFormat rep) code)
| otherwise
= do lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let rep = cmmLitType dflags lit
format = cmmTypeFormat rep
code dst =
LDATA (Section ReadOnlyData lbl) (Statics lbl [CmmStaticLit lit])
`consOL` (addr_code `snocOL` LD format dst addr)
return (Any format code)
getRegister' _ other = pprPanic "getRegister(ppc)" (pprExpr other)
-- extend?Rep: wrap integer expression of type rep
-- in a conversion to II32 or II64 resp.
extendSExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr
extendSExpr dflags W32 x
| target32Bit (targetPlatform dflags) = x
extendSExpr dflags W64 x
| not (target32Bit (targetPlatform dflags)) = x
extendSExpr dflags rep x =
let size = if target32Bit $ targetPlatform dflags
then W32
else W64
in CmmMachOp (MO_SS_Conv rep size) [x]
extendUExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr
extendUExpr dflags W32 x
| target32Bit (targetPlatform dflags) = x
extendUExpr dflags W64 x
| not (target32Bit (targetPlatform dflags)) = x
extendUExpr dflags rep x =
let size = if target32Bit $ targetPlatform dflags
then W32
else W64
in CmmMachOp (MO_UU_Conv rep size) [x]
-- -----------------------------------------------------------------------------
-- The 'Amode' type: Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
data InstrForm = D | DS
getAmode :: InstrForm -> CmmExpr -> NatM Amode
getAmode inf tree@(CmmRegOff _ _)
= do dflags <- getDynFlags
getAmode inf (mangleIndexTree dflags tree)
getAmode _ (CmmMachOp (MO_Sub W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True (-i)
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True i
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode D (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True (-i)
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode D (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True i
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode DS (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True (-i)
= do
(reg, code) <- getSomeReg x
(reg', off', code') <-
if i `mod` 4 == 0
then do return (reg, off, code)
else do
tmp <- getNewRegNat II64
return (tmp, ImmInt 0,
code `snocOL` ADD tmp reg (RIImm off))
return (Amode (AddrRegImm reg' off') code')
getAmode DS (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True i
= do
(reg, code) <- getSomeReg x
(reg', off', code') <-
if i `mod` 4 == 0
then do return (reg, off, code)
else do
tmp <- getNewRegNat II64
return (tmp, ImmInt 0,
code `snocOL` ADD tmp reg (RIImm off))
return (Amode (AddrRegImm reg' off') code')
-- optimize addition with 32-bit immediate
-- (needed for PIC)
getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit lit])
= do
tmp <- getNewRegNat II32
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
code = srcCode `snocOL` ADDIS tmp src (HA imm)
return (Amode (AddrRegImm tmp (LO imm)) code)
getAmode _ (CmmLit lit)
= do
dflags <- getDynFlags
case platformArch $ targetPlatform dflags of
ArchPPC -> do
tmp <- getNewRegNat II32
let imm = litToImm lit
code = unitOL (LIS tmp (HA imm))
return (Amode (AddrRegImm tmp (LO imm)) code)
_ -> do -- TODO: Load from TOC,
-- see getRegister' _ (CmmLit lit)
tmp <- getNewRegNat II64
let imm = litToImm lit
code = toOL [
LIS tmp (HIGHESTA imm),
OR tmp tmp (RIImm (HIGHERA imm)),
SL II64 tmp tmp (RIImm (ImmInt 32)),
ORIS tmp tmp (HA imm)
]
return (Amode (AddrRegImm tmp (LO imm)) code)
getAmode _ (CmmMachOp (MO_Add W32) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmode _ (CmmMachOp (MO_Add W64) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmode _ other
= do
(reg, code) <- getSomeReg other
let
off = ImmInt 0
return (Amode (AddrRegImm reg off) code)
-- The 'CondCode' type: Condition codes passed up the tree.
data CondCode
= CondCode Bool Cond InstrBlock
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- almost the same as everywhere else - but we need to
-- extend small integers to 32 bit or 64 bit first
getCondCode (CmmMachOp mop [x, y])
= do
dflags <- getDynFlags
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq rep -> condIntCode EQQ (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_Ne rep -> condIntCode NE (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_S_Gt rep -> condIntCode GTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Ge rep -> condIntCode GE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Lt rep -> condIntCode LTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Le rep -> condIntCode LE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Gt rep -> condIntCode GU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Ge rep -> condIntCode GEU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Lt rep -> condIntCode LU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Le rep -> condIntCode LEU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
_ -> pprPanic "getCondCode(powerpc)" (pprMachOp mop)
getCondCode _ = panic "getCondCode(2)(powerpc)"
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- ###FIXME: I16 and I8!
-- TODO: Is this still an issue? All arguments are extend?Expr'd.
condIntCode cond x (CmmLit (CmmInt y rep))
| Just src2 <- makeImmediate rep (not $ condUnsigned cond) y
= do
(src1, code) <- getSomeReg x
dflags <- getDynFlags
let format = archWordFormat $ target32Bit $ targetPlatform dflags
code' = code `snocOL`
(if condUnsigned cond then CMPL else CMP) format src1 (RIImm src2)
return (CondCode False cond code')
condIntCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
dflags <- getDynFlags
let format = archWordFormat $ target32Bit $ targetPlatform dflags
code' = code1 `appOL` code2 `snocOL`
(if condUnsigned cond then CMPL else CMP) format src1 (RIReg src2)
return (CondCode False cond code')
condFltCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
code' = code1 `appOL` code2 `snocOL` FCMP src1 src2
code'' = case cond of -- twiddle CR to handle unordered case
GE -> code' `snocOL` CRNOR ltbit eqbit gtbit
LE -> code' `snocOL` CRNOR gtbit eqbit ltbit
_ -> code'
where
ltbit = 0 ; eqbit = 2 ; gtbit = 1
return (CondCode True cond code'')
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_IntCode pk addr src = do
(srcReg, code) <- getSomeReg src
Amode dstAddr addr_code <- case pk of
II64 -> getAmode DS addr
_ -> getAmode D addr
return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src
= do
dflags <- getDynFlags
let dst = getRegisterReg (targetPlatform dflags) reg
r <- getRegister src
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` MR dst freg
-- Easy, isn't it?
assignMem_FltCode = assignMem_IntCode
assignReg_FltCode = assignReg_IntCode
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (unitOL $ JMP lbl)
genJump tree
= do
dflags <- getDynFlags
let platform = targetPlatform dflags
case platformOS platform of
OSLinux -> case platformArch platform of
ArchPPC -> genJump' tree GCPLinux
ArchPPC_64 ELF_V1 -> genJump' tree (GCPLinux64ELF 1)
ArchPPC_64 ELF_V2 -> genJump' tree (GCPLinux64ELF 2)
_ -> panic "PPC.CodeGen.genJump: Unknown Linux"
OSDarwin -> genJump' tree GCPDarwin
_ -> panic "PPC.CodeGen.genJump: not defined for this os"
genJump' :: CmmExpr -> GenCCallPlatform -> NatM InstrBlock
genJump' tree (GCPLinux64ELF 1)
= do
(target,code) <- getSomeReg tree
return (code
`snocOL` LD II64 r11 (AddrRegImm target (ImmInt 0))
`snocOL` LD II64 toc (AddrRegImm target (ImmInt 8))
`snocOL` MTCTR r11
`snocOL` LD II64 r11 (AddrRegImm target (ImmInt 16))
`snocOL` BCTR [] Nothing)
genJump' tree (GCPLinux64ELF 2)
= do
(target,code) <- getSomeReg tree
return (code
`snocOL` MR r12 target
`snocOL` MTCTR r12
`snocOL` BCTR [] Nothing)
genJump' tree _
= do
(target,code) <- getSomeReg tree
return (code `snocOL` MTCTR target `snocOL` BCTR [] Nothing)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump id bool = do
CondCode _ cond code <- getCondCode bool
return (code `snocOL` BCC cond id)
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
genCCall :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall target dest_regs argsAndHints
= do dflags <- getDynFlags
let platform = targetPlatform dflags
case platformOS platform of
OSLinux -> case platformArch platform of
ArchPPC -> genCCall' dflags GCPLinux
target dest_regs argsAndHints
ArchPPC_64 ELF_V1 -> genCCall' dflags (GCPLinux64ELF 1)
target dest_regs argsAndHints
ArchPPC_64 ELF_V2 -> genCCall' dflags (GCPLinux64ELF 2)
target dest_regs argsAndHints
_ -> panic "PPC.CodeGen.genCCall: Unknown Linux"
OSDarwin -> genCCall' dflags GCPDarwin target dest_regs argsAndHints
_ -> panic "PPC.CodeGen.genCCall: not defined for this os"
data GenCCallPlatform = GCPLinux | GCPDarwin | GCPLinux64ELF Int
genCCall'
:: DynFlags
-> GenCCallPlatform
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
{-
The PowerPC calling convention for Darwin/Mac OS X
is described in Apple's document
"Inside Mac OS X - Mach-O Runtime Architecture".
PowerPC Linux uses the System V Release 4 Calling Convention
for PowerPC. It is described in the
"System V Application Binary Interface PowerPC Processor Supplement".
Both conventions are similar:
Parameters may be passed in general-purpose registers starting at r3, in
floating point registers starting at f1, or on the stack.
But there are substantial differences:
* The number of registers used for parameter passing and the exact set of
nonvolatile registers differs (see MachRegs.hs).
* On Darwin, stack space is always reserved for parameters, even if they are
passed in registers. The called routine may choose to save parameters from
registers to the corresponding space on the stack.
* On Darwin, a corresponding amount of GPRs is skipped when a floating point
parameter is passed in an FPR.
* SysV insists on either passing I64 arguments on the stack, or in two GPRs,
starting with an odd-numbered GPR. It may skip a GPR to achieve this.
Darwin just treats an I64 like two separate II32s (high word first).
* I64 and FF64 arguments are 8-byte aligned on the stack for SysV, but only
4-byte aligned like everything else on Darwin.
* The SysV spec claims that FF32 is represented as FF64 on the stack. GCC on
PowerPC Linux does not agree, so neither do we.
PowerPC 64 Linux uses the System V Release 4 Calling Convention for
64-bit PowerPC. It is specified in
"64-bit PowerPC ELF Application Binary Interface Supplement 1.9".
According to all conventions, the parameter area should be part of the
caller's stack frame, allocated in the caller's prologue code (large enough
to hold the parameter lists for all called routines). The NCG already
uses the stack for register spilling, leaving 64 bytes free at the top.
If we need a larger parameter area than that, we just allocate a new stack
frame just before ccalling.
-}
genCCall' _ _ (PrimTarget MO_WriteBarrier) _ _
= return $ unitOL LWSYNC
genCCall' _ _ (PrimTarget MO_Touch) _ _
= return $ nilOL
genCCall' _ _ (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall' dflags gcp target dest_regs args
= ASSERT(not $ any (`elem` [II16]) $ map cmmTypeFormat argReps)
-- we rely on argument promotion in the codeGen
do
(finalStack,passArgumentsCode,usedRegs) <- passArguments
(zip args argReps)
allArgRegs
(allFPArgRegs platform)
initialStackOffset
(toOL []) []
(labelOrExpr, reduceToFF32) <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do
uses_pic_base_implicitly
return (Left lbl, False)
ForeignTarget expr _ -> do
uses_pic_base_implicitly
return (Right expr, False)
PrimTarget mop -> outOfLineMachOp mop
let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode
`appOL` toc_before
codeAfter = toc_after labelOrExpr `appOL` move_sp_up finalStack
`appOL` moveResult reduceToFF32
case labelOrExpr of
Left lbl -> do -- the linker does all the work for us
return ( codeBefore
`snocOL` BL lbl usedRegs
`appOL` codeAfter)
Right dyn -> do -- implement call through function pointer
(dynReg, dynCode) <- getSomeReg dyn
case gcp of
GCPLinux64ELF 1 -> return ( dynCode
`appOL` codeBefore
`snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 0))
`snocOL` LD II64 toc (AddrRegImm dynReg (ImmInt 8))
`snocOL` MTCTR r11
`snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 16))
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
GCPLinux64ELF 2 -> return ( dynCode
`appOL` codeBefore
`snocOL` MR r12 dynReg
`snocOL` MTCTR r12
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
_ -> return ( dynCode
`snocOL` MTCTR dynReg
`appOL` codeBefore
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
where
platform = targetPlatform dflags
uses_pic_base_implicitly = do
-- See Note [implicit register in PPC PIC code]
-- on why we claim to use PIC register here
when (gopt Opt_PIC dflags && target32Bit platform) $ do
_ <- getPicBaseNat $ archWordFormat True
return ()
initialStackOffset = case gcp of
GCPDarwin -> 24
GCPLinux -> 8
GCPLinux64ELF 1 -> 48
GCPLinux64ELF 2 -> 32
_ -> panic "genCall': unknown calling convention"
-- size of linkage area + size of arguments, in bytes
stackDelta finalStack = case gcp of
GCPDarwin ->
roundTo 16 $ (24 +) $ max 32 $ sum $
map (widthInBytes . typeWidth) argReps
GCPLinux -> roundTo 16 finalStack
GCPLinux64ELF 1 ->
roundTo 16 $ (48 +) $ max 64 $ sum $
map (widthInBytes . typeWidth) argReps
GCPLinux64ELF 2 ->
roundTo 16 $ (32 +) $ max 64 $ sum $
map (widthInBytes . typeWidth) argReps
_ -> panic "genCall': unknown calling conv."
argReps = map (cmmExprType dflags) args
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
spFormat = if target32Bit platform then II32 else II64
move_sp_down finalStack
| delta > 64 =
toOL [STU spFormat sp (AddrRegImm sp (ImmInt (-delta))),
DELTA (-delta)]
| otherwise = nilOL
where delta = stackDelta finalStack
toc_before = case gcp of
GCPLinux64ELF 1 -> unitOL $ ST spFormat toc (AddrRegImm sp (ImmInt 40))
GCPLinux64ELF 2 -> unitOL $ ST spFormat toc (AddrRegImm sp (ImmInt 24))
_ -> nilOL
toc_after labelOrExpr = case gcp of
GCPLinux64ELF 1 -> case labelOrExpr of
Left _ -> toOL [ NOP ]
Right _ -> toOL [ LD spFormat toc
(AddrRegImm sp
(ImmInt 40))
]
GCPLinux64ELF 2 -> case labelOrExpr of
Left _ -> toOL [ NOP ]
Right _ -> toOL [ LD spFormat toc
(AddrRegImm sp
(ImmInt 24))
]
_ -> nilOL
move_sp_up finalStack
| delta > 64 = -- TODO: fix-up stack back-chain
toOL [ADD sp sp (RIImm (ImmInt delta)),
DELTA 0]
| otherwise = nilOL
where delta = stackDelta finalStack
passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed)
passArguments ((arg,arg_ty):args) gprs fprs stackOffset
accumCode accumUsed | isWord64 arg_ty
&& target32Bit (targetPlatform dflags) =
do
ChildCode64 code vr_lo <- iselExpr64 arg
let vr_hi = getHiVRegFromLo vr_lo
case gcp of
GCPDarwin ->
do let storeWord vr (gpr:_) _ = MR gpr vr
storeWord vr [] offset
= ST II32 vr (AddrRegImm sp (ImmInt offset))
passArguments args
(drop 2 gprs)
fprs
(stackOffset+8)
(accumCode `appOL` code
`snocOL` storeWord vr_hi gprs stackOffset
`snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
((take 2 gprs) ++ accumUsed)
GCPLinux ->
do let stackOffset' = roundTo 8 stackOffset
stackCode = accumCode `appOL` code
`snocOL` ST II32 vr_hi (AddrRegImm sp (ImmInt stackOffset'))
`snocOL` ST II32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4)))
regCode hireg loreg =
accumCode `appOL` code
`snocOL` MR hireg vr_hi
`snocOL` MR loreg vr_lo
case gprs of
hireg : loreg : regs | even (length gprs) ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_skipped : hireg : loreg : regs ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_ -> -- only one or no regs left
passArguments args [] fprs (stackOffset'+8)
stackCode accumUsed
GCPLinux64ELF _ -> panic "passArguments: 32 bit code"
passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed
| reg : _ <- regs = do
register <- getRegister arg
let code = case register of
Fixed _ freg fcode -> fcode `snocOL` MR reg freg
Any _ acode -> acode reg
stackOffsetRes = case gcp of
-- The Darwin ABI requires that we reserve
-- stack slots for register parameters
GCPDarwin -> stackOffset + stackBytes
-- ... the SysV ABI 32-bit doesn't.
GCPLinux -> stackOffset
-- ... but SysV ABI 64-bit does.
GCPLinux64ELF _ -> stackOffset + stackBytes
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
stackOffsetRes
(accumCode `appOL` code)
(reg : accumUsed)
| otherwise = do
(vr, code) <- getSomeReg arg
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
(stackOffset' + stackBytes)
(accumCode `appOL` code `snocOL` ST (cmmTypeFormat rep) vr stackSlot)
accumUsed
where
stackOffset' = case gcp of
GCPDarwin ->
-- stackOffset is at least 4-byte aligned
-- The Darwin ABI is happy with that.
stackOffset
GCPLinux
-- ... the SysV ABI requires 8-byte
-- alignment for doubles.
| isFloatType rep && typeWidth rep == W64 ->
roundTo 8 stackOffset
| otherwise ->
stackOffset
GCPLinux64ELF _ ->
-- everything on the stack is 8-byte
-- aligned on a 64 bit system
-- (except vector status, not used now)
stackOffset
stackSlot = AddrRegImm sp (ImmInt stackOffset')
(nGprs, nFprs, stackBytes, regs)
= case gcp of
GCPDarwin ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- The Darwin ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
FF32 -> (1, 1, 4, fprs)
FF64 -> (2, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPLinux ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- ... the SysV ABI doesn't.
FF32 -> (0, 1, 4, fprs)
FF64 -> (0, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPLinux64ELF _ ->
case cmmTypeFormat rep of
II8 -> (1, 0, 8, gprs)
II16 -> (1, 0, 8, gprs)
II32 -> (1, 0, 8, gprs)
II64 -> (1, 0, 8, gprs)
-- The ELFv1 ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
FF32 -> (1, 1, 8, fprs)
FF64 -> (1, 1, 8, fprs)
FF80 -> panic "genCCall' passArguments FF80"
moveResult reduceToFF32 =
case dest_regs of
[] -> nilOL
[dest]
| reduceToFF32 && isFloat32 rep -> unitOL (FRSP r_dest f1)
| isFloat32 rep || isFloat64 rep -> unitOL (MR r_dest f1)
| isWord64 rep && target32Bit (targetPlatform dflags)
-> toOL [MR (getHiVRegFromLo r_dest) r3,
MR r_dest r4]
| otherwise -> unitOL (MR r_dest r3)
where rep = cmmRegType dflags (CmmLocal dest)
r_dest = getRegisterReg platform (CmmLocal dest)
_ -> panic "genCCall' moveResult: Bad dest_regs"
outOfLineMachOp mop =
do
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference $
mkForeignLabel functionName Nothing ForeignLabelInThisPackage IsFunction
let mopLabelOrExpr = case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return (mopLabelOrExpr, reduce)
where
(functionName, reduce) = case mop of
MO_F32_Exp -> (fsLit "exp", True)
MO_F32_Log -> (fsLit "log", True)
MO_F32_Sqrt -> (fsLit "sqrt", True)
MO_F32_Sin -> (fsLit "sin", True)
MO_F32_Cos -> (fsLit "cos", True)
MO_F32_Tan -> (fsLit "tan", True)
MO_F32_Asin -> (fsLit "asin", True)
MO_F32_Acos -> (fsLit "acos", True)
MO_F32_Atan -> (fsLit "atan", True)
MO_F32_Sinh -> (fsLit "sinh", True)
MO_F32_Cosh -> (fsLit "cosh", True)
MO_F32_Tanh -> (fsLit "tanh", True)
MO_F32_Pwr -> (fsLit "pow", True)
MO_F64_Exp -> (fsLit "exp", False)
MO_F64_Log -> (fsLit "log", False)
MO_F64_Sqrt -> (fsLit "sqrt", False)
MO_F64_Sin -> (fsLit "sin", False)
MO_F64_Cos -> (fsLit "cos", False)
MO_F64_Tan -> (fsLit "tan", False)
MO_F64_Asin -> (fsLit "asin", False)
MO_F64_Acos -> (fsLit "acos", False)
MO_F64_Atan -> (fsLit "atan", False)
MO_F64_Sinh -> (fsLit "sinh", False)
MO_F64_Cosh -> (fsLit "cosh", False)
MO_F64_Tanh -> (fsLit "tanh", False)
MO_F64_Pwr -> (fsLit "pow", False)
MO_UF_Conv w -> (fsLit $ word2FloatLabel w, False)
MO_Memcpy _ -> (fsLit "memcpy", False)
MO_Memset _ -> (fsLit "memset", False)
MO_Memmove _ -> (fsLit "memmove", False)
MO_BSwap w -> (fsLit $ bSwapLabel w, False)
MO_PopCnt w -> (fsLit $ popCntLabel w, False)
MO_Clz w -> (fsLit $ clzLabel w, False)
MO_Ctz w -> (fsLit $ ctzLabel w, False)
MO_AtomicRMW w amop -> (fsLit $ atomicRMWLabel w amop, False)
MO_Cmpxchg w -> (fsLit $ cmpxchgLabel w, False)
MO_AtomicRead w -> (fsLit $ atomicReadLabel w, False)
MO_AtomicWrite w -> (fsLit $ atomicWriteLabel w, False)
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_SubWordC {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| (gopt Opt_PIC dflags) || (not $ target32Bit $ targetPlatform dflags)
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let code = e_code `appOL` t_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
LD fmt tmp (AddrRegReg tableReg tmp),
ADD tmp tmp (RIReg tableReg),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
| otherwise
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
let code = e_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
ADDIS tmp tmp (HA (ImmCLbl lbl)),
LD fmt tmp (AddrRegImm tmp (LO (ImmCLbl lbl))),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (BCTR ids (Just lbl)) =
let jumpTable
| (gopt Opt_PIC dflags)
|| (not $ target32Bit $ targetPlatform dflags)
= map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
where jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
where blockLabel = mkAsmTempLabel (getUnique blockid)
in Just (CmmData (Section ReadOnlyData lbl) (Statics lbl jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condReg :: NatM CondCode -> NatM Register
condReg getCond = do
CondCode _ cond cond_code <- getCond
dflags <- getDynFlags
let
code dst = cond_code
`appOL` negate_code
`appOL` toOL [
MFCR dst,
RLWINM dst dst (bit + 1) 31 31
]
negate_code | do_negate = unitOL (CRNOR bit bit bit)
| otherwise = nilOL
(bit, do_negate) = case cond of
LTT -> (0, False)
LE -> (1, True)
EQQ -> (2, False)
GE -> (0, True)
GTT -> (1, False)
NE -> (2, True)
LU -> (0, False)
LEU -> (1, True)
GEU -> (0, True)
GU -> (1, False)
_ -> panic "PPC.CodeGen.codeReg: no match"
format = archWordFormat $ target32Bit $ targetPlatform dflags
return (Any format code)
condIntReg cond x y = condReg (condIntCode cond x y)
condFltReg cond x y = condReg (condFltCode cond x y)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
Wolfgang's PowerPC version of The Rules:
A slightly modified version of The Rules to take advantage of the fact
that PowerPC instructions work on all registers and don't implicitly
clobber any fixed registers.
* The only expression for which getRegister returns Fixed is (CmmReg reg).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
It may *not* modify global registers, unless the global
register happens to be the destination register.
It may not clobber any other registers. In fact, only ccalls clobber any
fixed registers.
Also, it may not modify the counter register (used by genCCall).
Corollary: If a getRegister for a subexpression returns Fixed, you need
not move it to a fresh temporary before evaluating the next subexpression.
The Fixed register won't be modified.
Therefore, we don't need a counterpart for the x86's getStableReg on PPC.
* SDM's First Rule is valid for PowerPC, too: subexpressions can depend on
the value of the destination register.
-}
trivialCode
:: Width
-> Bool
-> (Reg -> Reg -> RI -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
trivialCode rep signed instr x (CmmLit (CmmInt y _))
| Just imm <- makeImmediate rep signed y
= do
(src1, code1) <- getSomeReg x
let code dst = code1 `snocOL` instr dst src1 (RIImm imm)
return (Any (intFormat rep) code)
trivialCode rep _ instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2)
return (Any (intFormat rep) code)
shiftCode
:: Width
-> (Format-> Reg -> Reg -> RI -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
shiftCode width instr x (CmmLit (CmmInt y _))
| Just imm <- makeImmediate width False y
= do
(src1, code1) <- getSomeReg x
let format = intFormat width
let code dst = code1 `snocOL` instr format dst src1 (RIImm imm)
return (Any format code)
shiftCode width instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let format = intFormat width
let code dst = code1 `appOL` code2 `snocOL` instr format dst src1 (RIReg src2)
return (Any format code)
trivialCodeNoImm' :: Format -> (Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm' format instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2
return (Any format code)
trivialCodeNoImm :: Format -> (Format -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm format instr x y = trivialCodeNoImm' format (instr format) x y
trivialUCode
:: Format
-> (Reg -> Reg -> Instr)
-> CmmExpr
-> NatM Register
trivialUCode rep instr x = do
(src, code) <- getSomeReg x
let code' dst = code `snocOL` instr dst src
return (Any rep code')
-- There is no "remainder" instruction on the PPC, so we have to do
-- it the hard way.
-- The "div" parameter is the division instruction to use (DIVW or DIVWU)
remainderCode :: Width -> (Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
remainderCode rep div x y = do
dflags <- getDynFlags
let mull_instr = if target32Bit $ targetPlatform dflags then MULLW
else MULLD
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `appOL` toOL [
div dst src1 src2,
mull_instr dst dst (RIReg src2),
SUBF dst dst src1
]
return (Any (intFormat rep) code)
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP fromRep toRep x = do
dflags <- getDynFlags
let arch = platformArch $ targetPlatform dflags
coerceInt2FP' arch fromRep toRep x
coerceInt2FP' :: Arch -> Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP' ArchPPC fromRep toRep x = do
(src, code) <- getSomeReg x
lbl <- getNewLabelNat
itmp <- getNewRegNat II32
ftmp <- getNewRegNat FF64
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let
code' dst = code `appOL` maybe_exts `appOL` toOL [
LDATA (Section ReadOnlyData lbl) $ Statics lbl
[CmmStaticLit (CmmInt 0x43300000 W32),
CmmStaticLit (CmmInt 0x80000000 W32)],
XORIS itmp src (ImmInt 0x8000),
ST II32 itmp (spRel dflags 3),
LIS itmp (ImmInt 0x4330),
ST II32 itmp (spRel dflags 2),
LD FF64 ftmp (spRel dflags 2)
] `appOL` addr_code `appOL` toOL [
LD FF64 dst addr,
FSUB FF64 dst ftmp dst
] `appOL` maybe_frsp dst
maybe_exts = case fromRep of
W8 -> unitOL $ EXTS II8 src src
W16 -> unitOL $ EXTS II16 src src
W32 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
maybe_frsp dst
= case toRep of
W32 -> unitOL $ FRSP dst dst
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
return (Any (floatFormat toRep) code')
-- On an ELF v1 Linux we use the compiler doubleword in the stack frame
-- this is the TOC pointer doubleword on ELF v2 Linux. The latter is only
-- set right before a call and restored right after return from the call.
-- So it is fine.
coerceInt2FP' (ArchPPC_64 _) fromRep toRep x = do
(src, code) <- getSomeReg x
dflags <- getDynFlags
let
code' dst = code `appOL` maybe_exts `appOL` toOL [
ST II64 src (spRel dflags 3),
LD FF64 dst (spRel dflags 3),
FCFID dst dst
] `appOL` maybe_frsp dst
maybe_exts = case fromRep of
W8 -> unitOL $ EXTS II8 src src
W16 -> unitOL $ EXTS II16 src src
W32 -> unitOL $ EXTS II32 src src
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
maybe_frsp dst
= case toRep of
W32 -> unitOL $ FRSP dst dst
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
return (Any (floatFormat toRep) code')
coerceInt2FP' _ _ _ _ = panic "PPC.CodeGen.coerceInt2FP: unknown arch"
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int fromRep toRep x = do
dflags <- getDynFlags
let arch = platformArch $ targetPlatform dflags
coerceFP2Int' arch fromRep toRep x
coerceFP2Int' :: Arch -> Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int' ArchPPC _ toRep x = do
dflags <- getDynFlags
-- the reps don't really matter: F*->FF64 and II32->I* are no-ops
(src, code) <- getSomeReg x
tmp <- getNewRegNat FF64
let
code' dst = code `appOL` toOL [
-- convert to int in FP reg
FCTIWZ tmp src,
-- store value (64bit) from FP to stack
ST FF64 tmp (spRel dflags 2),
-- read low word of value (high word is undefined)
LD II32 dst (spRel dflags 3)]
return (Any (intFormat toRep) code')
coerceFP2Int' (ArchPPC_64 _) _ toRep x = do
dflags <- getDynFlags
-- the reps don't really matter: F*->FF64 and II64->I* are no-ops
(src, code) <- getSomeReg x
tmp <- getNewRegNat FF64
let
code' dst = code `appOL` toOL [
-- convert to int in FP reg
FCTIDZ tmp src,
-- store value (64bit) from FP to compiler word on stack
ST FF64 tmp (spRel dflags 3),
LD II64 dst (spRel dflags 3)]
return (Any (intFormat toRep) code')
coerceFP2Int' _ _ _ _ = panic "PPC.CodeGen.coerceFP2Int: unknown arch"
-- Note [.LCTOC1 in PPC PIC code]
-- The .LCTOC1 label is defined to point 32768 bytes into the GOT table
-- to make the most of the PPC's 16-bit displacements.
-- As 16-bit signed offset is used (usually via addi/lwz instructions)
-- first element will have '-32768' offset against .LCTOC1.
-- Note [implicit register in PPC PIC code]
-- PPC generates calls by labels in assembly
-- in form of:
-- bl puts+32768@plt
-- in this form it's not seen directly (by GHC NCG)
-- that r30 (PicBaseReg) is used,
-- but r30 is a required part of PLT code setup:
-- puts+32768@plt:
-- lwz r11,-30484(r30) ; offset in .LCTOC1
-- mtctr r11
-- bctr
| oldmanmike/ghc | compiler/nativeGen/PPC/CodeGen.hs | bsd-3-clause | 73,920 | 0 | 28 | 26,172 | 18,496 | 9,131 | 9,365 | -1 | -1 |
module Compose where
{-@
cmp :: forall < p :: b -> c -> Prop
, q :: a -> b -> Prop
, r :: a -> c -> Prop
>.
{x::a, w::b<q x> |- c<p w> <: c<r x>}
f:(y:b -> c<p y>)
-> g:(z:a -> b<q z>)
-> x:a -> c<r x>
@-}
cmp :: (b -> c)
-> (a -> b)
-> a -> c
cmp f g x = f (g x)
{-@ incr :: x:Nat -> {v:Nat | v == x + 1} @-}
incr :: Int -> Int
incr x = x + 1
{-@ incr2 :: x:Nat -> {v:Nat | v = x + 2} @-}
incr2 :: Int -> Int
incr2 = incr `cmp` incr
{-@ incr2' :: x:Nat -> {v:Nat | v = x + 2} @-}
incr2' :: Int -> Int
incr2' = incr `cmp` incr
{-@ plusminus :: n:Nat -> m:Nat -> x:{Nat | x <= m} -> {v:Nat | v < (m - x) + n} @-}
plusminus :: Int -> Int -> Int -> Int
plusminus n m = (n+) `cmp` (m-)
{-@ plus :: n:a -> x:a -> {v:a | v = (x + n)} @-}
plus :: Num a => a -> a -> a
plus = undefined
minus :: Num a => a -> a -> a
{-@ minus :: n:a -> x:a -> {v:a | v = x - n} @-}
minus _ _ = undefined
{-@ plus1 :: x:Nat -> {v:Nat | v == x + 20} @-}
plus1 :: Int -> Int
plus1 x = x + 20
{-@ plus2 :: x:{v:Nat | v > 10} -> {v:Nat | v == x + 2} @-}
plus2 :: Int -> Int
plus2 x = x + 2
{-@ plus42 :: x:Nat -> {v:Nat | v == x + 42} @-}
plus42 :: Int -> Int
plus42 = cmp plus2 plus1
{-@ qualif PLUSMINUS(v:int, x:int, y:int, z:int): (v = (x - y) + z) @-}
{-@ qualif PLUS (v:int, x:int, y:int) : (v = x + y) @-}
{-@ qualif MINUS (v:int, x:int, y:int) : (v = x - y) @-}
| mightymoose/liquidhaskell | benchmarks/icfp15/neg/Composition.hs | bsd-3-clause | 1,474 | 0 | 8 | 493 | 287 | 162 | 125 | 23 | 1 |
{-# LANGUAGE TypeFamilies, PatternGuards, CPP #-}
module Yesod.Core.Internal.LiteApp where
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid
#endif
import Yesod.Routes.Class
import Yesod.Core.Class.Yesod
import Yesod.Core.Class.Dispatch
import Yesod.Core.Types
import Yesod.Core.Content
import Data.Text (Text)
import Web.PathPieces
import Network.Wai
import Yesod.Core.Handler
import Yesod.Core.Internal.Run
import Network.HTTP.Types (Method)
import Data.Maybe (fromMaybe)
import Control.Applicative ((<|>))
import Control.Monad.Trans.Writer
newtype LiteApp = LiteApp
{ unLiteApp :: Method -> [Text] -> Maybe (LiteHandler TypedContent)
}
instance Yesod LiteApp
instance YesodDispatch LiteApp where
yesodDispatch yre req =
yesodRunner
(fromMaybe notFound $ f (requestMethod req) (pathInfo req))
yre
(Just $ LiteAppRoute $ pathInfo req)
req
where
LiteApp f = yreSite yre
instance RenderRoute LiteApp where
data Route LiteApp = LiteAppRoute [Text]
deriving (Show, Eq, Read, Ord)
renderRoute (LiteAppRoute x) = (x, [])
instance ParseRoute LiteApp where
parseRoute (x, _) = Just $ LiteAppRoute x
instance Monoid LiteApp where
mempty = LiteApp $ \_ _ -> Nothing
mappend (LiteApp x) (LiteApp y) = LiteApp $ \m ps -> x m ps <|> y m ps
type LiteHandler = HandlerT LiteApp IO
type LiteWidget = WidgetT LiteApp IO
liteApp :: Writer LiteApp () -> LiteApp
liteApp = execWriter
dispatchTo :: ToTypedContent a => LiteHandler a -> Writer LiteApp ()
dispatchTo handler = tell $ LiteApp $ \_ ps ->
if null ps
then Just $ fmap toTypedContent handler
else Nothing
onMethod :: Method -> Writer LiteApp () -> Writer LiteApp ()
onMethod method f = tell $ LiteApp $ \m ps ->
if method == m
then unLiteApp (liteApp f) m ps
else Nothing
onStatic :: Text -> Writer LiteApp () -> Writer LiteApp ()
onStatic p0 f = tell $ LiteApp $ \m ps0 ->
case ps0 of
p:ps | p == p0 -> unLiteApp (liteApp f) m ps
_ -> Nothing
withDynamic :: PathPiece p => (p -> Writer LiteApp ()) -> Writer LiteApp ()
withDynamic f = tell $ LiteApp $ \m ps0 ->
case ps0 of
p:ps | Just v <- fromPathPiece p -> unLiteApp (liteApp $ f v) m ps
_ -> Nothing
withDynamicMulti :: PathMultiPiece ps => (ps -> Writer LiteApp ()) -> Writer LiteApp ()
withDynamicMulti f = tell $ LiteApp $ \m ps ->
case fromPathMultiPiece ps of
Nothing -> Nothing
Just v -> unLiteApp (liteApp $ f v) m []
| MaxGabriel/yesod | yesod-core/Yesod/Core/Internal/LiteApp.hs | mit | 2,542 | 0 | 14 | 596 | 906 | 472 | 434 | 66 | 2 |
{-| Ganeti logging functions expressed using MonadBase
This allows to use logging functions without having instances for all
possible transformers.
-}
{-
Copyright (C) 2014 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.Logging.Lifted
( MonadLog()
, Priority(..)
, L.withErrorLogAt
, L.isDebugMode
, logAt
, logDebug
, logInfo
, logNotice
, logWarning
, logError
, logCritical
, logAlert
, logEmergency
) where
import Control.Monad.Base
import Ganeti.Logging (MonadLog, Priority(..))
import qualified Ganeti.Logging as L
-- * Logging function aliases for MonadBase
-- | A monad that allows logging.
logAt :: (MonadLog b, MonadBase b m) => Priority -> String -> m ()
logAt p = liftBase . L.logAt p
-- | Log at debug level.
logDebug :: (MonadLog b, MonadBase b m) => String -> m ()
logDebug = logAt DEBUG
-- | Log at info level.
logInfo :: (MonadLog b, MonadBase b m) => String -> m ()
logInfo = logAt INFO
-- | Log at notice level.
logNotice :: (MonadLog b, MonadBase b m) => String -> m ()
logNotice = logAt NOTICE
-- | Log at warning level.
logWarning :: (MonadLog b, MonadBase b m) => String -> m ()
logWarning = logAt WARNING
-- | Log at error level.
logError :: (MonadLog b, MonadBase b m) => String -> m ()
logError = logAt ERROR
-- | Log at critical level.
logCritical :: (MonadLog b, MonadBase b m) => String -> m ()
logCritical = logAt CRITICAL
-- | Log at alert level.
logAlert :: (MonadLog b, MonadBase b m) => String -> m ()
logAlert = logAt ALERT
-- | Log at emergency level.
logEmergency :: (MonadLog b, MonadBase b m) => String -> m ()
logEmergency = logAt EMERGENCY
| apyrgio/ganeti | src/Ganeti/Logging/Lifted.hs | bsd-2-clause | 2,867 | 0 | 9 | 518 | 466 | 258 | 208 | 37 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bool
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- The 'Bool' type and related functions.
--
-----------------------------------------------------------------------------
module Data.Bool (
-- * Booleans
Bool(..),
-- ** Operations
(&&), -- :: Bool -> Bool -> Bool
(||), -- :: Bool -> Bool -> Bool
not, -- :: Bool -> Bool
otherwise, -- :: Bool
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base
#endif
#ifdef __NHC__
import Prelude
import Prelude
( Bool(..)
, (&&)
, (||)
, not
, otherwise
)
#endif
| beni55/haste-compiler | libraries/ghc-7.8/base/Data/Bool.hs | bsd-3-clause | 919 | 0 | 6 | 203 | 93 | 73 | 20 | 8 | 0 |
module D where
data T = A Int | B Float deriving Eq
f x = x + 1
| urbanslug/ghc | testsuite/tests/ghci/prog001/D2.hs | bsd-3-clause | 66 | 0 | 6 | 21 | 33 | 19 | 14 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module HelpMenu (helpMenu, HelpT, helpWidgit) where
import Graphics.Vty hiding (pad)
import Graphics.Vty.Widgets.All
import System.Exit ( exitSuccess )
-- Visual attributes.
msgAttr :: Attr
msgAttr = fgColor blue
data HelpT = HelpT { helpWidgit :: Widget (VCentered (HCentered
(Bordered FormattedText)))
}
-- --------- --
-- Help Menu --
-- --------- --
helpMenu :: IO (HelpT, Widget FocusGroup)
helpMenu = do
-- ahs <- newHandlers
-- .
let msg = "- <TAB> switches input elements\n\n\
\- ordinary keystrokes edit\n\n\
\- <SPC> toggles checkboxes\n\n\
\- <ESC> quits"
helpBox <- bordered =<< (textWidget wrap msg >>= withNormalAttribute msgAttr)
setBorderedLabel helpBox "Help"
ui <- centered helpBox
let w = HelpT ui
fg <- newFocusGroup
addToFocusGroup fg ui
fg `onKeyPressed` \_ k _ ->
case k of
KEsc -> exitSuccess
_ -> return False
return (w, fg)
| alterapraxisptyltd/serialterm | src/HelpMenu.hs | isc | 1,028 | 0 | 15 | 278 | 250 | 132 | 118 | 23 | 2 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.EXTBlendMinMax
(pattern MIN_EXT, pattern MAX_EXT, EXTBlendMinMax(..),
gTypeEXTBlendMinMax)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
pattern MIN_EXT = 32775
pattern MAX_EXT = 32776
| ghcjs/jsaddle-dom | src/JSDOM/Generated/EXTBlendMinMax.hs | mit | 1,104 | 0 | 6 | 135 | 318 | 210 | 108 | 21 | 0 |
-- 1. It’s not a typo, we’re just being cute with the name.
data TisAnInteger = TisAn Integer
instance Eq TisAnInteger where
(==) (TisAn a) (TisAn b) = a == b
--2.
data TwoIntegers = Two Integer Integer
instance Eq TwoIntegers where
(==) (Two a b) (Two a' b') =
a == a' && b == b'
-- 3.
data StringOrInt = TisAnInt Int | TisAString String
instance Eq StringOrInt where
(==) (TisAnInt _) (TisAString _) = False
(==) (TisAnInt a) (TisAnInt a') = a == a'
(==) (TisAString a) (TisAString a') = a == a'
-- 4.
data Pair a = Pair a a
instance (Eq a) => Eq (Pair a) where
(==) (Pair a b) (Pair a' b') = a == a' && b == b'
-- 5.
data Tuple a b = Tuple a b
instance (Eq a, Eq b) => Eq (Tuple a b) where
(==) (Tuple a b) (Tuple a' b') = a == a' && b == b'
-- 6.
data Which a = ThisOne a | ThatOne a
instance Eq a => Eq (Which a) where
(==) (ThisOne a) (ThatOne a') = a == a'
(==) (ThisOne a) (ThisOne a') = a == a'
(==) (ThatOne a) (ThatOne a') = a == a'
-- 7.
data EitherOr a b = Hello a | Goodbye b
instance (Eq a, Eq b) => Eq (EitherOr a b) where
(==) (Hello _) (Goodbye _) = False
(==) (Hello a) (Hello a') = a == a'
(==) (Goodbye a) (Goodbye a') = a == a'
| diminishedprime/.org | reading-list/haskell_programming_from_first_principles/06_12.hs | mit | 1,184 | 0 | 8 | 288 | 620 | 335 | 285 | 28 | 0 |
main = putStrLn . show. sum $ [ x | x <- [1..999], (x `mod` 3) == 0 || (x `mod` 5) == 0]
| clementlee/projecteuler-haskell | p1.hs | mit | 89 | 0 | 12 | 24 | 68 | 38 | 30 | 1 | 1 |
module Graphics.Layouts (
fixedLayout,
borderLayout,
AnchorConstraint(..),
anchorLayout,
adaptativeLayout,
) where
import Data.Maybe
import Data.Tree
import Data.Tree.Zipper
import Graphics.Rendering.OpenGL
import Graphics.View
----------------------------------------------------------------------------------------------------
setBounds position size tree = layoutSetSize (viewLayout (rootLabel tree')) size tree' where
tree' = setPosition position tree
fixedLayout (Size w h) = Layout
(const (Just w, Just h))
setSize
{-
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ top ┃
┠─────┬──────────────┬─────┨
┃ │ │ ┃
┃ │ │ ┃
┃ │ │ ┃
┃left │ center │right┃
┃ │ │ ┃
┃ │ │ ┃
┃ │ │ ┃
┠─────┴──────────────┴─────┨
┃ bottom ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛
-}
data BordelLayouPosition = Center | Top | Left | Bottom | Right
borderLayout :: [BordelLayouPosition] -> Layout a
borderLayout positions = undefined -- TODO
{-
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ▲ ┃
┃ ┆ top ┃
┃ ▼ ┃
┃ ┌───────┐ ┃
┃ left │ │ right┃
┃◀---------▶│ │◀----▶┃
┃ │ │ ┃
┃ └───────┘ ┃
┃ ▲ ┃
┃ ┆ bottom ┃
┃ ▼ ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛
-}
data AnchorConstraint = AnchorConstraint
{ topDistance :: Maybe GLsizei
, rightDistance :: Maybe GLsizei
, bottomDistance :: Maybe GLsizei
, leftDistance :: Maybe GLsizei
} deriving Show
anchorLayout :: [AnchorConstraint] -> Layout a
anchorLayout constraints = Layout getter setter where
getter t = (Nothing, Nothing)
setter s t = setSize s t{ subForest = zipWith updateChild constraints (subForest t) } where
(Size w h) = s
updateChild constraint child = setBounds (Position xChild yChild) (Size wChild hChild) child where
(mWidth, mHeigh) = layoutGetNaturalSize (viewLayout (rootLabel child)) child
(xChild, wChild) = case (leftDistance constraint, mWidth, rightDistance constraint) of
(Nothing, _, Nothing) -> let iw = fromMaybe w mWidth in ((w - iw) `div` 2, iw) -- centrage
(Just l, _, Nothing) -> (l, w') where w' = fromMaybe (w - l) mWidth
(Nothing, _, Just r) -> (w - w' - r, w') where w' = fromMaybe (w - r) mWidth
(Just l, _, Just r) -> (l, w - l - r) -- La taille naturelle du composant est ignorée.
(yChild, hChild) = case (topDistance constraint, mHeigh, bottomDistance constraint) of
(Nothing, _, Nothing) -> let ih = fromMaybe h mHeigh in ((h - ih) `div` 2, ih) -- centrage
(Just t, _, Nothing) -> (t, h') where h' = fromMaybe (h - t) mHeigh
(Nothing, _, Just b) -> (h - h' - b, h') where h' = fromMaybe (h - b) mHeigh
(Just t, _, Just b) -> (t, h - t - b) -- La taille naturelle du composant est ignorée.
{-
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ┃
┃ 9x27 ┃
┃ (master) ┃
┃ ┃
┃ ┃
┃ ┃
┃ ┃
┃ ┃
┠────────┬────────┬────────┨
┃ 3x9 │ 3x9 │ 3x9 ┃
┃(slave) │(slave) │(slave) ┃
┗━━━━━━━━┷━━━━━━━━┷━━━━━━━━┛
-}
adaptativeLayout :: Layout a
adaptativeLayout = Layout getter setter where
getter t = case subForest t of
[] -> (Nothing, Nothing)
(master : slaves) ->
let n = fromIntegral (length slaves)
(mw, mh) = layoutGetNaturalSize (viewLayout (rootLabel master)) master
in if n > 0
then (mw, (\h -> h + h `div` n) <$> mh)
else (mw, mh)
setter s t = setSize s t' where
t' = case subForest t of
[] -> t
(master : slaves) ->
let n = fromIntegral (length slaves)
in if n > 0
then
let
(Size w h) = s
wMaster = w
hMaster = (n * h) `div` (n + 1)
wSlave = w `div` n
hSlave = h - hMaster
master' = setBounds (Position 0 0) (Size wMaster hMaster) master
updateSlave index = setBounds (Position (wSlave * index) hMaster) (Size wSlave hSlave)
in
t{ subForest = master' : zipWith updateSlave [0..] slaves }
else
t{ subForest = [setBounds (Position 0 0) s master] }
| Chatanga/kage | src/Graphics/Layouts.hs | mit | 5,724 | 0 | 23 | 2,070 | 1,237 | 671 | 566 | 68 | 7 |
{-# LANGUAGE DeriveGeneric #-}
module Handler.Account where
import Import
import Yesod.Auth.Simple (setPasswordR)
import Util.Slug (mkSlug)
import Util.User (newToken)
import Util.Handler (title)
import Util.Alert (successHtml)
import qualified Model.Snippet.Api as SnippetApi
import qualified Model.Run.Api as RunApi
data ProfileData = ProfileData {
name :: Text,
username :: Text
} deriving (Show, Generic)
instance FromJSON ProfileData
getAccountProfileR :: Handler Html
getAccountProfileR = do
userId <- requireAuthId
Entity _ profile <- runDB $ getBy404 $ UniqueProfile userId
defaultLayout $ do
setTitle $ title "Profile"
$(widgetFile "account/profile")
putAccountProfileR :: Handler Value
putAccountProfileR = do
userId <- requireAuthId
profileData <- requireJsonBody :: Handler ProfileData
Entity profileId _ <- runDB $ getBy404 $ UniqueProfile userId
now <- liftIO getCurrentTime
runDB $ update profileId [
ProfileName =. name profileData,
ProfileUsername =. (mkSlug $ username profileData),
ProfileModified =. now]
setMessage $ successHtml "Profile updated"
return $ object []
getAccountTokenR :: Handler Html
getAccountTokenR = do
userId <- requireAuthId
Entity _ apiUser <- runDB $ getBy404 $ UniqueApiUser userId
defaultLayout $ do
setTitle $ title "Api token"
$(widgetFile "account/token")
putAccountTokenR :: Handler Value
putAccountTokenR = do
userId <- requireAuthId
Entity apiUserId apiUser <- runDB $ getBy404 $ UniqueApiUser userId
token <- liftIO newToken
liftIO $ SnippetApi.setUserToken (apiUserSnippetsId apiUser) token
liftIO $ RunApi.setUserToken (apiUserRunId apiUser) token
now <- liftIO getCurrentTime
runDB $ update apiUserId [ApiUserToken =. token, ApiUserModified =. now]
setMessage $ successHtml "New token generated"
return $ object []
| vinnymac/glot-www | Handler/Account.hs | mit | 1,929 | 0 | 13 | 387 | 543 | 266 | 277 | 52 | 1 |
module Main where
{- A Tic-Tac-Toe Board
012
345
678
-}
import TTT.GameLogic as GL
main :: IO ()
main = print $
GL.hasWon 012 | tripattern/haskell | ticTacToe/src/Main.hs | mit | 138 | 0 | 7 | 37 | 36 | 21 | 15 | 5 | 1 |
{-|
Module : Database.Orville.PostgreSQL.Internal.Select
Copyright : Flipstone Technology Partners 2016-2018
License : MIT
-}
module Database.Orville.PostgreSQL.Internal.Select where
import Control.Monad.Reader
import qualified Data.List as List
import Database.HDBC
import Database.Orville.PostgreSQL.Internal.Expr
import Database.Orville.PostgreSQL.Internal.FieldDefinition (fieldToNameForm)
import Database.Orville.PostgreSQL.Internal.FromClause
import Database.Orville.PostgreSQL.Internal.SelectOptions
import Database.Orville.PostgreSQL.Internal.Types
data Select row = Select
{ selectBuilder :: FromSql row
, selectSql :: String
, selectValues :: [SqlValue]
}
selectQueryColumns ::
[SelectExpr] -> FromSql row -> FromClause -> SelectOptions -> Select row
selectQueryColumns selectExprs builder fromClause opts =
selectQueryRaw builder querySql (selectOptValues opts)
where
columns =
List.intercalate ", " $ map (rawExprToSql . generateSql) selectExprs
querySql =
List.concat
[ selectClause opts
, columns
, " "
, fromClauseToSql fromClause
, " "
, selectOptClause opts
]
selectQuery :: FromSql row -> FromClause -> SelectOptions -> Select row
selectQuery builder =
selectQueryColumns (expr <$> fromSqlSelects builder) builder
selectQueryTable ::
TableDefinition readEntity writeEntity key
-> SelectOptions
-> Select readEntity
selectQueryTable tbl = selectQuery (tableFromSql tbl) (fromClauseTable tbl)
selectQueryRows ::
[SelectExpr] -> FromClause -> SelectOptions -> Select [(String, SqlValue)]
selectQueryRows exprs = selectQueryColumns exprs rowFromSql
selectQueryRaw :: FromSql row -> String -> [SqlValue] -> Select row
selectQueryRaw = Select
selectQueryRawRows :: String -> [SqlValue] -> Select [(String, SqlValue)]
selectQueryRawRows = selectQueryRaw rowFromSql
-- N.B. This FromSql does *not* contain an accurate list of the columns
-- it decodes, because it does not decode any columns at all. It is not
-- suitable for uses where the FromSql is used to generate the columns in
-- a select clause. It is not exposed publically for this reason.
--
rowFromSql :: FromSql [(String, SqlValue)]
rowFromSql =
FromSql
{ fromSqlSelects =
error
"Database.Orville.PostgreSQL.Select.rowFromSql: fromSqlColumnNames was accessed. This is a bug."
, runFromSql = Right <$> ask
}
selectField :: FieldDefinition nulability a -> SelectForm
selectField field = selectColumn (fieldToNameForm field)
| flipstone/orville | orville-postgresql/src/Database/Orville/PostgreSQL/Internal/Select.hs | mit | 2,552 | 0 | 10 | 448 | 515 | 287 | 228 | 51 | 1 |
module Solar.Caster.Client where
| Cordite-Studios/solar | solar-wind/Solar/Caster/Client.hs | mit | 33 | 0 | 3 | 3 | 7 | 5 | 2 | 1 | 0 |
module Exercise where
money :: Int -> [[Int]]
money 0 = [[]]
money n = [(k:rest) | k <- [1,2,5,10,20,50],
k <= n,
rest <- (money (n - k)),
k <= minimum (n:rest), -- ordering does not matter
n == sum (k:rest)
]
| tcoenraad/functioneel-programmeren | 2014/opg1b.hs | mit | 321 | 0 | 11 | 154 | 142 | 79 | 63 | 8 | 1 |
------------------------------------------------------------------------------
-- |
-- Module : Hajong.Server.Config
-- Copyright : (C) 2016 Samuli Thomasson
-- License : %% (see the file LICENSE)
-- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi>
-- Stability : experimental
-- Portability : non-portable
--
-- Game server configuration.
------------------------------------------------------------------------------
module Hajong.Server.Config where
import Import
import Data.Aeson (FromJSON(..), withObject, (.:), (.:?), (.!=))
import Data.Yaml (decodeFileEither, parseEither)
import System.Exit (exitFailure)
data ServerConfig = ServerConfig
{ _websocketHost :: String
-- ^ Host to use for incoming websocket clients. Default to 0.0.0.0
, _websocketPort :: Int
-- ^ Port to use for incoming websocket clients.
, _databaseSocket :: FilePath
-- ^ Provide access to the ACIDic database at this socket.
, _logDirectory :: FilePath
-- ^ Directory to store logs into
, _websocketCtrlSecret :: Text
-- ^ A secret key a client must know to gain access into the internal
-- control channel via WS.
} deriving (Show, Read, Eq, Typeable)
instance FromJSON ServerConfig where
parseJSON = withObject "ServerConfig" $ \o -> do
_websocketHost <- o .:? "websocket-addr" .!= "0.0.0.0"
_websocketPort <- o .: "websocket-port"
_websocketCtrlSecret <- o .: "ctrl-secret-ws"
_databaseSocket <- o .: "db-socket-file"
_logDirectory <- o .: "logs-directory"
return ServerConfig{..}
-- * Reading configuration
-- | Exits when the configuration could not be read.
readConfigFile :: FilePath
-> Maybe Text -- ^ Optional subsection to use as the root.
-> IO ServerConfig
readConfigFile file mobj = do
val <- decodeFileEither file >>= either (\err -> print err >> exitFailure) return
either (\err -> print err >> exitFailure) return $
parseEither (maybe parseJSON (\k -> withObject "ServerConfig" (.: k)) mobj) val
-- * Lenses
makeLenses ''ServerConfig
| SimSaladin/hajong | hajong-server/src/Hajong/Server/Config.hs | mit | 2,149 | 0 | 14 | 475 | 369 | 208 | 161 | -1 | -1 |
module Yi.Keymap.Vim.Digraph
( charFromDigraph
, defDigraphs
) where
import Control.Applicative
charFromDigraph :: [(String, Char)] -> Char -> Char -> Maybe Char
charFromDigraph digraphTable c1 c2 =
lookup [c1, c2] digraphTable <|> lookup [c2, c1] digraphTable
defDigraphs :: [(String, Char)]
defDigraphs =
[ ("ae", 'æ')
, ("a'", 'á')
, ("e'", 'é')
, ("e`", 'è')
, ("o\"", 'ő')
, ("o:", 'ö')
, ("a:", 'ä')
, ("e:", 'ë')
, ("u:", 'ü')
, ("AE", 'Æ')
, ("Ae", 'Æ')
, ("A'", 'Á')
, ("E'", 'É')
, ("E`", 'È')
, ("O\"", 'Ő')
, ("O:", 'Ö')
, ("A:", 'Ä')
, ("E:", 'Ë')
, ("U:", 'Ü')
, ("=e", '€')
, ("Cu", '¤')
, ("+-", '±')
, ("-+", '∓')
, ("^1", '¹')
, ("^2", '²')
, ("^3", '³')
, ("^4", '⁴')
, ("^5", '⁵')
, ("^6", '⁶')
, ("^7", '⁷')
, ("^8", '⁸')
, ("^9", '⁹')
, ("0S", '⁰')
, ("1S", '¹')
, ("2S", '²')
, ("3S", '³')
, ("4S", '⁴')
, ("5S", '⁵')
, ("6S", '⁶')
, ("7S", '⁷')
, ("8S", '⁸')
, ("9S", '⁹')
, ("0S", '⁰')
, ("0s", '₀')
, ("1s", '₁')
, ("2s", '₂')
, ("3s", '₃')
, ("4s", '₄')
, ("5s", '₅')
, ("6s", '₆')
, ("7s", '₇')
, ("8s", '₈')
, ("9s", '₉')
, ("0s", '₀')
, ("'0", '˚')
]
| atsukotakahashi/wi | src/library/Yi/Keymap/Vim/Digraph.hs | gpl-2.0 | 1,459 | 0 | 8 | 503 | 602 | 392 | 210 | 64 | 1 |
-- Copyright (C) 2002-2003 David Roundy
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE CPP #-}
module Darcs.Patch.Named
( Named(..),
infopatch,
adddeps, namepatch, anonymous,
getdeps,
patch2patchinfo, patchname, patchcontents,
fmapNamed, fmapFL_Named,
commuterIdNamed, commuterNamedId,
mergerIdNamed
)
where
import Prelude hiding ( pi )
import Darcs.Patch.CommuteFn ( CommuteFn, commuterIdFL, commuterFLId
, MergeFn, mergerIdFL )
import Darcs.Patch.Conflict ( Conflict(..), CommuteNoConflicts )
import Darcs.Patch.Debug ( PatchDebug(..) )
import Darcs.Patch.Effect ( Effect(effect, effectRL) )
import Darcs.Patch.FileHunk ( IsHunk(..) )
import Darcs.Patch.Format ( PatchListFormat )
import Darcs.Patch.Info ( PatchInfo, readPatchInfo, showPatchInfo, patchinfo,
showPatchInfoUI, makePatchname, invertName )
import Darcs.Patch.Merge ( Merge(..) )
import Darcs.Patch.Patchy ( Commute(..), Invert(..), Apply(..),
PatchInspect(..), ReadPatch(..) )
import Darcs.Patch.Prim ( PrimOf, PrimPatchBase )
import Darcs.Patch.ReadMonads ( ParserM, option, lexChar,
choice, skipWhile, anyChar )
import Darcs.Patch.Rebase.NameHack ( NameHack(..) )
import Darcs.Patch.Repair ( mapMaybeSnd, Repair(..), RepairToFL, Check(..) )
import Darcs.Patch.Show ( ShowPatchBasic(..), ShowPatch(..), showNamedPrefix )
import Darcs.Patch.Summary ( plainSummary )
import Darcs.Patch.Viewing () -- for ShowPatch FL instances
import Darcs.Patch.Witnesses.Eq ( MyEq(..) )
import Darcs.Patch.Witnesses.Ordered
( (:>)(..), (:\/:)(..), (:/\:)(..), FL, mapFL, mapFL_FL )
import Darcs.Patch.Witnesses.Sealed ( Sealed, mapSeal )
import Darcs.Patch.Witnesses.Show ( ShowDict(..), Show1(..), Show2(..) )
import Darcs.Util.Diff ( DiffAlgorithm(MyersDiff) )
import Darcs.Util.Printer ( ($$), (<+>), (<>), prefix, text, vcat )
import Data.Maybe ( fromMaybe )
-- | The @Named@ type adds a patch info about a patch, that is a name.
data Named p wX wY where
NamedP :: !PatchInfo
-> ![PatchInfo]
-> !(FL p wX wY)
-> Named p wX wY
deriving Show
-- ^ @NamedP info deps p@ represents patch @p@ with name
-- @info@. @deps@ is a list of dependencies added at the named patch
-- level, compared with the unnamed level (ie, dependencies added with
-- @darcs record --ask-deps@).
instance PrimPatchBase p => PrimPatchBase (Named p) where
type PrimOf (Named p) = PrimOf p
instance Effect p => Effect (Named p) where
effect (NamedP _ _ p) = effect p
effectRL (NamedP _ _ p) = effectRL p
instance IsHunk (Named p) where
isHunk _ = Nothing
instance PatchListFormat (Named p)
instance (ReadPatch p, PatchListFormat p) => ReadPatch (Named p) where
readPatch' = readNamed
readNamed :: (ReadPatch p, PatchListFormat p, ParserM m) => m (Sealed (Named p wX))
readNamed
= do n <- readPatchInfo
d <- readDepends
p <- readPatch'
return $ (NamedP n d) `mapSeal` p
readDepends :: ParserM m => m [PatchInfo]
readDepends =
option [] $ do lexChar '<'
readPis
readPis :: ParserM m => m [PatchInfo]
readPis = choice [ do pi <- readPatchInfo
pis <- readPis
return (pi:pis)
, do skipWhile (/= '>')
_ <- anyChar
return [] ]
instance Apply p => Apply (Named p) where
type ApplyState (Named p) = ApplyState p
apply (NamedP _ _ p) = apply p
instance RepairToFL p => Repair (Named p) where
applyAndTryToFix (NamedP n d p) = mapMaybeSnd (NamedP n d) `fmap` applyAndTryToFix p
namepatch :: String -> String -> String -> [String] -> FL p wX wY -> IO (Named p wX wY)
namepatch date name author desc p
| '\n' `elem` name = error "Patch names cannot contain newlines."
| otherwise = do pinf <- patchinfo date name author desc
return $ NamedP pinf [] p
anonymous :: FL p wX wY -> IO (Named p wX wY)
anonymous p = namepatch "today" "anonymous" "unknown" ["anonymous"] p
infopatch :: PatchInfo -> FL p wX wY -> Named p wX wY
infopatch pi p = NamedP pi [] p
adddeps :: Named p wX wY -> [PatchInfo] -> Named p wX wY
adddeps (NamedP pi _ p) ds = NamedP pi ds p
getdeps :: Named p wX wY -> [PatchInfo]
getdeps (NamedP _ ds _) = ds
patch2patchinfo :: Named p wX wY -> PatchInfo
patch2patchinfo (NamedP i _ _) = i
patchname :: Named p wX wY -> String
patchname (NamedP i _ _) = show $ makePatchname i
patchcontents :: Named p wX wY -> FL p wX wY
patchcontents (NamedP _ _ p) = p
fmapNamed :: (forall wA wB . p wA wB -> q wA wB) -> Named p wX wY -> Named q wX wY
fmapNamed f (NamedP i deps p) = NamedP i deps (mapFL_FL f p)
fmapFL_Named :: (FL p wA wB -> FL q wC wD) -> Named p wA wB -> Named q wC wD
fmapFL_Named f (NamedP i deps p) = NamedP i deps (f p)
instance (Commute p, MyEq p) => MyEq (Named p) where
unsafeCompare (NamedP n1 d1 p1) (NamedP n2 d2 p2) =
n1 == n2 && d1 == d2 && unsafeCompare p1 p2
instance Invert p => Invert (Named p) where
invert (NamedP n d p) = NamedP (invertName n) (map invertName d) (invert p)
instance (Commute p, NameHack p) => Commute (Named p) where
commute (NamedP n1 d1 p1 :> NamedP n2 d2 p2) =
if n2 `elem` d1 || n1 `elem` d2
then Nothing
else do (p2' :> p1') <- commute (p1 :> p2)
let (informAdd, informDel) = fromMaybe (const id, const id) (nameHack MyersDiff)
return (NamedP n2 d2 (informAdd n1 p2') :> NamedP n1 d1 (informDel n2 p1'))
commuterIdNamed :: CommuteFn p1 p2 -> CommuteFn p1 (Named p2)
commuterIdNamed commuter (p1 :> NamedP n2 d2 p2) =
do p2' :> p1' <- commuterIdFL commuter (p1 :> p2)
return (NamedP n2 d2 p2' :> p1')
commuterNamedId :: CommuteFn p1 p2 -> CommuteFn (Named p1) p2
commuterNamedId commuter (NamedP n1 d1 p1 :> p2) =
do p2' :> p1' <- commuterFLId commuter (p1 :> p2)
return (p2' :> NamedP n1 d1 p1')
instance (Merge p, NameHack p) => Merge (Named p) where
merge (NamedP n1 d1 p1 :\/: NamedP n2 d2 p2)
= case merge (p1 :\/: p2) of
(p2' :/\: p1') -> NamedP n2 d2 p2' :/\: NamedP n1 d1 p1'
mergerIdNamed :: MergeFn p1 p2 -> MergeFn p1 (Named p2)
mergerIdNamed merger (p1 :\/: NamedP n2 d2 p2) =
case mergerIdFL merger (p1 :\/: p2) of
p2' :/\: p1' -> NamedP n2 d2 p2' :/\: p1'
instance PatchInspect p => PatchInspect (Named p) where
listTouchedFiles (NamedP _ _ p) = listTouchedFiles p
hunkMatches f (NamedP _ _ p) = hunkMatches f p
instance (CommuteNoConflicts p, Conflict p) => Conflict (Named p) where
listConflictedFiles (NamedP _ _ p) = listConflictedFiles p
resolveConflicts (NamedP _ _ p) = resolveConflicts p
instance Check p => Check (Named p) where
isInconsistent (NamedP _ _ p) = isInconsistent p
instance (PatchListFormat p, ShowPatchBasic p) => ShowPatchBasic (Named p) where
showPatch (NamedP n [] p) = showPatchInfo n <> showPatch p
showPatch (NamedP n d p) = showNamedPrefix n d <+> showPatch p
instance (Apply p, CommuteNoConflicts p, Conflict p, IsHunk p, PatchListFormat p,
PrimPatchBase p, ShowPatch p) => ShowPatch (Named p) where
showContextPatch (NamedP n [] p) = showContextPatch p >>= return . (showPatchInfo n <>)
showContextPatch (NamedP n d p) = showContextPatch p >>= return . (showNamedPrefix n d <+>)
description (NamedP n _ _) = showPatchInfoUI n
summary p = description p $$ text "" $$
prefix " " (plainSummary p) -- this isn't summary because summary does the
-- wrong thing with (Named (FL p)) so that it can
-- get the summary of a sequence of named patches
-- right.
summaryFL = vcat . mapFL summary
showNicely p@(NamedP _ _ pt) = description p $$
prefix " " (showNicely pt)
instance Show2 p => Show1 (Named p wX) where
showDict1 = ShowDictClass
instance Show2 p => Show2 (Named p) where
showDict2 = ShowDictClass
instance PatchDebug p => PatchDebug (Named p)
| DavidAlphaFox/darcs | src/Darcs/Patch/Named.hs | gpl-2.0 | 8,981 | 1 | 14 | 2,289 | 3,008 | 1,588 | 1,420 | -1 | -1 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-}
{-# OPTIONS_GHC -w #-}
module GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship (ScheduleRelationship(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.List as Prelude'
import qualified Data.Typeable as Prelude'
import qualified GHC.Generics as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data ScheduleRelationship = SCHEDULED
| ADDED
| UNSCHEDULED
| CANCELED
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data,
Prelude'.Generic)
instance P'.Mergeable ScheduleRelationship
instance Prelude'.Bounded ScheduleRelationship where
minBound = SCHEDULED
maxBound = CANCELED
instance P'.Default ScheduleRelationship where
defaultValue = SCHEDULED
toMaybe'Enum :: Prelude'.Int -> P'.Maybe ScheduleRelationship
toMaybe'Enum 0 = Prelude'.Just SCHEDULED
toMaybe'Enum 1 = Prelude'.Just ADDED
toMaybe'Enum 2 = Prelude'.Just UNSCHEDULED
toMaybe'Enum 3 = Prelude'.Just CANCELED
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum ScheduleRelationship where
fromEnum SCHEDULED = 0
fromEnum ADDED = 1
fromEnum UNSCHEDULED = 2
fromEnum CANCELED = 3
toEnum
= P'.fromMaybe
(Prelude'.error
"hprotoc generated code: toEnum failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship")
. toMaybe'Enum
succ SCHEDULED = ADDED
succ ADDED = UNSCHEDULED
succ UNSCHEDULED = CANCELED
succ _
= Prelude'.error
"hprotoc generated code: succ failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship"
pred ADDED = SCHEDULED
pred UNSCHEDULED = ADDED
pred CANCELED = UNSCHEDULED
pred _
= Prelude'.error
"hprotoc generated code: pred failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship"
instance P'.Wire ScheduleRelationship where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB ScheduleRelationship
instance P'.MessageAPI msg' (msg' -> ScheduleRelationship) ScheduleRelationship where
getVal m' f' = f' m'
instance P'.ReflectEnum ScheduleRelationship where
reflectEnum = [(0, "SCHEDULED", SCHEDULED), (1, "ADDED", ADDED), (2, "UNSCHEDULED", UNSCHEDULED), (3, "CANCELED", CANCELED)]
reflectEnumInfo _
= P'.EnumInfo
(P'.makePNF (P'.pack ".transit_realtime.TripDescriptor.ScheduleRelationship") ["GTFS", "Realtime", "Internal"]
["Com", "Google", "Transit", "Realtime", "TripDescriptor"]
"ScheduleRelationship")
["GTFS", "Realtime", "Internal", "Com", "Google", "Transit", "Realtime", "TripDescriptor", "ScheduleRelationship.hs"]
[(0, "SCHEDULED"), (1, "ADDED"), (2, "UNSCHEDULED"), (3, "CANCELED")]
Prelude'.False
instance P'.TextType ScheduleRelationship where
tellT = P'.tellShow
getT = P'.getRead | romanofski/gtfsschedule | src/GTFS/Realtime/Internal/Com/Google/Transit/Realtime/TripDescriptor/ScheduleRelationship.hs | gpl-3.0 | 3,470 | 0 | 11 | 614 | 784 | 437 | 347 | 73 | 1 |
module FQuoter.Repl.ReplForms
(shellForNotDefined)
where
import Control.Applicative
import Control.Monad
import System.Console.Haskeline
import qualified Data.Map as Map
import FQuoter.Quote
import FQuoter.Parser.ParserTypes
import FQuoter.Repl.ReplUtils
shellForNotDefined :: NotDefinedType -> InputT IO ParsedType
shellForNotDefined (NDAuthor) = loopAuthor
shellForNotDefined (NDSource) = loopSource
shellForNotDefined (NDQuote) = loopQuote
loopAsk :: String -> InputT IO [String]
loopAsk q = do outputStrLn q
i <- getInputLine' prompt
if null i
then return []
else (i :) <$> loopAsk q
loopDict :: String -> String -> InputT IO (Map.Map String String)
loopDict q1 q2 = liftM Map.fromList loopDict'
where
loopDict' = do outputStrLn q1
k <- getInputLine' prompt
if null k
then return []
else do outputStrLn q2
v <- getInputLine' prompt
( (k,v) :) <$> loopDict'
loopAuthor :: InputT IO ParsedType
loopAuthor = liftM PAuthor readAuthor
where readAuthor = Author <$> ask' "Enter the first name"
<*> ask' "Enter the last name"
<*> ask' "Enter the nick name if any"
loopSource :: InputT IO ParsedType
loopSource = liftM PSource readSource
where readSource = ParserSource <$> ask "Enter the title"
<*> loopAsk "Enter the author(s)"
<*> loopDict "Enter a metadata type" "Enter a metadata value"
loopQuote :: InputT IO ParsedType
loopQuote = liftM PQuote readQuote
where readQuote = ParserQuote <$> ask "Enter the quote"
<*> ask "Enter the source"
<*> ask' "Enter localization if any"
<*> loopAsk "Enter tags. Empty input to stop entering tag."
<*> loopAsk "Enter author. Empty input to stop entering tag."
<*> ask' "Enter a comment if you have one"
| Raveline/FQuoter | src/FQuoter/Repl/ReplForms.hs | gpl-3.0 | 2,184 | 0 | 14 | 785 | 458 | 230 | 228 | 46 | 2 |
{-# LANGUAGE FlexibleInstances, OverloadedStrings, MultiParamTypeClasses, TypeSynonymInstances #-}
module Carbon.Data.ResultSet where
import Control.Applicative
import Control.Arrow (first, second)
import Control.Monad
import Data.Aeson ((.=), ToJSON(..), object, FromJSON(..), Value(..), (.:))
import Data.Aeson.Types (Parser)
import Data.Function (on)
import Data.Map (Map)
import Data.Monoid (Monoid(..))
import Data.Set (Set)
import Data.Vector (Vector, (!?))
import qualified Data.Aeson as Aeson
import qualified Data.HashMap.Strict as HashMap
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import Carbon.Common ((?))
import Carbon.Data.Alias
import Carbon.Data.Common
import Carbon.Data.Id
import Carbon.Data.Logic.Diamond
import Carbon.Data.Result
import Carbon.Data.User (User)
import qualified Carbon.Data.User as User
data ResultSet = ResultSet {
resultSetId :: Maybe ResultSetId
, setCreation :: Timestamp
, results :: [Result]
, voters :: [(UserId, Voted)]
} deriving (Show, Read, Eq, Ord)
type ThreeSet = (Set ItemId, Set ItemId, Set ItemId)
fromResults :: Results ItemId -> ResultSet
fromResults (Results rs) =
let drMap = mkMap . map (first drToSets) $ swapExpand rs :: Map ThreeSet (Set ResultType)
go = map (uncurry mkResult . first setsToDr) . Map.toList :: Map ThreeSet (Set ResultType) -> [Result]
in mempty <+ go drMap
where
swapExpand :: [(ResultType, [DiamondResult ItemId])] -> [(DiamondResult ItemId, ResultType)]
swapExpand = concatMap (\(b, as) -> zip as $ repeat b)
drToSets :: DiamondResult ItemId -> ThreeSet
drToSets dr = let is = Set.fromList $ inSet dr
us = Set.fromList $ udecSet dr
os = Set.fromList $ outSet dr
in (is, us, os)
setsToDr :: ThreeSet -> DiamondResult ItemId
setsToDr (is, us, os) = DiamondResult (Set.toList is) (Set.toList us) $ Set.toList os
mkMap :: [(ThreeSet, ResultType)] -> Map ThreeSet (Set ResultType)
mkMap = Map.fromListWith Set.union . map (second $ Set.fromList . return)
mkResult :: DiamondResult ItemId -> Set ResultType -> Result
mkResult dRes rTypes = (mempty <+ fromDR dRes) <+ Set.toList rTypes
fromDR :: DiamondResult ItemId -> Set (ResultState, ItemId)
fromDR dRes =
let ins = zip (repeat In) $ inSet dRes
udecs = zip (repeat Udec) $ udecSet dRes
outs = zip (repeat Out) $ outSet dRes
in Set.fromList $ ins ++ udecs ++ outs
-- Instances:
instance FromJSON ResultSet where
parseJSON (Object v) = do
let setI r i = r{resultSetId = Just i}
setS r s = r{setCreation = s}
setR r s = r{results = s}
setV r v = r{voters = v}
parseI r = msum [liftM (setI r) (v .: "id"), return r]
parseS r = msum [liftM (setS r) (v .: "setCreation"), return r]
parseR r = msum [liftM (setR r) (v .: "results"), return r]
parseV r = msum [liftM (setV r) (parseVoters $ HashMap.lookup "voters" v), return r]
r <- parseV =<< parseR =<< parseS =<< parseI mempty
guard $ r /= mempty
return r
where
parseVoters :: Maybe Value -> Parser [(Id, Bool)]
parseVoters (Just (Array a)) = liftM Maybe.catMaybes . mapM parseVoter $ Vector.toList a
parseVoters _ = return []
parseVoter :: Value -> Parser (Maybe (Id, Bool))
parseVoter (Array a)
| Vector.length a >= 2 = do
let (x, y) = (Maybe.fromJust $ a !? 0, Maybe.fromJust $ a !? 1)
x' <- parseId x
y' <- parseVoted y
return $ Just (x', y')
| otherwise = return Nothing
parseVoter _ = return Nothing
parseId :: Value -> Parser Id
parseId (String t) = return . read $ Text.unpack t
parseVoted :: Value -> Parser Bool
parseVoted (Bool b) = return b
parseVoted _ = return False
parseJSON _ = mzero
instance Insertable ResultSet ResultSetId where
r <+ i = r{resultSetId = Just i}
instance Insertable ResultSet [Result] where
r <+ rs = r{results = rs}
instance Monoid ResultSet where
mempty = ResultSet {
resultSetId = mempty
, setCreation = mempty
, results = mempty
, voters = mempty
}
mappend a b = ResultSet {
resultSetId = (mappend `on` resultSetId) a b
, setCreation = (mergeStr `on` setCreation) a b
, results = results b
, voters = voters b
}
instance ToJSON ResultSet where
toJSON r = object [
"id" .= resultSetId r
, "setCreation" .= setCreation r
, "results" .= results r
, "voters" .= voters r
]
-- This one makes usage of sameId possible
instance HasId ResultSet where
getId = Maybe.fromMaybe mempty . resultSetId
-- Testing if changes to a ResultSet are permitted:
okRDelta :: User -> Maybe ResultSet -> Maybe ResultSet -> Bool
okRDelta = okRDelta' . User.userId
okRDelta' :: UserId -> Maybe ResultSet -> Maybe ResultSet -> Bool
okRDelta' _ Nothing Nothing = True
okRDelta' _ Nothing (Just _) = False
okRDelta' _ (Just _) Nothing = False
{- Voted for the user may only move from False -> True or stay True.
Only if the user just voted may the votes of results be larger by one.
The rest must remain unchanged. -}
okRDelta' uId (Just old) (Just new) =
let voted = justVoted uId old new
in and [sameId old new, sameCreation old new, sameVoters old new, voted, okResults voted old new]
-- Printing a table with the involved constraints to aid debugging:
rDeltaTable :: User -> Maybe ResultSet -> Maybe ResultSet -> IO ()
rDeltaTable = rDeltaTable' . User.userId
rDeltaTable' :: UserId -> Maybe ResultSet -> Maybe ResultSet -> IO ()
rDeltaTable' uId mOld mNew = do
let bothJust = (&&) `on` Maybe.isJust
(old, new) = (Maybe.fromJust mOld, Maybe.fromJust mNew)
details = [("sameId: ", sameId old new)
,("sameCreation: ", sameCreation old new)
,("sameVoters: ", sameVoters old new)
,("justVoted: ", justVoted uId old new)
,("okResults: ", okResults (justVoted uId old new) old new)
]
always = [("okRDelta: ", okRDelta' uId mOld mNew)]
stats = bothJust mOld mNew ? (details ++ always, always)
putStrLn "Carbon.Data.ResultSet:rDeltaTable:"
putStrLn "----------------------------------"
forM_ stats $ \(x,y) -> putStr x >> print y
putStrLn "----------------------------------"
putStrLn "Arguments:"
putStrLn "UserId: " >> print uId
putStrLn "Old: " >> print (show mOld)
putStrLn "New: " >> print (show mNew)
sameCreation :: ResultSet -> ResultSet -> Bool
sameCreation = (==) `on` setCreation
sameVoters :: ResultSet -> ResultSet -> Bool
sameVoters = (==) `on` (Set.fromList . map fst . voters)
justVoted :: Id -> ResultSet -> ResultSet -> Bool
justVoted uId = -- Not being a voter equals already having voted.
let fromList l = null l ? (True, snd $ head l)
in (<) `on` (fromList . filter ((==) uId . fst) . voters)
okResults voted = chkResults voted `on` (List.sortBy (compare `on` resultId) . results)
chkResults _ [] [] = True
chkResults _ [] (_:_) = False
chkResults _ (_:_) [] = False
chkResults voted (o:os) (n:ns) =
let justId = Maybe.isJust $ resultId o
sameId = (==) `on` resultId
sameTypes = (==) `on` (List.sort . List.nub . resultType)
sameItems = (==) `on` items
sameVotes = (==) `on` votes
okVotes = (\x y -> abs (x-y) == 1) `on` votes
in and [justId, sameId o n, sameItems o n, sameVotes o n || (voted && okVotes o n), chkResults voted os ns]
| runjak/carbon-adf | Carbon/Data/ResultSet.hs | gpl-3.0 | 7,857 | 0 | 17 | 1,997 | 2,808 | 1,493 | 1,315 | 163 | 1 |
module TodoTree.Dispatch where
-- import Control.Monad (when)
import System.Console.Docopt.NoTH
import TodoTree.Repl (repl)
dispatchOrExit :: String -> [String] -> IO ()
dispatchOrExit usg args = do
doc <- parseUsageOrExit usg
opts <- parseArgsOrExit doc args
dispatch doc opts
dispatch :: Docopt -> Arguments -> IO ()
dispatch usg args = do
let getArg' arg = getArgOrExitWith usg args $ argument arg
-- ifArg arg act = when (isPresent args $ argument arg) act
getArg' "file" >>= (\f -> repl [f])
| jefdaj/todotree | src/TodoTree/Dispatch.hs | gpl-3.0 | 515 | 0 | 11 | 97 | 162 | 81 | 81 | 12 | 1 |
{- The authors ask:
2. Write a function, lastButOne , that returns the element before the last.
-}
lastButOne :: [a] -> a
lastButOne xs = last (take ((length xs) - 1) xs)
| craigem/RealWorldHaskell | ch02/lastButOne.hs | gpl-3.0 | 172 | 0 | 11 | 34 | 46 | 24 | 22 | 2 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Games.Applications.Played
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Indicate that the currently authenticated user is playing your
-- application.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Reference> for @games.applications.played@.
module Network.Google.Resource.Games.Applications.Played
(
-- * REST Resource
ApplicationsPlayedResource
-- * Creating a Request
, applicationsPlayed
, ApplicationsPlayed
-- * Request Lenses
, apXgafv
, apUploadProtocol
, apAccessToken
, apUploadType
, apCallback
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.applications.played@ method which the
-- 'ApplicationsPlayed' request conforms to.
type ApplicationsPlayedResource =
"games" :>
"v1" :>
"applications" :>
"played" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Indicate that the currently authenticated user is playing your
-- application.
--
-- /See:/ 'applicationsPlayed' smart constructor.
data ApplicationsPlayed =
ApplicationsPlayed'
{ _apXgafv :: !(Maybe Xgafv)
, _apUploadProtocol :: !(Maybe Text)
, _apAccessToken :: !(Maybe Text)
, _apUploadType :: !(Maybe Text)
, _apCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ApplicationsPlayed' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'apXgafv'
--
-- * 'apUploadProtocol'
--
-- * 'apAccessToken'
--
-- * 'apUploadType'
--
-- * 'apCallback'
applicationsPlayed
:: ApplicationsPlayed
applicationsPlayed =
ApplicationsPlayed'
{ _apXgafv = Nothing
, _apUploadProtocol = Nothing
, _apAccessToken = Nothing
, _apUploadType = Nothing
, _apCallback = Nothing
}
-- | V1 error format.
apXgafv :: Lens' ApplicationsPlayed (Maybe Xgafv)
apXgafv = lens _apXgafv (\ s a -> s{_apXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
apUploadProtocol :: Lens' ApplicationsPlayed (Maybe Text)
apUploadProtocol
= lens _apUploadProtocol
(\ s a -> s{_apUploadProtocol = a})
-- | OAuth access token.
apAccessToken :: Lens' ApplicationsPlayed (Maybe Text)
apAccessToken
= lens _apAccessToken
(\ s a -> s{_apAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
apUploadType :: Lens' ApplicationsPlayed (Maybe Text)
apUploadType
= lens _apUploadType (\ s a -> s{_apUploadType = a})
-- | JSONP
apCallback :: Lens' ApplicationsPlayed (Maybe Text)
apCallback
= lens _apCallback (\ s a -> s{_apCallback = a})
instance GoogleRequest ApplicationsPlayed where
type Rs ApplicationsPlayed = ()
type Scopes ApplicationsPlayed =
'["https://www.googleapis.com/auth/games"]
requestClient ApplicationsPlayed'{..}
= go _apXgafv _apUploadProtocol _apAccessToken
_apUploadType
_apCallback
(Just AltJSON)
gamesService
where go
= buildClient
(Proxy :: Proxy ApplicationsPlayedResource)
mempty
| brendanhay/gogol | gogol-games/gen/Network/Google/Resource/Games/Applications/Played.hs | mpl-2.0 | 4,219 | 0 | 17 | 999 | 636 | 372 | 264 | 92 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.SourceRepo.Projects.Repos.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates information about a repo.
--
-- /See:/ <https://cloud.google.com/source-repositories/docs/apis Cloud Source Repositories API Reference> for @sourcerepo.projects.repos.patch@.
module Network.Google.Resource.SourceRepo.Projects.Repos.Patch
(
-- * REST Resource
ProjectsReposPatchResource
-- * Creating a Request
, projectsReposPatch
, ProjectsReposPatch
-- * Request Lenses
, prpXgafv
, prpUploadProtocol
, prpAccessToken
, prpUploadType
, prpPayload
, prpName
, prpCallback
) where
import Network.Google.Prelude
import Network.Google.SourceRepo.Types
-- | A resource alias for @sourcerepo.projects.repos.patch@ method which the
-- 'ProjectsReposPatch' request conforms to.
type ProjectsReposPatchResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] UpdateRepoRequest :>
Patch '[JSON] Repo
-- | Updates information about a repo.
--
-- /See:/ 'projectsReposPatch' smart constructor.
data ProjectsReposPatch =
ProjectsReposPatch'
{ _prpXgafv :: !(Maybe Xgafv)
, _prpUploadProtocol :: !(Maybe Text)
, _prpAccessToken :: !(Maybe Text)
, _prpUploadType :: !(Maybe Text)
, _prpPayload :: !UpdateRepoRequest
, _prpName :: !Text
, _prpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsReposPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prpXgafv'
--
-- * 'prpUploadProtocol'
--
-- * 'prpAccessToken'
--
-- * 'prpUploadType'
--
-- * 'prpPayload'
--
-- * 'prpName'
--
-- * 'prpCallback'
projectsReposPatch
:: UpdateRepoRequest -- ^ 'prpPayload'
-> Text -- ^ 'prpName'
-> ProjectsReposPatch
projectsReposPatch pPrpPayload_ pPrpName_ =
ProjectsReposPatch'
{ _prpXgafv = Nothing
, _prpUploadProtocol = Nothing
, _prpAccessToken = Nothing
, _prpUploadType = Nothing
, _prpPayload = pPrpPayload_
, _prpName = pPrpName_
, _prpCallback = Nothing
}
-- | V1 error format.
prpXgafv :: Lens' ProjectsReposPatch (Maybe Xgafv)
prpXgafv = lens _prpXgafv (\ s a -> s{_prpXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
prpUploadProtocol :: Lens' ProjectsReposPatch (Maybe Text)
prpUploadProtocol
= lens _prpUploadProtocol
(\ s a -> s{_prpUploadProtocol = a})
-- | OAuth access token.
prpAccessToken :: Lens' ProjectsReposPatch (Maybe Text)
prpAccessToken
= lens _prpAccessToken
(\ s a -> s{_prpAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
prpUploadType :: Lens' ProjectsReposPatch (Maybe Text)
prpUploadType
= lens _prpUploadType
(\ s a -> s{_prpUploadType = a})
-- | Multipart request metadata.
prpPayload :: Lens' ProjectsReposPatch UpdateRepoRequest
prpPayload
= lens _prpPayload (\ s a -> s{_prpPayload = a})
-- | The name of the requested repository. Values are of the form
-- \`projects\/\/repos\/\`.
prpName :: Lens' ProjectsReposPatch Text
prpName = lens _prpName (\ s a -> s{_prpName = a})
-- | JSONP
prpCallback :: Lens' ProjectsReposPatch (Maybe Text)
prpCallback
= lens _prpCallback (\ s a -> s{_prpCallback = a})
instance GoogleRequest ProjectsReposPatch where
type Rs ProjectsReposPatch = Repo
type Scopes ProjectsReposPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsReposPatch'{..}
= go _prpName _prpXgafv _prpUploadProtocol
_prpAccessToken
_prpUploadType
_prpCallback
(Just AltJSON)
_prpPayload
sourceRepoService
where go
= buildClient
(Proxy :: Proxy ProjectsReposPatchResource)
mempty
| brendanhay/gogol | gogol-sourcerepo/gen/Network/Google/Resource/SourceRepo/Projects/Repos/Patch.hs | mpl-2.0 | 4,945 | 0 | 16 | 1,153 | 776 | 453 | 323 | 112 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AdExchangeBuyer.PerformanceReport.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the authenticated user\'s list of performance metrics.
--
-- /See:/ <https://developers.google.com/ad-exchange/buyer-rest Ad Exchange Buyer API Reference> for @adexchangebuyer.performanceReport.list@.
module Network.Google.Resource.AdExchangeBuyer.PerformanceReport.List
(
-- * REST Resource
PerformanceReportListResource
-- * Creating a Request
, performanceReportList'
, PerformanceReportList'
-- * Request Lenses
, prlAccountId
, prlPageToken
, prlEndDateTime
, prlMaxResults
, prlStartDateTime
) where
import Network.Google.AdExchangeBuyer.Types
import Network.Google.Prelude
-- | A resource alias for @adexchangebuyer.performanceReport.list@ method which the
-- 'PerformanceReportList'' request conforms to.
type PerformanceReportListResource =
"adexchangebuyer" :>
"v1.4" :>
"performancereport" :>
QueryParam "accountId" (Textual Int64) :>
QueryParam "endDateTime" Text :>
QueryParam "startDateTime" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] PerformanceReportList
-- | Retrieves the authenticated user\'s list of performance metrics.
--
-- /See:/ 'performanceReportList'' smart constructor.
data PerformanceReportList' =
PerformanceReportList''
{ _prlAccountId :: !(Textual Int64)
, _prlPageToken :: !(Maybe Text)
, _prlEndDateTime :: !Text
, _prlMaxResults :: !(Maybe (Textual Word32))
, _prlStartDateTime :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PerformanceReportList'' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prlAccountId'
--
-- * 'prlPageToken'
--
-- * 'prlEndDateTime'
--
-- * 'prlMaxResults'
--
-- * 'prlStartDateTime'
performanceReportList'
:: Int64 -- ^ 'prlAccountId'
-> Text -- ^ 'prlEndDateTime'
-> Text -- ^ 'prlStartDateTime'
-> PerformanceReportList'
performanceReportList' pPrlAccountId_ pPrlEndDateTime_ pPrlStartDateTime_ =
PerformanceReportList''
{ _prlAccountId = _Coerce # pPrlAccountId_
, _prlPageToken = Nothing
, _prlEndDateTime = pPrlEndDateTime_
, _prlMaxResults = Nothing
, _prlStartDateTime = pPrlStartDateTime_
}
-- | The account id to get the reports.
prlAccountId :: Lens' PerformanceReportList' Int64
prlAccountId
= lens _prlAccountId (\ s a -> s{_prlAccountId = a})
. _Coerce
-- | A continuation token, used to page through performance reports. To
-- retrieve the next page, set this parameter to the value of
-- \"nextPageToken\" from the previous response. Optional.
prlPageToken :: Lens' PerformanceReportList' (Maybe Text)
prlPageToken
= lens _prlPageToken (\ s a -> s{_prlPageToken = a})
-- | The end time of the report in ISO 8601 timestamp format using UTC.
prlEndDateTime :: Lens' PerformanceReportList' Text
prlEndDateTime
= lens _prlEndDateTime
(\ s a -> s{_prlEndDateTime = a})
-- | Maximum number of entries returned on one result page. If not set, the
-- default is 100. Optional.
prlMaxResults :: Lens' PerformanceReportList' (Maybe Word32)
prlMaxResults
= lens _prlMaxResults
(\ s a -> s{_prlMaxResults = a})
. mapping _Coerce
-- | The start time of the report in ISO 8601 timestamp format using UTC.
prlStartDateTime :: Lens' PerformanceReportList' Text
prlStartDateTime
= lens _prlStartDateTime
(\ s a -> s{_prlStartDateTime = a})
instance GoogleRequest PerformanceReportList' where
type Rs PerformanceReportList' =
PerformanceReportList
type Scopes PerformanceReportList' =
'["https://www.googleapis.com/auth/adexchange.buyer"]
requestClient PerformanceReportList''{..}
= go (Just _prlAccountId) (Just _prlEndDateTime)
(Just _prlStartDateTime)
_prlPageToken
_prlMaxResults
(Just AltJSON)
adExchangeBuyerService
where go
= buildClient
(Proxy :: Proxy PerformanceReportListResource)
mempty
| brendanhay/gogol | gogol-adexchange-buyer/gen/Network/Google/Resource/AdExchangeBuyer/PerformanceReport/List.hs | mpl-2.0 | 5,076 | 0 | 16 | 1,134 | 672 | 391 | 281 | 101 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AccessContextManager.AccessPolicies.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Update an AccessPolicy. The longrunning Operation from this RPC will
-- have a successful status once the changes to the AccessPolicy have
-- propagated to long-lasting storage. Syntactic and basic semantic errors
-- will be returned in \`metadata\` as a BadRequest proto.
--
-- /See:/ <https://cloud.google.com/access-context-manager/docs/reference/rest/ Access Context Manager API Reference> for @accesscontextmanager.accessPolicies.patch@.
module Network.Google.Resource.AccessContextManager.AccessPolicies.Patch
(
-- * REST Resource
AccessPoliciesPatchResource
-- * Creating a Request
, accessPoliciesPatch
, AccessPoliciesPatch
-- * Request Lenses
, appXgafv
, appUploadProtocol
, appUpdateMask
, appAccessToken
, appUploadType
, appPayload
, appName
, appCallback
) where
import Network.Google.AccessContextManager.Types
import Network.Google.Prelude
-- | A resource alias for @accesscontextmanager.accessPolicies.patch@ method which the
-- 'AccessPoliciesPatch' request conforms to.
type AccessPoliciesPatchResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AccessPolicy :>
Patch '[JSON] Operation
-- | Update an AccessPolicy. The longrunning Operation from this RPC will
-- have a successful status once the changes to the AccessPolicy have
-- propagated to long-lasting storage. Syntactic and basic semantic errors
-- will be returned in \`metadata\` as a BadRequest proto.
--
-- /See:/ 'accessPoliciesPatch' smart constructor.
data AccessPoliciesPatch =
AccessPoliciesPatch'
{ _appXgafv :: !(Maybe Xgafv)
, _appUploadProtocol :: !(Maybe Text)
, _appUpdateMask :: !(Maybe GFieldMask)
, _appAccessToken :: !(Maybe Text)
, _appUploadType :: !(Maybe Text)
, _appPayload :: !AccessPolicy
, _appName :: !Text
, _appCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccessPoliciesPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'appXgafv'
--
-- * 'appUploadProtocol'
--
-- * 'appUpdateMask'
--
-- * 'appAccessToken'
--
-- * 'appUploadType'
--
-- * 'appPayload'
--
-- * 'appName'
--
-- * 'appCallback'
accessPoliciesPatch
:: AccessPolicy -- ^ 'appPayload'
-> Text -- ^ 'appName'
-> AccessPoliciesPatch
accessPoliciesPatch pAppPayload_ pAppName_ =
AccessPoliciesPatch'
{ _appXgafv = Nothing
, _appUploadProtocol = Nothing
, _appUpdateMask = Nothing
, _appAccessToken = Nothing
, _appUploadType = Nothing
, _appPayload = pAppPayload_
, _appName = pAppName_
, _appCallback = Nothing
}
-- | V1 error format.
appXgafv :: Lens' AccessPoliciesPatch (Maybe Xgafv)
appXgafv = lens _appXgafv (\ s a -> s{_appXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
appUploadProtocol :: Lens' AccessPoliciesPatch (Maybe Text)
appUploadProtocol
= lens _appUploadProtocol
(\ s a -> s{_appUploadProtocol = a})
-- | Required. Mask to control which fields get updated. Must be non-empty.
appUpdateMask :: Lens' AccessPoliciesPatch (Maybe GFieldMask)
appUpdateMask
= lens _appUpdateMask
(\ s a -> s{_appUpdateMask = a})
-- | OAuth access token.
appAccessToken :: Lens' AccessPoliciesPatch (Maybe Text)
appAccessToken
= lens _appAccessToken
(\ s a -> s{_appAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
appUploadType :: Lens' AccessPoliciesPatch (Maybe Text)
appUploadType
= lens _appUploadType
(\ s a -> s{_appUploadType = a})
-- | Multipart request metadata.
appPayload :: Lens' AccessPoliciesPatch AccessPolicy
appPayload
= lens _appPayload (\ s a -> s{_appPayload = a})
-- | Output only. Resource name of the \`AccessPolicy\`. Format:
-- \`accessPolicies\/{policy_id}\`
appName :: Lens' AccessPoliciesPatch Text
appName = lens _appName (\ s a -> s{_appName = a})
-- | JSONP
appCallback :: Lens' AccessPoliciesPatch (Maybe Text)
appCallback
= lens _appCallback (\ s a -> s{_appCallback = a})
instance GoogleRequest AccessPoliciesPatch where
type Rs AccessPoliciesPatch = Operation
type Scopes AccessPoliciesPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient AccessPoliciesPatch'{..}
= go _appName _appXgafv _appUploadProtocol
_appUpdateMask
_appAccessToken
_appUploadType
_appCallback
(Just AltJSON)
_appPayload
accessContextManagerService
where go
= buildClient
(Proxy :: Proxy AccessPoliciesPatchResource)
mempty
| brendanhay/gogol | gogol-accesscontextmanager/gen/Network/Google/Resource/AccessContextManager/AccessPolicies/Patch.hs | mpl-2.0 | 5,942 | 0 | 17 | 1,334 | 861 | 503 | 358 | 123 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
module TimWilliamsStreaming where
import Control.Monad.Trans
-- ListT done right
-- list elements 'a' interleaved with effect 'm'
newtype ListT (m :: * -> *) (a :: *) = ListT { runListT :: m (Step m a) }
deriving Functor
data Step (m :: * -> *) (a :: *)
= Cons a (ListT m a)
| Nil
deriving Functor
instance Monad m => Semigroup (ListT (m :: * -> *) (a :: *)) where
(<>) (ListT mstep) s' = ListT $ mstep >>= \case
Cons a s -> return $ Cons a (s `mappend` s')
Nil -> runListT s'
instance Monad m => Monoid (ListT (m :: * -> *) (a :: *)) where
mempty = ListT $ return Nil
mappend = (<>)
concat :: Monad m => ListT m (ListT (m :: * -> *) (a :: *)) -> ListT m a
concat (ListT mstep) = ListT $ mstep >>= \case
Cons s ss -> runListT $ s `mappend` TimWilliamsStreaming.concat ss
Nil -> return Nil
instance Monad m => Applicative (ListT (m :: * -> *)) where
pure a = ListT $ return $ Cons a mempty
(<*>) = undefined
{-
ListT m <*> l = ListT $ m >>= \case
Nil -> pure Nil
Cons f l' -> runListT (fmap f l <|> (l' <*> l))
-}
instance Monad m => Monad (ListT (m :: * -> *)) where
return = pure -- yields control and delivers a result
(>>=) :: ListT (m :: * -> *) (a :: *) -> (a -> ListT m (b :: *)) -> ListT m b
s >>= f = TimWilliamsStreaming.concat $ fmap f s
-- lift monad 'm' into 'ListT'
-- :k MonadTrans :: ((* -> *) -> * -> *) -> Constraint
instance MonadTrans ListT where
lift m = ListT $ m >>= \a -> return (Cons a mempty)
-- lift IO monad 'm' into 'ListT'
-- :k MonadIO :: (* -> *) -> Constraint
instance MonadIO m => MonadIO (ListT (m :: * -> *)) where
liftIO = lift . liftIO
-- completely evaluate a stream computation
mapMS_ :: Monad m => (a -> m ()) -> ListT m a -> m ()
mapMS_ f (ListT mstep) = mstep >>= \case
Cons a s -> f a >> mapMS_ f s
Nil -> return ()
-- incrementation on-demand computation
-- similar to Java's Iterable<>
type Stream' a = ListT IO a
example :: IO ()
example = mapMS_ print (return 1 <> return 2 <> return 3 :: Stream' Int) | haroldcarr/learn-haskell-coq-ml-etc | haskell/topic/streaming/2018-10-tim-williams-streaming-haskellX/src/TimWilliamsStreaming.hs | unlicense | 2,175 | 0 | 13 | 542 | 797 | 427 | 370 | 41 | 2 |
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-
hsCRDT.hs
Copyright 2015 Sebastien Soudan
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.
-}
-- @Author: Sebastien Soudan
-- @Date: 2015-04-22 11:16:32
-- @Last Modified by: Sebastien Soudan
-- @Last Modified time: 2015-04-24 14:23:22
module CRDT
where
import Data.Monoid
----------------------------
-- Join semi-Lattice related definitions
----------------------------
class Compare p where
is :: p -> p -> Bool -- (is p p') is True if p <= p'
class (Compare p) => JoinSemiLattice p where
lub :: p -> p -> p -- least-upper-bound
----------------------------
-- CRDT related definitions - state-based specification
----------------------------
class Payload p where
initial :: p
class (Eq a, Payload p) => Query p q a where
query :: p -> q -> Maybe a
----------------------------
-- CvRDT definition
----------------------------
class (Payload p, Compare p, JoinSemiLattice p) => CvRDT p u where
update :: p -> u -> Maybe p
instance (CvRDT p u) => Monoid p where
mempty = initial
mappend = lub
-- merge is an alias for 'lub'
merge :: (JoinSemiLattice p) => p -> p -> p
merge = lub
| ssoudan/hsCRDT | src/CRDT.hs | apache-2.0 | 1,946 | 0 | 9 | 392 | 249 | 142 | 107 | 25 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
-- | Data types for K3 dataflow provenance
module Language.K3.Analysis.Provenance.Core where
import Control.DeepSeq
import GHC.Generics (Generic)
import Data.Binary
import Data.Serialize
import Data.List
import Data.Tree
import Data.Typeable
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Utils.Pretty
import Data.Text ( Text )
import qualified Data.Text as T
import qualified Language.K3.Utils.PrettyText as PT
type PPtr = Int
data PMatVar = PMatVar {pmvn :: !Identifier, pmvloc :: !UID, pmvptr :: !PPtr}
deriving (Eq, Ord, Read, Show, Typeable, Generic)
data Provenance =
-- Atoms
PFVar !Identifier !(Maybe UID)
| PBVar !PMatVar
| PTemporary -- A local leading to no lineage of interest
-- Terms
| PGlobal !Identifier
| PSet -- Non-deterministic (if-then-else or case)
| PChoice -- One of the cases must be chosen ie. they're exclusive
| PDerived -- A value derived from named children e.g. x + y ==> [x;y]
| PData !(Maybe [Identifier]) -- A value derived from a data constructor (optionally with named components)
| PRecord !Identifier
| PTuple !Int
| PIndirection
| POption
| PLambda !Identifier ![PMatVar] -- Lambda argument identifier, and new bound variables introduced for closure-captures.
| PApply !(Maybe PMatVar) -- The lambda, argument, and return value provenances of the application.
-- The apply also tracks any provenance variable binding needed for the lambda.
| PMaterialize ![PMatVar] -- A materialized return value scope, denoting provenance varibles bound in the child.
| PProject !Identifier -- The source of the projection, and the provenance of the projected value if available.
| PAssign !Identifier -- The provenance of the expression used for assignment.
| PSend -- The provenance of the value being sent.
deriving (Eq, Ord, Read, Show, Typeable, Generic)
data instance Annotation Provenance = PDeclared !(K3 Provenance)
deriving (Eq, Ord, Read, Show, Generic)
{- Provenance instances -}
instance NFData PMatVar
instance NFData Provenance
instance NFData (Annotation Provenance)
instance Binary PMatVar
instance Binary Provenance
instance Binary (Annotation Provenance)
instance Serialize PMatVar
instance Serialize Provenance
instance Serialize (Annotation Provenance)
{- Annotation extractors -}
isPDeclared :: Annotation Provenance -> Bool
isPDeclared (PDeclared _) = True
instance Pretty (K3 Provenance) where
prettyLines (Node (tg :@: as) ch) =
let (aStr, chAStr) = drawPAnnotations as
in [show tg ++ aStr]
++ (let (p,l) = if null ch then ("`- ", " ") else ("+- ", "| ")
in shift p l chAStr)
++ drawSubTrees ch
drawPAnnotations :: [Annotation Provenance] -> (String, [String])
drawPAnnotations as =
let (pdeclAnns, anns) = partition isPDeclared as
prettyPrAnns = concatMap drawPDeclAnnotation pdeclAnns
in (drawAnnotations anns, prettyPrAnns)
where drawPDeclAnnotation (PDeclared p) = ["PDeclared "] %+ prettyLines p
instance PT.Pretty (K3 Provenance) where
prettyLines (Node (tg :@: as) ch) =
let (aTxt, chATxt) = drawPAnnotationsT as
in [T.append (T.pack $ show tg) aTxt]
++ (let (p,l) = if null ch then (T.pack "`- ", T.pack " ")
else (T.pack "+- ", T.pack "| ")
in PT.shift p l chATxt)
++ PT.drawSubTrees ch
drawPAnnotationsT :: [Annotation Provenance] -> (Text, [Text])
drawPAnnotationsT as =
let (pdeclAnns, anns) = partition isPDeclared as
prettyPrAnns = concatMap drawPDeclAnnotation pdeclAnns
in (PT.drawAnnotations anns, prettyPrAnns)
where drawPDeclAnnotation (PDeclared p) = [T.pack "PDeclared "] PT.%+ PT.prettyLines p
| DaMSL/K3 | src/Language/K3/Analysis/Provenance/Core.hs | apache-2.0 | 4,165 | 0 | 18 | 1,050 | 993 | 533 | 460 | 115 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextLayout.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTextLayout (
QqTextLayout(..)
,QqTextLayout_nf(..)
,additionalFormats
,beginLayout
,cacheEnabled
,clearAdditionalFormats
,createLine
,QdrawCursor(..), QqdrawCursor(..)
,endLayout
,isValidCursorPosition
,lineAt
,lineCount
,lineForTextPosition
,QnextCursorPosition(..)
,preeditAreaPosition
,preeditAreaText
,QpreviousCursorPosition(..)
,setCacheEnabled
,setPreeditArea
,setTextOption
,textOption
,qTextLayout_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QTextLayout
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqTextLayout x1 where
qTextLayout :: x1 -> IO (QTextLayout ())
instance QqTextLayout (()) where
qTextLayout ()
= withQTextLayoutResult $
qtc_QTextLayout
foreign import ccall "qtc_QTextLayout" qtc_QTextLayout :: IO (Ptr (TQTextLayout ()))
instance QqTextLayout ((String)) where
qTextLayout (x1)
= withQTextLayoutResult $
withCWString x1 $ \cstr_x1 ->
qtc_QTextLayout1 cstr_x1
foreign import ccall "qtc_QTextLayout1" qtc_QTextLayout1 :: CWString -> IO (Ptr (TQTextLayout ()))
instance QqTextLayout ((QTextBlock t1)) where
qTextLayout (x1)
= withQTextLayoutResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextLayout2 cobj_x1
foreign import ccall "qtc_QTextLayout2" qtc_QTextLayout2 :: Ptr (TQTextBlock t1) -> IO (Ptr (TQTextLayout ()))
instance QqTextLayout ((String, QFont t2)) where
qTextLayout (x1, x2)
= withQTextLayoutResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextLayout3 cstr_x1 cobj_x2
foreign import ccall "qtc_QTextLayout3" qtc_QTextLayout3 :: CWString -> Ptr (TQFont t2) -> IO (Ptr (TQTextLayout ()))
instance QqTextLayout ((String, QFont t2, QPaintDevice t3)) where
qTextLayout (x1, x2, x3)
= withQTextLayoutResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTextLayout4 cstr_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTextLayout4" qtc_QTextLayout4 :: CWString -> Ptr (TQFont t2) -> Ptr (TQPaintDevice t3) -> IO (Ptr (TQTextLayout ()))
instance QqTextLayout ((String, QFont t2, QWidget t3)) where
qTextLayout (x1, x2, x3)
= withQTextLayoutResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTextLayout4_widget cstr_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTextLayout4_widget" qtc_QTextLayout4_widget :: CWString -> Ptr (TQFont t2) -> Ptr (TQWidget t3) -> IO (Ptr (TQTextLayout ()))
class QqTextLayout_nf x1 where
qTextLayout_nf :: x1 -> IO (QTextLayout ())
instance QqTextLayout_nf (()) where
qTextLayout_nf ()
= withObjectRefResult $
qtc_QTextLayout
instance QqTextLayout_nf ((String)) where
qTextLayout_nf (x1)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
qtc_QTextLayout1 cstr_x1
instance QqTextLayout_nf ((QTextBlock t1)) where
qTextLayout_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextLayout2 cobj_x1
instance QqTextLayout_nf ((String, QFont t2)) where
qTextLayout_nf (x1, x2)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextLayout3 cstr_x1 cobj_x2
instance QqTextLayout_nf ((String, QFont t2, QPaintDevice t3)) where
qTextLayout_nf (x1, x2, x3)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTextLayout4 cstr_x1 cobj_x2 cobj_x3
instance QqTextLayout_nf ((String, QFont t2, QWidget t3)) where
qTextLayout_nf (x1, x2, x3)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTextLayout4_widget cstr_x1 cobj_x2 cobj_x3
additionalFormats :: QTextLayout a -> (()) -> IO ([QTextLayout__FormatRange ()])
additionalFormats x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_additionalFormats cobj_x0 arr
foreign import ccall "qtc_QTextLayout_additionalFormats" qtc_QTextLayout_additionalFormats :: Ptr (TQTextLayout a) -> Ptr (Ptr (TQTextLayout__FormatRange ())) -> IO CInt
beginLayout :: QTextLayout a -> (()) -> IO ()
beginLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_beginLayout cobj_x0
foreign import ccall "qtc_QTextLayout_beginLayout" qtc_QTextLayout_beginLayout :: Ptr (TQTextLayout a) -> IO ()
instance QqqboundingRect (QTextLayout a) (()) (IO (QRectF ())) where
qqboundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_boundingRect cobj_x0
foreign import ccall "qtc_QTextLayout_boundingRect" qtc_QTextLayout_boundingRect :: Ptr (TQTextLayout a) -> IO (Ptr (TQRectF ()))
instance QqboundingRect (QTextLayout a) (()) (IO (RectF)) where
qboundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QTextLayout_boundingRect_qth" qtc_QTextLayout_boundingRect_qth :: Ptr (TQTextLayout a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
cacheEnabled :: QTextLayout a -> (()) -> IO (Bool)
cacheEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_cacheEnabled cobj_x0
foreign import ccall "qtc_QTextLayout_cacheEnabled" qtc_QTextLayout_cacheEnabled :: Ptr (TQTextLayout a) -> IO CBool
clearAdditionalFormats :: QTextLayout a -> (()) -> IO ()
clearAdditionalFormats x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_clearAdditionalFormats cobj_x0
foreign import ccall "qtc_QTextLayout_clearAdditionalFormats" qtc_QTextLayout_clearAdditionalFormats :: Ptr (TQTextLayout a) -> IO ()
createLine :: QTextLayout a -> (()) -> IO (QTextLine ())
createLine x0 ()
= withQTextLineResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_createLine cobj_x0
foreign import ccall "qtc_QTextLayout_createLine" qtc_QTextLayout_createLine :: Ptr (TQTextLayout a) -> IO (Ptr (TQTextLine ()))
instance Qdraw (QTextLayout a) ((QPainter t1, PointF)) where
draw x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QTextLayout_draw_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y
foreign import ccall "qtc_QTextLayout_draw_qth" qtc_QTextLayout_draw_qth :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> IO ()
instance Qqdraw (QTextLayout a) ((QPainter t1, QPointF t2)) where
qdraw x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextLayout_draw cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTextLayout_draw" qtc_QTextLayout_draw :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> Ptr (TQPointF t2) -> IO ()
class QdrawCursor x1 where
drawCursor :: QTextLayout a -> x1 -> IO ()
class QqdrawCursor x1 where
qdrawCursor :: QTextLayout a -> x1 -> IO ()
instance QdrawCursor ((QPainter t1, PointF, Int)) where
drawCursor x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QTextLayout_drawCursor_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y (toCInt x3)
foreign import ccall "qtc_QTextLayout_drawCursor_qth" qtc_QTextLayout_drawCursor_qth :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> CInt -> IO ()
instance QdrawCursor ((QPainter t1, PointF, Int, Int)) where
drawCursor x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QTextLayout_drawCursor1_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTextLayout_drawCursor1_qth" qtc_QTextLayout_drawCursor1_qth :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> CInt -> CInt -> IO ()
instance QqdrawCursor ((QPainter t1, QPointF t2, Int)) where
qdrawCursor x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextLayout_drawCursor cobj_x0 cobj_x1 cobj_x2 (toCInt x3)
foreign import ccall "qtc_QTextLayout_drawCursor" qtc_QTextLayout_drawCursor :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> Ptr (TQPointF t2) -> CInt -> IO ()
instance QqdrawCursor ((QPainter t1, QPointF t2, Int, Int)) where
qdrawCursor x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextLayout_drawCursor1 cobj_x0 cobj_x1 cobj_x2 (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTextLayout_drawCursor1" qtc_QTextLayout_drawCursor1 :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> Ptr (TQPointF t2) -> CInt -> CInt -> IO ()
endLayout :: QTextLayout a -> (()) -> IO ()
endLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_endLayout cobj_x0
foreign import ccall "qtc_QTextLayout_endLayout" qtc_QTextLayout_endLayout :: Ptr (TQTextLayout a) -> IO ()
instance Qfont (QTextLayout a) (()) where
font x0 ()
= withQFontResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_font cobj_x0
foreign import ccall "qtc_QTextLayout_font" qtc_QTextLayout_font :: Ptr (TQTextLayout a) -> IO (Ptr (TQFont ()))
isValidCursorPosition :: QTextLayout a -> ((Int)) -> IO (Bool)
isValidCursorPosition x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_isValidCursorPosition cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextLayout_isValidCursorPosition" qtc_QTextLayout_isValidCursorPosition :: Ptr (TQTextLayout a) -> CInt -> IO CBool
lineAt :: QTextLayout a -> ((Int)) -> IO (QTextLine ())
lineAt x0 (x1)
= withQTextLineResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_lineAt cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextLayout_lineAt" qtc_QTextLayout_lineAt :: Ptr (TQTextLayout a) -> CInt -> IO (Ptr (TQTextLine ()))
lineCount :: QTextLayout a -> (()) -> IO (Int)
lineCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_lineCount cobj_x0
foreign import ccall "qtc_QTextLayout_lineCount" qtc_QTextLayout_lineCount :: Ptr (TQTextLayout a) -> IO CInt
lineForTextPosition :: QTextLayout a -> ((Int)) -> IO (QTextLine ())
lineForTextPosition x0 (x1)
= withQTextLineResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_lineForTextPosition cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextLayout_lineForTextPosition" qtc_QTextLayout_lineForTextPosition :: Ptr (TQTextLayout a) -> CInt -> IO (Ptr (TQTextLine ()))
instance QmaximumWidth (QTextLayout a) (()) (IO (Double)) where
maximumWidth x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_maximumWidth cobj_x0
foreign import ccall "qtc_QTextLayout_maximumWidth" qtc_QTextLayout_maximumWidth :: Ptr (TQTextLayout a) -> IO CDouble
instance QminimumWidth (QTextLayout a) (()) (IO (Double)) where
minimumWidth x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_minimumWidth cobj_x0
foreign import ccall "qtc_QTextLayout_minimumWidth" qtc_QTextLayout_minimumWidth :: Ptr (TQTextLayout a) -> IO CDouble
class QnextCursorPosition x1 where
nextCursorPosition :: QTextLayout a -> x1 -> IO (Int)
instance QnextCursorPosition ((Int)) where
nextCursorPosition x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_nextCursorPosition cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextLayout_nextCursorPosition" qtc_QTextLayout_nextCursorPosition :: Ptr (TQTextLayout a) -> CInt -> IO CInt
instance QnextCursorPosition ((Int, CursorMode)) where
nextCursorPosition x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_nextCursorPosition1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTextLayout_nextCursorPosition1" qtc_QTextLayout_nextCursorPosition1 :: Ptr (TQTextLayout a) -> CInt -> CLong -> IO CInt
instance Qposition (QTextLayout a) (()) (IO (PointF)) where
position x0 ()
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_position_qth cobj_x0 cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QTextLayout_position_qth" qtc_QTextLayout_position_qth :: Ptr (TQTextLayout a) -> Ptr CDouble -> Ptr CDouble -> IO ()
instance Qqposition (QTextLayout a) (()) where
qposition x0 ()
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_position cobj_x0
foreign import ccall "qtc_QTextLayout_position" qtc_QTextLayout_position :: Ptr (TQTextLayout a) -> IO (Ptr (TQPointF ()))
preeditAreaPosition :: QTextLayout a -> (()) -> IO (Int)
preeditAreaPosition x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_preeditAreaPosition cobj_x0
foreign import ccall "qtc_QTextLayout_preeditAreaPosition" qtc_QTextLayout_preeditAreaPosition :: Ptr (TQTextLayout a) -> IO CInt
preeditAreaText :: QTextLayout a -> (()) -> IO (String)
preeditAreaText x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_preeditAreaText cobj_x0
foreign import ccall "qtc_QTextLayout_preeditAreaText" qtc_QTextLayout_preeditAreaText :: Ptr (TQTextLayout a) -> IO (Ptr (TQString ()))
class QpreviousCursorPosition x1 where
previousCursorPosition :: QTextLayout a -> x1 -> IO (Int)
instance QpreviousCursorPosition ((Int)) where
previousCursorPosition x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_previousCursorPosition cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextLayout_previousCursorPosition" qtc_QTextLayout_previousCursorPosition :: Ptr (TQTextLayout a) -> CInt -> IO CInt
instance QpreviousCursorPosition ((Int, CursorMode)) where
previousCursorPosition x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_previousCursorPosition1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTextLayout_previousCursorPosition1" qtc_QTextLayout_previousCursorPosition1 :: Ptr (TQTextLayout a) -> CInt -> CLong -> IO CInt
setCacheEnabled :: QTextLayout a -> ((Bool)) -> IO ()
setCacheEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_setCacheEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTextLayout_setCacheEnabled" qtc_QTextLayout_setCacheEnabled :: Ptr (TQTextLayout a) -> CBool -> IO ()
instance QsetFont (QTextLayout a) ((QFont t1)) where
setFont x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextLayout_setFont cobj_x0 cobj_x1
foreign import ccall "qtc_QTextLayout_setFont" qtc_QTextLayout_setFont :: Ptr (TQTextLayout a) -> Ptr (TQFont t1) -> IO ()
instance QsetPosition (QTextLayout a) ((PointF)) where
setPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QTextLayout_setPosition_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QTextLayout_setPosition_qth" qtc_QTextLayout_setPosition_qth :: Ptr (TQTextLayout a) -> CDouble -> CDouble -> IO ()
instance QqsetPosition (QTextLayout a) ((QPointF t1)) where
qsetPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextLayout_setPosition cobj_x0 cobj_x1
foreign import ccall "qtc_QTextLayout_setPosition" qtc_QTextLayout_setPosition :: Ptr (TQTextLayout a) -> Ptr (TQPointF t1) -> IO ()
setPreeditArea :: QTextLayout a -> ((Int, String)) -> IO ()
setPreeditArea x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x2 $ \cstr_x2 ->
qtc_QTextLayout_setPreeditArea cobj_x0 (toCInt x1) cstr_x2
foreign import ccall "qtc_QTextLayout_setPreeditArea" qtc_QTextLayout_setPreeditArea :: Ptr (TQTextLayout a) -> CInt -> CWString -> IO ()
instance QsetText (QTextLayout a) ((String)) where
setText x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTextLayout_setText cobj_x0 cstr_x1
foreign import ccall "qtc_QTextLayout_setText" qtc_QTextLayout_setText :: Ptr (TQTextLayout a) -> CWString -> IO ()
setTextOption :: QTextLayout a -> ((QTextOption t1)) -> IO ()
setTextOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextLayout_setTextOption cobj_x0 cobj_x1
foreign import ccall "qtc_QTextLayout_setTextOption" qtc_QTextLayout_setTextOption :: Ptr (TQTextLayout a) -> Ptr (TQTextOption t1) -> IO ()
instance Qtext (QTextLayout a) (()) (IO (String)) where
text x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_text cobj_x0
foreign import ccall "qtc_QTextLayout_text" qtc_QTextLayout_text :: Ptr (TQTextLayout a) -> IO (Ptr (TQString ()))
textOption :: QTextLayout a -> (()) -> IO (QTextOption ())
textOption x0 ()
= withQTextOptionResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_textOption cobj_x0
foreign import ccall "qtc_QTextLayout_textOption" qtc_QTextLayout_textOption :: Ptr (TQTextLayout a) -> IO (Ptr (TQTextOption ()))
qTextLayout_delete :: QTextLayout a -> IO ()
qTextLayout_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextLayout_delete cobj_x0
foreign import ccall "qtc_QTextLayout_delete" qtc_QTextLayout_delete :: Ptr (TQTextLayout a) -> IO ()
| uduki/hsQt | Qtc/Gui/QTextLayout.hs | bsd-2-clause | 18,021 | 0 | 14 | 2,890 | 5,620 | 2,870 | 2,750 | -1 | -1 |
{-# OPTIONS_GHC -Wall -Werror #-}
module IRTS.CLaSH.Show where
import Core.CaseTree
import Core.TT
showSC :: SC -> String
showSC (STerm t) = showTerm t
showSC (Case n alts) = "Case " ++ show n ++ " of " ++ unlines (map showAlt alts)
showSC sc = "showSC: " ++ show sc
showAlt :: CaseAlt -> String
showAlt (ConCase n i ns sc) = show (n,i,ns) ++ " -> " ++ showSC sc
showAlt (ConstCase c sc) = showConstant c ++ " -> " ++ showSC sc
showAlt (DefaultCase sc) = "_ ->" ++ showSC sc
showAlt alt = "showAlt: " ++ show alt
showTerm :: Term -> String
showTerm (App e1 e2) = "App (" ++ showTerm e1 ++ ") (" ++ showTerm e2 ++ ")"
showTerm (Constant c) = "Constant (" ++ showConstant c ++ ")"
showTerm Impossible = "Impossible"
showTerm Erased = "Erased"
showTerm (P nt n tm) = "P {" ++ show nt ++ "} " ++ show n ++ " (" ++ showTerm tm ++ ")"
showTerm (V v) = "V " ++ show v
showTerm (Bind n bndr tm) = "Bind " ++ show n ++ " (" ++ showBinder bndr ++ ") (" ++ showTerm tm ++ ")"
showTerm (Proj tm i) = "Proj " ++ show i ++ " (" ++ show tm ++ ")"
showTerm (TType uexp) = "TType " ++ show uexp
showBinder :: Binder Term -> String
showBinder (Pi tm) = "Pi (" ++ showTerm tm ++ ")"
showBinder b = "showBinder: " ++ show b
showConstant :: Const -> String
showConstant (I _) = "(I i)"
showConstant (BI _) = "(BI i)"
showConstant (Fl _) = "(Fl f)"
showConstant (Ch _) = "(Ch c)"
showConstant (Str _) = "(Str s)"
showConstant (AType a) = "AType (" ++ showAType a ++ ")"
showConstant StrType = "StrType"
showConstant PtrType = "PtrType "
showConstant VoidType = "VoidType"
showConstant Forgot = "Forgot"
showConstant (B8 _) = "(B8 w)"
showConstant (B16 _) = "(B16 w)"
showConstant (B32 _) = "(B32 w)"
showConstant (B64 _) = "(B64 w)"
showConstant c = "showConstant: " ++ show c
showAType :: ArithTy -> String
showAType (ATInt ITNative) = "(ATInt ITNative)"
showAType (ATInt ITBig) = "(ATInt ITBig)"
showAType (ATInt ITChar) = "(ATInt ITChar)"
showAType (ATInt (ITFixed _)) = "(ATInt (ITFixed n))"
showAType (ATInt (ITVec _ _)) = "(ATInt (ITVec e c))"
showAType ATFloat = "ATFloat"
| christiaanb/Idris-dev | src/IRTS/CLaSH/Show.hs | bsd-3-clause | 2,225 | 0 | 11 | 562 | 849 | 418 | 431 | 49 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.