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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Show where
import Data.List
import Text.Printf
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.UTF8 as UTF8
import Network.DBus
showDBus :: DBusValue -> String
showDBus (DBusByte v) = show v
showDBus (DBusBoolean True) = "true"
showDBus (DBusBoolean False) = "false"
showDBus (DBusInt16 v) = show v
showDBus (DBusUInt16 v) = show v
showDBus (DBusInt32 v) = show v
showDBus (DBusUInt32 v) = show v
showDBus (DBusInt64 v) = show v
showDBus (DBusUInt64 v) = show v
showDBus (DBusDouble v) = show v
showDBus (DBusString (PackedString p)) = UTF8.toString p
showDBus (DBusObjectPath p) = unObjectPath p
showDBus (DBusSignature s) = show s
showDBus (DBusArray (SigDict _ _) kvs) = "{\n" ++ (unlines . map (" "++) . map showDBus $ kvs) ++ "}"
showDBus (DBusArray _ xs) = intercalate "\n" . map showDBus $ xs
showDBus (DBusByteArray b) = show b
showDBus (DBusStruct _ xs) = intercalate "\n" . map showDBus $ xs
showDBus (DBusDict k v) = printf "%-30s = %s" ("\"" ++ showDBus k ++ "\"") (showDBus v)
showDBus (DBusVariant v) = showDBus v
showDBus (DBusUnixFD v) = show v
|
crogers1/manager
|
xec/Show.hs
|
gpl-2.0
| 1,869
| 0
| 12
| 327
| 497
| 256
| 241
| 27
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Register
-- Copyright : Isaac Jones 2003-2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module deals with registering and unregistering packages. There are a
-- couple ways it can do this, one is to do it directly. Another is to generate
-- a script that can be run later to do it. The idea here being that the user
-- is shielded from the details of what command to use for package registration
-- for a particular compiler. In practice this aspect was not especially
-- popular so we also provide a way to simply generate the package registration
-- file which then must be manually passed to @ghc-pkg@. It is possible to
-- generate registration information for where the package is to be installed,
-- or alternatively to register the package in place in the build tree. The
-- latter is occasionally handy, and will become more important when we try to
-- build multi-package systems.
--
-- This module does not delegate anything to the per-compiler modules but just
-- mixes it all in in this module, which is rather unsatisfactory. The script
-- generation and the unregister feature are not well used or tested.
module Distribution.Simple.Register (
register,
unregister,
initPackageDB,
invokeHcPkg,
registerPackage,
generateRegistrationInfo,
inplaceInstalledPackageInfo,
absoluteInstalledPackageInfo,
generalInstalledPackageInfo,
) where
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), ComponentLocalBuildInfo(..)
, ComponentName(..), getComponentLocalBuildInfo
, InstallDirs(..), absoluteInstallDirs )
import Distribution.Simple.BuildPaths (haddockName)
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.GHCJS as GHCJS
import qualified Distribution.Simple.LHC as LHC
import qualified Distribution.Simple.UHC as UHC
import qualified Distribution.Simple.HaskellSuite as HaskellSuite
import Distribution.Simple.Compiler
( compilerVersion, Compiler, CompilerFlavor(..), compilerFlavor
, PackageDB, PackageDBStack, absolutePackageDBPaths
, registrationPackageDB )
import Distribution.Simple.Program
( ProgramConfiguration, runProgramInvocation )
import Distribution.Simple.Program.Script
( invocationAsSystemScript )
import Distribution.Simple.Program.HcPkg (HcPkgInfo)
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import Distribution.Simple.Setup
( RegisterFlags(..), CopyDest(..)
, fromFlag, fromFlagOrDefault, flagToMaybe )
import Distribution.PackageDescription
( PackageDescription(..), Library(..), BuildInfo(..), libModules )
import Distribution.Package
( Package(..), packageName, InstalledPackageId(..)
, getHSLibraryName )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo, InstalledPackageInfo_(InstalledPackageInfo)
, showInstalledPackageInfo )
import qualified Distribution.InstalledPackageInfo as IPI
import Distribution.Simple.Utils
( writeUTF8File, writeFileAtomic, setFileExecutable
, die, notice, setupMessage, shortRelativePath )
import Distribution.System
( OS(..), buildOS )
import Distribution.Text
( display )
import Distribution.Version ( Version(..) )
import Distribution.Verbosity as Verbosity
( Verbosity, normal )
import System.FilePath ((</>), (<.>), isAbsolute)
import System.Directory
( getCurrentDirectory )
import Control.Monad (when)
import Data.Maybe
( isJust, fromMaybe, maybeToList )
import Data.List
( partition, nub )
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
-- -----------------------------------------------------------------------------
-- Registration
register :: PackageDescription -> LocalBuildInfo
-> RegisterFlags -- ^Install in the user's database?; verbose
-> IO ()
register pkg@PackageDescription { library = Just lib } lbi regFlags
= do
let clbi = getComponentLocalBuildInfo lbi CLibName
absPackageDBs <- absolutePackageDBPaths packageDbs
installedPkgInfo <- generateRegistrationInfo
verbosity pkg lib lbi clbi inplace reloc distPref
(registrationPackageDB absPackageDBs)
when (fromFlag (regPrintId regFlags)) $ do
putStrLn (display (IPI.installedPackageId installedPkgInfo))
-- Three different modes:
case () of
_ | modeGenerateRegFile -> writeRegistrationFile installedPkgInfo
| modeGenerateRegScript -> writeRegisterScript installedPkgInfo
| otherwise -> registerPackage verbosity
installedPkgInfo pkg lbi inplace packageDbs
where
modeGenerateRegFile = isJust (flagToMaybe (regGenPkgConf regFlags))
regFile = fromMaybe (display (packageId pkg) <.> "conf")
(fromFlag (regGenPkgConf regFlags))
modeGenerateRegScript = fromFlag (regGenScript regFlags)
inplace = fromFlag (regInPlace regFlags)
reloc = relocatable lbi
-- FIXME: there's really no guarantee this will work.
-- registering into a totally different db stack can
-- fail if dependencies cannot be satisfied.
packageDbs = nub $ withPackageDB lbi
++ maybeToList (flagToMaybe (regPackageDB regFlags))
distPref = fromFlag (regDistPref regFlags)
verbosity = fromFlag (regVerbosity regFlags)
writeRegistrationFile installedPkgInfo = do
notice verbosity ("Creating package registration file: " ++ regFile)
writeUTF8File regFile (showInstalledPackageInfo installedPkgInfo)
writeRegisterScript installedPkgInfo =
case compilerFlavor (compiler lbi) of
JHC -> notice verbosity "Registration scripts not needed for jhc"
UHC -> notice verbosity "Registration scripts not needed for uhc"
_ -> withHcPkg
"Registration scripts are not implemented for this compiler"
(compiler lbi) (withPrograms lbi)
(writeHcPkgRegisterScript verbosity installedPkgInfo packageDbs)
register _ _ regFlags = notice verbosity "No package to register"
where
verbosity = fromFlag (regVerbosity regFlags)
generateRegistrationInfo :: Verbosity
-> PackageDescription
-> Library
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Bool
-> Bool
-> FilePath
-> PackageDB
-> IO InstalledPackageInfo
generateRegistrationInfo verbosity pkg lib lbi clbi inplace reloc distPref packageDb = do
--TODO: eliminate pwd!
pwd <- getCurrentDirectory
--TODO: the method of setting the InstalledPackageId is compiler specific
-- this aspect should be delegated to a per-compiler helper.
let comp = compiler lbi
ipid <-
case compilerFlavor comp of
GHC | compilerVersion comp >= Version [6,11] [] -> do
s <- GHC.libAbiHash verbosity pkg lbi lib clbi
return (InstalledPackageId (display (packageId pkg) ++ '-':s))
GHCJS -> do
s <- GHCJS.libAbiHash verbosity pkg lbi lib clbi
return (InstalledPackageId (display (packageId pkg) ++ '-':s))
_other -> do
return (InstalledPackageId (display (packageId pkg)))
installedPkgInfo <-
if inplace
then return (inplaceInstalledPackageInfo pwd distPref
pkg ipid lib lbi clbi)
else if reloc
then relocRegistrationInfo verbosity
pkg lib lbi clbi ipid packageDb
else return (absoluteInstalledPackageInfo
pkg ipid lib lbi clbi)
return installedPkgInfo{ IPI.installedPackageId = ipid }
relocRegistrationInfo :: Verbosity
-> PackageDescription
-> Library
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> InstalledPackageId
-> PackageDB
-> IO InstalledPackageInfo
relocRegistrationInfo verbosity pkg lib lbi clbi ipid packageDb =
case (compilerFlavor (compiler lbi)) of
GHC -> do fs <- GHC.pkgRoot verbosity lbi packageDb
return (relocatableInstalledPackageInfo
pkg ipid lib lbi clbi fs)
_ -> die "Distribution.Simple.Register.relocRegistrationInfo: \
\not implemented for this compiler"
-- | Create an empty package DB at the specified location.
initPackageDB :: Verbosity -> Compiler -> ProgramConfiguration -> FilePath
-> IO ()
initPackageDB verbosity comp conf dbPath =
case compilerFlavor comp of
HaskellSuite {} -> HaskellSuite.initPackageDB verbosity conf dbPath
_ -> withHcPkg "Distribution.Simple.Register.initPackageDB: \
\not implemented for this compiler" comp conf
(\hpi -> HcPkg.init hpi verbosity dbPath)
-- | Run @hc-pkg@ using a given package DB stack, directly forwarding the
-- provided command-line arguments to it.
invokeHcPkg :: Verbosity -> Compiler -> ProgramConfiguration -> PackageDBStack
-> [String] -> IO ()
invokeHcPkg verbosity comp conf dbStack extraArgs =
withHcPkg "invokeHcPkg" comp conf
(\hpi -> HcPkg.invoke hpi verbosity dbStack extraArgs)
withHcPkg :: String -> Compiler -> ProgramConfiguration
-> (HcPkgInfo -> IO a) -> IO a
withHcPkg name comp conf f =
case compilerFlavor comp of
GHC -> f (GHC.hcPkgInfo conf)
GHCJS -> f (GHCJS.hcPkgInfo conf)
LHC -> f (LHC.hcPkgInfo conf)
_ -> die ("Distribution.Simple.Register." ++ name ++ ":\
\not implemented for this compiler")
registerPackage :: Verbosity
-> InstalledPackageInfo
-> PackageDescription
-> LocalBuildInfo
-> Bool
-> PackageDBStack
-> IO ()
registerPackage verbosity installedPkgInfo pkg lbi inplace packageDbs = do
let msg = if inplace
then "In-place registering"
else "Registering"
setupMessage verbosity msg (packageId pkg)
case compilerFlavor (compiler lbi) of
GHC -> GHC.registerPackage verbosity installedPkgInfo pkg lbi inplace packageDbs
GHCJS -> GHCJS.registerPackage verbosity installedPkgInfo pkg lbi inplace packageDbs
LHC -> LHC.registerPackage verbosity installedPkgInfo pkg lbi inplace packageDbs
UHC -> UHC.registerPackage verbosity installedPkgInfo pkg lbi inplace packageDbs
JHC -> notice verbosity "Registering for jhc (nothing to do)"
HaskellSuite {} ->
HaskellSuite.registerPackage verbosity installedPkgInfo pkg lbi inplace packageDbs
_ -> die "Registering is not implemented for this compiler"
writeHcPkgRegisterScript :: Verbosity
-> InstalledPackageInfo
-> PackageDBStack
-> HcPkgInfo
-> IO ()
writeHcPkgRegisterScript verbosity installedPkgInfo packageDbs hpi = do
let invocation = HcPkg.reregisterInvocation hpi Verbosity.normal
packageDbs (Right installedPkgInfo)
regScript = invocationAsSystemScript buildOS invocation
notice verbosity ("Creating package registration script: " ++ regScriptFileName)
writeUTF8File regScriptFileName regScript
setFileExecutable regScriptFileName
regScriptFileName :: FilePath
regScriptFileName = case buildOS of
Windows -> "register.bat"
_ -> "register.sh"
-- -----------------------------------------------------------------------------
-- Making the InstalledPackageInfo
-- | Construct 'InstalledPackageInfo' for a library in a package, given a set
-- of installation directories.
--
generalInstalledPackageInfo
:: ([FilePath] -> [FilePath]) -- ^ Translate relative include dir paths to
-- absolute paths.
-> PackageDescription
-> InstalledPackageId
-> Library
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> InstallDirs FilePath
-> InstalledPackageInfo
generalInstalledPackageInfo adjustRelIncDirs pkg ipid lib lbi clbi installDirs =
InstalledPackageInfo {
IPI.installedPackageId = ipid,
IPI.sourcePackageId = packageId pkg,
IPI.packageKey = componentPackageKey clbi,
IPI.license = license pkg,
IPI.copyright = copyright pkg,
IPI.maintainer = maintainer pkg,
IPI.author = author pkg,
IPI.stability = stability pkg,
IPI.homepage = homepage pkg,
IPI.pkgUrl = pkgUrl pkg,
IPI.synopsis = synopsis pkg,
IPI.description = description pkg,
IPI.category = category pkg,
IPI.exposed = libExposed lib,
IPI.exposedModules = map fixupSelf (componentExposedModules clbi),
IPI.hiddenModules = otherModules bi,
IPI.instantiatedWith = map (\(k,(p,n)) ->
(k,IPI.OriginalModule (IPI.installedPackageId p) n))
(instantiatedWith lbi),
IPI.trusted = IPI.trusted IPI.emptyInstalledPackageInfo,
IPI.importDirs = [ libdir installDirs | hasModules ],
-- Note. the libsubdir and datasubdir templates have already been expanded
-- into libdir and datadir.
IPI.libraryDirs = if hasLibrary
then libdir installDirs : extraLibDirs bi
else extraLibDirs bi,
IPI.dataDir = datadir installDirs,
IPI.hsLibraries = if hasLibrary
then [getHSLibraryName (componentLibraryName clbi)]
else [],
IPI.extraLibraries = extraLibs bi,
IPI.extraGHCiLibraries = extraGHCiLibs bi,
IPI.includeDirs = absinc ++ adjustRelIncDirs relinc,
IPI.includes = includes bi,
IPI.depends = map fst (componentPackageDeps clbi),
IPI.ccOptions = [], -- Note. NOT ccOptions bi!
-- We don't want cc-options to be propagated
-- to C compilations in other packages.
IPI.ldOptions = ldOptions bi,
IPI.frameworkDirs = [],
IPI.frameworks = frameworks bi,
IPI.haddockInterfaces = [haddockdir installDirs </> haddockName pkg],
IPI.haddockHTMLs = [htmldir installDirs],
IPI.pkgRoot = Nothing
}
where
bi = libBuildInfo lib
(absinc, relinc) = partition isAbsolute (includeDirs bi)
hasModules = not $ null (libModules lib)
hasLibrary = hasModules || not (null (cSources bi))
|| (not (null (jsSources bi)) &&
compilerFlavor (compiler lbi) == GHCJS)
-- Since we currently don't decide the InstalledPackageId of our package
-- until just before we register, we didn't have one for the re-exports
-- of modules defined within this package, so we used an empty one that
-- we fill in here now that we know what it is. It's a bit of a hack,
-- we ought really to decide the InstalledPackageId ahead of time.
fixupSelf (IPI.ExposedModule n o o') =
IPI.ExposedModule n (fmap fixupOriginalModule o)
(fmap fixupOriginalModule o')
fixupOriginalModule (IPI.OriginalModule i m) = IPI.OriginalModule (fixupIpid i) m
fixupIpid (InstalledPackageId []) = ipid
fixupIpid x = x
-- | Construct 'InstalledPackageInfo' for a library that is in place in the
-- build tree.
--
-- This function knows about the layout of in place packages.
--
inplaceInstalledPackageInfo :: FilePath -- ^ top of the build tree
-> FilePath -- ^ location of the dist tree
-> PackageDescription
-> InstalledPackageId
-> Library
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> InstalledPackageInfo
inplaceInstalledPackageInfo inplaceDir distPref pkg ipid lib lbi clbi =
generalInstalledPackageInfo adjustRelativeIncludeDirs
pkg ipid lib lbi clbi installDirs
where
adjustRelativeIncludeDirs = map (inplaceDir </>)
installDirs =
(absoluteInstallDirs pkg lbi NoCopyDest) {
libdir = inplaceDir </> buildDir lbi,
datadir = inplaceDir </> dataDir pkg,
docdir = inplaceDocdir,
htmldir = inplaceHtmldir,
haddockdir = inplaceHtmldir
}
inplaceDocdir = inplaceDir </> distPref </> "doc"
inplaceHtmldir = inplaceDocdir </> "html" </> display (packageName pkg)
-- | Construct 'InstalledPackageInfo' for the final install location of a
-- library package.
--
-- This function knows about the layout of installed packages.
--
absoluteInstalledPackageInfo :: PackageDescription
-> InstalledPackageId
-> Library
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> InstalledPackageInfo
absoluteInstalledPackageInfo pkg ipid lib lbi clbi =
generalInstalledPackageInfo adjustReativeIncludeDirs
pkg ipid lib lbi clbi installDirs
where
-- For installed packages we install all include files into one dir,
-- whereas in the build tree they may live in multiple local dirs.
adjustReativeIncludeDirs _
| null (installIncludes bi) = []
| otherwise = [includedir installDirs]
bi = libBuildInfo lib
installDirs = absoluteInstallDirs pkg lbi NoCopyDest
relocatableInstalledPackageInfo :: PackageDescription
-> InstalledPackageId
-> Library
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> FilePath
-> InstalledPackageInfo
relocatableInstalledPackageInfo pkg ipid lib lbi clbi pkgroot =
generalInstalledPackageInfo adjustReativeIncludeDirs
pkg ipid lib lbi clbi installDirs
where
-- For installed packages we install all include files into one dir,
-- whereas in the build tree they may live in multiple local dirs.
adjustReativeIncludeDirs _
| null (installIncludes bi) = []
| otherwise = [includedir installDirs]
bi = libBuildInfo lib
installDirs = fmap (("${pkgroot}" </>) . shortRelativePath pkgroot)
$ absoluteInstallDirs pkg lbi NoCopyDest
-- -----------------------------------------------------------------------------
-- Unregistration
unregister :: PackageDescription -> LocalBuildInfo -> RegisterFlags -> IO ()
unregister pkg lbi regFlags = do
let pkgid = packageId pkg
genScript = fromFlag (regGenScript regFlags)
verbosity = fromFlag (regVerbosity regFlags)
packageDb = fromFlagOrDefault (registrationPackageDB (withPackageDB lbi))
(regPackageDB regFlags)
unreg hpi =
let invocation = HcPkg.unregisterInvocation
hpi Verbosity.normal packageDb pkgid
in if genScript
then writeFileAtomic unregScriptFileName
(BS.Char8.pack $ invocationAsSystemScript buildOS invocation)
else runProgramInvocation verbosity invocation
setupMessage verbosity "Unregistering" pkgid
withHcPkg "unregistering is only implemented for GHC and GHCJS"
(compiler lbi) (withPrograms lbi) unreg
unregScriptFileName :: FilePath
unregScriptFileName = case buildOS of
Windows -> "unregister.bat"
_ -> "unregister.sh"
|
rimmington/cabal
|
Cabal/Distribution/Simple/Register.hs
|
bsd-3-clause
| 20,437
| 0
| 22
| 5,935
| 3,687
| 1,960
| 1,727
| 341
| 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="da-DK">
<title>All In One Notes Add-On</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/allinonenotes/src/main/javahelp/org/zaproxy/zap/extension/allinonenotes/resources/help_da_DK/helpset_da_DK.hs
|
apache-2.0
| 968
| 77
| 67
| 159
| 417
| 211
| 206
| -1
| -1
|
module A2 where
data BTree a
= Empty | T a (BTree a) (BTree a) deriving Show
buildtree :: Ord a => [a] -> BTree a
buildtree [] = Empty
buildtree ((x : xs)) = insert x (buildtree xs)
insert :: Ord a => a -> (BTree a) -> BTree a
insert val Empty = T val Empty Empty
insert val t@(T tval left right)
| val > tval = T tval left (insert val right)
| otherwise = t
main :: BTree Int
main = buildtree [3, 1, 2]
|
kmate/HaRe
|
old/testing/unfoldAsPatterns/A2AST.hs
|
bsd-3-clause
| 429
| 0
| 9
| 115
| 225
| 115
| 110
| 13
| 1
|
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation: expressions
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmExpr ( cgExpr ) where
#define FAST_STRING_NOT_NEEDED
#include "HsVersions.h"
import {-# SOURCE #-} StgCmmBind ( cgBind )
import StgCmmMonad
import StgCmmHeap
import StgCmmEnv
import StgCmmCon
import StgCmmProf (saveCurrentCostCentre, restoreCurrentCostCentre, emitSetCCC)
import StgCmmLayout
import StgCmmPrim
import StgCmmHpc
import StgCmmTicky
import StgCmmUtils
import StgCmmClosure
import StgSyn
import MkGraph
import BlockId
import Cmm
import CmmInfo
import CoreSyn
import DataCon
import ForeignCall
import Id
import PrimOp
import TyCon
import Type
import CostCentre ( CostCentreStack, currentCCS )
import Maybes
import Util
import FastString
import Outputable
import Control.Monad (when,void)
import Control.Arrow (first)
#if __GLASGOW_HASKELL__ >= 709
import Prelude hiding ((<*>))
#endif
------------------------------------------------------------------------
-- cgExpr: the main function
------------------------------------------------------------------------
cgExpr :: StgExpr -> FCode ReturnKind
cgExpr (StgApp fun args) = cgIdApp fun args
{- seq# a s ==> a -}
cgExpr (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _res_ty) =
cgIdApp a []
cgExpr (StgOpApp op args ty) = cgOpApp op args ty
cgExpr (StgConApp con args) = cgConApp con args
cgExpr (StgTick t e) = cgTick t >> cgExpr e
cgExpr (StgLit lit) = do cmm_lit <- cgLit lit
emitReturn [CmmLit cmm_lit]
cgExpr (StgLet binds expr) = do { cgBind binds; cgExpr expr }
cgExpr (StgLetNoEscape _ _ binds expr) =
do { u <- newUnique
; let join_id = mkBlockId u
; cgLneBinds join_id binds
; r <- cgExpr expr
; emitLabel join_id
; return r }
cgExpr (StgCase expr _live_vars _save_vars bndr _srt alt_type alts) =
cgCase expr bndr alt_type alts
cgExpr (StgLam {}) = panic "cgExpr: StgLam"
------------------------------------------------------------------------
-- Let no escape
------------------------------------------------------------------------
{- Generating code for a let-no-escape binding, aka join point is very
very similar to what we do for a case expression. The duality is
between
let-no-escape x = b
in e
and
case e of ... -> b
That is, the RHS of 'x' (ie 'b') will execute *later*, just like
the alternative of the case; it needs to be compiled in an environment
in which all volatile bindings are forgotten, and the free vars are
bound only to stable things like stack locations.. The 'e' part will
execute *next*, just like the scrutinee of a case. -}
-------------------------
cgLneBinds :: BlockId -> StgBinding -> FCode ()
cgLneBinds join_id (StgNonRec bndr rhs)
= do { local_cc <- saveCurrentCostCentre
-- See Note [Saving the current cost centre]
; (info, fcode) <- cgLetNoEscapeRhs join_id local_cc bndr rhs
; fcode
; addBindC info }
cgLneBinds join_id (StgRec pairs)
= do { local_cc <- saveCurrentCostCentre
; r <- sequence $ unzipWith (cgLetNoEscapeRhs join_id local_cc) pairs
; let (infos, fcodes) = unzip r
; addBindsC infos
; sequence_ fcodes
}
-------------------------
cgLetNoEscapeRhs
:: BlockId -- join point for successor of let-no-escape
-> Maybe LocalReg -- Saved cost centre
-> Id
-> StgRhs
-> FCode (CgIdInfo, FCode ())
cgLetNoEscapeRhs join_id local_cc bndr rhs =
do { (info, rhs_code) <- cgLetNoEscapeRhsBody local_cc bndr rhs
; let (bid, _) = expectJust "cgLetNoEscapeRhs" $ maybeLetNoEscape info
; let code = do { (_, body) <- getCodeScoped rhs_code
; emitOutOfLine bid (first (<*> mkBranch join_id) body) }
; return (info, code)
}
cgLetNoEscapeRhsBody
:: Maybe LocalReg -- Saved cost centre
-> Id
-> StgRhs
-> FCode (CgIdInfo, FCode ())
cgLetNoEscapeRhsBody local_cc bndr (StgRhsClosure cc _bi _ _upd _ args body)
= cgLetNoEscapeClosure bndr local_cc cc (nonVoidIds args) body
cgLetNoEscapeRhsBody local_cc bndr (StgRhsCon cc con args)
= cgLetNoEscapeClosure bndr local_cc cc [] (StgConApp con args)
-- For a constructor RHS we want to generate a single chunk of
-- code which can be jumped to from many places, which will
-- return the constructor. It's easy; just behave as if it
-- was an StgRhsClosure with a ConApp inside!
-------------------------
cgLetNoEscapeClosure
:: Id -- binder
-> Maybe LocalReg -- Slot for saved current cost centre
-> CostCentreStack -- XXX: *** NOT USED *** why not?
-> [NonVoid Id] -- Args (as in \ args -> body)
-> StgExpr -- Body (as in above)
-> FCode (CgIdInfo, FCode ())
cgLetNoEscapeClosure bndr cc_slot _unused_cc args body
= do dflags <- getDynFlags
return ( lneIdInfo dflags bndr args
, code )
where
code = forkLneBody $ do {
; withNewTickyCounterLNE (idName bndr) args $ do
; restoreCurrentCostCentre cc_slot
; arg_regs <- bindArgsToRegs args
; void $ noEscapeHeapCheck arg_regs (tickyEnterLNE >> cgExpr body) }
------------------------------------------------------------------------
-- Case expressions
------------------------------------------------------------------------
{- Note [Compiling case expressions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is quite interesting to decide whether to put a heap-check at the
start of each alternative. Of course we certainly have to do so if
the case forces an evaluation, or if there is a primitive op which can
trigger GC.
A more interesting situation is this (a Plan-B situation)
!P!;
...P...
case x# of
0# -> !Q!; ...Q...
default -> !R!; ...R...
where !x! indicates a possible heap-check point. The heap checks
in the alternatives *can* be omitted, in which case the topmost
heapcheck will take their worst case into account.
In favour of omitting !Q!, !R!:
- *May* save a heap overflow test,
if ...P... allocates anything.
- We can use relative addressing from a single Hp to
get at all the closures so allocated.
- No need to save volatile vars etc across heap checks
in !Q!, !R!
Against omitting !Q!, !R!
- May put a heap-check into the inner loop. Suppose
the main loop is P -> R -> P -> R...
Q is the loop exit, and only it does allocation.
This only hurts us if P does no allocation. If P allocates,
then there is a heap check in the inner loop anyway.
- May do more allocation than reqd. This sometimes bites us
badly. For example, nfib (ha!) allocates about 30\% more space if the
worst-casing is done, because many many calls to nfib are leaf calls
which don't need to allocate anything.
We can un-allocate, but that costs an instruction
Neither problem hurts us if there is only one alternative.
Suppose the inner loop is P->R->P->R etc. Then here is
how many heap checks we get in the *inner loop* under various
conditions
Alooc Heap check in branches (!Q!, !R!)?
P Q R yes no (absorb to !P!)
--------------------------------------
n n n 0 0
n y n 0 1
n . y 1 1
y . y 2 1
y . n 1 1
Best choices: absorb heap checks from Q and R into !P! iff
a) P itself does some allocation
or
b) P does allocation, or there is exactly one alternative
We adopt (b) because that is more likely to put the heap check at the
entry to a function, when not many things are live. After a bunch of
single-branch cases, we may have lots of things live
Hence: two basic plans for
case e of r { alts }
------ Plan A: the general case ---------
...save current cost centre...
...code for e,
with sequel (SetLocals r)
...restore current cost centre...
...code for alts...
...alts do their own heap checks
------ Plan B: special case when ---------
(i) e does not allocate or call GC
(ii) either upstream code performs allocation
or there is just one alternative
Then heap allocation in the (single) case branch
is absorbed by the upstream check.
Very common example: primops on unboxed values
...code for e,
with sequel (SetLocals r)...
...code for alts...
...no heap check...
-}
-------------------------------------
data GcPlan
= GcInAlts -- Put a GC check at the start the case alternatives,
[LocalReg] -- which binds these registers
| NoGcInAlts -- The scrutinee is a primitive value, or a call to a
-- primitive op which does no GC. Absorb the allocation
-- of the case alternative(s) into the upstream check
-------------------------------------
cgCase :: StgExpr -> Id -> AltType -> [StgAlt] -> FCode ReturnKind
cgCase (StgOpApp (StgPrimOp op) args _) bndr (AlgAlt tycon) alts
| isEnumerationTyCon tycon -- Note [case on bool]
= do { tag_expr <- do_enum_primop op args
-- If the binder is not dead, convert the tag to a constructor
-- and assign it.
; when (not (isDeadBinder bndr)) $ do
{ dflags <- getDynFlags
; tmp_reg <- bindArgToReg (NonVoid bndr)
; emitAssign (CmmLocal tmp_reg)
(tagToClosure dflags tycon tag_expr) }
; (mb_deflt, branches) <- cgAlgAltRhss (NoGcInAlts,AssignedDirectly)
(NonVoid bndr) alts
; emitSwitch tag_expr branches mb_deflt 0 (tyConFamilySize tycon - 1)
; return AssignedDirectly
}
where
do_enum_primop :: PrimOp -> [StgArg] -> FCode CmmExpr
do_enum_primop TagToEnumOp [arg] -- No code!
= getArgAmode (NonVoid arg)
do_enum_primop primop args
= do dflags <- getDynFlags
tmp <- newTemp (bWord dflags)
cgPrimOp [tmp] primop args
return (CmmReg (CmmLocal tmp))
{-
Note [case on bool]
~~~~~~~~~~~~~~~~~~~
This special case handles code like
case a <# b of
True ->
False ->
--> case tagToEnum# (a <$# b) of
True -> .. ; False -> ...
--> case (a <$# b) of r ->
case tagToEnum# r of
True -> .. ; False -> ...
If we let the ordinary case code handle it, we'll get something like
tmp1 = a < b
tmp2 = Bool_closure_tbl[tmp1]
if (tmp2 & 7 != 0) then ... // normal tagged case
but this junk won't optimise away. What we really want is just an
inline comparison:
if (a < b) then ...
So we add a special case to generate
tmp1 = a < b
if (tmp1 == 0) then ...
and later optimisations will further improve this.
Now that #6135 has been resolved it should be possible to remove that
special case. The idea behind this special case and pre-6135 implementation
of Bool-returning primops was that tagToEnum# was added implicitly in the
codegen and then optimized away. Now the call to tagToEnum# is explicit
in the source code, which allows to optimize it away at the earlier stages
of compilation (i.e. at the Core level).
Note [Scrutinising VoidRep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have this STG code:
f = \[s : State# RealWorld] ->
case s of _ -> blah
This is very odd. Why are we scrutinising a state token? But it
can arise with bizarre NOINLINE pragmas (Trac #9964)
crash :: IO ()
crash = IO (\s -> let {-# NOINLINE s' #-}
s' = s
in (# s', () #))
Now the trouble is that 's' has VoidRep, and we do not bind void
arguments in the environment; they don't live anywhere. See the
calls to nonVoidIds in various places. So we must not look up
's' in the environment. Instead, just evaluate the RHS! Simple.
-}
cgCase (StgApp v []) _ (PrimAlt _) alts
| isVoidRep (idPrimRep v) -- See Note [Scrutinising VoidRep]
, [(DEFAULT, _, _, rhs)] <- alts
= cgExpr rhs
{- Note [Dodgy unsafeCoerce 1]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
case (x :: HValue) |> co of (y :: MutVar# Int)
DEFAULT -> ...
We want to gnerate an assignment
y := x
We want to allow this assignment to be generated in the case when the
types are compatible, because this allows some slightly-dodgy but
occasionally-useful casts to be used, such as in RtClosureInspect
where we cast an HValue to a MutVar# so we can print out the contents
of the MutVar#. If instead we generate code that enters the HValue,
then we'll get a runtime panic, because the HValue really is a
MutVar#. The types are compatible though, so we can just generate an
assignment.
-}
cgCase (StgApp v []) bndr alt_type@(PrimAlt _) alts
| isUnLiftedType (idType v) -- Note [Dodgy unsafeCoerce 1]
|| reps_compatible
= -- assignment suffices for unlifted types
do { dflags <- getDynFlags
; when (not reps_compatible) $
panic "cgCase: reps do not match, perhaps a dodgy unsafeCoerce?"
; v_info <- getCgIdInfo v
; emitAssign (CmmLocal (idToReg dflags (NonVoid bndr)))
(idInfoToAmode v_info)
; bindArgsToRegs [NonVoid bndr]
; cgAlts (NoGcInAlts,AssignedDirectly) (NonVoid bndr) alt_type alts }
where
reps_compatible = idPrimRep v == idPrimRep bndr
{- Note [Dodgy unsafeCoerce 2, #3132]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In all other cases of a lifted Id being cast to an unlifted type, the
Id should be bound to bottom, otherwise this is an unsafe use of
unsafeCoerce. We can generate code to enter the Id and assume that
it will never return. Hence, we emit the usual enter/return code, and
because bottom must be untagged, it will be entered. The Sequel is a
type-correct assignment, albeit bogus. The (dead) continuation loops;
it would be better to invoke some kind of panic function here.
-}
cgCase scrut@(StgApp v []) _ (PrimAlt _) _
= do { dflags <- getDynFlags
; mb_cc <- maybeSaveCostCentre True
; withSequel (AssignTo [idToReg dflags (NonVoid v)] False) (cgExpr scrut)
; restoreCurrentCostCentre mb_cc
; emitComment $ mkFastString "should be unreachable code"
; l <- newLabelC
; emitLabel l
; emit (mkBranch l) -- an infinite loop
; return AssignedDirectly
}
{- Note [Handle seq#]
~~~~~~~~~~~~~~~~~~~~~
case seq# a s of v
(# s', a' #) -> e
==>
case a of v
(# s', a' #) -> e
(taking advantage of the fact that the return convention for (# State#, a #)
is the same as the return convention for just 'a')
-}
cgCase (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _) bndr alt_type alts
= -- Note [Handle seq#]
-- Use the same return convention as vanilla 'a'.
cgCase (StgApp a []) bndr alt_type alts
cgCase scrut bndr alt_type alts
= -- the general case
do { dflags <- getDynFlags
; up_hp_usg <- getVirtHp -- Upstream heap usage
; let ret_bndrs = chooseReturnBndrs bndr alt_type alts
alt_regs = map (idToReg dflags) ret_bndrs
; simple_scrut <- isSimpleScrut scrut alt_type
; let do_gc | not simple_scrut = True
| isSingleton alts = False
| up_hp_usg > 0 = False
| otherwise = True
-- cf Note [Compiling case expressions]
gc_plan = if do_gc then GcInAlts alt_regs else NoGcInAlts
; mb_cc <- maybeSaveCostCentre simple_scrut
; let sequel = AssignTo alt_regs do_gc{- Note [scrut sequel] -}
; ret_kind <- withSequel sequel (cgExpr scrut)
; restoreCurrentCostCentre mb_cc
; _ <- bindArgsToRegs ret_bndrs
; cgAlts (gc_plan,ret_kind) (NonVoid bndr) alt_type alts
}
{-
Note [scrut sequel]
The job of the scrutinee is to assign its value(s) to alt_regs.
Additionally, if we plan to do a heap-check in the alternatives (see
Note [Compiling case expressions]), then we *must* retreat Hp to
recover any unused heap before passing control to the sequel. If we
don't do this, then any unused heap will become slop because the heap
check will reset the heap usage. Slop in the heap breaks LDV profiling
(+RTS -hb) which needs to do a linear sweep through the nursery.
Note [Inlining out-of-line primops and heap checks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If shouldInlinePrimOp returns True when called from StgCmmExpr for the
purpose of heap check placement, we *must* inline the primop later in
StgCmmPrim. If we don't things will go wrong.
-}
-----------------
maybeSaveCostCentre :: Bool -> FCode (Maybe LocalReg)
maybeSaveCostCentre simple_scrut
| simple_scrut = return Nothing
| otherwise = saveCurrentCostCentre
-----------------
isSimpleScrut :: StgExpr -> AltType -> FCode Bool
-- Simple scrutinee, does not block or allocate; hence safe to amalgamate
-- heap usage from alternatives into the stuff before the case
-- NB: if you get this wrong, and claim that the expression doesn't allocate
-- when it does, you'll deeply mess up allocation
isSimpleScrut (StgOpApp op args _) _ = isSimpleOp op args
isSimpleScrut (StgLit _) _ = return True -- case 1# of { 0# -> ..; ... }
isSimpleScrut (StgApp _ []) (PrimAlt _) = return True -- case x# of { 0# -> ..; ... }
isSimpleScrut _ _ = return False
isSimpleOp :: StgOp -> [StgArg] -> FCode Bool
-- True iff the op cannot block or allocate
isSimpleOp (StgFCallOp (CCall (CCallSpec _ _ safe)) _) _ = return $! not (playSafe safe)
isSimpleOp (StgPrimOp op) stg_args = do
arg_exprs <- getNonVoidArgAmodes stg_args
dflags <- getDynFlags
-- See Note [Inlining out-of-line primops and heap checks]
return $! isJust $ shouldInlinePrimOp dflags op arg_exprs
isSimpleOp (StgPrimCallOp _) _ = return False
-----------------
chooseReturnBndrs :: Id -> AltType -> [StgAlt] -> [NonVoid Id]
-- These are the binders of a case that are assigned
-- by the evaluation of the scrutinee
-- Only non-void ones come back
chooseReturnBndrs bndr (PrimAlt _) _alts
= nonVoidIds [bndr]
chooseReturnBndrs _bndr (UbxTupAlt _) [(_, ids, _, _)]
= nonVoidIds ids -- 'bndr' is not assigned!
chooseReturnBndrs bndr (AlgAlt _) _alts
= nonVoidIds [bndr] -- Only 'bndr' is assigned
chooseReturnBndrs bndr PolyAlt _alts
= nonVoidIds [bndr] -- Only 'bndr' is assigned
chooseReturnBndrs _ _ _ = panic "chooseReturnBndrs"
-- UbxTupALt has only one alternative
-------------------------------------
cgAlts :: (GcPlan,ReturnKind) -> NonVoid Id -> AltType -> [StgAlt]
-> FCode ReturnKind
-- At this point the result of the case are in the binders
cgAlts gc_plan _bndr PolyAlt [(_, _, _, rhs)]
= maybeAltHeapCheck gc_plan (cgExpr rhs)
cgAlts gc_plan _bndr (UbxTupAlt _) [(_, _, _, rhs)]
= maybeAltHeapCheck gc_plan (cgExpr rhs)
-- Here bndrs are *already* in scope, so don't rebind them
cgAlts gc_plan bndr (PrimAlt _) alts
= do { dflags <- getDynFlags
; tagged_cmms <- cgAltRhss gc_plan bndr alts
; let bndr_reg = CmmLocal (idToReg dflags bndr)
(DEFAULT,deflt) = head tagged_cmms
-- PrimAlts always have a DEFAULT case
-- and it always comes first
tagged_cmms' = [(lit,code)
| (LitAlt lit, code) <- tagged_cmms]
; emitCmmLitSwitch (CmmReg bndr_reg) tagged_cmms' deflt
; return AssignedDirectly }
cgAlts gc_plan bndr (AlgAlt tycon) alts
= do { dflags <- getDynFlags
; (mb_deflt, branches) <- cgAlgAltRhss gc_plan bndr alts
; let fam_sz = tyConFamilySize tycon
bndr_reg = CmmLocal (idToReg dflags bndr)
-- Is the constructor tag in the node reg?
; if isSmallFamily dflags fam_sz
then do
let -- Yes, bndr_reg has constr. tag in ls bits
tag_expr = cmmConstrTag1 dflags (CmmReg bndr_reg)
branches' = [(tag+1,branch) | (tag,branch) <- branches]
emitSwitch tag_expr branches' mb_deflt 1 fam_sz
return AssignedDirectly
else -- No, get tag from info table
do dflags <- getDynFlags
let -- Note that ptr _always_ has tag 1
-- when the family size is big enough
untagged_ptr = cmmRegOffB bndr_reg (-1)
tag_expr = getConstrTag dflags (untagged_ptr)
emitSwitch tag_expr branches mb_deflt 0 (fam_sz - 1)
return AssignedDirectly }
cgAlts _ _ _ _ = panic "cgAlts"
-- UbxTupAlt and PolyAlt have only one alternative
-- Note [alg-alt heap check]
--
-- In an algebraic case with more than one alternative, we will have
-- code like
--
-- L0:
-- x = R1
-- goto L1
-- L1:
-- if (x & 7 >= 2) then goto L2 else goto L3
-- L2:
-- Hp = Hp + 16
-- if (Hp > HpLim) then goto L4
-- ...
-- L4:
-- call gc() returns to L5
-- L5:
-- x = R1
-- goto L1
-------------------
cgAlgAltRhss :: (GcPlan,ReturnKind) -> NonVoid Id -> [StgAlt]
-> FCode ( Maybe CmmAGraphScoped
, [(ConTagZ, CmmAGraphScoped)] )
cgAlgAltRhss gc_plan bndr alts
= do { tagged_cmms <- cgAltRhss gc_plan bndr alts
; let { mb_deflt = case tagged_cmms of
((DEFAULT,rhs) : _) -> Just rhs
_other -> Nothing
-- DEFAULT is always first, if present
; branches = [ (dataConTagZ con, cmm)
| (DataAlt con, cmm) <- tagged_cmms ]
}
; return (mb_deflt, branches)
}
-------------------
cgAltRhss :: (GcPlan,ReturnKind) -> NonVoid Id -> [StgAlt]
-> FCode [(AltCon, CmmAGraphScoped)]
cgAltRhss gc_plan bndr alts = do
dflags <- getDynFlags
let
base_reg = idToReg dflags bndr
cg_alt :: StgAlt -> FCode (AltCon, CmmAGraphScoped)
cg_alt (con, bndrs, _uses, rhs)
= getCodeScoped $
maybeAltHeapCheck gc_plan $
do { _ <- bindConArgs con base_reg bndrs
; _ <- cgExpr rhs
; return con }
forkAlts (map cg_alt alts)
maybeAltHeapCheck :: (GcPlan,ReturnKind) -> FCode a -> FCode a
maybeAltHeapCheck (NoGcInAlts,_) code = code
maybeAltHeapCheck (GcInAlts regs, AssignedDirectly) code =
altHeapCheck regs code
maybeAltHeapCheck (GcInAlts regs, ReturnedTo lret off) code =
altHeapCheckReturnsTo regs lret off code
-----------------------------------------------------------------------------
-- Tail calls
-----------------------------------------------------------------------------
cgConApp :: DataCon -> [StgArg] -> FCode ReturnKind
cgConApp con stg_args
| isUnboxedTupleCon con -- Unboxed tuple: assign and return
= do { arg_exprs <- getNonVoidArgAmodes stg_args
; tickyUnboxedTupleReturn (length arg_exprs)
; emitReturn arg_exprs }
| otherwise -- Boxed constructors; allocate and return
= ASSERT2( stg_args `lengthIs` dataConRepRepArity con, ppr con <+> ppr stg_args )
do { (idinfo, fcode_init) <- buildDynCon (dataConWorkId con) False
currentCCS con stg_args
-- The first "con" says that the name bound to this
-- closure is is "con", which is a bit of a fudge, but
-- it only affects profiling (hence the False)
; emit =<< fcode_init
; emitReturn [idInfoToAmode idinfo] }
cgIdApp :: Id -> [StgArg] -> FCode ReturnKind
cgIdApp fun_id [] | isVoidTy (idType fun_id) = emitReturn []
cgIdApp fun_id args = do
dflags <- getDynFlags
fun_info <- getCgIdInfo fun_id
self_loop_info <- getSelfLoop
let cg_fun_id = cg_id fun_info
-- NB: use (cg_id fun_info) instead of fun_id, because
-- the former may be externalised for -split-objs.
-- See Note [Externalise when splitting] in StgCmmMonad
fun_arg = StgVarArg cg_fun_id
fun_name = idName cg_fun_id
fun = idInfoToAmode fun_info
lf_info = cg_lf fun_info
node_points dflags = nodeMustPointToIt dflags lf_info
case (getCallMethod dflags fun_name cg_fun_id lf_info (length args) (cg_loc fun_info) self_loop_info) of
-- A value in WHNF, so we can just return it.
ReturnIt -> emitReturn [fun] -- ToDo: does ReturnIt guarantee tagged?
EnterIt -> ASSERT( null args ) -- Discarding arguments
emitEnter fun
SlowCall -> do -- A slow function call via the RTS apply routines
{ tickySlowCall lf_info args
; emitComment $ mkFastString "slowCall"
; slowCall fun args }
-- A direct function call (possibly with some left-over arguments)
DirectEntry lbl arity -> do
{ tickyDirectCall arity args
; if node_points dflags
then directCall NativeNodeCall lbl arity (fun_arg:args)
else directCall NativeDirectCall lbl arity args }
-- Let-no-escape call or self-recursive tail-call
JumpToIt blk_id lne_regs -> do
{ adjustHpBackwards -- always do this before a tail-call
; cmm_args <- getNonVoidArgAmodes args
; emitMultiAssign lne_regs cmm_args
; emit (mkBranch blk_id)
; return AssignedDirectly }
-- Note [Self-recursive tail calls]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Self-recursive tail calls can be optimized into a local jump in the same
-- way as let-no-escape bindings (see Note [What is a non-escaping let] in
-- stgSyn/CoreToStg.hs). Consider this:
--
-- foo.info:
-- a = R1 // calling convention
-- b = R2
-- goto L1
-- L1: ...
-- ...
-- ...
-- L2: R1 = x
-- R2 = y
-- call foo(R1,R2)
--
-- Instead of putting x and y into registers (or other locations required by the
-- calling convention) and performing a call we can put them into local
-- variables a and b and perform jump to L1:
--
-- foo.info:
-- a = R1
-- b = R2
-- goto L1
-- L1: ...
-- ...
-- ...
-- L2: a = x
-- b = y
-- goto L1
--
-- This can be done only when function is calling itself in a tail position
-- and only if the call passes number of parameters equal to function's arity.
-- Note that this cannot be performed if a function calls itself with a
-- continuation.
--
-- This in fact implements optimization known as "loopification". It was
-- described in "Low-level code optimizations in the Glasgow Haskell Compiler"
-- by Krzysztof Woś, though we use different approach. Krzysztof performed his
-- optimization at the Cmm level, whereas we perform ours during code generation
-- (Stg-to-Cmm pass) essentially making sure that optimized Cmm code is
-- generated in the first place.
--
-- Implementation is spread across a couple of places in the code:
--
-- * FCode monad stores additional information in its reader environment
-- (cgd_self_loop field). This information tells us which function can
-- tail call itself in an optimized way (it is the function currently
-- being compiled), what is the label of a loop header (L1 in example above)
-- and information about local registers in which we should arguments
-- before making a call (this would be a and b in example above).
--
-- * Whenever we are compiling a function, we set that information to reflect
-- the fact that function currently being compiled can be jumped to, instead
-- of called. This is done in closureCodyBody in StgCmmBind.
--
-- * We also have to emit a label to which we will be jumping. We make sure
-- that the label is placed after a stack check but before the heap
-- check. The reason is that making a recursive tail-call does not increase
-- the stack so we only need to check once. But it may grow the heap, so we
-- have to repeat the heap check in every self-call. This is done in
-- do_checks in StgCmmHeap.
--
-- * When we begin compilation of another closure we remove the additional
-- information from the environment. This is done by forkClosureBody
-- in StgCmmMonad. Other functions that duplicate the environment -
-- forkLneBody, forkAlts, codeOnly - duplicate that information. In other
-- words, we only need to clean the environment of the self-loop information
-- when compiling right hand side of a closure (binding).
--
-- * When compiling a call (cgIdApp) we use getCallMethod to decide what kind
-- of call will be generated. getCallMethod decides to generate a self
-- recursive tail call when (a) environment stores information about
-- possible self tail-call; (b) that tail call is to a function currently
-- being compiled; (c) number of passed arguments is equal to function's
-- arity. (d) loopification is turned on via -floopification command-line
-- option.
--
-- * Command line option to turn loopification on and off is implemented in
-- DynFlags.
--
emitEnter :: CmmExpr -> FCode ReturnKind
emitEnter fun = do
{ dflags <- getDynFlags
; adjustHpBackwards
; sequel <- getSequel
; updfr_off <- getUpdFrameOff
; case sequel of
-- For a return, we have the option of generating a tag-test or
-- not. If the value is tagged, we can return directly, which
-- is quicker than entering the value. This is a code
-- size/speed trade-off: when optimising for speed rather than
-- size we could generate the tag test.
--
-- Right now, we do what the old codegen did, and omit the tag
-- test, just generating an enter.
Return _ -> do
{ let entry = entryCode dflags $ closureInfoPtr dflags $ CmmReg nodeReg
; emit $ mkJump dflags NativeNodeCall entry
[cmmUntag dflags fun] updfr_off
; return AssignedDirectly
}
-- The result will be scrutinised in the sequel. This is where
-- we generate a tag-test to avoid entering the closure if
-- possible.
--
-- The generated code will be something like this:
--
-- R1 = fun -- copyout
-- if (fun & 7 != 0) goto Lcall else goto Lret
-- Lcall:
-- call [fun] returns to Lret
-- Lret:
-- fun' = R1 -- copyin
-- ...
--
-- Note in particular that the label Lret is used as a
-- destination by both the tag-test and the call. This is
-- becase Lret will necessarily be a proc-point, and we want to
-- ensure that we generate only one proc-point for this
-- sequence.
--
-- Furthermore, we tell the caller that we generated a native
-- return continuation by returning (ReturnedTo Lret off), so
-- that the continuation can be reused by the heap-check failure
-- code in the enclosing case expression.
--
AssignTo res_regs _ -> do
{ lret <- newLabelC
; let (off, _, copyin) = copyInOflow dflags NativeReturn (Young lret) res_regs []
; lcall <- newLabelC
; updfr_off <- getUpdFrameOff
; let area = Young lret
; let (outArgs, regs, copyout) = copyOutOflow dflags NativeNodeCall Call area
[fun] updfr_off []
-- refer to fun via nodeReg after the copyout, to avoid having
-- both live simultaneously; this sometimes enables fun to be
-- inlined in the RHS of the R1 assignment.
; let entry = entryCode dflags (closureInfoPtr dflags (CmmReg nodeReg))
the_call = toCall entry (Just lret) updfr_off off outArgs regs
; tscope <- getTickScope
; emit $
copyout <*>
mkCbranch (cmmIsTagged dflags (CmmReg nodeReg)) lret lcall <*>
outOfLine lcall (the_call,tscope) <*>
mkLabel lret tscope <*>
copyin
; return (ReturnedTo lret off)
}
}
------------------------------------------------------------------------
-- Ticks
------------------------------------------------------------------------
-- | Generate Cmm code for a tick. Depending on the type of Tickish,
-- this will either generate actual Cmm instrumentation code, or
-- simply pass on the annotation as a @CmmTickish@.
cgTick :: Tickish Id -> FCode ()
cgTick tick
= do { dflags <- getDynFlags
; case tick of
ProfNote cc t p -> emitSetCCC cc t p
HpcTick m n -> emit (mkTickBox dflags m n)
SourceNote s n -> emitTick $ SourceNote s n
_other -> return () -- ignore
}
|
urbanslug/ghc
|
compiler/codeGen/StgCmmExpr.hs
|
bsd-3-clause
| 33,142
| 8
| 20
| 8,862
| 4,814
| 2,536
| 2,278
| -1
| -1
|
-- !!! Recursive newtypes
-- Needs -O
-- This one made GHC < 5.00.2 go into an
-- infinite loop in the strictness analysier
module Foo where
newtype V = MkV V
f :: V -> V
f (MkV v) = v
|
urbanslug/ghc
|
testsuite/tests/stranal/should_compile/str002.hs
|
bsd-3-clause
| 191
| 0
| 7
| 48
| 39
| 24
| 15
| 4
| 1
|
import Control.Concurrent
import Control.Monad
import GHC.Conc
main = do
mainTid <- myThreadId
labelThread mainTid "main"
forM_ [0..0] $ \i -> forkIO $ do
subTid <- myThreadId
labelThread subTid $ "sub " ++ show i
forM_ [0..100000000] $ \j -> putStrLn $ "sub " ++ show i ++ ": " ++ show j
yield
setNumCapabilities 2
|
urbanslug/ghc
|
testsuite/tests/rts/T8209.hs
|
bsd-3-clause
| 339
| 0
| 17
| 78
| 135
| 63
| 72
| 12
| 1
|
import Control.Applicative
import Control.Arrow
import Control.Monad
import qualified Data.List as List
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
{-| One dimension by which the board can be covered -}
data Dimension = DRow -- horizontal row
| DCol -- vertical col
| DAsc -- L->R, B->T
| DDsc -- L->R, T->B
deriving (Eq, Ord)
{-| A "Covered" area of hte board into which no Queen should be placed.
Each queen covers a row, column, ascender, and descender - represented by the dimension and a
number (row number, column number, etc).
-}
data Covered = Covered Dimension Int deriving (Eq, Ord)
{-| A position on the board. Tiles are counted from 0 starting at the top-left, incrementing by 1
across (within a row) and then down (into a new row).
-}
newtype Position = Position Int deriving (Eq, Ord)
{-| A game board containing a set of placed queens and tracked data indicating what areas are covered.
-}
data Board = Board (Set Position) (Set Covered) deriving (Eq, Ord)
-- | Gives the width and height of a game board.
boardEdge :: Int
boardEdge = 8
instance Show Board where
show (Board positions _) =
let edgeIndices = [0 .. (boardEdge - 1)]
isSet col row = Set.member (positionAt col row) positions
boardInfo = [ [ isSet col row | col <- edgeIndices ] | row <- edgeIndices ]
showCell True = "X"
showCell False = "-"
showRow tiles = join (showCell <$> tiles)
in unlines (showRow <$> boardInfo)
-- | List of all possible positions on a board
allPositions :: [Position]
allPositions = Position <$> [ 0.. (boardEdge * boardEdge - 1)]
positionAt :: Int -> Int -> Position
positionAt col row = Position $ row * boardEdge + col
emptyBoard :: Board
emptyBoard = Board Set.empty Set.empty
isSolved :: Board -> Bool
isSolved (Board positions _) = length positions == boardEdge
{- | Gets the coverage a position has. Used to determine what row,col,asc,dsc will be occupied
if a queen is placed in the given position. -}
coveredBy :: Position -> [Covered]
coveredBy (Position tileIndex) =
[ Covered DDsc . uncurry (+)
, Covered DAsc . uncurry (-)
, Covered DRow . fst
, Covered DCol . snd ] <*> [rowcol]
where rowcol = tileIndex `divMod` boardEdge
{- | Attempt to take the given position. Fails (Nothing) if any Queen on the board already covers
the position. Returns the new Board (if possible) with new coverage state.
For performance reasons positions must be taken in increasing order. -}
takePosition :: Board -> Position -> Maybe Board
takePosition (Board positions covered) position
| any (`Set.member` covered) positionCovers = Nothing
| otherwise = Just $ Board combinedPositions combinedCovered
where positionCovers = coveredBy position
combinedPositions = Set.insert position positions
combinedCovered = foldr Set.insert covered positionCovers
-- | Solve the board by trying to take all given positions
solve :: [Position] -> Board -> [Board]
solve positionsToTry board
| isSolved board = [board]
| (position : remaining) <- positionsToTry
= let boardWithPos = maybeToList $ takePosition board position
in (board : boardWithPos) >>= solve remaining
| otherwise = []
-- | Find unique items from a (possilby large) list
unique :: (Ord a) => [a] -> [a]
unique = unique' Set.empty where
unique' :: (Ord a) => Set a -> [a] -> [a]
unique' _ [] = []
unique' previouslySeen (currentItem : xs)
| Set.member currentItem previouslySeen = unique' previouslySeen xs
| otherwise = currentItem : unique' previouslyAndCurrentSeen xs
where previouslyAndCurrentSeen = Set.insert currentItem previouslySeen
-- | Perform IO while iterating through a sequence
countIO :: (Monad m, Foldable t) => (Integer -> a -> m ()) -> t a -> m Integer
countIO f = foldr (\ value count -> do c <- count
f c value
return (c + 1)) (pure 0)
main :: IO ()
main =
countIO (\ count board -> do putStr "Solution "
print (count + 1)
print board
putStrLn "") (unique $ solve allPositions emptyBoard)
>> pure ()
|
jnonce/queens
|
queens.hs
|
mit
| 4,379
| 6
| 12
| 1,144
| 1,088
| 570
| 518
| 74
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Gather.Utils where
--import Data.ByteString as BS
import Data.Char as C
import Data.Text as T
import qualified Network.HTTP as NH
import System.Time
import Text.HTML.TagSoup
openURL :: String -> IO String
openURL x = do
response <- NH.simpleHTTP (NH.getRequest x)
response_body <- NH.getResponseBody response
return $ Prelude.map C.toLower response_body
getTitle :: [Tag String] -> T.Text
getTitle tags =
T.pack title_text
where
the_sections = sections (~== ("<title>" :: String)) tags
TagText title_text =
case Prelude.length the_sections of
0 -> TagText ("" :: String)
_ -> the_sections !! 0 !! 1
getTimeStamp :: IO Integer
getTimeStamp = getClockTime >>= \(TOD unix _) -> return unix
|
qpfiffer/gather
|
src/Gather/Utils.hs
|
mit
| 842
| 0
| 11
| 219
| 241
| 128
| 113
| 22
| 2
|
{-# LANGUAGE MonadComprehensions, RecordWildCards #-}
{-# OPTIONS_GHC -Wall #-}
module HW07 where
import Prelude hiding (mapM)
import HW07.Cards
import Control.Monad hiding (mapM, liftM)
import Control.Monad.Random
import Data.Functor
import Data.Function (on)
import Data.Monoid
import Data.Vector (Vector, cons, (!), (!?), (//))
import System.Random
import qualified Data.Vector as V
-- Exercise 1 -----------------------------------------
liftM :: Monad m => (a -> b) -> m a -> m b
liftM f v = v >>= return . f
swapV :: Int -> Int -> Vector a -> Maybe (Vector a)
swapV i1 i2 v = (liftM2 (\e1 e2 -> v // [(i1, e2), (i2, e1)]) `on` (v !?)) i1 i2
-- Exercise 2 -----------------------------------------
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
mapM f = foldr (\a b -> ((:) <$> f a <*> b)) (return [])
getElts :: [Int] -> Vector a -> Maybe [a]
getElts l v = mapM (v !?) l
-- Exercise 3 -----------------------------------------
type Rnd a = Rand StdGen a
randomElt :: Vector a -> Rnd (Maybe a)
randomElt v = getRandomR (0, length v) >>= return . (v !?)
-- Exercise 4 -----------------------------------------
randomVec :: Random a => Int -> Rnd (Vector a)
randomVec len = replicateM len getRandom >>= return . V.fromList
randomVecR :: Random a => Int -> (a, a) -> Rnd (Vector a)
randomVecR len (lo, hi) = replicateM len (getRandomR (lo, hi)) >>= return . V.fromList
-- Exercise 5 -----------------------------------------
shuffle :: Vector a -> Rnd (Vector a)
shuffle v = go (length v - 1) v
where go 0 acc = return acc
go n acc = getRandomR (0, n) >>= go (n-1) . swapUnsafe acc n
swapUnsafe vec i1 i2 = vec // [(i1, vec ! i2), (i2, vec ! i1)]
-- Exercise 6 -----------------------------------------
partitionAt :: Ord a => Vector a -> Int -> (Vector a, a, Vector a)
partitionAt v idx = ( V.filter (< pivot) vec, pivot, V.filter (>= pivot) vec)
where pivot = v ! idx
vec = V.take idx v V.++ V.drop (idx+1) v
-- Exercise 7 -----------------------------------------
-- Quicksort
quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = quicksort [ y | y <- xs, y < x ]
<> (x : quicksort [ y | y <- xs, y >= x ])
qsort :: Ord a => Vector a -> Vector a
qsort v | V.null v = v
| otherwise = let (smaller, pivot, larger) = partitionAt v 0
in qsort smaller V.++ cons pivot (qsort larger)
-- Exercise 8 -----------------------------------------
qsortR :: Ord a => Vector a -> Rnd (Vector a)
qsortR v | V.null v = return v
| otherwise = getRandomR (0, length v - 1) >>= recurse . partitionAt v
where recurse (smaller, pivot, larger) = (V.++) <$> qsortR smaller <*> (cons <$> pure pivot <*> (qsortR larger))
-- Exercise 9 -----------------------------------------
-- Selection
select :: Ord a => Int -> Vector a -> Rnd (Maybe a)
select rank v | V.null v = return Nothing
| otherwise = do
randomIndex <- getRandomR (0, length v - 1)
let (smaller, pivot, larger) = v `partitionAt` randomIndex
lengthSmaller = length smaller
if rank < lengthSmaller
then select rank smaller
else if rank > lengthSmaller
then select (rank - lengthSmaller - 1) larger
else return $ Just pivot
-- Exercise 10 ----------------------------------------
allCards :: Deck
allCards = [Card label suit | suit <- suits, label <- labels]
newDeck :: Rnd Deck
newDeck = shuffle allCards
-- Exercise 11 ----------------------------------------
nextCard :: Deck -> Maybe (Card, Deck)
nextCard deck | V.null deck = Nothing
| otherwise = Just (V.head deck, V.tail deck)
-- Exercise 12 ----------------------------------------
getCards :: Int -> Deck -> Maybe ([Card], Deck)
getCards n deck | n == 0 = Just ([], deck)
| otherwise = do
(card, remaining) <- nextCard deck
(cards, remainingDeck) <- getCards (n-1) remaining
return $ (card : cards, remainingDeck)
-- Exercise 13 ----------------------------------------
data State = State { money :: Int, deck :: Deck }
repl :: State -> IO ()
repl s@State{..} | money <= 0 = putStrLn "You ran out of money!"
| V.null deck = deckEmpty
| otherwise = do
putStrLn $ "You have \ESC[32m$" ++ show money ++ "\ESC[0m"
putStrLn "Would you like to play (y/n)?"
cont <- getLine
if cont == "n"
then putStrLn $ "You left the casino with \ESC[32m$"
++ show money ++ "\ESC[0m"
else play
where deckEmpty = putStrLn $ "The deck is empty. You got \ESC[32m$"
++ show money ++ "\ESC[0m"
play = do
putStrLn "How much do you want to bet?"
amt <- read <$> getLine
if amt < 1 || amt > money
then play
else do
case getCards 2 deck of
Just ([c1, c2], d) -> do
putStrLn $ "You got:\n" ++ show c1
putStrLn $ "I got:\n" ++ show c2
case () of
_ | c1 > c2 -> repl $ State (money + amt) d
| c1 < c2 -> repl $ State (money - amt) d
| otherwise -> war s{deck = d} amt
_ -> deckEmpty
war (State m d) amt = do
putStrLn "War!"
case getCards 6 d of
Just ([c11, c21, c12, c22, c13, c23], d') -> do
putStrLn $ "You got\n" ++ ([c11, c12, c13] >>= show)
putStrLn $ "I got\n" ++ ([c21, c22, c23] >>= show)
case () of
_ | c13 > c23 -> repl $ State (m + amt) d'
| c13 < c23 -> repl $ State (m - amt) d'
| otherwise -> war (State m d') amt
_ -> deckEmpty
|
mrordinaire/upenn-haskell
|
src/HW07.hs
|
mit
| 5,731
| 0
| 24
| 1,639
| 2,197
| 1,128
| 1,069
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.Binding
-- License : MIT (see the LICENSE file)
-- Maintainer : Felix Klein (klein@react.uni-saarland.de)
--
-- A data type to store an identifier bound to an expression.
--
-----------------------------------------------------------------------------
module Data.Binding
( Binding
, BindExpr(..)
) where
-----------------------------------------------------------------------------
import Data.Expression
( Expr
, ExprPos
)
-----------------------------------------------------------------------------
-- | We use the type @Binding@ as a shortcut for a binding of an expression
-- to an integer.
type Binding = BindExpr Int
-----------------------------------------------------------------------------
-- | The data type @Bind a@ expresses a binding of some instance of type
-- @a@ to some expression. The identifiers inside this expression need to
-- be represented by instances of type @a@ as well. Finally, a binding also
-- containts the source position of the bound identifier as well as possible
-- arguments in case the bindings represents a function.
data BindExpr a =
BindExpr
{ bIdent :: a
, bArgs :: [(a,ExprPos)]
, bPos :: ExprPos
, bVal :: [Expr a]
} deriving (Show)
-----------------------------------------------------------------------------
|
reactive-systems/syfco
|
src/lib/Data/Binding.hs
|
mit
| 1,418
| 0
| 10
| 227
| 116
| 80
| 36
| 14
| 0
|
-- Type arithmetic
-- ref: https://wiki.haskell.org/Type_arithmetic
-- oleg: http://article.gmane.org/gmane.comp.lang.haskell.general/13223
-- ref: https://wiki.haskell.org/Typeful_symbolic_differentiation
-- oleg: https://mail.haskell.org/pipermail/haskell/2004-November/014939.html
-- Type arithmetic (or type-level computation) are calculations on the type-level, often implemented in Haskell using functional dependencies to represent functions.
-- type-level quick-sort
module Sort where
-- natural numbers
data Zero
data Succ a
-- booleans
data True
data False
-- lists
data Nil
data Cons a b
-- shortcuts
type One = Succ Zero
type Two = Succ One
type Three = Succ Two
type Four = Succ Three
-- example list
list1 :: Cons Three (Cons Two (Cons Four (Cons One Nil)))
list1 = undefined
-- utilities
numPred :: Succ a -> a
numPred = const undefined
class Number a where
numValue :: a -> Int
instance Number Zero where
numValue = const 0
instance Number x => Number (Succ x) where
numValue x = numValue (numPred x) + 1
numlHead :: Cons a b -> a
numlHead = const undefined
numlTail :: Cons a b -> b
numlTail = const undefined
class NumList l where
listValue :: l -> [Int]
instance NumList Nil where
listValue = const []
instance (Number x, NumList xs) => NumList (Cons x xs) where
listValue l = numValue (numlHead l) : listValue (numlTail l)
-- comparisons
data Less
data Equal
data Greater
class Cmp x y c | x y -> c
instance Cmp Zero Zero Equal
instance Cmp Zero (Succ x) Less
instance Cmp (Succ x) Zero Greater
instance Cmp x y c => Cmp (Succ x) (Succ y) c
-- put a value into one of three lists according to a pivot element
class Pick c x ls eqs gs ls' eqs' gs' | c x ls eqs gs -> ls' eqs' gs'
instance Pick Less x ls eqs gs (Cons x ls) eqs gs
instance Pick Equal x ls eqs gs ls (Cons x eqs) gs
instance Pick Greater x ls eqs gs ls eqs (Cons x gs)
-- split a list into three parts according to a pivot element
class Split n xs ls eqs gs | n xs -> ls eqs gs
instance Split n Nil Nil Nil Nil
instance (Split n xs ls' eqs' gs',
Cmp x n c,
Pick c x ls' eqs' gs' ls eqs gs) =>
Split n (Cons x xs) ls eqs gs
listSplit :: Split n xs ls eqs gs => (n, xs) -> (ls, eqs, gs)
listSplit = const (undefined, undefined, undefined)
-- zs = xs ++ ys
class App xs ys zs | xs ys -> zs
instance App Nil ys ys
instance App xs ys zs => App (Cons x xs) ys (Cons x zs)
-- zs = xs ++ [n] ++ ys
-- this is needed because
--
-- class CCons x xs xss | x xs -> xss
-- instance CCons x xs (Cons x xs)
--
-- doesn't work
class App' xs n ys zs | xs n ys -> zs
instance App' Nil n ys (Cons n ys)
instance (App' xs n ys zs) => App' (Cons x xs) n ys (Cons x zs)
-- quicksort
class QSort xs ys | xs -> ys
instance QSort Nil Nil
instance (Split x xs ls eqs gs,
QSort ls ls',
QSort gs gs',
App eqs gs' geqs,
App' ls' x geqs ys) =>
QSort (Cons x xs) ys
listQSort :: QSort xs ys => xs -> ys
listQSort = const undefined
-- type-level lambda calculus
{-# OPTIONS -fglasgow-exts #-}
data X
data App t u
data Lam t
class Subst s t u | s t -> u
instance Subst X u u
instance (Subst s u s', Subst t u t') => Subst (App s t) u (App s' t')
instance Subst (Lam t) u (Lam t)
class Apply s t u | s t -> u
instance (Subst s t u, Eval u u') => Apply (Lam s) t u'
class Eval t u | t -> u
instance Eval X X
instance Eval (Lam t) (Lam t)
instance (Eval s s', Apply s' t u) => Eval (App s t) u
{-
Now, lets evaluate some lambda expressions:
> :t undefined :: Eval (App (Lam X) X) u => u
undefined :: Eval (App (Lam X) X) u => u :: X
Ok good, and:
> :t undefined :: Eval (App (Lam (App X X)) (Lam (App X X)) ) u => u
^CInterrupted.
-}
-- It's possible to embed the Turing-complete SK combinator calculus at the type level.
-- Typeful symbolic differentiation
-- "A `symbolic' differentiator for a subset of Haskell functions (which covers arithmetics and a bit of trigonometry). We can evaluate our functions _numerically_ -- and differentiate them _symbolically_. Partial derivatives are supported as well."
|
Airtnp/Freshman_Simple_Haskell_Lib
|
Idioms/Type-arithmetic.hs
|
mit
| 4,063
| 0
| 11
| 898
| 1,290
| 679
| 611
| -1
| -1
|
module Flight where
import Text.Regex.PCRE
import qualified Data.Map.Strict as Map
import Control.Monad.Trans.RWS.Strict
import Control.Monad (replicateM_, forM_)
import Data.List (maximumBy)
import Data.Ord (comparing)
type Reindeer = String
data Constraint = Constraint
{ name :: Reindeer
, kmPerSec :: Int
, fliesFor :: Int
, mustRest :: Int
} deriving (Show, Eq)
type Score = Int
data Distance = Distance
{ distance :: Int
, flightTimeLeft :: Int
, restTimeLeft :: Int
, score :: Score
} deriving (Show, Eq)
type Distances = Map.Map String Distance
type Race = RWS [Constraint] () Distances ()
constraintRegex = "(\\w+) can fly (\\d+) km/s for (\\d+) seconds, but then must rest for (\\d+) seconds."
parseConstraint :: String -> Constraint
parseConstraint l =
let [_, s, k, f, m] = getAllTextSubmatches (l =~ constraintRegex :: (AllTextSubmatches [] String))
in Constraint s (read k) (read f) (read m)
resetTime :: Constraint -> Distance -> Distance
resetTime c d = d { flightTimeLeft = fliesFor c
, restTimeLeft = mustRest c }
mtDistance = Distance 0 0 0 0
starting :: [Constraint] -> Distances
starting constraints = Map.fromList [(name x, f x) | x <- constraints]
where f c = resetTime c mtDistance
step :: Race
step = do
constraints <- ask
forM_ constraints $ \c ->
modify (Map.adjust (step1 c) (name c))
dists <- get
let maxDist = distance . maximumBy (comparing distance) $ Map.elems dists
let winners = Map.keys $ Map.filter (\x -> distance x == maxDist) dists
forM_ winners $ \winner ->
modify (Map.adjust (\x -> x { score = score x + 1}) winner)
step1 :: Constraint -> Distance -> Distance
step1 c d
| restTimeLeft d < 0 || flightTimeLeft d < 0 = error "Should not become negative"
| restTimeLeft d == 1 = resetTime c d
| flightTimeLeft d == 0 = d { restTimeLeft = restTimeLeft d - 1}
| otherwise = d { flightTimeLeft = flightTimeLeft d - 1
, distance = distance d + kmPerSec c }
race :: Int -> [Constraint] -> Distances
race seconds constraints =
let startState = starting constraints
in fst $ execRWS (replicateM_ seconds step) constraints startState
maxDistance :: Int -> [Constraint] -> Int
maxDistance i c = maximum . map distance . Map.elems $ race i c
maxScore :: Int -> [Constraint] -> Int
maxScore i c = maximum . map score . Map.elems $ race i c
|
corajr/adventofcode2015
|
14/Flight.hs
|
mit
| 2,475
| 0
| 17
| 602
| 894
| 468
| 426
| 60
| 1
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGRenderingIntent
(pattern RENDERING_INTENT_UNKNOWN, pattern RENDERING_INTENT_AUTO,
pattern RENDERING_INTENT_PERCEPTUAL,
pattern RENDERING_INTENT_RELATIVE_COLORIMETRIC,
pattern RENDERING_INTENT_SATURATION,
pattern RENDERING_INTENT_ABSOLUTE_COLORIMETRIC, SVGRenderingIntent,
castToSVGRenderingIntent, gTypeSVGRenderingIntent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
pattern RENDERING_INTENT_UNKNOWN = 0
pattern RENDERING_INTENT_AUTO = 1
pattern RENDERING_INTENT_PERCEPTUAL = 2
pattern RENDERING_INTENT_RELATIVE_COLORIMETRIC = 3
pattern RENDERING_INTENT_SATURATION = 4
pattern RENDERING_INTENT_ABSOLUTE_COLORIMETRIC = 5
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/SVGRenderingIntent.hs
|
mit
| 1,486
| 0
| 6
| 170
| 361
| 231
| 130
| 28
| 0
|
{-@ LIQUID "--no-termination" @-}
{-@ measure len @-}
len :: BTree a -> Int
len m =
case m of
Nil -> 1
Branch t1 _ t2 -> 1 + len t1 + len t2
data BTree a = Nil | Branch (BTree a) a (BTree a) deriving Eq
mapBTree :: (a -> a) -> BTree a -> BTree a
mapBTree f Nil = Nil
mapBTree f (Branch b1 v b2) = Branch (mapBTree f b1) (f v) (mapBTree f b2)
exs :: [(BTree Bool, BTree Bool)]
exs = [
(Branch Nil True Nil,
Branch Nil True Nil)]
|
santolucito/ives
|
tests/btree.hs
|
mit
| 452
| 0
| 10
| 122
| 225
| 115
| 110
| 13
| 2
|
-- No explicit exports.
-- Typeclass instances are always exported?
module Ternary.List.ExactNum () where
import Ternary.Core.Digit (T2(..), negateT2)
import Ternary.List.Exact
import Ternary.Core.Multiplication (fineStructure)
negateDigits :: [T2] -> [T2]
negateDigits = map negateT2
absDigits :: [T2] -> [T2]
absDigits [] = []
absDigits (O0:as) = O0 : absDigits as
absDigits x@(P1:_) = x
absDigits x@(P2:_) = x
absDigits x = negateDigits x
instance Num Exact where
abs = unsafeApplyToDigits absDigits
signum = error "Exact.signum is undefined"
negate = unsafeApplyToDigits negateDigits
fromInteger = integerToExact
(+) = addExact
(*) = multiplyExact fineStructure
|
jeroennoels/exact-real
|
src/Ternary/List/ExactNum.hs
|
mit
| 687
| 0
| 8
| 110
| 220
| 126
| 94
| 19
| 1
|
{-# LANGUAGE FlexibleInstances -- needed for instance
-- Replacement [Either Int String]
-- else
{- Illegal instance declaration for `Replacement [Either Int String]'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Replacement ([Either Int String])'
-}
#-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Description : high-level functions for working with perl-compatible regular
expressions
Copyright : (c) Martyn J. Pearce 2014, 2015
License : BSD
Maintainer : haskell@sixears.com
high-level functions for working with perl-compatible regular expressions
-}
module Fluffy.Text.PCRE
( Replacement(..), subst, substg )
where
-- base --------------------------------
import Data.Char ( isNumber )
-- array -------------------------------
import Data.Array ( elems )
-- regex-pcre --------------------------
import Text.Regex.PCRE ( (=~), mrAfter, mrBefore, mrSubs )
-- Replacement -----------------------------------------------------------------
{- | like Perl's s///; perform patten substition.
e.g., "^Type.readType \"(.*)\" \"(.*)\" :: \\1" `subst` "$2 $1"
$ "Type.readType \"Double\" \"1.1\" :: Double"
--> "1.1 Double"
The substitution string, as shown, may include $nn where $nn is an integer
$0 will give back the whole outer match.
Note that use of a capture group reference that doesn't exist in the regex
will cause a runtime exception. However, an optional group that doesn't
match (i.e., something appended with a '?') will just give an empty string.
e.g., "readType \"(.*)\" (?:\"(y.*)\")?.* :: \\1" `subst` "[$2]"
$ "Type.readType \"Double\" \"x\" :: Double"
--> "[]"
-}
class Replacement a where
replacement :: a -> [Either Int String]
instance Replacement [Either Int String] where
replacement = id
_rplc :: String -> [Either Int String]
_rplc xs = let (ys, zs) = break (`elem` "\\$") (tail xs)
in Right (head xs : ys) : replacement zs
instance Replacement String where
replacement [] = []
replacement ('\\' : i : xs) = _rplc (i : xs)
replacement ('$' : i : xs) | isNumber i =
let (is, ys) = span isNumber xs
in Left (read (i : is)) : replacement ys
replacement xs = _rplc xs
-- subst -----------------------------------------------------------------------
-- | perl's s/// in Haskell; no /g modifier, so replace only the first instance
-- of the regex found
subst :: Replacement r
=> String -- ^ the match regex
-> r -- ^ the replacement for matched strings
-> String -- ^ the string to match/replace against
-> String
subst match replace as =
let res = as =~ match
in case elems (mrSubs res) :: [String] of
[] -> as
grps -> concat [ mrBefore res
, replacement replace >>= \ r -> case r of
Left i -> grps !! i
Right s -> s
, mrAfter res
]
-- substg ----------------------------------------------------------------------
-- | like subst, but with Perl's /g modifier - i.e., replace every found
-- instance of the match regex
substg :: Replacement r => String -> r -> String -> String
substg match replace as =
let res = as =~ match
in case elems (mrSubs res) :: [String] of
[] -> as
grps -> concat [ mrBefore res
, replacement replace >>= \ r -> case r of
Left i -> grps !! i
Right s -> s
, substg match replace (mrAfter res)
]
|
sixears/fluffy
|
src/Fluffy/Text/PCRE.hs
|
mit
| 4,062
| 0
| 17
| 1,261
| 632
| 332
| 300
| 45
| 3
|
module System.AtomicWrite.Writer.LazyByteStringSpec (spec) where
import Test.Hspec (it, describe, shouldBe, Spec)
import System.AtomicWrite.Writer.LazyByteString (atomicWriteFile, atomicWriteFileWithMode)
import System.IO.Temp (withSystemTempDirectory)
import System.FilePath.Posix (joinPath)
import System.PosixCompat.Files
(setFileMode, setFileCreationMask, getFileStatus, fileMode)
import Data.ByteString.Lazy.Char8 (pack)
spec :: Spec
spec = do
describe "atomicWriteFile" $ do
it "writes contents to a file" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let path = joinPath [ tmpDir, "writeTest.tmp" ]
atomicWriteFile path $ pack "just testing"
contents <- readFile path
contents `shouldBe` "just testing"
it "preserves the permissions of original file, regardless of umask" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let filePath = joinPath [tmpDir, "testFile"]
writeFile filePath "initial contents"
setFileMode filePath 0o100644
newStat <- getFileStatus filePath
fileMode newStat `shouldBe` 0o100644
-- New files are created with 100600 perms.
_ <- setFileCreationMask 0o100066
-- Create a new file once different mask is set and make sure that mask
-- is applied.
writeFile (joinPath [tmpDir, "sanityCheck"]) "with sanity check mask"
sanityCheckStat <- getFileStatus $ joinPath [tmpDir, "sanityCheck"]
fileMode sanityCheckStat `shouldBe` 0o100600
-- Since we move, this makes the new file assume the filemask of 0600
atomicWriteFile filePath $ pack "new contents"
resultStat <- getFileStatus filePath
-- reset mask to not break subsequent specs
_ <- setFileCreationMask 0o100022
-- Fails when using atomic mv command unless apply perms on initial file
fileMode resultStat `shouldBe` 0o100644
it "creates a new file with permissions based on active umask" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let
filePath = joinPath [tmpDir, "testFile"]
sampleFilePath = joinPath [tmpDir, "sampleFile"]
-- Set somewhat distinctive defaults for test
_ <- setFileCreationMask 0o100171
-- We don't know what the default file permissions are, so create a
-- file to sample them.
writeFile sampleFilePath "I'm being written to sample permissions"
newStat <- getFileStatus sampleFilePath
fileMode newStat `shouldBe` 0o100606
atomicWriteFile filePath $ pack "new contents"
resultStat <- getFileStatus filePath
-- reset mask to not break subsequent specs
_ <- setFileCreationMask 0o100022
-- The default tempfile permissions are 0600, so this fails unless we
-- make sure that the default umask is relied on for creation of the
-- tempfile.
fileMode resultStat `shouldBe` 0o100606
describe "atomicWriteFileWithMode" $ do
it "writes contents to a file" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let path = joinPath [ tmpDir, "writeTest.tmp" ]
atomicWriteFileWithMode 0o100777 path $ pack "just testing"
contents <- readFile path
contents `shouldBe` "just testing"
it "changes the permissions of a previously created file, regardless of umask" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let filePath = joinPath [tmpDir, "testFile"]
writeFile filePath "initial contents"
setFileMode filePath 0o100644
newStat <- getFileStatus filePath
fileMode newStat `shouldBe` 0o100644
-- New files are created with 100600 perms.
_ <- setFileCreationMask 0o100066
-- Create a new file once different mask is set and make sure that mask
-- is applied.
writeFile (joinPath [tmpDir, "sanityCheck"]) "with sanity check mask"
sanityCheckStat <- getFileStatus $ joinPath [tmpDir, "sanityCheck"]
fileMode sanityCheckStat `shouldBe` 0o100600
-- Since we move, this makes the new file assume the filemask of 0600
atomicWriteFileWithMode 0o100655 filePath $ pack "new contents"
resultStat <- getFileStatus filePath
-- reset mask to not break subsequent specs
_ <- setFileCreationMask 0o100022
-- Fails when using atomic mv command unless apply perms on initial file
fileMode resultStat `shouldBe` 0o100655
it "creates a new file with specified permissions" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let
filePath = joinPath [tmpDir, "testFile"]
atomicWriteFileWithMode 0o100606 filePath $ pack "new contents"
resultStat <- getFileStatus filePath
fileMode resultStat `shouldBe` 0o100606
|
stackbuilders/atomic-write
|
spec/System/AtomicWrite/Writer/LazyByteStringSpec.hs
|
mit
| 4,920
| 0
| 18
| 1,240
| 884
| 433
| 451
| 74
| 1
|
-- Copyright © 2013 Julian Blake Kongslie <jblake@jblake.org>
-- Licensed under the MIT license.
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -Wall -Werror -fno-warn-type-defaults #-}
-- |Here we define the actual opcodes allowed in our assembly language.
-- There's no particularly compact way to do this, so we essentially have three big lists, one for each arity of opcode.
-- Opcode names are always expressed as lowercase strings.
-- You don't need to worry about reference or math operands; those will always be replaced by Abs by the time functions here are called.
module Language.GBAsm.Opcodes
( Opcode(..)
)
where
import Data.Bits
import Data.ByteString.Lazy as BS
import Prelude as P
import Language.GBAsm.Types
-- |This is just a helper to make things a little simpler.
bs :: (Integral n) => [n] -> Maybe ByteString
bs = Just . pack . P.map fromIntegral
-- |Another helper for single-byte opcodes.
b :: (Integral n) => n -> Maybe ByteString
b = bs . (: [])
-- |Opcodes are compiled using this class, just to allow a single entry point for nullary, unary, and binary opcodes.
class Opcode f where
opc :: String -> f
-- |Nullary opcodes.
instance Opcode (Maybe ByteString) where
opc "nop" = b 0x00
opc "stop" = b 0x10
opc "daa" = b 0x27
opc "cpl" = b 0x2f
opc "scf" = b 0x37
opc "ccf" = b 0x3f
opc "halt" = b 0x76
opc "ret" = b 0xc9
opc "reti" = b 0xd9
opc "di" = b 0xf3
opc "ei" = b 0xfb
opc _ = Nothing
-- |Unary opcodes.
instance Opcode (Operand -> Maybe ByteString) where
opc "inc" BC = b 0x03
opc "inc" B = b 0x04
opc "dec" B = b 0x05
opc "rlc" A = b 0x07
opc "dec" BC = b 0x0b
opc "inc" C = b 0x0c
opc "dec" C = b 0x0d
opc "rrc" A = b 0x0f
opc "inc" DE = b 0x13
opc "inc" D = b 0x14
opc "dec" D = b 0x15
opc "rl" A = b 0x17
opc "jr" (Abs n) = bs [0x18, n]
opc "dec" DE = b 0x1b
opc "inc" E = b 0x1c
opc "dec" E = b 0x1d
opc "rr" A = b 0x1f
opc "inc" HL = b 0x23
opc "inc" H = b 0x24
opc "dec" H = b 0x25
opc "dec" HL = b 0x2b
opc "inc" L = b 0x2c
opc "dec" L = b 0x2d
opc "inc" SP = b 0x33
opc "inc" (Ind HL) = b 0x34
opc "dec" (Ind HL) = b 0x35
opc "dec" SP = b 0x3b
opc "inc" A = b 0x3c
opc "dec" A = b 0x3d
opc "ret" NZ = b 0xc0
opc "pop" BC = b 0xc1
opc "jp" (Abs n) = bs [0xc3, n, n `shiftR` 8]
opc "push" BC = b 0xc5
opc "rst" (Abs 0x00) = b 0xc7
opc "ret" Z = b 0xc8
opc "call" (Abs n) = bs [0xcd, n, n `shiftR` 8]
opc "rst" (Abs 0x08) = b 0xcf
opc "ret" NC = b 0xd0
opc "pop" DE = b 0xd1
opc "push" DE = b 0xd5
opc "rst" (Abs 0x10) = b 0xd7
opc "ret" C = b 0xd8
opc "rst" (Abs 0x18) = b 0xdf
opc "pop" HL = b 0xe1
opc "push" HL = b 0xe5
opc "rst" (Abs 0x20) = b 0xe7
opc "jp" (Ind HL) = b 0xe9
opc "rst" (Abs 0x28) = b 0xef
opc "pop" AF = b 0xf1
opc "push" AF = b 0xf5
opc "rst" (Abs 0x30) = b 0xf7
opc "cp" (Abs n) = bs [0xfe, n]
opc "rst" (Abs 0x38) = b 0xff
opc "rlc" B = bs [0xcb, 0x00]
opc "rlc" C = bs [0xcb, 0x01]
opc "rlc" D = bs [0xcb, 0x02]
opc "rlc" E = bs [0xcb, 0x03]
opc "rlc" H = bs [0xcb, 0x04]
opc "rlc" L = bs [0xcb, 0x05]
opc "rlc" (Ind HL) = bs [0xcb, 0x06]
-- opc "rlc" A = bs [0xcb, 0x07]
opc "rrc" B = bs [0xcb, 0x08]
opc "rrc" C = bs [0xcb, 0x09]
opc "rrc" D = bs [0xcb, 0x0a]
opc "rrc" E = bs [0xcb, 0x0b]
opc "rrc" H = bs [0xcb, 0x0c]
opc "rrc" L = bs [0xcb, 0x0d]
opc "rrc" (Ind HL) = bs [0xcb, 0x0e]
-- opc "rrc" A = bs [0xcb, 0x0f]
opc "rl" B = bs [0xcb, 0x10]
opc "rl" C = bs [0xcb, 0x11]
opc "rl" D = bs [0xcb, 0x12]
opc "rl" E = bs [0xcb, 0x13]
opc "rl" H = bs [0xcb, 0x14]
opc "rl" L = bs [0xcb, 0x15]
opc "rl" (Ind HL) = bs [0xcb, 0x16]
-- opc "rl" A = bs [0xcb, 0x17]
opc "rr" B = bs [0xcb, 0x18]
opc "rr" C = bs [0xcb, 0x19]
opc "rr" D = bs [0xcb, 0x1a]
opc "rr" E = bs [0xcb, 0x1b]
opc "rr" H = bs [0xcb, 0x1c]
opc "rr" L = bs [0xcb, 0x1d]
opc "rr" (Ind HL) = bs [0xcb, 0x1e]
-- opc "rr" A = bs [0xcb, 0x1f]
opc "sla" B = bs [0xcb, 0x20]
opc "sla" C = bs [0xcb, 0x21]
opc "sla" D = bs [0xcb, 0x22]
opc "sla" E = bs [0xcb, 0x23]
opc "sla" H = bs [0xcb, 0x24]
opc "sla" L = bs [0xcb, 0x25]
opc "sla" (Ind HL) = bs [0xcb, 0x26]
opc "sla" A = bs [0xcb, 0x27]
opc "sra" B = bs [0xcb, 0x28]
opc "sra" C = bs [0xcb, 0x29]
opc "sra" D = bs [0xcb, 0x2a]
opc "sra" E = bs [0xcb, 0x2b]
opc "sra" H = bs [0xcb, 0x2c]
opc "sra" L = bs [0xcb, 0x2d]
opc "sra" (Ind HL) = bs [0xcb, 0x2e]
opc "sra" A = bs [0xcb, 0x2f]
opc "swap" B = bs [0xcb, 0x30]
opc "swap" C = bs [0xcb, 0x31]
opc "swap" D = bs [0xcb, 0x32]
opc "swap" E = bs [0xcb, 0x33]
opc "swap" H = bs [0xcb, 0x34]
opc "swap" L = bs [0xcb, 0x35]
opc "swap" (Ind HL) = bs [0xcb, 0x36]
opc "swap" A = bs [0xcb, 0x37]
opc "srl" B = bs [0xcb, 0x38]
opc "srl" C = bs [0xcb, 0x39]
opc "srl" D = bs [0xcb, 0x3a]
opc "srl" E = bs [0xcb, 0x3b]
opc "srl" H = bs [0xcb, 0x3c]
opc "srl" L = bs [0xcb, 0x3d]
opc "srl" (Ind HL) = bs [0xcb, 0x3e]
opc "srl" A = bs [0xcb, 0x3f]
opc _ _ = Nothing
-- |Binary opcodes.
instance Opcode (Operand -> Operand -> Maybe ByteString) where
opc "ld" BC (Abs n) = bs [0x01, n, n `shiftR` 8]
opc "ld" (Ind BC) A = b 0x02
opc "ld" B (Abs n) = bs [0x06, n]
opc "ld" (Ind (Abs n)) SP = bs [0x08, n, n `shiftR` 8]
opc "add" HL BC = b 0x09
opc "ld" A (Ind BC) = b 0x0a
opc "ld" C (Abs n) = bs [0x0e, n]
opc "ld" DE (Abs n) = bs [0x11, n, n `shiftR` 8]
opc "ld" (Ind DE) A = b 0x12
opc "ld" D (Abs n) = bs [0x16, n]
opc "add" HL DE = b 0x19
opc "ld" A (Ind DE) = b 0x1a
opc "ld" E (Abs n) = bs [0x1e, n]
opc "jr" NZ (Abs n) = bs [0x20, n]
opc "ld" HL (Abs n) = bs [0x21, n, n `shiftR` 8]
opc "ldi" (Ind HL) A = b 0x22
opc "ld" H (Abs n) = bs [0x26, n]
opc "jr" Z (Abs n) = bs [0x28, n]
opc "add" HL HL = b 0x29
opc "ldi" A (Ind HL) = b 0x2a
opc "ld" L (Abs n) = bs [0x2e, n]
opc "jr" NC (Abs n) = bs [0x30, n]
opc "ld" SP (Abs n) = bs [0x31, n, n `shiftR` 8]
opc "ldd" (Ind HL) A = b 0x32
opc "ld" (Ind HL) (Abs n) = bs [0x36, n]
opc "jr" C (Abs n) = bs [0x38, n]
opc "add" HL SP = b 0x39
opc "ldd" A (Ind HL) = b 0x3a
opc "ld" A (Abs n) = bs [0x3e, n]
opc "ld" B B = b 0x40
opc "ld" B C = b 0x41
opc "ld" B D = b 0x42
opc "ld" B E = b 0x43
opc "ld" B H = b 0x44
opc "ld" B L = b 0x45
opc "ld" B (Ind HL) = b 0x46
opc "ld" B A = b 0x47
opc "ld" C B = b 0x48
opc "ld" C C = b 0x49
opc "ld" C D = b 0x4a
opc "ld" C E = b 0x4b
opc "ld" C H = b 0x4c
opc "ld" C L = b 0x4d
opc "ld" C (Ind HL) = b 0x4e
opc "ld" C A = b 0x4f
opc "ld" D B = b 0x50
opc "ld" D C = b 0x51
opc "ld" D D = b 0x52
opc "ld" D E = b 0x53
opc "ld" D H = b 0x54
opc "ld" D L = b 0x55
opc "ld" D (Ind HL) = b 0x56
opc "ld" D A = b 0x57
opc "ld" E B = b 0x58
opc "ld" E C = b 0x59
opc "ld" E D = b 0x5a
opc "ld" E E = b 0x5b
opc "ld" E H = b 0x5c
opc "ld" E L = b 0x5d
opc "ld" E (Ind HL) = b 0x5e
opc "ld" E A = b 0x5f
opc "ld" H B = b 0x60
opc "ld" H C = b 0x61
opc "ld" H D = b 0x62
opc "ld" H E = b 0x63
opc "ld" H H = b 0x64
opc "ld" H L = b 0x65
opc "ld" H (Ind HL) = b 0x66
opc "ld" H A = b 0x67
opc "ld" L B = b 0x68
opc "ld" L C = b 0x69
opc "ld" L D = b 0x6a
opc "ld" L E = b 0x6b
opc "ld" L H = b 0x6c
opc "ld" L L = b 0x6d
opc "ld" L (Ind HL) = b 0x6e
opc "ld" L A = b 0x6f
opc "ld" (Ind HL) B = b 0x70
opc "ld" (Ind HL) C = b 0x71
opc "ld" (Ind HL) D = b 0x72
opc "ld" (Ind HL) E = b 0x73
opc "ld" (Ind HL) H = b 0x74
opc "ld" (Ind HL) L = b 0x75
opc "ld" (Ind HL) A = b 0x77
opc "ld" A B = b 0x78
opc "ld" A C = b 0x79
opc "ld" A D = b 0x7a
opc "ld" A E = b 0x7b
opc "ld" A H = b 0x7c
opc "ld" A L = b 0x7d
opc "ld" A (Ind HL) = b 0x7e
opc "ld" A A = b 0x7f
opc "add" A B = b 0x80
opc "add" A C = b 0x81
opc "add" A D = b 0x82
opc "add" A E = b 0x83
opc "add" A H = b 0x84
opc "add" A L = b 0x85
opc "add" A (Ind HL) = b 0x86
opc "add" A A = b 0x87
opc "adc" A B = b 0x88
opc "adc" A C = b 0x89
opc "adc" A D = b 0x8a
opc "adc" A E = b 0x8b
opc "adc" A H = b 0x8c
opc "adc" A L = b 0x8d
opc "adc" A (Ind HL) = b 0x8e
opc "adc" A A = b 0x8f
opc "sub" A B = b 0x90
opc "sub" A C = b 0x91
opc "sub" A D = b 0x92
opc "sub" A E = b 0x93
opc "sub" A H = b 0x94
opc "sub" A L = b 0x95
opc "sub" A (Ind HL) = b 0x96
opc "sub" A A = b 0x97
opc "sbc" A B = b 0x98
opc "sbc" A C = b 0x99
opc "sbc" A D = b 0x9a
opc "sbc" A E = b 0x9b
opc "sbc" A H = b 0x9c
opc "sbc" A L = b 0x9d
opc "sbc" A (Ind HL) = b 0x9e
opc "sbc" A A = b 0x9f
opc "and" A B = b 0xa0
opc "and" A C = b 0xa1
opc "and" A D = b 0xa2
opc "and" A E = b 0xa3
opc "and" A H = b 0xa4
opc "and" A L = b 0xa5
opc "and" A (Ind HL) = b 0xa6
opc "and" A A = b 0xa7
opc "xor" A B = b 0xa8
opc "xor" A C = b 0xa9
opc "xor" A D = b 0xaa
opc "xor" A E = b 0xab
opc "xor" A H = b 0xac
opc "xor" A L = b 0xad
opc "xor" A (Ind HL) = b 0xae
opc "xor" A A = b 0xaf
opc "or" A B = b 0xb0
opc "or" A C = b 0xb1
opc "or" A D = b 0xb2
opc "or" A E = b 0xb3
opc "or" A H = b 0xb4
opc "or" A L = b 0xb5
opc "or" A (Ind HL) = b 0xb6
opc "or" A A = b 0xb7
opc "cp" A B = b 0xb8
opc "cp" A C = b 0xb9
opc "cp" A D = b 0xba
opc "cp" A E = b 0xbb
opc "cp" A H = b 0xbc
opc "cp" A L = b 0xbd
opc "cp" A (Ind HL) = b 0xbe
opc "cp" A A = b 0xbf
opc "jp" NZ (Abs n) = bs [0xc2, n, n `shiftR` 8]
opc "call" NZ (Abs n) = bs [0xc4, n, n `shiftR` 8]
opc "add" A (Abs n) = bs [0xc6, n]
opc "jp" Z (Abs n) = bs [0xca, n, n `shiftR` 8]
opc "call" Z (Abs n) = bs [0xcc, n, n `shiftR` 8]
opc "adc" A (Abs n) = bs [0xce, n]
opc "jp" NC (Abs n) = bs [0xd2, n, n `shiftR` 8]
opc "call" NC (Abs n) = bs [0xd4, n, n `shiftR` 8]
opc "sub" A (Abs n) = bs [0xd6, n]
opc "jp" C (Abs n) = bs [0xda, n, n `shiftR` 8]
opc "call" C (Abs n) = bs [0xdc, n, n `shiftR` 8]
opc "sbc" A (Abs n) = bs [0xde, n]
opc "ldh" (Ind (Abs n)) A | n >= 0xff00 = bs [0xe0, n]
opc "ldh" (Ind C) A = b 0xe2
opc "and" A (Abs n) = bs [0xe6, n]
opc "add" SP (Abs n) = bs [0xe8, n]
opc "ld" (Ind (Abs n)) A = bs [0xea, n, n `shiftR` 8]
opc "xor" A (Abs n) = bs [0xee, n]
opc "ldh" A (Ind (Abs n)) | n >= 0xff00 = bs [0xf0, n]
opc "or" A (Abs n) = bs [0xf6, n]
opc "ldhl" SP (Ind (Abs n)) | n >= 0xff00 = bs [0xf8, n]
opc "ld" SP HL = b 0xf9
opc "ld" A (Ind (Abs n)) = bs [0xfa, n, n `shiftR` 8]
opc "bit" (Abs 0) B = bs [0xcb, 0x40]
opc "bit" (Abs 0) C = bs [0xcb, 0x41]
opc "bit" (Abs 0) D = bs [0xcb, 0x42]
opc "bit" (Abs 0) E = bs [0xcb, 0x43]
opc "bit" (Abs 0) H = bs [0xcb, 0x44]
opc "bit" (Abs 0) L = bs [0xcb, 0x45]
opc "bit" (Abs 0) (Ind HL) = bs [0xcb, 0x46]
opc "bit" (Abs 0) A = bs [0xcb, 0x47]
opc "bit" (Abs 1) B = bs [0xcb, 0x48]
opc "bit" (Abs 1) C = bs [0xcb, 0x49]
opc "bit" (Abs 1) D = bs [0xcb, 0x4a]
opc "bit" (Abs 1) E = bs [0xcb, 0x4b]
opc "bit" (Abs 1) H = bs [0xcb, 0x4c]
opc "bit" (Abs 1) L = bs [0xcb, 0x4d]
opc "bit" (Abs 1) (Ind HL) = bs [0xcb, 0x4e]
opc "bit" (Abs 1) A = bs [0xcb, 0x4f]
opc "bit" (Abs 2) B = bs [0xcb, 0x50]
opc "bit" (Abs 2) C = bs [0xcb, 0x51]
opc "bit" (Abs 2) D = bs [0xcb, 0x52]
opc "bit" (Abs 2) E = bs [0xcb, 0x53]
opc "bit" (Abs 2) H = bs [0xcb, 0x54]
opc "bit" (Abs 2) L = bs [0xcb, 0x55]
opc "bit" (Abs 2) (Ind HL) = bs [0xcb, 0x56]
opc "bit" (Abs 2) A = bs [0xcb, 0x57]
opc "bit" (Abs 3) B = bs [0xcb, 0x58]
opc "bit" (Abs 3) C = bs [0xcb, 0x59]
opc "bit" (Abs 3) D = bs [0xcb, 0x5a]
opc "bit" (Abs 3) E = bs [0xcb, 0x5b]
opc "bit" (Abs 3) H = bs [0xcb, 0x5c]
opc "bit" (Abs 3) L = bs [0xcb, 0x5d]
opc "bit" (Abs 3) (Ind HL) = bs [0xcb, 0x5e]
opc "bit" (Abs 3) A = bs [0xcb, 0x5f]
opc "bit" (Abs 4) B = bs [0xcb, 0x60]
opc "bit" (Abs 4) C = bs [0xcb, 0x61]
opc "bit" (Abs 4) D = bs [0xcb, 0x62]
opc "bit" (Abs 4) E = bs [0xcb, 0x63]
opc "bit" (Abs 4) H = bs [0xcb, 0x64]
opc "bit" (Abs 4) L = bs [0xcb, 0x65]
opc "bit" (Abs 4) (Ind HL) = bs [0xcb, 0x66]
opc "bit" (Abs 4) A = bs [0xcb, 0x67]
opc "bit" (Abs 5) B = bs [0xcb, 0x68]
opc "bit" (Abs 5) C = bs [0xcb, 0x69]
opc "bit" (Abs 5) D = bs [0xcb, 0x6a]
opc "bit" (Abs 5) E = bs [0xcb, 0x6b]
opc "bit" (Abs 5) H = bs [0xcb, 0x6c]
opc "bit" (Abs 5) L = bs [0xcb, 0x6d]
opc "bit" (Abs 5) (Ind HL) = bs [0xcb, 0x6e]
opc "bit" (Abs 5) A = bs [0xcb, 0x6f]
opc "bit" (Abs 6) B = bs [0xcb, 0x70]
opc "bit" (Abs 6) C = bs [0xcb, 0x71]
opc "bit" (Abs 6) D = bs [0xcb, 0x72]
opc "bit" (Abs 6) E = bs [0xcb, 0x73]
opc "bit" (Abs 6) H = bs [0xcb, 0x74]
opc "bit" (Abs 6) L = bs [0xcb, 0x75]
opc "bit" (Abs 6) (Ind HL) = bs [0xcb, 0x76]
opc "bit" (Abs 6) A = bs [0xcb, 0x77]
opc "bit" (Abs 7) B = bs [0xcb, 0x78]
opc "bit" (Abs 7) C = bs [0xcb, 0x79]
opc "bit" (Abs 7) D = bs [0xcb, 0x7a]
opc "bit" (Abs 7) E = bs [0xcb, 0x7b]
opc "bit" (Abs 7) H = bs [0xcb, 0x7c]
opc "bit" (Abs 7) L = bs [0xcb, 0x7d]
opc "bit" (Abs 7) (Ind HL) = bs [0xcb, 0x7e]
opc "bit" (Abs 7) A = bs [0xcb, 0x7f]
opc "res" (Abs 0) B = bs [0xcb, 0x80]
opc "res" (Abs 0) C = bs [0xcb, 0x81]
opc "res" (Abs 0) D = bs [0xcb, 0x82]
opc "res" (Abs 0) E = bs [0xcb, 0x83]
opc "res" (Abs 0) H = bs [0xcb, 0x84]
opc "res" (Abs 0) L = bs [0xcb, 0x85]
opc "res" (Abs 0) (Ind HL) = bs [0xcb, 0x86]
opc "res" (Abs 0) A = bs [0xcb, 0x87]
opc "res" (Abs 1) B = bs [0xcb, 0x88]
opc "res" (Abs 1) C = bs [0xcb, 0x89]
opc "res" (Abs 1) D = bs [0xcb, 0x8a]
opc "res" (Abs 1) E = bs [0xcb, 0x8b]
opc "res" (Abs 1) H = bs [0xcb, 0x8c]
opc "res" (Abs 1) L = bs [0xcb, 0x8d]
opc "res" (Abs 1) (Ind HL) = bs [0xcb, 0x8e]
opc "res" (Abs 1) A = bs [0xcb, 0x8f]
opc "res" (Abs 2) B = bs [0xcb, 0x90]
opc "res" (Abs 2) C = bs [0xcb, 0x91]
opc "res" (Abs 2) D = bs [0xcb, 0x92]
opc "res" (Abs 2) E = bs [0xcb, 0x93]
opc "res" (Abs 2) H = bs [0xcb, 0x94]
opc "res" (Abs 2) L = bs [0xcb, 0x95]
opc "res" (Abs 2) (Ind HL) = bs [0xcb, 0x96]
opc "res" (Abs 2) A = bs [0xcb, 0x97]
opc "res" (Abs 3) B = bs [0xcb, 0x98]
opc "res" (Abs 3) C = bs [0xcb, 0x99]
opc "res" (Abs 3) D = bs [0xcb, 0x9a]
opc "res" (Abs 3) E = bs [0xcb, 0x9b]
opc "res" (Abs 3) H = bs [0xcb, 0x9c]
opc "res" (Abs 3) L = bs [0xcb, 0x9d]
opc "res" (Abs 3) (Ind HL) = bs [0xcb, 0x9e]
opc "res" (Abs 3) A = bs [0xcb, 0x9f]
opc "res" (Abs 4) B = bs [0xcb, 0xa0]
opc "res" (Abs 4) C = bs [0xcb, 0xa1]
opc "res" (Abs 4) D = bs [0xcb, 0xa2]
opc "res" (Abs 4) E = bs [0xcb, 0xa3]
opc "res" (Abs 4) H = bs [0xcb, 0xa4]
opc "res" (Abs 4) L = bs [0xcb, 0xa5]
opc "res" (Abs 4) (Ind HL) = bs [0xcb, 0xa6]
opc "res" (Abs 4) A = bs [0xcb, 0xa7]
opc "res" (Abs 5) B = bs [0xcb, 0xa8]
opc "res" (Abs 5) C = bs [0xcb, 0xa9]
opc "res" (Abs 5) D = bs [0xcb, 0xaa]
opc "res" (Abs 5) E = bs [0xcb, 0xab]
opc "res" (Abs 5) H = bs [0xcb, 0xac]
opc "res" (Abs 5) L = bs [0xcb, 0xad]
opc "res" (Abs 5) (Ind HL) = bs [0xcb, 0xae]
opc "res" (Abs 5) A = bs [0xcb, 0xaf]
opc "res" (Abs 6) B = bs [0xcb, 0xb0]
opc "res" (Abs 6) C = bs [0xcb, 0xb1]
opc "res" (Abs 6) D = bs [0xcb, 0xb2]
opc "res" (Abs 6) E = bs [0xcb, 0xb3]
opc "res" (Abs 6) H = bs [0xcb, 0xb4]
opc "res" (Abs 6) L = bs [0xcb, 0xb5]
opc "res" (Abs 6) (Ind HL) = bs [0xcb, 0xb6]
opc "res" (Abs 6) A = bs [0xcb, 0xb7]
opc "res" (Abs 7) B = bs [0xcb, 0xb8]
opc "res" (Abs 7) C = bs [0xcb, 0xb9]
opc "res" (Abs 7) D = bs [0xcb, 0xba]
opc "res" (Abs 7) E = bs [0xcb, 0xbb]
opc "res" (Abs 7) H = bs [0xcb, 0xbc]
opc "res" (Abs 7) L = bs [0xcb, 0xbd]
opc "res" (Abs 7) (Ind HL) = bs [0xcb, 0xbe]
opc "res" (Abs 7) A = bs [0xcb, 0xbf]
opc "set" (Abs 0) B = bs [0xcb, 0xc0]
opc "set" (Abs 0) C = bs [0xcb, 0xc1]
opc "set" (Abs 0) D = bs [0xcb, 0xc2]
opc "set" (Abs 0) E = bs [0xcb, 0xc3]
opc "set" (Abs 0) H = bs [0xcb, 0xc4]
opc "set" (Abs 0) L = bs [0xcb, 0xc5]
opc "set" (Abs 0) (Ind HL) = bs [0xcb, 0xc6]
opc "set" (Abs 0) A = bs [0xcb, 0xc7]
opc "set" (Abs 1) B = bs [0xcb, 0xc8]
opc "set" (Abs 1) C = bs [0xcb, 0xc9]
opc "set" (Abs 1) D = bs [0xcb, 0xca]
opc "set" (Abs 1) E = bs [0xcb, 0xcb]
opc "set" (Abs 1) H = bs [0xcb, 0xcc]
opc "set" (Abs 1) L = bs [0xcb, 0xcd]
opc "set" (Abs 1) (Ind HL) = bs [0xcb, 0xce]
opc "set" (Abs 1) A = bs [0xcb, 0xcf]
opc "set" (Abs 2) B = bs [0xcb, 0xd0]
opc "set" (Abs 2) C = bs [0xcb, 0xd1]
opc "set" (Abs 2) D = bs [0xcb, 0xd2]
opc "set" (Abs 2) E = bs [0xcb, 0xd3]
opc "set" (Abs 2) H = bs [0xcb, 0xd4]
opc "set" (Abs 2) L = bs [0xcb, 0xd5]
opc "set" (Abs 2) (Ind HL) = bs [0xcb, 0xd6]
opc "set" (Abs 2) A = bs [0xcb, 0xd7]
opc "set" (Abs 3) B = bs [0xcb, 0xd8]
opc "set" (Abs 3) C = bs [0xcb, 0xd9]
opc "set" (Abs 3) D = bs [0xcb, 0xda]
opc "set" (Abs 3) E = bs [0xcb, 0xdb]
opc "set" (Abs 3) H = bs [0xcb, 0xdc]
opc "set" (Abs 3) L = bs [0xcb, 0xdd]
opc "set" (Abs 3) (Ind HL) = bs [0xcb, 0xde]
opc "set" (Abs 3) A = bs [0xcb, 0xdf]
opc "set" (Abs 4) B = bs [0xcb, 0xe0]
opc "set" (Abs 4) C = bs [0xcb, 0xe1]
opc "set" (Abs 4) D = bs [0xcb, 0xe2]
opc "set" (Abs 4) E = bs [0xcb, 0xe3]
opc "set" (Abs 4) H = bs [0xcb, 0xe4]
opc "set" (Abs 4) L = bs [0xcb, 0xe5]
opc "set" (Abs 4) (Ind HL) = bs [0xcb, 0xe6]
opc "set" (Abs 4) A = bs [0xcb, 0xe7]
opc "set" (Abs 5) B = bs [0xcb, 0xe8]
opc "set" (Abs 5) C = bs [0xcb, 0xe9]
opc "set" (Abs 5) D = bs [0xcb, 0xea]
opc "set" (Abs 5) E = bs [0xcb, 0xeb]
opc "set" (Abs 5) H = bs [0xcb, 0xec]
opc "set" (Abs 5) L = bs [0xcb, 0xed]
opc "set" (Abs 5) (Ind HL) = bs [0xcb, 0xee]
opc "set" (Abs 5) A = bs [0xcb, 0xef]
opc "set" (Abs 6) B = bs [0xcb, 0xf0]
opc "set" (Abs 6) C = bs [0xcb, 0xf1]
opc "set" (Abs 6) D = bs [0xcb, 0xf2]
opc "set" (Abs 6) E = bs [0xcb, 0xf3]
opc "set" (Abs 6) H = bs [0xcb, 0xf4]
opc "set" (Abs 6) L = bs [0xcb, 0xf5]
opc "set" (Abs 6) (Ind HL) = bs [0xcb, 0xf6]
opc "set" (Abs 6) A = bs [0xcb, 0xf7]
opc "set" (Abs 7) B = bs [0xcb, 0xf8]
opc "set" (Abs 7) C = bs [0xcb, 0xf9]
opc "set" (Abs 7) D = bs [0xcb, 0xfa]
opc "set" (Abs 7) E = bs [0xcb, 0xfb]
opc "set" (Abs 7) H = bs [0xcb, 0xfc]
opc "set" (Abs 7) L = bs [0xcb, 0xfd]
opc "set" (Abs 7) (Ind HL) = bs [0xcb, 0xfe]
opc "set" (Abs 7) A = bs [0xcb, 0xff]
opc _ _ _ = Nothing
|
jblake/gbasm
|
src/Language/GBAsm/Opcodes.hs
|
mit
| 27,879
| 0
| 10
| 14,786
| 11,230
| 5,704
| 5,526
| 515
| 1
|
import Data.Array
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as IO
import Text.Parsec
import Text.Parsec.Text
data Instruction
= Half Register
| Triple Register
| Increment Register
| Jump Int
| JumpIfEven Register Int
| JumpIfOne Register Int
deriving (Eq, Show)
data Register = A | B
deriving (Eq, Ord, Enum, Bounded, Ix, Show)
data RunState = RunState {programCounter :: Int, registers :: Array Register Int}
deriving (Eq, Show)
main = do
input <- Text.lines <$> IO.getContents
let instructions = map parseInput input
let finalState = execute initialState instructions
print finalState
parseInput :: Text -> Instruction
parseInput text = either (error . show) id $ parse parser "" text
where
parser = try hlf <|> try tpl <|> try inc <|> try jmp <|> try jie <|> try jio
hlf = Half <$> (string "hlf " >> register)
tpl = Triple <$> (string "tpl " >> register)
inc = Increment <$> (string "inc " >> register)
jmp = Jump <$> (string "jmp " >> number)
jie = do
string "jie "
condition <- register
string ", "
amount <- number
return $ JumpIfEven condition amount
jio = do
string "jio "
condition <- register
string ", "
amount <- number
return $ JumpIfOne condition amount
register = try (string "a" >> return A) <|> try (string "b" >> return B)
number = read <$> ((optional (char '+') >> many1 digit) <|> ((:) <$> char '-' <*> many1 digit))
initialState :: RunState
initialState = RunState 0 (listArray (minBound, maxBound) (1 : repeat 0))
execute :: RunState -> [Instruction] -> RunState
execute state@(RunState counter registers) instructions =
if counter >= length instructions
then state
else execute' (instructions !! counter)
where
execute' (Half register) =
execute (nextState {registers = registers // [(register, (registers ! register) `div` 2)]}) instructions
execute' (Triple register) =
execute (nextState {registers = registers // [(register, (registers ! register) * 3)]}) instructions
execute' (Increment register) =
execute (nextState {registers = registers // [(register, (registers ! register) + 1)]}) instructions
execute' (Jump amount) =
execute (state {programCounter = counter + amount}) instructions
execute' (JumpIfEven register amount)
| even (registers ! register) =
execute (state {programCounter = counter + amount}) instructions
| otherwise =
execute nextState instructions
execute' (JumpIfOne register amount)
| registers ! register == 1 =
execute (state {programCounter = counter + amount}) instructions
| otherwise =
execute nextState instructions
nextState = state {programCounter = counter + 1}
|
SamirTalwar/advent-of-code
|
2015/AOC_23_2.hs
|
mit
| 2,825
| 0
| 16
| 653
| 1,011
| 523
| 488
| -1
| -1
|
import Control.Concurrent.MVar
import qualified System.FilePath.Glob as Glob
import qualified Data.Map.Strict as Map
import Data.Either
import System.Directory
import System.Environment
import System.IO
import System.IO.Error
import System.INotify
data FileState = FS Integer
data State = State String (Map.Map String FileState)
type EventTypeHandler = State -> Event -> IO State
type EventFileHandler = State -> String -> IO State
patternFilter :: Glob.Pattern -> String -> State -> (EventFileHandler) -> IO State
patternFilter pattern filePath s handler =
if (Glob.match pattern filePath) then
handler s filePath
else
return s
fullPath root path = root ++ "/" ++ path
advanceFileState (State root stateMap) fileName = do
let path = fullPath root fileName
let (FS oldPos) = Map.findWithDefault (FS 0) path stateMap
fileHandle <- openFile path ReadMode
-- What if it was just a timestamp update? What if it's shorter now?
hSeek fileHandle AbsoluteSeek (oldPos) -- HACK! Probably need to trycatch this.
contents <- hGetContents fileHandle
let len = toInteger $ length contents
putStr contents
hFlush stdout -- Otherwise it looks like it buffers to newline.
let newState = (State root (Map.insert path (FS (len + oldPos)) stateMap))
hClose fileHandle
return newState
handleNewFile :: EventFileHandler
handleNewFile = advanceFileState
handleUpdatedFile :: EventFileHandler
handleUpdatedFile = advanceFileState
eventHandler :: Glob.Pattern -> EventTypeHandler
eventHandler pattern s e@(Created isDirectory filePath) =
patternFilter pattern filePath s handleNewFile
eventHandler pattern s e@(Modified isDirectory maybeFileName) =
case maybeFileName of
Nothing -> return s
Just fileName -> patternFilter pattern fileName s handleUpdatedFile
eventHandler p s e = return s
inotifyCallback :: MVar State -> INotify -> EventTypeHandler -> Event -> IO()
inotifyCallback mvar inotify eventTypeHandler e = do
oldState <- takeMVar mvar
result <- tryIOError (eventTypeHandler oldState e)
newState <-
case result of
(Left error) -> (putStrLn $ show error) >> return oldState
(Right nextState) -> return nextState
putMVar mvar newState
main = do
args <- getArgs
if length args /= 2 then
-- TODO: Make this not silly.
fail "Usage: tailpattern DIRECTORY PATTERN"
else
-- Not what one would expect in something like Python.
return ()
let watchDirectory = args !! 0
let patternGlob = args !! 1
let pattern = Glob.compile patternGlob
inotify <- initINotify
mvar <- newMVar (State watchDirectory Map.empty)
wd <- addWatch
inotify
[Open, Close, Access, Modify, Move, Create]
watchDirectory
(inotifyCallback mvar inotify (eventHandler pattern))
getLine
(State root files) <- takeMVar mvar
putStrLn $ show $ Map.keys files
removeWatch wd
|
cwgreene/tailpattern
|
src/Main.hs
|
mit
| 2,895
| 0
| 17
| 571
| 856
| 422
| 434
| 71
| 2
|
module Main where
import Criterion.Main
-- infixl 9 !?
-- _ !? n | n<0 = Nothing
-- [] !?_ = Nothing
-- (x:_) !? 0 = Just x
-- (_:xs) !? n = xs !? (n-1)
infixl 9 !?
{-# INLINABLE (!?) #-}
(!?) :: [a] -> Int -> Maybe a
xs !? n
| n < 0 = Nothing
| otherwise =
foldr
(\x r k ->
case k of
0 -> Just x
_ -> r (k-1))
(const Nothing) xs n
myList :: [Int]
myList = [1..9999]
main :: IO ()
main = defaultMain
[ bench "index list 9999"
$ whnf (myList !!) 9998
, bench "index list maybe index 9999"
$ whnf (myList !?) 9998
]
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter28.hsproj/BenchIndex.hs
|
mit
| 602
| 0
| 14
| 208
| 201
| 108
| 93
| 21
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Typechecker where
import Prelude hiding (lookup)
import Syntax
import Data.Word(Word64)
import Data.HashMap.Strict(HashMap, fromList, insert, foldrWithKey, lookup)
import Data.Monoid(getAp)
import Control.Monad.Trans.Reader(ReaderT(ReaderT), runReaderT, asks, local)
import Control.Monad.Trans.Class(lift)
import Data.List(nub, foldl')
import Data.Maybe(isNothing)
import Control.Monad(when, unless, zipWithM)
import Data.IORef(readIORef, newIORef, modifyIORef', IORef)
import Data.Generics.Uniplate.Data(universe, para, descend)
import Data.Foldable(traverse_, foldMap')
import Control.Exception(onException)
type Environment = HashMap Name Type
type Substitution = HashMap Id Type
data TypecheckerState =
TypecheckerState Environment (IORef Word64) (IORef Substitution)
type Typechecker a = ReaderT TypecheckerState IO a
typecheckModule env m = do
r <- newIORef 0
s <- newIORef mempty
runReaderT (inferModule m) (TypecheckerState env r s)
inferModule (ModuleDeclaration modName decls) = do
info ("Typechecking Module " ++ renderName modName)
constructors <- getAp (foldMap' gatherConstructor decls)
let signatures = fromList (foldMap' gatherTypeSig decls)
let types = mappend constructors signatures
-- The signatures are also passed as a plain argument for lookups
binds <- with types (inferDecls generalize signatures decls)
sanitySkolemCheck binds
sanityFreeVariableCheck binds
return (mappend types binds)
-- Skolem variables are caught earlier,
-- so this check is redundant, but makes sure
-- that no skolem variables make it to the top level
sanitySkolemCheck = traverseWithKey_ (\k v ->
let s = skolems v
in unless (null s)
(fail ("Bug: " ++ pretty k ++ " leaked skolems " ++ pretty s)))
sanityFreeVariableCheck = traverseWithKey_ (\k v ->
let vs = freeVars v
in unless (null vs)
(fail ("Bug: " ++ pretty k ++ " leaked free variable " ++ pretty vs)))
traverseWithKey_ f = foldrWithKey (\k v r -> f k v *> r) (pure ())
-- Typecheck Expressions
typecheck :: Expression -> Type -> Typechecker ()
typecheck (LiteralExpression lit) ty =
typecheckLiteral lit ty
typecheck (Variable x) ty =
typecheckVar x ty
typecheck (ConstructorExpression c) ty =
typecheckVar c ty
-- A possible shortcut that avoids generating new type variables
-- because the type of x does not have to be inferred but can be read of
-- similar to typecheckPattern (ConstructorPattern c ps)
-- typecheck (FunctionApplication (Variable x) e) ty =
typecheck (FunctionApplication e1 e2) ty = do
alpha <- newTyVar
typecheck e1 (TypeArrow alpha ty)
typecheck e2 alpha
typecheck (CaseExpression expr alts) ty = do
pty <- newTyVar
traverse_ (uncurry (typecheckAlt pty ty)) alts
typecheck expr pty
-- A common shortcut that avoids generating new type variables
typecheck (LambdaExpression [p] e) (TypeArrow pty ety) =
typecheckAlt pty ety p e
-- A shortcut that avoids generating new type variables
typecheck (LambdaExpression [p] e) s@(ForAll _ (TypeArrow _ _)) = do
(skolVars, TypeArrow alpha beta) <- skolemise s
typecheckAlt alpha beta p e
subst <- getSubst
env <- getEnv
let escVars = skolems s ++ foldMap' (skolems . apply subst) env
let escaped = including escVars skolVars
unless (null escaped) (fail ("Escape check lambda: "
++ pretty escaped ++ " escaped when checking fun "
++ pretty p ++ " -> ... against " ++ pretty s))
typecheck (LambdaExpression [p] e) ty = do
alpha <- newTyVar
beta <- newTyVar
typecheckAlt alpha beta p e
subsume (TypeArrow alpha beta) ty
typecheck (LetExpression decls e) ty = do
let signatures = fromList (foldMap' gatherTypeSig decls)
binds <- with signatures (inferDecls return signatures decls)
with (mappend signatures binds) (typecheck e ty)
typecheck (IfExpression c th el) ty = do
typecheck c (TypeConstructor (fromText "Native.Boolean"))
typecheck th ty
typecheck el ty
typecheck (ArrayExpression es) ty = do
alpha <- newTyVar
traverse_ (flip typecheck alpha) es
unify (TypeApplication (TypeConstructor (fromText "Native.Array")) alpha) ty
typecheck other _ = fail ("Cannot typecheck expression " ++ show other)
typecheckVar x ty = do
env <- getEnv
scheme <- mfind x env
subsume scheme ty
typecheckAlt pty ety pat expr = do
binds <- typecheckPattern pat pty
with (fromList binds) (typecheck expr ety)
{-
Typecheck Constructors
capture the signature of all constructors from a type declaration
for example
type Vector a = Vec2 a a | Vec3 a a a
becomes
Vec2 : forall a. a -> a -> Vector a
Vec3 : forall a. a -> a -> a -> Vector a
Vec2 is a constructor and Vector a type constructor
-}
gatherConstructor (TypeDeclaration tyIdent vars constructors) =
let
resTy = TypeConstructor tyIdent
tyCon = foldl' TypeApplication resTy (fmap TypeVariable vars)
in fmap fromList (traverse (traverse (constructorToType tyCon vars)) constructors)
gatherConstructor _ = pure mempty
-- convert a constructor declaration to a type
constructorToType tyCon vars tys =
scopeCheck (makeForAll vars (foldr TypeArrow tyCon tys))
-- fails type W = Wrapped (a -> a)
-- works type W a = Wrapped (a -> a)
-- works type W = Wrapped (forall a. a -> a)
scopeCheck ty = case freeVars ty of
[] -> pure ty
frees -> fail ("Type variables " ++ pretty frees ++ " have no definition")
arrowsToList (TypeArrow x xs) = x:arrowsToList xs
arrowsToList x = [x]
-- Typecheck Bindings
gatherTypeSig (TypeSignature name ty) =
[(name, makeForAll (freeVars ty) ty)]
gatherTypeSig _ = mempty
-- Assumes that the let bindings are already sorted
-- Let bindings have to be sorted for the translation anyway
inferDecls gen signatures =
foldr (inferDecl gen signatures) (return mempty)
-- A version of onException that works with ReaderT
onException' a b = ReaderT (\s -> onException (runReaderT a s) b)
-- If a signature is given, check against it
-- otherwise create a new type variable and infer a type
-- TODO match variable against its signature in cases like this:
-- x : Int
-- Tuple x _ = Tuple "hi" "ho"
-- Should be a type error
findSignature signatures (VariablePattern v) =
maybe newTyVar return (lookup v signatures)
findSignature _ _ = newTyVar
bindsWithoutSignatures signatures binds =
filter (\x -> isNothing (lookup (fst x) signatures)) binds
inferDecl gen signatures (ExpressionDeclaration p e) next = do
ty <- findSignature signatures p
binds <- typecheckPattern p ty
let binds' = fromList (bindsWithoutSignatures signatures binds)
-- If an error occurs, show in which declaration it happened
onException' (with binds' (typecheck e ty))
(putStrLn ("When typechecking declaration " ++ pretty p
++ " at " ++ locationInfo p))
-- generalize e.g. id : x1 -> x1 to id : forall x1 . x1 -> x1
-- NOTE if binds contain signatures then those are not generalized
-- because they are already in the form forall x1 ... xn . t
-- also in LetExpressions gen is just 'return' and does nothing
generalized <- traverse gen binds'
nextTys <- with generalized next
return (mappend generalized nextTys)
inferDecl _ _ _ next = next
-- Typecheck Patterns
typecheckPattern (VariablePattern x) ty =
return [(x, ty)]
typecheckPattern (AliasPattern x p) ty = do
binds <- typecheckPattern p ty
return ((x, ty):binds)
typecheckPattern (Wildcard _) _ =
return mempty
typecheckPattern (LiteralPattern l) ty = do
typecheckLiteral l ty
return mempty
typecheckPattern (ConstructorPattern c ps) ty = do
env <- getEnv
scheme <- mfind c env
consTy <- instantiate scheme
let tys = arrowsToList consTy
let resultTy = last tys
let consTys = init tys
when (length ps /= length consTys)
(fail ("Constructor " ++ pretty c
++ " was given wrong number of arguments"))
binds <- zipWithM typecheckPattern ps consTys
unify resultTy ty
return (mconcat binds)
typecheckPattern (ArrayPattern ps) ty = do
alpha <- newTyVar
binds <- traverse (\p -> typecheckPattern p alpha) ps
unify (TypeApplication (TypeConstructor (fromText "Native.Array")) alpha) ty
return (mconcat binds)
typecheckPattern other _ =
fail ("Cannot typecheck pattern " ++ pretty other)
-- Typecheck Literals
typecheckLiteral (Numeral _) ty =
unify (TypeConstructor (fromText "Native.Numeral")) ty
typecheckLiteral (Text _) ty =
unify (TypeConstructor (fromText "Native.Text")) ty
-- Unification
unify x y = do
subst <- getSubst
unify' (apply subst x) (apply subst y)
unify' (SkolemConstant x) (SkolemConstant y) | x == y = return ()
unify' (TypeVariable x) (TypeVariable y) | x == y = return ()
unify' (TypeConstructor a) (TypeConstructor b) | a == b = return ()
-- When unifying, no higher rank type should appear
unify' s@(ForAll _ _) ty =
fail ("Cannot unify scheme " ++ pretty s ++ " and " ++ pretty ty)
unify' ty s@(ForAll _ _) =
fail ("Cannot unify " ++ pretty ty ++ " and scheme " ++ pretty s)
unify' (TypeVariable x) ty = unifyVar x ty
unify' ty (TypeVariable x) = unifyVar x ty
-- After unifying f1 and f2 the substitution might have changed
-- and therefore needs to be reapplied to e1 and e2
unify' (TypeApplication f1 e1) (TypeApplication f2 e2) =
unify' f1 f2 *> unify e1 e2
unify' (TypeArrow a1 b1) (TypeArrow a2 b2) =
unify' a1 a2 *> unify b1 b2
unify' a b =
fail ("Cannot unify " ++ pretty a ++ " and " ++ pretty b)
unifyVar x ty = if occurs x ty
then fail ("Occurs check: " ++ pretty x ++ " occurs in " ++ pretty ty)
else insertSubst x ty
-- Does a type variable occur in a type?
occurs x ty = elem x (freeVars ty)
-- substitute bound variables with unification variables
apply subst (ForAll vs ty) =
let filteredSubst = excludingKeys vs subst
in ForAll vs (apply filteredSubst ty)
-- TODO investigate infinite loop
-- sometimes the typechecker looped infinitely
-- substituting a variable again and again
-- it is not clear why this happens
-- as this should be caught in the occurs check
apply subst ty@(TypeVariable x) =
maybe ty (\ty2 -> case ty2 of
-- do not substitute if the variable
-- would be substituted with itself
TypeVariable y | x == y -> ty2
_ -> apply subst ty2) (lookup x subst)
apply subst ty = descend (apply subst) ty
-- Environment
getEnv = asks (\(TypecheckerState env _ _) -> env)
insertSubst k v = do
r <- asks (\(TypecheckerState _ _ s) -> s)
modifyRef r (insert k v)
getSubst = do
r <- asks (\(TypecheckerState _ _ s) -> s)
readRef r
with binds = local (\(TypecheckerState env r s) ->
TypecheckerState (mappend binds env) r s)
-- Type Variables
newUnique = do
r <- asks (\(TypecheckerState _ u _) -> u)
modifyRef r succ
readRef r
newTyVar = fmap TypeVariable newUniqueName
newUniqueName = fmap (prefixedId . show) newUnique
-- extract skolem constants
skolems ty = [c | SkolemConstant c <- universe ty]
-- extract free variables
freeVars ty =
let
f (ForAll vars _) cs = excluding vars (concat cs)
f (TypeVariable v) _ = [v]
f _ cs = concat cs
in para f ty
generalize ty = do
subst <- getSubst
let ty' = apply subst ty
env <- getEnv
let envVars = foldMap' (freeVars . apply subst) env
let qualVars = excluding envVars (freeVars ty')
return (makeForAll qualVars ty')
instantiate (ForAll vars ty) = do
subst <- traverse (\x -> fmap (\t -> (x, t)) newTyVar) vars
return (apply (fromList subst) ty)
instantiate ty = return ty
subsume x y = do
subst <- getSubst
subsume' (apply subst x) (apply subst y)
{-
This typechecker roughly follows the tutorial of
"Practical type inference for arbitrary-rank types"
However, subsumption was kept simple with the intention to
complete it when needed.
Meanwhile, the ghc proposal "Simplify subsumption" proposed
to keep subsumption simple anyway
-}
subsume' scheme1 scheme2@(ForAll _ _) = do
(skolVars, ty) <- skolemise scheme2
subsume' scheme1 ty
subst <- getSubst
let escVars = skolems (apply subst scheme1) ++ skolems (apply subst scheme2)
let escaped = including escVars skolVars
unless (null escaped) (fail ("Escape check: " ++ pretty escaped
++ " escaped when subsuming " ++ pretty scheme1
++ " and " ++ pretty scheme2))
subsume' scheme@(ForAll _ _) t2 = do
t1 <- instantiate scheme
subsume' t1 t2
subsume' t1 t2 = unify' t1 t2
-- Normalizes foralls
-- forall a. forall b. t becomes forall a b. t
-- forall a a. t becomes forall a. t
makeForAll tvs1 (ForAll tvs2 ty) =
makeForAll (tvs1 ++ tvs2) ty
makeForAll [] ty = ty
makeForAll tvs ty = ForAll (nub tvs) ty
skolemise (ForAll vars ty) = do
skolVars <- traverse (const newUniqueName) vars
let subs = fromList (zip vars (fmap SkolemConstant skolVars))
return (skolVars, apply subs ty)
skolemise ty = return ([], ty)
info s = lift (putStrLn s)
readRef s = lift (readIORef s)
modifyRef s f = lift (modifyIORef' s f)
|
kindl/Hypatia
|
src/Typechecker.hs
|
mit
| 13,186
| 0
| 17
| 2,845
| 4,089
| 1,995
| 2,094
| 255
| 3
|
-- Copyright (C) 2002-2004 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.
module Darcs.UI.Commands.Help (
helpCmd,
commandControlList, environmentHelp, -- these are for preproc.hs
printVersion,
listAvailableCommands ) where
import Darcs.UI.Flags
( DarcsFlag
, environmentHelpEmail
, environmentHelpSendmail
)
import Darcs.UI.Options.Markdown ( optionsMarkdown )
import Darcs.UI.Commands
( CommandArgs(..)
, CommandControl(..)
, normalCommand
, DarcsCommand(..), withStdOpts
, WrappedCommand(..)
, wrappedCommandName
, disambiguateCommands
, extractCommands
, getCommandHelp
, nodefaults
, usage
)
import Darcs.UI.External ( viewDoc )
import Darcs.Repository.Lock ( environmentHelpTmpdir, environmentHelpKeepTmpdir
, environmentHelpLocks )
import Darcs.Patch.Match ( helpOnMatchers )
import Darcs.Repository.Prefs ( boringFileHelp, binariesFileHelp, environmentHelpHome )
import Darcs.Repository.Ssh ( environmentHelpSsh, environmentHelpScp, environmentHelpSshPort )
import Darcs.Repository.External ( environmentHelpProtocols )
import Darcs.Util.File ( withCurrentDirectory )
import Darcs.Util.Path ( AbsolutePath )
import Control.Arrow ( (***) )
import Data.Char ( isAlphaNum, toLower, toUpper )
import Data.Either ( partitionEithers )
import Data.List ( groupBy, isPrefixOf, intercalate, nub )
import Darcs.Util.English ( andClauses )
import Darcs.Util.Printer (text, vcat, vsep, ($$), empty)
import Darcs.Util.Printer.Color ( environmentHelpColor, environmentHelpEscape, environmentHelpEscapeWhite )
import System.Exit ( exitSuccess )
import Version ( version )
import Darcs.Util.Download ( environmentHelpProxy, environmentHelpProxyPassword )
import Darcs.Util.Workaround ( getCurrentDirectory )
import Darcs.UI.Options ( DarcsOption, defaultFlags, ocheck, onormalise, oid )
import qualified Darcs.UI.Options.All as O ( StdCmdAction, Verbosity, UseCache )
import qualified Darcs.UI.TheCommands as TheCommands
helpDescription :: String
helpDescription = "Display help about darcs and darcs commands."
helpHelp :: String
helpHelp =
"Without arguments, `darcs help` prints a categorized list of darcs\n" ++
"commands and a short description of each one. With an extra argument,\n" ++
"`darcs help foo` prints detailed help about the darcs command foo.\n"
argPossibilities :: [String]
argPossibilities = map wrappedCommandName $ extractCommands commandControlList
helpOpts :: DarcsOption a
(Maybe O.StdCmdAction
-> Bool
-> Bool
-> O.Verbosity
-> Bool
-> O.UseCache
-> Maybe String
-> Bool
-> Maybe String
-> Bool
-> a)
helpOpts = withStdOpts oid oid
help :: DarcsCommand [DarcsFlag]
help = DarcsCommand
{ commandProgramName = "darcs"
, commandName = "help"
, commandHelp = helpHelp
, commandDescription = helpDescription
, commandExtraArgs = -1
, commandExtraArgHelp = ["[<DARCS_COMMAND> [DARCS_SUBCOMMAND]] "]
, commandCommand = \ x y z -> helpCmd x y z >> exitSuccess
, commandPrereq = \_ -> return $ Right ()
, commandGetArgPossibilities = return argPossibilities
, commandArgdefaults = nodefaults
, commandAdvancedOptions = []
, commandBasicOptions = []
, commandDefaults = defaultFlags helpOpts
, commandCheckOptions = ocheck helpOpts
, commandParseOptions = onormalise helpOpts
}
helpCmd :: (AbsolutePath, AbsolutePath) -> [DarcsFlag] -> [String] -> IO ()
helpCmd _ _ ["manpage"] = putStr $ unlines manpageLines
helpCmd _ _ ["markdown"] = putStr $ unlines markdownLines
helpCmd _ _ ["patterns"] = viewDoc $ text $ unlines helpOnMatchers
helpCmd _ _ ("environment":vs_) =
viewDoc $ header $$
vsep (map render known) $$
footer
where
header | null known = empty
| otherwise = text "Environment Variables" $$
text "====================="
footer | null unknown = empty
| otherwise = text "" $$
text ("Unknown environment variables: "
++ intercalate ", " unknown)
render (ks, ds) = text (andClauses ks ++ ":") $$
vcat [ text (" " ++ d) | d <- ds ]
(unknown, known) = case map (map toUpper) vs_ of
[] -> ([], environmentHelp)
vs -> (nub *** (nub . concat)) . partitionEithers $
map doLookup vs
-- v is not known if it doesn't appear in the list of aliases of any
-- of the environment var help descriptions.
doLookup v = case filter ((v `elem`) . fst) environmentHelp of
[] -> Left v
es -> Right es
helpCmd _ _ [] = viewDoc $ text $ usage commandControlList
helpCmd _ _ (cmd:args) =
let disambiguated = disambiguateCommands commandControlList cmd args
in case disambiguated of
Left err -> fail err
Right (cmds,_) ->
let msg = case cmds of
CommandOnly c -> getCommandHelp Nothing c
SuperCommandOnly c -> getCommandHelp Nothing c
SuperCommandSub c s -> getCommandHelp (Just c) s
in viewDoc $ text msg
listAvailableCommands :: IO ()
listAvailableCommands =
do here <- getCurrentDirectory
is_valid <- mapM
(\(WrappedCommand c)-> withCurrentDirectory here $ commandPrereq c [])
(extractCommands commandControlList)
putStr $ unlines $ map (wrappedCommandName . fst) $
filter (isRight.snd) $
zip (extractCommands commandControlList) is_valid
putStrLn "--help"
putStrLn "--version"
putStrLn "--exact-version"
putStrLn "--overview"
where isRight (Right _) = True
isRight _ = False
printVersion :: IO ()
printVersion = putStrLn $ "darcs version " ++ version
-- avoiding a module import cycle between Help and TheCommands
commandControlList :: [CommandControl]
commandControlList =
normalCommand help : TheCommands.commandControlList
-- FIXME: the "grouping" comments below should made subsections in the
-- manpage, as we already do for DarcsCommand groups. --twb, 2009
-- | Help on each environment variable in which Darcs is interested.
environmentHelp :: [([String], [String])]
environmentHelp = [
-- General-purpose
environmentHelpHome,
environmentHelpEditor,
environmentHelpPager,
environmentHelpColor,
environmentHelpEscapeWhite,
environmentHelpEscape,
environmentHelpTmpdir,
environmentHelpKeepTmpdir,
environmentHelpEmail,
environmentHelpSendmail,
environmentHelpLocks,
-- Remote Repositories
environmentHelpSsh,
environmentHelpScp,
environmentHelpSshPort,
environmentHelpProxy,
environmentHelpProxyPassword,
environmentHelpProtocols,
environmentHelpTimeout]
-- | This module is responsible for emitting a darcs "man-page", a
-- reference document used widely on Unix-like systems. Manpages are
-- primarily used as a quick reference, or "memory jogger", so the
-- output should be terser than the user manual.
--
-- Before modifying the output, please be sure to read the man(7) and
-- man-pages(7) manpages, as these respectively describe the relevant
-- syntax and conventions.
-- | The lines of the manpage to be printed.
manpageLines :: [String]
manpageLines = [
".TH DARCS 1 \"" ++ version ++ "\"",
".SH NAME",
"darcs \\- an advanced revision control system",
".SH SYNOPSIS",
".B darcs", ".I command", ".RI < arguments |[ options ]>...",
"",
"Where the", ".I commands", "and their respective", ".I arguments", "are",
"",
unlines synopsis,
".SH DESCRIPTION",
-- FIXME: this is copy-and-pasted from darcs.cabal, so
-- it'll get out of date as people forget to maintain
-- both in sync.
"Darcs is a free, open source revision control",
"system. It is:",
".TP 3", "\\(bu",
"Distributed: Every user has access to the full",
"command set, removing boundaries between server and",
"client or committer and non\\(hycommitters.",
".TP", "\\(bu",
"Interactive: Darcs is easy to learn and efficient to",
"use because it asks you questions in response to",
"simple commands, giving you choices in your work",
"flow. You can choose to record one change in a file,",
"while ignoring another. As you update from upstream,",
"you can review each patch name, even the full `diff'",
"for interesting patches.",
".TP", "\\(bu",
"Smart: Originally developed by physicist David",
"Roundy, darcs is based on a unique algebra of",
"patches.",
"This smartness lets you respond to changing demands",
"in ways that would otherwise not be possible. Learn",
"more about spontaneous branches with darcs.",
".SH OPTIONS",
"Different options are accepted by different Darcs commands.",
"Each command's most important options are listed in the",
".B COMMANDS",
"section. For a full list of all options accepted by",
"a particular command, run `darcs", ".I command", "\\-\\-help'.",
".SS " ++ escape (unlines helpOnMatchers), -- FIXME: this is a kludge.
".SH COMMANDS",
unlines commands,
unlines environment,
".SH FILES",
".SS \"_darcs/prefs/binaries\"",
escape $ unlines binariesFileHelp,
".SS \"_darcs/prefs/boring\"",
escape $ unlines boringFileHelp,
".SH BUGS",
"At http://bugs.darcs.net/ you can find a list of known",
"bugs in Darcs. Unknown bugs can be reported at that",
"site (after creating an account) or by emailing the",
"report to bugs@darcs.net.",
-- ".SH EXAMPLE",
-- FIXME:
-- new project: init, rec -la;
-- track upstream project: clone, pull -a;
-- contribute to project: add, rec, push/send.
".SH SEE ALSO",
"The Darcs website provides a lot of additional information.",
"It can be found at http://darcs.net/",
".SH LICENSE",
"Darcs 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." ]
where
-- | A synopsis line for each command. Uses 'foldl' because it is
-- necessary to avoid blank lines from Hidden_commands, as groff
-- translates them into annoying vertical padding (unlike TeX).
synopsis :: [String]
synopsis = foldl iter [] commandControlList
where iter :: [String] -> CommandControl -> [String]
iter acc (GroupName _) = acc
iter acc (HiddenCommand _) = acc
iter acc (CommandData (WrappedCommand c@SuperCommand {})) =
acc ++ concatMap
(render (commandName c ++ " "))
(extractCommands (commandSubCommands c))
iter acc (CommandData c) = acc ++ render "" c
render :: String -> WrappedCommand -> [String]
render prefix (WrappedCommand c) =
[".B darcs " ++ prefix ++ commandName c] ++
map mangle_args (commandExtraArgHelp c) ++
-- In the output, we want each command to be on its own
-- line, but we don't want blank lines between them.
-- AFAICT this can only be achieved with the .br
-- directive, which is probably a GNUism.
[".br"]
-- | As 'synopsis', but make each group a subsection (.SS), and
-- include the help text for each command.
commands :: [String]
commands = foldl iter [] commandControlList
where iter :: [String] -> CommandControl -> [String]
iter acc (GroupName x) = acc ++ [".SS \"" ++ x ++ "\""]
iter acc (HiddenCommand _) = acc
iter acc (CommandData (WrappedCommand c@SuperCommand {})) =
acc ++ concatMap
(render (commandName c ++ " "))
(extractCommands (commandSubCommands c))
iter acc (CommandData c) = acc ++ render "" c
render :: String -> WrappedCommand -> [String]
render prefix (WrappedCommand c) =
[".B darcs " ++ prefix ++ commandName c] ++
map mangle_args (commandExtraArgHelp c) ++
[".RS 4", escape $ commandHelp c, ".RE"]
-- | Now I'm showing off: mangle the extra arguments of Darcs commands
-- so as to use the ideal format for manpages, italic words and roman
-- punctuation.
mangle_args :: String -> String
mangle_args s =
".RI " ++ unwords (map show (groupBy cmp $ map toLower $ gank s))
where cmp x y = not $ xor (isAlphaNum x) (isAlphaNum y)
xor x y = (x && not y) || (y && not x)
gank (' ':'o':'r':' ':xs) = '|' : gank xs
gank (x:xs) = x : gank xs
gank [] = []
environment :: [String]
environment = ".SH ENVIRONMENT" : concat
[(".SS \"" ++ andClauses ks ++ "\"") : map escape ds
| (ks, ds) <- environmentHelp]
escape :: String -> String
escape = minus . bs -- Order is important
where
minus = replace "-" "\\-"
bs = replace "\\" "\\\\"
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace _ _ [] = []
replace find repl s =
if find `isPrefixOf` s
then repl ++ replace find repl (drop (length find) s)
else head s : replace find repl (tail s)
markdownLines :: [String]
markdownLines =
[ "Darcs " ++ version, ""
, "# Commands", ""
, unlines commands
, "# Environment variables"
, "", unlines environment
, "# Patterns"
, "", unlines helpOnMatchers ]
where
environment :: [String]
environment = intercalate [""]
[ renderEnv ks ds | (ks, ds) <- environmentHelp ]
where
renderEnv k d = ("## " ++ (intercalate ", " k)) : "" : d
commands :: [String]
commands = foldl iter [] commandControlList
iter :: [String] -> CommandControl -> [String]
iter acc (GroupName x) = acc ++ ["## " ++ x, ""]
iter acc (HiddenCommand _) = acc
iter acc (CommandData (WrappedCommand c@SuperCommand {})) =
acc ++ concatMap
(render (commandName c ++ " "))
(extractCommands (commandSubCommands c))
iter acc (CommandData c) = acc ++ render "" c
render :: String -> WrappedCommand -> [String]
render prefix (WrappedCommand c) =
[ "### " ++ prefix ++ commandName c
, "", "darcs " ++ prefix ++ commandName c ++ " [OPTION]... " ++
unwords (commandExtraArgHelp c)
, "", commandDescription c
, "", commandHelp c
, "Options:", optionsMarkdown $ commandBasicOptions c
, if null opts2 then ""
else unlines ["Advanced Options:", optionsMarkdown opts2]
]
where opts2 = commandAdvancedOptions c
environmentHelpEditor :: ([String], [String])
environmentHelpEditor = (["DARCS_EDITOR", "DARCSEDITOR", "VISUAL", "EDITOR"],[
"To edit a patch description of email comment, Darcs will invoke an",
"external editor. Your preferred editor can be set as any of the",
"environment variables $DARCS_EDITOR, $DARCSEDITOR, $VISUAL or $EDITOR.",
"If none of these are set, vi(1) is used. If vi crashes or is not",
"found in your PATH, emacs, emacs -nw, nano and (on Windows) edit are",
"each tried in turn."])
environmentHelpPager :: ([String], [String])
environmentHelpPager = (["DARCS_PAGER", "PAGER"],[
"Darcs will sometimes invoke a pager if it deems output to be too long",
"to fit onscreen. Darcs will use the pager specified by $DARCS_PAGER",
"or $PAGER. If neither are set, `less` will be used."])
environmentHelpTimeout :: ([String], [String])
environmentHelpTimeout = (["DARCS_CONNECTION_TIMEOUT"],[
"Set the maximum time in seconds that darcs allows and connection to",
"take. If the variable is not specified the default are 30 seconds. This",
"option only works with curl."])
-- | There are two environment variables that we do not document:
-- - DARCS_USE_ISPRINT: deprecated, use DARCS_DONT_ESCAPE_ISPRINT.
-- - DARCS_TESTING_PREFS_DIR: used by the test suite to tell darcs
-- where to find its configuration files.
|
DavidAlphaFox/darcs
|
src/Darcs/UI/Commands/Help.hs
|
gpl-2.0
| 17,275
| 0
| 19
| 4,548
| 3,419
| 1,907
| 1,512
| 324
| 11
|
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, Rank2Types, RecordWildCards, NamedFieldPuns, DeriveDataTypeable, ScopedTypeVariables, LambdaCase, BangPatterns #-}
module Main
( main
) where
import Control.Concurrent.MVar
import qualified Control.Exception as E
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.Monad (when, join, unless, replicateM_)
import Control.Monad.IO.Class (MonadIO(..))
import Data.CurAndPrev (current)
import Data.IORef
import Data.MRUMemo (memoIO)
import Data.Maybe
import qualified Data.Monoid as Monoid
import Data.Proxy (Proxy(..))
import Data.Store.Db (Db)
import qualified Data.Store.IRef as IRef
import Data.Store.Transaction (Transaction)
import qualified Data.Store.Transaction as Transaction
import Data.Time.Clock (getCurrentTime)
import Data.Typeable (Typeable)
import GHC.Conc (setNumCapabilities, getNumProcessors)
import GHC.Stack (whoCreated)
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.Rendering.OpenGL.GL as GL
import Graphics.UI.Bottle.Main (mainLoopWidget)
import qualified Graphics.UI.Bottle.Main as MainLoop
import Graphics.UI.Bottle.Widget (Widget)
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.EventMapDoc as EventMapDoc
import qualified Graphics.UI.Bottle.Widgets.FlyNav as FlyNav
import qualified Graphics.UI.GLFW as GLFW
import qualified Graphics.UI.GLFW.Utils as GLFWUtils
import Lamdu.Config (Config)
import qualified Lamdu.Config as Config
import Lamdu.Config.Sampler (Sampler)
import qualified Lamdu.Config.Sampler as ConfigSampler
import qualified Lamdu.Data.DbInit as DbInit
import qualified Lamdu.Data.DbLayout as DbLayout
import Lamdu.Data.Export.Codejam (exportFancy)
import qualified Lamdu.Data.Export.JSON as Export
import Lamdu.DataFile (getLamduDir)
import qualified Lamdu.Eval.Manager as EvalManager
import Lamdu.Eval.Results (EvalResults)
import Lamdu.Expr.IRef (ValI)
import Lamdu.Font (FontSize, Fonts(..))
import qualified Lamdu.Font as Font
import Lamdu.GUI.CodeEdit.Settings (Settings(..))
import qualified Lamdu.GUI.CodeEdit.Settings as Settings
import qualified Lamdu.GUI.Main as GUIMain
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import Lamdu.GUI.Zoom (Zoom)
import qualified Lamdu.GUI.Zoom as Zoom
import qualified Lamdu.Opts as Opts
import qualified Lamdu.Style as Style
import qualified Lamdu.VersionControl as VersionControl
import Lamdu.VersionControl.Actions (mUndo)
import qualified System.Directory as Directory
import System.FilePath ((</>))
import qualified System.FilePath as FilePath
import System.IO (hPutStrLn, stderr)
import Prelude.Compat
type T = Transaction
defaultFonts :: Fonts FilePath
defaultFonts =
Fonts defaultFont defaultFont defaultFont defaultFont defaultFont
where
defaultFont = "fonts/Purisa.ttf"
main :: IO ()
main =
do
setNumCapabilities =<< getNumProcessors
Opts.Parsed{_poShouldDeleteDB,_poUndoCount,_poWindowMode,_poCopyJSOutputPath,_poLamduDB,_poWindowTitle} <-
either fail return =<< Opts.get
lamduDir <- maybe getLamduDir return _poLamduDB
let withDB = DbInit.withDB lamduDir
let windowTitle = fromMaybe "Lamdu" _poWindowTitle
if _poShouldDeleteDB
then deleteDB lamduDir
else withDB $
if _poUndoCount > 0
then undoN _poUndoCount
else runEditor windowTitle _poCopyJSOutputPath _poWindowMode
`E.catch` \e@E.SomeException{} -> do
hPutStrLn stderr $ "Main exiting due to exception: " ++ show e
mapM_ (hPutStrLn stderr) =<< whoCreated e
return ()
deleteDB :: FilePath -> IO ()
deleteDB lamduDir =
do
putStrLn "Deleting DB..."
Directory.removeDirectoryRecursive lamduDir
undoN :: Int -> Db -> IO ()
undoN n db =
do
putStrLn $ "Undoing " ++ show n ++ " times"
DbLayout.runDbTransaction db $ replicateM_ n undo
where
undo =
do
actions <- VersionControl.makeActions
fromMaybe (fail "Cannot undo any further") $ mUndo actions
createWindow :: String -> Opts.WindowMode -> IO GLFW.Window
createWindow title mode =
do
monitor <-
GLFW.getPrimaryMonitor
>>= maybe (fail "GLFW: Can't get primary monitor") return
videoModeSize <- GLFWUtils.getVideoModeSize monitor
let createWin = GLFWUtils.createWindow title
case mode of
Opts.FullScreen -> createWin (Just monitor) videoModeSize
Opts.VideoModeSize -> createWin Nothing videoModeSize
Opts.WindowSize winSize -> createWin Nothing winSize
settingsChangeHandler :: EvalManager.Evaluator -> Settings -> IO ()
settingsChangeHandler evaluator settings =
case settings ^. Settings.sInfoMode of
Settings.Evaluation -> EvalManager.start evaluator
_ -> EvalManager.stop evaluator
-- Number of times fonts changed / needed reload
type FontsVersion = Version
data CachedWidgetInput = CachedWidgetInput
{ _cwiFontsVer :: FontsVersion
, _cwiConfig :: Config
, _cwiSize :: Widget.Size
, _cwiFonts :: Fonts Draw.Font
}
instance Eq CachedWidgetInput where
CachedWidgetInput x0 y0 z0 _ == CachedWidgetInput x1 y1 z1 _ =
(x0, y0, z0) == (x1, y1, z1)
exportActions ::
Config -> EvalResults (ValI DbLayout.ViewM) -> GUIMain.ExportActions DbLayout.ViewM
exportActions config evalResults =
GUIMain.ExportActions
{ GUIMain.exportRepl = fileExport Export.fileExportRepl
, GUIMain.exportAll = fileExport Export.fileExportAll
, GUIMain.exportFancy = export (exportFancy evalResults)
, GUIMain.exportDef = fileExport . Export.fileExportDef
, GUIMain.importAll = importAll
}
where
Config.Export{exportPath} = Config.export config
export x = x <&> flip (,) () & return & GUIMain.M
fileExport exporter = exporter exportPath & export
importAll path = Export.fileImportAll path <&> fmap ((,) (pure ())) & GUIMain.M
makeRootWidget ::
Db -> Zoom -> IORef Settings -> EvalManager.Evaluator ->
CachedWidgetInput -> IO (Widget (MainLoop.M Widget.EventResult))
makeRootWidget db zoom settingsRef evaluator input =
do
cursor <-
DbLayout.cursor DbLayout.revisionProps
& Transaction.getP
& DbLayout.runDbTransaction db
globalEventMap <- Settings.mkEventMap (settingsChangeHandler evaluator) config settingsRef
let eventMap = globalEventMap `mappend` Zoom.eventMap zoom (Config.zoom config)
evalResults <- EvalManager.getResults evaluator
settings <- readIORef settingsRef
let env = GUIMain.Env
{ _envEvalRes = evalResults
, _envExportActions =
exportActions config (evalResults ^. current)
, _envConfig = config
, _envSettings = settings
, _envStyle = Style.style config fonts
, _envFullSize = size
, _envCursor = cursor
}
let dbToIO action =
case settings ^. Settings.sInfoMode of
Settings.Evaluation ->
EvalManager.runTransactionAndMaybeRestartEvaluator evaluator action
_ -> DbLayout.runDbTransaction db action
mkWidgetWithFallback dbToIO env
<&> Widget.weakerEvents (eventMap <&> liftIO)
where
CachedWidgetInput _fontsVer config size fonts = input
withMVarProtection :: a -> (MVar (Maybe a) -> IO b) -> IO b
withMVarProtection val =
E.bracket (newMVar (Just val)) (\mvar -> modifyMVar_ mvar (\_ -> return Nothing))
printGLVersion :: IO ()
printGLVersion =
do
ver <- GL.get GL.glVersion
putStrLn $ "Using GL version: " ++ show ver
zoomConfig :: Zoom -> Config -> IO Config
zoomConfig zoom config =
do
factor <- Zoom.getSizeFactor zoom
return config
{ Config.baseTextSize =
Config.baseTextSize config * realToFrac factor
}
runEditor :: String -> Maybe FilePath -> Opts.WindowMode -> Db -> IO ()
runEditor title copyJSOutputPath windowMode db =
do
-- Load config as early as possible, before we open any windows/etc
rawConfigSampler <- ConfigSampler.new
GLFWUtils.withGLFW $ do
win <- createWindow title windowMode
printGLVersion
-- Fonts must be loaded after the GL context is created..
wrapFlyNav <- FlyNav.makeIO Style.flyNav WidgetIds.flyNav
invalidateCacheRef <- newIORef (return ())
let invalidateCache = join (readIORef invalidateCacheRef)
withMVarProtection db $ \dbMVar ->
do
evaluator <-
EvalManager.new EvalManager.NewParams
{ EvalManager.invalidateCache = invalidateCache
, EvalManager.dbMVar = dbMVar
, EvalManager.copyJSOutputPath = copyJSOutputPath
}
zoom <- Zoom.make . (^. _2) =<< GLFWUtils.getDisplayScale win
let configSampler =
ConfigSampler.onEachSample (zoomConfig zoom)
rawConfigSampler
let initialSettings = Settings Settings.defaultInfoMode
settingsRef <- newIORef initialSettings
settingsChangeHandler evaluator initialSettings
(invalidateCacheAction, makeRootWidgetCached) <-
makeRootWidget db zoom settingsRef evaluator
& memoizeMakeWidget
refreshScheduler <- newRefreshScheduler
writeIORef invalidateCacheRef $
do
invalidateCacheAction
scheduleRefresh refreshScheduler
addHelp <- EventMapDoc.makeToggledHelpAdder EventMapDoc.HelpNotShown
mainLoop win refreshScheduler configSampler $ \fontsVer fonts config size ->
makeRootWidgetCached (CachedWidgetInput fontsVer config size fonts)
>>= wrapFlyNav
>>= addHelp (Style.help (Font.fontHelp fonts) (Config.help config)) size
newtype RefreshScheduler = RefreshScheduler (IORef Bool)
newRefreshScheduler :: IO RefreshScheduler
newRefreshScheduler = newIORef False <&> RefreshScheduler
isRefreshScheduled :: RefreshScheduler -> IO Bool
isRefreshScheduled (RefreshScheduler ref) = atomicModifyIORef ref $ \r -> (False, r)
scheduleRefresh :: RefreshScheduler -> IO ()
scheduleRefresh (RefreshScheduler ref) = writeIORef ref True
type Version = Int
loopWhileException :: forall a e. E.Exception e => Proxy e -> (Version -> IO a) -> IO a
loopWhileException _ act = loop 0
where
loop !n =
(act n <&> Just)
`E.catch` (\(_ :: e) -> return Nothing)
>>= \case
Nothing -> loop (n+1)
Just res -> return res
prependConfigPath :: ConfigSampler.Sample Config -> Fonts FilePath -> Fonts FilePath
prependConfigPath sample =
Lens.mapped %~ (dir </>)
where
dir = FilePath.takeDirectory (ConfigSampler.sFilePath sample)
assignFontSizes ::
ConfigSampler.Sample Config -> Fonts FilePath -> Fonts (FontSize, FilePath)
assignFontSizes sample fonts =
fonts
<&> (,) baseTextSize
& Font.lfontHelp . _1 .~ helpTextSize
where
baseTextSize = Config.baseTextSize config
helpTextSize = Config.helpTextSize (Config.help config)
config = ConfigSampler.sValue sample
curSampleFonts :: ConfigSampler.Sample Config -> Fonts (FontSize, FilePath)
curSampleFonts sample =
ConfigSampler.sValue sample
& Config.fonts
& prependConfigPath sample
& assignFontSizes sample
data FontChanged = FontChanged
deriving (Show, Typeable)
instance E.Exception FontChanged
withFontLoop :: Sampler Config -> (FontsVersion -> IO () -> Fonts Draw.Font -> IO a) -> IO a
withFontLoop configSampler act =
loopWhileException (Proxy :: Proxy FontChanged) $ \fontsVer -> do
sample <- ConfigSampler.getSample configSampler
let absFonts = curSampleFonts sample
let defaultFontsAbs =
prependConfigPath sample defaultFonts & assignFontSizes sample
let throwIfFontChanged =
do
newAbsFonts <- ConfigSampler.getSample configSampler <&> curSampleFonts
when (newAbsFonts /= absFonts) $ E.throwIO FontChanged
let runAct = act fontsVer throwIfFontChanged
res <-
withFont (const (return Nothing)) absFonts $ \fonts ->
Just <$> runAct fonts
case res of
Nothing -> withFont E.throwIO defaultFontsAbs runAct
Just success -> return success
where
withFont err = Font.with (\x@E.SomeException{} -> err x)
mainLoop ::
GLFW.Window -> RefreshScheduler -> Sampler Config ->
(FontsVersion -> Fonts Draw.Font -> Config -> Widget.Size ->
IO (Widget (MainLoop.M Widget.EventResult))) -> IO ()
mainLoop win refreshScheduler configSampler iteration =
withFontLoop configSampler $ \fontsVer checkFonts fonts ->
do
lastVersionNumRef <- newIORef =<< getCurrentTime
let getConfig =
ConfigSampler.getSample configSampler
<&> Style.mainLoopConfig . ConfigSampler.sValue
let makeWidget size =
do
config <-
ConfigSampler.getSample configSampler
<&> ConfigSampler.sValue
iteration fontsVer fonts config size
let tickHandler =
do
checkFonts
curVersionNum <-
ConfigSampler.getSample configSampler
<&> ConfigSampler.sVersion
configChanged <- atomicModifyIORef lastVersionNumRef $ \lastVersionNum ->
(curVersionNum, lastVersionNum /= curVersionNum)
if configChanged
then return True
else isRefreshScheduled refreshScheduler
mainLoopWidget win tickHandler makeWidget getConfig
memoizeMakeWidget ::
(MonadIO m, Eq a) =>
(a -> IO (Widget (m b))) -> IO (IO (), a -> IO (Widget (m b)))
memoizeMakeWidget mkWidget =
do
widgetCacheRef <- newIORef =<< memoIO mkWidget
let invalidateCache = writeIORef widgetCacheRef =<< memoIO mkWidget
return
( invalidateCache
, \x ->
readIORef widgetCacheRef
>>= ($ x)
<&> Widget.events %~ (<* liftIO invalidateCache)
)
rootCursor :: Widget.Id
rootCursor = WidgetIds.fromUUID $ IRef.uuid $ DbLayout.panes DbLayout.codeIRefs
mkWidgetWithFallback ::
(forall a. T DbLayout.DbM a -> IO a) ->
GUIMain.Env -> IO (Widget (MainLoop.M Widget.EventResult))
mkWidgetWithFallback dbToIO env =
do
(isValid, widget) <-
dbToIO $
do
candidateWidget <- makeMainGui dbToIO env
(isValid, widget) <-
if Widget.isFocused candidateWidget
then return (True, candidateWidget)
else do
finalWidget <-
env & GUIMain.envCursor .~ rootCursor & makeMainGui dbToIO
Transaction.setP (DbLayout.cursor DbLayout.revisionProps) rootCursor
return (False, finalWidget)
unless (Widget.isFocused widget) $
fail "Root cursor did not match"
return (isValid, widget)
unless isValid $ putStrLn $ "Invalid cursor: " ++ show (env ^. GUIMain.envCursor)
widget
& Widget.backgroundColor
(Config.layerMax (Config.layers config))
["background"] (bgColor isValid config)
& return
where
config = env ^. GUIMain.envConfig
bgColor False = Config.invalidCursorBGColor
bgColor True = Config.backgroundColor
makeMainGui ::
(forall a. T DbLayout.DbM a -> IO a) ->
GUIMain.Env -> T DbLayout.DbM (Widget (MainLoop.M Widget.EventResult))
makeMainGui dbToIO env =
GUIMain.make env rootCursor
<&> Widget.events %~ \act ->
act ^. GUIMain.m
& Lens.mapped %~ (>>= _2 attachCursor)
<&> dbToIO
& join
<&> uncurry MainLoop.EventResult & MainLoop.M
where
attachCursor eventResult =
do
eventResult ^. Widget.eCursor
& Monoid.getLast
& maybe (return ())
(Transaction.setP (DbLayout.cursor DbLayout.revisionProps))
& (eventResult <$)
|
da-x/lamdu
|
Lamdu/Main.hs
|
gpl-3.0
| 17,332
| 0
| 22
| 5,082
| 4,258
| 2,204
| 2,054
| -1
| -1
|
{-# OPTIONS -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Graphics.UI.Bottle.Widgets.EventMapDoc(make, addHelp, makeToggledHelpAdder) where
import Data.IORef (newIORef, readIORef, modifyIORef)
import Data.List.Utils (groupOn, sortOn)
import Data.Monoid (mappend)
import Graphics.UI.Bottle.EventMap (EventMap)
import Graphics.UI.Bottle.SizeRange (srMinSize)
import Graphics.UI.Bottle.Sized (Sized(..))
import Graphics.UI.Bottle.Widget (Widget)
import qualified Data.ByteString.Char8 as SBS8
import qualified Data.Tuple as Tuple
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.UI.Bottle.Animation as Anim
import qualified Graphics.UI.Bottle.EventMap as E
import qualified Graphics.UI.Bottle.Sized as Sized
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.GridView as GridView
import qualified Graphics.UI.Bottle.Widgets.Spacer as Spacer
import qualified Graphics.UI.Bottle.Widgets.TextView as TextView
groupByKey :: Eq b => (a -> (b, c)) -> [a] -> [(b, [c])]
groupByKey f =
map perGroup . groupOn fst . map f
where
perGroup xs = (fst (head xs), map snd xs)
make :: EventMap a -> TextView.Style -> Anim.AnimId -> Sized Anim.Frame
make eventMap style animId =
GridView.make . map toRow . groupByKey Tuple.swap . sortOn snd . E.eventMapDocs $ eventMap
where
textView uniq str =
TextView.make style str $
Anim.joinId animId (map SBS8.pack [str, uniq])
toRow (eventDoc, eventKeys) =
[ GridView.make [concatMap (: [Spacer.makeHorizontal 8]) (map (textView "key") eventKeys)]
, textView "doc" eventDoc]
addHelp :: TextView.Style -> Widget f -> Widget f
addHelp style =
Widget.atMkSizeDependentWidgetData f
where
f mkSizeDependentWidgetData size = Widget.atSdwdFrame (mappend docFrame) userIO
where
rSize = srMinSize (requestedSize eventMapDoc)
eventMapDoc = make eventMap style ["help box"]
transparency = Draw.Color 1 1 1
docFrame =
(Anim.onImages . Draw.tint . transparency) 0.8 .
Anim.onDepth (subtract 10) .
Anim.translate (size - rSize) .
Anim.backgroundColor ["help doc background"] 1 (Draw.Color 0.3 0.2 0.1 1) rSize $
Sized.fromSize eventMapDoc size
eventMap = Widget.sdwdEventMap userIO
userIO = mkSizeDependentWidgetData size
makeToggledHelpAdder :: [E.EventType] -> TextView.Style -> IO (Widget IO -> IO (Widget IO))
makeToggledHelpAdder overlayDocKeys style = do
showingHelpVar <- newIORef True
let
toggle = modifyIORef showingHelpVar not
addToggleEventMap doc =
Widget.strongerEvents $
Widget.actionEventMap overlayDocKeys doc toggle
return $ \widget -> do
showingHelp <- readIORef showingHelpVar
return $
if showingHelp
then addHelp style $ addToggleEventMap "Hide Key Bindings" widget
else addToggleEventMap "Show Key Bindings" widget
|
nimia/bottle
|
bottlelib/Graphics/UI/Bottle/Widgets/EventMapDoc.hs
|
gpl-3.0
| 2,939
| 0
| 17
| 546
| 873
| 481
| 392
| 62
| 2
|
-- Copyright 2012 Justus Sagemüller.
--
-- This file is part of the Cqtx library.
-- This library is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with this library. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- {-# LANGUAGE FunctionalDependencies#-}
{-# LANGUAGE FlexibleInstances #-}
-- {-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : CodeGen.CXX.Cqtx.PhqFn
-- Copyright : (c) Justus Sagemüller 2012
-- License : GPL v3
--
-- Maintainer : (@) sagemuej $ smail.uni-koeln.de
-- Stability : experimental
-- Portability : portable
--
-- While the cqtx library provides quite versatile and /in principle/ very
-- low-requirement fitting of general physical functions (namely without the
-- need for any gradients etc.), in practise this is hampered by the cumbersomeness
-- of defining the fittable_phmsqfn subclasses. The macros in @fitfnmacros.h@ can
-- only partially alleviate this: due to the limits of the C preprocessor, most of
-- the calculation load needs to be done in also cumbersome C++ templates or,
-- more likely, at runtime. At the moment, this is implemented rather poorly, in
-- particular the almost bogosort-quality dimensional analysis.
--
-- This Haskell module does not claim to be an optimal solution, but it produces
-- significantly better code than the CPP macros, with very safe and easy invocation.
-- In the future this might become a lot more powerful, since it is also possible
-- to automatically create highly optimised specialised versions of the functions, e.g.
-- squaredistance-calculation on CUDA.
--
module CodeGen.CXX.Cqtx.PhqFn( phqFn, phqFlatMultiIdFn, phqSingleIdMultiFn
-- * General Cqtx code generation
, module CodeGen.CXX.Code
, CqtxCode
, CqtxConfig, withDefaultCqtxConfig
, PhqfnDefining(..)
-- * Length-indexed lists
, IsolenEnd(P), IsolenCons(..)
) where
import CodeGen.CXX.Code
import Control.Monad hiding (forM_)
import Control.Monad.Writer hiding (forM_)
import Control.Monad.Reader hiding (forM_)
import Control.Arrow
import Data.Function
import Data.List (sort, sortBy, intersperse, intercalate, group, find)
import Data.Monoid
import Data.Ratio
import Data.Maybe
import Data.Tuple
import Data.Foldable
import Prelude hiding (foldr, concat, sum, product, any, elem)
-- import Data.Hashable
-- import Data.HashMap
-- | Create a physical function that can be fitted to measured data using the cqtx
-- algorithms such as @evolution_minimizer@. The invocation is similar to the
-- primitive CPP macros, but type-safe and allows full Haskell syntax in the
-- definition – though this can of course be exploited only so much, since phqfns
-- are very limited in their abilities. To make sure these limits are maintained
-- we use universally-quantised arguments (which also suits the implementation very
-- well).
--
-- For example, the standard gaussian peak
-- @𝐴⋅exp(-(𝑥-𝑥₀)²/(2⋅𝜎²))@
-- could be defined thus:
--
-- > phqFn "gaussPeak" ("x":."x_0":."\\sigma":."A":.P)
-- > (\ ( x :. x0 :. sigma :. a :.P)
-- > -> let q = (x-x0)/sigma in a * exp(-0.5 * q^2) )
--
-- The use of the type-determined–length lists makes it impossible to accidentally
-- give different numbers of parameter bindings and -labels.
--
-- Avoidance of duplicate calculation, as well as rudimentary optimisation, is taken
-- care for by this preprocessor.
phqFn :: forall paramsList . IsolenList paramsList
=> String -- ^ Name of the resulting phqFn C++ object
-> paramsList String -- ^ Default labels of the parameters
-> (forall x. PhqfnDefining x
=> paramsList x -> x) -- ^ Function definition, as a lambda
-> CqtxCode() -- ^ C++ class and object code for a cqtx fittable physical function corresponding to the given definition.
phqFn fnName sclLabels function
= phqFlatMultiIdFn fnName sclLabels P $ \P -> (P, \scl P -> function scl)
phqSingleIdMultiFn :: forall scalarPrmsList indexedPrmsList
. (IsolenList scalarPrmsList, IsolenList indexedPrmsList)
=> String
-> scalarPrmsList String
-> (String, Maybe Int)
-> ( PhqVarIndexer ->
( indexedPrmsList String
, forall x. PhqfnDefining x
=> scalarPrmsList x -> indexedPrmsList (IdxablePhqDefVar x) -> x) )
-> CqtxCode()
phqSingleIdMultiFn fnName' sclLabels indexer indexedFn
= phqFlatMultiIdFn fnName' sclLabels (indexer:.P) $
\(i:.P) -> first (fmap (,i)) $ indexedFn i
phqFlatMultiIdFn :: forall scalarPrmsList indexerList indexedPrmsList
. (IsolenList scalarPrmsList, IsolenList indexerList, IsolenList indexedPrmsList)
=> String
-> scalarPrmsList String
-> indexerList (String, Maybe Int)
-> ( indexerList PhqVarIndexer ->
( indexedPrmsList (String, PhqVarIndexer)
, forall x. PhqfnDefining x
=> scalarPrmsList x -> indexedPrmsList (IdxablePhqDefVar x) -> x) )
-> CqtxCode()
phqFlatMultiIdFn fnName' sclLabels ixerLabels indexedFn = ReaderT $ codeWith where
codeWith config = do
cxxLine $ " COPYABLE_PDERIVED_CLASS(/*"
cxxLine $ "class*/"++className++",/*: public */fittable_phmsqfn) {"
helpers <- cxxIndent 2 $ do
rangesDecl
offsetMgr
dimFetchDeclares
cxxLine $ " public:"
cxxIndent 2 $ do constructor
paramExamples helpers
functionEval
cxxLine $ "} " ++ (guard (null rangeConstsNeeded) >> fnName) ++ ";"
where
-- function :: forall x . PhqfnDefining x
-- => scalarPrmsList x -> indexedPrmsList (IdxablePhqDefVar x) -> x
ixaParams :: indexedPrmsList (String, PhqVarIndexer)
(ixaParams, function) = indexedFn indexers
fnResultTerm :: PhqFuncTerm
fnResultTerm = function (fmap (\i->PhqFnParameter $ show i) scalarParamIds)
(perfectZipWith (\vni (vnm, PhqVarIndexer ix inm)
-> IdxablePhqDefVar $ q vni vnm ix inm)
offsetConstsNeeded ixaParams)
where q vni vnm ix inm (PhqVarIndexer ix' inm')
| ix'==ix = PhqFnParameter $ vni ++ " + "
++ indizesPrefix ++ makeSafeCXXIdentifier inm
| otherwise = error
$ "In HsMacro-defined phqfunction '"++fnName++"':\n\
\ Using wrong indexer '"++inm'++"' (not adapted range!) \
\for indexing variable '"++vnm++"'.\n\
\ Correct indexer would be '"++inm++"'."
fnDimTrace :: DimTracer
fnDimTrace = function (fmap (VardimVar . PhqIdf) scalarParamIds)
(fmap (\i -> IdxablePhqDefVar
$ \_ -> VardimVar $ PhqIdf i) ixableParamIds)
functionEval :: CXXCode()
functionEval = do
cxxLine $ "auto operator()(const measure& parameters)const -> physquantity {"
cxxIndent 2 $ do
-- cxxLine $ "std::cout << \"evaluate "++fnName++" with parameters\\n\""
-- cxxLine $ " << parameters << std::endl;"
result <- cqtxTermImplementation "parameters" fnResultTerm
cxxSurround "return "result";"
cxxLine $ "}"
paramExamples :: [(Int,CXXExpression)] -> CXXCode()
paramExamples helpers = do
cxxLine $ "auto example_parameterset( const measure& constraints\n\
\ , const physquantity& desiredret)const override -> measure {"
cxxIndent 2 $ do
cxxLine $ "measure example;"
forM_ helpers $ \(n,helper) -> if n < nScalarParams
then do
cxxLine $ "if(!constraints.has(*argdrfs["++show n++"]))"
cxxLine $ " example.let(*argdrfs["++show n++"]) = "
++helper++"(constraints, desiredret);"
else do
let n' = n - nScalarParams
(idxerId, PhqVarIndexer _ i) = ixaParams !!@ n'
idxerRange = ixableParamRanges !!@ n'
offsetQ = offsetConstsNeeded !!@ n'
cxxLine $ "for(unsigned "++i++"=0\
\; "++i++"<"++idxerRange
++"; ++"++i++") {"
cxxIndent 2 $ do
let locatei = "argdrfs["++offsetQ++" + "++i++"]"
cxxLine $ "if(!constraints.has(*"++locatei++")) {"
cxxIndent 2 $ do
cxxLine $ "example.let(*"++locatei++")\
\ = "++helper++"(constraints, desiredret);"
cxxLine $ "}"
cxxLine $ "}"
cxxLine $ "return example;"
cxxLine $ "}"
dimFetchDeclares :: CXXCode [(Int, CXXExpression)]
dimFetchDeclares = forM ( map (False,) (toList scalarParamIds)
++ map (True, ) (toList ixableParamIds) )
$ \(needsIndexer, prmId) -> do
let functionName = "example_"++(guard needsIndexer >> "multi")
++"parameter"++show prmId++"value"
let resultOptions = relevantDimExprsFor (PhqIdf prmId) fnDimTrace
cxxLine $ "auto "++functionName++"( const measure& constraints\n\
\ , const physquantity& desiredret)const -> physquantity {"
cxxIndent 2 $ do
forM_ resultOptions $ \decomp -> do
cxxLine $ "{"
cxxIndent 2 $ do
let refMultiParamVarb n = "reference_for_multiparam_"++show n
cxxLine $ "bool thisdecomp_failed = false;"
forM_ (fixValDecomposition decomp) $ \(e,_) -> case e of
PhqFnParamVal (PhqIdf n) -> if n < nScalarParams
then do
cxxLine $ "if(!constraints.has(*argdrfs["++show n++"]))"
cxxLine $ " thisdecomp_failed = true;"
else do
let n' = n - nScalarParams
(idxerId, PhqVarIndexer _ i) = ixaParams !!@ n'
idxerRange = ixableParamRanges !!@ n'
offsetQ = offsetConstsNeeded !!@ n'
matchFound = "forany_"++i++"_pfound"
cxxLine $ "physquantity "++refMultiParamVarb n'++";"
cxxLine $ "{"
cxxIndent 2 $ do
cxxLine $ "bool "++matchFound++" = false;"
cxxLine $ "for(unsigned "++i++"=0\
\; "++i++"<"++idxerRange
++"; ++"++i++") {"
cxxIndent 2 $ do
let locatei = "argdrfs["++offsetQ++" + "++i++"]"
cxxLine $ "if(constraints.has(*"++locatei++")) {"
cxxIndent 2 $ do
cxxLine $ matchFound++" = true;"
cxxLine $ refMultiParamVarb n'
++" = "++locatei++"(constraints);"
cxxLine $ "break;"
cxxLine $ "}"
cxxLine $ "}"
cxxLine $ "if(!"++matchFound++") thisdecomp_failed = true;"
cxxLine $ "}"
_ -> return ()
cxxLine $ "if(!thisdecomp_failed) {"
cxxIndent 2 $ do
let q (PhqIdf n)
| n < nScalarParams = PhqFnParameter $ show n
| n' <-n-nScalarParams = PhqFnTempRef minBound $ refMultiParamVarb n'
result <- cqtxTermImplementation "constraints" $
calculateDimExpression q decomp
cxxSurround "physquantity result = " result ";"
cxxLine $ "return result.werror(result);"
cxxLine $ "}"
cxxLine $ "}"
cxxLine $ "std::cerr << \"Insufficient constraints given to determine the physical dimension\\n\
\ of parameter \\\"\" << *argdrfs["++show prmId++"] << \"\\\"\
\ in phqfn '"++fnName++"'.\\n Sufficient constraint choices would be:\\n\";"
forM_ resultOptions $ \(DimExpression decomp) -> do
cxxLine $ "std::cerr<<\" \"" ++ concat (intersperse"<<','"$
[ case fixv of
PhqDimlessConst -> ""
PhqFnParamVal (PhqIdf j) -> "<<miniTeX(*argdrfs["++show j++"])"
PhqFnResultVal -> "<<\"<function result>\""
| (fixv,_) <- decomp ]) ++ " << std::endl;"
cxxLine $ "abort();"
cxxLine $ "}"
return (prmId,functionName)
rangesDecl :: CXXCode()
rangesDecl = do
when (not $ null rangeConstsNeeded) .
cxxLine $ "unsigned "
++ intercalate ", " rangeConstsNeeded ++ ";"
when (not . null $ toList offsetConstsNeeded) .
cxxLine $ "unsigned "
++ intercalate ", " (toList offsetConstsNeeded) ++ ";"
rangeConstsNeeded :: [CXXExpression]
rangeConstsNeeded = map ( (indizesPrefix++) . (++indexRangePostfix)
. makeSafeCXXIdentifier . fst )
. filter ( isNothing . snd )
$ toList ixerLabels
offsetConstsNeeded :: indexedPrmsList CXXExpression
offsetConstsNeeded = fmap ( (ixablePPrefix++) . (++ixaOffsetPostfix)
. makeSafeCXXIdentifier . fst )
ixaParams
className
| null rangeConstsNeeded = fnName++"Function"
| otherwise = fnName
fnName = makeSafeCXXIdentifier fnName'
offsetMgr :: CXXCode()
offsetMgr = do
cxxLine $ "void manage_paramarr_offsets() {"
cxxIndent 2 $ do
cxxLine $ "unsigned stackp = "++show(isoLength scalarParamIds)++";"
forM_ (perfectZip offsetConstsNeeded ixableParamRanges)
$ \(osc, rng) -> do
cxxLine $ osc ++ " = stackp;"
cxxLine $ "stackp += " ++ rng ++ ";"
cxxLine $ "argdrfs.resize(stackp);"
cxxLine $ "}"
constructor :: CXXCode()
constructor = do
cxxLine $ className ++"("++args++")"++initialisers++" {"
cxxIndent 2 $ do
cxxLine $ "manage_paramarr_offsets();"
forM_ idxedDefaultLabels $ \(n,label) ->
cxxLine $ "argdrfs["++show n++"] = "++show label++";"
forM_ (perfectZip3 ixaParams ixableParamRanges offsetConstsNeeded)
$ \((ixaLbl, (PhqVarIndexer _ ixn)), rangeq, offsetQ) -> do
cxxLine $ "for (unsigned "++ixn++"=0\
\; "++ixn++" < "++rangeq
++"; ++"++ixn++")"
cxxIndent 2 $ do
cxxLine $ "argdrfs["++offsetQ++" + "++ixn++"] = "
++show ixaLbl++" + LaTeX_subscript("++ixn++");"
cxxLine $ "}"
where cstrArgs = rangeConstsNeeded
args = intercalate ", " $ map ("unsigned "++) cstrArgs
initialisers
| null $ toList ixableParamRanges = ""
| otherwise = "\n : "
++ intercalate ", " ( map (\a -> a++"("++a++")" ) cstrArgs )
indexers :: indexerList PhqVarIndexer
indexers = perfectZipWith PhqVarIndexer (enumFrom' 0) $ fmap fst ixerLabels
scalarParamIds :: scalarPrmsList Int
scalarParamIds = enumFrom' 0
ixableParamIds :: indexedPrmsList Int
ixableParamIds = enumFrom' nScalarParams
ixableParamRanges :: indexedPrmsList CXXExpression
ixableParamRanges = fmap (rngFind . snd) ixaParams
where rngFind (PhqVarIndexer ix _)
= case ixerLabels !!@ ix of
(_, Just n) -> show n
(name, _ ) -> indizesPrefix ++ makeSafeCXXIdentifier name
++ indexRangePostfix
idxedDefaultLabels = perfectZip scalarParamIds sclLabels
nScalarParams = isoLength scalarParamIds
indizesPrefix, ixablePPrefix, indexRangePostfix, ixaOffsetPostfix :: CXXExpression
indizesPrefix = "paramindex_"
ixablePPrefix = "ixaparam_"
indexRangePostfix = "_range"
ixaOffsetPostfix = "_offset"
data PhqIdf = PhqIdf Int deriving (Eq, Ord, Show)
argderefv :: CXXExpression -> CXXExpression -> String
argderefv paramSource n = "argdrfs["++n++"]("++paramSource++")"
data DimTracer = DimlessConstant (Maybe Rational)
| VardimVar PhqIdf
| DimEqualities [(DimTracer,DimTracer)] -- pairs of expressions that should have equal phys-dimension, but not necessarily related to the result
[DimTracer] -- expressions that should have the same phys-dimension as the result
| DimtraceProduct [DimTracer]
| DimtracePower DimTracer Rational
deriving(Show)
unknownDimlessConst :: DimTracer
unknownDimlessConst = DimlessConstant Nothing
beDimLess :: DimTracer -> DimTracer
beDimLess a = DimEqualities [(a, unknownDimlessConst)] [unknownDimlessConst]
biBeDimLess :: DimTracer -> DimTracer -> DimTracer
biBeDimLess a b = DimEqualities (map(,unknownDimlessConst)[a,b]) [unknownDimlessConst]
instance Num DimTracer where
fromInteger = DimlessConstant . Just . fromInteger
a + b = DimEqualities [(a,b)] [a,b]
a - b = DimEqualities [(a,b)] [a,b]
DimtraceProduct l * tr = DimtraceProduct (tr:l)
tr * DimtraceProduct l = DimtraceProduct (tr:l)
a * b = DimtraceProduct [a, b]
negate = id
abs = id
signum a = DimEqualities [(a,a)] [unknownDimlessConst]
instance Fractional DimTracer where
fromRational = DimlessConstant . Just
DimtraceProduct l / tr = DimtraceProduct (recip tr : l)
a / b = DimtraceProduct [a, recip b]
recip a = DimtracePower a (-1)
instance Floating DimTracer where
pi = unknownDimlessConst
exp = beDimLess; log = beDimLess
sqrt a = DimtracePower a (1/2)
a**(DimlessConstant (Just b)) = DimtracePower a b
a**b = biBeDimLess a b
logBase = biBeDimLess
sin = beDimLess; cos = beDimLess; tan = beDimLess
asin = beDimLess; acos = beDimLess; atan = beDimLess
sinh = beDimLess; cosh = beDimLess; tanh = beDimLess
asinh = beDimLess; acosh = beDimLess; atanh = beDimLess
data PhqFixValue = PhqDimlessConst
| PhqFnParamVal PhqIdf
| PhqFnResultVal
deriving(Eq, Ord, Show)
newtype DimExpression = DimExpression { fixValDecomposition :: [(PhqFixValue, Rational)] }
deriving(Eq, Ord, Show)
expExpMap :: (Rational -> Rational) -> DimExpression -> DimExpression
expExpMap f (DimExpression l) = DimExpression[ (a,f r) | (a,r)<-l ]
invDimExp :: DimExpression -> DimExpression
invDimExp = expExpMap negate
primDimExpr :: PhqFixValue -> DimExpression
primDimExpr v = DimExpression[(v,1)]
dimExpNormalForm :: DimExpression -> DimExpression -- DimExpression must always be normalised to this form
dimExpNormalForm (DimExpression l) = DimExpression . reduce . sortf $ l
where sortf = sortBy (compare`on`fst)
reduce ((PhqDimlessConst,_):l') = reduce l'
reduce ((a,r):β@(b,s):l')
| a==b = reduce $ (a,r+s):l'
| otherwise = (a,r) : reduce (β:l')
reduce l' = l'
instance Monoid DimExpression where
mempty = DimExpression[]
mappend (DimExpression a) (DimExpression b) = dimExpNormalForm $ DimExpression(a++b)
mconcat l = dimExpNormalForm . DimExpression $ l >>= fixValDecomposition
dimExprnComplexity :: DimExpression -> Integer
dimExprnComplexity (DimExpression l) = sum $ map complexity l
where complexity (_, fr) = abs(denominator fr) + abs(numerator fr - 1)
compareDimsBasis :: DimExpression -> DimExpression -> Ordering
compareDimsBasis (DimExpression l) (DimExpression r)
= comp (map fst l) (map fst r)
where comp [] [] = EQ
comp _ [] = GT
comp [] _ = LT
comp (l:ls) (r:rs)
| l<r = GT
| l>r = LT
| l==r = comp ls rs
strictlySimplerDimsBasis :: DimExpression -> DimExpression -> Bool
strictlySimplerDimsBasis (DimExpression l) (DimExpression r)
= comp (map fst l) (map fst r)
where comp _ [] = False
comp [] _ = True
comp (l:ls) (r:rs)
| l<r = False
| l>r = comp (l:ls) rs
| l==r = comp ls rs
traceAsValue :: DimTracer -> [DimExpression]
traceAsValue (DimlessConstant _) = return mempty
traceAsValue (VardimVar a) = return (primDimExpr $ PhqFnParamVal a)
traceAsValue (DimEqualities _ v) = v >>= traceAsValue
traceAsValue (DimtraceProduct l) = map mconcat . sequence $ map traceAsValue l
traceAsValue (DimtracePower a q) = map (expExpMap (q*)) $ traceAsValue a
(//-) :: DimExpression -> DimExpression -> DimExpression
a //- b = a <> invDimExp b
extractFixValExp :: PhqFixValue -> DimExpression -> (Rational, DimExpression)
extractFixValExp v = (\(a,b)->(a,DimExpression b)) . go id . fixValDecomposition
where go acc (t@(w,r):l)
| v==w = (r, acc l)
| v>w = go (acc.(t:)) l
go acc e = (0, acc e)
nubDimExprs :: [DimExpression] -> [DimExpression]
nubDimExprs = map head . group . sort
dimExpressionsFor :: PhqIdf -> DimTracer -> [DimExpression]
dimExpressionsFor idf e = go e $ primDimExpr PhqFnResultVal
where go :: DimTracer -> DimExpression -> [DimExpression]
go (DimEqualities mutualEqs resEqs) rev
= nubDimExprs $ ((`go`rev) =<< resEqs) ++ ( do
(ida,idb) <- mutualEqs
(go idb =<< traceAsValue ida)
++ (go ida =<< traceAsValue idb) )
go e@(DimtraceProduct l) rev = nubDimExprs $ do
way <- l
value <- traceAsValue way
invprod <- map invDimExp $ traceAsValue e
go way $ rev<>invprod<>value
go (DimtracePower p q) rev = go p $ expExpMap(/q) rev
go rest rev = do
value <- traceAsValue rest
let (q,p) = extractFixValExp (PhqFnParamVal idf) $ value //- rev
guard (q /= 0)
[expExpMap(/(-q))p]
relevantDimExprsFor :: PhqIdf -> DimTracer -> [DimExpression]
relevantDimExprsFor idf = prune . cplxtySort . dimExpressionsFor idf
where cplxtySort = sortBy (compare `on` negate . dimExprnComplexity)
prune [] = []
prune (e:es)
| any(`strictlySimplerDimsBasis`e)es = prune es
| otherwise = e : prune es
newtype CXXFunc = CXXFunc { wrapCXXFunc :: CXXExpression -> CXXExpression }
newtype CXXInfix = CXXInfix { wrapCXXInfix :: CXXExpression -> CXXExpression -> CXXExpression }
instance Eq CXXFunc where
CXXFunc f==CXXFunc g = f""==g""
instance Eq CXXInfix where
CXXInfix f==CXXInfix g = ""`f`""==""`g`""
cxxFunction :: CXXExpression -> CXXFunc
cxxFunction s = CXXFunc $ \e -> s++"("++e++")"
cxxInfix :: CXXExpression -> CXXInfix
cxxInfix s = CXXInfix $ \e1 e2 -> "("++e1++s++e2++")"
type PhysicalCqtxConst = String
data PhqFuncTerm = PhqFnDimlessConst Double
| PhqFnPhysicalConst PhysicalCqtxConst
| PhqFnTempRef Int CXXExpression
| PhqFnParameter
CXXExpression -- not the parameter itself, but an expression for its /index/ in the argdrfs array.
| PhqFnFuncApply CXXFunc PhqFuncTerm
| PhqFnInfixApply CXXInfix PhqFuncTerm PhqFuncTerm
| PhqFnInfixFoldOverIndexer PhqVarIndexer
CXXInfix
PhqFuncTerm -- init
PhqFuncTerm -- summand
deriving (Eq)
cxxFuncPhqApply :: CXXExpression -> PhqFuncTerm -> PhqFuncTerm
cxxFuncPhqApply s = PhqFnFuncApply $ cxxFunction s
cxxInfixPhqApply :: CXXExpression -> PhqFuncTerm -> PhqFuncTerm -> PhqFuncTerm
cxxInfixPhqApply s = PhqFnInfixApply $ cxxInfix s
isPrimitive :: PhqFuncTerm -> Bool
isPrimitive (PhqFnDimlessConst _) = True
isPrimitive (PhqFnPhysicalConst _) = True
isPrimitive (PhqFnParameter _) = True
isPrimitive _ = False
instance Num PhqFuncTerm where
fromInteger = PhqFnDimlessConst . fromInteger
(+) = cxxInfixPhqApply"+"
(-) = cxxInfixPhqApply"-"
a*(PhqFnDimlessConst 1) = a
(PhqFnDimlessConst 1)*b = b
a*b
| a==b = PhqFnFuncApply (CXXFunc $ \e -> "("++e++").squared()") a
| otherwise = cxxInfixPhqApply"*" a b
negate = cxxFuncPhqApply"-"
abs = cxxFuncPhqApply"abs"
signum = cxxFuncPhqApply"sgn"
instance Fractional PhqFuncTerm where
fromRational = PhqFnDimlessConst . fromRational
(/) = cxxInfixPhqApply"/"
recip = cxxFuncPhqApply"inv"
instance Floating PhqFuncTerm where
pi = PhqFnDimlessConst pi
exp = cxxFuncPhqApply"exp"
log = cxxFuncPhqApply"ln"
sqrt = cxxFuncPhqApply"sqrt"
a**(PhqFnDimlessConst 1) = a
a**(PhqFnDimlessConst x) = PhqFnFuncApply
(CXXFunc $ \base -> "(("++base++").to("++show x++"))") a
a**x = exp(log a*x)
sin = cxxFuncPhqApply"sin"
cos = cxxFuncPhqApply"cos"
tan = cxxFuncPhqApply"tan"
tanh = cxxFuncPhqApply"tanh"
asin = error "asin of physquantities not currently implemented."
acos = error "acos of physquantities not currently implemented."
atan = error "atan of physquantities not currently implemented."
sinh = error "sinh of physquantities not currently implemented."
cosh = error "cosh of physquantities not currently implemented."
asinh = error "asinh of physquantities not currently implemented."
acosh = error "acosh of physquantities not currently implemented."
atanh = error "atanh of physquantities not currently implemented."
-- 'seqPrunePhqFuncTerm' could be implemented much more efficiently by replacing
-- the lists with hash tables. This has low priority, since any function complicated
-- enough for this to take noteworthy time would always take yet a lot more time
-- when used with the cqtx algorithms.
-- instance Hashable PhqFuncTerm where
-- hash (PhqFnDimlessConst a) = hash"DimlessConst"`combine`hash a
-- hash (PhqFnPhysicalConst a) = hash"PhysicalConst"`combine`hash a
-- hash (PhqFnParameter a) = hash"Parameter"`combine`hash a
-- hash (PhqFnFuncApply f a) = hash"FuncApply"`combine`hash f`combine`hash a
-- hash (PhqFnInfixApply f a b) = hash"InfixApply"`combine`hash f`combine`hash a`combine`hash b
-- migrateRs (PhqFnTempRef n) = PhqFnTempRef (n+nLhsRefs)
-- migrateRs (PhqFnFuncApply f a) = PhqFnFuncApply f (migrateRs a)
-- migrateRs (PhqFnInfixApply f a b) = PhqFnInfixApply f (migrateRs a) (migrateRs b)
-- migrateRs c = c
-- | Obtain / eliminate common subexpressions.
seqPrunePhqFuncTerm :: PhqFuncTerm -- The original expression /e/, with possibly duplicate subexpressions.
-> ( PhqFuncTerm -- The \"trimmed\" version of /e/, in which duplicate expressions are replaced by variables, namely
, [(CXXExpression,PhqFuncTerm)] -- The common-subexpr–variables, with the names that were given to them.
)
seqPrunePhqFuncTerm = second ( map . first $ ("tmp"++) . show )
. prune . reverse . go []
where go :: [PhqFuncTerm] -> PhqFuncTerm -> [PhqFuncTerm]
go acc term
| (l, _:r) <- break((==term).expandRefs acc) acc
= refIn acc (length r) : acc
go acc x@(PhqFnFuncApply f a)
| isPrimitive a = x:acc
| otherwise
= let acc' = go acc a
in PhqFnFuncApply f (refIn acc' $ length acc'-1) : acc'
go acc x@(PhqFnInfixApply f a b)
= ifxGo acc x a b $ PhqFnInfixApply f
go acc x@(PhqFnInfixFoldOverIndexer ixd ifx fdInit fdand)
-- = ifxGo acc x fdInit fdand $ PhqFnInfixFoldOverIndexer ixd ifx
| isPrimitive fdInit = x:acc
| otherwise
= let acc' = go acc fdInit
in PhqFnInfixFoldOverIndexer ixd ifx (refIn acc' $ length acc'-1) fdand : acc'
go acc term = term : acc
ifxGo :: [PhqFuncTerm] -> PhqFuncTerm -> PhqFuncTerm -> PhqFuncTerm
-> ( PhqFuncTerm->PhqFuncTerm->PhqFuncTerm )
-> [ PhqFuncTerm ]
ifxGo acc x a b recomb
| isPrimitive a, isPrimitive b = x:acc
| isPrimitive a
= let acc' = go acc b
in recomb a (refIn acc' $ length acc'-1) : acc'
| isPrimitive b
= let acc' = go acc a
in recomb (refIn acc' $ length acc'-1) b : acc'
| otherwise
= let accL = go acc a
accR = go accL b
[nLhsRefs,nRhsRefs] = map length [accL,accR]
in recomb (refIn accR $ nLhsRefs-1)
(refIn accR $ nRhsRefs-1) : accR
expandRefs :: [PhqFuncTerm] -> PhqFuncTerm -> PhqFuncTerm
expandRefs rrl c = expnd c
where reflist = reverse rrl
expnd (PhqFnTempRef n _) = expnd $ reflist!!n
expnd (PhqFnFuncApply f t) = PhqFnFuncApply f $ expnd t
expnd (PhqFnInfixApply f a b) = PhqFnInfixApply f (expnd a) (expnd b)
expnd (PhqFnInfixFoldOverIndexer ixd ifx fdInit fdand)
= PhqFnInfixFoldOverIndexer ixd ifx (expnd fdInit) (expnd fdand)
expnd c = c
refIn rrl n = chase(PhqFnTempRef n $ "tmp"++show n)
where reflist = reverse rrl
chase (PhqFnTempRef n _)
| r'@(PhqFnTempRef _ _)<-reflist!!n = chase r'
chase c = c
prune :: [PhqFuncTerm] -> (PhqFuncTerm, [(Int, PhqFuncTerm)])
prune l = ( inlineIn $ last l, catMaybes $ map zap indexed )
where indexed = zip[0..] l
zap (n, e)
| n`elem`doomed = Nothing
| otherwise = Just (n, inlineIn e)
inlineIn (PhqFnTempRef n' _)
| n'`elem`doomed = inlineIn $ l!!n'
inlineIn (PhqFnFuncApply f e) = PhqFnFuncApply f $ inlineIn e
inlineIn (PhqFnInfixApply f a b) = PhqFnInfixApply f (inlineIn a) (inlineIn b)
inlineIn (PhqFnInfixFoldOverIndexer ixd ifx fdInit fdand)
= PhqFnInfixFoldOverIndexer ixd ifx (inlineIn fdInit) (inlineIn fdand)
inlineIn e = e
doomed = filter ((<=1) . length . referingTo) $ map fst indexed
referingTo n = filter (refersTo n) l
refersTo n (PhqFnTempRef n' _) = n==n'
refersTo n (PhqFnFuncApply _ e) = refersTo n e
refersTo n (PhqFnInfixApply _ a b) = refersTo n a || refersTo n b
refersTo n (PhqFnInfixFoldOverIndexer _ _ a b) = refersTo n a || refersTo n b
refersTo _ _ = False
calculateDimExpression :: (PhqIdf->PhqFuncTerm) -> DimExpression -> PhqFuncTerm
calculateDimExpression prImpl (DimExpression decomp)
= product $ map phqfImplement decomp
where phqfImplement (e, x) = implement e ** fromRational x
implement (PhqFnParamVal pr) = prImpl pr
implement PhqFnResultVal = PhqFnPhysicalConst "desiredret"
implement PhqDimlessConst = PhqFnDimlessConst 1
cqtxTermImplementation :: CXXExpression -> PhqFuncTerm -> CXXCode ( CXXCode() )
cqtxTermImplementation paramSource e = do
forM_ seqChain $ \(rn,se) ->
cxxSurround ("physquantity "++rn++" =") (showE se) (";")
return $ showE result
where (result,seqChain) = seqPrunePhqFuncTerm e
showE (PhqFnDimlessConst x) = cxxLine $ "("++show x++"*real1)"
showE (PhqFnPhysicalConst x) = cxxLine $ "("++x++")"
showE (PhqFnParameter x) = cxxLine $ argderefv paramSource x
showE (PhqFnTempRef _ tmpvn) = cxxLine $ tmpvn
showE (PhqFnFuncApply (CXXFunc f) a) = procCXXCode f $ showE a
showE (PhqFnInfixApply (CXXInfix f) a b) = cxxCombineBlockIndented f (showE a) (showE b)
showE (PhqFnInfixFoldOverIndexer (PhqVarIndexer idxId idxNm)
folder initE summandE ) = do
cxxLine $ "[&]() -> physquantity {"
cxxIndent 2 $ do
let i = indizesPrefix++idxNm
fdAcc = "foldvrb_over_"++idxNm
cxxSurround ("physquantity "++fdAcc++" = ") (showE initE) (";")
cxxLine $ "for(unsigned "++i++"=0\
\; "++i++"<"++i++indexRangePostfix++"\
\; ++"++i++") {"
cxxIndent 2 $ do
foldandResE <- cqtxTermImplementation paramSource summandE
combineAssigner folder fdAcc foldandResE
cxxLine $ "}"
cxxLine $ "return "++fdAcc++";"
cxxLine $ "}()"
-- | Transform a C / C++ infix into the corresponding combined assignment operator,
-- i.e. @+ x y@ maps to @x += y;@. When this is not possible, the explicit form is
-- used, e.g. @x pow@ will yield @x = pow(x, y);@.
combineAssigner :: CXXInfix -> CXXExpression -> CXXCode() -> CXXCode()
combineAssigner (CXXInfix f) acc inc
= case filter(/=' ') $ f"""" of
"+" -> cxxSurround (acc++" += ") inc (";")
"-" -> cxxSurround (acc++" -= ") inc (";")
"*" -> cxxSurround (acc++" *= ") inc (";")
"/" -> cxxSurround (acc++" /= ") inc (";")
_ -> cxxSurround (acc++" = ") (procCXXCode (f acc) inc) (";")
type CqtxConfig = ()
type CqtxCode = ReaderT CqtxConfig CXXCode
withDefaultCqtxConfig :: CqtxCode a -> CXXCode a
withDefaultCqtxConfig = flip runReaderT ()
newtype IdxablePhqDefVar x
= IdxablePhqDefVar {
indexisePhqDefVar :: PhqVarIndexer -> x }
data PhqVarIndexer = PhqVarIndexer
{ phqVarIndexerId :: Int
, phqVarIndexerName :: String
} deriving(Eq)
class (Floating a) => PhqfnDefining a where
sumOverIdx :: PhqVarIndexer
-> ((IdxablePhqDefVar a->a) -> a) -> a
instance PhqfnDefining PhqFuncTerm where
sumOverIdx i summand
= PhqFnInfixFoldOverIndexer i (cxxInfix"+") 0
. forbidDupFold i "sum"
. summand $ \(IdxablePhqDefVar e) -> e i
instance PhqfnDefining DimTracer where
sumOverIdx i summand = summand $
\(IdxablePhqDefVar e) -> e i
forbidDupFold :: PhqVarIndexer -> String -> PhqFuncTerm -> PhqFuncTerm
forbidDupFold i@(PhqVarIndexer _ nmm) fnm = go
where go(PhqFnInfixFoldOverIndexer i' ifx ini tm)
| i'==i = error $ "Duplicate "++fnm++" over index "++nmm
| otherwise = PhqFnInfixFoldOverIndexer i' ifx (go ini) (go tm)
go(PhqFnFuncApply f tm) = PhqFnFuncApply f $ go tm
go(PhqFnInfixApply ifx l r) = PhqFnInfixApply ifx (go l) (go r)
go e = e
class (Functor l, Foldable l) => IsolenList l where
perfectZipWith :: (a->b->c) -> l a -> l b -> l c
buildIsolenList :: (b->b) -> b -> l b
isoLength :: l a -> Int
isoLength = length . toList
enumFrom' :: Enum a => a -> l a
enumFrom' = buildIsolenList succ
(!!@) :: l a -> Int -> a
perfectZip :: IsolenList l => l a -> l b -> l (a,b)
perfectZip = perfectZipWith(,)
perfectZipWith3 :: IsolenList l => (a -> b -> c -> d) -> l a -> l b -> l c -> l d
perfectZipWith3 f la lb = perfectZipWith (uncurry . f) la . perfectZip lb
perfectZip3 :: IsolenList l => l a -> l b -> l c -> l (a,b,c)
perfectZip3 = perfectZipWith3 (,,)
data IsolenEnd a = P deriving (Show)
infixr 5 :.
data IsolenCons l a = a :. l a deriving (Show)
instance Functor IsolenEnd where
fmap _ P = P
instance (Functor l) => Functor (IsolenCons l) where
fmap f (x:.xs) = f x :. fmap f xs
instance Foldable IsolenEnd where
foldr _ = const
instance (Foldable l) => Foldable (IsolenCons l) where
foldr f ini (x:.xs) = x `f` foldr f ini xs
instance IsolenList IsolenEnd where
perfectZipWith _ P P = P
buildIsolenList _ _ = P
isoLength _ = 0
P !!@ (-1) = undefined
instance (IsolenList l) => IsolenList (IsolenCons l) where
perfectZipWith f (x:.xs) (y:.ys) = f x y :. perfectZipWith f xs ys
buildIsolenList f s = s :. buildIsolenList f (f s)
isoLength (_:.xs) = 1 + isoLength xs
(x:._) !!@ 0 = x
(_:.xs) !!@ n = xs !!@ (n-1)
-- instance IsolenList [] where -- obviously unsafe
-- perfectZipWith = zipWith
-- buildIsolenList = iterate
-- enumFrom' = enumFrom
-- singleList = id
-- unfoldToMatch [] _ _ = []
-- unfoldToMatch (_:xs) uff s = let (y,s') = uff s
-- in y : unfoldToMatch xs uff s'
-- buildIsolenList l1 f = unfoldToMatch l1 $ (\b->(b,b)) . f
|
leftaroundabout/cqtx
|
HsMacro/CodeGen/CXX/Cqtx/PhqFn.hs
|
gpl-3.0
| 39,637
| 1
| 44
| 13,287
| 9,719
| 4,960
| 4,759
| -1
| -1
|
module TestImport
( module TestImport
, module X
) where
import Application (makeFoundation, makeLogWare)
#if MIN_VERSION_classy_prelude(1, 0, 0)
import ClassyPrelude as X hiding (delete, deleteBy, Handler)
#else
import ClassyPrelude as X hiding (delete, deleteBy)
#endif
import Database.Persist as X hiding (get)
import Database.Persist.MongoDB hiding (master)
import Foundation as X
import Model as X
import Settings (appDatabaseConf)
import Test.Hspec as X
import Yesod.Default.Config2 (useEnv, loadYamlSettings)
import Yesod.Auth as X
import Yesod.Test as X
-- Wiping the test database
import Database.MongoDB.Query (allCollections)
import Database.MongoDB.Admin (dropCollection)
import Control.Monad.Trans.Control (MonadBaseControl)
runDB :: Action IO a -> YesodExample App a
runDB query = do
app <- getTestYesod
liftIO $ runDBWithApp app query
runDBWithApp :: App -> Action IO a -> IO a
runDBWithApp app query = do
liftIO $ runMongoDBPool
(mgAccessMode $ appDatabaseConf $ appSettings app)
query
(appConnPool app)
withApp :: SpecWith (TestApp App) -> Spec
withApp = before $ do
settings <- loadYamlSettings
["config/test-settings.yml", "config/settings.yml"]
[]
useEnv
foundation <- makeFoundation settings
wipeDB foundation
logWare <- liftIO $ makeLogWare foundation
return (foundation, logWare)
-- This function will wipe your database.
-- 'withApp' calls it before each test, creating a clean environment for each
-- spec to run in.
wipeDB :: App -> IO ()
wipeDB app = void $ runDBWithApp app dropAllCollections
dropAllCollections :: (MonadIO m, MonadBaseControl IO m) => Action m [Bool]
dropAllCollections = allCollections >>= return . filter (not . isSystemCollection) >>= mapM dropCollection
where
isSystemCollection = isPrefixOf "system."
-- | Authenticate as a user. This relies on the `auth-dummy-login: true` flag
-- being set in test-settings.yaml, which enables dummy authentication in
-- Foundation.hs
authenticateAs :: Entity User -> YesodExample App ()
authenticateAs (Entity _ u) = do
request $ do
setMethod "POST"
addPostParam "ident" $ userIdent u
setUrl $ AuthR $ PluginR "dummy" []
-- | Create a user.
createUser :: Text -> YesodExample App (Entity User)
createUser ident = do
runDB $ insertEntity User
{ userIdent = ident
, userPassword = Nothing
}
|
uros-stegic/canx
|
server/canx-server/test/TestImport.hs
|
gpl-3.0
| 2,583
| 0
| 12
| 629
| 599
| 324
| 275
| -1
| -1
|
{- This file is part of PhoneDirectory.
Copyright (C) 2009 Michael Steele
PhoneDirectory is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PhoneDirectory 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 PhoneDirectory. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Name
( Name
, Strategy (render, _compare)
, sur
, given
, mkName
, firstLast
, lastFirst
) where
import Control.Applicative
import Data.Function
import Data.Monoid
import Data.Aeson ((.=), (.:))
import qualified Data.Aeson as A
import Data.Text (Text)
import qualified Data.Text as T
-- |A contact's name. This sorts by last name and prints out as 'Last,
-- First'.
data Name
= FirstLast {-# UNPACK #-} !Text {-# UNPACK #-} !Text
-- |Use this whenever you want a contact to always sort and print the
-- same way.
| SingleName {-# UNPACK #-} !Text
deriving (Eq)
data Strategy = Strategy
{ render :: Name -> Text
, _compare :: Name -> Name -> Ordering }
given :: Name -> Text
given (FirstLast f _) = f
given (SingleName n) = n
sur :: Name -> Maybe Text
sur (FirstLast _ l) = Just l
sur _ = Nothing
firstLast, lastFirst :: Strategy
firstLast = Strategy { render = renderFL, _compare = compareFL }
lastFirst = Strategy { render = renderLF, _compare = compareLF }
renderFL :: Name -> Text
renderFL (FirstLast f l) = f `T.append` " " `T.append` l
renderFL (SingleName n) = n
renderLF :: Name -> Text
renderLF (FirstLast f l) = l `T.append` ", " `T.append` f
renderLF (SingleName n) = n
compareFL :: Name -> Name -> Ordering
compareFL (FirstLast a b) (FirstLast c d) = compare a c <> compare b d
compareFL (FirstLast a b) (SingleName c) = compare (T.append a b) c
compareFL (SingleName c) (FirstLast a b) = compare c (T.append a b)
compareFL (SingleName a) (SingleName b) = compare a b
compareLF :: Name -> Name -> Ordering
compareLF = compareFL `on` swapFL
swapFL :: Name -> Name
swapFL (FirstLast f l) = FirstLast l f
swapFL n = n
instance A.ToJSON Name where
toJSON n = case n of
SingleName sn -> A.toJSON sn
_ -> A.object
[ "first" .= A.toJSON (given n)
, "last" .= A.toJSON (sur n)]
instance A.FromJSON Name where
parseJSON (A.Object v) = FirstLast
<$> v .: "first"
<*> v .: "last"
parseJSON sn = SingleName <$> A.parseJSON sn
-- |Convencience function to create a name from two strings.
mkName :: Text -- ^First name or blank.
-> Text -- ^Last name or blank.
-> Name
mkName f l | T.null f = SingleName l
| T.null l = SingleName f
| otherwise = FirstLast f l
|
mikesteele81/Phone-Directory
|
src/Name.hs
|
gpl-3.0
| 3,136
| 0
| 14
| 720
| 826
| 444
| 382
| 69
| 1
|
-- TabCode - A parser for the Tabcode lute tablature language
--
-- Copyright (C) 2015-2017 Richard Lewis
-- Author: Richard Lewis <richard@rjlewis.me.uk>
-- This file is part of TabCode
-- TabCode is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- TabCode 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 TabCode. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE OverloadedStrings #-}
module TabCode.Serialiser.MEIXML.Elements where
import Control.Applicative ((<$>))
import Data.Maybe (mapMaybe)
import Data.Monoid (mempty, (<>))
import Data.Text (Text, pack, unpack, append)
import TabCode.Types
import TabCode.Serialiser.MEIXML.Types
noMEIAttrs :: MEIAttrs
noMEIAttrs = mempty
getAttrs :: MEI -> MEIAttrs
getAttrs (MEI atts _) = atts
getAttrs (MEIAnnot atts _) = atts
getAttrs (MEIBarLine atts _) = atts
getAttrs (MEIBassTuning atts _) = atts
getAttrs (MEIBeam atts _) = atts
getAttrs (MEIBody atts _) = atts
getAttrs (MEIChord atts _) = atts
getAttrs (MEICourse atts _) = atts
getAttrs (MEICourseTuning atts _) = atts
getAttrs (MEIFermata atts _) = atts
getAttrs (MEIFileDesc atts _) = atts
getAttrs (MEIFingering atts _) = atts
getAttrs (MEIFretGlyph atts _) = atts
getAttrs (MEIHead atts _) = atts
getAttrs (MEIInstrConfig atts _) = atts
getAttrs (MEIInstrDesc atts _) = atts
getAttrs (MEIInstrName atts _) = atts
getAttrs (MEILayer atts _) = atts
getAttrs (MEIMDiv atts _) = atts
getAttrs (MEIMeasure atts _) = atts
getAttrs (MEIMensur atts _) = atts
getAttrs (MEIMeterSig atts _) = atts
getAttrs (MEIMusic atts _) = atts
getAttrs (MEINote atts _) = atts
getAttrs (MEINotesStmt atts _) = atts
getAttrs (TCOrnament atts _) = atts
getAttrs (MEIPageBreak atts _) = atts
getAttrs (MEIPart atts _) = atts
getAttrs (MEIParts atts _) = atts
getAttrs (MEIPerfMedium atts _) = atts
getAttrs (MEIPerfRes atts _) = atts
getAttrs (MEIPerfResList atts _) = atts
getAttrs (MEIPubStmt atts _) = atts
getAttrs (MEIRest atts _) = atts
getAttrs (MEIRhythmSign atts _) = atts
getAttrs (MEISection atts _) = atts
getAttrs (MEISource atts _) = atts
getAttrs (MEISourceDesc atts _) = atts
getAttrs (MEIStaff atts _) = atts
getAttrs (MEIStaffDef atts _) = atts
getAttrs (MEIString atts _) = atts
getAttrs (MEISystemBreak atts _) = atts
getAttrs (MEITitle atts _) = atts
getAttrs (MEITitleStmt atts _) = atts
getAttrs (MEITuplet atts _) = atts
getAttrs (MEIWork atts _) = atts
getAttrs (MEIWorkDesc atts _) = atts
getAttrs (XMLComment _) = noMEIAttrs
getAttrs (XMLText _) = noMEIAttrs
getChildren :: MEI -> [MEI]
getChildren (MEI _ cs) = cs
getChildren (MEIAnnot _ cs) = cs
getChildren (MEIBarLine _ cs) = cs
getChildren (MEIBassTuning _ cs) = cs
getChildren (MEIBeam _ cs) = cs
getChildren (MEIBody _ cs) = cs
getChildren (MEIChord _ cs) = cs
getChildren (MEICourse _ cs) = cs
getChildren (MEICourseTuning _ cs) = cs
getChildren (MEIFermata _ cs) = cs
getChildren (MEIFileDesc _ cs) = cs
getChildren (MEIFingering _ cs) = cs
getChildren (MEIFretGlyph _ cs) = cs
getChildren (MEIHead _ cs) = cs
getChildren (MEIInstrConfig _ cs) = cs
getChildren (MEIInstrDesc _ cs) = cs
getChildren (MEIInstrName _ cs) = cs
getChildren (MEILayer _ cs) = cs
getChildren (MEIMDiv _ cs) = cs
getChildren (MEIMeasure _ cs) = cs
getChildren (MEIMensur _ cs) = cs
getChildren (MEIMeterSig _ cs) = cs
getChildren (MEIMusic _ cs) = cs
getChildren (MEINote _ cs) = cs
getChildren (MEINotesStmt _ cs) = cs
getChildren (TCOrnament _ cs) = cs
getChildren (MEIPageBreak _ cs) = cs
getChildren (MEIPart _ cs) = cs
getChildren (MEIParts _ cs) = cs
getChildren (MEIPerfMedium _ cs) = cs
getChildren (MEIPerfRes _ cs) = cs
getChildren (MEIPerfResList _ cs) = cs
getChildren (MEIPubStmt _ cs) = cs
getChildren (MEIRest _ cs) = cs
getChildren (MEIRhythmSign _ cs) = cs
getChildren (MEISection _ cs) = cs
getChildren (MEISource _ cs) = cs
getChildren (MEISourceDesc _ cs) = cs
getChildren (MEIStaff _ cs) = cs
getChildren (MEIStaffDef _ cs) = cs
getChildren (MEIString _ cs) = cs
getChildren (MEISystemBreak _ cs) = cs
getChildren (MEITitle _ cs) = cs
getChildren (MEITitleStmt _ cs) = cs
getChildren (MEITuplet _ cs) = cs
getChildren (MEIWork _ cs) = cs
getChildren (MEIWorkDesc _ cs) = cs
getChildren (XMLText _) = []
getChildren (XMLComment _) = []
attrName :: MEIAttr -> Text
attrName (StringAttr name _) = name
attrName (IntAttr name _) = name
attrName (PrefIntAttr name _) = name
attrNameEq :: Text -> MEIAttr -> Bool
attrNameEq att (StringAttr name _) = att == name
attrNameEq att (IntAttr name _) = att == name
attrNameEq att (PrefIntAttr name _) = att == name
renameAttr :: Text -> MEIAttr -> MEIAttr
renameAttr new (StringAttr _ v) = StringAttr new v
renameAttr new (IntAttr _ v) = IntAttr new v
renameAttr new (PrefIntAttr _ v) = PrefIntAttr new v
intAttrToStrAttr :: MEIAttr -> MEIAttr
intAttrToStrAttr a@(StringAttr _ _) = a
intAttrToStrAttr (IntAttr name value) = StringAttr name (pack $ show value)
intAttrToStrAttr (PrefIntAttr name (prefix, value)) = StringAttr name (prefix `append` (pack $ show value))
incIntAttr :: Int -> MEIAttr -> MEIAttr
incIntAttr _ (StringAttr name value) = error $ unpack $ "Cannot apply incIntAttr to string attribute " `append` name `append` ": \"" `append` value `append` "\""
incIntAttr n (IntAttr name value) = IntAttr name (value + n)
incIntAttr n (PrefIntAttr name (prefix, value)) = PrefIntAttr name (prefix, value + n)
getAttr :: Text -> MEIAttrs -> MEIAttrs
getAttr att meiAttrs = take 1 $ filter (attrNameEq att) meiAttrs
updateStrAttrValue :: (Text -> Text) -> MEIAttr -> MEIAttr
updateStrAttrValue m (StringAttr name v) = StringAttr name $ m v
updateStrAttrValue _ _ = error $ unpack "Cannot apply updateStrAttrValue to non-StringAttr attribute"
someAttrs :: [Text] -> MEIAttrs -> MEIAttrs
someAttrs keys meiAttrs =
filter (\att -> (attrName att) `elem` keys) meiAttrs
updateAttrs :: MEIAttrs -> MEIAttrs -> MEIAttrs
updateAttrs initial new =
(filter (\att -> (attrName att) `notElem` nKeys) initial) ++ new
where
nKeys = map attrName new
replaceAttrs :: MEIAttrs -> MEIAttrs -> MEIAttrs
replaceAttrs initial [] = initial
replaceAttrs _ new = new
mutateAttr :: Text -> (MEIAttr -> MEIAttr) -> MEIAttrs -> MEIAttrs
mutateAttr att m meiAttrs = rpl meiAttrs
where
rpl (a:as)
| (attrName a) == att = m a : rpl as
| otherwise = a : rpl as
rpl [] = []
children :: Maybe [a] -> [a]
children (Just xs) = xs
children Nothing = []
(<$:>) :: (a -> [b]) -> Maybe a -> [b]
f <$:> Just x = f x
_ <$:> Nothing = []
attrs :: MEIAttrs -> MEIAttrs -> MEIAttrs
attrs xs ys = xs <> ys
emptyState :: MEIState
emptyState = MEIState
{ stRules = []
, stMdiv = noMEIAttrs
, stPart = noMEIAttrs
, stSection = noMEIAttrs
, stStaff = noMEIAttrs
, stStaffDef = noMEIAttrs
, stLayer = noMEIAttrs
, stMeasure = noMEIAttrs
, stMeasureId = noMEIAttrs
, stBarLine = noMEIAttrs
, stBarLineId = noMEIAttrs
, stChordId = noMEIAttrs
, stChord = noMEIAttrs
, stRestId = noMEIAttrs
, stRhythmGlyphId = noMEIAttrs
, stNoteId = noMEIAttrs
}
initialState :: MEIState
initialState = MEIState
{ stRules = []
, stMdiv = [ IntAttr "n" 1 ]
, stPart = [ IntAttr "n" 1 ]
, stSection = [ IntAttr "n" 1 ]
, stStaff = [ IntAttr "n" 1 ]
, stStaffDef = [ PrefIntAttr "xml:id" ("staff-", 0) ]
, stLayer = [ IntAttr "n" 1 ]
, stMeasure = [ IntAttr "n" 0 ]
, stMeasureId = [ PrefIntAttr "xml:id" ("m", 0) ]
, stBarLine = [ IntAttr "n" 0 ]
, stBarLineId = [ PrefIntAttr "xml:id" ("bl", 0) ]
, stChordId = [ PrefIntAttr "xml:id" ("c", 1) ]
, stChord = noMEIAttrs
, stRestId = [ PrefIntAttr "xml:id" ("r", 1) ]
, stRhythmGlyphId = [ PrefIntAttr "xml:id" ("rg", 1) ]
, stNoteId = [ PrefIntAttr "xml:id" ("n", 1) ]
}
boundedIntAttr :: Int -> (Int, Int) -> Text -> MEIAttrs
boundedIntAttr i (l, u) n
| i >= l && i <= u = [ IntAttr n i ]
| otherwise = error $ "Invalid " ++ (unpack n) ++ ": " ++ (show i)
atCount :: Int -> MEIAttrs
atCount c = [ IntAttr "count" c ]
atCut :: Int -> MEIAttrs
atCut n = boundedIntAttr n (1,6) "slash"
atDef :: Text -> MEIAttrs
atDef d = [ StringAttr "def" d ]
atDur :: RhythmSign -> MEIAttrs
atDur (RhythmSign s _ Dot _) = [ StringAttr "dur" (meiDur s), IntAttr "dots" 1 ]
atDur (RhythmSign s _ NoDot _) = [ StringAttr "dur" (meiDur s) ]
atDurSymb :: Duration -> Beat -> Dot -> MEIAttrs
atDurSymb dur bt Dot =
[ StringAttr "symbol" (durSymb dur bt Dot)
, IntAttr "dots" 1 ]
atDurSymb dur bt NoDot =
[ StringAttr "symbol" (durSymb dur bt NoDot) ]
atDot :: Bool -> MEIAttrs
atDot True = [ StringAttr "dot" "true" ]
atDot False = [ StringAttr "dot" "false" ]
atForm :: String -> MEIAttrs
atForm s = [ StringAttr "form" (pack s) ]
atLabel :: String -> MEIAttrs
atLabel l = [ StringAttr "label" (pack l) ]
atMeiVersion :: MEIAttrs
atMeiVersion = [ StringAttr "meiversion" "3.0.0" ]
atNum :: Int -> MEIAttrs
atNum n = [ IntAttr "num" n ]
atNumDef :: Int -> MEIAttrs
atNumDef n = [ IntAttr "num.default" n ]
atNumbase :: Int -> MEIAttrs
atNumbase b = [ IntAttr "numbase" b ]
atNumbaseDef :: Int -> MEIAttrs
atNumbaseDef b = [ IntAttr "numbase.default" b ]
atOct :: Int -> MEIAttrs
atOct o = boundedIntAttr o (1,6) "oct"
atPlayingFinger :: Finger -> MEIAttrs
atPlayingFinger fngr = [ StringAttr "playingFinger" (finger fngr) ]
atPname :: String -> MEIAttrs
atPname p = [ StringAttr "pname" (pack p) ]
atProlation :: Int -> MEIAttrs
atProlation p = boundedIntAttr p (2,3) "prolatio"
atRight :: String -> MEIAttrs
atRight s = [ StringAttr "right" (pack s) ]
atSign :: Char -> MEIAttrs
atSign 'O' = [ StringAttr "sign" "O" ]
atSign 'C' = [ StringAttr "sign" "C" ]
atSign c = error $ "Invalid mensuration symbol: " ++ (show c)
atSlash :: Int -> MEIAttrs
atSlash n = [ IntAttr "mensur.slash" n ]
atSolo :: Bool -> MEIAttrs
atSolo True = [ StringAttr "solo" "true" ]
atSolo False = [ StringAttr "solo" "false" ]
atTabCourse :: Course -> MEIAttrs
atTabCourse crs = [ StringAttr "tab.course" (course crs) ]
atTabFret :: Fret -> MEIAttrs
atTabFret frt = [ StringAttr "tab.fret" (fretNo frt) ]
atTempus :: Int -> MEIAttrs
atTempus t = boundedIntAttr t (2,3) "tempus"
atUnit :: Int -> MEIAttrs
atUnit u = [ IntAttr "unit" u ]
atXmlId :: String -> Int -> MEIAttrs
atXmlId prefix n = [ PrefIntAttr "xml:id" (pack prefix, n) ]
atXmlIdNext :: MEIAttrs -> MEIAttrs
atXmlIdNext atts = mutateAttr "xml:id" (incIntAttr 1) atts
withXmlId :: MEIAttrs -> MEIAttrs -> MEIAttrs
withXmlId idAttrs otherAttrs =
updateAttrs otherAttrs $ getAttr "xml:id" idAttrs
xmlIdNumber :: MEIAttrs -> Int
xmlIdNumber ((PrefIntAttr "xml:id" (_, i)):_) = i
xmlIdNumber (_:atts) = xmlIdNumber atts
xmlIdNumber [] = 0
elArticulation :: MEIAttrs -> Articulation -> [MEI]
elArticulation _ _ = [XMLComment ""]
elConnectingLine :: MEIAttrs -> Connecting -> [MEI]
elConnectingLine _ _ = [XMLComment ""]
elFingering :: MEIAttrs -> Fingering -> [MEI]
elFingering coreAttrs (FingeringLeft fngr _) = [ MEIFingering (coreAttrs <> [ StringAttr "playingHand" "left" ] <> (atPlayingFinger fngr)) [] ]
elFingering coreAttrs (FingeringRight fngr _) = [ MEIFingering (coreAttrs <> [ StringAttr "playingHand" "right" ] <> (atPlayingFinger fngr)) [] ]
elFretGlyph :: MEIAttrs -> [Rule] -> Fret -> Maybe [MEI]
elFretGlyph coreAttrs rls frt = m <$> glyph
where
m g = [ MEIFretGlyph coreAttrs [ XMLText g ] ]
glyph = case notation rls of
Just "italian" -> Just $ fretGlyphIt frt
Just "french" -> Just $ fretGlyphFr frt
_ -> Nothing
elNote :: MEIAttrs -> [Rule] -> Note -> [MEI]
elNote coreAttrs rls (Note crs frt (fng1, fng2) orn artic conn) =
[ MEINote ( coreAttrs <> atTabCourse crs <> atTabFret frt ) $ children ( (elFretGlyph noMEIAttrs rls frt)
<> (elFingering noMEIAttrs <$> fng1)
<> (elFingering noMEIAttrs <$> fng2) ) ]
<> children ( (elOrnament noMEIAttrs <$> orn)
<> (elArticulation noMEIAttrs <$> artic)
<> (elConnectingLine noMEIAttrs <$> conn ) )
elOrnament :: MEIAttrs -> Ornament -> [MEI]
elOrnament coreAttrs o =
case o of
(OrnA s _) -> orn "a" s
(OrnB s _) -> orn "b" s
(OrnC s _) -> orn "c" s
(OrnD s _) -> orn "d" s
(OrnE s _) -> orn "e" s
(OrnF s _) -> orn "f" s
(OrnG s _) -> orn "g" s
(OrnH s _) -> orn "h" s
(OrnI s _) -> orn "i" s
(OrnJ s _) -> orn "j" s
(OrnK s _) -> orn "k" s
(OrnL s _) -> orn "l" s
(OrnM s _) -> orn "m" s
where
orn t s = [ TCOrnament (coreAttrs <> [ StringAttr "type" t ] <> (ornST <$:> s)) [] ]
ornST st = [ IntAttr "sub-type" st ]
elPerfMediumLute :: MEIAttrs -> String -> [MEI] -> MEI
elPerfMediumLute coreAttrs label courseElements =
MEIPerfMedium coreAttrs [ perfResList ]
where
perfResList = MEIPerfResList noMEIAttrs [ perfRes ]
perfRes = MEIPerfRes ( atLabel "lute" <> atSolo True ) [ instrDesc, instrConfig ]
instrDesc = MEIInstrDesc noMEIAttrs [ MEIInstrName noMEIAttrs [ XMLText "Lute" ] ]
instrConfig = MEIInstrConfig ( atLabel label ) [ MEICourseTuning noMEIAttrs courseElements ]
elRhythmSign :: MEIAttrs -> RhythmSign -> [MEI]
elRhythmSign coreAttrs (RhythmSign Fermata _ _ _) = [ MEIFermata coreAttrs [] ]
elRhythmSign coreAttrs (RhythmSign dur bt dt _) = [ MEIRhythmSign ( coreAttrs <> atDurSymb dur bt dt ) [] ]
elFileDesc :: MEIAttrs -> [MEI]
elFileDesc coreAttrs = [ MEIFileDesc coreAttrs ( elTitleStmt coreAttrs <> elPubStmt coreAttrs <> elSourceDesc coreAttrs ) ]
elPubStmt :: MEIAttrs -> [MEI]
elPubStmt coreAttrs = [ MEIPubStmt coreAttrs [] ]
elSource :: MEIAttrs -> [MEI]
elSource coreAttrs = [ MEISource coreAttrs ( elNotesStmt coreAttrs ( elAnnot coreAttrs "Generated with tc2mei" ) ) ]
elSourceDesc :: MEIAttrs -> [MEI]
elSourceDesc coreAttrs = [ MEISourceDesc coreAttrs ( elSource coreAttrs ) ]
elAnnot :: MEIAttrs -> String -> [MEI]
elAnnot coreAttrs annot = [ MEIAnnot coreAttrs [ XMLText (pack annot) ] ]
elNotesStmt :: MEIAttrs -> [MEI] -> [MEI]
elNotesStmt coreAttrs stmts = [ MEINotesStmt coreAttrs stmts ]
elTitle :: MEIAttrs -> [MEI]
elTitle coreAttrs = [ MEITitle coreAttrs [] ]
elTitleStmt :: MEIAttrs -> [MEI]
elTitleStmt coreAttrs = [ MEITitleStmt coreAttrs ( elTitle coreAttrs ) ]
elWorkDesc :: MEIAttrs -> [Rule] -> [MEI]
elWorkDesc coreAttrs rls = [ MEIWorkDesc coreAttrs [ work ] ]
where
work = MEIWork coreAttrs $ mapMaybe descEl rls
--descEl (Rule "title" t) = Just $ MEITitle noMEIAttrs $ XMLText t
descEl (Rule "tuning_named" t) = Just $ tuning t
descEl (Rule _ _) = Nothing
-- FIXME What are the correct tunings?
tuning :: String -> MEI
tuning "renaissance" =
elPerfMediumLute noMEIAttrs
"renaissance"
[ MEICourse ( atPname "g" <> atOct 4 ) [ MEIString ( atPname "g" <> atOct 4 ) [] ]
, MEICourse ( atPname "d" <> atOct 4 ) [ MEIString ( atPname "d" <> atOct 4 ) [] ]
, MEICourse ( atPname "a" <> atOct 4 ) [ MEIString ( atPname "a" <> atOct 4 ) [] ]
, MEICourse ( atPname "f" <> atOct 3 ) [ MEIString ( atPname "f" <> atOct 3 ) [] ]
, MEICourse ( atPname "c" <> atOct 3 ) [ MEIString ( atPname "c" <> atOct 3 ) [] ]
, MEICourse ( atPname "g" <> atOct 2 ) [ MEIString ( atPname "g" <> atOct 2 ) [] ]
]
-- FIXME What are the correct tunings?
tuning "baroque" =
elPerfMediumLute noMEIAttrs
"baroque"
[ MEICourse ( atPname "g" <> atOct 4 ) [ MEIString ( atPname "g" <> atOct 4 ) [] ]
, MEICourse ( atPname "d" <> atOct 4 ) [ MEIString ( atPname "d" <> atOct 4 ) [] ]
, MEICourse ( atPname "a" <> atOct 4 ) [ MEIString ( atPname "a" <> atOct 4 ) [] ]
, MEICourse ( atPname "f" <> atOct 3 ) [ MEIString ( atPname "f" <> atOct 3 ) [] ]
, MEICourse ( atPname "c" <> atOct 3 ) [ MEIString ( atPname "c" <> atOct 3 ) [] ]
, MEICourse ( atPname "g" <> atOct 2 ) [ MEIString ( atPname "g" <> atOct 2 ) [] ]
]
tuning t = error $ "Unknown tuning name: " ++ t
course :: Course -> Text
course One = pack "1"
course Two = pack "2"
course Three = pack "3"
course Four = pack "4"
course Five = pack "5"
course Six = pack "6"
course (Bass n) = pack $ show $ 6 + n
finger :: Finger -> Text
finger FingerOne = pack "1"
finger FingerTwo = pack "2"
finger FingerThree = pack "3"
finger FingerFour = pack "4"
finger Thumb = pack "t"
fretNo :: Fret -> Text
fretNo A = pack "0"
fretNo B = pack "1"
fretNo C = pack "2"
fretNo D = pack "3"
fretNo E = pack "4"
fretNo F = pack "5"
fretNo G = pack "6"
fretNo H = pack "7"
fretNo I = pack "8"
fretNo J = pack "9"
fretNo K = pack "10"
fretNo L = pack "11"
fretNo M = pack "12"
fretNo N = pack "13"
fretGlyphIt :: Fret -> Text
fretGlyphIt f = fretNo f
fretGlyphFr :: Fret -> Text
fretGlyphFr A = pack "a"
fretGlyphFr B = pack "b"
fretGlyphFr C = pack "c"
fretGlyphFr D = pack "d"
fretGlyphFr E = pack "e"
fretGlyphFr F = pack "f"
fretGlyphFr G = pack "g"
fretGlyphFr H = pack "h"
fretGlyphFr I = pack "i"
fretGlyphFr J = pack "j"
fretGlyphFr K = pack "k"
fretGlyphFr L = pack "l"
fretGlyphFr M = pack "m"
fretGlyphFr N = pack "n"
durSymb :: Duration -> Beat -> Dot -> Text
durSymb Fermata _ Dot = error "Dotted fermata not allowed"
durSymb Fermata _ NoDot = pack "F"
durSymb Breve Simple Dot = pack "B."
durSymb Breve Simple NoDot = pack "B"
durSymb Breve Compound Dot = pack "B3."
durSymb Breve Compound NoDot = pack "B3"
durSymb Semibreve Simple Dot = pack "W."
durSymb Semibreve Simple NoDot = pack "W"
durSymb Semibreve Compound Dot = pack "W3."
durSymb Semibreve Compound NoDot = pack "W3"
durSymb Minim Simple Dot = pack "H."
durSymb Minim Simple NoDot = pack "H"
durSymb Minim Compound Dot = pack "H3."
durSymb Minim Compound NoDot = pack "H3"
durSymb Crotchet Simple Dot = pack "Q."
durSymb Crotchet Simple NoDot = pack "Q"
durSymb Crotchet Compound Dot = pack "Q3."
durSymb Crotchet Compound NoDot = pack "Q3"
durSymb Quaver Simple Dot = pack "E."
durSymb Quaver Simple NoDot = pack "E"
durSymb Quaver Compound Dot = pack "E3."
durSymb Quaver Compound NoDot = pack "E3"
durSymb Semiquaver Simple Dot = pack "S."
durSymb Semiquaver Simple NoDot = pack "S"
durSymb Semiquaver Compound Dot = pack "S3."
durSymb Semiquaver Compound NoDot = pack "S3"
durSymb Demisemiquaver Simple Dot = pack "T."
durSymb Demisemiquaver Simple NoDot = pack "T"
durSymb Demisemiquaver Compound Dot = pack "T3."
durSymb Demisemiquaver Compound NoDot = pack "T3"
durSymb Hemidemisemiquaver Simple Dot = pack "Y."
durSymb Hemidemisemiquaver Simple NoDot = pack "Y"
durSymb Hemidemisemiquaver Compound Dot = pack "Y3."
durSymb Hemidemisemiquaver Compound NoDot = pack "Y3"
durSymb Semihemidemisemiquaver Simple Dot = pack "Z."
durSymb Semihemidemisemiquaver Simple NoDot = pack "Z"
durSymb Semihemidemisemiquaver Compound Dot = pack "Z3."
durSymb Semihemidemisemiquaver Compound NoDot = pack "Z3"
meiDur :: Duration -> Text
meiDur Fermata = pack "fermata"
meiDur Breve = pack "breve"
meiDur Semibreve = pack "1"
meiDur Minim = pack "2"
meiDur Crotchet = pack "4"
meiDur Quaver = pack "8"
meiDur Semiquaver = pack "16"
meiDur Demisemiquaver = pack "32"
meiDur Hemidemisemiquaver = pack "64"
meiDur Semihemidemisemiquaver = pack "128"
|
TransformingMusicology/tabcode-haskell
|
src/TabCode/Serialiser/MEIXML/Elements.hs
|
gpl-3.0
| 19,571
| 0
| 14
| 3,947
| 7,409
| 3,760
| 3,649
| 456
| 13
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.PublicAdvertisedPrefixes.Delete
-- 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)
--
-- Deletes the specified PublicAdvertisedPrefix
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.publicAdvertisedPrefixes.delete@.
module Network.Google.Resource.Compute.PublicAdvertisedPrefixes.Delete
(
-- * REST Resource
PublicAdvertisedPrefixesDeleteResource
-- * Creating a Request
, publicAdvertisedPrefixesDelete
, PublicAdvertisedPrefixesDelete
-- * Request Lenses
, papdRequestId
, papdPublicAdvertisedPrefix
, papdProject
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.publicAdvertisedPrefixes.delete@ method which the
-- 'PublicAdvertisedPrefixesDelete' request conforms to.
type PublicAdvertisedPrefixesDeleteResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"publicAdvertisedPrefixes" :>
Capture "publicAdvertisedPrefix" Text :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Operation
-- | Deletes the specified PublicAdvertisedPrefix
--
-- /See:/ 'publicAdvertisedPrefixesDelete' smart constructor.
data PublicAdvertisedPrefixesDelete =
PublicAdvertisedPrefixesDelete'
{ _papdRequestId :: !(Maybe Text)
, _papdPublicAdvertisedPrefix :: !Text
, _papdProject :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PublicAdvertisedPrefixesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'papdRequestId'
--
-- * 'papdPublicAdvertisedPrefix'
--
-- * 'papdProject'
publicAdvertisedPrefixesDelete
:: Text -- ^ 'papdPublicAdvertisedPrefix'
-> Text -- ^ 'papdProject'
-> PublicAdvertisedPrefixesDelete
publicAdvertisedPrefixesDelete pPapdPublicAdvertisedPrefix_ pPapdProject_ =
PublicAdvertisedPrefixesDelete'
{ _papdRequestId = Nothing
, _papdPublicAdvertisedPrefix = pPapdPublicAdvertisedPrefix_
, _papdProject = pPapdProject_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
papdRequestId :: Lens' PublicAdvertisedPrefixesDelete (Maybe Text)
papdRequestId
= lens _papdRequestId
(\ s a -> s{_papdRequestId = a})
-- | Name of the PublicAdvertisedPrefix resource to delete.
papdPublicAdvertisedPrefix :: Lens' PublicAdvertisedPrefixesDelete Text
papdPublicAdvertisedPrefix
= lens _papdPublicAdvertisedPrefix
(\ s a -> s{_papdPublicAdvertisedPrefix = a})
-- | Project ID for this request.
papdProject :: Lens' PublicAdvertisedPrefixesDelete Text
papdProject
= lens _papdProject (\ s a -> s{_papdProject = a})
instance GoogleRequest PublicAdvertisedPrefixesDelete
where
type Rs PublicAdvertisedPrefixesDelete = Operation
type Scopes PublicAdvertisedPrefixesDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient PublicAdvertisedPrefixesDelete'{..}
= go _papdProject _papdPublicAdvertisedPrefix
_papdRequestId
(Just AltJSON)
computeService
where go
= buildClient
(Proxy ::
Proxy PublicAdvertisedPrefixesDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/PublicAdvertisedPrefixes/Delete.hs
|
mpl-2.0
| 4,890
| 0
| 16
| 1,017
| 477
| 287
| 190
| 79
| 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.IdentityToolkit.RelyingParty.VerifyCustomToken
-- 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)
--
-- Verifies the developer asserted ID token.
--
-- /See:/ <https://developers.google.com/identity-toolkit/v3/ Google Identity Toolkit API Reference> for @identitytoolkit.relyingparty.verifyCustomToken@.
module Network.Google.Resource.IdentityToolkit.RelyingParty.VerifyCustomToken
(
-- * REST Resource
RelyingPartyVerifyCustomTokenResource
-- * Creating a Request
, relyingPartyVerifyCustomToken
, RelyingPartyVerifyCustomToken
-- * Request Lenses
, rpvctPayload
) where
import Network.Google.IdentityToolkit.Types
import Network.Google.Prelude
-- | A resource alias for @identitytoolkit.relyingparty.verifyCustomToken@ method which the
-- 'RelyingPartyVerifyCustomToken' request conforms to.
type RelyingPartyVerifyCustomTokenResource =
"identitytoolkit" :>
"v3" :>
"relyingparty" :>
"verifyCustomToken" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON]
IdentitytoolkitRelyingPartyVerifyCustomTokenRequest
:> Post '[JSON] VerifyCustomTokenResponse
-- | Verifies the developer asserted ID token.
--
-- /See:/ 'relyingPartyVerifyCustomToken' smart constructor.
newtype RelyingPartyVerifyCustomToken =
RelyingPartyVerifyCustomToken'
{ _rpvctPayload :: IdentitytoolkitRelyingPartyVerifyCustomTokenRequest
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RelyingPartyVerifyCustomToken' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rpvctPayload'
relyingPartyVerifyCustomToken
:: IdentitytoolkitRelyingPartyVerifyCustomTokenRequest -- ^ 'rpvctPayload'
-> RelyingPartyVerifyCustomToken
relyingPartyVerifyCustomToken pRpvctPayload_ =
RelyingPartyVerifyCustomToken' {_rpvctPayload = pRpvctPayload_}
-- | Multipart request metadata.
rpvctPayload :: Lens' RelyingPartyVerifyCustomToken IdentitytoolkitRelyingPartyVerifyCustomTokenRequest
rpvctPayload
= lens _rpvctPayload (\ s a -> s{_rpvctPayload = a})
instance GoogleRequest RelyingPartyVerifyCustomToken
where
type Rs RelyingPartyVerifyCustomToken =
VerifyCustomTokenResponse
type Scopes RelyingPartyVerifyCustomToken =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient RelyingPartyVerifyCustomToken'{..}
= go (Just AltJSON) _rpvctPayload
identityToolkitService
where go
= buildClient
(Proxy ::
Proxy RelyingPartyVerifyCustomTokenResource)
mempty
|
brendanhay/gogol
|
gogol-identity-toolkit/gen/Network/Google/Resource/IdentityToolkit/RelyingParty/VerifyCustomToken.hs
|
mpl-2.0
| 3,452
| 0
| 13
| 701
| 308
| 189
| 119
| 54
| 1
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.RangeSet.Parse
( showRangeSet
, parseRangeSet
) where
import Control.Applicative (optional)
import Data.Maybe (fromMaybe)
import qualified Data.RangeSet.List as R
import qualified Text.ParserCombinators.ReadP as RP
import qualified Text.ParserCombinators.ReadPrec as RP (lift, readPrec_to_P, minPrec)
import Text.Read (readMaybe, readPrec)
newtype RangeList a = RangeList { unRangeList :: [(a,a)] } deriving (Monoid)
rangeSetList :: R.RSet a -> RangeList a
rangeSetList = RangeList . R.toRangeList
rangeListSet :: (Ord a, Enum a) => RangeList a -> R.RSet a
rangeListSet = R.fromRangeList . unRangeList
instance (Show a, Eq a, Bounded a) => Show (RangeList a) where
showsPrec _ = sl . unRangeList where
sl [] = id
sl [r] = sr r
sl (r:l) = sr r . showChar ',' . sl l
sr (a,b)
| a == b = shows a
| otherwise = (if a == minBound then id else shows a)
. showChar '-' .
(if b == maxBound then id else shows b)
showRangeSet :: (Show a, Eq a, Bounded a) => R.RSet a -> String
showRangeSet = show . rangeSetList
readP :: Read a => RP.ReadP a
readP = RP.readPrec_to_P readPrec RP.minPrec
instance (Read a, Bounded a) => Read (RangeList a) where
readPrec = RP.lift $ RangeList <$> RP.sepBy rr (RP.char ',') where
ru = do
_ <- RP.char '-'
RP.option maxBound readP
rr = do
l <- optional readP
let lb = fromMaybe minBound l
ub <- maybe ru (`RP.option` ru) l
return (lb, ub)
parseRangeSet :: (Ord a, Enum a, Bounded a, Read a) => String -> Maybe (R.RSet a)
parseRangeSet = fmap rangeListSet . readMaybe
|
databrary/databrary
|
src/Data/RangeSet/Parse.hs
|
agpl-3.0
| 1,651
| 0
| 13
| 367
| 661
| 351
| 310
| 41
| 1
|
module Hodor.Reports where
import Control.Arrow (first)
import Data.Function (on)
import Data.List (groupBy, intercalate, sort)
import Data.Time (Day)
import Hodor (
Project,
TodoItem,
dateCompleted,
unparse,
)
-- True when item has been closed on 'day' or after.
closedSince :: Day -> TodoItem -> Bool
closedSince day = maybe True (>= day) . dateCompleted
-- Nicely format a project and its sub-items.
renderProjectAndItems :: (Maybe Project, [TodoItem]) -> String
renderProjectAndItems (p, ts) =
project ++ "\n" ++ items ++ "\n"
where
project = maybe "(no project)" show p
items = intercalate "\n" (map ((" "++) . unparse) ts)
-- Render TodoItems grouped by projects
projectReview :: [TodoItem] -> String
projectReview = concat . map renderProjectAndItems . groupByProjects
decorate :: (a -> [b]) -> a -> [(Maybe b, a)]
decorate f x = let keys = f x in
if null keys then [(Nothing, x)]
else zip (map Just keys) (repeat x)
groupByKeys :: (Ord a, Ord b) => (a -> [b]) -> [a] -> [(Maybe b, [a])]
groupByKeys f = map (first head . unzip) . groupBy (on (==) fst) . sort . concatMap (decorate f)
-- Group TodoItems by project
groupByProjects :: [TodoItem] -> [(Maybe Project, [TodoItem])]
groupByProjects = groupByKeys projects
|
jml/hodor
|
Hodor/Reports.hs
|
apache-2.0
| 1,300
| 0
| 12
| 276
| 470
| 261
| 209
| 27
| 2
|
{- |
Module : Environment
Description : REPL environment
Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt)
License : BSD3
Maintainer : Boya Peng <u3502350@connect.hku.hk>
Stability : stable
Portability : portable
-}
module Environment where
import Data.List.Split
import Parser
import Src
import Text.PrettyPrint.ANSI.Leijen
type Env = [(String, Exp)]
type Exp = (String, Src.ReadExpr)
empty :: Env
empty = []
insert :: (String, String) -> Env -> Env
insert (var, exp) env =
case Parser.reader exp of
POk expr -> (var, (exp, expr)) : env
PError error -> env
createExp :: [String] -> String
createExp [] = ""
createExp (x:xs) = x ++ " " ++ createExp xs
-- y is "="
-- Sample input: ["x", "=", "y" , "+", "2"]
-- Sample output: splitOn ["="] xs ~> [["x"], ["y", "+", "2"]]
-- Sample output: ("x", "y+2")
createPair :: [String] -> (String, String)
createPair xs = (var, exp) where
var = ((splitOn ["="] xs) !! 0) !! 0
exp = createExp ((splitOn ["="] xs) !! 1)
reverseEnv :: Env -> Env
reverseEnv = reverse
createBindEnv :: Env -> String
createBindEnv [] = ""
createBindEnv ((var,(str,expr)) : xs) = "let " ++ var ++ " = " ++ str
++ " in " ++ createBindEnv xs
searchEnv :: String -> Env -> Bool
searchEnv var env = case lookup var env of
Nothing -> False
Just exp -> True
showPrettyEnv :: Env -> String
showPrettyEnv [] = ""
showPrettyEnv ((var, (_, expr)) : xs) = "(" ++ show var ++ ", "
++ show (pretty expr)
++ "); " ++ showPrettyEnv xs
|
bixuanzju/fcore
|
repl/Environment.hs
|
bsd-2-clause
| 1,708
| 0
| 12
| 507
| 493
| 273
| 220
| 36
| 2
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QHostAddress.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Network.QHostAddress (
QqHostAddress(..)
,QqHostAddress_nf(..)
,protocol
,scopeId
,QsetAddress(..)
,setScopeId
,toIPv4Address
,toIPv6Address
,qHostAddress_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Network.QAbstractSocket
import Qtc.Enums.Network.QHostAddress
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Network
import Qtc.ClassTypes.Network
class QqHostAddress x1 where
qHostAddress :: x1 -> IO (QHostAddress ())
instance QqHostAddress (()) where
qHostAddress ()
= withQHostAddressResult $
qtc_QHostAddress
foreign import ccall "qtc_QHostAddress" qtc_QHostAddress :: IO (Ptr (TQHostAddress ()))
instance QqHostAddress ((SpecialAddress)) where
qHostAddress (x1)
= withQHostAddressResult $
qtc_QHostAddress1 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHostAddress1" qtc_QHostAddress1 :: CLong -> IO (Ptr (TQHostAddress ()))
instance QqHostAddress ((Int)) where
qHostAddress (x1)
= withQHostAddressResult $
qtc_QHostAddress2 (toCUInt x1)
foreign import ccall "qtc_QHostAddress2" qtc_QHostAddress2 :: CUInt -> IO (Ptr (TQHostAddress ()))
instance QqHostAddress ((String)) where
qHostAddress (x1)
= withQHostAddressResult $
withCWString x1 $ \cstr_x1 ->
qtc_QHostAddress3 cstr_x1
foreign import ccall "qtc_QHostAddress3" qtc_QHostAddress3 :: CWString -> IO (Ptr (TQHostAddress ()))
instance QqHostAddress ((QHostAddress t1)) where
qHostAddress (x1)
= withQHostAddressResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHostAddress4 cobj_x1
foreign import ccall "qtc_QHostAddress4" qtc_QHostAddress4 :: Ptr (TQHostAddress t1) -> IO (Ptr (TQHostAddress ()))
class QqHostAddress_nf x1 where
qHostAddress_nf :: x1 -> IO (QHostAddress ())
instance QqHostAddress_nf (()) where
qHostAddress_nf ()
= withObjectRefResult $
qtc_QHostAddress
instance QqHostAddress_nf ((SpecialAddress)) where
qHostAddress_nf (x1)
= withObjectRefResult $
qtc_QHostAddress1 (toCLong $ qEnum_toInt x1)
instance QqHostAddress_nf ((Int)) where
qHostAddress_nf (x1)
= withObjectRefResult $
qtc_QHostAddress2 (toCUInt x1)
instance QqHostAddress_nf ((String)) where
qHostAddress_nf (x1)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
qtc_QHostAddress3 cstr_x1
instance QqHostAddress_nf ((QHostAddress t1)) where
qHostAddress_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHostAddress4 cobj_x1
instance Qclear (QHostAddress a) (()) where
clear x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_clear cobj_x0
foreign import ccall "qtc_QHostAddress_clear" qtc_QHostAddress_clear :: Ptr (TQHostAddress a) -> IO ()
instance QqisNull (QHostAddress a) (()) where
qisNull x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_isNull cobj_x0
foreign import ccall "qtc_QHostAddress_isNull" qtc_QHostAddress_isNull :: Ptr (TQHostAddress a) -> IO CBool
protocol :: QHostAddress a -> (()) -> IO (NetworkLayerProtocol)
protocol x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_protocol cobj_x0
foreign import ccall "qtc_QHostAddress_protocol" qtc_QHostAddress_protocol :: Ptr (TQHostAddress a) -> IO CLong
scopeId :: QHostAddress a -> (()) -> IO (String)
scopeId x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_scopeId cobj_x0
foreign import ccall "qtc_QHostAddress_scopeId" qtc_QHostAddress_scopeId :: Ptr (TQHostAddress a) -> IO (Ptr (TQString ()))
class QsetAddress x1 xr where
setAddress :: QHostAddress a -> x1 -> xr
instance QsetAddress ((Int)) (IO ()) where
setAddress x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_setAddress cobj_x0 (toCUInt x1)
foreign import ccall "qtc_QHostAddress_setAddress" qtc_QHostAddress_setAddress :: Ptr (TQHostAddress a) -> CUInt -> IO ()
instance QsetAddress ((String)) (IO (Bool)) where
setAddress x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHostAddress_setAddress1 cobj_x0 cstr_x1
foreign import ccall "qtc_QHostAddress_setAddress1" qtc_QHostAddress_setAddress1 :: Ptr (TQHostAddress a) -> CWString -> IO CBool
setScopeId :: QHostAddress a -> ((String)) -> IO ()
setScopeId x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHostAddress_setScopeId cobj_x0 cstr_x1
foreign import ccall "qtc_QHostAddress_setScopeId" qtc_QHostAddress_setScopeId :: Ptr (TQHostAddress a) -> CWString -> IO ()
toIPv4Address :: QHostAddress a -> (()) -> IO (Int)
toIPv4Address x0 ()
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_toIPv4Address cobj_x0
foreign import ccall "qtc_QHostAddress_toIPv4Address" qtc_QHostAddress_toIPv4Address :: Ptr (TQHostAddress a) -> IO CUInt
toIPv6Address :: QHostAddress a -> (()) -> IO (Q_IPV6ADDR ())
toIPv6Address x0 ()
= withQ_IPV6ADDRResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_toIPv6Address cobj_x0
foreign import ccall "qtc_QHostAddress_toIPv6Address" qtc_QHostAddress_toIPv6Address :: Ptr (TQHostAddress a) -> IO (Ptr (TQ_IPV6ADDR ()))
instance QtoString (QHostAddress a) (()) where
toString x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_toString cobj_x0
foreign import ccall "qtc_QHostAddress_toString" qtc_QHostAddress_toString :: Ptr (TQHostAddress a) -> IO (Ptr (TQString ()))
qHostAddress_delete :: QHostAddress a -> IO ()
qHostAddress_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHostAddress_delete cobj_x0
foreign import ccall "qtc_QHostAddress_delete" qtc_QHostAddress_delete :: Ptr (TQHostAddress a) -> IO ()
|
keera-studios/hsQt
|
Qtc/Network/QHostAddress.hs
|
bsd-2-clause
| 6,241
| 0
| 12
| 983
| 1,776
| 922
| 854
| -1
| -1
|
module ElmFormat.World where
class Monad m => World m where
readFile :: FilePath -> m String
writeFile :: FilePath -> String -> m ()
putStrLn :: String -> m ()
getProgName :: m String
-- instance World IO where
|
nukisman/elm-format-short
|
src/ElmFormat/World.hs
|
bsd-3-clause
| 229
| 0
| 10
| 57
| 75
| 38
| 37
| 6
| 0
|
{-# LANGUAGE TemplateHaskell #-}
module Ppt.Frame.Parser where -- (parseFile, compileFrame) where
import Control.Exception (handle)
import Control.Lens hiding (element, noneOf)
import Control.Monad
import Data.Aeson (decode, encode)
import Data.ByteString.Lazy.Char8 (pack, unpack)
import Data.List
import Data.Maybe (catMaybes, mapMaybe)
import Ppt.Frame.Types
import Ppt.Frame.ParsedRep
import Safe
import Text.ParserCombinators.Parsec (GenParser, ParseError, alphaNum, char,
digit, eof, many, many1, noneOf, sepBy1,
string, try, (<?>), (<|>))
import Text.ParserCombinators.Parsec.Language (javaStyle)
import Text.ParserCombinators.Parsec.Prim (parse)
import qualified Control.Lens.Fold as CLF
import qualified Data.HashMap.Strict as HM
import qualified Text.ParserCombinators.Parsec.Token as P
lexer :: P.TokenParser ()
lexer = P.makeTokenParser
(javaStyle {
P.reservedNames = [
"emit", "frame", "double", "int", "float", "option",
"time", "default", "buffer", "counter", "interval",
"calc", "gap", "var", "mean" ]
, P.caseSensitive = True
} )
ws = P.whiteSpace lexer
lexeme = P.lexeme lexer
symbol = P.symbol lexer
natural = P.natural lexer
parens = P.parens lexer
semi = P.semi lexer
comma = P.comma lexer
identifier= P.identifier lexer
resvd = P.reserved lexer
reservedOp= P.reservedOp lexer
ch = char
type Parser t = GenParser Char () t
primType o = ( resvd "double" >> return (PRational PPDouble Nothing))
<|> ( resvd "int" >> return (PIntegral PPInt Nothing))
<|> ( resvd "float" >> return (PRational PPFloat Nothing ))
<|> ( resvd "time" >> return (PTime Nothing))
<|> ( resvd "counter" >> return (PCounter NotExpanded Nothing))
<?> "type name"
-- TODO: replace primType here with a higher-level production that
-- also takes interval and other keywords. They form a list of
-- qualified-type-specifiers, which get processed by another function
-- into the FMemberElem.
element :: Bool -> EmitOptions -> Parser [FrameElement]
element mul o = do { typ <- primType o
; names <- identifier `sepBy1` comma
; semi
; return (map (\n -> FMemberElem $ FMember typ n mul) names)
}
-- |Primary member parser. This will need some additions over time.
-- The syntax will be:
-- - interval time duration;
-- - int count;
-- - [live] [exported] stat field = gap(duration) / count
frameMember :: EmitOptions -> Parser [FrameElement]
frameMember opts = do { try (resvd "interval" >> (element True opts)) }
<|> (element False opts)
<?> "member declaration"
frame opts = do { resvd "frame"
; name <- identifier
; ch '{'
; ws
; members <- many (frameMember opts)
; ws
; ch '}'
; ws
; return (Frame name (concat members))
}
emitType :: Parser ELanguage
emitType = do { try (char 'C' >> char '+' >> char '+'); return ELangCpp }
<|> do { string "C" >> return ELangC }
<?> "language name"
emitCmd :: Parser ELanguage
emitCmd = do { resvd "emit"
; ws
; lang <- emitType
; ws
; semi
; return lang
}
bufferValue = ( resvd "default" >> return Nothing )
<|> do { ds <- many1 digit; ws; return (Just (read ds)) }
bufferCmd = do { resvd "buffer"
; name <- identifier
; size <- bufferValue
; ws
; semi
; return (EBuffer name size)
}
timeSpecOption :: Parser ETimeSource
timeSpecOption = (resvd "realtime" >> return ETimeClockRealtime)
<|> (resvd "realtime_coarse" >> return ETimeClockRealtimeCoarse)
<|> (resvd "monotonic" >> return ETimeClockMonotonic)
<|> (resvd "monotonic_course" >> return ETimeClockMonotonicCoarse)
<|> (resvd "monotonic_raw" >> return ETimeClockMonotonicRaw)
<|> (resvd "boottime" >> return ETimeClockBoottime)
<|> (resvd "proc_cputime" >> return ETimeClockProcessCputimeId)
<|> (resvd "thread_cputime" >> return ETimeClockThreadCputimeId)
<?> "clock type"
timeOption ::Parser ETimeRep
timeOption = (resvd "timeval" >> return ETimeVal)
<|> do { resvd "timespec"
; kind <- timeSpecOption
; return (ETimeSpec kind)
}
<?> "time type"
boolOption :: Parser Bool
boolOption = (resvd "true" >> return True)
<|> (resvd "True" >> return True)
<|> (resvd "false" >> return False)
<|> (resvd "False" >> return False)
<?> "bool"
runtimeOption :: Parser ERuntime
runtimeOption = do { resvd "multithread"
; val <- boolOption
; return (ERuntime val) }
possiblyQuotedString :: Parser String
possiblyQuotedString = quotedString <|> many (char '_' <|> alphaNum)
quotedString = do
char '"'
x <- many (noneOf "\"" <|> (char '\\' >> char '\"'))
char '"'
return x
tagOption = do { resvd "tag"
; key <- possiblyQuotedString
; ws
; val <- possiblyQuotedString
; return (Tag key val) }
-- TODO(lally): EmitOptions *should* have each type of EOption as a
-- full-fledged member (unless I leave it as a secondary 'misc'
-- bucket, or a generator config, I donno.). But right now I'm saving
-- time to get this out.
data PartialOption = OptLang { _lang :: ELanguage }
| OptBuffer { _buffer :: EBuffer }
| OptTime { _time :: ETimeRep }
| OptRuntime { _runtime :: ERuntime }
| OptTags { _tags :: [ETag] }
| OptCounter { _isNative :: Bool }
| OptDebug { _isDebug :: Bool }
deriving (Eq, Show)
makeLenses ''PartialOption
optionParser :: Parser PartialOption
optionParser = (do { resvd "time"
; timeOpt <- timeOption
; ws
; semi
; return (OptTime timeOpt) })
<|> (do { resvd "runtime"
; run <- runtimeOption
; ws
; semi
; return (OptRuntime run) })
<|> (do { resvd "native_counter"
; ws
; run <- boolOption
; semi
; return (OptCounter run) })
<|> (do { resvd "debug"
; ws
; run <- boolOption
; semi
; return (OptDebug run) })
<|> (do { tag <- tagOption
; ws
; semi
; return (OptTags [tag]) })
<?> "option type: time, runtime, tag"
min1 :: [a] -> String -> Either String a
min1 (x:_) _ = Right x
min1 [] name = Left (name ++ " required")
max1 :: [a] -> String -> a -> Either String a
max1 (x:[]) _ _ = Right x
max1 [] _ def = Right def
max1 _ name def = Left ("Only 1 " ++ name ++ " allowed")
exact1 :: [a] -> String -> Either String a
exact1 (x:[]) _ = Right x
exact1 _ name = Left ("Exactly 1 " ++ name ++ " required")
optionCombine :: [PartialOption] -> Either String EmitOptions
optionCombine opts = let
langs = catMaybes $ map (preview lang) opts
buffers = catMaybes $ map (preview buffer) opts
timereps = catMaybes $ map (preview time) opts
runtimes = catMaybes $ map (preview runtime) opts
lastBool lens = let list = catMaybes $ map (preview lens) opts
len = length list
in drop (max 0 (len-1)) list
-- For other runtime opts, concatenate the lists created in this form
counters = map ENativeCounter $ lastBool isNative
debugOpts = map EDebug $ lastBool isDebug
theTags = concat $ catMaybes $ map (preview tags) opts
in (EmitOptions
<$> max1 buffers "buffer line" (EBuffer "unlisted" Nothing)
<*> exact1 langs "Language"
<*> max1 timereps "Time representation" (
ETimeSpec ETimeClockMonotonic)
<*> max1 runtimes "multithread option" (ERuntime False)
<*> (pure theTags)
<*> (pure (counters ++ debugOpts)))
optionUpdate :: EmitOptions -> [PartialOption] -> EmitOptions
optionUpdate base opts =
let -- Pattern:
-- 'ins' here will be 'opts' above.
replace inpl outl ins outs =
let override = lastOf (traverse . inpl) ins
in maybe (view outl outs) id override
concatenate inpl outl ins outs =
catMaybes [preview outl outs, preview inpl ins]
updateTags ins outs =
let decompose (Tag k v) = (k, v)
compose (k, v) = Tag k v
origTags :: HM.HashMap String String
origTags = HM.fromList $ map decompose $ view eTags outs
newTags :: [(String, String)]
newTags = map decompose $ concat $ mapMaybe (preview tags) ins
combined = foldl (\hm (k, v) -> HM.insert k v hm) origTags newTags
in map compose $ HM.toList combined
langs = catMaybes $ map (preview lang) opts
lang_ = replace lang eLanguage opts base
buffers = catMaybes $ map (preview buffer) opts
buffer_ = replace buffer eBuffer opts base
timereps = catMaybes $ map (preview time) opts
timeRep_ = replace time eTimeRep opts base
runtimes = catMaybes $ map (preview runtime) opts
runtime_ = replace runtime eRuntime opts base
theTags = concat $ catMaybes $ map (preview tags) opts
tags_ = updateTags opts base
in EmitOptions buffer_ lang_ timeRep_ runtime_ tags_ (_eOptions base)
parseHead :: Parser PartialOption
parseHead = (resvd "option" >> optionParser)
<|> (do { r <- emitCmd ; return $OptLang r})
<|> (do { r <- bufferCmd; return$ OptBuffer r})
<?> "header matter"
headParser :: Parser EmitOptions
headParser = do { options <- many parseHead
; case (optionCombine $ options) of
Left msg -> fail msg
Right opts -> return opts
}
parseText :: Show a => Parser a -> String -> String -> Either ParseError a
parseText p input fname = parse (do { ws
; x <- p
; eof
; return x
}) fname input
tparse :: Show a => Parser a -> String -> Either ParseError a
tparse p input = parseText p input "input"
fileParser :: [PartialOption] -> Parser Buffer
fileParser opts = do { ws
; head <- headParser
; let eopts = optionUpdate head opts
; frames <- many (frame eopts)
; return (Buffer head frames) }
parseFile :: String -> [PartialOption] -> IO (Either String Buffer)
parseFile fname opts = do {
let showLeft :: Show a => Either a b -> Either String b
showLeft (Left a) = Left $ show a
showLeft (Right b) = Right b
showErr :: String -> IOError -> IO (Either String a)
showErr fname ex = return $ Left $ fname ++ ": " ++ show ex
; res <- handle (showErr fname) (do {
filetext <- readFile fname ;
return $ showLeft $ parse (fileParser opts) fname filetext
})
; return res
}
-- |Read a buffer from a JSON string
readBuffer :: String -> Maybe Buffer
readBuffer s = decode (pack s)
-- |Show a buffer to a JSON string
saveBuffer :: Buffer -> String
saveBuffer b = unpack $ encode b
|
lally/libmet
|
src/Ppt/Frame/Parser.hs
|
bsd-3-clause
| 12,173
| 0
| 17
| 4,280
| 3,497
| 1,795
| 1,702
| 253
| 2
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Config
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : lemmih@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Utilities for handling saved state such as known packages, known servers and downloaded packages.
-----------------------------------------------------------------------------
module Distribution.Client.Config (
SavedConfig(..),
loadConfig,
showConfig,
showConfigWithComments,
parseConfig,
defaultCabalDir,
defaultConfigFile,
defaultCacheDir,
defaultLogsDir,
) where
import Distribution.Client.Types
( RemoteRepo(..), Username(..), Password(..) )
import Distribution.Client.BuildReports.Types
( ReportLevel(..) )
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand
, ConfigExFlags(..), configureExOptions, defaultConfigExFlags
, InstallFlags(..), installOptions, defaultInstallFlags
, UploadFlags(..), uploadCommand
, ReportFlags(..), reportCommand
, showRepo, parseRepo )
import Distribution.Simple.Setup
( ConfigFlags(..), configureOptions, defaultConfigFlags
, installDirsOptions
, Flag, toFlag, flagToMaybe, fromFlagOrDefault )
import Distribution.Simple.InstallDirs
( InstallDirs(..), defaultInstallDirs
, PathTemplate, toPathTemplate )
import Distribution.ParseUtils
( FieldDescr(..), liftField
, ParseResult(..), locatedErrorMsg, showPWarning
, readFields, warning, lineNo
, simpleField, listField, parseFilePathQ, parseTokenQ )
import qualified Distribution.ParseUtils as ParseUtils
( Field(..) )
import qualified Distribution.Text as Text
( Text(..) )
import Distribution.Simple.Command
( CommandUI(commandOptions), commandDefaultFlags, ShowOrParseArgs(..)
, viewAsFieldDescr )
import Distribution.Simple.Program
( defaultProgramConfiguration )
import Distribution.Simple.Utils
( notice, warn, lowercase )
import Distribution.Compiler
( CompilerFlavor(..), defaultCompilerFlavor )
import Distribution.Verbosity
( Verbosity, normal )
import Data.List
( partition, find )
import Data.Maybe
( fromMaybe )
import Data.Monoid
( Monoid(..) )
import Control.Monad
( when, foldM, liftM )
import qualified Data.Map as Map
import qualified Distribution.Compat.ReadP as Parse
( option )
import qualified Text.PrettyPrint.HughesPJ as Disp
( Doc, render, text, colon, vcat, empty, isEmpty, nest )
import Text.PrettyPrint.HughesPJ
( (<>), (<+>), ($$), ($+$) )
import System.Directory
( createDirectoryIfMissing, getAppUserDataDirectory )
import Network.URI
( URI(..), URIAuth(..) )
import System.FilePath
( (</>), takeDirectory )
import System.Environment
( getEnvironment )
import System.IO.Error
( isDoesNotExistError )
--
-- * Configuration saved in the config file
--
data SavedConfig = SavedConfig {
savedGlobalFlags :: GlobalFlags,
savedInstallFlags :: InstallFlags,
savedConfigureFlags :: ConfigFlags,
savedConfigureExFlags :: ConfigExFlags,
savedUserInstallDirs :: InstallDirs (Flag PathTemplate),
savedGlobalInstallDirs :: InstallDirs (Flag PathTemplate),
savedUploadFlags :: UploadFlags,
savedReportFlags :: ReportFlags
}
instance Monoid SavedConfig where
mempty = SavedConfig {
savedGlobalFlags = mempty,
savedInstallFlags = mempty,
savedConfigureFlags = mempty,
savedConfigureExFlags = mempty,
savedUserInstallDirs = mempty,
savedGlobalInstallDirs = mempty,
savedUploadFlags = mempty,
savedReportFlags = mempty
}
mappend a b = SavedConfig {
savedGlobalFlags = combine savedGlobalFlags,
savedInstallFlags = combine savedInstallFlags,
savedConfigureFlags = combine savedConfigureFlags,
savedConfigureExFlags = combine savedConfigureExFlags,
savedUserInstallDirs = combine savedUserInstallDirs,
savedGlobalInstallDirs = combine savedGlobalInstallDirs,
savedUploadFlags = combine savedUploadFlags,
savedReportFlags = combine savedReportFlags
}
where combine field = field a `mappend` field b
updateInstallDirs :: Flag Bool -> SavedConfig -> SavedConfig
updateInstallDirs userInstallFlag
savedConfig@SavedConfig {
savedConfigureFlags = configureFlags,
savedUserInstallDirs = userInstallDirs,
savedGlobalInstallDirs = globalInstallDirs
} =
savedConfig {
savedConfigureFlags = configureFlags {
configInstallDirs = installDirs
}
}
where
installDirs | userInstall = userInstallDirs
| otherwise = globalInstallDirs
userInstall = fromFlagOrDefault defaultUserInstall $
configUserInstall configureFlags `mappend` userInstallFlag
--
-- * Default config
--
-- | These are the absolute basic defaults. The fields that must be
-- initialised. When we load the config from the file we layer the loaded
-- values over these ones, so any missing fields in the file take their values
-- from here.
--
baseSavedConfig :: IO SavedConfig
baseSavedConfig = do
userPrefix <- defaultCabalDir
logsDir <- defaultLogsDir
worldFile <- defaultWorldFile
return mempty {
savedConfigureFlags = mempty {
configHcFlavor = toFlag defaultCompiler,
configUserInstall = toFlag defaultUserInstall,
configVerbosity = toFlag normal
},
savedUserInstallDirs = mempty {
prefix = toFlag (toPathTemplate userPrefix)
},
savedGlobalFlags = mempty {
globalLogsDir = toFlag logsDir,
globalWorldFile = toFlag worldFile
}
}
-- | This is the initial configuration that we write out to to the config file
-- if the file does not exist (or the config we use if the file cannot be read
-- for some other reason). When the config gets loaded it gets layered on top
-- of 'baseSavedConfig' so we do not need to include it into the initial
-- values we save into the config file.
--
initialSavedConfig :: IO SavedConfig
initialSavedConfig = do
cacheDir <- defaultCacheDir
logsDir <- defaultLogsDir
worldFile <- defaultWorldFile
return mempty {
savedGlobalFlags = mempty {
globalCacheDir = toFlag cacheDir,
globalRemoteRepos = [defaultRemoteRepo],
globalWorldFile = toFlag worldFile
},
savedInstallFlags = mempty {
installSummaryFile = [toPathTemplate (logsDir </> "build.log")],
installBuildReports= toFlag AnonymousReports
}
}
--TODO: misleading, there's no way to override this default
-- either make it possible or rename to simply getCabalDir.
defaultCabalDir :: IO FilePath
defaultCabalDir = getAppUserDataDirectory "cabal"
defaultConfigFile :: IO FilePath
defaultConfigFile = do
dir <- defaultCabalDir
return $ dir </> "config"
defaultCacheDir :: IO FilePath
defaultCacheDir = do
dir <- defaultCabalDir
return $ dir </> "packages"
defaultLogsDir :: IO FilePath
defaultLogsDir = do
dir <- defaultCabalDir
return $ dir </> "logs"
-- | Default position of the world file
defaultWorldFile :: IO FilePath
defaultWorldFile = do
dir <- defaultCabalDir
return $ dir </> "world"
defaultCompiler :: CompilerFlavor
defaultCompiler = fromMaybe GHC defaultCompilerFlavor
defaultUserInstall :: Bool
defaultUserInstall = True
-- We do per-user installs by default on all platforms. We used to default to
-- global installs on Windows but that no longer works on Windows Vista or 7.
defaultRemoteRepo :: RemoteRepo
defaultRemoteRepo = RemoteRepo name uri
where
name = "hackage.haskell.org"
uri = URI "http:" (Just (URIAuth "" name "")) "/packages/archive" "" ""
--
-- * Config file reading
--
loadConfig :: Verbosity -> Flag FilePath -> Flag Bool -> IO SavedConfig
loadConfig verbosity configFileFlag userInstallFlag = addBaseConf $ do
let sources = [
("commandline option", return . flagToMaybe $ configFileFlag),
("env var CABAL_CONFIG", lookup "CABAL_CONFIG" `liftM` getEnvironment),
("default config file", Just `liftM` defaultConfigFile) ]
getSource [] = error "no config file path candidate found."
getSource ((msg,action): xs) =
action >>= maybe (getSource xs) (return . (,) msg)
(source, configFile) <- getSource sources
minp <- readConfigFile mempty configFile
case minp of
Nothing -> do
notice verbosity $ "Config file path source is " ++ source ++ "."
notice verbosity $ "Config file " ++ configFile ++ " not found."
notice verbosity $ "Writing default configuration to " ++ configFile
commentConf <- commentSavedConfig
initialConf <- initialSavedConfig
writeConfigFile configFile commentConf initialConf
return initialConf
Just (ParseOk ws conf) -> do
when (not $ null ws) $ warn verbosity $
unlines (map (showPWarning configFile) ws)
return conf
Just (ParseFailed err) -> do
let (line, msg) = locatedErrorMsg err
warn verbosity $
"Error parsing config file " ++ configFile
++ maybe "" (\n -> ":" ++ show n) line ++ ":\n" ++ msg
warn verbosity $ "Using default configuration."
initialSavedConfig
where
addBaseConf body = do
base <- baseSavedConfig
extra <- body
return (updateInstallDirs userInstallFlag (base `mappend` extra))
readConfigFile :: SavedConfig -> FilePath -> IO (Maybe (ParseResult SavedConfig))
readConfigFile initial file = handleNotExists $
fmap (Just . parseConfig initial) (readFile file)
where
handleNotExists action = catch action $ \ioe ->
if isDoesNotExistError ioe
then return Nothing
else ioError ioe
writeConfigFile :: FilePath -> SavedConfig -> SavedConfig -> IO ()
writeConfigFile file comments vals = do
createDirectoryIfMissing True (takeDirectory file)
writeFile file $ explanation ++ showConfigWithComments comments vals ++ "\n"
where
explanation = unlines
["-- This is the configuration file for the 'cabal' command line tool."
,""
,"-- The available configuration options are listed below."
,"-- Some of them have default values listed."
,""
,"-- Lines (like this one) beginning with '--' are comments."
,"-- Be careful with spaces and indentation because they are"
,"-- used to indicate layout for nested sections."
,"",""
]
-- | These are the default values that get used in Cabal if a no value is
-- given. We use these here to include in comments when we write out the
-- initial config file so that the user can see what default value they are
-- overriding.
--
commentSavedConfig :: IO SavedConfig
commentSavedConfig = do
userInstallDirs <- defaultInstallDirs defaultCompiler True True
globalInstallDirs <- defaultInstallDirs defaultCompiler False True
return SavedConfig {
savedGlobalFlags = commandDefaultFlags globalCommand,
savedInstallFlags = defaultInstallFlags,
savedConfigureExFlags = defaultConfigExFlags,
savedConfigureFlags = (defaultConfigFlags defaultProgramConfiguration) {
configUserInstall = toFlag defaultUserInstall
},
savedUserInstallDirs = fmap toFlag userInstallDirs,
savedGlobalInstallDirs = fmap toFlag globalInstallDirs,
savedUploadFlags = commandDefaultFlags uploadCommand,
savedReportFlags = commandDefaultFlags reportCommand
}
-- | All config file fields.
--
configFieldDescriptions :: [FieldDescr SavedConfig]
configFieldDescriptions =
toSavedConfig liftGlobalFlag
(commandOptions globalCommand ParseArgs)
["version", "numeric-version", "config-file"] []
++ toSavedConfig liftConfigFlag
(configureOptions ParseArgs)
(["builddir", "configure-option"] ++ map fieldName installDirsFields)
--FIXME: this is only here because viewAsFieldDescr gives us a parser
-- that only recognises 'ghc' etc, the case-sensitive flag names, not
-- what the normal case-insensitive parser gives us.
[simpleField "compiler"
(fromFlagOrDefault Disp.empty . fmap Text.disp) (optional Text.parse)
configHcFlavor (\v flags -> flags { configHcFlavor = v })
]
++ toSavedConfig liftConfigExFlag
(configureExOptions ParseArgs)
[] []
++ toSavedConfig liftInstallFlag
(installOptions ParseArgs)
["dry-run", "reinstall", "only"] []
++ toSavedConfig liftUploadFlag
(commandOptions uploadCommand ParseArgs)
["verbose", "check"] []
++ toSavedConfig liftReportFlag
(commandOptions reportCommand ParseArgs)
["verbose"] []
where
toSavedConfig lift options exclusions replacements =
[ lift (fromMaybe field replacement)
| opt <- options
, let field = viewAsFieldDescr opt
name = fieldName field
replacement = find ((== name) . fieldName) replacements
, name `notElem` exclusions ]
optional = Parse.option mempty . fmap toFlag
-- TODO: next step, make the deprecated fields elicit a warning.
--
deprecatedFieldDescriptions :: [FieldDescr SavedConfig]
deprecatedFieldDescriptions =
[ liftGlobalFlag $
listField "repos"
(Disp.text . showRepo) parseRepo
globalRemoteRepos (\rs cfg -> cfg { globalRemoteRepos = rs })
, liftGlobalFlag $
simpleField "cachedir"
(Disp.text . fromFlagOrDefault "") (optional parseFilePathQ)
globalCacheDir (\d cfg -> cfg { globalCacheDir = d })
, liftUploadFlag $
simpleField "hackage-username"
(Disp.text . fromFlagOrDefault "" . fmap unUsername)
(optional (fmap Username parseTokenQ))
uploadUsername (\d cfg -> cfg { uploadUsername = d })
, liftUploadFlag $
simpleField "hackage-password"
(Disp.text . fromFlagOrDefault "" . fmap unPassword)
(optional (fmap Password parseTokenQ))
uploadPassword (\d cfg -> cfg { uploadPassword = d })
]
++ map (modifyFieldName ("user-"++) . liftUserInstallDirs) installDirsFields
++ map (modifyFieldName ("global-"++) . liftGlobalInstallDirs) installDirsFields
where
optional = Parse.option mempty . fmap toFlag
modifyFieldName :: (String -> String) -> FieldDescr a -> FieldDescr a
modifyFieldName f d = d { fieldName = f (fieldName d) }
liftUserInstallDirs :: FieldDescr (InstallDirs (Flag PathTemplate))
-> FieldDescr SavedConfig
liftUserInstallDirs = liftField
savedUserInstallDirs (\flags conf -> conf { savedUserInstallDirs = flags })
liftGlobalInstallDirs :: FieldDescr (InstallDirs (Flag PathTemplate))
-> FieldDescr SavedConfig
liftGlobalInstallDirs = liftField
savedGlobalInstallDirs (\flags conf -> conf { savedGlobalInstallDirs = flags })
liftGlobalFlag :: FieldDescr GlobalFlags -> FieldDescr SavedConfig
liftGlobalFlag = liftField
savedGlobalFlags (\flags conf -> conf { savedGlobalFlags = flags })
liftConfigFlag :: FieldDescr ConfigFlags -> FieldDescr SavedConfig
liftConfigFlag = liftField
savedConfigureFlags (\flags conf -> conf { savedConfigureFlags = flags })
liftConfigExFlag :: FieldDescr ConfigExFlags -> FieldDescr SavedConfig
liftConfigExFlag = liftField
savedConfigureExFlags (\flags conf -> conf { savedConfigureExFlags = flags })
liftInstallFlag :: FieldDescr InstallFlags -> FieldDescr SavedConfig
liftInstallFlag = liftField
savedInstallFlags (\flags conf -> conf { savedInstallFlags = flags })
liftUploadFlag :: FieldDescr UploadFlags -> FieldDescr SavedConfig
liftUploadFlag = liftField
savedUploadFlags (\flags conf -> conf { savedUploadFlags = flags })
liftReportFlag :: FieldDescr ReportFlags -> FieldDescr SavedConfig
liftReportFlag = liftField
savedReportFlags (\flags conf -> conf { savedReportFlags = flags })
parseConfig :: SavedConfig -> String -> ParseResult SavedConfig
parseConfig initial = \str -> do
fields <- readFields str
let (knownSections, others) = partition isKnownSection fields
config <- parse others
let user0 = savedUserInstallDirs config
global0 = savedGlobalInstallDirs config
(user, global) <- foldM parseSections (user0, global0) knownSections
return config {
savedUserInstallDirs = user,
savedGlobalInstallDirs = global
}
where
isKnownSection (ParseUtils.Section _ "install-dirs" _ _) = True
isKnownSection _ = False
parse = parseFields (configFieldDescriptions
++ deprecatedFieldDescriptions) initial
parseSections accum@(u,g) (ParseUtils.Section _ "install-dirs" name fs)
| name' == "user" = do u' <- parseFields installDirsFields u fs
return (u', g)
| name' == "global" = do g' <- parseFields installDirsFields g fs
return (u, g')
| otherwise = do
warning "The install-paths section should be for 'user' or 'global'"
return accum
where name' = lowercase name
parseSections accum f = do
warning $ "Unrecognized stanza on line " ++ show (lineNo f)
return accum
showConfig :: SavedConfig -> String
showConfig = showConfigWithComments mempty
showConfigWithComments :: SavedConfig -> SavedConfig -> String
showConfigWithComments comment vals = Disp.render $
ppFields configFieldDescriptions comment vals
$+$ Disp.text ""
$+$ installDirsSection "user" savedUserInstallDirs
$+$ Disp.text ""
$+$ installDirsSection "global" savedGlobalInstallDirs
where
installDirsSection name field =
ppSection "install-dirs" name installDirsFields
(field comment) (field vals)
------------------------
-- * Parsing utils
--
--FIXME: replace this with something better in Cabal-1.5
parseFields :: [FieldDescr a] -> a -> [ParseUtils.Field] -> ParseResult a
parseFields fields initial = foldM setField initial
where
fieldMap = Map.fromList
[ (name, f) | f@(FieldDescr name _ _) <- fields ]
setField accum (ParseUtils.F line name value) = case Map.lookup name fieldMap of
Just (FieldDescr _ _ set) -> set line value accum
Nothing -> do
warning $ "Unrecognized field " ++ name ++ " on line " ++ show line
return accum
setField accum f = do
warning $ "Unrecognized stanza on line " ++ show (lineNo f)
return accum
-- | This is a customised version of the function from Cabal that also prints
-- default values for empty fields as comments.
--
ppFields :: [FieldDescr a] -> a -> a -> Disp.Doc
ppFields fields def cur = Disp.vcat [ ppField name (getter def) (getter cur)
| FieldDescr name getter _ <- fields]
ppField :: String -> Disp.Doc -> Disp.Doc -> Disp.Doc
ppField name def cur
| Disp.isEmpty cur = Disp.text "--" <+> Disp.text name <> Disp.colon <+> def
| otherwise = Disp.text name <> Disp.colon <+> cur
ppSection :: String -> String -> [FieldDescr a] -> a -> a -> Disp.Doc
ppSection name arg fields def cur =
Disp.text name <+> Disp.text arg
$$ Disp.nest 2 (ppFields fields def cur)
installDirsFields :: [FieldDescr (InstallDirs (Flag PathTemplate))]
installDirsFields = map viewAsFieldDescr installDirsOptions
|
yihuang/cabal-install
|
Distribution/Client/Config.hs
|
bsd-3-clause
| 19,554
| 0
| 20
| 4,410
| 4,384
| 2,363
| 2,021
| 386
| 4
|
module Process.CssBox where
import Data.Char
import Data.DataTreeCSS
import qualified Data.Map as Map
import Data.Maybe
import Graphics.UI.WX hiding (get)
import Graphics.UI.WXCore
import Data.CommonTypes
import Data.Property
import Process.Attributes
import Process.DownloadProcess
import Utils.TextExtend
import Utils.Utiles
-- build a font from the list of css properties
buildFont props
= let fsze = toInt $ (\vp -> vp/1.6) $ unPixelUsedValue "CssBox.hs" (props `get` "font-size")
-- la funcion que le aplico es porque wxwidgets trabaja con points
fwgt = toFontWeight $ computedValue (props `get` "font-weight")
fstl = toFontStyle $ computedValue (props `get` "font-style")
(family, face) = getFont_Family_Face (computedValue (props `get` "font-family"))
in fontDefault { _fontSize = fsze
, _fontWeight = fwgt
, _fontShape = fstl
, _fontFamily = family
, _fontFace = face
}
where toFontWeight w
= case w of
KeyValue "bold" -> WeightBold
otherwise -> WeightNormal
toFontStyle s
= case s of
KeyValue "italic" -> ShapeItalic
KeyValue "oblique" -> ShapeSlant
otherwise -> ShapeNormal
getFont_Family_Face fn
= case fn of
ListValue list -> case head list of
StringValue str -> (FontDefault,str)
KeyValue "serif" -> (FontRoman,"")
KeyValue "sans-serif" -> (FontSwiss,"")
KeyValue "cursive" -> (FontScript,"")
KeyValue "fantasy" -> (FontDecorative,"")
KeyValue "monospace" -> (FontModern,"")
otherwise -> (FontDefault,"") -- por si acaso
otherwise -> (FontDefault,"") -- por si acaso
-- get the size(width and height) of a string with the list of css properties
getSizeBox cnt wn props
= do pnl <- window wn []
let myFont = buildFont props
set pnl [font := myFont]
let newCnt = applyTextTransform props cnt
(Size wContent hContent,d,e) <- getTextSize pnl newCnt
windowDestroy pnl
--let (wExternal,hExternal) = getExternalSizeBox props -- realmente necesito hacer esto? porque siempre los bordes del texto son nulas
return (wContent,hContent,d,e)
-- (width,height,descent,externalLeading)
-- descent is the distance from baseline to the bottom's font
applyTextTransform props str
= case usedValue (props `get` "text-transform") of
KeyValue "none"
-> str
KeyValue "capitalize"
-> let newStr = words str
fcap (c:cs) = toUpper c : cs
in unwords $ map fcap newStr
KeyValue "uppercase"
-> map toUpper str
KeyValue "lowercase"
-> map toLower str
-- get the margin properties from a list of css properties
getMarginProperties props = map toInt [ maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "margin-top" )
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "margin-right" )
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "margin-bottom")
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "margin-left" )]
-- get the border-width properties from a list of css properties
getBorderProperties props = let bst = getBorderStyleProperties props
bwd = map toInt [ maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "border-top-width" )
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "border-right-width" )
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "border-bottom-width")
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "border-left-width" )]
in zipWith (\str wd -> if str=="none" then 0 else wd) bst bwd
-- get the padding properties from a list of css properties
getPaddingProperties props = map toInt [ maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "padding-top" )
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "padding-right" )
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "padding-bottom")
, maybe 0 (unPixelUsedValue "CssBox.hs") (props `getM` "padding-left" )]
-- get the border-style properties from a list of css properties
getBorderStyleProperties props = [ maybe "none" unKeyComputedValue (props `getM` "border-top-style" )
, maybe "none" unKeyComputedValue (props `getM` "border-right-style" )
, maybe "none" unKeyComputedValue (props `getM` "border-bottom-style")
, maybe "none" unKeyComputedValue (props `getM` "border-left-style" )]
-- get the border-color properties from a list of css properties
getBorderColorProperties props = [ maybe (0,0,0) unKeyComputedColor (props `getM` "border-top-color" )
, maybe (0,0,0) unKeyComputedColor (props `getM` "border-right-color" )
, maybe (0,0,0) unKeyComputedColor (props `getM` "border-bottom-color")
, maybe (0,0,0) unKeyComputedColor (props `getM` "border-left-color" )]
-- get the length of the external boxes (margin, border and padding area) of a css box as a tuple
getExternalSizeBox props =
let [mt,mr,mb,ml] = getMarginProperties props
[bt,br,bb,bl] = getBorderProperties props
[ppt,ppr,ppb,ppl] = getPaddingProperties props
in (ml+bl+ppl+ppr+br+mr,mt+bt+ppt+ppb+bb+mb)
-- get the length of the external boxes (margin, border and padding area) of a css box as a cuadtuple
getExternalSizeBox4Tuple props =
let [mt,mr,mb,ml] = getMarginProperties props
[bt,br,bb,bl] = getBorderProperties props
[ppt,ppr,ppb,ppl] = getPaddingProperties props
in ( ml+bl+ppl -- external left
, ppr+br+mr -- external right
, mt+bt+ppt -- external top
, ppb+bb+mb -- external bottom
)
-- get the (x,y) position of the content area of a css box
getTopLeftContentPoint tp props =
let [mt,_,_,ml] = checkWithTypeElement tp $ getMarginProperties props
[bt,_,_,bl] = checkWithTypeElement tp $ getBorderProperties props
[ppt,_,_,ppl] = checkWithTypeElement tp $ getPaddingProperties props
in (ml+bl+ppl,mt+bt+ppt)
-- build a marker
boxMarker cnt wn (x,y) (w,h) continuation props attrs replaced
= do hb <- box cnt wn (x,y) (w,h) continuation props attrs replaced
return ()
-- build a container box
boxContainer = box ""
-- build a text box
box cnt wn (x,y) (w,h) continuation props attrs replaced
= do pnl <- scrolledWindow wn [ size := sz w h
, on paint := onBoxPaint cnt continuation props attrs replaced
]
windowMove pnl (pt x y)
return pnl
-- paint a css box
onBoxPaint cnt tp props attrs replaced dc rt@(Rect x y w h) = do
-- setting the font style
let myFont = buildFont props
dcSetFontStyle dc myFont
-- margin points
let [mt,mr,mb,ml] = checkWithTypeElement tp $ getMarginProperties props
--border color
let toColor (r,g,b) = rgb r g b
let [bct,bcr,bcb,bcl] = map toColor $ getBorderColorProperties props
-- text color
let txtColor = toColor $ maybe (0,0,0) unKeyComputedColor (props `getM` "color")
-- background color, brush
let bkgBrush = case props `getM` "background-color" of
Just p -> case computedValue p of
KeyValue "transparent" -> brushTransparent
KeyColor value -> brushSolid (toColor value)
Nothing -> error "unexpected value at background-color property"
-- border style and border widths
let toPenStyle s = case s of
"hidden" -> PenTransparent
"dotted" -> PenDash DashDot
"dashed" -> PenDash DashLong
_ -> PenSolid -- solid border
let [bst,bsr,bsb,bsl] = getBorderStyleProperties props
let [bt,br,bb,bl] = checkWithTypeElement tp $ getBorderProperties props
-- padding widths
let [ppt,ppr,ppb,ppl] = checkWithTypeElement tp $ getPaddingProperties props
-- obtaining border points
let (bx1,bx2) = (ml,w-mr-1)
let (by1,by2) = (mt,h-mb-1)
-- painting the background-color
let bkgRect = rect (pt bx1 by1) (sz (bx2 - bx1 + 1) (by2 - by1 + 1))
drawRect dc bkgRect [brush := bkgBrush, pen := penTransparent]
-- painting the borders
paintLine dc (bx1,by1) (bx2,by1) bt True True [penWidth := 1, penColor := bct, penKind := toPenStyle bst]
paintLine dc (bx2,by1) (bx2,by2) br False False [penWidth := 1, penColor := bcr, penKind := toPenStyle bsr]
paintLine dc (bx2,by2) (bx1,by2) bb True False [penWidth := 1, penColor := bcb, penKind := toPenStyle bsb]
paintLine dc (bx1,by2) (bx1,by1) bl False True [penWidth := 1, penColor := bcl, penKind := toPenStyle bsl]
-- building the top-left point in the content
let ptContent = pt (ml+bl+ppl) (mt+bt+ppt)
-- painting the content
if replaced
then do path <- getImagePath (getAttribute "src" attrs)
let szimg = sz (w-mr-br-ppr-1-ml-bl-ppl) (h-mb-bb-ppb-1-mt-bt-ppt)
img1 <- imageCreateFromFile path
img2 <- imageScale img1 szimg
drawImage dc img2 ptContent []
--putStrLn $ show w ++ " " ++ show mr ++ " " ++ show br ++ " " ++ show ppr ++ " " ++ show ml ++ " " ++ show bl ++ " " ++ show ppl
--drawRect dc (rect ptContent szimg) []
return ()
else case usedValue (props `get` "display") of
{- KeyValue "block"
-> return ()
KeyValue "inline"
-} _
-> do -- text
let newCnt = applyTextTransform props cnt
drawText dc newCnt ptContent [color := txtColor]
-- decoration
case usedValue (props `get` "text-decoration") of
KeyValue "none" -> return ()
ListValue list -> do metrics <- getFullTextExtent dc newCnt
mapM_ (doDecoration dc ptContent txtColor metrics) list
doDecoration dc (Point x y) txtColor (Size width height, baseline, a) value
= case value of
KeyValue "underline"
-> do let yb = height - baseline + 2
line dc (pt 0 yb) (pt width yb) [penColor := txtColor]
KeyValue "overline"
-> do let yb = y
line dc (pt 0 yb) (pt width yb) [penColor := txtColor]
KeyValue "line-through"
-> do let yb = height - baseline - ((height - baseline) `div` 3)
line dc (pt 0 yb) (pt width yb) [penColor := txtColor]
-- check if a consider that width according to the TypeElement
checkWithTypeElement tp lst@(wt:wr:wb:wl:[])
= case tp of
Full -> lst -- I consider everything
Init -> [wt,0 ,wb,wl] -- I don't consider the right width
Medium -> [wt,0 ,wb,0 ] -- I don't consider the left and right width
End -> [wt,wr,wb,0 ] -- I don't consider the left width
-- paint a line of a specific width
paintLine _ _ _ 0 _ _ _
= return ()
paintLine dc (x1,y1) (x2,y2) width kind dir style
= do line dc (pt x1 y1) (pt x2 y2) style
if kind -- kind -> | True == Horizontal, | False == Vertical
then do let (y3,y4) = if dir -- dir -> | True == Up2Down, | False == Bottom2Up
then (y1+1,y2+1)
else (y1-1,y2-1)
paintLine dc (x1,y3) (x2,y4) (width - 1) kind dir style
else do let (x3,x4) = if dir -- dir -> | True == Left2Right, | False == Right2Left
then (x1+1,x2+1)
else (x1-1,x2-1)
paintLine dc (x3,y1) (x4,y2) (width - 1) kind dir style
|
carliros/Simple-San-Simon-Functional-Web-Browser
|
src/Process/CssBox.hs
|
bsd-3-clause
| 13,074
| 0
| 21
| 4,624
| 3,532
| 1,872
| 1,660
| 187
| 11
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Command.Info
( CommandInfo(..)
, name
, aliases
, permissions
, help
, dynCmdInfo
)
where
import Control.Lens
import Data.Aeson.TH
import Data.Text (Text)
import Command.Permissions (Permissions)
import qualified Command.Permissions as Perms
data CommandInfo = CommandInfo
{ _name :: Text
, _aliases :: [Text]
, _permissions :: Permissions
, _help :: Text
} deriving (Show)
makeLenses ''CommandInfo
$(deriveJSON defaultOptions{fieldLabelModifier = drop 1} ''CommandInfo)
dynCmdInfo :: Text -> CommandInfo
dynCmdInfo txt = CommandInfo
{ _name = txt
, _aliases = []
, _permissions = Perms.Anyone
, _help = "Usage !" <> txt <> " [optional username, w/ or w/out @]"
}
|
frublox/aichanbot
|
src/Command/Info.hs
|
bsd-3-clause
| 901
| 0
| 10
| 269
| 202
| 121
| 81
| 28
| 1
|
{-# LANGUAGE OverloadedStrings, NamedFieldPuns,
ScopedTypeVariables, CPP, RecordWildCards #-}
{-# OPTIONS_GHC -fwarn-unused-imports #-}
-- This module implements the commandline driver for the paragrep program.
{-
[2011.02.21]
Observing Mac/Linux differences. First with respect to the
matching of the "empty_line" pattern against lines containing only
spaces. Second, with the failure (or lack of) on broken symlinks.
The latter may be because of a problem with System.Directory.Tree.
[2011.03.08]
Switching from System.Directory.Tree to System.FilePath.Find
[2011.04.06]
Removing the WholeFile partition method from the default hierarchy.
-}
module Paragrep.Executable (paragrepMain) where
import Control.Monad
import Data.Maybe
import Data.Char
import Data.IORef
import Numeric (readDec)
import Prelude as P
import System.Environment
import System.Console.GetOpt
import System.Exit
import Paragrep.Globals
import Paragrep.Lib
import Paragrep.Server
-- Considering possible pager type functionality for navigating results....
-- import UI.HSCurses.Curses
-- import UI.HSCurses.Widgets
--------------------------------------------------------------------------------
-- Command line options
--------------------------------------------------------------------------------
-- | Recognized flags, for documentation see `options` below.
data CmdFlag =
NoColor
| Help
| HierarchyList String
| CaseInsensitive
| FollowIncludes
| Root String
| Verbose (Maybe Int)
| Version
| PrependDatePart
| WholeFile
| RunServer Int
deriving (Show,Eq)
-- <boilerplate> Pure boilerplate, would be nice to scrap it:
getRoot (Root x) = Just x
getRoot _ = Nothing
getHierarchy (HierarchyList str) = Just str
getHierarchy _ = Nothing
getVerbose (Verbose x) = Just x
getVerbose _ = Nothing
getRunServer (RunServer x) = Just x
getRunServer _ = Nothing
-- </boilerplate>
-- | Command line options and their meaning.
options :: [OptDescr CmdFlag]
options =
[
Option ['h'] ["help"] (NoArg Help) "show this help information"
, Option ['r'] ["root"] (ReqArg Root "PATH") "set the root file or directory to search"
, Option ['i'] ["ignore-case"] (NoArg CaseInsensitive) "treat file contents and search terms as completely lower-case"
, Option ['v'] ["verbose"] (OptArg (Verbose . fmap safeRead) "LVL")
"set or increment verbosity level 0-4, default 1"
, Option ['V'] ["version"] (NoArg Version) "Show version number."
, Option [] [] (NoArg undefined) ""
, Option ['d'] ["date"] (NoArg PrependDatePart) "prepend a splitter on date-tags '[2011.02.21]' to the hierarchy list"
, Option ['w'] ["wholefile"] (NoArg WholeFile) "append the WholeFile granularity to the list of splitters"
-- TODO / FIXME -- these still need to be implemented:
-- , Option [] ["custom"] (ReqArg HierarchyList "LIST") "use a custom hierarchy of partition methods"
-- , Option ['f'] ["follow"] (NoArg FollowIncludes) "follow \\include{...} expressions like the original 1988 'help'"
-- , Option ['n'] ["nocolor"] (NoArg NoColor) "disable ANSI color output"
, Option ['s'] ["server"] (ReqArg (RunServer . read) "PORT") "run as HTTP server listening on PORT"
]
usage = "\nVersion "++version++"\n"++
"Usage: "++progName++" [OPTION...] searchterm1 [searchterm2 ...]\n\n"++
"The "++progName++" program provides flexible search at paragraph\n"++
"granularity, or other custom granularities. A list of partitioning\n"++
"methods splits files into progressively smaller pieces. The program\n"++
"prints matching spans of text as output, printing the smallest delimited\n" ++
"span that matches.\n"++
" \n"++
"\nOptions include:\n"
defaultErr errs = error $ "ERROR!\n" ++ (P.concat errs ++ usageInfo usage options)
safeRead :: String -> Int
safeRead s =
case readDec s of
[(n,"")] -> n
_ -> error$ "Could not read '"++ s ++"' as an integer."
--------------------------------------------------------------------------------
-- The imperative main function.
--------------------------------------------------------------------------------
paragrepMain =
do
args <- getArgs
(opts,terms) <-
case getOpt Permute options args of
(o,rest,[]) -> return (o,rest)
(_,_,errs) -> defaultErr errs
------------------------------------------------------------
-- First handle execution modes that do something completely
-- different and exit through a separate control path:
when (Version `elem` opts)$ do
putStrLn$ "\nVersion: "++version
exitSuccess
when (Help `elem` opts)$ do
putStrLn$ usageInfo usage options
exitSuccess
------------------------------------------------------------
let caseinsensitive = CaseInsensitive `elem` opts
case mapMaybe getVerbose opts of
[] -> return ()
[Nothing] -> modifyIORef verbosityRef (+1)
[Just n] -> writeIORef verbosityRef n
_ -> error "More than one -verbose flag not currently allowed."
let
root = case mapMaybe getRoot opts of
[] -> "."
[r] -> r
_ -> error$ progName++": More than one --root option not currently supported"
hier1 = [partition_paragraphs]
hier2 = if PrependDatePart `elem` opts
then partition_dateTags : hier1
else hier1
default_hierarchy = hier2
initmethod =
if WholeFile `elem` opts
then "WholeFile"
else ""
hierarchy = case mapMaybe getHierarchy opts of
[] -> default_hierarchy
[str] -> error "Custom hierarchy descriptions not implemented yet."
----------------------------------------------------------------------
-- Choose either batch or server execution mode:
case (mapMaybe getRunServer opts) of
[port] -> do chatter 1$ "Running server on port " ++ show port
runServer port root
chatter 1$ "Server exited."
exitSuccess
a:b:t -> error$ "Cannot run server on multiple ports: "++ show (a:b:t)
[] -> do
----------------------------------------------------------------------
when (terms == [])$ defaultErr [" NO SEARCH TERMS"]
chatter 2$ "Searching for terms: " ++ show terms
txtfiles <- listAllFiles root
allhelp <- findHelpFiles caseinsensitive initmethod terms hierarchy txtfiles
-- Print out the structure of the match tree:
-- putStrLn$ render (pPrint allhelp)
printMatchTree allhelp
----------------------------------------------------------------------
-- BL.-putStrLn "Done."
----------------------------------------------------------------------
|
rrnewton/paragrep
|
Paragrep/Executable.hs
|
bsd-3-clause
| 6,893
| 79
| 18
| 1,542
| 1,226
| 675
| 551
| 113
| 12
|
module Main where
import Graphomania.Main
main :: IO ()
main = defaultMain
|
schernichkin/BSPM
|
graphomania/app/Main.hs
|
bsd-3-clause
| 87
| 0
| 6
| 24
| 24
| 14
| 10
| 4
| 1
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.TextureEnvDot3
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.TextureEnvDot3 (
-- * Extension Support
glGetARBTextureEnvDot3,
gl_ARB_texture_env_dot3,
-- * Enums
pattern GL_DOT3_RGBA_ARB,
pattern GL_DOT3_RGB_ARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/TextureEnvDot3.hs
|
bsd-3-clause
| 679
| 0
| 5
| 95
| 52
| 39
| 13
| 8
| 0
|
module Marvin.Adapter.Telegram.Internal.Common where
import Control.Applicative
import Control.Concurrent.Async.Lifted
import Control.Concurrent.Chan.Lifted
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Logger
import Data.Aeson as A hiding (Error, Success)
import Data.Aeson.Types as A (Parser, parseEither)
import qualified Data.ByteString.Lazy as BS
import Data.Char (isSpace)
import Data.Foldable (asum)
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import Data.Traversable (for)
import Lens.Micro.Platform
import Marvin.Adapter hiding (mkAdapterId)
import Marvin.Interpolate.All
import Marvin.Types
import Network.Wreq as Wreq
import Network.Wreq.Types as Wreq
import Util
data APIResponse a
= Success { description :: Maybe T.Text, result :: a }
| Error { errorCode :: Int, errDescription :: T.Text }
-- | The telegram adapter type for a particular update type. Either 'Push' or 'Poll'
data TelegramAdapter updateType = TelegramAdapter
newtype TelegramFileId = TelegramFileId { unwrapFileId :: T.Text } deriving Eq
instance FromJSON TelegramFileId where parseJSON = withText "expected string" (pure . TelegramFileId)
instance ToJSON TelegramFileId where toJSON = String . unwrapFileId
data TelegramUpdate any
= Ev (Event (TelegramAdapter any))
| Ignored
| Unhandeled
-- | Chat type as defined by the telegram api
data ChatType
= PrivateChat
| GroupChat
| SupergroupChat
| ChannelChat
class HasId_ s a | s -> a where id_ :: Lens' s a
-- | A user object as contained in the telegram update objects
data TelegramUser = TelegramUser
{ telegramUserId_ :: Integer
, telegramUserFirstName :: Maybe L.Text
, telegramUserLastName :: Maybe L.Text
, telegramUserUsername :: L.Text
}
data TelegramRemoteFileStruct
= RemoteAudio
{ telegramRemoteFileStructDuration :: Integer
, telegramRemoteFileStructPerformer :: Maybe L.Text
, telegramRemoteFileStructTitle :: Maybe L.Text
}
| RemoteDocument
| RemoteSticker
{ telegramRemoteFileStructWidth :: Integer
, telegramRemoteFileStructHeight :: Integer
, telegramRemoteFileStructEmoji :: Maybe L.Text
}
| RemoteVideo
{ telegramRemoteFileStructWidth :: Integer
, telegramRemoteFileStructHeight :: Integer
, telegramRemoteFileStructDuration :: Integer
}
| RemoteVoice
{ telegramRemoteFileStructDuration :: Integer
}
data TelegramRemoteFile a = TelegramRemoteFile
{ telegramRemoteFileStruct :: TelegramRemoteFileStruct
, telegramRemoteFileSize :: Integer
, telegramRemoteFileFid :: TelegramFileId
, telegramRemoteFileFileType :: Maybe L.Text
, telegramRemoteFileName :: Maybe L.Text
}
data TelegramLocalFileStruct
= LocalPhoto
| LocalAudio
{ telegramLocalFileStructDuration :: Maybe Int
, telegramLocalFileStructPerformer :: Maybe L.Text
-- , telegramLocalFileStructShowTitle :: Maybe L.Text
}
| LocalDocument
| LocalVideo
{ telegramLocalFileStructDuration :: Maybe Int
, telegramLocalFileStructWidth :: Maybe Int
, telegramLocalFileStructHeight :: Maybe Int
}
data TelegramLocalFile = TelegramLocalFile
{ telegramLocalFileStruct :: TelegramLocalFileStruct
, telegramLocalFileContent :: FileContent
, telegramLocalFileName :: L.Text
, telegramLocalFileFileType :: Maybe L.Text
, telegramLocalFileDisableNotification :: Maybe Bool
, telegramLocalFileFromRef :: Maybe TelegramFileId
, telegramLocalFileCaption :: Maybe L.Text
}
makeFields ''TelegramUser
makeFields ''TelegramRemoteFileStruct
makeFields ''TelegramRemoteFile
makeFields ''TelegramLocalFileStruct
makeFields ''TelegramLocalFile
instance HasUrl (TelegramRemoteFile a) (Maybe L.Text) where url = lens (const Nothing) const
instance HasCreationDate (TelegramRemoteFile a) (TimeStamp a) where creationDate = lens (const undefined) const
instance HasName TelegramUser (Maybe L.Text) where
name = lens
(\u -> (mappend <$> u^.firstName <*> (mappend " " <$> u^.lastName)) <|> u^.firstName <|> u^.lastName)
(flip set_)
where
set_ Nothing = (firstName .~ Nothing) . (lastName .~ Nothing)
set_ (Just n) = (firstName .~ Just first) . (lastName .~ if L.null rest then Nothing else Just rest)
where
(first, rest') = L.break (== ' ') n
rest = L.tail rest'
-- | A telegram chat object as contained in telegram updates
data TelegramChat = TelegramChat
{ telegramChatId_ :: Integer
, telegramChatType_ :: ChatType
, telegramChatUsername :: Maybe L.Text
, telegramChatFirstName :: Maybe L.Text
, telegramChatLastName :: Maybe L.Text
}
makeFields ''TelegramChat
instance HasName TelegramChat (Maybe L.Text) where
name = username
instance FromJSON ChatType where
parseJSON = withText "expected string" $
\case
"private" -> pure PrivateChat
"group" -> pure GroupChat
"supergroup" -> pure SupergroupChat
"channel" -> pure ChannelChat
a -> fail $(isS "Unknown chat type #{a}")
instance FromJSON TelegramUser where
parseJSON = withObject "user must be object" $ \o ->
TelegramUser
<$> o .: "id"
<*> (Just <$> o .: "first_name")
<*> o .:? "last_name"
<*> (maybe (o .: "first_name") return =<< o .:? "username")
instance FromJSON TelegramChat where
parseJSON = withObject "channel must be object" $ \o ->
TelegramChat
<$> o .: "id"
<*> o .: "type"
<*> o .:? "username"
<*> o .:? "first_name"
<*> o .:? "last_name"
parseFileHelper :: (Object -> Parser TelegramRemoteFileStruct) -> Value -> Parser (Object, TelegramRemoteFileStruct)
parseFileHelper f = withObject "expected object" $ \o -> (o, ) <$> f o
parseTelegramAudio :: Object -> Parser TelegramRemoteFileStruct
parseTelegramAudio o =
RemoteAudio
<$> o .: "duration"
<*> o .:? "performer"
<*> o .:? "title"
parseTelegramDocument :: Object -> Parser TelegramRemoteFileStruct
parseTelegramDocument = const (return RemoteDocument)
parseTelegramSticker :: Object -> Parser TelegramRemoteFileStruct
parseTelegramSticker o =
RemoteSticker
<$> o .: "width"
<*> o .: "height"
<*> o .:? "emoji"
parseTelegramVideo :: Object -> Parser TelegramRemoteFileStruct
parseTelegramVideo o =
RemoteVideo
<$> o .: "width"
<*> o .: "height"
<*> o .: "duration"
parseTelegramVoice :: Object -> Parser TelegramRemoteFileStruct
parseTelegramVoice o = RemoteVoice <$> o .: "duration"
parseTelegramFile :: Object -> Parser (TelegramRemoteFile a)
parseTelegramFile o = do
(o', mediaStruct) <- msum
[ o .: "audio" >>= parseFileHelper parseTelegramAudio
, o .: "document" >>= parseFileHelper parseTelegramDocument
, o .: "sticker" >>= parseFileHelper parseTelegramSticker
, o .: "video" >>= parseFileHelper parseTelegramVideo
, o .: "voice" >>= parseFileHelper parseTelegramVoice
]
TelegramRemoteFile mediaStruct
<$> o' .:? "file_size" .!= (-1)
<*> o' .: "file_id"
<*> o' .: "file_name"
<*> o' .:? "mime_type"
instance MkTelegram a => FromJSON (TelegramUpdate a) where
parseJSON = withObject "expected object" inner
where
inner o = msum [isMessage, isPost, isDocument, isUnhandeled]
where
isMessage = Ev <$> (o .: "message" >>= msgParser)
isPost = Ev <$> (o .: "channel_post" >>= msgParser)
isUnhandeled = return Unhandeled
isDocument = do
file <- parseTelegramFile o
ev <- FileSharedEvent
<$> o .: "from"
<*> o .: "chat"
<*> pure file
<*> (o .: "date" >>= timestampFromNumber)
pure $ Ev ev
telegramSupportedUpdates :: [T.Text]
telegramSupportedUpdates =
[ "message"
, "channel_post"
]
msgParser :: Value -> Parser (Event (TelegramAdapter a))
msgParser = withObject "expected message object" $ \o ->
MessageEvent
<$> o .: "from"
<*> o .: "chat"
<*> o .: "text"
<*> (o .: "date" >>= timestampFromNumber)
apiResponseParser :: (Value -> Parser a) -> Value -> Parser (APIResponse a)
apiResponseParser innerParser = withObject "expected object" $ \o -> do
ok <- o .: "ok"
if ok
then Success <$> o .:? "description" <*> (o .: "result" >>= innerParser)
else Error <$> o .: "error_code" <*> o .: "description"
execAPIMethod :: (MkTelegram b, Postable p)
=> (Value -> Parser a)
-> String
-> p
-> AdapterM (TelegramAdapter b) (Either String (APIResponse a))
execAPIMethod = execAPIMethodWith defaults
execAPIMethodWith :: (MkTelegram b, Postable p)
=> Wreq.Options
-> (Value -> Parser a)
-> String
-> p
-> AdapterM (TelegramAdapter b) (Either String (APIResponse a))
execAPIMethodWith opts innerParser methodName fparams = do
token <- requireFromAdapterConfig "token"
res <- retry (3 :: Int) (liftIO (postWith opts $(isS "https://api.telegram.org/bot#{token :: String}/#{methodName}") fparams))
return $ res >>= eitherDecode . (^. responseBody) >>= parseEither (apiResponseParser innerParser)
where
retry n a = (Right <$> a) `catch` \e -> if n <= 0
then -- TODO only catch appropriate exceptions
return $ Left $ displayException (e :: SomeException)
else retry (succ n) a
getChannelNameImpl :: TelegramChat -> AdapterM (TelegramAdapter a) L.Text
getChannelNameImpl c = return $ fromMaybe "<unnamed>" $
c^.username <|> (L.unwords <$> sequence [c^.firstName, c^.lastName]) <|> c^.firstName
messageChannelImpl :: MkTelegram a => TelegramChat -> L.Text -> AdapterM (TelegramAdapter a) ()
messageChannelImpl chat msg = do
res <- execAPIMethod msgParser "sendMessage" ["chat_id" := (chat^.id_) , "text" := msg]
case res of
Left err -> error $(isS "Unparseable JSON #{err}")
Right Success{} -> return ()
Right (Error code desc) ->
logErrorN $(isT "Sending message failed with #{code}: #{desc}")
stripWhiteSpaceMay :: L.Text -> Maybe L.Text
stripWhiteSpaceMay t =
case L.uncons t of
Just (c, _) | isSpace c -> Just $ L.stripStart t
_ -> Nothing
runnerImpl :: MkTelegram a => EventConsumer (TelegramAdapter a) -> AdapterM (TelegramAdapter a) ()
runnerImpl handler = do
msgChan <- newChan
let eventGetter = mkEventGetter msgChan
a <- async eventGetter
link a
forever $ do
logDebugN "Starting to read"
d <- readChan msgChan
logDebugN "Recieved message"
case d of
Ev ev@(MessageEvent u chat msg ts) -> do
botname <- L.toLower <$> getBotname
let strippedMsg = L.stripStart msg
let lmsg = L.toLower strippedMsg
handler $ case (chat^.type_, asum $ map ((\prefix -> if prefix `L.isPrefixOf` lmsg then Just $ L.drop (L.length prefix) strippedMsg else Nothing) >=> stripWhiteSpaceMay) [botname, L.cons '@' botname, L.cons '/' botname]) of
(PrivateChat, _) -> CommandEvent u chat msg ts
(_, Nothing) -> ev
(_, Just m') -> CommandEvent u chat m' ts
Ev ev -> handler ev
Ignored -> return ()
Unhandeled -> logDebugN $(isT "Unhadeled event.")
toFtype :: TelegramLocalFileStruct -> (String, T.Text)
toFtype LocalPhoto = ("Photo", "photo")
toFtype LocalAudio{} = ("Audio", "audio")
toFtype LocalDocument = ("Document", "document")
toFtype LocalVideo{} = ("Video", "video")
partShow :: Show a => T.Text -> a -> Part
partShow name' = partString name' . show
mkStructParts :: TelegramLocalFile -> [Maybe Part]
mkStructParts f =
case f^.struct of
LocalAudio duration' performer' ->
[ partText "performer" . L.toStrict <$> performer'
, partShow "duration" <$> duration'
, Just ("title" `partText` L.toStrict (f^.name)) -- perhaps make this optional
]
LocalVideo duration' width' height' ->
[ partShow "duration" <$> duration'
, partShow "width" <$> width'
, partShow "height" <$> height'
]
_ -> []
shareFileImpl :: MkTelegram a => TelegramLocalFile -> [TelegramChat] -> AdapterM (TelegramAdapter a) (Either L.Text (TelegramRemoteFile (TelegramAdapter a)))
shareFileImpl localFile targets = do
contentPart <- case localFile^.fromRef of
Just (TelegramFileId fid') -> return $ propName `partText` fid'
Nothing ->
(propName `partLBS`) <$> case localFile^.content of
FileInMemory bs -> return bs
FileOnDisk path -> liftIO $ BS.readFile path
fmap (handleRes <=< headRes) $ for targets $ \chan ->
execAPIMethod parser ("send" ++ ftype) $ catMaybes $
[ Just $ "chat_id" `partString` show (chan ^. id_)
, Just contentPart
, partText "caption" . L.toStrict <$> localFile^.caption
, partText "diable_notofication" . boolToText <$> localFile^.disableNotification
] ++ structParts
where
parser = withObject "expected object" parseTelegramFile
(ftype, propName) = toFtype (localFile^.struct)
structParts = mkStructParts localFile
boolToText True = "true"
boolToText _ = "false"
headRes [] = Left "No targets specified"
headRes (x:_) = mapLeft L.pack x
handleRes Success{result=a} = pure a
handleRes Error{errDescription=d} = Left $ L.fromStrict d
-- | Class to enable polymorphism over update mechanics for 'TelegramAdapter'
class MkTelegram a where
mkEventGetter :: Chan (TelegramUpdate a) -> AdapterM (TelegramAdapter a) ()
mkAdapterId :: AdapterId (TelegramAdapter a)
instance MkTelegram a => IsAdapter (TelegramAdapter a) where
type User (TelegramAdapter a) = TelegramUser
type Channel (TelegramAdapter a) = TelegramChat
adapterId = mkAdapterId
initAdapter = return TelegramAdapter
runAdapter = runnerImpl
resolveChannel _ = do
logErrorN "Channel resolving not supported"
return Nothing
resolveUser _ = do
logErrorN "User resolving not supported"
return Nothing
messageChannel = messageChannelImpl
instance MkTelegram a => SupportsFiles (TelegramAdapter a) where
type RemoteFile (TelegramAdapter a) = TelegramRemoteFile (TelegramAdapter a)
type LocalFile (TelegramAdapter a) = TelegramLocalFile
shareFile = shareFileImpl
readFileBytes remoteFile = do
res <- execAPIMethod (withObject "expected object" (.: "file_path")) "getFile" ["file_id" := unwrapFileId (remoteFile^.fid)]
case res of
Left err -> logErrorN $(isT "Error when downloading file: #{err}") >> return Nothing
Right Error{errDescription=desc} -> logErrorN $(isT "Error when downloading file: #{desc}") >> return Nothing
Right Success{result=Nothing} -> logErrorN $(isT "Fetched file had no filepath") >> return Nothing
Right Success{result=Just fp} -> do
token <- requireFromAdapterConfig "token"
fres <- liftIO $ get $(is "https://api.telegram.org/bot#{token}/#{fp}")
case fres ^. responseStatus . statusCode of
200 -> return $ Just $ fres ^. responseBody
code -> do
logErrorN $(isT "Non 200 Response when downloading file: #{code} - #{view (responseStatus.statusMessage) fres}")
return Nothing
newLocalFile fname content' = pure $ TelegramLocalFile LocalDocument content' fname Nothing Nothing Nothing Nothing
|
JustusAdam/marvin
|
src/Marvin/Adapter/Telegram/Internal/Common.hs
|
bsd-3-clause
| 16,862
| 0
| 29
| 4,837
| 4,352
| 2,248
| 2,104
| -1
| -1
|
{-# LANGUAGE ScopedTypeVariables, TypeOperators, TypeFamilies, FlexibleContexts, UndecidableInstances #-}
module Foreign.Storable.Generic (
-- * Generic Storable class
GStorable(..),
-- * Default functions
sizeOfDefault,
alignmentDefault,
peekDefault,
peekByteOffDefault,
peekElemOffDefault,
pokeDefault,
pokeByteOffDefault,
pokeElemOffDefault,
-- * Wrapper
StorableWrapper(..),
) where
import Control.Monad
import Data.Word
import Foreign.Ptr
import Foreign.Storable
import GHC.Generics
-- | Generic Storable class
class GStorable f where
gsizeOf :: f a -> Int
galignment :: f a -> Int
galignment = gsizeOf
{-# INLINABLE galignment #-}
gpeek :: Ptr (f a) -> IO (f a)
gpeekByteOff :: Ptr (f a) -> Int -> IO (f a)
gpeekByteOff addr off = gpeek (addr `plusPtr` off)
{-# INLINEABLE gpeekByteOff #-}
gpeekElemOff :: Ptr (f a) -> Int -> IO (f a)
gpeekElemOff addr idx = gpeek (addr `plusPtr` (idx * gsizeOf (undefined :: f a)))
{-# INLINEABLE gpeekElemOff #-}
gpoke :: Ptr (f a) -> f a -> IO ()
gpokeByteOff :: Ptr (f a) -> Int -> f a -> IO ()
gpokeByteOff addr off x = gpoke (addr `plusPtr` off) x
{-# INLINEABLE gpokeByteOff #-}
gpokeElemOff :: Ptr (f a) -> Int -> f a -> IO ()
gpokeElemOff addr idx x = gpoke (addr `plusPtr` (idx * gsizeOf (undefined :: f a))) x
{-# INLINEABLE gpokeElemOff #-}
sizeOfDefault :: (Generic a, GStorable (Rep a)) => a -> Int
sizeOfDefault = gsizeOf . from
alignmentDefault :: (Generic a, GStorable (Rep a)) => a -> Int
alignmentDefault = galignment . from
peekDefault :: (Generic a, GStorable (Rep a)) => Ptr a -> IO a
peekDefault ptr = return . to =<< gpeek (castPtr ptr)
peekByteOffDefault :: (Generic a, GStorable (Rep a)) => Ptr a -> Int -> IO a
peekByteOffDefault ptr ofs = return . to =<< gpeekByteOff (castPtr ptr) ofs
peekElemOffDefault :: (Generic a, GStorable (Rep a)) => Ptr a -> Int -> IO a
peekElemOffDefault ptr idx = return . to =<< gpeekElemOff (castPtr ptr) idx
pokeDefault :: (Generic a, GStorable (Rep a)) => Ptr a -> a -> IO ()
pokeDefault ptr = gpoke (castPtr ptr) . from
pokeByteOffDefault :: (Generic a, GStorable (Rep a)) => Ptr a -> Int -> a -> IO ()
pokeByteOffDefault ptr ofs = gpokeByteOff (castPtr ptr) ofs . from
pokeElemOffDefault :: (Generic a, GStorable (Rep a)) => Ptr a -> Int -> a -> IO ()
pokeElemOffDefault ptr idx = gpokeElemOff (castPtr ptr) idx . from
newtype StorableWrapper a = StorableWrapper { unStorableWrapper :: a }
instance (Generic a, GStorable (Rep a)) => Storable (StorableWrapper a) where
sizeOf _ = gsizeOf $ from (undefined :: a)
{-# INLINEABLE sizeOf #-}
alignment _ = galignment $ from (undefined :: a)
{-# INLINEABLE alignment #-}
peek ptr = return . StorableWrapper . to =<< gpeek (castPtr ptr)
{-# INLINEABLE peek #-}
poke ptr (StorableWrapper v) = gpoke (castPtr ptr) $ from v
{-# INLINEABLE poke #-}
instance GStorable U1 where
gsizeOf _ = 0
{-# INLINEABLE gsizeOf #-}
gpeek _ = return U1
{-# INLINEABLE gpeek #-}
gpoke _ _ = return ()
{-# INLINEABLE gpoke #-}
instance (GStorable a, GStorable b) => GStorable (a :*: b) where
gsizeOf _ = gsizeOf (undefined :: a x) + gsizeOf (undefined :: b x)
{-# INLINEABLE gsizeOf #-}
gpeek ptr = do
a <- gpeek (castPtr ptr)
b <- gpeekByteOff (castPtr ptr) (gsizeOf a)
return $ a :*: b
{-# INLINEABLE gpeek #-}
gpoke ptr (a :*: b) = do
gpoke (castPtr ptr) a
gpokeByteOff (castPtr ptr) (gsizeOf a) b
{-# INLINEABLE gpoke #-}
instance (GStorable a, GStorable b) => GStorable (a :+: b) where
gsizeOf _ = 4 + (gsizeOf (undefined :: a x) `max` gsizeOf (undefined :: b x))
{-# INLINEABLE gsizeOf #-}
gpeek ptr = do
tag <- peek (castPtr ptr)
if (tag :: Word32) == 0
then return L1 `ap` gpeekByteOff (castPtr ptr) 4
else return R1 `ap` gpeekByteOff (castPtr ptr) 4
{-# INLINEABLE gpeek #-}
gpoke ptr (L1 val) = poke (castPtr ptr) (0 :: Word32) >> gpokeByteOff (castPtr ptr) 4 val
gpoke ptr (R1 val) = poke (castPtr ptr) (1 :: Word32) >> gpokeByteOff (castPtr ptr) 4 val
{-# INLINEABLE gpoke #-}
instance (GStorable a) => GStorable (M1 i c a) where
gsizeOf _ = gsizeOf (undefined :: a x)
{-# INLINEABLE gsizeOf #-}
gpeek ptr = return M1 `ap` gpeek (castPtr ptr)
{-# INLINEABLE gpeek #-}
gpoke ptr (M1 val) = gpoke (castPtr ptr) val
{-# INLINEABLE gpoke #-}
instance (Storable a) => GStorable (K1 i a) where
gsizeOf _ = sizeOf (undefined :: a)
{-# INLINEABLE gsizeOf #-}
gpeek ptr = return K1 `ap` peek (castPtr ptr)
{-# INLINEABLE gpeek #-}
gpoke ptr (K1 val) = poke (castPtr ptr) val
{-# INLINEABLE gpoke #-}
|
tanakh/generic-storable
|
Foreign/Storable/Generic.hs
|
bsd-3-clause
| 4,670
| 0
| 14
| 1,016
| 1,770
| 914
| 856
| 83
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Network.AMI
(Parameters,
ActionType, EventType,
ActionID, ResponseType,
EventHandler, ResponseHandler,
Packet (..),
ConnectInfo (..),
open, openMD5,
close,
withAMI, withAMI_MD5,
runAMI, runAMI',
sendAction,
handleEvent,
wait
) where
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Instances
import Control.Monad.State
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as L
import Data.Digest.Pure.MD5
import Network
import Network.Socket
import System.IO
type Parameters = [(B.ByteString, B.ByteString)]
type ActionType = B.ByteString
type EventType = B.ByteString
type ActionID = B.ByteString
type ResponseType = B.ByteString
type EventHandler = Parameters -> AMI ()
type ResponseHandler = Packet -> AMI ()
-- | Any AMI packet
data Packet =
Action ActionID ActionType Parameters
| Response ActionID ResponseType Parameters [B.ByteString]
| Event EventType Parameters
deriving (Eq, Show)
data AMIState = AMIState {
amiHandle :: Maybe Handle,
amiActionID :: Integer,
amiResponseHandlers :: M.Map ActionID ResponseHandler,
amiEventHandlers :: M.Map EventType EventHandler }
-- | Info needed to connect and authenticate in Asterisk
data ConnectInfo = ConnectInfo {
ciHost :: String,
ciPort :: Int,
ciUsername :: B.ByteString,
ciSecret :: B.ByteString }
deriving (Eq, Show)
-- | The AMI monad
type AMI a = StateT AMIState IO a
-- | Return next ActionID
inc :: AMI ActionID
inc = do
st <- get
let n = 1 + amiActionID st
put $ st {amiActionID = n}
return (B.pack $ show n)
-- | Get connection handle
getHandle :: AMI Handle
getHandle = do
mbh <- gets amiHandle
case mbh of
Nothing -> fail "Connection is not opened"
Just h -> return h
-- | Add an event handler
handleEvent :: EventType -> EventHandler -> AMI ()
handleEvent t handler = modify add
where
add st = st {amiEventHandlers = M.insert t handler (amiEventHandlers st)}
-- | Send an Action packet and install a handler for the anser
sendAction :: ActionType -> Parameters -> ResponseHandler -> AMI ()
sendAction t ps handler = do
i <- inc
modify (\st -> st {amiResponseHandlers = M.insert i (change i handler) (amiResponseHandlers st)})
h <- getHandle
liftIO $ sendPacket h (Action i t ps)
where
change i hdlr p = do
hdlr p
modify $ \st -> st {amiResponseHandlers = M.delete i (amiResponseHandlers st)}
-- | Wait for (one) response or event
wait :: AMI ()
wait = do
h <- getHandle
str <- liftIO $ readUntilEmptyLine h
case parse str of
Left err -> fail err
Right (Action {}) -> fail "Unexpected Action from server"
Right p@(Response i t _ _) -> do
st <- get
case M.lookup i (amiResponseHandlers st) of
Nothing -> return ()
Just handler -> do
put $ st {amiResponseHandlers = M.delete i (amiResponseHandlers st)}
handler p
Right (Event t ps) -> do
m <- gets amiEventHandlers
case M.lookup t m of
Nothing -> return ()
Just handler -> handler ps
-- | Open a connection to Asterisk and authenticate
open :: ConnectInfo -> AMI ()
open info = do
h <- liftIO $ connectTo (ciHost info) (PortNumber $ fromIntegral $ ciPort info)
modify $ \st -> st {amiHandle = Just h}
s <- liftIO $ B.hGetLine h
sendAction "Login" [("Username", ciUsername info), ("Secret", ciSecret info)] handleAuth
wait
where
handleAuth :: Packet -> AMI ()
handleAuth (Response _ "Success" _ _) = return ()
handleAuth _ = fail "Authentication failed"
-- | Open a connection to Asterisk and authenticate using MD5 challenge
openMD5 :: ConnectInfo -> AMI ()
openMD5 info = do
h <- liftIO $ connectTo (ciHost info) (PortNumber $ fromIntegral $ ciPort info)
modify $ \st -> st {amiHandle = Just h}
s <- liftIO $ B.hGetLine h
sendAction "Challenge" [("AuthType", "md5")] challenger
wait
where
challenger :: Packet -> AMI ()
challenger (Response _ "Success" [("Challenge", ch)] _) = do
let key = B.pack $ show $ md5 $ L.fromChunks [ch `B.append` ciSecret info]
sendAction "Login" [("AuthType", "md5"),
("Username", ciUsername info),
("Key", key)] auth
challenger _ = fail "Cannot get challenge for MD5 authentication"
auth :: Packet -> AMI ()
auth (Response _ "Success" _ _) = return ()
auth x = fail $ "MD5 authentication failed: " ++ show x
-- | Close Asterisk connection
close :: AMI ()
close = do
sendAction "Logoff" [] (const $ return ())
wait
h <- getHandle
liftIO $ hClose h
modify $ \st -> st {amiHandle = Nothing}
-- | Connect, execute acions, disconnect
withAMI :: ConnectInfo -> AMI a -> IO a
withAMI info ami = runAMI $ do
open info
r <- ami
close
return r
-- | Connect (using MD5 challenge), execute acions, disconnect
withAMI_MD5 :: ConnectInfo -> AMI a -> IO a
withAMI_MD5 info ami = runAMI $ do
openMD5 info
r <- ami
close
return r
-- | Send one AMI packet
sendPacket :: Handle -> Packet -> IO ()
sendPacket h p = do
let s = format p `B.append` "\r\n"
B.hPutStr h s
B.hPutStr h "\r\n"
hFlush h
-- | Run AMI actions
runAMI :: AMI a -> IO a
runAMI ami = evalStateT ami (AMIState Nothing 0 M.empty M.empty)
-- | Run AMI actions, starting with given ActionID
runAMI' :: Integer -> AMI a -> IO a
runAMI' z ami = evalStateT ami (AMIState Nothing z M.empty M.empty)
readUntilEmptyLine :: Handle -> IO B.ByteString
readUntilEmptyLine h = do
str <- B.hGetLine h
if (str == "\n") || (str == "\r") || (str == "\r\n")
then return str
else do
next <- readUntilEmptyLine h
return $ str `B.append` next
linesB y = h : if B.null t then [] else linesB (B.drop 2 t)
where (h,t) = B.breakSubstring "\r\n" y
-- | Parse packet
parse :: B.ByteString -> Either String Packet
parse str = uncurry toPacket =<< (toPairs [] $ B.split '\r' str)
where
toPairs :: Parameters -> [B.ByteString] -> Either String (Parameters, [B.ByteString])
toPairs [] [] = Left "Empty packet"
toPairs acc [] = Right (acc, [])
toPairs acc (s:ss) =
case B.split ':' s of
[] -> return (acc, [])
[n,v] -> let new = (n, B.dropWhile (== ' ') v)
in toPairs (acc ++ [new]) ss
x -> Right (acc, (s:ss))
toPacket :: Parameters -> [B.ByteString] -> Either String Packet
toPacket [] text = Right $ Response "" "text" [] text
toPacket ((k,v):pairs) text =
case k of
"Action" -> toAction v pairs
"Response" -> toResponse v pairs text
"Event" -> toEvent v pairs
_ -> Left $ "Invalid first parameter: " ++ show v
getField :: B.ByteString -> Parameters -> Either String (B.ByteString, Parameters)
getField x ps = go x [] ps
go x acc [] = Left "No field in packet"
go x acc ((k,v):rest)
| x == k = Right (v, acc ++ rest)
| otherwise = go x ((k,v):acc) rest
toAction name pairs = do
(i, ps) <- getField "ActionID" pairs
return $ Action i name ps
toResponse name pairs text = do
(i, ps) <- getField "ActionID" pairs
return $ Response i name ps text
toEvent name pairs = Right $ Event name pairs
format :: Packet -> B.ByteString
format (Action i name ps) = formatParams $ [("Action", name), ("ActionID", i)] ++ ps
format (Response i name ps text) =
formatParams ([("Response", name), ("ActionID", i)] ++ ps) `B.append` "\r\n" `B.append` B.intercalate "\r\n" text
format (Event name ps) = formatParams $ [("Event", name)] ++ ps
formatParams :: Parameters -> B.ByteString
formatParams pairs = B.intercalate "\r\n" $ map one pairs
where
one (k,v) = k `B.append` ": " `B.append` v
|
trskop/AMI
|
Network/AMI.hs
|
bsd-3-clause
| 7,923
| 0
| 22
| 1,992
| 2,870
| 1,474
| 1,396
| 199
| 10
|
-- | Quote ASCII arguments to be passed through the Unix shell.
--
-- For safety, these functions drop all non-ASCII characters.
module System.Posix.Escape
( escape
, escapeMany
) where
import qualified System.Posix.Escape.Unicode as U
import Data.Char
-- | Wrap a @String@ so it can be used within a Unix shell command line, and
-- end up as a single argument to the program invoked.
escape :: String -> String
escape = U.escape . filter isAscii
-- | Wrap some @String@s as separate arguments, by inserting spaces before and
-- after each. This will break if, for example, prefixed with a backslash.
escapeMany :: [String] -> String
escapeMany = U.escapeMany . map (filter isAscii)
|
kmcallister/posix-escape
|
System/Posix/Escape.hs
|
bsd-3-clause
| 700
| 0
| 8
| 131
| 92
| 57
| 35
| 9
| 1
|
-- Mini Benchmark
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables, CPP #-}
module Main where
import Control.Concurrent
import Control.DeepSeq
import Criterion.IO
import Criterion.Main
import Criterion.Types
import qualified Data.ByteString as B
import Flat
import qualified Data.Map as M
import Report
import System.Directory
import System.FilePath
import System.Process (callCommand)
import Test.Data.Flat
import Test.Data.Values
import Test.E
import Test.E.Flat
import Data.List
import Common
#ifdef ETA_VERSION
import Data.Function (trampoline)
import GHC.IO (trampolineIO)
#else
trampoline = id
trampolineIO = id
#endif
bname = bench . benchName
setupEnv = do
-- print treeLarge
let small = replicate 1000 (1 :: Int)
let v1 = (E3_3, B.pack [193])
let v2 = (E16_16, B.pack [241])
-- let v3 = valTest longBoolListT
let v3 = "" -- (E256_256, B.pack [255, 1])
let v4 = valTest treeLargeT
-- print $ "Size Tree is " ++ show (getSize treeLarge)
-- print $ "Size Tree " ++ show (5999999 == getSize treeLarge)
-- print $ "Size Tree " ++ show (6999999 == getSize treeLarge)
-- print $ unwords ["Size S3 ",show ( == getSize S1treeLarge)
-- print v4
-- putStrLn $ take 1000 . show $ (unflat $ enc v4 :: Either DecodeException ((Tree N)))
-- big <-
-- map length . words <$>
-- readFile "/Users/titto/workspace/flat/benchmarks/Simple.hs"
return (v1, v2, v3, v4)
projDir = "."
workDir = projDir </> "benchmarks/data"
tmpDir = "/tmp"
main = trampolineIO
$ do
createDirectoryIfMissing True workDir
mainBench_ (reportsFile workDir)
prtMeasures
prtMeasures = do
-- delete measures to avoid eta read bug
-- #ifdef ETA_VERSION
-- deleteMeasures workDir
-- #endif
ms <- updateMeasures_ workDir
printMeasuresDiff ms
-- printMeasuresAll ms
printMeasuresCurrent ms
mainBench_ jsonReportFile = defaultMainWith
(defaultConfig { jsonFile = Just jsonReportFile })
-- ,verbosity=Quiet -- avoid trouble with unit of measure character
[runtime]
where
runtime = env setupEnv
$ \ ~(v1, v2, v3, v4) -> bgroup "basic" [basicTest "large Tree" v4]
-- ,basicTest "large list" v3
basicTest name v = bgroup
name
[ bname "size" $ whnf (getSize . val) v
, bname "enc" $ whnf (\tv -> B.length (bs (encod (val tv))) == encLen tv) v
, bname "dec eq" $ whnf (\tv -> val tv == val tv) v
, bname "dec" $ whnf (\tv -> decod (enc tv) == Right (val tv)) v]
--compilation = bgroup "compilation-basic" [bench "compile" $ nfIO comp]
-- comp = do
-- callCommand $ concat ["touch ", projDir </> "test/Test/E/Flat.hs"]
-- callCommand $
-- concat
-- ["cd ", projDir, ";stack ghc -- -isrc -itest -O test/Test/E/Flat.hs"]
fromRight (Right a) = a
-- fromRight (Left e) = error $ show e
|
tittoassini/flat
|
benchmarks/Mini.hs
|
bsd-3-clause
| 3,009
| 0
| 18
| 753
| 609
| 337
| 272
| 56
| 1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, PatternGuards, TypeSynonymInstances #-}
-- --------------------------------------------------------------------------
-- |
-- Module : XMonad.Operations
-- Copyright : (c) Spencer Janssen 2007
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : dons@cse.unsw.edu.au
-- Stability : unstable
-- Portability : not portable, Typeable deriving, mtl, posix
--
-- Operations.
--
-----------------------------------------------------------------------------
module XMonad.Operations where
import XMonad.Core
import XMonad.Layout (Full(..))
import qualified XMonad.StackSet as W
import Data.Maybe
import Data.Monoid (Endo(..))
import Data.List (nub, (\\), find)
import Data.Bits ((.|.), (.&.), complement, testBit)
import Data.Ratio
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.State
import qualified Control.Exception.Extensible as C
import System.Posix.Process (executeFile)
import Graphics.X11.Xlib
import Graphics.X11.Xinerama (getScreenInfo)
import Graphics.X11.Xlib.Extras
-- ---------------------------------------------------------------------
-- |
-- Window manager operations
-- manage. Add a new window to be managed in the current workspace.
-- Bring it into focus.
--
-- Whether the window is already managed, or not, it is mapped, has its
-- border set, and its event mask set.
--
manage :: Window -> X ()
manage w = whenX (not <$> isClient w) $ withDisplay $ \d -> do
sh <- io $ getWMNormalHints d w
let isFixedSize = sh_min_size sh /= Nothing && sh_min_size sh == sh_max_size sh
isTransient <- isJust <$> io (getTransientForHint d w)
rr <- snd `fmap` floatLocation w
-- ensure that float windows don't go over the edge of the screen
let adjust (W.RationalRect x y wid h) | x + wid > 1 || y + h > 1 || x < 0 || y < 0
= W.RationalRect (0.5 - wid/2) (0.5 - h/2) wid h
adjust r = r
f ws | isFixedSize || isTransient = W.float w (adjust rr) . W.insertUp w . W.view i $ ws
| otherwise = W.insertUp w ws
where i = W.tag $ W.workspace $ W.current ws
mh <- asks (manageHook . config)
g <- appEndo <$> userCodeDef (Endo id) (runQuery mh w)
windows (g . f)
-- | unmanage. A window no longer exists, remove it from the window
-- list, on whatever workspace it is.
--
unmanage :: Window -> X ()
unmanage = windows . W.delete
-- | Kill the specified window. If we do kill it, we'll get a
-- delete notify back from X.
--
-- There are two ways to delete a window. Either just kill it, or if it
-- supports the delete protocol, send a delete event (e.g. firefox)
--
killWindow :: Window -> X ()
killWindow w = withDisplay $ \d -> do
wmdelt <- atom_WM_DELETE_WINDOW ; wmprot <- atom_WM_PROTOCOLS
protocols <- io $ getWMProtocols d w
io $ if wmdelt `elem` protocols
then allocaXEvent $ \ev -> do
setEventType ev clientMessage
setClientMessageEvent ev w wmprot 32 wmdelt 0
sendEvent d w False noEventMask ev
else killClient d w >> return ()
-- | Kill the currently focused client.
kill :: X ()
kill = withFocused killWindow
-- ---------------------------------------------------------------------
-- Managing windows
-- | windows. Modify the current window list with a pure function, and refresh
windows :: (WindowSet -> WindowSet) -> X ()
windows f = do
XState { windowset = old } <- get
let oldvisible = concatMap (W.integrate' . W.stack . W.workspace) $ W.current old : W.visible old
newwindows = W.allWindows ws \\ W.allWindows old
ws = f old
XConf { display = d , normalBorder = nbc, focusedBorder = fbc } <- ask
mapM_ setInitialProperties newwindows
whenJust (W.peek old) $ \otherw -> io $ setWindowBorder d otherw nbc
modify (\s -> s { windowset = ws })
-- notify non visibility
let tags_oldvisible = map (W.tag . W.workspace) $ W.current old : W.visible old
gottenhidden = filter (flip elem tags_oldvisible . W.tag) $ W.hidden ws
mapM_ (sendMessageWithNoRefresh Hide) gottenhidden
-- for each workspace, layout the currently visible workspaces
let allscreens = W.screens ws
summed_visible = scanl (++) [] $ map (W.integrate' . W.stack . W.workspace) allscreens
rects <- fmap concat $ forM (zip allscreens summed_visible) $ \ (w, vis) -> do
let wsp = W.workspace w
this = W.view n ws
n = W.tag wsp
tiled = (W.stack . W.workspace . W.current $ this)
>>= W.filter (`M.notMember` W.floating ws)
>>= W.filter (`notElem` vis)
viewrect = screenRect $ W.screenDetail w
-- just the tiled windows:
-- now tile the windows on this workspace, modified by the gap
(rs, ml') <- runLayout wsp { W.stack = tiled } viewrect `catchX`
runLayout wsp { W.stack = tiled, W.layout = Layout Full } viewrect
updateLayout n ml'
let m = W.floating ws
flt = [(fw, scaleRationalRect viewrect r)
| fw <- filter (flip M.member m) (W.index this)
, Just r <- [M.lookup fw m]]
vs = flt ++ rs
io $ restackWindows d (map fst vs)
-- return the visible windows for this workspace:
return vs
let visible = map fst rects
mapM_ (uncurry tileWindow) rects
whenJust (W.peek ws) $ \w -> io $ setWindowBorder d w fbc
mapM_ reveal visible
setTopFocus
-- hide every window that was potentially visible before, but is not
-- given a position by a layout now.
mapM_ hide (nub (oldvisible ++ newwindows) \\ visible)
-- all windows that are no longer in the windowset are marked as
-- withdrawn, it is important to do this after the above, otherwise 'hide'
-- will overwrite withdrawnState with iconicState
mapM_ (flip setWMState withdrawnState) (W.allWindows old \\ W.allWindows ws)
isMouseFocused <- asks mouseFocused
unless isMouseFocused $ clearEvents enterWindowMask
asks (logHook . config) >>= userCodeDef ()
-- | Produce the actual rectangle from a screen and a ratio on that screen.
scaleRationalRect :: Rectangle -> W.RationalRect -> Rectangle
scaleRationalRect (Rectangle sx sy sw sh) (W.RationalRect rx ry rw rh)
= Rectangle (sx + scale sw rx) (sy + scale sh ry) (scale sw rw) (scale sh rh)
where scale s r = floor (toRational s * r)
-- | setWMState. set the WM_STATE property
setWMState :: Window -> Int -> X ()
setWMState w v = withDisplay $ \dpy -> do
a <- atom_WM_STATE
io $ changeProperty32 dpy w a a propModeReplace [fromIntegral v, fromIntegral none]
-- | hide. Hide a window by unmapping it, and setting Iconified.
hide :: Window -> X ()
hide w = whenX (gets (S.member w . mapped)) $ withDisplay $ \d -> do
io $ do selectInput d w (clientMask .&. complement structureNotifyMask)
unmapWindow d w
selectInput d w clientMask
setWMState w iconicState
-- this part is key: we increment the waitingUnmap counter to distinguish
-- between client and xmonad initiated unmaps.
modify (\s -> s { waitingUnmap = M.insertWith (+) w 1 (waitingUnmap s)
, mapped = S.delete w (mapped s) })
-- | reveal. Show a window by mapping it and setting Normal
-- this is harmless if the window was already visible
reveal :: Window -> X ()
reveal w = withDisplay $ \d -> do
setWMState w normalState
io $ mapWindow d w
whenX (isClient w) $ modify (\s -> s { mapped = S.insert w (mapped s) })
-- | The client events that xmonad is interested in
clientMask :: EventMask
clientMask = structureNotifyMask .|. enterWindowMask .|. propertyChangeMask
-- | Set some properties when we initially gain control of a window
setInitialProperties :: Window -> X ()
setInitialProperties w = asks normalBorder >>= \nb -> withDisplay $ \d -> do
setWMState w iconicState
io $ selectInput d w clientMask
bw <- asks (borderWidth . config)
io $ setWindowBorderWidth d w bw
-- we must initially set the color of new windows, to maintain invariants
-- required by the border setting in 'windows'
io $ setWindowBorder d w nb
-- | refresh. Render the currently visible workspaces, as determined by
-- the 'StackSet'. Also, set focus to the focused window.
--
-- This is our 'view' operation (MVC), in that it pretty prints our model
-- with X calls.
--
refresh :: X ()
refresh = windows id
-- | clearEvents. Remove all events of a given type from the event queue.
clearEvents :: EventMask -> X ()
clearEvents mask = withDisplay $ \d -> io $ do
sync d False
allocaXEvent $ \p -> fix $ \again -> do
more <- checkMaskEvent d mask p
when more again -- beautiful
-- | tileWindow. Moves and resizes w such that it fits inside the given
-- rectangle, including its border.
tileWindow :: Window -> Rectangle -> X ()
tileWindow w r = withDisplay $ \d -> do
bw <- (fromIntegral . wa_border_width) <$> io (getWindowAttributes d w)
-- give all windows at least 1x1 pixels
let least x | x <= bw*2 = 1
| otherwise = x - bw*2
io $ moveResizeWindow d w (rect_x r) (rect_y r)
(least $ rect_width r) (least $ rect_height r)
-- ---------------------------------------------------------------------
-- | Returns 'True' if the first rectangle is contained within, but not equal
-- to the second.
containedIn :: Rectangle -> Rectangle -> Bool
containedIn r1@(Rectangle x1 y1 w1 h1) r2@(Rectangle x2 y2 w2 h2)
= and [ r1 /= r2
, x1 >= x2
, y1 >= y2
, fromIntegral x1 + w1 <= fromIntegral x2 + w2
, fromIntegral y1 + h1 <= fromIntegral y2 + h2 ]
-- | Given a list of screens, remove all duplicated screens and screens that
-- are entirely contained within another.
nubScreens :: [Rectangle] -> [Rectangle]
nubScreens xs = nub . filter (\x -> not $ any (x `containedIn`) xs) $ xs
-- | Cleans the list of screens according to the rules documented for
-- nubScreens.
getCleanedScreenInfo :: MonadIO m => Display -> m [Rectangle]
getCleanedScreenInfo = io . fmap nubScreens . getScreenInfo
-- | rescreen. The screen configuration may have changed (due to
-- xrandr), update the state and refresh the screen, and reset the gap.
rescreen :: X ()
rescreen = do
xinesc <- withDisplay getCleanedScreenInfo
windows $ \ws@(W.StackSet { W.current = v, W.visible = vs, W.hidden = hs }) ->
let (xs, ys) = splitAt (length xinesc) $ map W.workspace (v:vs) ++ hs
(a:as) = zipWith3 W.Screen xs [0..] $ map SD xinesc
in ws { W.current = a
, W.visible = as
, W.hidden = ys }
-- ---------------------------------------------------------------------
-- | setButtonGrab. Tell whether or not to intercept clicks on a given window
setButtonGrab :: Bool -> Window -> X ()
setButtonGrab grab w = do
pointerMode <- asks $ \c -> if clickJustFocuses (config c)
then grabModeAsync
else grabModeSync
withDisplay $ \d -> io $ if grab
then forM_ [button1, button2, button3] $ \b ->
grabButton d b anyModifier w False buttonPressMask
pointerMode grabModeSync none none
else ungrabButton d anyButton anyModifier w
-- ---------------------------------------------------------------------
-- Setting keyboard focus
-- | Set the focus to the window on top of the stack, or root
setTopFocus :: X ()
setTopFocus = withWindowSet $ maybe (setFocusX =<< asks theRoot) setFocusX . W.peek
-- | Set focus explicitly to window 'w' if it is managed by us, or root.
-- This happens if X notices we've moved the mouse (and perhaps moved
-- the mouse to a new screen).
focus :: Window -> X ()
focus w = local (\c -> c { mouseFocused = True }) $ withWindowSet $ \s -> do
let stag = W.tag . W.workspace
curr = stag $ W.current s
mnew <- maybe (return Nothing) (fmap (fmap stag) . uncurry pointScreen)
=<< asks mousePosition
root <- asks theRoot
case () of
_ | W.member w s && W.peek s /= Just w -> windows (W.focusWindow w)
| Just new <- mnew, w == root && curr /= new
-> windows (W.view new)
| otherwise -> return ()
-- | Call X to set the keyboard focus details.
setFocusX :: Window -> X ()
setFocusX w = withWindowSet $ \ws -> do
dpy <- asks display
-- clear mouse button grab and border on other windows
forM_ (W.current ws : W.visible ws) $ \wk ->
forM_ (W.index (W.view (W.tag (W.workspace wk)) ws)) $ \otherw ->
setButtonGrab True otherw
-- If we ungrab buttons on the root window, we lose our mouse bindings.
whenX (not <$> isRoot w) $ setButtonGrab False w
hints <- io $ getWMHints dpy w
protocols <- io $ getWMProtocols dpy w
wmprot <- atom_WM_PROTOCOLS
wmtf <- atom_WM_TAKE_FOCUS
currevt <- asks currentEvent
let inputHintSet = wmh_flags hints `testBit` inputHintBit
when ((inputHintSet && wmh_input hints) || (not inputHintSet)) $
io $ do setInputFocus dpy w revertToPointerRoot 0
when (wmtf `elem` protocols) $
io $ allocaXEvent $ \ev -> do
setEventType ev clientMessage
setClientMessageEvent ev w wmprot 32 wmtf $ maybe currentTime event_time currevt
sendEvent dpy w False noEventMask ev
where event_time ev =
if (ev_event_type ev) `elem` timedEvents then
ev_time ev
else
currentTime
timedEvents = [ keyPress, keyRelease, buttonPress, buttonRelease, enterNotify, leaveNotify, selectionRequest ]
------------------------------------------------------------------------
-- Message handling
-- | Throw a message to the current 'LayoutClass' possibly modifying how we
-- layout the windows, then refresh.
sendMessage :: Message a => a -> X ()
sendMessage a = do
w <- W.workspace . W.current <$> gets windowset
ml' <- handleMessage (W.layout w) (SomeMessage a) `catchX` return Nothing
whenJust ml' $ \l' ->
windows $ \ws -> ws { W.current = (W.current ws)
{ W.workspace = (W.workspace $ W.current ws)
{ W.layout = l' }}}
-- | Send a message to all layouts, without refreshing.
broadcastMessage :: Message a => a -> X ()
broadcastMessage a = withWindowSet $ \ws -> do
let c = W.workspace . W.current $ ws
v = map W.workspace . W.visible $ ws
h = W.hidden ws
mapM_ (sendMessageWithNoRefresh a) (c : v ++ h)
-- | Send a message to a layout, without refreshing.
sendMessageWithNoRefresh :: Message a => a -> W.Workspace WorkspaceId (Layout Window) Window -> X ()
sendMessageWithNoRefresh a w =
handleMessage (W.layout w) (SomeMessage a) `catchX` return Nothing >>=
updateLayout (W.tag w)
-- | Update the layout field of a workspace
updateLayout :: WorkspaceId -> Maybe (Layout Window) -> X ()
updateLayout i ml = whenJust ml $ \l ->
runOnWorkspaces $ \ww -> return $ if W.tag ww == i then ww { W.layout = l} else ww
-- | Set the layout of the currently viewed workspace
setLayout :: Layout Window -> X ()
setLayout l = do
ss@(W.StackSet { W.current = c@(W.Screen { W.workspace = ws })}) <- gets windowset
handleMessage (W.layout ws) (SomeMessage ReleaseResources)
windows $ const $ ss {W.current = c { W.workspace = ws { W.layout = l } } }
------------------------------------------------------------------------
-- Utilities
-- | Return workspace visible on screen 'sc', or 'Nothing'.
screenWorkspace :: ScreenId -> X (Maybe WorkspaceId)
screenWorkspace sc = withWindowSet $ return . W.lookupWorkspace sc
-- | Apply an 'X' operation to the currently focused window, if there is one.
withFocused :: (Window -> X ()) -> X ()
withFocused f = withWindowSet $ \w -> whenJust (W.peek w) f
-- | 'True' if window is under management by us
isClient :: Window -> X Bool
isClient w = withWindowSet $ return . W.member w
-- | Combinations of extra modifier masks we need to grab keys\/buttons for.
-- (numlock and capslock)
extraModifiers :: X [KeyMask]
extraModifiers = do
nlm <- gets numberlockMask
return [0, nlm, lockMask, nlm .|. lockMask ]
-- | Strip numlock\/capslock from a mask
cleanMask :: KeyMask -> X KeyMask
cleanMask km = do
nlm <- gets numberlockMask
return (complement (nlm .|. lockMask) .&. km)
-- | Get the 'Pixel' value for a named color
initColor :: Display -> String -> IO (Maybe Pixel)
initColor dpy c = C.handle (\(C.SomeException _) -> return Nothing) $
(Just . color_pixel . fst) <$> allocNamedColor dpy colormap c
where colormap = defaultColormap dpy (defaultScreen dpy)
------------------------------------------------------------------------
-- | @restart name resume@. Attempt to restart xmonad by executing the program
-- @name@. If @resume@ is 'True', restart with the current window state.
-- When executing another window manager, @resume@ should be 'False'.
restart :: String -> Bool -> X ()
restart prog resume = do
broadcastMessage ReleaseResources
io . flush =<< asks display
let wsData = show . W.mapLayout show . windowset
maybeShow (t, Right (PersistentExtension ext)) = Just (t, show ext)
maybeShow (t, Left str) = Just (t, str)
maybeShow _ = Nothing
extState = return . show . catMaybes . map maybeShow . M.toList . extensibleState
args <- if resume then gets (\s -> "--resume":wsData s:extState s) else return []
catchIO (executeFile prog True args Nothing)
------------------------------------------------------------------------
-- | Floating layer support
-- | Given a window, find the screen it is located on, and compute
-- the geometry of that window wrt. that screen.
floatLocation :: Window -> X (ScreenId, W.RationalRect)
floatLocation w = withDisplay $ \d -> do
ws <- gets windowset
wa <- io $ getWindowAttributes d w
bw <- fi <$> asks (borderWidth . config)
sc <- fromMaybe (W.current ws) <$> pointScreen (fi $ wa_x wa) (fi $ wa_y wa)
let sr = screenRect . W.screenDetail $ sc
rr = W.RationalRect ((fi (wa_x wa) - fi (rect_x sr)) % fi (rect_width sr))
((fi (wa_y wa) - fi (rect_y sr)) % fi (rect_height sr))
(fi (wa_width wa + bw*2) % fi (rect_width sr))
(fi (wa_height wa + bw*2) % fi (rect_height sr))
return (W.screen sc, rr)
where fi x = fromIntegral x
-- | Given a point, determine the screen (if any) that contains it.
pointScreen :: Position -> Position
-> X (Maybe (W.Screen WorkspaceId (Layout Window) Window ScreenId ScreenDetail))
pointScreen x y = withWindowSet $ return . find p . W.screens
where p = pointWithin x y . screenRect . W.screenDetail
-- | @pointWithin x y r@ returns 'True' if the @(x, y)@ co-ordinate is within
-- @r@.
pointWithin :: Position -> Position -> Rectangle -> Bool
pointWithin x y r = x >= rect_x r &&
x < rect_x r + fromIntegral (rect_width r) &&
y >= rect_y r &&
y < rect_y r + fromIntegral (rect_height r)
-- | Make a tiled window floating, using its suggested rectangle
float :: Window -> X ()
float w = do
(sc, rr) <- floatLocation w
windows $ \ws -> W.float w rr . fromMaybe ws $ do
i <- W.findTag w ws
guard $ i `elem` map (W.tag . W.workspace) (W.screens ws)
f <- W.peek ws
sw <- W.lookupWorkspace sc ws
return (W.focusWindow f . W.shiftWin sw w $ ws)
-- ---------------------------------------------------------------------
-- Mouse handling
-- | Accumulate mouse motion events
mouseDrag :: (Position -> Position -> X ()) -> X () -> X ()
mouseDrag f done = do
drag <- gets dragging
case drag of
Just _ -> return () -- error case? we're already dragging
Nothing -> do
XConf { theRoot = root, display = d } <- ask
io $ grabPointer d root False (buttonReleaseMask .|. pointerMotionMask)
grabModeAsync grabModeAsync none none currentTime
modify $ \s -> s { dragging = Just (motion, cleanup) }
where
cleanup = do
withDisplay $ io . flip ungrabPointer currentTime
modify $ \s -> s { dragging = Nothing }
done
motion x y = do z <- f x y
clearEvents pointerMotionMask
return z
-- | XXX comment me
mouseMoveWindow :: Window -> X ()
mouseMoveWindow w = whenX (isClient w) $ withDisplay $ \d -> do
io $ raiseWindow d w
wa <- io $ getWindowAttributes d w
(_, _, _, ox', oy', _, _, _) <- io $ queryPointer d w
let ox = fromIntegral ox'
oy = fromIntegral oy'
mouseDrag (\ex ey -> io $ moveWindow d w (fromIntegral (fromIntegral (wa_x wa) + (ex - ox)))
(fromIntegral (fromIntegral (wa_y wa) + (ey - oy))))
(float w)
-- | XXX comment me
mouseResizeWindow :: Window -> X ()
mouseResizeWindow w = whenX (isClient w) $ withDisplay $ \d -> do
io $ raiseWindow d w
wa <- io $ getWindowAttributes d w
sh <- io $ getWMNormalHints d w
io $ warpPointer d none w 0 0 0 0 (fromIntegral (wa_width wa)) (fromIntegral (wa_height wa))
mouseDrag (\ex ey ->
io $ resizeWindow d w `uncurry`
applySizeHintsContents sh (ex - fromIntegral (wa_x wa),
ey - fromIntegral (wa_y wa)))
(float w)
-- ---------------------------------------------------------------------
-- | Support for window size hints
type D = (Dimension, Dimension)
-- | Given a window, build an adjuster function that will reduce the given
-- dimensions according to the window's border width and size hints.
mkAdjust :: Window -> X (D -> D)
mkAdjust w = withDisplay $ \d -> liftIO $ do
sh <- getWMNormalHints d w
bw <- fmap (fromIntegral . wa_border_width) $ getWindowAttributes d w
return $ applySizeHints bw sh
-- | Reduce the dimensions if needed to comply to the given SizeHints, taking
-- window borders into account.
applySizeHints :: Integral a => Dimension -> SizeHints -> (a, a) -> D
applySizeHints bw sh =
tmap (+ 2 * bw) . applySizeHintsContents sh . tmap (subtract $ 2 * fromIntegral bw)
where
tmap f (x, y) = (f x, f y)
-- | Reduce the dimensions if needed to comply to the given SizeHints.
applySizeHintsContents :: Integral a => SizeHints -> (a, a) -> D
applySizeHintsContents sh (w, h) =
applySizeHints' sh (fromIntegral $ max 1 w, fromIntegral $ max 1 h)
-- | XXX comment me
applySizeHints' :: SizeHints -> D -> D
applySizeHints' sh =
maybe id applyMaxSizeHint (sh_max_size sh)
. maybe id (\(bw, bh) (w, h) -> (w+bw, h+bh)) (sh_base_size sh)
. maybe id applyResizeIncHint (sh_resize_inc sh)
. maybe id applyAspectHint (sh_aspect sh)
. maybe id (\(bw,bh) (w,h) -> (w-bw, h-bh)) (sh_base_size sh)
-- | Reduce the dimensions so their aspect ratio falls between the two given aspect ratios.
applyAspectHint :: (D, D) -> D -> D
applyAspectHint ((minx, miny), (maxx, maxy)) x@(w,h)
| or [minx < 1, miny < 1, maxx < 1, maxy < 1] = x
| w * maxy > h * maxx = (h * maxx `div` maxy, h)
| w * miny < h * minx = (w, w * miny `div` minx)
| otherwise = x
-- | Reduce the dimensions so they are a multiple of the size increments.
applyResizeIncHint :: D -> D -> D
applyResizeIncHint (iw,ih) x@(w,h) =
if iw > 0 && ih > 0 then (w - w `mod` iw, h - h `mod` ih) else x
-- | Reduce the dimensions if they exceed the given maximum dimensions.
applyMaxSizeHint :: D -> D -> D
applyMaxSizeHint (mw,mh) x@(w,h) =
if mw > 0 && mh > 0 then (min w mw,min h mh) else x
|
markus1189/xmonad-710
|
XMonad/Operations.hs
|
bsd-3-clause
| 24,275
| 0
| 23
| 6,293
| 7,196
| 3,663
| 3,533
| 363
| 4
|
{-# LANGUAGE DeriveGeneric #-}
module Saturnin.Server.Config
( ConfigServer (..)
, readConfig
, MachineDescription
, Hostname
, YBServerPersistentState (..)
, readPState
, writePState
, JobID (..)
, bumpJobID
)
where
import Data.Default
import Data.HashMap.Strict
import Data.Yaml
import GHC.Generics
import System.Directory
import System.FilePath.Posix
type MachineDescription = String
type Hostname = String
data ConfigServer = ConfigServer
{ listen_addr :: Maybe String
, listen_port :: Maybe String
, machines :: HashMap MachineDescription Hostname
, work_dir :: Maybe FilePath
} deriving (Show, Generic)
instance FromJSON ConfigServer
instance Default ConfigServer where
def = ConfigServer
{ listen_addr = Nothing
, listen_port = Nothing
, machines = empty
, work_dir = Nothing
}
readConfig :: IO (Either ParseException ConfigServer)
readConfig = do
tmp <- getTemporaryDirectory
cg <- decodeFileEither "/etc/ybs.yml"
return $ fmap (defWorkDir tmp) cg
where
defWorkDir t (cg @ ConfigServer { work_dir = Nothing }) =
cg { work_dir = Just $ t </> "ybs" }
defWorkDir _ cg = cg
data JobID = JobID Int
deriving (Show, Read, Generic)
instance Enum JobID where
toEnum x = JobID x
fromEnum (JobID x) = x
instance FromJSON JobID
instance ToJSON JobID
data YBServerPersistentState = YBServerPersistentState
{ lastJobID :: JobID }
deriving (Show, Read, Generic)
instance FromJSON YBServerPersistentState
instance ToJSON YBServerPersistentState
instance Default YBServerPersistentState where
def = YBServerPersistentState $ JobID 0
bumpJobID :: YBServerPersistentState -> YBServerPersistentState
bumpJobID x = x { lastJobID = succ $ lastJobID x }
readPState :: IO (Either ParseException YBServerPersistentState)
readPState = do
x <- doesFileExist pstatePath
if x
then decodeFileEither pstatePath
else return $ Right def
writePState :: YBServerPersistentState -> IO ()
writePState = encodeFile pstatePath
pstatePath :: FilePath
pstatePath = "/var/lib/ybs/state"
|
yaccz/saturnin
|
library/Saturnin/Server/Config.hs
|
bsd-3-clause
| 2,191
| 1
| 13
| 506
| 560
| 303
| 257
| 66
| 2
|
module Write.Quirks where
import Data.HashMap.Strict as M
import Write.Utils
-- | Entities which must be put in hs-boot files to break dependency cycles
--
-- Only handles are allowed in here, this isn't checked
cycleBreakers :: HashMap ModuleName [String]
cycleBreakers = M.fromList [ (ModuleName "Graphics.Vulkan.Device", ["VkDevice"])
, (ModuleName "Graphics.Vulkan.Pass", ["VkRenderPass"])
]
sourceImports = M.fromList [ ( ModuleName "Graphics.Vulkan.Memory"
, [ModuleName "Graphics.Vulkan.Device"]
)
, ( ModuleName "Graphics.Vulkan.Pipeline"
, [ModuleName "Graphics.Vulkan.Pass"]
)
]
|
oldmanmike/vulkan
|
generate/src/Write/Quirks.hs
|
bsd-3-clause
| 818
| 0
| 9
| 300
| 121
| 71
| 50
| 10
| 1
|
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module Main where
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Lazy.Char8 as BL
import System.Environment (getArgs)
import Case
main :: IO ()
main = do
args <- getArgs
xs <- getContents
if length args /= 0 then -- "-w"
printWire xs
else
printJSON xs
printWire :: String -> IO ()
printWire = print . sourceToWire . read
printJSON :: String -> IO ()
printJSON = BL.putStrLn . encodePretty . toJSON . wireToCase . read
|
bergmark/http2
|
test-frame/frame-encode.hs
|
bsd-3-clause
| 561
| 0
| 9
| 119
| 163
| 90
| 73
| 18
| 2
|
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE TypeFamilies #-}
-- | Use @ByteArray@s containing one element for mutable references.
--
-- This is similar to @URef@s, but avoids the overhead of storing the length of
-- the @Vector@, which we statically know will always be 1. This allows it to
-- be a bit faster.
--
-- Motivated by: <http://stackoverflow.com/questions/27261813/why-is-my-little-stref-int-require-allocating-gigabytes> and ArrayRef.
module Data.Mutable.PRef
( -- * Types
PRef
, IOPRef
-- * Functions
, asPRef
, MutableRef (..)
) where
import Control.Monad (liftM)
import Data.Mutable.Class
import Data.Primitive (sizeOf)
import Data.Primitive.ByteArray (MutableByteArray, newByteArray, readByteArray,
writeByteArray)
import Data.Primitive.Types (Prim)
import GHC.Types (Int (..))
-- | A primitive ByteArray reference, supporting any monad.
--
-- Since 0.2.0
newtype PRef s a = PRef (MutableByteArray s)
-- |
-- Since 0.2.0
asPRef :: PRef s a -> PRef s a
asPRef x = x
{-# INLINE asPRef #-}
-- | A primitive ByteArray IO reference.
type IOPRef = PRef (PrimState IO)
instance MutableContainer (PRef s a) where
type MCState (PRef s a) = s
instance Prim a => MutableRef (PRef s a) where
type RefElement (PRef s a) = a
newRef x = do
ba <- newByteArray (sizeOf $! x)
writeByteArray ba 0 x
return $! PRef ba
{-# INLINE newRef #-}
readRef (PRef ba) = readByteArray ba 0
{-# INLINE readRef #-}
writeRef (PRef ba) = writeByteArray ba 0
{-# INLINE writeRef #-}
modifyRef (PRef ba) f = do
x <- readByteArray ba 0
writeByteArray ba 0 $! f x
{-# INLINE modifyRef #-}
modifyRef' = modifyRef
{-# INLINE modifyRef' #-}
|
bitemyapp/mutable-containers
|
Data/Mutable/PRef.hs
|
mit
| 1,817
| 0
| 11
| 464
| 381
| 213
| 168
| 39
| 1
|
module Text.XkbCommon.Types
( Direction, keyUp, keyDown,
CLogLevel, CKeycode(..), CLayoutIndex(..), CModIndex(..), CLevelIndex(..),
CLedIndex(..), Keysym(..), StateComponent, CModMask(..),
stateModDepressed, stateModLatched, stateModLocked, stateModEffective,
stateLayoutDepressed, stateLayoutLatched, stateLayoutLocked,
stateLayoutEffective, stateLeds,
) where
import Text.XkbCommon.InternalTypes
|
tulcod/haskell-xkbcommon
|
Text/XkbCommon/Types.hs
|
mit
| 432
| 0
| 5
| 62
| 107
| 74
| 33
| 8
| 0
|
{-|
Pier Configuration
-}
module Urbit.King.Config where
import Urbit.Prelude
{-|
All the configuration data revolving around a ship and the current
execution options.
-}
data PierConfig = PierConfig
{ _pcPierPath :: FilePath
, _pcDryRun :: Bool
} deriving (Show)
makeLenses ''PierConfig
class HasPierConfig env where
pierConfigL :: Lens' env PierConfig
pierPathL ∷ HasPierConfig a => Lens' a FilePath
pierPathL = pierConfigL . pcPierPath
dryRunL :: HasPierConfig a => Lens' a Bool
dryRunL = pierConfigL . pcDryRun
-------------------------------------------------------------------------------
data NetMode
= NMNone
| NMLocalhost
| NMNormal
deriving (Eq, Ord, Show)
data NetworkConfig = NetworkConfig
{ _ncNetMode :: NetMode
, _ncAmesPort :: Maybe Word16
, _ncHttpPort :: Maybe Word16
, _ncHttpsPort :: Maybe Word16
, _ncLocalPort :: Maybe Word16
} deriving (Show)
makeLenses ''NetworkConfig
class HasNetworkConfig env where
networkConfigL :: Lens' env NetworkConfig
|
jfranklin9000/urbit
|
pkg/hs/urbit-king/lib/Urbit/King/Config.hs
|
mit
| 1,043
| 0
| 9
| 204
| 235
| 127
| 108
| -1
| -1
|
{-# LANGUAGE DeriveDataTypeable #-}
module InnerEar.Exercises.ThresholdOfSilence (thresholdOfSilenceExercise) where
import Reflex
import Reflex.Dom
import Data.Map
import Text.JSON
import Text.JSON.Generic
import Sound.MusicW
import InnerEar.Exercises.MultipleChoice
import InnerEar.Types.ExerciseId
import InnerEar.Types.Exercise
import InnerEar.Types.Score
import InnerEar.Types.MultipleChoiceStore
import InnerEar.Types.Data hiding (Time)
import InnerEar.Types.Sound
import InnerEar.Widgets.Config
import InnerEar.Widgets.SpecEval
import InnerEar.Widgets.AnswerButton
import InnerEar.Widgets.Utility
type Config = Int -- gain value for attenuated sounds
configs :: [Config]
configs = [-20,-30,-40,-50,-60,-70,-80,-90,-100,-110]
configMap::Map Int (String, Config)
configMap = fromList $ zip [(0::Int),1..]$ fmap (\x-> (show x ++ " dB",x)) configs
data Answer = Answer Bool deriving (Eq,Ord,Data,Typeable)
answers :: [Answer]
answers = [Answer True,Answer False]
instance Show Answer where
show (Answer True) = "Attenuated Sound"
show (Answer False) = "No sound at all"
instance Buttonable Answer where
makeButton = showAnswerButton
renderAnswer :: Map String AudioBuffer -> Config -> (SourceNodeSpec, Maybe Time) -> Maybe Answer -> Synth ()
renderAnswer _ db (src, dur) (Just (Answer True)) = buildSynth $ do
let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur
synthSource src >> gain (Db $ fromIntegral db) >> env >> destination
maybeDelete (fmap (+ Sec 0.2) dur)
renderAnswer _ db _ (Just (Answer False)) = buildSynth_ $ silent >> destination
renderAnswer _ db (src, dur) Nothing = buildSynth $ do
let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur
synthSource src >> gain (Db $ fromIntegral db) >> env >> destination
maybeDelete (fmap (+ Sec 0.2) dur)
instructionsText = "In this exercise, the system either makes no sound at all \
\or it plays a sound that has been reduced in level by some specific amount \
\of attenuation. As you make the level lower and lower, it should become more \
\difficult to tell when the system is playing a sound versus when it is playing \
\nothing."
data MyTabs = Instructions | Other deriving (Eq,Show)
instructions :: MonadWidget t m => m ()
-- instructions = elClass "div" "instructionsText" $ text instructionsText
instructions = elClass "div" "instructionsText" $ do
tab <- simpleTabBar [Instructions,Other] Instructions
tabAVisible <- mapDyn (== Instructions) tab
visibleWhen tabAVisible $ text "This would be the text of the instructions."
tabBVisible <- mapDyn (== Other) tab
visibleWhen tabBVisible $ text "Now we are displaying some other text instead!"
displayEval :: MonadWidget t m => Dynamic t (Map Answer Score) -> Dynamic t (MultipleChoiceStore Config Answer) -> m ()
displayEval e _ = displayMultipleChoiceEvaluationGraph ("scoreBarWrapper","svgBarContainer","svgFaintedLine", "xLabel") "Session Performance" "" answers e
generateQ :: Config -> [ExerciseDatum] -> IO ([Answer],Answer)
generateQ _ _ = randomMultipleChoiceQuestion answers
sourcesMap :: Map Int (String, SoundSourceConfigOption)
sourcesMap = fromList $ [
(0, ("Pink noise", Resource "pinknoise.wav" (Just $ Sec 2))),
(1, ("White noise", Resource "whitenoise.wav" (Just $ Sec 2))),
(2, ("Load a sound file", UserProvidedResource))
]
thresholdOfSilenceExercise :: MonadWidget t m => Exercise t m Int [Answer] Answer (Map Answer Score) (MultipleChoiceStore Config Answer)
thresholdOfSilenceExercise = multipleChoiceExercise
1
answers
instructions
(configWidget "thresholdOfSilenceExercise" sourcesMap 0 "Attenuation: " configMap) -- (dynRadioConfigWidget "fiveBandBoostCutExercise" sourcesMap 0 configMap)
renderAnswer
ThresholdOfSilence
(-20)
displayEval
generateQ
(const (0,2))
|
luisnavarrodelangel/InnerEar
|
src/InnerEar/Exercises/ThresholdOfSilence.hs
|
gpl-3.0
| 3,826
| 0
| 15
| 588
| 1,134
| 606
| 528
| 72
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.MachineLearning.DeleteEvaluation
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Assigns the 'DELETED' status to an 'Evaluation', rendering it unusable.
--
-- After invoking the 'DeleteEvaluation' operation, you can use the 'GetEvaluation'
-- operation to verify that the status of the 'Evaluation' changed to 'DELETED'.
--
-- Caution The results of the 'DeleteEvaluation' operation are irreversible.
--
--
-- <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_DeleteEvaluation.html>
module Network.AWS.MachineLearning.DeleteEvaluation
(
-- * Request
DeleteEvaluation
-- ** Request constructor
, deleteEvaluation
-- ** Request lenses
, deEvaluationId
-- * Response
, DeleteEvaluationResponse
-- ** Response constructor
, deleteEvaluationResponse
-- ** Response lenses
, derEvaluationId
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.MachineLearning.Types
import qualified GHC.Exts
newtype DeleteEvaluation = DeleteEvaluation
{ _deEvaluationId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteEvaluation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'deEvaluationId' @::@ 'Text'
--
deleteEvaluation :: Text -- ^ 'deEvaluationId'
-> DeleteEvaluation
deleteEvaluation p1 = DeleteEvaluation
{ _deEvaluationId = p1
}
-- | A user-supplied ID that uniquely identifies the 'Evaluation' to delete.
deEvaluationId :: Lens' DeleteEvaluation Text
deEvaluationId = lens _deEvaluationId (\s a -> s { _deEvaluationId = a })
newtype DeleteEvaluationResponse = DeleteEvaluationResponse
{ _derEvaluationId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'DeleteEvaluationResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'derEvaluationId' @::@ 'Maybe' 'Text'
--
deleteEvaluationResponse :: DeleteEvaluationResponse
deleteEvaluationResponse = DeleteEvaluationResponse
{ _derEvaluationId = Nothing
}
-- | A user-supplied ID that uniquely identifies the 'Evaluation'. This value should
-- be identical to the value of the 'EvaluationId' in the request.
derEvaluationId :: Lens' DeleteEvaluationResponse (Maybe Text)
derEvaluationId = lens _derEvaluationId (\s a -> s { _derEvaluationId = a })
instance ToPath DeleteEvaluation where
toPath = const "/"
instance ToQuery DeleteEvaluation where
toQuery = const mempty
instance ToHeaders DeleteEvaluation
instance ToJSON DeleteEvaluation where
toJSON DeleteEvaluation{..} = object
[ "EvaluationId" .= _deEvaluationId
]
instance AWSRequest DeleteEvaluation where
type Sv DeleteEvaluation = MachineLearning
type Rs DeleteEvaluation = DeleteEvaluationResponse
request = post "DeleteEvaluation"
response = jsonResponse
instance FromJSON DeleteEvaluationResponse where
parseJSON = withObject "DeleteEvaluationResponse" $ \o -> DeleteEvaluationResponse
<$> o .:? "EvaluationId"
|
kim/amazonka
|
amazonka-ml/gen/Network/AWS/MachineLearning/DeleteEvaluation.hs
|
mpl-2.0
| 4,056
| 0
| 9
| 811
| 464
| 284
| 180
| 56
| 1
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}
-- |
-- Module : Statistics.Distribution.Exponential
-- Copyright : (c) 2009 Bryan O'Sullivan
-- License : BSD3
--
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : portable
--
-- The exponential distribution. This is the continuous probability
-- distribution of the times between events in a poisson process, in
-- which events occur continuously and independently at a constant
-- average rate.
module Statistics.Distribution.Exponential
(
ExponentialDistribution
-- * Constructors
, exponential
, exponentialE
-- * Accessors
, edLambda
) where
import Control.Applicative
import Data.Aeson (FromJSON(..),ToJSON,Value(..),(.:))
import Data.Binary (Binary, put, get)
import Data.Data (Data, Typeable)
import GHC.Generics (Generic)
import Numeric.SpecFunctions (log1p,expm1)
import Numeric.MathFunctions.Constants (m_neg_inf)
import qualified System.Random.MWC.Distributions as MWC
import qualified Data.Vector.Generic as G
import qualified Statistics.Distribution as D
import qualified Statistics.Sample as S
import Statistics.Internal
newtype ExponentialDistribution = ED {
edLambda :: Double
} deriving (Eq, Typeable, Data, Generic)
instance Show ExponentialDistribution where
showsPrec n (ED l) = defaultShow1 "exponential" l n
instance Read ExponentialDistribution where
readPrec = defaultReadPrecM1 "exponential" exponentialE
instance ToJSON ExponentialDistribution
instance FromJSON ExponentialDistribution where
parseJSON (Object v) = do
l <- v .: "edLambda"
maybe (fail $ errMsg l) return $ exponentialE l
parseJSON _ = empty
instance Binary ExponentialDistribution where
put = put . edLambda
get = do
l <- get
maybe (fail $ errMsg l) return $ exponentialE l
instance D.Distribution ExponentialDistribution where
cumulative = cumulative
complCumulative = complCumulative
instance D.ContDistr ExponentialDistribution where
density (ED l) x
| x < 0 = 0
| otherwise = l * exp (-l * x)
logDensity (ED l) x
| x < 0 = m_neg_inf
| otherwise = log l + (-l * x)
quantile = quantile
complQuantile = complQuantile
instance D.Mean ExponentialDistribution where
mean (ED l) = 1 / l
instance D.Variance ExponentialDistribution where
variance (ED l) = 1 / (l * l)
instance D.MaybeMean ExponentialDistribution where
maybeMean = Just . D.mean
instance D.MaybeVariance ExponentialDistribution where
maybeStdDev = Just . D.stdDev
maybeVariance = Just . D.variance
instance D.Entropy ExponentialDistribution where
entropy (ED l) = 1 - log l
instance D.MaybeEntropy ExponentialDistribution where
maybeEntropy = Just . D.entropy
instance D.ContGen ExponentialDistribution where
genContVar = MWC.exponential . edLambda
cumulative :: ExponentialDistribution -> Double -> Double
cumulative (ED l) x | x <= 0 = 0
| otherwise = - expm1 (-l * x)
complCumulative :: ExponentialDistribution -> Double -> Double
complCumulative (ED l) x | x <= 0 = 1
| otherwise = exp (-l * x)
quantile :: ExponentialDistribution -> Double -> Double
quantile (ED l) p
| p >= 0 && p <= 1 = - log1p(-p) / l
| otherwise =
error $ "Statistics.Distribution.Exponential.quantile: p must be in [0,1] range. Got: "++show p
complQuantile :: ExponentialDistribution -> Double -> Double
complQuantile (ED l) p
| p == 0 = 0
| p >= 0 && p < 1 = -log p / l
| otherwise =
error $ "Statistics.Distribution.Exponential.quantile: p must be in [0,1] range. Got: "++show p
-- | Create an exponential distribution.
exponential :: Double -- ^ Rate parameter.
-> ExponentialDistribution
exponential l = maybe (error $ errMsg l) id $ exponentialE l
-- | Create an exponential distribution.
exponentialE :: Double -- ^ Rate parameter.
-> Maybe ExponentialDistribution
exponentialE l
| l > 0 = Just (ED l)
| otherwise = Nothing
errMsg :: Double -> String
errMsg l = "Statistics.Distribution.Exponential.exponential: scale parameter must be positive. Got " ++ show l
-- | Create exponential distribution from sample. Returns @Nothing@ if
-- sample is empty or contains negative elements. No other tests are
-- made to check whether it truly is exponential.
instance D.FromSample ExponentialDistribution Double where
fromSample xs
| G.null xs = Nothing
| G.all (>= 0) xs = Nothing
| otherwise = Just $! ED (S.mean xs)
|
bos/statistics
|
Statistics/Distribution/Exponential.hs
|
bsd-2-clause
| 4,798
| 3
| 12
| 1,125
| 1,200
| 629
| 571
| 98
| 1
|
module Reddit.Types.Listing where
import Reddit.Parser
import Control.Applicative
import Data.Aeson
import Data.Traversable
import Data.Monoid
import Network.API.Builder.Query
import Prelude
data ListingType = Hot
| New
| Rising
| Controversial
| Top
deriving (Show, Read, Eq)
instance ToQuery ListingType where
toQuery k t = return $ (,) k $ case t of
Hot -> "hot"
New -> "new"
Rising -> "rising"
Controversial -> "controversial"
Top -> "top"
data Listing t a = Listing { before :: Maybe t
, after :: Maybe t
, contents :: [a] }
deriving (Show, Read, Eq)
instance Functor (Listing t) where
fmap f (Listing b a x) = Listing b a (fmap f x)
instance Ord t => Monoid (Listing t a) where
mappend (Listing a b cs) (Listing d e fs) =
Listing (max a d) (min b e) (cs <> fs)
mempty = Listing Nothing Nothing []
instance (FromJSON t, FromJSON a) => FromJSON (Listing t a) where
parseJSON (Object o) = do
o `ensureKind` "Listing"
d <- o .: "data"
Listing <$> (d .:? "before" >>= traverse parseJSON)
<*> (d .:? "after" >>= traverse parseJSON)
<*> (o .: "data" >>= (.: "children"))
parseJSON (String "") = return $ Listing Nothing Nothing []
parseJSON Null = return $ Listing Nothing Nothing []
parseJSON _ = mempty
|
FranklinChen/reddit
|
src/Reddit/Types/Listing.hs
|
bsd-2-clause
| 1,414
| 0
| 13
| 421
| 520
| 273
| 247
| 41
| 0
|
{-# LANGUAGE CPP #-}
-- |
-- Copyright : (c) 2011 Simon Meier
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-- Hexadecimal encoding of nibbles (4-bit) and octets (8-bit) as ASCII
-- characters.
--
-- The current implementation is based on a table based encoding inspired by
-- the code in the 'base64-bytestring' library by Bryan O'Sullivan. In our
-- benchmarks on a 32-bit machine it turned out to be the fastest
-- implementation option.
--
module Data.ByteString.Lazy.Builder.BasicEncoding.Internal.Base16 (
EncodingTable
-- , upperTable
, lowerTable
, encode4_as_8
, encode8_as_16h
-- , encode8_as_8_8
) where
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S
#if MIN_VERSION_base(4,4,0)
import Foreign hiding (unsafePerformIO, unsafeForeignPtrToPtr)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import System.IO.Unsafe (unsafePerformIO)
#else
import Foreign
#endif
-- Creating the encoding tables
-------------------------------
-- TODO: Use table from C implementation.
-- | An encoding table for Base16 encoding.
newtype EncodingTable = EncodingTable (ForeignPtr Word8)
tableFromList :: [Word8] -> EncodingTable
tableFromList xs = case S.pack xs of S.PS fp _ _ -> EncodingTable fp
unsafeIndex :: EncodingTable -> Int -> IO Word8
unsafeIndex (EncodingTable table) = peekElemOff (unsafeForeignPtrToPtr table)
base16EncodingTable :: EncodingTable -> IO EncodingTable
base16EncodingTable alphabet = do
xs <- sequence $ concat $ [ [ix j, ix k] | j <- [0..15], k <- [0..15] ]
return $ tableFromList xs
where
ix = unsafeIndex alphabet
{-
{-# NOINLINE upperAlphabet #-}
upperAlphabet :: EncodingTable
upperAlphabet =
tableFromList $ map (fromIntegral . fromEnum) $ ['0'..'9'] ++ ['A'..'F']
-- | The encoding table for hexadecimal values with upper-case characters;
-- e.g., DEADBEEF.
{-# NOINLINE upperTable #-}
upperTable :: EncodingTable
upperTable = unsafePerformIO $ base16EncodingTable upperAlphabet
-}
{-# NOINLINE lowerAlphabet #-}
lowerAlphabet :: EncodingTable
lowerAlphabet =
tableFromList $ map (fromIntegral . fromEnum) $ ['0'..'9'] ++ ['a'..'f']
-- | The encoding table for hexadecimal values with lower-case characters;
-- e.g., deadbeef.
{-# NOINLINE lowerTable #-}
lowerTable :: EncodingTable
lowerTable = unsafePerformIO $ base16EncodingTable lowerAlphabet
-- Encoding nibbles and octets
------------------------------
-- | Encode a nibble as an octet.
--
-- > encode4_as_8 lowerTable 10 = fromIntegral (char 'a')
--
{-# INLINE encode4_as_8 #-}
encode4_as_8 :: EncodingTable -> Word8 -> IO Word8
encode4_as_8 table x = unsafeIndex table (2 * fromIntegral x + 1)
-- TODO: Use a denser table to reduce cache utilization.
-- | Encode an octet as 16bit word comprising both encoded nibbles ordered
-- according to the host endianness. Writing these 16bit to memory will write
-- the nibbles in the correct order (i.e. big-endian).
{-# INLINE encode8_as_16h #-}
encode8_as_16h :: EncodingTable -> Word8 -> IO Word16
encode8_as_16h (EncodingTable table) =
peekElemOff (castPtr $ unsafeForeignPtrToPtr table) . fromIntegral
{-
-- | Encode an octet as a big-endian ordered tuple of octets; i.e.,
--
-- > encode8_as_8_8 lowerTable 10
-- > = (fromIntegral (chr '0'), fromIntegral (chr 'a'))
--
{-# INLINE encode8_as_8_8 #-}
encode8_as_8_8 :: EncodingTable -> Word8 -> IO (Word8, Word8)
encode8_as_8_8 table x =
(,) <$> unsafeIndex table i <*> unsafeIndex table (i + 1)
where
i = 2 * fromIntegral x
-}
|
meiersi/bytestring-builder
|
Data/ByteString/Lazy/Builder/BasicEncoding/Internal/Base16.hs
|
bsd-3-clause
| 3,680
| 0
| 12
| 641
| 467
| 272
| 195
| 33
| 1
|
{-# LANGUAGE CPP, MagicHash #-}
-- | Dynamically lookup up values from modules and loading them.
module DynamicLoading (
#if defined(GHCI)
-- * Loading plugins
loadPlugins,
loadFrontendPlugin,
-- * Force loading information
forceLoadModuleInterfaces,
forceLoadNameModuleInterface,
forceLoadTyCon,
-- * Finding names
lookupRdrNameInModuleForPlugins,
-- * Loading values
getValueSafely,
getHValueSafely,
lessUnsafeCoerce
#else
pluginError,
#endif
) where
import GhcPrelude
#if defined(GHCI)
import Linker ( linkModule, getHValue )
import GHCi ( wormhole )
import SrcLoc ( noSrcSpan )
import Finder ( findPluginModule, cannotFindModule )
import TcRnMonad ( initTcInteractive, initIfaceTcRn )
import LoadIface ( loadPluginInterface )
import RdrName ( RdrName, ImportSpec(..), ImpDeclSpec(..)
, ImpItemSpec(..), mkGlobalRdrEnv, lookupGRE_RdrName
, gre_name, mkRdrQual )
import OccName ( OccName, mkVarOcc )
import RnNames ( gresFromAvails )
import DynFlags
import Plugins ( Plugin, FrontendPlugin, CommandLineOption )
import PrelNames ( pluginTyConName, frontendPluginTyConName )
import HscTypes
import GHCi.RemoteTypes ( HValue )
import Type ( Type, eqType, mkTyConTy, pprTyThingCategory )
import TyCon ( TyCon )
import Name ( Name, nameModule_maybe )
import Id ( idType )
import Module ( Module, ModuleName )
import Panic
import FastString
import ErrUtils
import Outputable
import Exception
import Hooks
import Data.Maybe ( mapMaybe )
import GHC.Exts ( unsafeCoerce# )
#else
import Module ( ModuleName, moduleNameString )
import Panic
import Data.List ( intercalate )
#endif
#if defined(GHCI)
loadPlugins :: HscEnv -> IO [(ModuleName, Plugin, [CommandLineOption])]
loadPlugins hsc_env
= do { plugins <- mapM (loadPlugin hsc_env) to_load
; return $ zipWith attachOptions to_load plugins }
where
dflags = hsc_dflags hsc_env
to_load = pluginModNames dflags
attachOptions mod_nm plug = (mod_nm, plug, options)
where
options = [ option | (opt_mod_nm, option) <- pluginModNameOpts dflags
, opt_mod_nm == mod_nm ]
loadPlugin :: HscEnv -> ModuleName -> IO Plugin
loadPlugin = loadPlugin' (mkVarOcc "plugin") pluginTyConName
loadFrontendPlugin :: HscEnv -> ModuleName -> IO FrontendPlugin
loadFrontendPlugin = loadPlugin' (mkVarOcc "frontendPlugin") frontendPluginTyConName
loadPlugin' :: OccName -> Name -> HscEnv -> ModuleName -> IO a
loadPlugin' occ_name plugin_name hsc_env mod_name
= do { let plugin_rdr_name = mkRdrQual mod_name occ_name
dflags = hsc_dflags hsc_env
; mb_name <- lookupRdrNameInModuleForPlugins hsc_env mod_name
plugin_rdr_name
; case mb_name of {
Nothing ->
throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep
[ text "The module", ppr mod_name
, text "did not export the plugin name"
, ppr plugin_rdr_name ]) ;
Just name ->
do { plugin_tycon <- forceLoadTyCon hsc_env plugin_name
; mb_plugin <- getValueSafely hsc_env name (mkTyConTy plugin_tycon)
; case mb_plugin of
Nothing ->
throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep
[ text "The value", ppr name
, text "did not have the type"
, ppr pluginTyConName, text "as required"])
Just plugin -> return plugin } } }
-- | Force the interfaces for the given modules to be loaded. The 'SDoc' parameter is used
-- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
forceLoadModuleInterfaces :: HscEnv -> SDoc -> [Module] -> IO ()
forceLoadModuleInterfaces hsc_env doc modules
= (initTcInteractive hsc_env $
initIfaceTcRn $
mapM_ (loadPluginInterface doc) modules)
>> return ()
-- | Force the interface for the module containing the name to be loaded. The 'SDoc' parameter is used
-- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
forceLoadNameModuleInterface :: HscEnv -> SDoc -> Name -> IO ()
forceLoadNameModuleInterface hsc_env reason name = do
let name_modules = mapMaybe nameModule_maybe [name]
forceLoadModuleInterfaces hsc_env reason name_modules
-- | Load the 'TyCon' associated with the given name, come hell or high water. Fails if:
--
-- * The interface could not be loaded
-- * The name is not that of a 'TyCon'
-- * The name did not exist in the loaded module
forceLoadTyCon :: HscEnv -> Name -> IO TyCon
forceLoadTyCon hsc_env con_name = do
forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of loadTyConTy") con_name
mb_con_thing <- lookupTypeHscEnv hsc_env con_name
case mb_con_thing of
Nothing -> throwCmdLineErrorS dflags $ missingTyThingError con_name
Just (ATyCon tycon) -> return tycon
Just con_thing -> throwCmdLineErrorS dflags $ wrongTyThingError con_name con_thing
where dflags = hsc_dflags hsc_env
-- | Loads the value corresponding to a 'Name' if that value has the given 'Type'. This only provides limited safety
-- in that it is up to the user to ensure that that type corresponds to the type you try to use the return value at!
--
-- If the value found was not of the correct type, returns @Nothing@. Any other condition results in an exception:
--
-- * If we could not load the names module
-- * If the thing being loaded is not a value
-- * If the Name does not exist in the module
-- * If the link failed
getValueSafely :: HscEnv -> Name -> Type -> IO (Maybe a)
getValueSafely hsc_env val_name expected_type = do
mb_hval <- lookupHook getValueSafelyHook getHValueSafely dflags hsc_env val_name expected_type
case mb_hval of
Nothing -> return Nothing
Just hval -> do
value <- lessUnsafeCoerce dflags "getValueSafely" hval
return (Just value)
where
dflags = hsc_dflags hsc_env
getHValueSafely :: HscEnv -> Name -> Type -> IO (Maybe HValue)
getHValueSafely hsc_env val_name expected_type = do
forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of getHValueSafely") val_name
-- Now look up the names for the value and type constructor in the type environment
mb_val_thing <- lookupTypeHscEnv hsc_env val_name
case mb_val_thing of
Nothing -> throwCmdLineErrorS dflags $ missingTyThingError val_name
Just (AnId id) -> do
-- Check the value type in the interface against the type recovered from the type constructor
-- before finally casting the value to the type we assume corresponds to that constructor
if expected_type `eqType` idType id
then do
-- Link in the module that contains the value, if it has such a module
case nameModule_maybe val_name of
Just mod -> do linkModule hsc_env mod
return ()
Nothing -> return ()
-- Find the value that we just linked in and cast it given that we have proved it's type
hval <- getHValue hsc_env val_name >>= wormhole dflags
return (Just hval)
else return Nothing
Just val_thing -> throwCmdLineErrorS dflags $ wrongTyThingError val_name val_thing
where dflags = hsc_dflags hsc_env
-- | Coerce a value as usual, but:
--
-- 1) Evaluate it immediately to get a segfault early if the coercion was wrong
--
-- 2) Wrap it in some debug messages at verbosity 3 or higher so we can see what happened
-- if it /does/ segfault
lessUnsafeCoerce :: DynFlags -> String -> a -> IO b
lessUnsafeCoerce dflags context what = do
debugTraceMsg dflags 3 $ (text "Coercing a value in") <+> (text context) <>
(text "...")
output <- evaluate (unsafeCoerce# what)
debugTraceMsg dflags 3 (text "Successfully evaluated coercion")
return output
-- | Finds the 'Name' corresponding to the given 'RdrName' in the
-- context of the 'ModuleName'. Returns @Nothing@ if no such 'Name'
-- could be found. Any other condition results in an exception:
--
-- * If the module could not be found
-- * If we could not determine the imports of the module
--
-- Can only be used for looking up names while loading plugins (and is
-- *not* suitable for use within plugins). The interface file is
-- loaded very partially: just enough that it can be used, without its
-- rules and instances affecting (and being linked from!) the module
-- being compiled. This was introduced by 57d6798.
lookupRdrNameInModuleForPlugins :: HscEnv -> ModuleName -> RdrName -> IO (Maybe Name)
lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do
-- First find the package the module resides in by searching exposed packages and home modules
found_module <- findPluginModule hsc_env mod_name
case found_module of
Found _ mod -> do
-- Find the exports of the module
(_, mb_iface) <- initTcInteractive hsc_env $
initIfaceTcRn $
loadPluginInterface doc mod
case mb_iface of
Just iface -> do
-- Try and find the required name in the exports
let decl_spec = ImpDeclSpec { is_mod = mod_name, is_as = mod_name
, is_qual = False, is_dloc = noSrcSpan }
imp_spec = ImpSpec decl_spec ImpAll
env = mkGlobalRdrEnv (gresFromAvails (Just imp_spec) (mi_exports iface))
case lookupGRE_RdrName rdr_name env of
[gre] -> return (Just (gre_name gre))
[] -> return Nothing
_ -> panic "lookupRdrNameInModule"
Nothing -> throwCmdLineErrorS dflags $ hsep [text "Could not determine the exports of the module", ppr mod_name]
err -> throwCmdLineErrorS dflags $ cannotFindModule dflags mod_name err
where
dflags = hsc_dflags hsc_env
doc = text "contains a name used in an invocation of lookupRdrNameInModule"
wrongTyThingError :: Name -> TyThing -> SDoc
wrongTyThingError name got_thing = hsep [text "The name", ppr name, ptext (sLit "is not that of a value but rather a"), pprTyThingCategory got_thing]
missingTyThingError :: Name -> SDoc
missingTyThingError name = hsep [text "The name", ppr name, ptext (sLit "is not in the type environment: are you sure it exists?")]
throwCmdLineErrorS :: DynFlags -> SDoc -> IO a
throwCmdLineErrorS dflags = throwCmdLineError . showSDoc dflags
throwCmdLineError :: String -> IO a
throwCmdLineError = throwGhcExceptionIO . CmdLineError
#else
pluginError :: [ModuleName] -> a
pluginError modnames = throwGhcException (CmdLineError msg)
where
msg = "not built for interactive use - can't load plugins ("
-- module names are not z-encoded
++ intercalate ", " (map moduleNameString modnames)
++ ")"
#endif
|
ezyang/ghc
|
compiler/main/DynamicLoading.hs
|
bsd-3-clause
| 11,481
| 1
| 24
| 3,118
| 1,991
| 1,036
| 955
| 12
| 1
|
-- | Same as 'txt', but stupidly wraps long lines
module Brick.Widgets.WrappedText
( wrappedText
) where
import Brick
import Control.Lens
import Data.Text (Text)
import qualified Data.Text as T
wrappedText :: Text -> Widget n
wrappedText theText = Widget Fixed Fixed $ do
ctx <- getContext
let newText = wrapLines (ctx^.availWidthL) theText
render $ txt newText
wrapLines :: Int -> Text -> Text
wrapLines width = T.unlines . concat . map wrap . T.lines
where wrap = T.chunksOf width
|
rootzlevel/device-manager
|
src/Brick/Widgets/WrappedText.hs
|
bsd-3-clause
| 539
| 0
| 13
| 134
| 158
| 83
| 75
| 14
| 1
|
{-# LANGUAGE CPP, NondecreasingIndentation, ScopedTypeVariables #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2012
--
-- The GHC API
--
-- -----------------------------------------------------------------------------
module GHC (
-- * Initialisation
defaultErrorHandler,
defaultCleanupHandler,
prettyPrintGhcErrors,
-- * GHC Monad
Ghc, GhcT, GhcMonad(..), HscEnv,
runGhc, runGhcT, initGhcMonad,
gcatch, gbracket, gfinally,
printException,
handleSourceError,
needsTemplateHaskell,
-- * Flags and settings
DynFlags(..), GeneralFlag(..), Severity(..), HscTarget(..), gopt,
GhcMode(..), GhcLink(..), defaultObjectTarget,
parseDynamicFlags,
getSessionDynFlags, setSessionDynFlags,
getProgramDynFlags, setProgramDynFlags,
getInteractiveDynFlags, setInteractiveDynFlags,
parseStaticFlags,
-- * Targets
Target(..), TargetId(..), Phase,
setTargets,
getTargets,
addTarget,
removeTarget,
guessTarget,
-- * Loading\/compiling the program
depanal,
load, LoadHowMuch(..), InteractiveImport(..),
SuccessFlag(..), succeeded, failed,
defaultWarnErrLogger, WarnErrLogger,
workingDirectoryChanged,
parseModule, typecheckModule, desugarModule, loadModule,
ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
TypecheckedSource, ParsedSource, RenamedSource, -- ditto
TypecheckedMod, ParsedMod,
moduleInfo, renamedSource, typecheckedSource,
parsedSource, coreModule,
-- ** Compiling to Core
CoreModule(..),
compileToCoreModule, compileToCoreSimplified,
-- * Inspecting the module structure of the program
ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
getModSummary,
getModuleGraph,
isLoaded,
topSortModuleGraph,
-- * Inspecting modules
ModuleInfo,
getModuleInfo,
modInfoTyThings,
modInfoTopLevelScope,
modInfoExports,
modInfoExportsWithSelectors,
modInfoInstances,
modInfoIsExportedName,
modInfoLookupName,
modInfoIface,
modInfoSafe,
lookupGlobalName,
findGlobalAnns,
mkPrintUnqualifiedForModule,
ModIface(..),
SafeHaskellMode(..),
-- * Querying the environment
-- packageDbModules,
-- * Printing
PrintUnqualified, alwaysQualify,
-- * Interactive evaluation
#ifdef GHCI
-- ** Executing statements
execStmt, ExecOptions(..), execOptions, ExecResult(..),
resumeExec,
-- ** Adding new declarations
runDecls, runDeclsWithLocation,
-- ** Get/set the current context
parseImportDecl,
setContext, getContext,
setGHCiMonad, getGHCiMonad,
#endif
-- ** Inspecting the current context
getBindings, getInsts, getPrintUnqual,
findModule, lookupModule,
#ifdef GHCI
isModuleTrusted, moduleTrustReqs,
getNamesInScope,
getRdrNamesInScope,
getGRE,
moduleIsInterpreted,
getInfo,
showModule,
isModuleInterpreted,
-- ** Inspecting types and kinds
exprType, TcRnExprMode(..),
typeKind,
-- ** Looking up a Name
parseName,
#endif
lookupName,
#ifdef GHCI
-- ** Compiling expressions
HValue, parseExpr, compileParsedExpr,
InteractiveEval.compileExpr, dynCompileExpr,
ForeignHValue,
compileExprRemote, compileParsedExprRemote,
-- ** Other
runTcInteractive, -- Desired by some clients (Trac #8878)
isStmt, hasImport, isImport, isDecl,
-- ** The debugger
SingleStep(..),
Resume(..),
History(historyBreakInfo, historyEnclosingDecls),
GHC.getHistorySpan, getHistoryModule,
abandon, abandonAll,
getResumeContext,
GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
modInfoModBreaks,
ModBreaks(..), BreakIndex,
BreakInfo(breakInfo_number, breakInfo_module),
InteractiveEval.back,
InteractiveEval.forward,
-- ** Deprecated API
RunResult(..),
runStmt, runStmtWithLocation,
resume,
#endif
-- * Abstract syntax elements
-- ** Packages
UnitId,
-- ** Modules
Module, mkModule, pprModule, moduleName, moduleUnitId,
ModuleName, mkModuleName, moduleNameString,
-- ** Names
Name,
isExternalName, nameModule, pprParenSymName, nameSrcSpan,
NamedThing(..),
RdrName(Qual,Unqual),
-- ** Identifiers
Id, idType,
isImplicitId, isDeadBinder,
isExportedId, isLocalId, isGlobalId,
isRecordSelector,
isPrimOpId, isFCallId, isClassOpId_maybe,
isDataConWorkId, idDataCon,
isBottomingId, isDictonaryId,
recordSelectorTyCon,
-- ** Type constructors
TyCon,
tyConTyVars, tyConDataCons, tyConArity,
isClassTyCon, isTypeSynonymTyCon, isTypeFamilyTyCon, isNewTyCon,
isPrimTyCon, isFunTyCon,
isFamilyTyCon, isOpenFamilyTyCon, isOpenTypeFamilyTyCon,
tyConClass_maybe,
synTyConRhs_maybe, synTyConDefn_maybe, tyConKind,
-- ** Type variables
TyVar,
alphaTyVars,
-- ** Data constructors
DataCon,
dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
dataConIsInfix, isVanillaDataCon, dataConUserType,
dataConSrcBangs,
StrictnessMark(..), isMarkedStrict,
-- ** Classes
Class,
classMethods, classSCTheta, classTvsFds, classATs,
pprFundeps,
-- ** Instances
ClsInst,
instanceDFunId,
pprInstance, pprInstanceHdr,
pprFamInst,
FamInst,
-- ** Types and Kinds
Type, splitForAllTys, funResultTy,
pprParendType, pprTypeApp,
Kind,
PredType,
ThetaType, pprForAll, pprForAllImplicit, pprThetaArrowTy,
-- ** Entities
TyThing(..),
-- ** Syntax
module HsSyn, -- ToDo: remove extraneous bits
-- ** Fixities
FixityDirection(..),
defaultFixity, maxPrecedence,
negateFixity,
compareFixity,
-- ** Source locations
SrcLoc(..), RealSrcLoc,
mkSrcLoc, noSrcLoc,
srcLocFile, srcLocLine, srcLocCol,
SrcSpan(..), RealSrcSpan,
mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
srcSpanStart, srcSpanEnd,
srcSpanFile,
srcSpanStartLine, srcSpanEndLine,
srcSpanStartCol, srcSpanEndCol,
-- ** Located
GenLocated(..), Located,
-- *** Constructing Located
noLoc, mkGeneralLocated,
-- *** Deconstructing Located
getLoc, unLoc,
-- *** Combining and comparing Located values
eqLocated, cmpLocated, combineLocs, addCLoc,
leftmost_smallest, leftmost_largest, rightmost,
spans, isSubspanOf,
-- * Exceptions
GhcException(..), showGhcException,
-- * Token stream manipulations
Token,
getTokenStream, getRichTokenStream,
showRichTokenStream, addSourceToTokens,
-- * Pure interface to the parser
parser,
-- * API Annotations
ApiAnns,AnnKeywordId(..),AnnotationComment(..),
getAnnotation, getAndRemoveAnnotation,
getAnnotationComments, getAndRemoveAnnotationComments,
unicodeAnn,
-- * Miscellaneous
--sessionHscEnv,
cyclicModuleErr,
) where
{-
ToDo:
* inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
* what StaticFlags should we expose, if any?
-}
#include "HsVersions.h"
#ifdef GHCI
import ByteCodeTypes
import InteractiveEval
import InteractiveEvalTypes
import TcRnDriver ( runTcInteractive )
import GHCi
import GHCi.RemoteTypes
#endif
import PprTyThing ( pprFamInst )
import HscMain
import GhcMake
import DriverPipeline ( compileOne' )
import GhcMonad
import TcRnMonad ( finalSafeMode, fixSafeInstances )
import TcRnTypes
import Packages
import NameSet
import RdrName
import HsSyn
import Type hiding( typeKind )
import TcType hiding( typeKind )
import Id
import TysPrim ( alphaTyVars )
import TyCon
import Class
import DataCon
import Name hiding ( varName )
import Avail
import InstEnv
import FamInstEnv ( FamInst )
import SrcLoc
import CoreSyn
import TidyPgm
import DriverPhases ( Phase(..), isHaskellSrcFilename )
import Finder
import HscTypes
import DynFlags
import StaticFlags
import SysTools
import Annotations
import Module
import Panic
import Platform
import Bag ( unitBag )
import ErrUtils
import MonadUtils
import Util
import StringBuffer
import Outputable
import BasicTypes
import Maybes ( expectJust )
import FastString
import qualified Parser
import Lexer
import ApiAnnotation
import qualified GHC.LanguageExtensions as LangExt
import System.Directory ( doesFileExist )
import Data.Maybe
import Data.List ( find )
import Data.Time
import Data.Typeable ( Typeable )
import Data.Word ( Word8 )
import Control.Monad
import System.Exit ( exitWith, ExitCode(..) )
import Exception
import Data.IORef
import System.FilePath
import System.IO
import Prelude hiding (init)
-- %************************************************************************
-- %* *
-- Initialisation: exception handlers
-- %* *
-- %************************************************************************
-- | Install some default exception handlers and run the inner computation.
-- Unless you want to handle exceptions yourself, you should wrap this around
-- the top level of your program. The default handlers output the error
-- message(s) to stderr and exit cleanly.
defaultErrorHandler :: (ExceptionMonad m)
=> FatalMessager -> FlushOut -> m a -> m a
defaultErrorHandler fm (FlushOut flushOut) inner =
-- top-level exception handler: any unrecognised exception is a compiler bug.
ghandle (\exception -> liftIO $ do
flushOut
case fromException exception of
-- an IO exception probably isn't our fault, so don't panic
Just (ioe :: IOException) ->
fatalErrorMsg'' fm (show ioe)
_ -> case fromException exception of
Just UserInterrupt ->
-- Important to let this one propagate out so our
-- calling process knows we were interrupted by ^C
liftIO $ throwIO UserInterrupt
Just StackOverflow ->
fatalErrorMsg'' fm "stack overflow: use +RTS -K<size> to increase it"
_ -> case fromException exception of
Just (ex :: ExitCode) -> liftIO $ throwIO ex
_ ->
fatalErrorMsg'' fm
(show (Panic (show exception)))
exitWith (ExitFailure 1)
) $
-- error messages propagated as exceptions
handleGhcException
(\ge -> liftIO $ do
flushOut
case ge of
Signal _ -> exitWith (ExitFailure 1)
_ -> do fatalErrorMsg'' fm (show ge)
exitWith (ExitFailure 1)
) $
inner
-- | This function is no longer necessary, cleanup is now done by
-- runGhc/runGhcT.
{-# DEPRECATED defaultCleanupHandler "Cleanup is now done by runGhc/runGhcT" #-}
defaultCleanupHandler :: (ExceptionMonad m) => DynFlags -> m a -> m a
defaultCleanupHandler _ m = m
where _warning_suppression = m `gonException` undefined
-- %************************************************************************
-- %* *
-- The Ghc Monad
-- %* *
-- %************************************************************************
-- | Run function for the 'Ghc' monad.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
--
-- Any errors not handled inside the 'Ghc' action are propagated as IO
-- exceptions.
runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> Ghc a -- ^ The action to perform.
-> IO a
runGhc mb_top_dir ghc = do
ref <- newIORef (panic "empty session")
let session = Session ref
flip unGhc session $ do
initGhcMonad mb_top_dir
withCleanupSession ghc
-- XXX: unregister interrupt handlers here?
-- | Run function for 'GhcT' monad transformer.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
runGhcT :: ExceptionMonad m =>
Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> GhcT m a -- ^ The action to perform.
-> m a
runGhcT mb_top_dir ghct = do
ref <- liftIO $ newIORef (panic "empty session")
let session = Session ref
flip unGhcT session $ do
initGhcMonad mb_top_dir
withCleanupSession ghct
withCleanupSession :: GhcMonad m => m a -> m a
withCleanupSession ghc = ghc `gfinally` cleanup
where
cleanup = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
liftIO $ do
cleanTempFiles dflags
cleanTempDirs dflags
#ifdef GHCI
stopIServ hsc_env -- shut down the IServ
#endif
-- exceptions will be blocked while we clean the temporary files,
-- so there shouldn't be any difficulty if we receive further
-- signals.
-- | Initialise a GHC session.
--
-- If you implement a custom 'GhcMonad' you must call this function in the
-- monad run function. It will initialise the session variable and clear all
-- warnings.
--
-- The first argument should point to the directory where GHC's library files
-- reside. More precisely, this should be the output of @ghc --print-libdir@
-- of the version of GHC the module using this API is compiled with. For
-- portability, you should use the @ghc-paths@ package, available at
-- <http://hackage.haskell.org/package/ghc-paths>.
initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
initGhcMonad mb_top_dir
= do { env <- liftIO $
do { installSignalHandlers -- catch ^C
; initStaticOpts
; mySettings <- initSysTools mb_top_dir
; dflags <- initDynFlags (defaultDynFlags mySettings)
; checkBrokenTablesNextToCode dflags
; setUnsafeGlobalDynFlags dflags
-- c.f. DynFlags.parseDynamicFlagsFull, which
-- creates DynFlags and sets the UnsafeGlobalDynFlags
; newHscEnv dflags }
; setSession env }
-- | The binutils linker on ARM emits unnecessary R_ARM_COPY relocations which
-- breaks tables-next-to-code in dynamically linked modules. This
-- check should be more selective but there is currently no released
-- version where this bug is fixed.
-- See https://sourceware.org/bugzilla/show_bug.cgi?id=16177 and
-- https://ghc.haskell.org/trac/ghc/ticket/4210#comment:29
checkBrokenTablesNextToCode :: MonadIO m => DynFlags -> m ()
checkBrokenTablesNextToCode dflags
= do { broken <- checkBrokenTablesNextToCode' dflags
; when broken
$ do { _ <- liftIO $ throwIO $ mkApiErr dflags invalidLdErr
; fail "unsupported linker"
}
}
where
invalidLdErr = text "Tables-next-to-code not supported on ARM" <+>
text "when using binutils ld (please see:" <+>
text "https://sourceware.org/bugzilla/show_bug.cgi?id=16177)"
checkBrokenTablesNextToCode' :: MonadIO m => DynFlags -> m Bool
checkBrokenTablesNextToCode' dflags
| not (isARM arch) = return False
| WayDyn `notElem` ways dflags = return False
| not (tablesNextToCode dflags) = return False
| otherwise = do
linkerInfo <- liftIO $ getLinkerInfo dflags
case linkerInfo of
GnuLD _ -> return True
_ -> return False
where platform = targetPlatform dflags
arch = platformArch platform
-- %************************************************************************
-- %* *
-- Flags & settings
-- %* *
-- %************************************************************************
-- $DynFlags
--
-- The GHC session maintains two sets of 'DynFlags':
--
-- * The "interactive" @DynFlags@, which are used for everything
-- related to interactive evaluation, including 'runStmt',
-- 'runDecls', 'exprType', 'lookupName' and so on (everything
-- under \"Interactive evaluation\" in this module).
--
-- * The "program" @DynFlags@, which are used when loading
-- whole modules with 'load'
--
-- 'setInteractiveDynFlags', 'getInteractiveDynFlags' work with the
-- interactive @DynFlags@.
--
-- 'setProgramDynFlags', 'getProgramDynFlags' work with the
-- program @DynFlags@.
--
-- 'setSessionDynFlags' sets both @DynFlags@, and 'getSessionDynFlags'
-- retrieves the program @DynFlags@ (for backwards compatibility).
-- | Updates both the interactive and program DynFlags in a Session.
-- This also reads the package database (unless it has already been
-- read), and prepares the compilers knowledge about packages. It can
-- be called again to load new packages: just add new package flags to
-- (packageFlags dflags).
--
-- Returns a list of new packages that may need to be linked in using
-- the dynamic linker (see 'linkPackages') as a result of new package
-- flags. If you are not doing linking or doing static linking, you
-- can ignore the list of packages returned.
--
setSessionDynFlags :: GhcMonad m => DynFlags -> m [UnitId]
setSessionDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
(dflags'', preload) <- liftIO $ initPackages dflags'
modifySession $ \h -> h{ hsc_dflags = dflags''
, hsc_IC = (hsc_IC h){ ic_dflags = dflags'' } }
invalidateModSummaryCache
return preload
-- | Sets the program 'DynFlags'.
setProgramDynFlags :: GhcMonad m => DynFlags -> m [UnitId]
setProgramDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
(dflags'', preload) <- liftIO $ initPackages dflags'
modifySession $ \h -> h{ hsc_dflags = dflags'' }
invalidateModSummaryCache
return preload
-- When changing the DynFlags, we want the changes to apply to future
-- loads, but without completely discarding the program. But the
-- DynFlags are cached in each ModSummary in the hsc_mod_graph, so
-- after a change to DynFlags, the changes would apply to new modules
-- but not existing modules; this seems undesirable.
--
-- Furthermore, the GHC API client might expect that changing
-- log_action would affect future compilation messages, but for those
-- modules we have cached ModSummaries for, we'll continue to use the
-- old log_action. This is definitely wrong (#7478).
--
-- Hence, we invalidate the ModSummary cache after changing the
-- DynFlags. We do this by tweaking the date on each ModSummary, so
-- that the next downsweep will think that all the files have changed
-- and preprocess them again. This won't necessarily cause everything
-- to be recompiled, because by the time we check whether we need to
-- recopmile a module, we'll have re-summarised the module and have a
-- correct ModSummary.
--
invalidateModSummaryCache :: GhcMonad m => m ()
invalidateModSummaryCache =
modifySession $ \h -> h { hsc_mod_graph = map inval (hsc_mod_graph h) }
where
inval ms = ms { ms_hs_date = addUTCTime (-1) (ms_hs_date ms) }
-- | Returns the program 'DynFlags'.
getProgramDynFlags :: GhcMonad m => m DynFlags
getProgramDynFlags = getSessionDynFlags
-- | Set the 'DynFlags' used to evaluate interactive expressions.
-- Note: this cannot be used for changes to packages. Use
-- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the
-- 'pkgState' into the interactive @DynFlags@.
setInteractiveDynFlags :: GhcMonad m => DynFlags -> m ()
setInteractiveDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
modifySession $ \h -> h{ hsc_IC = (hsc_IC h) { ic_dflags = dflags' }}
-- | Get the 'DynFlags' used to evaluate interactive expressions.
getInteractiveDynFlags :: GhcMonad m => m DynFlags
getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h))
parseDynamicFlags :: MonadIO m =>
DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
parseDynamicFlags = parseDynamicFlagsCmdLine
-- | Checks the set of new DynFlags for possibly erroneous option
-- combinations when invoking 'setSessionDynFlags' and friends, and if
-- found, returns a fixed copy (if possible).
checkNewDynFlags :: MonadIO m => DynFlags -> m DynFlags
checkNewDynFlags dflags = do
-- See Note [DynFlags consistency]
let (dflags', warnings) = makeDynFlagsConsistent dflags
liftIO $ handleFlagWarnings dflags warnings
return dflags'
-- %************************************************************************
-- %* *
-- Setting, getting, and modifying the targets
-- %* *
-- %************************************************************************
-- ToDo: think about relative vs. absolute file paths. And what
-- happens when the current directory changes.
-- | Sets the targets for this session. Each target may be a module name
-- or a filename. The targets correspond to the set of root modules for
-- the program\/library. Unloading the current program is achieved by
-- setting the current set of targets to be empty, followed by 'load'.
setTargets :: GhcMonad m => [Target] -> m ()
setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
-- | Returns the current set of targets
getTargets :: GhcMonad m => m [Target]
getTargets = withSession (return . hsc_targets)
-- | Add another target.
addTarget :: GhcMonad m => Target -> m ()
addTarget target
= modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
-- | Remove a target
removeTarget :: GhcMonad m => TargetId -> m ()
removeTarget target_id
= modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
where
filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
-- | Attempts to guess what Target a string refers to. This function
-- implements the @--make@/GHCi command-line syntax for filenames:
--
-- - if the string looks like a Haskell source filename, then interpret it
-- as such
--
-- - if adding a .hs or .lhs suffix yields the name of an existing file,
-- then use that
--
-- - otherwise interpret the string as a module name
--
guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
guessTarget str (Just phase)
= return (Target (TargetFile str (Just phase)) True Nothing)
guessTarget str Nothing
| isHaskellSrcFilename file
= return (target (TargetFile file Nothing))
| otherwise
= do exists <- liftIO $ doesFileExist hs_file
if exists
then return (target (TargetFile hs_file Nothing))
else do
exists <- liftIO $ doesFileExist lhs_file
if exists
then return (target (TargetFile lhs_file Nothing))
else do
if looksLikeModuleName file
then return (target (TargetModule (mkModuleName file)))
else do
dflags <- getDynFlags
liftIO $ throwGhcExceptionIO
(ProgramError (showSDoc dflags $
text "target" <+> quotes (text file) <+>
text "is not a module name or a source file"))
where
(file,obj_allowed)
| '*':rest <- str = (rest, False)
| otherwise = (str, True)
hs_file = file <.> "hs"
lhs_file = file <.> "lhs"
target tid = Target tid obj_allowed Nothing
-- | Inform GHC that the working directory has changed. GHC will flush
-- its cache of module locations, since it may no longer be valid.
--
-- Note: Before changing the working directory make sure all threads running
-- in the same session have stopped. If you change the working directory,
-- you should also unload the current program (set targets to empty,
-- followed by load).
workingDirectoryChanged :: GhcMonad m => m ()
workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
-- %************************************************************************
-- %* *
-- Running phases one at a time
-- %* *
-- %************************************************************************
class ParsedMod m where
modSummary :: m -> ModSummary
parsedSource :: m -> ParsedSource
class ParsedMod m => TypecheckedMod m where
renamedSource :: m -> Maybe RenamedSource
typecheckedSource :: m -> TypecheckedSource
moduleInfo :: m -> ModuleInfo
tm_internals :: m -> (TcGblEnv, ModDetails)
-- ToDo: improvements that could be made here:
-- if the module succeeded renaming but not typechecking,
-- we can still get back the GlobalRdrEnv and exports, so
-- perhaps the ModuleInfo should be split up into separate
-- fields.
class TypecheckedMod m => DesugaredMod m where
coreModule :: m -> ModGuts
-- | The result of successful parsing.
data ParsedModule =
ParsedModule { pm_mod_summary :: ModSummary
, pm_parsed_source :: ParsedSource
, pm_extra_src_files :: [FilePath]
, pm_annotations :: ApiAnns }
-- See Note [Api annotations] in ApiAnnotation.hs
instance ParsedMod ParsedModule where
modSummary m = pm_mod_summary m
parsedSource m = pm_parsed_source m
-- | The result of successful typechecking. It also contains the parser
-- result.
data TypecheckedModule =
TypecheckedModule { tm_parsed_module :: ParsedModule
, tm_renamed_source :: Maybe RenamedSource
, tm_typechecked_source :: TypecheckedSource
, tm_checked_module_info :: ModuleInfo
, tm_internals_ :: (TcGblEnv, ModDetails)
}
instance ParsedMod TypecheckedModule where
modSummary m = modSummary (tm_parsed_module m)
parsedSource m = parsedSource (tm_parsed_module m)
instance TypecheckedMod TypecheckedModule where
renamedSource m = tm_renamed_source m
typecheckedSource m = tm_typechecked_source m
moduleInfo m = tm_checked_module_info m
tm_internals m = tm_internals_ m
-- | The result of successful desugaring (i.e., translation to core). Also
-- contains all the information of a typechecked module.
data DesugaredModule =
DesugaredModule { dm_typechecked_module :: TypecheckedModule
, dm_core_module :: ModGuts
}
instance ParsedMod DesugaredModule where
modSummary m = modSummary (dm_typechecked_module m)
parsedSource m = parsedSource (dm_typechecked_module m)
instance TypecheckedMod DesugaredModule where
renamedSource m = renamedSource (dm_typechecked_module m)
typecheckedSource m = typecheckedSource (dm_typechecked_module m)
moduleInfo m = moduleInfo (dm_typechecked_module m)
tm_internals m = tm_internals_ (dm_typechecked_module m)
instance DesugaredMod DesugaredModule where
coreModule m = dm_core_module m
type ParsedSource = Located (HsModule RdrName)
type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
Maybe LHsDocString)
type TypecheckedSource = LHsBinds Id
-- NOTE:
-- - things that aren't in the output of the typechecker right now:
-- - the export list
-- - the imports
-- - type signatures
-- - type/data/newtype declarations
-- - class declarations
-- - instances
-- - extra things in the typechecker's output:
-- - default methods are turned into top-level decls.
-- - dictionary bindings
-- | Return the 'ModSummary' of a module with the given name.
--
-- The module must be part of the module graph (see 'hsc_mod_graph' and
-- 'ModuleGraph'). If this is not the case, this function will throw a
-- 'GhcApiError'.
--
-- This function ignores boot modules and requires that there is only one
-- non-boot module with the given name.
getModSummary :: GhcMonad m => ModuleName -> m ModSummary
getModSummary mod = do
mg <- liftM hsc_mod_graph getSession
case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
[] -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "Module not part of module graph")
[ms] -> return ms
multiple -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "getModSummary is ambiguous: " <+> ppr multiple)
-- | Parse a module.
--
-- Throws a 'SourceError' on parse error.
parseModule :: GhcMonad m => ModSummary -> m ParsedModule
parseModule ms = do
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
hpm <- liftIO $ hscParse hsc_env_tmp ms
return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm)
(hpm_annotations hpm))
-- See Note [Api annotations] in ApiAnnotation.hs
-- | Typecheck and rename a parsed module.
--
-- Throws a 'SourceError' if either fails.
typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
typecheckModule pmod = do
let ms = modSummary pmod
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
(tc_gbl_env, rn_info)
<- liftIO $ hscTypecheckRename hsc_env_tmp ms $
HsParsedModule { hpm_module = parsedSource pmod,
hpm_src_files = pm_extra_src_files pmod,
hpm_annotations = pm_annotations pmod }
details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env
safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env
return $
TypecheckedModule {
tm_internals_ = (tc_gbl_env, details),
tm_parsed_module = pmod,
tm_renamed_source = rn_info,
tm_typechecked_source = tcg_binds tc_gbl_env,
tm_checked_module_info =
ModuleInfo {
minf_type_env = md_types details,
minf_exports = md_exports details,
minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
minf_instances = fixSafeInstances safe $ md_insts details,
minf_iface = Nothing,
minf_safe = safe
#ifdef GHCI
,minf_modBreaks = emptyModBreaks
#endif
}}
-- | Desugar a typechecked module.
desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
desugarModule tcm = do
let ms = modSummary tcm
let (tcg, _) = tm_internals tcm
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg
return $
DesugaredModule {
dm_typechecked_module = tcm,
dm_core_module = guts
}
-- | Load a module. Input doesn't need to be desugared.
--
-- A module must be loaded before dependent modules can be typechecked. This
-- always includes generating a 'ModIface' and, depending on the
-- 'DynFlags.hscTarget', may also include code generation.
--
-- This function will always cause recompilation and will always overwrite
-- previous compilation results (potentially files on disk).
--
loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
loadModule tcm = do
let ms = modSummary tcm
let mod = ms_mod_name ms
let loc = ms_location ms
let (tcg, _details) = tm_internals tcm
mb_linkable <- case ms_obj_date ms of
Just t | t > ms_hs_date ms -> do
l <- liftIO $ findObjectLinkable (ms_mod ms)
(ml_obj_file loc) t
return (Just l)
_otherwise -> return Nothing
let source_modified | isNothing mb_linkable = SourceModified
| otherwise = SourceUnmodified
-- we can't determine stability here
-- compile doesn't change the session
hsc_env <- getSession
mod_info <- liftIO $ compileOne' (Just tcg) Nothing
hsc_env ms 1 1 Nothing mb_linkable
source_modified
modifySession $ \e -> e{ hsc_HPT = addToHpt (hsc_HPT e) mod mod_info }
return tcm
-- %************************************************************************
-- %* *
-- Dealing with Core
-- %* *
-- %************************************************************************
-- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
-- the 'GHC.compileToCoreModule' interface.
data CoreModule
= CoreModule {
-- | Module name
cm_module :: !Module,
-- | Type environment for types declared in this module
cm_types :: !TypeEnv,
-- | Declarations
cm_binds :: CoreProgram,
-- | Safe Haskell mode
cm_safe :: SafeHaskellMode
}
instance Outputable CoreModule where
ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb,
cm_safe = sf})
= text "%module" <+> ppr mn <+> parens (ppr sf) <+> ppr te
$$ vcat (map ppr cb)
-- | This is the way to get access to the Core bindings corresponding
-- to a module. 'compileToCore' parses, typechecks, and
-- desugars the module, then returns the resulting Core module (consisting of
-- the module name, type declarations, and function declarations) if
-- successful.
compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
compileToCoreModule = compileCore False
-- | Like compileToCoreModule, but invokes the simplifier, so
-- as to return simplified and tidied Core.
compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
compileToCoreSimplified = compileCore True
compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
compileCore simplify fn = do
-- First, set the target to the desired filename
target <- guessTarget fn Nothing
addTarget target
_ <- load LoadAllTargets
-- Then find dependencies
modGraph <- depanal [] True
case find ((== fn) . msHsFilePath) modGraph of
Just modSummary -> do
-- Now we have the module name;
-- parse, typecheck and desugar the module
mod_guts <- coreModule `fmap`
-- TODO: space leaky: call hsc* directly?
(desugarModule =<< typecheckModule =<< parseModule modSummary)
liftM (gutsToCoreModule (mg_safe_haskell mod_guts)) $
if simplify
then do
-- If simplify is true: simplify (hscSimplify), then tidy
-- (tidyProgram).
hsc_env <- getSession
simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts
tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
return $ Left tidy_guts
else
return $ Right mod_guts
Nothing -> panic "compileToCoreModule: target FilePath not found in\
module dependency graph"
where -- two versions, based on whether we simplify (thus run tidyProgram,
-- which returns a (CgGuts, ModDetails) pair, or not (in which case
-- we just have a ModGuts.
gutsToCoreModule :: SafeHaskellMode
-> Either (CgGuts, ModDetails) ModGuts
-> CoreModule
gutsToCoreModule safe_mode (Left (cg, md)) = CoreModule {
cm_module = cg_module cg,
cm_types = md_types md,
cm_binds = cg_binds cg,
cm_safe = safe_mode
}
gutsToCoreModule safe_mode (Right mg) = CoreModule {
cm_module = mg_module mg,
cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg))
(mg_tcs mg)
(mg_fam_insts mg),
cm_binds = mg_binds mg,
cm_safe = safe_mode
}
-- %************************************************************************
-- %* *
-- Inspecting the session
-- %* *
-- %************************************************************************
-- | Get the module dependency graph.
getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
getModuleGraph = liftM hsc_mod_graph getSession
-- | Determines whether a set of modules requires Template Haskell.
--
-- Note that if the session's 'DynFlags' enabled Template Haskell when
-- 'depanal' was called, then each module in the returned module graph will
-- have Template Haskell enabled whether it is actually needed or not.
needsTemplateHaskell :: ModuleGraph -> Bool
needsTemplateHaskell ms =
any (xopt LangExt.TemplateHaskell . ms_hspp_opts) ms
-- | Return @True@ <==> module is loaded.
isLoaded :: GhcMonad m => ModuleName -> m Bool
isLoaded m = withSession $ \hsc_env ->
return $! isJust (lookupHpt (hsc_HPT hsc_env) m)
-- | Return the bindings for the current interactive session.
getBindings :: GhcMonad m => m [TyThing]
getBindings = withSession $ \hsc_env ->
return $ icInScopeTTs $ hsc_IC hsc_env
-- | Return the instances for the current interactive session.
getInsts :: GhcMonad m => m ([ClsInst], [FamInst])
getInsts = withSession $ \hsc_env ->
return $ ic_instances (hsc_IC hsc_env)
getPrintUnqual :: GhcMonad m => m PrintUnqualified
getPrintUnqual = withSession $ \hsc_env ->
return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
-- | Container for information about a 'Module'.
data ModuleInfo = ModuleInfo {
minf_type_env :: TypeEnv,
minf_exports :: [AvailInfo],
minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
minf_instances :: [ClsInst],
minf_iface :: Maybe ModIface,
minf_safe :: SafeHaskellMode
#ifdef GHCI
,minf_modBreaks :: ModBreaks
#endif
}
-- We don't want HomeModInfo here, because a ModuleInfo applies
-- to package modules too.
-- | Request information about a loaded 'Module'
getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
getModuleInfo mdl = withSession $ \hsc_env -> do
let mg = hsc_mod_graph hsc_env
if mdl `elem` map ms_mod mg
then liftIO $ getHomeModuleInfo hsc_env mdl
else do
{- if isHomeModule (hsc_dflags hsc_env) mdl
then return Nothing
else -} liftIO $ getPackageModuleInfo hsc_env mdl
-- ToDo: we don't understand what the following comment means.
-- (SDM, 19/7/2011)
-- getPackageModuleInfo will attempt to find the interface, so
-- we don't want to call it for a home module, just in case there
-- was a problem loading the module and the interface doesn't
-- exist... hence the isHomeModule test here. (ToDo: reinstate)
getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
#ifdef GHCI
getPackageModuleInfo hsc_env mdl
= do eps <- hscEPS hsc_env
iface <- hscGetModuleInterface hsc_env mdl
let
avails = mi_exports iface
pte = eps_PTE eps
tys = [ ty | name <- concatMap availNames avails,
Just ty <- [lookupTypeEnv pte name] ]
--
return (Just (ModuleInfo {
minf_type_env = mkTypeEnv tys,
minf_exports = avails,
minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
minf_instances = error "getModuleInfo: instances for package module unimplemented",
minf_iface = Just iface,
minf_safe = getSafeMode $ mi_trust iface,
minf_modBreaks = emptyModBreaks
}))
#else
-- bogusly different for non-GHCI (ToDo)
getPackageModuleInfo _hsc_env _mdl = do
return Nothing
#endif
getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
getHomeModuleInfo hsc_env mdl =
case lookupHpt (hsc_HPT hsc_env) (moduleName mdl) of
Nothing -> return Nothing
Just hmi -> do
let details = hm_details hmi
iface = hm_iface hmi
return (Just (ModuleInfo {
minf_type_env = md_types details,
minf_exports = md_exports details,
minf_rdr_env = mi_globals $! hm_iface hmi,
minf_instances = md_insts details,
minf_iface = Just iface,
minf_safe = getSafeMode $ mi_trust iface
#ifdef GHCI
,minf_modBreaks = getModBreaks hmi
#endif
}))
-- | The list of top-level entities defined in a module
modInfoTyThings :: ModuleInfo -> [TyThing]
modInfoTyThings minf = typeEnvElts (minf_type_env minf)
modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
modInfoTopLevelScope minf
= fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
modInfoExports :: ModuleInfo -> [Name]
modInfoExports minf = concatMap availNames $! minf_exports minf
modInfoExportsWithSelectors :: ModuleInfo -> [Name]
modInfoExportsWithSelectors minf = concatMap availNamesWithSelectors $! minf_exports minf
-- | Returns the instances defined by the specified module.
-- Warning: currently unimplemented for package modules.
modInfoInstances :: ModuleInfo -> [ClsInst]
modInfoInstances = minf_instances
modInfoIsExportedName :: ModuleInfo -> Name -> Bool
modInfoIsExportedName minf name = elemNameSet name (availsToNameSet (minf_exports minf))
mkPrintUnqualifiedForModule :: GhcMonad m =>
ModuleInfo
-> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
modInfoLookupName :: GhcMonad m =>
ModuleInfo -> Name
-> m (Maybe TyThing) -- XXX: returns a Maybe X
modInfoLookupName minf name = withSession $ \hsc_env -> do
case lookupTypeEnv (minf_type_env minf) name of
Just tyThing -> return (Just tyThing)
Nothing -> do
eps <- liftIO $ readIORef (hsc_EPS hsc_env)
return $! lookupType (hsc_dflags hsc_env)
(hsc_HPT hsc_env) (eps_PTE eps) name
modInfoIface :: ModuleInfo -> Maybe ModIface
modInfoIface = minf_iface
-- | Retrieve module safe haskell mode
modInfoSafe :: ModuleInfo -> SafeHaskellMode
modInfoSafe = minf_safe
#ifdef GHCI
modInfoModBreaks :: ModuleInfo -> ModBreaks
modInfoModBreaks = minf_modBreaks
#endif
isDictonaryId :: Id -> Bool
isDictonaryId id
= case tcSplitSigmaTy (idType id) of {
(_tvs, _theta, tau) -> isDictTy tau }
-- | Looks up a global name: that is, any top-level name in any
-- visible module. Unlike 'lookupName', lookupGlobalName does not use
-- the interactive context, and therefore does not require a preceding
-- 'setContext'.
lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
lookupGlobalName name = withSession $ \hsc_env -> do
liftIO $ lookupTypeHscEnv hsc_env name
findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
findGlobalAnns deserialize target = withSession $ \hsc_env -> do
ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
return (findAnns deserialize ann_env target)
#ifdef GHCI
-- | get the GlobalRdrEnv for a session
getGRE :: GhcMonad m => m GlobalRdrEnv
getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
#endif
-- -----------------------------------------------------------------------------
{- ToDo: Move the primary logic here to compiler/main/Packages.hs
-- | Return all /external/ modules available in the package database.
-- Modules from the current session (i.e., from the 'HomePackageTable') are
-- not included. This includes module names which are reexported by packages.
packageDbModules :: GhcMonad m =>
Bool -- ^ Only consider exposed packages.
-> m [Module]
packageDbModules only_exposed = do
dflags <- getSessionDynFlags
let pkgs = eltsUFM (pkgIdMap (pkgState dflags))
return $
[ mkModule pid modname
| p <- pkgs
, not only_exposed || exposed p
, let pid = packageConfigId p
, modname <- exposedModules p
++ map exportName (reexportedModules p) ]
-}
-- -----------------------------------------------------------------------------
-- Misc exported utils
dataConType :: DataCon -> Type
dataConType dc = idType (dataConWrapId dc)
-- | print a 'NamedThing', adding parentheses if the name is an operator.
pprParenSymName :: NamedThing a => a -> SDoc
pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
-- ----------------------------------------------------------------------------
#if 0
-- ToDo:
-- - Data and Typeable instances for HsSyn.
-- ToDo: check for small transformations that happen to the syntax in
-- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
-- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
-- to get from TyCons, Ids etc. to TH syntax (reify).
-- :browse will use either lm_toplev or inspect lm_interface, depending
-- on whether the module is interpreted or not.
#endif
-- Extract the filename, stringbuffer content and dynflags associed to a module
--
-- XXX: Explain pre-conditions
getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
getModuleSourceAndFlags mod = do
m <- getModSummary (moduleName mod)
case ml_hs_file $ ms_location m of
Nothing -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "No source available for module " <+> ppr mod)
Just sourceFile -> do
source <- liftIO $ hGetStringBuffer sourceFile
return (sourceFile, source, ms_hspp_opts m)
-- | Return module source as token stream, including comments.
--
-- The module must be in the module graph and its source must be available.
-- Throws a 'HscTypes.SourceError' on parse error.
getTokenStream :: GhcMonad m => Module -> m [Located Token]
getTokenStream mod = do
(sourceFile, source, flags) <- getModuleSourceAndFlags mod
let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
case lexTokenStream source startLoc flags of
POk _ ts -> return ts
PFailed span err ->
do dflags <- getDynFlags
liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
-- | Give even more information on the source than 'getTokenStream'
-- This function allows reconstructing the source completely with
-- 'showRichTokenStream'.
getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
getRichTokenStream mod = do
(sourceFile, source, flags) <- getModuleSourceAndFlags mod
let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
case lexTokenStream source startLoc flags of
POk _ ts -> return $ addSourceToTokens startLoc source ts
PFailed span err ->
do dflags <- getDynFlags
liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
-- | Given a source location and a StringBuffer corresponding to this
-- location, return a rich token stream with the source associated to the
-- tokens.
addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token]
-> [(Located Token, String)]
addSourceToTokens _ _ [] = []
addSourceToTokens loc buf (t@(L span _) : ts)
= case span of
UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts
RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts
where
(newLoc, newBuf, str) = go "" loc buf
start = realSrcSpanStart s
end = realSrcSpanEnd s
go acc loc buf | loc < start = go acc nLoc nBuf
| start <= loc && loc < end = go (ch:acc) nLoc nBuf
| otherwise = (loc, buf, reverse acc)
where (ch, nBuf) = nextChar buf
nLoc = advanceSrcLoc loc ch
-- | Take a rich token stream such as produced from 'getRichTokenStream' and
-- return source code almost identical to the original code (except for
-- insignificant whitespace.)
showRichTokenStream :: [(Located Token, String)] -> String
showRichTokenStream ts = go startLoc ts ""
where sourceFile = getFile $ map (getLoc . fst) ts
getFile [] = panic "showRichTokenStream: No source file found"
getFile (UnhelpfulSpan _ : xs) = getFile xs
getFile (RealSrcSpan s : _) = srcSpanFile s
startLoc = mkRealSrcLoc sourceFile 1 1
go _ [] = id
go loc ((L span _, str):ts)
= case span of
UnhelpfulSpan _ -> go loc ts
RealSrcSpan s
| locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
. (str ++)
. go tokEnd ts
| otherwise -> ((replicate (tokLine - locLine) '\n') ++)
. ((replicate (tokCol - 1) ' ') ++)
. (str ++)
. go tokEnd ts
where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
(tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
tokEnd = realSrcSpanEnd s
-- -----------------------------------------------------------------------------
-- Interactive evaluation
-- | Takes a 'ModuleName' and possibly a 'UnitId', and consults the
-- filesystem and package database to find the corresponding 'Module',
-- using the algorithm that is used for an @import@ declaration.
findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
let
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
--
case maybe_pkg of
Just pkg | fsToUnitId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
res <- findImportedModule hsc_env mod_name maybe_pkg
case res of
Found _ m -> return m
err -> throwOneError $ noModError dflags noSrcSpan mod_name err
_otherwise -> do
home <- lookupLoadedHomeModule mod_name
case home of
Just m -> return m
Nothing -> liftIO $ do
res <- findImportedModule hsc_env mod_name maybe_pkg
case res of
Found loc m | moduleUnitId m /= this_pkg -> return m
| otherwise -> modNotLoadedError dflags m loc
err -> throwOneError $ noModError dflags noSrcSpan mod_name err
modNotLoadedError :: DynFlags -> Module -> ModLocation -> IO a
modNotLoadedError dflags m loc = throwGhcExceptionIO $ CmdLineError $ showSDoc dflags $
text "module is not loaded:" <+>
quotes (ppr (moduleName m)) <+>
parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
-- | Like 'findModule', but differs slightly when the module refers to
-- a source file, and the file has not been loaded via 'load'. In
-- this case, 'findModule' will throw an error (module not loaded),
-- but 'lookupModule' will check to see whether the module can also be
-- found in a package, and if so, that package 'Module' will be
-- returned. If not, the usual module-not-found error will be thrown.
--
lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
lookupModule mod_name Nothing = withSession $ \hsc_env -> do
home <- lookupLoadedHomeModule mod_name
case home of
Just m -> return m
Nothing -> liftIO $ do
res <- findExposedPackageModule hsc_env mod_name Nothing
case res of
Found _ m -> return m
err -> throwOneError $ noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
case lookupHpt (hsc_HPT hsc_env) mod_name of
Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
_not_a_home_module -> return Nothing
#ifdef GHCI
-- | Check that a module is safe to import (according to Safe Haskell).
--
-- We return True to indicate the import is safe and False otherwise
-- although in the False case an error may be thrown first.
isModuleTrusted :: GhcMonad m => Module -> m Bool
isModuleTrusted m = withSession $ \hsc_env ->
liftIO $ hscCheckSafe hsc_env m noSrcSpan
-- | Return if a module is trusted and the pkgs it depends on to be trusted.
moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [UnitId])
moduleTrustReqs m = withSession $ \hsc_env ->
liftIO $ hscGetSafe hsc_env m noSrcSpan
-- | Set the monad GHCi lifts user statements into.
--
-- Checks that a type (in string form) is an instance of the
-- @GHC.GHCi.GHCiSandboxIO@ type class. Sets it to be the GHCi monad if it is,
-- throws an error otherwise.
setGHCiMonad :: GhcMonad m => String -> m ()
setGHCiMonad name = withSession $ \hsc_env -> do
ty <- liftIO $ hscIsGHCiMonad hsc_env name
modifySession $ \s ->
let ic = (hsc_IC s) { ic_monad = ty }
in s { hsc_IC = ic }
-- | Get the monad GHCi lifts user statements into.
getGHCiMonad :: GhcMonad m => m Name
getGHCiMonad = fmap (ic_monad . hsc_IC) getSession
getHistorySpan :: GhcMonad m => History -> m SrcSpan
getHistorySpan h = withSession $ \hsc_env ->
return $ InteractiveEval.getHistorySpan hsc_env h
obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
obtainTermFromVal bound force ty a = withSession $ \hsc_env ->
liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
obtainTermFromId bound force id = withSession $ \hsc_env ->
liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id
#endif
-- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
-- entity known to GHC, including 'Name's defined using 'runStmt'.
lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
lookupName name =
withSession $ \hsc_env ->
liftIO $ hscTcRcLookupName hsc_env name
-- -----------------------------------------------------------------------------
-- Pure API
-- | A pure interface to the module parser.
--
parser :: String -- ^ Haskell module source text (full Unicode is supported)
-> DynFlags -- ^ the flags
-> FilePath -- ^ the filename (for source locations)
-> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
parser str dflags filename =
let
loc = mkRealSrcLoc (mkFastString filename) 1 1
buf = stringToStringBuffer str
in
case unP Parser.parseModule (mkPState dflags buf loc) of
PFailed span err ->
Left (unitBag (mkPlainErrMsg dflags span err))
POk pst rdr_module ->
let (warns,_) = getMessages pst dflags in
Right (warns, rdr_module)
|
vTurbine/ghc
|
compiler/main/GHC.hs
|
bsd-3-clause
| 56,666
| 4
| 28
| 15,356
| 10,125
| 5,455
| 4,670
| -1
| -1
|
{-# LANGUAGE BangPatterns #-}
-- |
-- Module : Data.ByteString.Lazy.Search.DFA
-- Copyright : Daniel Fischer
-- Licence : BSD3
-- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability : Provisional
-- Portability : non-portable (BangPatterns)
--
-- Fast search of lazy 'L.ByteString' values. Breaking,
-- splitting and replacing using a deterministic finite automaton.
module Data.ByteString.Lazy.Search.DFA ( -- * Overview
-- $overview
-- ** Complexity and performance
-- $complexity
-- ** Partial application
-- $partial
-- * Finding substrings
indices
, nonOverlappingIndices
-- * Breaking on substrings
, breakOn
, breakAfter
, breakFindAfter
-- * Replacing
, replace
-- * Splitting
, split
, splitKeepEnd
, splitKeepFront
) where
import Data.ByteString.Search.Internal.Utils (automaton, keep, ldrop, lsplit)
import Data.ByteString.Search.Substitution
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Internal as LI
import Data.ByteString.Unsafe (unsafeIndex)
import Data.Array.Base (unsafeAt)
--import Data.Array.Unboxed (UArray)
import Data.Bits
import Data.Int (Int64)
-- $overview
--
-- This module provides functions related to searching a substring within
-- a string. The searching algorithm uses a deterministic finite automaton
-- based on the Knuth-Morris-Pratt algorithm.
-- The automaton is implemented as an array of @(patternLength + 1) * σ@
-- state transitions, where σ is the alphabet size (256), so it is only
-- suitable for short enough patterns, therefore the patterns in this module
-- are required to be strict 'S.ByteString's.
--
-- When searching a pattern in a UTF-8-encoded 'L.ByteString', be aware that
-- these functions work on bytes, not characters, so the indices are
-- byte-offsets, not character offsets.
-- $complexity
--
-- The time and space complexity of the preprocessing phase is
-- /O/(@patternLength * σ@).
-- The searching phase is /O/(@targetLength@), each target character is
-- inspected only once.
--
-- In general the functions in this module have about the same performance as
-- the corresponding functions using the Knuth-Morris-Pratt algorithm but
-- are considerably slower than the Boyer-Moore functions. For very short
-- patterns or, in the case of 'indices', patterns with a short period
-- which occur often, however, times are close to or even below the
-- Boyer-Moore times.
-- $partial
--
-- All functions can usefully be partially applied. Given only a pattern,
-- the automaton is constructed only once, allowing efficient re-use.
------------------------------------------------------------------------------
-- Exported Functions --
------------------------------------------------------------------------------
-- | @'indices'@ finds the starting indices of all possibly overlapping
-- occurrences of the pattern in the target string.
-- If the pattern is empty, the result is @[0 .. 'length' target]@.
{-# INLINE indices #-}
indices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
indices !pat = lazySearcher True pat . L.toChunks
-- | @'nonOverlappingIndices'@ finds the starting indices of all
-- non-overlapping occurrences of the pattern in the target string.
-- It is more efficient than removing indices from the list produced
-- by 'indices'.
{-# INLINE nonOverlappingIndices #-}
nonOverlappingIndices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
nonOverlappingIndices !pat = lazySearcher False pat . L.toChunks
-- | @'breakOn' pattern target@ splits @target@ at the first occurrence
-- of @pattern@. If the pattern does not occur in the target, the
-- second component of the result is empty, otherwise it starts with
-- @pattern@. If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
--
-- @
-- 'uncurry' 'L.append' . 'breakOn' pattern = 'id'
-- @
breakOn :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken at substring
breakOn pat = breaker . L.toChunks
where
lbrk = lazyBreaker True pat
breaker strs = let (f, b) = lbrk strs
in (L.fromChunks f, L.fromChunks b)
-- | @'breakAfter' pattern target@ splits @target@ behind the first occurrence
-- of @pattern@. An empty second component means that either the pattern
-- does not occur in the target or the first occurrence of pattern is at
-- the very end of target. If you need to discriminate between those cases,
-- use breakFindAfter.
-- If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
-- @
-- 'uncurry' 'L.append' . 'breakAfter' pattern = 'id'
-- @
breakAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken after substring
breakAfter pat = breaker . L.toChunks
where
lbrk = lazyBreaker False pat
breaker strs = let (f, b) = lbrk strs
in (L.fromChunks f, L.fromChunks b)
-- | @'breakFindAfter'@ does the same as 'breakAfter' but additionally indicates
-- whether the pattern is present in the target.
--
-- @
-- 'fst' . 'breakFindAfter' pat = 'breakAfter' pat
-- @
breakFindAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> ((L.ByteString, L.ByteString), Bool)
-- ^ Head and tail of string broken after substring
-- and presence of pattern
breakFindAfter pat
| S.null pat = \str -> ((L.empty, str), True)
breakFindAfter pat = breaker . L.toChunks
where
!patLen = S.length pat
lbrk = lazyBreaker True pat
breaker strs = let (f, b) = lbrk strs
(f1, b1) = lsplit patLen b
mbpat = L.fromChunks f1
in ((foldr LI.chunk mbpat f, L.fromChunks b1), not (null b))
-- | @'replace' pat sub text@ replaces all (non-overlapping) occurrences of
-- @pat@ in @text@ with @sub@. If occurrences of @pat@ overlap, the first
-- occurrence that does not overlap with a replaced previous occurrence
-- is substituted. Occurrences of @pat@ arising from a substitution
-- will not be substituted. For example:
--
-- @
-- 'replace' \"ana\" \"olog\" \"banana\" = \"bologna\"
-- 'replace' \"ana\" \"o\" \"bananana\" = \"bono\"
-- 'replace' \"aab\" \"abaa\" \"aaabb\" = \"aabaab\"
-- @
--
-- The result is a lazy 'L.ByteString',
-- which is lazily produced, without copying.
-- Equality of pattern and substitution is not checked, but
--
-- @
-- 'replace' pat pat text == text
-- @
--
-- holds (the internal structure is generally different).
-- If the pattern is empty but not the substitution, the result
-- is equivalent to (were they 'String's) @cycle sub@.
--
-- For non-empty @pat@ and @sub@ a lazy 'L.ByteString',
--
-- @
-- 'L.concat' . 'Data.List.intersperse' sub . 'split' pat = 'replace' pat sub
-- @
--
-- and analogous relations hold for other types of @sub@.
replace :: Substitution rep
=> S.ByteString -- ^ Strict pattern to replace
-> rep -- ^ Replacement string
-> L.ByteString -- ^ Lazy string to modify
-> L.ByteString -- ^ Lazy result
replace pat
| S.null pat = \sub -> prependCycle sub
| otherwise =
let !patLen = S.length pat
breaker = lazyBreaker True pat
repl subst strs
| null strs = []
| otherwise =
let (pre, mtch) = breaker strs
in pre ++ case mtch of
[] -> []
_ -> subst (repl subst (ldrop patLen mtch))
in \sub -> let {-# NOINLINE subst #-}
!subst = substitution sub
repl1 = repl subst
in L.fromChunks . repl1 . L.toChunks
-- | @'split' pattern target@ splits @target@ at each (non-overlapping)
-- occurrence of @pattern@, removing @pattern@. If @pattern@ is empty,
-- the result is an infinite list of empty 'L.ByteString's, if @target@
-- is empty but not @pattern@, the result is an empty list, otherwise
-- the following relations hold (where @patL@ is the lazy 'L.ByteString'
-- corresponding to @pat@):
--
-- @
-- 'L.concat' . 'Data.List.intersperse' patL . 'split' pat = 'id',
-- 'length' ('split' pattern target) ==
-- 'length' ('nonOverlappingIndices' pattern target) + 1,
-- @
--
-- no fragment in the result contains an occurrence of @pattern@.
split :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
split pat
| S.null pat = const (repeat L.empty)
split pat = map L.fromChunks . splitter . L.toChunks
where
!patLen = S.length pat
breaker = lazyBreaker True pat
splitter strs
| null strs = []
| otherwise = splitter' strs
splitter' strs
| null strs = [[]]
| otherwise =
case breaker strs of
(pre, mtch) ->
pre : case mtch of
[] -> []
_ -> splitter' (ldrop patLen mtch)
-- | @'splitKeepEnd' pattern target@ splits @target@ after each (non-overlapping)
-- occurrence of @pattern@. If @pattern@ is empty, the result is an
-- infinite list of empty 'L.ByteString's, otherwise the following
-- relations hold:
--
-- @
-- 'L.concat' . 'splitKeepEnd' pattern = 'id,'
-- @
--
-- all fragments in the result except possibly the last end with
-- @pattern@, no fragment contains more than one occurrence of @pattern@.
splitKeepEnd :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepEnd pat
| S.null pat = const (repeat L.empty)
splitKeepEnd pat = map L.fromChunks . splitter . L.toChunks
where
breaker = lazyBreaker False pat
splitter [] = []
splitter strs =
case breaker strs of
(pre, mtch) -> pre : splitter mtch
-- | @'splitKeepFront'@ is like 'splitKeepEnd', except that @target@ is split
-- before each occurrence of @pattern@ and hence all fragments
-- with the possible exception of the first begin with @pattern@.
-- No fragment contains more than one non-overlapping occurrence
-- of @pattern@.
splitKeepFront :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepFront pat
| S.null pat = const (repeat L.empty)
splitKeepFront pat = map L.fromChunks . splitter . L.toChunks
where
!patLen = S.length pat
breaker = lazyBreaker True pat
splitter strs = case splitter' strs of
([] : rst) -> rst
other -> other
splitter' [] = []
splitter' strs =
case breaker strs of
(pre, mtch) ->
pre : case mtch of
[] -> []
_ -> case lsplit patLen mtch of
(pt, rst) ->
if null rst
then [pt]
else let (h : t) = splitter' rst
in (pt ++ h) : t
------------------------------------------------------------------------------
-- Searching Function --
------------------------------------------------------------------------------
lazySearcher :: Bool -> S.ByteString -> [S.ByteString] -> [Int64]
lazySearcher _ !pat
| S.null pat =
let zgo _ [] = []
zgo !prior (!str : rest) =
let !l = S.length str
!prior' = prior + fromIntegral l
in [prior + fromIntegral i | i <- [1 .. l]] ++ zgo prior' rest
in (0:) . zgo 0
| S.length pat == 1 =
let !w = S.head pat
ixes = S.elemIndices w
go _ [] = []
go !prior (!str : rest)
= let !prior' = prior + fromIntegral (S.length str)
in map ((+ prior) . fromIntegral) (ixes str) ++ go prior' rest
in go 0
lazySearcher !overlap pat = search 0 0
where
!patLen = S.length pat
!auto = automaton pat
!p0 = unsafeIndex pat 0
!ams = if overlap then patLen else 0
search _ _ [] = []
search !prior st (!str:rest) = match st 0
where
!strLen = S.length str
{-# INLINE strAt #-}
strAt :: Int -> Int
strAt i = fromIntegral (str `unsafeIndex` i)
match 0 !idx
| idx == strLen = search (prior + fromIntegral strLen) 0 rest
| unsafeIndex str idx == p0 = match 1 (idx + 1)
| otherwise = match 0 (idx + 1)
match state idx
| idx == strLen = search (prior + fromIntegral strLen) state rest
| otherwise =
let nstate = unsafeAt auto ((state `shiftL` 8) + strAt idx)
!nxtIdx = idx + 1
in if nstate == patLen
then (prior + fromIntegral (nxtIdx - patLen)) :
match ams nxtIdx
else match nstate nxtIdx
------------------------------------------------------------------------------
-- Breaking --
------------------------------------------------------------------------------
-- Code duplication :(
-- Needed for reasonable performance.
lazyBreaker :: Bool -> S.ByteString -> [S.ByteString]
-> ([S.ByteString], [S.ByteString])
lazyBreaker before pat
| S.null pat = \strs -> ([], strs)
| S.length pat == 1 =
let !w = S.head pat
!a = if before then 0 else 1
ixes = S.elemIndices w
scan [] = ([], [])
scan (!str:rest) =
let !strLen = S.length str
in case ixes str of
[] -> let (fr, bk) = scan rest in (str : fr, bk)
(i:_) -> let !j = i + a
in if j == strLen
then ([str],rest)
else ([S.take j str], S.drop j str : rest)
in scan
lazyBreaker !before pat = bscan [] 0
where
!patLen = S.length pat
!auto = automaton pat
!p0 = unsafeIndex pat 0
bscan _ _ [] = ([], [])
bscan !past !sta (!str:rest) = match sta 0
where
!strLen = S.length str
{-# INLINE strAt #-}
strAt :: Int -> Int
strAt i = fromIntegral (str `unsafeIndex` i)
match 0 idx
| idx == strLen =
let (fr, bk) = bscan [] 0 rest
in (foldr (flip (.) . (:)) id past (str:fr), bk)
| unsafeIndex str idx == p0 = match 1 (idx + 1)
| otherwise = match 0 (idx + 1)
match state idx
| idx == strLen =
let (kp, !rl) = if before
then keep state (str:past)
else ([], str:past)
(fr, bk) = bscan kp state rest
in (foldr (flip (.) . (:)) id rl fr, bk)
| otherwise =
let !nstate = unsafeAt auto ((state `shiftL` 8) + strAt idx)
!nxtIdx = idx + 1
in if nstate == patLen
then case if before then nxtIdx - patLen else nxtIdx of
0 -> (foldr (flip (.) . (:)) id past [], str:rest)
stIx | stIx < 0 -> rgo (-stIx) (str:rest) past
| stIx == strLen ->
(foldr (flip (.) . (:)) id past [str],rest)
| otherwise ->
(foldr (flip (.) . (:)) id past
[S.take stIx str], S.drop stIx str : rest)
else match nstate nxtIdx
-- Did I already mention that I suck at finding names?
{-# INLINE rgo #-}
rgo :: Int -> [S.ByteString] -> [S.ByteString]
-> ([S.ByteString], [S.ByteString])
rgo !kp acc (!str:more)
| sl == kp = (reverse more, str:acc)
| sl < kp = rgo (kp - sl) (str:acc) more
| otherwise = case S.splitAt (sl - kp) str of
(fr, bk) ->
(foldr (flip (.) . (:)) id more [fr], bk:acc)
where
!sl = S.length str
rgo _ _ [] = error "Not enough past!"
-- If that error is ever encountered, I screwed up badly.
|
seereason/stringsearch
|
Data/ByteString/Lazy/Search/DFA.hs
|
bsd-3-clause
| 18,013
| 0
| 23
| 5,963
| 3,539
| 1,873
| 1,666
| 236
| 11
|
import System.Process
import Data.Char
import Data.List
import Data.Maybe
main = getDepLibs "hets"
getDepLibs :: String -> IO ()
getDepLibs binOrLib = do
str <- readProcess "otool" ["-L", binOrLib] ""
let ls = map (takeWhile $ not . isSpace)
$ mapMaybe (stripPrefix lib . dropWhile isSpace) $ lines str
mapM_ (handleLibs binOrLib) ls
lib :: String
lib = "/opt/local/lib/"
handleLibs :: String -> String -> IO ()
handleLibs binOrLib s = do
rawSystem "cp" $ (lib ++ s) : ["."]
let name = "@executable_path/" ++ s
rawSystem "install_name_tool" ["-id", name, s]
rawSystem "install_name_tool" ["-change", lib ++ s, name, binOrLib]
putStrLn s
getDepLibs s
|
keithodulaigh/Hets
|
utils/macports/libs.hs
|
gpl-2.0
| 696
| 0
| 15
| 148
| 269
| 131
| 138
| 21
| 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="sk-SK">
<title>JSON View</title>
<maps>
<homeID>jsonview</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/jsonview/src/main/javahelp/help_sk_SK/helpset_sk_SK.hs
|
apache-2.0
| 959
| 82
| 52
| 156
| 390
| 206
| 184
| -1
| -1
|
module Main where
import MainIO
import System
main = do
[f1,f2] <- getArgs
mainIO f1 f2
|
forste/haReFork
|
StrategyLib-4.0-beta/examples/joos-rule02/testsuite/Main.hs
|
bsd-3-clause
| 109
| 0
| 8
| 37
| 36
| 20
| 16
| 6
| 1
|
module BSimple where
-- Test for refactor of if to case
foo x = if (odd x) then "Odd" else "Even"
|
RefactoringTools/HaRe
|
test/testdata/Case/BSimple.hs
|
bsd-3-clause
| 100
| 0
| 7
| 23
| 27
| 16
| 11
| 2
| 2
|
{-# LANGUAGE OverloadedStrings, CPP #-}
-- | Basic bindings to HTML5 WebStorage.
module Haste.LocalStorage (setItem, getItem, removeItem) where
import Haste
import Haste.Foreign
import Haste.Serialize
import Haste.JSON
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
-- | Locally store a serializable value.
setItem :: Serialize a => String -> a -> IO ()
setItem k = store k . encodeJSON . toJSON
store :: String -> JSString -> IO ()
store = ffi "(function(k,v) {localStorage.setItem(k,v);})"
-- | Load a serializable value from local storage. Will fail if the given key
-- does not exist or if the value stored at the key does not match the
-- requested type.
getItem :: Serialize a => String -> IO (Either String a)
getItem k = do
maybe (Left "No such value") (\s -> decodeJSON s >>= fromJSON) <$> load k
load :: String -> IO (Maybe JSString)
load = ffi "(function(k) {return localStorage.getItem(k);})"
-- | Remove a value from local storage.
removeItem :: String -> IO ()
removeItem = ffi "(function(k) {localStorage.removeItem(k);})"
|
beni55/haste-compiler
|
libraries/haste-lib/src/Haste/LocalStorage.hs
|
bsd-3-clause
| 1,066
| 0
| 12
| 179
| 238
| 126
| 112
| 18
| 1
|
module Foo () where
gloop = poop True
{-@ poop :: z:a -> {v: Maybe a | fromJust(v) = z} @-}
poop z = Just z
|
mightymoose/liquidhaskell
|
tests/pos/maybe00.hs
|
bsd-3-clause
| 112
| 0
| 5
| 30
| 27
| 15
| 12
| 3
| 1
|
{-# LANGUAGE FlexibleContexts, OverloadedStrings, TypeFamilies, Rank2Types, PatternGuards #-}
module Lamdu.Sugar.Convert
( convertDefI
) where
import Control.Applicative (Applicative(..), (<$>), (<$))
import Control.Lens (LensLike, Lens')
import Control.Lens.Operators
import Control.Monad (guard, void)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.State (StateT(..))
import Control.MonadA (MonadA)
import Data.Foldable (traverse_)
import Data.Map (Map)
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Monoid (Monoid(..))
import Data.Store.Guid (Guid)
import Data.Store.IRef (Tag)
import Data.Traversable (traverse)
import Data.Typeable (Typeable1)
import Lamdu.Data.Expression.IRef (DefIM)
import Lamdu.Data.Expression.Infer.Conflicts (InferredWithConflicts(..))
import Lamdu.Sugar.Convert.Monad (ConvertM, Context(..))
import Lamdu.Sugar.Internal
import Lamdu.Sugar.Types
import Lamdu.Sugar.Types.Internal
import System.Random (RandomGen)
import System.Random.Utils (genFromHashable)
import qualified Control.Lens as Lens
import qualified Data.List.Utils as ListUtils
import qualified Data.Map as Map
import qualified Data.Store.Guid as Guid
import qualified Data.Store.IRef as IRef
import qualified Data.Store.Property as Property
import qualified Data.Store.Transaction as Transaction
import qualified Lamdu.Data.Anchors as Anchors
import qualified Lamdu.Data.Definition as Definition
import qualified Lamdu.Data.Expression as Expr
import qualified Lamdu.Data.Expression.IRef as ExprIRef
import qualified Lamdu.Data.Expression.Infer as Infer
import qualified Lamdu.Data.Expression.Lens as ExprLens
import qualified Lamdu.Data.Expression.Load as Load
import qualified Lamdu.Data.Expression.Utils as ExprUtil
import qualified Lamdu.Data.Ops as DataOps
import qualified Lamdu.Sugar.Convert.Apply as ConvertApply
import qualified Lamdu.Sugar.Convert.Expression as ConvertExpr
import qualified Lamdu.Sugar.Convert.Hole as ConvertHole
import qualified Lamdu.Sugar.Convert.Infer as SugarInfer
import qualified Lamdu.Sugar.Convert.Monad as ConvertM
import qualified Lamdu.Sugar.InputExpr as InputExpr
import qualified Lamdu.Sugar.RemoveTypes as SugarRemoveTypes
onMatchingSubexprs ::
MonadA m => (a -> m ()) ->
(Expr.Expression def a -> Bool) ->
Expr.Expression def a -> m ()
onMatchingSubexprs action predicate =
traverse_ (action . (^. Expr.ePayload)) .
filter predicate . ExprUtil.subExpressions
toHole :: MonadA m => Stored m -> T m ()
toHole = void . DataOps.setToHole
isGetParamOf :: Guid -> Expr.Expression def a -> Bool
isGetParamOf = Lens.anyOf ExprLens.exprParameterRef . (==)
isGetFieldParam :: Guid -> Guid -> Expr.Expression def a -> Bool
isGetFieldParam param tagG =
p . (^? ExprLens.exprGetField)
where
p Nothing = False
p (Just (Expr.GetField record tag)) =
Lens.anyOf ExprLens.exprTag (== tagG) tag &&
Lens.anyOf ExprLens.exprParameterRef (== param) record
deleteParamRef ::
MonadA m => Guid -> Expr.Expression def (Stored m) -> T m ()
deleteParamRef =
onMatchingSubexprs toHole . isGetParamOf
deleteFieldParamRef ::
MonadA m => Guid -> Guid -> Expr.Expression def (Stored m) -> T m ()
deleteFieldParamRef param tagG =
onMatchingSubexprs toHole $ isGetFieldParam param tagG
lambdaWrap :: MonadA m => Stored m -> T m Guid
lambdaWrap stored =
f <$> DataOps.lambdaWrap stored
where
f (newParam, newLamI) = Guid.combine (ExprIRef.exprGuid newLamI) newParam
fakeExample :: Guid -> ExpressionP name0 m0 (Payload name1 m1 ())
fakeExample guid =
Expression (BodyAtom "NotImplemented") Payload
{ _plGuid = Guid.augment "EXAMPLE" guid
, _plInferredTypes = []
, _plActions = Nothing
, _plData = ()
}
mkPositionalFuncParamActions ::
MonadA m => Guid -> Stored m -> Expr.Expression def (Stored m) ->
FuncParamActions MStoredName m
mkPositionalFuncParamActions param lambdaProp body =
FuncParamActions
{ _fpListItemActions =
ListItemActions
{ _itemDelete = do
deleteParamRef param body
SugarInfer.replaceWith lambdaProp $ body ^. Expr.ePayload
, _itemAddNext = lambdaWrap $ body ^. Expr.ePayload
}
, _fpGetExample = pure $ fakeExample param
}
getStoredNameS :: MonadA m => Guid -> ConvertM m (Maybe String)
getStoredNameS = ConvertM.liftTransaction . ConvertExpr.getStoredName
addFuncParamName ::
MonadA m => FuncParam MStoredName f expr ->
ConvertM m (FuncParam MStoredName f expr)
addFuncParamName fp = do
name <- getStoredNameS $ fp ^. fpGuid
pure fp { _fpName = name }
getInferredVal :: InputExpr m a -> ExprIRef.ExpressionM m ()
getInferredVal x =
x ^. Expr.ePayload . ipInferred
<&> void . Infer.iValue . iwcInferred
& fromMaybe ExprUtil.pureHole
convertPositionalFuncParam ::
(Typeable1 m, MonadA m, Monoid a) => Expr.Lam (InputExpr m a) ->
InputPayload m a ->
ConvertM m (FuncParam MStoredName m (ExpressionU m a))
convertPositionalFuncParam (Expr.Lam _k paramGuid paramType body) lamExprPl = do
paramTypeS <- ConvertM.convertSubexpression paramType
addFuncParamName FuncParam
{ _fpName = Nothing
, _fpGuid = paramGuid
, _fpVarKind = FuncParameter
, _fpId = Guid.combine lamGuid paramGuid
, _fpAltIds = [paramGuid] -- For easy jumpTo
, _fpType = SugarRemoveTypes.successfulType paramTypeS
, _fpInferredType = getInferredVal paramType
, _fpMActions =
mkPositionalFuncParamActions paramGuid
<$> lamExprPl ^. ipStored
<*> traverse (^. ipStored) body
}
where
lamGuid = lamExprPl ^. ipGuid
convertLam ::
(MonadA m, Typeable1 m, Monoid a) =>
Expr.Lam (InputExpr m a) ->
InputPayload m a -> ConvertM m (ExpressionU m a)
convertLam lam@(Expr.Lam k paramGuid _paramType result) exprPl = do
param <- convertPositionalFuncParam lam exprPl
resultS <- ConvertM.convertSubexpression result
BodyLam
Lam
{ _lParam =
param
& fpMActions .~ Nothing
, _lResultType = resultS
, _lKind = k
, _lIsDep = isDep
}
& ConvertExpr.make exprPl
<&> rPayload . plActions . Lens._Just . mSetToInnerExpr .~ do
guard $ Lens.nullOf ExprLens.exprHole result
bodyStored <- traverse (^. ipStored) result
stored <- exprPl ^. ipStored
return $ do
deleteParamRef paramGuid bodyStored
ExprIRef.exprGuid <$>
DataOps.setToWrapper (Property.value (bodyStored ^. Expr.ePayload)) stored
where
isDep =
case k of
KVal -> SugarInfer.isPolymorphicFunc exprPl
KType -> ExprUtil.exprHasGetVar paramGuid result
convertParameterRef ::
(MonadA m, Typeable1 m) => Guid ->
InputPayload m a -> ConvertM m (ExpressionU m a)
convertParameterRef parGuid exprPl = do
recordParamsMap <- (^. ConvertM.scRecordParamsInfos) <$> ConvertM.readContext
case Map.lookup parGuid recordParamsMap of
Just (ConvertM.RecordParamsInfo defGuid jumpTo) -> do
defName <- getStoredNameS defGuid
ConvertExpr.make exprPl $ BodyGetParams GetParams
{ _gpDefGuid = defGuid
, _gpDefName = defName
, _gpJumpTo = jumpTo
}
Nothing -> do
parName <- getStoredNameS parGuid
ConvertExpr.make exprPl .
BodyGetVar $ GetVar
{ _gvName = parName
, _gvIdentifier = parGuid
, _gvJumpTo = pure parGuid
, _gvVarType = GetParameter
}
jumpToDefI ::
MonadA m => Anchors.CodeProps m -> DefIM m -> T m Guid
jumpToDefI cp defI = IRef.guid defI <$ DataOps.newPane cp defI
convertGetVariable ::
(MonadA m, Typeable1 m) =>
Expr.VariableRef (DefIM m) ->
InputPayload m a -> ConvertM m (ExpressionU m a)
convertGetVariable varRef exprPl = do
cp <- (^. ConvertM.scCodeAnchors) <$> ConvertM.readContext
case varRef of
Expr.ParameterRef parGuid -> convertParameterRef parGuid exprPl
Expr.DefinitionRef defI -> do
let defGuid = IRef.guid defI
defName <- getStoredNameS defGuid
ConvertExpr.make exprPl .
BodyGetVar $ GetVar
{ _gvName = defName
, _gvIdentifier = defGuid
, _gvJumpTo = jumpToDefI cp defI
, _gvVarType = GetDefinition
}
convertLiteralInteger ::
(MonadA m, Typeable1 m) => Integer ->
InputPayload m a -> ConvertM m (ExpressionU m a)
convertLiteralInteger i exprPl = ConvertExpr.make exprPl $ BodyLiteralInteger i
convertTag ::
(MonadA m, Typeable1 m) => Guid ->
InputPayload m a -> ConvertM m (ExpressionU m a)
convertTag tag exprPl = do
name <- getStoredNameS tag
ConvertExpr.make exprPl . BodyTag $ TagG tag name
convertAtom ::
(MonadA m, Typeable1 m) => String ->
InputPayload m a -> ConvertM m (ExpressionU m a)
convertAtom str exprPl =
ConvertExpr.make exprPl $ BodyAtom str
sideChannel ::
Monad m =>
Lens' s a ->
LensLike m s (side, s) a (side, a)
sideChannel lens f s = (`runStateT` s) . Lens.zoom lens $ StateT f
writeRecordFields ::
MonadA m =>
ExprIRef.ExpressionIM m -> result ->
( [(ExprIRef.ExpressionIM m, ExprIRef.ExpressionIM m)] ->
T m
( result
, [(ExprIRef.ExpressionIM m, ExprIRef.ExpressionIM m)]
)
) ->
T m result
writeRecordFields iref def f = do
oldBody <- ExprIRef.readExprBody iref
case oldBody ^? Expr._BodyRecord of
Nothing -> return def
Just oldRecord -> do
(res, newRecord) <-
sideChannel Expr.recordFields f oldRecord
ExprIRef.writeExprBody iref $ Expr.BodyRecord newRecord
return res
recordFieldActions ::
MonadA m => Guid -> ExprIRef.ExpressionIM m -> ExprIRef.ExpressionIM m ->
ListItemActions m
recordFieldActions defaultGuid exprIRef iref =
ListItemActions
{ _itemDelete = action delete
, _itemAddNext = action addNext
}
where
action f = writeRecordFields iref defaultGuid $ splitFields f
addNext (prevFields, field, nextFields) = do
tagHole <- DataOps.newHole
exprHole <- DataOps.newHole
return
( ExprIRef.exprGuid tagHole
, prevFields ++ field : (tagHole, exprHole) : nextFields
)
delete (prevFields, _, nextFields) =
return
( case nextFields ++ reverse prevFields of
[] -> defaultGuid
((nextTagExpr, _) : _) -> ExprIRef.exprGuid nextTagExpr
, prevFields ++ nextFields
)
splitFields f oldFields =
case break ((== exprIRef) . fst) oldFields of
(prevFields, field : nextFields) -> f (prevFields, field, nextFields)
_ -> return (defaultGuid, oldFields)
convertField ::
(Typeable1 m, MonadA m, Monoid a) =>
Maybe (ExprIRef.ExpressionIM m) -> Guid ->
( InputExpr m a
, InputExpr m a
) ->
ConvertM m (RecordField m (ExpressionU m a))
convertField mIRef defaultGuid (tagExpr, expr) = do
tagExprS <- ConvertM.convertSubexpression tagExpr
exprS <- ConvertM.convertSubexpression expr
return RecordField
{ _rfMItemActions =
recordFieldActions defaultGuid <$> tagExpr ^? SugarInfer.exprIRef <*> mIRef
, _rfTag = tagExprS
, _rfExpr = exprS
}
convertRecord ::
(Typeable1 m, MonadA m, Monoid a) =>
Expr.Record (InputExpr m a) ->
InputPayload m a -> ConvertM m (ExpressionU m a)
convertRecord (Expr.Record k fields) exprPl = do
sFields <- mapM (convertField (exprPl ^? SugarInfer.plIRef) defaultGuid) fields
ConvertExpr.make exprPl $ BodyRecord
Record
{ _rKind = k
, _rFields =
FieldList
{ _flItems =
sFields
<&> rfTag . rPayload .
plActions . Lens._Just . wrap .~ WrapNotAllowed -- Tag cannot be wrapped
, _flMAddFirstItem = addField <$> exprPl ^? SugarInfer.plIRef
}
}
where
defaultGuid = exprPl ^. ipGuid
addField iref =
writeRecordFields iref defaultGuid $ \recordFields -> do
holeTagExpr <- DataOps.newHole
holeExpr <- DataOps.newHole
return
( ExprIRef.exprGuid holeTagExpr
, (holeTagExpr, holeExpr) : recordFields
)
convertGetField ::
(MonadA m, Typeable1 m, Monoid a) =>
Expr.GetField (InputExpr m a) ->
InputPayload m a ->
ConvertM m (ExpressionU m a)
convertGetField (Expr.GetField recExpr tagExpr) exprPl = do
tagParamInfos <- (^. ConvertM.scTagParamInfos) <$> ConvertM.readContext
let
mkGetVar (tag, jumpTo) = do
name <- getStoredNameS tag
pure GetVar
{ _gvName = name
, _gvIdentifier = tag
, _gvJumpTo = pure jumpTo
, _gvVarType = GetFieldParameter
}
mVar <- traverse mkGetVar $ do
tag <- tagExpr ^? ExprLens.exprTag
paramInfo <- Map.lookup tag tagParamInfos
param <- recExpr ^? ExprLens.exprParameterRef
guard $ param == ConvertM.tpiFromParameters paramInfo
return (tag, ConvertM.tpiJumpTo paramInfo)
ConvertExpr.make exprPl =<<
case mVar of
Just var ->
return $ BodyGetVar var
Nothing ->
traverse ConvertM.convertSubexpression
GetField
{ _gfRecord = recExpr
, _gfTag = tagExpr
}
<&> gfTag . rPayload . plActions . Lens._Just . wrap .~ WrapNotAllowed -- Tag cannot be wrapped
<&> BodyGetField
removeRedundantSubExprTypes :: Expression n m a -> Expression n m a
removeRedundantSubExprTypes =
rBody %~
( Lens.traversed %~ removeRedundantTypes
& Lens.outside _BodyHole .~
BodyHole . (Lens.traversed %~ removeRedundantSubExprTypes)
) .
(_BodyApply . aFunc %~ remSuc) .
(_BodyGetField . gfRecord %~ remSuc) .
(_BodyLam . lResultType %~ remSuc) .
(_BodyRecord %~
(fields . rfTag %~ remSuc) .
(Lens.filtered ((== KType) . (^. rKind)) . fields . rfExpr %~ remSuc)
)
where
fields = rFields . flItems . Lens.traversed
remSuc =
Lens.filtered (Lens.nullOf (rBody . _BodyHole)) %~
SugarRemoveTypes.successfulType
removeRedundantTypes :: Expression name m a -> Expression name m a
removeRedundantTypes =
removeRedundantSubExprTypes .
(Lens.filtered cond %~ SugarRemoveTypes.successfulType)
where
cond e =
Lens.anyOf (rBody . _BodyGetVar) ((/= GetDefinition) . (^. gvVarType)) e ||
Lens.has (rBody . _BodyRecord) e
convertExpressionI ::
(Typeable1 m, MonadA m, Monoid a) =>
InputExpr m a -> ConvertM m (ExpressionU m a)
convertExpressionI ee =
($ ee ^. Expr.ePayload) $
case ee ^. Expr.eBody of
Expr.BodyLam x -> convertLam x
Expr.BodyApply x -> ConvertApply.convert x
Expr.BodyRecord x -> convertRecord x
Expr.BodyGetField x -> convertGetField x
Expr.BodyLeaf (Expr.GetVariable x) -> convertGetVariable x
Expr.BodyLeaf (Expr.LiteralInteger x) -> convertLiteralInteger x
Expr.BodyLeaf (Expr.Tag x) -> convertTag x
Expr.BodyLeaf Expr.Hole -> ConvertHole.convert
Expr.BodyLeaf Expr.Type -> convertAtom "Type"
Expr.BodyLeaf Expr.IntegerType -> convertAtom "Int"
Expr.BodyLeaf Expr.TagType -> convertAtom "Tag"
-- Check no holes
isCompleteType :: Expr.Expression def a -> Bool
isCompleteType =
Lens.nullOf (Lens.folding ExprUtil.subExpressions . ExprLens.exprHole)
mkContext ::
(MonadA m, Typeable1 m) =>
Anchors.Code (Transaction.MkProperty m) (Tag m) ->
InferContext m -> InferContext m -> InferContext m ->
T m (Context m)
mkContext cp holeInferContext structureInferContext withVarsInferContext = do
specialFunctions <- Transaction.getP $ Anchors.specialFunctions cp
return Context
{ _scHoleInferContext = holeInferContext
, _scStructureInferContext = structureInferContext
, _scWithVarsInferContext = withVarsInferContext
, _scCodeAnchors = cp
, _scSpecialFunctions = specialFunctions
, _scTagParamInfos = mempty
, _scRecordParamsInfos = mempty
, scConvertSubexpression = convertExpressionI
}
convertExpressionPure ::
(MonadA m, Typeable1 m, RandomGen g, Monoid a) =>
Anchors.CodeProps m -> g ->
ExprIRef.ExpressionM m a -> CT m (ExpressionU m a)
convertExpressionPure cp gen res = do
context <-
lift $ mkContext cp
(err "holeInferContext")
(err "structureInferContext")
(err "withVarsInferContext")
fmap removeRedundantTypes .
ConvertM.run context .
ConvertM.convertSubexpression $
InputExpr.makePure gen res
where
err x = error $ "convertExpressionPure: " ++ x
data ConventionalParams m a = ConventionalParams
{ cpTags :: [Guid]
, cpParamInfos :: Map Guid ConvertM.TagParamInfo
, cpRecordParamsInfos :: Map Guid (ConvertM.RecordParamsInfo m)
, cpParams :: [FuncParam MStoredName m (ExpressionU m a)]
, cpAddFirstParam :: T m Guid
, cpHiddenPayloads :: [InputPayload m a]
}
data FieldParam m a = FieldParam
{ fpTagGuid :: Guid
, fpTagExpr :: InputExpr m a
, fpFieldType :: InputExpr m a
}
mkRecordParams ::
(MonadA m, Typeable1 m, Monoid a) =>
ConvertM.RecordParamsInfo m -> Guid -> [FieldParam m a] ->
InputExpr m a ->
Maybe (ExprIRef.ExpressionIM m) ->
Maybe (ExprIRef.ExpressionM m (Stored m)) ->
ConvertM m (ConventionalParams m a)
mkRecordParams recordParamsInfo paramGuid fieldParams lambdaExprI mParamTypeI mBodyStored = do
params <- traverse mkParam fieldParams
pure ConventionalParams
{ cpTags = fpTagGuid <$> fieldParams
, cpParamInfos = mconcat $ mkParamInfo <$> fieldParams
, cpRecordParamsInfos = Map.singleton paramGuid recordParamsInfo
, cpParams = params
, cpAddFirstParam =
addFirstFieldParam lamGuid $
fromMaybe (error "Record param type must be stored!") mParamTypeI
, cpHiddenPayloads = [lambdaExprI ^. Expr.ePayload]
}
where
lamGuid = lambdaExprI ^. SugarInfer.exprGuid
mLambdaP = lambdaExprI ^. Expr.ePayload . ipStored
mkParamInfo fp =
Map.singleton (fpTagGuid fp) . ConvertM.TagParamInfo paramGuid .
Guid.combine lamGuid $ fpTagGuid fp
mkParam fp = do
typeS <- ConvertM.convertSubexpression $ fpFieldType fp
let
guid = fpTagGuid fp
tagExprGuid = fpTagExpr fp ^. Expr.ePayload . ipGuid
addFuncParamName FuncParam
{ _fpName = Nothing
, _fpGuid = guid
, _fpId = Guid.combine lamGuid guid
, _fpAltIds = [tagExprGuid]
, _fpVarKind = FuncFieldParameter
, _fpType = SugarRemoveTypes.successfulType typeS
, _fpInferredType = getInferredVal $ fpFieldType fp
, _fpMActions =
fpActions tagExprGuid
<$> mLambdaP <*> mParamTypeI <*> mBodyStored
}
fpActions tagExprGuid lambdaP paramTypeI bodyStored =
FuncParamActions
{ _fpListItemActions = ListItemActions
{ _itemAddNext = addFieldParamAfter lamGuid tagExprGuid paramTypeI
, _itemDelete =
delFieldParam tagExprGuid paramTypeI paramGuid lambdaP bodyStored
}
, _fpGetExample = pure $ fakeExample tagExprGuid
}
type ExprField m = (ExprIRef.ExpressionIM m, ExprIRef.ExpressionIM m)
rereadFieldParamTypes ::
MonadA m =>
Guid -> ExprIRef.ExpressionIM m ->
([ExprField m] -> ExprField m -> [ExprField m] -> T m Guid) ->
T m Guid
rereadFieldParamTypes tagExprGuid paramTypeI f = do
paramType <- ExprIRef.readExprBody paramTypeI
let
mBrokenFields =
paramType ^? Expr._BodyRecord . ExprLens.kindedRecordFields KType .
(Lens.to . break) ((tagExprGuid ==) . ExprIRef.exprGuid . fst)
case mBrokenFields of
Just (prevFields, theField : nextFields) -> f prevFields theField nextFields
_ -> return tagExprGuid
rewriteFieldParamTypes ::
MonadA m => ExprIRef.ExpressionIM m -> [ExprField m] -> T m ()
rewriteFieldParamTypes paramTypeI fields =
ExprIRef.writeExprBody paramTypeI . Expr.BodyRecord $
Expr.Record KType fields
addFieldParamAfter :: MonadA m => Guid -> Guid -> ExprIRef.ExpressionIM m -> T m Guid
addFieldParamAfter lamGuid tagExprGuid paramTypeI =
rereadFieldParamTypes tagExprGuid paramTypeI $
\prevFields theField nextFields -> do
fieldGuid <- Transaction.newKey
tagExprI <- ExprIRef.newExprBody $ ExprLens.bodyTag # fieldGuid
holeTypeI <- DataOps.newHole
rewriteFieldParamTypes paramTypeI $
prevFields ++ theField : (tagExprI, holeTypeI) : nextFields
pure $ Guid.combine lamGuid fieldGuid
delFieldParam ::
MonadA m => Guid -> ExprIRef.ExpressionIM m -> Guid ->
Stored m -> ExprIRef.ExpressionM m (Stored m) -> T m Guid
delFieldParam tagExprGuid paramTypeI paramGuid lambdaP bodyStored =
rereadFieldParamTypes tagExprGuid paramTypeI $
\prevFields (tagExprI, _) nextFields -> do
tagExpr <- ExprIRef.readExprBody tagExprI
case tagExpr ^? ExprLens.bodyTag of
Just tagG -> deleteFieldParamRef paramGuid tagG bodyStored
Nothing -> return ()
case prevFields ++ nextFields of
[] -> error "We were given fewer than 2 field params, which should never happen"
[(fieldTagI, fieldTypeI)] -> do
fieldTag <- ExprIRef.readExprBody fieldTagI
let
fieldTagGuid =
fromMaybe (error "field params always have proper Tag expr") $
fieldTag ^? ExprLens.bodyTag
ExprIRef.writeExprBody (Property.value lambdaP) $
ExprUtil.makeLambda fieldTagGuid fieldTypeI bodyI
deleteParamRef paramGuid bodyStored
let
toGetParam iref =
ExprIRef.writeExprBody iref $
ExprLens.bodyParameterRef # fieldTagGuid
onMatchingSubexprs (toGetParam . Property.value)
(isGetFieldParam paramGuid fieldTagGuid) bodyStored
pure $ Guid.combine lamGuid fieldTagGuid
newFields -> do
rewriteFieldParamTypes paramTypeI newFields
dest prevFields nextFields
where
lamGuid = ExprIRef.exprGuid $ Property.value lambdaP
bodyI = bodyStored ^. Expr.ePayload . Property.pVal
dest prevFields nextFields =
fromMaybe (ExprIRef.exprGuid bodyI) . listToMaybe <$>
traverse (getParamGuidFromTagExprI . fst)
(nextFields ++ reverse prevFields)
getParamGuidFromTagExprI tagExprI = do
tagExpr <- ExprIRef.readExprBody tagExprI
pure . Guid.combine lamGuid .
fromMaybe (error "field param must have tags") $
tagExpr ^? ExprLens.bodyTag
-- | Convert a (potentially stored) param type hole with inferred val
-- to the unstored inferred val
paramTypeExprMM ::
Monoid a => InputExpr m a -> InputExpr m a
paramTypeExprMM origParamType
| Lens.has ExprLens.exprHole origParamType
, Just inferredParamType <- origParamType ^. SugarInfer.exprInferred
= paramTypeOfInferredVal . Infer.iValue $ iwcInferred inferredParamType
| otherwise = origParamType
where
paramTypeGen = genFromHashable $ origParamType ^. SugarInfer.exprGuid
paramTypeOfInferredVal iVal =
iVal
& Lens.mapped .~ mempty
-- Copy the paramType payload to top-level of inferred val so it
-- isn't lost:
& Expr.ePayload .~ origParamType ^. SugarInfer.exprData
& InputExpr.makePure paramTypeGen
convertDefinitionParams ::
(MonadA m, Typeable1 m, Monoid a) =>
ConvertM.RecordParamsInfo m -> [Guid] -> InputExpr m a ->
ConvertM m
( [FuncParam MStoredName m (ExpressionU m a)]
, ConventionalParams m a
, InputExpr m a
)
convertDefinitionParams recordParamsInfo usedTags expr =
case expr ^. Expr.eBody of
Expr.BodyLam lambda@(Expr.Lam KVal paramGuid origParamType body) -> do
param <-
convertPositionalFuncParam lambda (expr ^. Expr.ePayload)
-- Slightly strange but we mappend the hidden lambda's
-- annotation into the param type:
<&> fpType . rPayload . plData <>~ expr ^. SugarInfer.exprData
let paramType = paramTypeExprMM origParamType
if SugarInfer.isPolymorphicFunc $ expr ^. Expr.ePayload
then do -- Dependent:
(depParams, convParams, deepBody) <- convertDefinitionParams recordParamsInfo usedTags body
return (param : depParams, convParams, deepBody)
else -- Independent:
case paramType ^. Expr.eBody of
Expr.BodyRecord (Expr.Record KType fields)
| ListUtils.isLengthAtLeast 2 fields
, Just fieldParams <- traverse makeFieldParam fields
, all ((`notElem` usedTags) . fpTagGuid) fieldParams -> do
convParams <-
mkRecordParams recordParamsInfo paramGuid fieldParams
expr (origParamType ^? SugarInfer.exprIRef)
(traverse (^. ipStored) body)
return ([], convParams, body)
_ ->
pure
( []
, singleConventionalParam stored param paramGuid origParamType body
, body
)
_ -> return ([], emptyConventionalParams stored, expr)
where
stored =
fromMaybe (error "Definition body is always stored!") $
expr ^. SugarInfer.exprStored
makeFieldParam (tagExpr, typeExpr) = do
fieldTagGuid <- tagExpr ^? ExprLens.exprTag
pure FieldParam
{ fpTagGuid = fieldTagGuid
, fpTagExpr = tagExpr
, fpFieldType = typeExpr
}
singleConventionalParam ::
MonadA m =>
Stored m -> FuncParam MStoredName m (ExpressionU m a) ->
Guid -> InputExpr m a -> InputExpr m a -> ConventionalParams m a
singleConventionalParam lamProp existingParam existingParamGuid existingParamType body =
ConventionalParams
{ cpTags = []
, cpParamInfos = Map.empty
, cpRecordParamsInfos = Map.empty
, cpParams =
[ existingParam & fpMActions . Lens._Just . fpListItemActions . itemAddNext .~
addSecondParam (\old new -> [old, new])
]
, cpAddFirstParam = addSecondParam (\old new -> [new, old])
, cpHiddenPayloads = []
}
where
existingParamTag = ExprLens.bodyTag # existingParamGuid
existingParamTypeIRef =
fromMaybe (error "Only stored record param type is converted as record") $
existingParamType ^? SugarInfer.exprIRef
bodyWithStored =
fromMaybe (error "Definition body should be stored") $
traverse (^. ipStored) body
addSecondParam mkFields = do
existingParamTagI <- ExprIRef.newExprBody existingParamTag
let existingParamField = (existingParamTagI, existingParamTypeIRef)
(newTagGuid, newParamField) <- newField
newParamTypeI <-
ExprIRef.newExprBody . Expr.BodyRecord . Expr.Record KType $
mkFields existingParamField newParamField
newParamsGuid <- Transaction.newKey
ExprIRef.writeExprBody (Property.value lamProp) $
ExprUtil.makeLambda newParamsGuid newParamTypeI .
Property.value $ bodyWithStored ^. Expr.ePayload
let
toGetField iref = do
recordRef <- ExprIRef.newExprBody $ ExprLens.bodyParameterRef # newParamsGuid
tagRef <- ExprIRef.newExprBody existingParamTag
ExprIRef.writeExprBody iref $
Expr.BodyGetField Expr.GetField
{ Expr._getFieldRecord = recordRef
, Expr._getFieldTag = tagRef
}
onMatchingSubexprs (toGetField . Property.value)
(isGetParamOf existingParamGuid) bodyWithStored
let lamGuid = ExprIRef.exprGuid $ Property.value lamProp
pure $ Guid.combine lamGuid newTagGuid
emptyConventionalParams :: MonadA m => ExprIRef.ExpressionProperty m -> ConventionalParams m a
emptyConventionalParams stored = ConventionalParams
{ cpTags = []
, cpParamInfos = Map.empty
, cpRecordParamsInfos = Map.empty
, cpParams = []
, cpAddFirstParam = lambdaWrap stored
, cpHiddenPayloads = []
}
data ExprWhereItem m a = ExprWhereItem
{ ewiBody :: ExprIRef.ExpressionM m a
, ewiParamGuid :: Guid
, ewiArg :: ExprIRef.ExpressionM m a
, ewiHiddenPayloads :: [a]
, ewiInferredType :: ExprIRef.ExpressionM m ()
}
mExtractWhere :: InputExpr m a -> Maybe (ExprWhereItem m (InputPayload m a))
mExtractWhere expr = do
Expr.Apply func arg <- expr ^? ExprLens.exprApply
(paramGuid, paramType, body) <- func ^? ExprLens.exprKindedLam KVal
-- paramType has to be Hole for this to be sugarred to Where
paramType ^? ExprLens.exprHole
Just ExprWhereItem
{ ewiBody = body
, ewiParamGuid = paramGuid
, ewiArg = arg
, ewiHiddenPayloads = (^. Expr.ePayload) <$> [expr, func, paramType]
, ewiInferredType = getInferredVal paramType
}
convertWhereItems ::
(MonadA m, Typeable1 m, Monoid a) =>
[Guid] ->
InputExpr m a ->
ConvertM m ([WhereItem MStoredName m (ExpressionU m a)], InputExpr m a)
convertWhereItems usedTags expr =
case mExtractWhere expr of
Nothing -> return ([], expr)
Just ewi -> do
let
defGuid = ewiParamGuid ewi
recordParamsInfo =
ConvertM.RecordParamsInfo defGuid $ pure defGuid
value <-
convertDefinitionContent recordParamsInfo usedTags $
ewiArg ewi
let
mkWIActions topLevelProp bodyStored =
ListItemActions
{ _itemDelete = do
deleteParamRef defGuid bodyStored
SugarInfer.replaceWith topLevelProp $ bodyStored ^. Expr.ePayload
, _itemAddNext = fmap fst $ DataOps.redexWrap topLevelProp
}
name <- getStoredNameS defGuid
let
hiddenData = ewiHiddenPayloads ewi ^. Lens.traversed . ipData
item = WhereItem
{ _wiValue =
value
& dBody . rPayload . plData <>~ hiddenData
, _wiGuid = defGuid
, _wiActions =
mkWIActions <$>
expr ^. SugarInfer.exprStored <*>
traverse (^. ipStored) (ewiBody ewi)
, _wiName = name
, _wiInferredType = ewiInferredType ewi
}
(nextItems, whereBody) <- convertWhereItems usedTags $ ewiBody ewi
return (item : nextItems, whereBody)
newField ::
MonadA m => T m (Guid, (ExprIRef.ExpressionIM m, ExprIRef.ExpressionIM m))
newField = do
tag <- Transaction.newKey
newTagI <- ExprIRef.newExprBody (ExprLens.bodyTag # tag)
holeI <- DataOps.newHole
return (tag, (newTagI, holeI))
addFirstFieldParam :: MonadA m => Guid -> ExprIRef.ExpressionIM m -> T m Guid
addFirstFieldParam lamGuid recordI = do
recordBody <- ExprIRef.readExprBody recordI
case recordBody ^? Expr._BodyRecord . ExprLens.kindedRecordFields KType of
Just fields -> do
(newTagGuid, field) <- newField
ExprIRef.writeExprBody recordI $
Expr.BodyRecord . Expr.Record KType $ field : fields
pure $ Guid.combine lamGuid newTagGuid
_ -> pure $ ExprIRef.exprGuid recordI
assertedGetProp ::
String ->
Expr.Expression def (InputPayloadP inferred (Maybe stored) a) -> stored
assertedGetProp _
Expr.Expression
{ Expr._ePayload =
InputPayload { _ipStored = Just prop } } = prop
assertedGetProp msg _ = error msg
convertDefinitionContent ::
(MonadA m, Typeable1 m, Monoid a) =>
ConvertM.RecordParamsInfo m -> [Guid] -> InputExpr m a ->
ConvertM m (DefinitionContent MStoredName m (ExpressionU m a))
convertDefinitionContent recordParamsInfo usedTags expr = do
(depParams, convParams, funcBody) <-
convertDefinitionParams recordParamsInfo usedTags expr
ConvertM.local
((ConvertM.scTagParamInfos <>~ cpParamInfos convParams) .
(ConvertM.scRecordParamsInfos <>~ cpRecordParamsInfos convParams)) $ do
(whereItems, whereBody) <-
convertWhereItems (usedTags ++ cpTags convParams) funcBody
bodyS <- ConvertM.convertSubexpression whereBody
return DefinitionContent
{ _dDepParams = depParams
, _dParams = cpParams convParams
, _dBody =
bodyS
& rPayload . plData <>~
cpHiddenPayloads convParams ^. Lens.traversed . ipData
, _dWhereItems = whereItems
, _dAddFirstParam = cpAddFirstParam convParams
, _dAddInnermostWhereItem =
fmap fst . DataOps.redexWrap $
assertedGetProp "Where must be stored" whereBody
}
convertDefIBuiltin ::
(Typeable1 m, MonadA m) => Anchors.CodeProps m ->
Definition.Builtin -> DefIM m ->
ExprIRef.ExpressionM m (Stored m) ->
CT m (DefinitionBody MStoredName m (ExpressionU m [Guid]))
convertDefIBuiltin cp (Definition.Builtin name) defI defType =
DefinitionBodyBuiltin <$> do
defTypeS <-
convertExpressionPure cp iDefTypeGen (void defType)
<&> Lens.mapped . Lens.mapped .~ mempty
pure DefinitionBuiltin
{ biName = name
, biMSetName = Just setName
, biType = defTypeS
}
where
defGuid = IRef.guid defI
iDefTypeGen = ConvertExpr.mkGen 1 3 defGuid
typeIRef = Property.value (defType ^. Expr.ePayload)
setName =
Transaction.writeIRef defI .
(`Definition.Body` typeIRef) .
Definition.ContentBuiltin . Definition.Builtin
makeTypeInfo ::
(Typeable1 m, MonadA m, Monoid a) =>
Anchors.CodeProps m -> DefIM m ->
ExprIRef.ExpressionM m (Stored m, a) ->
ExprIRef.ExpressionM m a -> Bool ->
CT m (DefinitionTypeInfo m (ExpressionU m a))
makeTypeInfo cp defI defType inferredType success = do
defTypeS <- conv iDefTypeGen $ snd <$> defType
case () of
()
| not success || not (isCompleteType inferredType) ->
DefinitionIncompleteType <$> do
inferredTypeS <- conv iNewTypeGen inferredType
pure ShowIncompleteType
{ sitOldType = defTypeS
, sitNewIncompleteType = inferredTypeS
}
| typesMatch -> pure $ DefinitionExportedTypeInfo defTypeS
| otherwise ->
DefinitionNewType <$> do
inferredTypeS <- conv iNewTypeGen inferredType
pure AcceptNewType
{ antOldType = defTypeS
, antNewType = inferredTypeS
, antAccept =
Property.set (defType ^. Expr.ePayload . Lens._1) =<<
ExprIRef.newExpression (void inferredType)
}
where
conv = convertExpressionPure cp
iDefTypeGen = ConvertExpr.mkGen 1 3 defGuid
iNewTypeGen = ConvertExpr.mkGen 2 3 defGuid
typesMatch = (snd <$> defType) `ExprUtil.alphaEq` inferredType
defGuid = IRef.guid defI
convertDefIExpression ::
(MonadA m, Typeable1 m) => Anchors.CodeProps m ->
ExprIRef.ExpressionM m (Load.ExprPropertyClosure (Tag m)) ->
DefIM m ->
ExprIRef.ExpressionM m (Stored m) ->
CT m (DefinitionBody MStoredName m (ExpressionU m [Guid]))
convertDefIExpression cp exprLoaded defI defType = do
ilr@SugarInfer.InferredWithImplicits
{ SugarInfer._iwiExpr = iwiExpr
, SugarInfer._iwiSuccess = success
} <-
SugarInfer.inferAddImplicits inferLoadedGen (Just defI)
exprLoaded initialContext rootNode
let
inferredType =
void . Infer.iType . iwcInferred $ iwiExpr ^. SugarInfer.exprInferred
addStoredGuids lens x = (x, ExprIRef.exprGuid . Property.value <$> x ^.. lens)
guidIntoPl (pl, x) = pl & ipData %~ \() -> x
typeInfo <-
makeTypeInfo cp defI (addStoredGuids id <$> defType) (mempty <$ inferredType) success
context <-
lift $ mkContext cp
(ilr ^. SugarInfer.iwiBaseInferContext)
(ilr ^. SugarInfer.iwiStructureInferContext)
(ilr ^. SugarInfer.iwiInferContext)
ConvertM.run context $ do
content <-
iwiExpr
<&> guidIntoPl . addStoredGuids (ipStored . Lens._Just)
& traverse . ipInferred %~ Just
& convertDefinitionContent recordParamsInfo []
return $ DefinitionBodyExpression DefinitionExpression
{ _deContent = removeRedundantTypes <$> content
, _deTypeInfo = typeInfo
}
where
(initialContext, rootNode) = initialInferContext $ Just defI
defGuid = IRef.guid defI
recordParamsInfo = ConvertM.RecordParamsInfo defGuid $ jumpToDefI cp defI
inferLoadedGen = ConvertExpr.mkGen 0 3 defGuid
convertDefI ::
(MonadA m, Typeable1 m) =>
Anchors.CodeProps m ->
-- TODO: Use DefinitionClosure?
Definition.Definition
(ExprIRef.ExpressionM m (Load.ExprPropertyClosure (Tag m)))
(ExprIRef.DefIM m) ->
CT m (Definition (Maybe String) m (ExpressionU m [Guid]))
convertDefI cp (Definition.Definition (Definition.Body bodyContent typeLoaded) defI) = do
bodyS <- convertDefContent bodyContent $ Load.exprPropertyOfClosure <$> typeLoaded
name <- lift $ ConvertExpr.getStoredName defGuid
return Definition
{ _drGuid = defGuid
, _drName = name
, _drBody = bodyS
}
where
defGuid = IRef.guid defI
convertDefContent (Definition.ContentBuiltin builtin) =
convertDefIBuiltin cp builtin defI
convertDefContent (Definition.ContentExpression exprLoaded) =
convertDefIExpression cp exprLoaded defI
|
aleksj/lamdu
|
Lamdu/Sugar/Convert.hs
|
gpl-3.0
| 35,949
| 0
| 22
| 7,934
| 10,423
| 5,320
| 5,103
| -1
| -1
|
-- | Extra Maybe utilities.
module Data.Maybe.Extra where
import Control.Applicative
import Control.Monad
import Data.Traversable hiding (mapM)
import Data.Maybe
import Prelude -- Silence redundant import warnings
-- | Applicative 'mapMaybe'.
mapMaybeA :: Applicative f => (a -> f (Maybe b)) -> [a] -> f [b]
mapMaybeA f = fmap catMaybes . traverse f
-- | @'forMaybeA' '==' 'flip' 'mapMaybeA'@
forMaybeA :: Applicative f => [a] -> (a -> f (Maybe b)) -> f [b]
forMaybeA = flip mapMaybeA
-- | Monadic 'mapMaybe'.
mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f = liftM catMaybes . mapM f
-- | @'forMaybeM' '==' 'flip' 'mapMaybeM'@
forMaybeM :: Monad m => [a] -> (a -> m (Maybe b)) -> m [b]
forMaybeM = flip mapMaybeM
|
AndreasPK/stack
|
src/Data/Maybe/Extra.hs
|
bsd-3-clause
| 743
| 0
| 12
| 135
| 274
| 145
| 129
| 14
| 1
|
module ListExtras where
foldFilter :: (a -> b -> (a, Bool)) -> a -> [b] -> [b] -> (a, [b])
foldFilter _ acc [] lacc = (acc, lacc)
foldFilter f acc (x:xs) lacc =
let (acc', filterOut) = f acc x
lacc' = if filterOut then lacc else lacc ++ [x]
in foldFilter f acc' xs lacc'
|
fredmorcos/attic
|
projects/pet/archive/pet_haskell_20131209/ListExtras.hs
|
isc
| 286
| 0
| 11
| 72
| 152
| 84
| 68
| 7
| 2
|
{-# LANGUAGE FlexibleContexts #-}
module Futhark.Internalise.Lambdas
( InternaliseLambda
, internaliseMapLambda
, internaliseFoldLambda
, internaliseRedomapInnerLambda
, internaliseStreamLambda
, internalisePartitionLambdas
)
where
import Control.Applicative
import Control.Monad
import Data.List
import Data.Loc
import qualified Data.Set as S
import Language.Futhark as E
import Futhark.Representation.SOACS as I
import Futhark.MonadFreshNames
import Futhark.Internalise.Monad
import Futhark.Internalise.AccurateSizes
import Futhark.Representation.SOACS.Simplify (simplifyLambda)
import Futhark.Optimise.DeadVarElim (deadCodeElimLambda)
import Prelude hiding (mapM)
-- | A function for internalising lambdas.
type InternaliseLambda =
E.Lambda -> [I.Type] -> InternaliseM ([I.LParam], I.Body, [I.ExtType])
internaliseMapLambda :: InternaliseLambda
-> E.Lambda
-> [I.SubExp]
-> InternaliseM I.Lambda
internaliseMapLambda internaliseLambda lam args = do
argtypes <- mapM I.subExpType args
let rowtypes = map I.rowType argtypes
(params, body, rettype) <- internaliseLambda lam rowtypes
(rettype', inner_shapes) <- instantiateShapes' rettype
let outer_shape = arraysSize 0 argtypes
shape_body <- bindingParamTypes params $
shapeBody (map I.identName inner_shapes) rettype' body
shapefun <- makeShapeFun params shape_body (length inner_shapes)
bindMapShapes inner_shapes shapefun args outer_shape
body' <- bindingParamTypes params $
ensureResultShape asserting "not all iterations produce same shape"
(srclocOf lam) rettype' body
return $ I.Lambda params body' rettype'
makeShapeFun :: [I.LParam] -> I.Body -> Int
-> InternaliseM I.Lambda
makeShapeFun params body n = do
-- Some of 'params' may be unique, which means that the shape slice
-- would consume its input. This is not acceptable - that input is
-- needed for the value function! Hence, for all unique parameters,
-- we create a substitute non-unique parameter, and insert a
-- copy-binding in the body of the function.
(params', copybnds) <- nonuniqueParams params
return $ I.Lambda params' (insertStms copybnds body) rettype
where rettype = replicate n $ I.Prim int32
bindMapShapes :: [I.Ident] -> I.Lambda -> [I.SubExp] -> SubExp
-> InternaliseM ()
bindMapShapes inner_shapes sizefun args outer_shape
| null $ I.lambdaReturnType sizefun = return ()
| otherwise = do
let size_args = replicate (length $ lambdaParams sizefun) Nothing
sizefun' <- deadCodeElimLambda <$> simplifyLambda sizefun Nothing size_args
let sizefun_safe =
all (I.safeExp . I.stmExp) $ I.bodyStms $ I.lambdaBody sizefun'
sizefun_arg_invariant =
not $ any (`S.member` freeInBody (I.lambdaBody sizefun')) $
map I.paramName $ lambdaParams sizefun'
if sizefun_safe && sizefun_arg_invariant
then do ses <- bodyBind $ lambdaBody sizefun'
forM_ (zip inner_shapes ses) $ \(v, se) ->
letBind_ (basicPattern' [] [v]) $ I.BasicOp $ I.SubExp se
else letBind_ (basicPattern' [] inner_shapes) =<<
eIf' isnonempty nonemptybranch emptybranch IfFallback
where emptybranch =
pure $ resultBody (map (const zero) $ I.lambdaReturnType sizefun)
nonemptybranch = insertStmsM $
resultBody <$> (eLambda sizefun =<< mapM index0 args)
isnonempty = eNot $ eCmpOp (I.CmpEq I.int32)
(pure $ I.BasicOp $ I.SubExp outer_shape)
(pure $ I.BasicOp $ SubExp zero)
zero = constant (0::I.Int32)
index0 arg = do
arg' <- letExp "arg" $ I.BasicOp $ I.SubExp arg
arg_t <- lookupType arg'
letSubExp "elem" $ I.BasicOp $ I.Index arg' $ fullSlice arg_t [I.DimFix zero]
internaliseFoldLambda :: InternaliseLambda
-> E.Lambda
-> [I.Type] -> [I.Type]
-> InternaliseM I.Lambda
internaliseFoldLambda internaliseLambda lam acctypes arrtypes = do
let rowtypes = map I.rowType arrtypes
(params, body, rettype) <- internaliseLambda lam $ acctypes ++ rowtypes
let rettype' = [ t `I.setArrayShape` I.arrayShape shape
| (t,shape) <- zip rettype acctypes ]
-- The result of the body must have the exact same shape as the
-- initial accumulator. We accomplish this with an assertion and
-- reshape().
body' <- bindingParamTypes params $
ensureResultShape asserting
"shape of result does not match shape of initial value" (srclocOf lam) rettype' body
return $ I.Lambda params body' rettype'
internaliseRedomapInnerLambda :: InternaliseLambda
-> E.Lambda
-> [I.SubExp]
-> [I.SubExp]
-> InternaliseM I.Lambda
internaliseRedomapInnerLambda internaliseLambda lam nes arr_args = do
arrtypes <- mapM I.subExpType arr_args
acctypes <- mapM I.subExpType nes
let rowtypes = map I.rowType arrtypes
--
(params, body, rettype) <- internaliseLambda lam $ acctypes ++ rowtypes
-- split rettype into (i) accummulator types && (ii) result-array-elem types
let acc_len = length acctypes
(acc_tps, res_el_tps) = (take acc_len rettype, drop acc_len rettype)
-- For the map part: for shape computation we build
-- a map lambda from the inner lambda by dropping from
-- the result the accumular and binding the accumulating
-- param to their corresponding neutral-element subexp.
-- Troels: would this be correct?
(rettypearr', inner_shapes) <- instantiateShapes' res_el_tps
let outer_shape = arraysSize 0 arrtypes
acc_params = take acc_len params
map_bodyres = drop acc_len $ I.bodyResult body
acc_bindings= map (\(ac_var,ac_val) ->
mkLet' [] [paramIdent ac_var] (BasicOp $ SubExp ac_val)
) (zip acc_params nes)
map_bindings= acc_bindings ++ bodyStms body
map_lore = bodyAttr body
map_body = I.Body map_lore map_bindings map_bodyres
shape_body <- bindingParamTypes params $
shapeBody (map I.identName inner_shapes) rettypearr' map_body
shapefun <- makeShapeFun (drop acc_len params) shape_body (length inner_shapes)
bindMapShapes inner_shapes shapefun arr_args outer_shape
--
-- for the reduce part
let acctype' = [ t `I.setArrayShape` I.arrayShape shape
| (t,shape) <- zip acc_tps acctypes ]
-- The reduce-part result of the body must have the exact same
-- shape as the initial accumulator. We accomplish this with
-- an assertion and reshape().
--
-- finally, place assertions and return result
body' <- bindingParamTypes params $
ensureResultShape asserting "shape of result does not match shape of initial value"
(srclocOf lam) (acctype'++rettypearr') body
return $ I.Lambda params body' (acctype'++rettypearr')
internaliseStreamLambda :: InternaliseLambda
-> E.Lambda
-> [I.Type]
-> InternaliseM I.ExtLambda
internaliseStreamLambda internaliseLambda lam rowts = do
chunk_size <- newVName "chunk_size"
let chunk_param = I.Param chunk_size $ I.Prim int32
chunktypes = map (`arrayOfRow` I.Var chunk_size) rowts
(params, body, rettype) <- localScope (scopeOfLParams [chunk_param]) $
internaliseLambda lam chunktypes
return $ I.ExtLambda (chunk_param:params) body rettype
-- Given @k@ lambdas, this will return a lambda that returns an
-- (k+2)-element tuple of integers. The first element is the
-- equivalence class ID in the range [0,k]. The remaining are all zero
-- except for possibly one element.
internalisePartitionLambdas :: InternaliseLambda
-> [E.Lambda]
-> [I.SubExp]
-> InternaliseM I.Lambda
internalisePartitionLambdas internaliseLambda lams args = do
argtypes <- mapM I.subExpType args
let rowtypes = map I.rowType argtypes
lams' <- forM lams $ \lam -> do
(params, body, _) <- internaliseLambda lam rowtypes
return (params, body)
params <- newIdents "partition_param" rowtypes
let params' = [ I.Param name t
| I.Ident name t <- params]
body <- mkCombinedLambdaBody params 0 lams'
return $ I.Lambda params' body rettype
where k = length lams
rettype = replicate (k+2) $ I.Prim int32
result i = resultBody $
map constant $ (fromIntegral i :: Int32) :
(replicate i 0 ++ [1::Int32] ++ replicate (k-i) 0)
mkCombinedLambdaBody :: [I.Ident]
-> Int
-> [([I.LParam], I.Body)]
-> InternaliseM I.Body
mkCombinedLambdaBody _ i [] =
return $ result i
mkCombinedLambdaBody params i ((lam_params,lam_body):lams') =
case lam_body of
Body () bodybnds [boolres] -> do
intres <- (:) <$> newIdent "eq_class" (I.Prim int32) <*>
replicateM (k+1) (newIdent "partition_incr" $ I.Prim int32)
next_lam_body <-
mkCombinedLambdaBody (map paramIdent lam_params) (i+1) lams'
let parambnds =
[ mkLet' [] [paramIdent top] $ I.BasicOp $ I.SubExp $ I.Var $ I.identName fromp
| (top,fromp) <- zip lam_params params ]
branchbnd = mkLet' [] intres $ I.If boolres
(result i)
next_lam_body $
ifCommon rettype
return $ mkBody (parambnds++bodybnds++[branchbnd]) $
map (I.Var . I.identName) intres
_ ->
fail "Partition lambda returns too many values."
|
ihc/futhark
|
src/Futhark/Internalise/Lambdas.hs
|
isc
| 10,022
| 0
| 22
| 2,790
| 2,556
| 1,286
| 1,270
| 177
| 3
|
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RecordWildCards #-}
module Eventful.ProcessManager
( ProcessManager (..)
, ProcessManagerCommand (..)
, applyProcessManagerCommandsAndEvents
) where
import Control.Monad (forM_, void)
import Eventful.CommandHandler
import Eventful.Projection
import Eventful.Store.Class
import Eventful.UUID
-- | A 'ProcessManager' manages interaction between event streams. It works by
-- listening to events on an event bus and applying events to its internal
-- 'Projection' (see 'applyProcessManagerCommandsAndEvents'). Then, pending
-- commands and events are plucked off of that Projection and applied to the
-- appropriate 'CommandHandler' or Projections in other streams.
data ProcessManager state event command
= ProcessManager
{ processManagerProjection :: Projection state (VersionedStreamEvent event)
, processManagerPendingCommands :: state -> [ProcessManagerCommand event command]
, processManagerPendingEvents :: state -> [StreamEvent UUID () event]
}
-- | This is a @command@ along with the UUID of the target 'CommandHandler', as
-- well as the 'CommandHandler' type. Note that this uses an existential type
-- to hide the @state@ type parameter on the CommandHandler.
data ProcessManagerCommand event command
= forall state. ProcessManagerCommand
{ processManagerCommandTargetId :: UUID
, processManagerCommandCommandHandler :: CommandHandler state event command
, processManagerCommandCommand :: command
}
instance (Show command, Show event) => Show (ProcessManagerCommand event command) where
show (ProcessManagerCommand uuid _ command) =
"ProcessManagerCommand{processManagerCommandCommandHandlerId = " ++ show uuid ++
", processManagerCommandCommand = " ++ show command ++ "}"
-- | Plucks the pending commands and events off of the process manager's state
-- and applies them to the appropriate locations in the event store.
applyProcessManagerCommandsAndEvents
:: (Monad m)
=> ProcessManager state event command
-> VersionedEventStoreWriter m event
-> VersionedEventStoreReader m event
-> state
-> m ()
applyProcessManagerCommandsAndEvents ProcessManager{..} writer reader state = do
forM_ (processManagerPendingCommands state) $ \(ProcessManagerCommand targetId commandHandler command) ->
void $ applyCommandHandler writer reader commandHandler targetId command
forM_ (processManagerPendingEvents state) $ \(StreamEvent projectionId () event) ->
storeEvents writer projectionId AnyPosition [event]
|
jdreaver/eventful
|
eventful-core/src/Eventful/ProcessManager.hs
|
mit
| 2,530
| 0
| 12
| 368
| 415
| 228
| 187
| 37
| 1
|
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.SQLTransactionCallback
(newSQLTransactionCallback, newSQLTransactionCallbackSync,
newSQLTransactionCallbackAsync, SQLTransactionCallback)
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
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionCallback Mozilla SQLTransactionCallback documentation>
newSQLTransactionCallback ::
(MonadDOM m) =>
(SQLTransaction -> JSM ()) -> m SQLTransactionCallback
newSQLTransactionCallback callback
= liftDOM
(SQLTransactionCallback . Callback <$>
function
(\ _ _ [transaction] ->
fromJSValUnchecked transaction >>=
\ transaction' -> callback transaction'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionCallback Mozilla SQLTransactionCallback documentation>
newSQLTransactionCallbackSync ::
(MonadDOM m) =>
(SQLTransaction -> JSM ()) -> m SQLTransactionCallback
newSQLTransactionCallbackSync callback
= liftDOM
(SQLTransactionCallback . Callback <$>
function
(\ _ _ [transaction] ->
fromJSValUnchecked transaction >>=
\ transaction' -> callback transaction'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionCallback Mozilla SQLTransactionCallback documentation>
newSQLTransactionCallbackAsync ::
(MonadDOM m) =>
(SQLTransaction -> JSM ()) -> m SQLTransactionCallback
newSQLTransactionCallbackAsync callback
= liftDOM
(SQLTransactionCallback . Callback <$>
asyncFunction
(\ _ _ [transaction] ->
fromJSValUnchecked transaction >>=
\ transaction' -> callback transaction'))
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/SQLTransactionCallback.hs
|
mit
| 2,740
| 0
| 13
| 605
| 561
| 335
| 226
| 49
| 1
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Game.GBA.RegisterSet
( Register
, RegisterSet(..)
, RegisterID
, register'
, makeRegisterSet
-- * Special registers
, linkRegister
, programCounter
, stackPointer
-- Status registers
, StatusRegister(..)
, StatusRegisterSet(..)
, BankMode(..)
, ProcessorMode(..)
, makeStatusRegisterSet
, fromModeBits
, toModeBits
)
where
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.ST
import Data.Binary
import Data.Word
import Data.STRef
import GHC.Generics
import Language.Literals.Binary
-- Why are these registers @STRef@s? So we don't have to write the whole thing every
-- time. Is it worth it? Maybe not, but I don't particular care enough...
--
-- Unfortunately the fact that these registers are mutable means they will be a pain
-- to debug. But they have to live in the ST monad somehow.
type Register s = STRef s Word32
type RegisterID = Int
-- | All the registers available. This datatype is purposely closed - you must
-- use the @register@ function to get a lens to it; with this function you can
-- 17 (or 16 in user mode) registers available for a specific mode.
data RegisterSet s = RegisterSet {
register0 :: {-# UNPACK #-} !(Register s)
, register1 :: {-# UNPACK #-} !(Register s)
, register2 :: {-# UNPACK #-} !(Register s)
, register3 :: {-# UNPACK #-} !(Register s)
, register4 :: {-# UNPACK #-} !(Register s)
, register5 :: {-# UNPACK #-} !(Register s)
, register6 :: {-# UNPACK #-} !(Register s)
, register7 :: {-# UNPACK #-} !(Register s)
, register8 :: {-# UNPACK #-} !(Register s)
, register9 :: {-# UNPACK #-} !(Register s)
, register10 :: {-# UNPACK #-} !(Register s)
, register11 :: {-# UNPACK #-} !(Register s)
, register12 :: {-# UNPACK #-} !(Register s)
, register13 :: {-# UNPACK #-} !(Register s)
, register14 :: {-# UNPACK #-} !(Register s)
, register15 :: {-# UNPACK #-} !(Register s)
, register8fiq :: {-# UNPACK #-} !(Register s)
, register9fiq :: {-# UNPACK #-} !(Register s)
, register10fiq :: {-# UNPACK #-} !(Register s)
, register11fiq :: {-# UNPACK #-} !(Register s)
, register12fiq :: {-# UNPACK #-} !(Register s)
, register13fiq :: {-# UNPACK #-} !(Register s)
, register14fiq :: {-# UNPACK #-} !(Register s)
, register13svc :: {-# UNPACK #-} !(Register s)
, register14svc :: {-# UNPACK #-} !(Register s)
, register13abt :: {-# UNPACK #-} !(Register s)
, register14abt :: {-# UNPACK #-} !(Register s)
, register13irq :: {-# UNPACK #-} !(Register s)
, register14irq :: {-# UNPACK #-} !(Register s)
, register13und :: {-# UNPACK #-} !(Register s)
, register14und :: {-# UNPACK #-} !(Register s)
}
data StatusRegisterSet s = StatusRegisterSet {
registerCPSR :: {-# UNPACK #-} !(StatusRegister s)
, registerSPSRfiq :: {-# UNPACK #-} !(StatusRegister s)
, registerSPSRsvc :: {-# UNPACK #-} !(StatusRegister s)
, registerSPSRabt :: {-# UNPACK #-} !(StatusRegister s)
, registerSPSRirq :: {-# UNPACK #-} !(StatusRegister s)
, registerSPSRund :: {-# UNPACK #-} !(StatusRegister s)
}
data StatusRegister s = StatusRegister
{ statusN :: {-# UNPACK #-} !(STRef s Bool)
, statusZ :: {-# UNPACK #-} !(STRef s Bool)
, statusC :: {-# UNPACK #-} !(STRef s Bool)
, statusV :: {-# UNPACK #-} !(STRef s Bool)
, statusQ :: {-# UNPACK #-} !(STRef s Bool)
, statusI :: {-# UNPACK #-} !(STRef s Bool)
, statusF :: {-# UNPACK #-} !(STRef s Bool)
, statusT :: {-# UNPACK #-} !(STRef s ProcessorMode)
, statusB :: {-# UNPACK #-} !(STRef s BankMode)
}
-- | Generally we probably spend most of our time in @UserMode@.
data BankMode = UserMode | FIQMode | SupervisorMode | AbortMode | IRQMode | UndefinedMode | SystemMode
-- | Processor state.
data ProcessorMode = ARM | Thumb
deriving (Enum, Ord, Eq, Show, Read)
-- | Converts a 5-bit representation into a bank mode.
fromModeBits :: Integral i => i -> BankMode
fromModeBits [b|10000|] = UserMode
fromModeBits [b|10001|] = FIQMode
fromModeBits [b|10010|] = IRQMode
fromModeBits [b|10011|] = SupervisorMode
fromModeBits [b|10111|] = AbortMode
fromModeBits [b|11011|] = UndefinedMode
fromModeBits [b|11111|] = SystemMode
fromModeBits _ = error "fromModeBits: invalid mode"
-- | Converts a @BankMode@ into its 5-bit representation.
toModeBits :: Integral i => BankMode -> i
toModeBits UserMode = [b|10000|]
toModeBits FIQMode = [b|10001|]
toModeBits IRQMode = [b|10010|]
toModeBits SupervisorMode = [b|10011|]
toModeBits AbortMode = [b|10111|]
toModeBits UndefinedMode = [b|11011|]
toModeBits SystemMode = [b|11111|]
stackPointer :: RegisterID
stackPointer = 13
linkRegister :: RegisterID
linkRegister = 14
programCounter :: RegisterID
programCounter = 15
-- | Theres a bit of nastiness where there is no register for
-- SPSR in UserMode mode. My hope is that this never gets called,
-- as it shouldn't even get called. Therefore, this does
-- not return a @Maybe@ and is as such not total.
--
-- This is an insane amount of boilerplate, but I'm actually
-- not sure what a better way to do this is. Luckily it is
-- all encapsulated within here.
register' :: BankMode -> RegisterID -> RegisterSet s -> Register s
register' _ 0 = register0
register' _ 1 = register1
register' _ 2 = register2
register' _ 3 = register3
register' _ 4 = register4
register' _ 5 = register5
register' _ 6 = register6
register' _ 7 = register7
register' FIQMode 8 = register8fiq
register' FIQMode 9 = register9fiq
register' FIQMode 10 = register10fiq
register' FIQMode 11 = register11fiq
register' FIQMode 12 = register12fiq
register' _ 8 = register8
register' _ 9 = register9
register' _ 10 = register10
register' _ 11 = register11
register' _ 12 = register12
register' UserMode 13 = register13
register' UserMode 14 = register14
register' SystemMode 13 = register13
register' SystemMode 14 = register14
register' FIQMode 13 = register13fiq
register' FIQMode 14 = register14fiq
register' SupervisorMode 13 = register13svc
register' SupervisorMode 14 = register14svc
register' AbortMode 13 = register13abt
register' AbortMode 14 = register14abt
register' IRQMode 13 = register13irq
register' IRQMode 14 = register14irq
register' UndefinedMode 13 = register13und
register' UndefinedMode 14 = register14und
-- program pointer
register' _ 15 = register15
makeStatusRegister :: ST s (StatusRegister s)
makeStatusRegister = let k = newSTRef False in StatusRegister
<$> k <*> k <*> k <*> k <*> k
<*> k <*> k <*> newSTRef ARM <*> newSTRef SystemMode
makeStatusRegisterSet :: ST s (StatusRegisterSet s)
makeStatusRegisterSet = let m = makeStatusRegister in StatusRegisterSet
<$> m <*> m <*> m <*> m <*> m
<*> m
-- | Makes a register set, with every register initialized to zero.
--
-- This is the only way to create a register set. Normally this only
-- needs to be done by boot process or test harnesses.
makeRegisterSet :: ST s (RegisterSet s)
makeRegisterSet = let k = newSTRef 0 in RegisterSet
<$> k <*> k <*> k <*> k <*> k -- 0
<*> k <*> k <*> k <*> k <*> k -- 5
<*> k <*> k <*> k <*> k <*> k -- 10
<*> k <*> k <*> k <*> k <*> k -- 15
<*> k <*> k <*> k <*> k <*> k -- 20
<*> k <*> k <*> k <*> k <*> k -- 25
<*> k
|
jhance/gba-hs
|
src/Game/GBA/RegisterSet.hs
|
mit
| 7,557
| 0
| 37
| 1,612
| 1,809
| 1,027
| 782
| 157
| 1
|
module Graphics.D3D11Binding.Interface.D3D11SamplerState where
import Graphics.D3D11Binding.Interface.Unknown
data ID3D11SamplerState = ID3D11SamplerState
instance UnknownInterface ID3D11SamplerState
|
jwvg0425/d3d11binding
|
src/Graphics/D3D11Binding/Interface/D3D11SamplerState.hs
|
mit
| 202
| 0
| 5
| 14
| 29
| 18
| 11
| 4
| 0
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Control.Monad.Trans.Pool (WithResourceT, WithResource, withResource, tryWithResource, runPooled, runDedicated) where
import Control.Arrow (Kleisli(..))
import Control.Monad.Trans.Class (MonadTrans(lift))
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Free.Church (FT, toFT, iterT, liftF)
import Data.Functor.Coyoneda (Coyoneda(..), liftCoyoneda)
import Data.Functor.Kan.Lan (Lan(..), glan)
import Data.Pool (Pool)
import qualified Data.Pool as Pool (tryWithResource, withResource)
data WithResourceF r m a = WithResource (Coyoneda (Kleisli m r) a)
| TryWithResource (Lan Maybe (Kleisli m r) a)
deriving Functor
type WithResource r a = WithResourceT r IO a
newtype WithResourceT r m a = WithResourceT (FT (WithResourceF r m) m a)
deriving (Functor, Applicative, Monad)
instance MonadTrans (WithResourceT r) where
lift = WithResourceT . lift
runPooledF :: MonadBaseControl IO m => Pool r -> WithResourceF r m (m a) -> m a
runPooledF pool (WithResource (Coyoneda next k)) = Pool.withResource pool (runKleisli k) >>= next
runPooledF pool (TryWithResource (Lan next k)) = Pool.tryWithResource pool (runKleisli k) >>= next
runPooled :: MonadBaseControl IO m => WithResourceT r m a -> Pool r -> m a
runPooled (WithResourceT m) pool = iterT (runPooledF pool) m
runDedicatedF :: Monad m => r -> WithResourceF r m (m a) -> m a
runDedicatedF r (WithResource (Coyoneda next k)) = runKleisli k r >>= next
runDedicatedF r (TryWithResource (Lan next k)) = runKleisli k r >>= next . Just
runDedicated :: Monad m => WithResourceT r m a -> r -> m a
runDedicated (WithResourceT m) r = iterT (runDedicatedF r) m
withResource :: Monad m => (r -> m a) -> WithResourceT r m a
withResource = WithResourceT . liftF . WithResource . liftCoyoneda . Kleisli
tryWithResource :: Monad m => (r -> m a) -> WithResourceT r m (Maybe a)
tryWithResource = WithResourceT . liftF . TryWithResource . glan . Kleisli
|
srijs/haskell-resource-pool-monad
|
src/Control/Monad/Trans/Pool.hs
|
mit
| 2,094
| 0
| 10
| 343
| 757
| 407
| 350
| 35
| 1
|
module Shexkell.Data.Common where
import Data.Char (toLower)
data SemAct = SemAct IRI (Maybe String)
deriving (Show, Eq)
data ObjectValue =
IRIValue IRI
| StringValue String
| DatatypeString String IRI
| LangString String String
| NumericValue NumericLiteral
deriving (Show, Eq)
data NumericLiteral =
NumericInt Int
| NumericDouble Double
| NumericDecimal Double
deriving (Show)
type IRI = String
data ShapeLabel =
IRILabel IRI
| BNodeId String
deriving (Show)
modifyLabel :: (String -> String) -> ShapeLabel -> ShapeLabel
modifyLabel f (IRILabel iri) = IRILabel $ f iri
modifyLabel f (BNodeId bnodeId) = BNodeId $ f bnodeId
instance Eq ShapeLabel where
(IRILabel a) == (IRILabel b) = map toLower a == map toLower b
(BNodeId a) == (BNodeId b) = map toLower a == map toLower b
_ == _ = False
instance Eq NumericLiteral where
(NumericInt n1) == (NumericInt n2) = n1 == n2
(NumericDouble d1) == (NumericDouble d2) = d1 == d2
(NumericDecimal d1) == (NumericDecimal d2) = d1 == d2
(NumericInt n) == (NumericDouble d) = fromIntegral n == d
(NumericInt n) == (NumericDecimal d) = fromIntegral n == d
(NumericDouble d) == (NumericInt n) = d == fromIntegral n
(NumericDouble d1) == (NumericDecimal d2) = d1 == d2
(NumericDecimal d) == (NumericInt n) = d == fromIntegral n
(NumericDecimal d1) == (NumericDouble d2) = d1 == d2
instance Ord NumericLiteral where
(NumericInt n1) `compare` (NumericInt n2) = n1 `compare` n2
(NumericDouble d1) `compare` (NumericDouble d2) = d1 `compare` d2
(NumericDecimal d1) `compare` (NumericDecimal d2) = d1 `compare` d2
(NumericInt n) `compare` (NumericDouble d) = fromIntegral n `compare` d
(NumericInt n) `compare` (NumericDecimal d) = fromIntegral n `compare` d
(NumericDouble d) `compare` (NumericInt n) = d `compare` fromIntegral n
(NumericDouble d) `compare` (NumericDecimal d2) = d `compare` d2
(NumericDecimal d) `compare` (NumericInt n) = d `compare` fromIntegral n
(NumericDecimal d1) `compare` (NumericDouble d2) = d1 `compare` d2
|
weso/shexkell
|
src/Shexkell/Data/Common.hs
|
mit
| 2,064
| 0
| 8
| 403
| 863
| 444
| 419
| 48
| 1
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
module L.Interpreter.Runtime where
import Control.Applicative
import Control.Monad.Error.Class
import Data.Bits
import Data.Foldable hiding (concat)
import Data.Int
import L.Interpreter.Output
import L.L1.L1L2AST
import L.L3.L3AST
data Runtime a = Num Int64 | Pointer Int64 | Runtime a deriving (Eq, Functor, Foldable, Show)
instance Applicative Runtime where
pure = Runtime
Runtime f <*> Runtime a = Runtime (f a)
instance Monad Runtime where
return = Runtime
Num i >>= _ = Num i
Pointer i >>= _ = Pointer i
Runtime a >>= f = f a
type MonadRuntime m = MonadError Halt m
lTrue, lFalse :: Runtime a
lTrue = Num 1
lFalse = Num 0
--TODO: rename to x86Op
runOp :: (Show a, MonadRuntime m) => Runtime a -> X86Op -> Runtime a -> m (Runtime a)
runOp (Num l) Increment (Num r) = return $ Num (l + r)
runOp (Num l) Increment (Pointer r) = return $ Pointer (l + r)
runOp (Pointer l) Increment (Num r) = return $ Pointer (l + r)
runOp (Num l) Decrement (Num r) = return $ Num (l - r)
runOp (Pointer l) Decrement (Num r) = return $ Pointer (l - r)
runOp (Num l) Multiply (Num r) = return $ Num (l * r)
runOp (Num i) LeftShift (Num amount) = return $ Num $ shiftL i (fromIntegral amount)
runOp (Num i) RightShift (Num amount) = return $ Num $ shiftR i (fromIntegral amount)
runOp (Num l) BitwiseAnd (Num r) = return $ Num (l .&. r)
-- If you're going to mess with pointers like this, you're just going to get back a Num.
runOp (Pointer l) BitwiseAnd (Num r) = return $ Num (l .&. r)
runOp l op r = exception $ "cannot do " ++ show l ++ " " ++ x86OpSymbol op ++ " " ++ show r
mathOp :: (Show a, MonadRuntime m) => PrimName -> Runtime a -> Runtime a -> m (Runtime a)
mathOp Add (Num l) (Num r) = return . Num $ l + r
mathOp Sub (Num l) (Num r) = return . Num $ l - r
mathOp Mult (Num l) (Num r) = return . Num $ l * r
mathOp LessThan (Num l) (Num r) = return . boolToNum $ l < r
mathOp LTorEQ (Num l) (Num r) = return . boolToNum $ l <= r
mathOp EqualTo (Num l) (Num r) = return . boolToNum $ l == r
mathOp b l r = exception $
concat ["invalid arguments to ", show b, " :", show l, ", " , show r]
boolToNum :: Bool -> Runtime a
boolToNum True = Num 1
boolToNum False = Num 0
isNumber :: Runtime a -> Runtime a
isNumber (Num _) = lTrue
isNumber _ = lFalse
isArray :: Runtime a -> Runtime a
isArray = boolToNum . isPointer
expectNum :: (Show a, MonadRuntime m) => Runtime a -> m Int64
expectNum (Num i) = return i
expectNum r = exception $ "expected a Num, but got: " ++ show r
expectPointer :: (Show a, MonadRuntime m) => String -> Runtime a -> m Int64
expectPointer _ (Pointer i) = return i
expectPointer caller r = exception $ caller ++ " expected Pointer, but got: " ++ show r
isPointer :: Runtime a -> Bool
isPointer (Pointer _) = True
isPointer _ = False
|
joshcough/L5-Haskell
|
src/L/Interpreter/Runtime.hs
|
mit
| 3,051
| 0
| 11
| 748
| 1,308
| 659
| 649
| 64
| 1
|
module Routing
( API
, api
, server
) where
import qualified AccessCode.Controller as AccessCode
import App (AppT)
import Data.Text (Text)
import qualified Home.Controller as Home
import Servant
import Servant.HTML.Blaze (HTML)
import Text.Blaze.Html5 (Html)
type API = MarketingAPI
type MarketingAPI = Home
:<|> "access-code" :> AccessCode
type Home = Get '[HTML] Html
type AccessCode = QueryParam "code" Text :> Get '[JSON] ()
server :: ServerT API AppT
server = Home.showA
:<|> AccessCode.showA
api :: Proxy API
api = Proxy
|
gust/feature-creature
|
auth-service/app/Routing.hs
|
mit
| 560
| 0
| 8
| 112
| 173
| 103
| 70
| -1
| -1
|
{-# htermination (*) :: Float -> Float -> Float #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_STAR_3.hs
|
mit
| 52
| 0
| 2
| 10
| 3
| 2
| 1
| 1
| 0
|
module CheapestInsertion (algCheapestInsertion) where
import TSPLib
import Insertion
import Data.List hiding (insert)
import Data.Function
algCheapestInsertion :: TSPAlgorithm
algCheapestInsertion = insertionAlgorithm select
select :: Path -> [Node] -> Node
select subtour restNs = selectedNode
where selectedNode = minimumBy (compare `on` flip cost subtour) restNs
cost :: Node -> Path -> Double
cost n p = edgeLength minEdge
where edges = pathToEdges p
dist (a,b) = distance a n + distance n b - distance a b
minEdge = minimumBy (compare `on` dist) edges
|
shouya/thinking-dumps
|
tsp/CheapestInsertion.hs
|
mit
| 591
| 0
| 10
| 116
| 188
| 102
| 86
| 15
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Query
-- Copyright : (c) 2014 Stefan Bühler
-- License : MIT-style (see the file COPYING)
--
-- Maintainer : stbuehler@web.de
-- Stability : experimental
-- Portability : portable
--
-- Request/Response framework, handling queries in a separate thread,
-- should kill the thread if reference to server object gets lost.
--
-----------------------------------------------------------------------------
module Control.Query
( QueryHandler
, QueryServer
, startQueryServer
, stopQueryServer
, query
) where
import Foreign.StablePtr
import Control.Concurrent
import Control.Exception
import System.Mem.Weak (addFinalizer)
{-| internal request data -}
newtype Request a b = Request (a, MVar b)
{-|
Server object; the server (thread) gets killed if this object dies. Used to
send queries to the server thread.
-}
data QueryServer a b = QueryServer
{ qsThread :: ThreadId
, qsQuery :: MVar (Request a b)
}
{-|
Type alias for a function handling requests in a 'QueryServer'. The first
parameter is the request data, the second the action to return the response
with.
Example:
> forkingHandler :: (a -> IO b) -> QueryHandler a b
> forkingHandler h req resp = forkIO $ h req >>= resp
-}
type QueryHandler a b = a -> (b -> IO()) -> IO ()
{-|
Start a new 'QueryServer' with the given handler
-}
startQueryServer :: forall a b. QueryHandler a b -> IO (QueryServer a b)
startQueryServer handler = do
q <- newEmptyMVar :: IO (MVar (Request a b))
t <- forkIO $ serve q
let qs = QueryServer t q
addFinalizer qs (throwTo t ThreadKilled)
return qs
where
serve :: MVar (Request a b) -> IO ()
serve input = do
Request (req, resp) <- takeMVar input
handler req (putMVar resp)
serve input
{-|
Manually stop the 'QueryServer' instead of waiting for garbage collection.
-}
stopQueryServer :: QueryServer a b -> IO ()
stopQueryServer qs = throwTo (qsThread qs) ThreadKilled
{-|
Send a query to the 'QueryServer' and wait for the response.
-}
query :: forall a b. QueryServer a b -> a -> IO b
query qs req = do
-- keep reference to QueryServer alive
bracket (newStablePtr qs) freeStablePtr $ \_ -> do
resp <- newEmptyMVar :: IO (MVar b)
putMVar (qsQuery qs) $ Request (req, resp)
takeMVar resp
|
stbuehler/haskell-mail-policy
|
src/Control/Query.hs
|
mit
| 2,376
| 7
| 14
| 441
| 500
| 266
| 234
| 36
| 1
|
module Jaml.Parser.JavaScript.Line
( silentJS
, noisyJS
) where
import Text.ParserCombinators.Parsec
import Control.Monad (liftM)
import Jaml.Types
import Jaml.Parser.Util (tillEol, optSpaces)
silentJS :: Parser Node
silentJS =
do char '-' >> optSpaces
liftM SilentJS tillEol -- don't use 'between' (which consumes)
noisyJS :: Parser Node
noisyJS =
do char '=' >> optSpaces
liftM NoisyJS tillEol
|
marklar/jaml
|
Jaml/Parser/JavaScript/Line.hs
|
mit
| 423
| 0
| 8
| 80
| 114
| 62
| 52
| 15
| 1
|
module Behaviors.CountingBrowser where
import Control.Concurrent.STM (TVar, atomically, modifyTVar')
import Data.Text (Text)
import Data.Time (getCurrentTime, diffUTCTime)
import Simulation.Node.Endpoint.AppCounter
import Simulation.Node.Endpoint.Behavior
import Simulation.Node.Endpoint.Behavior.Browser (browsePage)
import Behaviors.Counter
browsePageCounted :: (BehaviorState s) => Text -> Behavior Counter s [Text]
browsePageCounted url = do
start <- liftIO getCurrentTime
pages <- browsePage url
stop <- liftIO getCurrentTime
let duration = stop `diffUTCTime` start
modifyCounter $ maybeAdjustLongestFetchTime duration .
addTotalFetchTime duration .
incNumPageFetches
return pages
modifyCounter :: (AppCounter c, BehaviorState s) => (c -> c) -> Behavior c s ()
modifyCounter g = do
counter <- appCounter
liftIO $ modifyTVarIO' counter g
modifyTVarIO' :: TVar a -> (a -> a) -> IO ()
modifyTVarIO' tvar g = atomically $ modifyTVar' tvar g
|
kosmoskatten/programmable-endpoint-demo
|
src/Behaviors/CountingBrowser.hs
|
mit
| 1,000
| 0
| 10
| 173
| 300
| 157
| 143
| 24
| 1
|
module QuickTest (module QuickTest) where
import Test.QuickCheck
import Test.QuickCheck.Monadic
import HspInterpreter
import Phonemizer
import Soundgluer
qtest :: IO ()
qtest = do
putStrLn "Checking phonemizer"
quickCheck prop_phonemizer
putStrLn "Checking matchLangRule"
quickCheck prop_matchLangRule
putStrLn "Checking replaceOccurences"
quickCheck prop_replaceOccurences
putStrLn "strToLangRule: x -> x"
quickCheck prop_strToLangRule_xTox
putStrLn "despace: works like filter"
quickCheck prop_despace_likeFilter
putStrLn "isWave: true for .wav files"
quickCheck prop_isWave_trueForWav
putStrLn "phoneName: drops .wav extension"
quickCheck prop_phoneName_dropsWav
putStrLn "getLangPath: prepends langDirectory + separator"
quickCheck prop_getLangPath_prependsLangDirSep
prop_phonemizer :: String -> Property
prop_phonemizer s = monadicIO $ do
phnmzd <- run (phonemize "pol" s)
let wrds= words s
assert ((length phnmzd)==(length wrds))
prop_matchLangRule :: String -> String -> [String] -> Bool
prop_matchLangRule a b c =
let
string=a++b
rule=MkLangRule a c
in ((matchLangRule string [rule])==rule)
prop_replaceOccurences :: String -> [String] -> [String] -> Bool
prop_replaceOccurences x y z=((x `elem` y) || not (x `elem` (replaceOccurences x y z)))
prop_strToLangRule_xTox :: String -> Bool
prop_strToLangRule_xTox x =
let x' = filter (/= ' ') . filter (/= ',') $ x
in (MkLangRule x' [x']) == (strToLangRule $ x' ++ " -> " ++ x')
prop_despace_likeFilter :: String -> Bool
prop_despace_likeFilter x =
filter (/= ' ') x == despace x
prop_isWave_trueForWav :: String -> Bool
prop_isWave_trueForWav x =
isWave $ x ++ waveExtension
prop_phoneName_dropsWav :: String -> Bool
prop_phoneName_dropsWav x =
x == phoneName (x ++ ".wav")
prop_getLangPath_prependsLangDirSep :: String -> Bool
prop_getLangPath_prependsLangDirSep x =
(langsDirectory ++ pathSeparator ++ x) == getLangPath x
|
mprzewie/haspell
|
test/QuickTest.hs
|
mit
| 2,067
| 0
| 12
| 426
| 569
| 282
| 287
| 53
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot1click-project-devicetemplate.html
module Stratosphere.ResourceProperties.IoT1ClickProjectDeviceTemplate where
import Stratosphere.ResourceImports
-- | Full data type definition for IoT1ClickProjectDeviceTemplate. See
-- 'ioT1ClickProjectDeviceTemplate' for a more convenient constructor.
data IoT1ClickProjectDeviceTemplate =
IoT1ClickProjectDeviceTemplate
{ _ioT1ClickProjectDeviceTemplateCallbackOverrides :: Maybe Object
, _ioT1ClickProjectDeviceTemplateDeviceType :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON IoT1ClickProjectDeviceTemplate where
toJSON IoT1ClickProjectDeviceTemplate{..} =
object $
catMaybes
[ fmap (("CallbackOverrides",) . toJSON) _ioT1ClickProjectDeviceTemplateCallbackOverrides
, fmap (("DeviceType",) . toJSON) _ioT1ClickProjectDeviceTemplateDeviceType
]
-- | Constructor for 'IoT1ClickProjectDeviceTemplate' containing required
-- fields as arguments.
ioT1ClickProjectDeviceTemplate
:: IoT1ClickProjectDeviceTemplate
ioT1ClickProjectDeviceTemplate =
IoT1ClickProjectDeviceTemplate
{ _ioT1ClickProjectDeviceTemplateCallbackOverrides = Nothing
, _ioT1ClickProjectDeviceTemplateDeviceType = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot1click-project-devicetemplate.html#cfn-iot1click-project-devicetemplate-callbackoverrides
itcpdtCallbackOverrides :: Lens' IoT1ClickProjectDeviceTemplate (Maybe Object)
itcpdtCallbackOverrides = lens _ioT1ClickProjectDeviceTemplateCallbackOverrides (\s a -> s { _ioT1ClickProjectDeviceTemplateCallbackOverrides = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot1click-project-devicetemplate.html#cfn-iot1click-project-devicetemplate-devicetype
itcpdtDeviceType :: Lens' IoT1ClickProjectDeviceTemplate (Maybe (Val Text))
itcpdtDeviceType = lens _ioT1ClickProjectDeviceTemplateDeviceType (\s a -> s { _ioT1ClickProjectDeviceTemplateDeviceType = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/IoT1ClickProjectDeviceTemplate.hs
|
mit
| 2,176
| 0
| 12
| 203
| 252
| 145
| 107
| 27
| 1
|
module Cryptography.MACs.Macro where
import Types
import Functions.Application.Macro
-- * MAC
-- | Tag space
tsp_ :: Note
tsp_ = mathcal "T"
-- | Concrete MAC function
mfn_ :: Note
mfn_ = "f"
-- | Computation of tag of message and key
mfn :: Note -> Note -> Note
mfn = fn2 mfn_
|
NorfairKing/the-notes
|
src/Cryptography/MACs/Macro.hs
|
gpl-2.0
| 304
| 0
| 6
| 78
| 64
| 39
| 25
| 9
| 1
|
{-# LANGUAGE
RecordWildCards
, FlexibleInstances
, FlexibleContexts
, TypeFamilies
#-}
module Hammer.VoxBox.Render
( getExtendedVoxBox
, getVoxBoxCornersPoints
, RenderVox(..)
) where
import qualified Data.Vector.Unboxed as U
import Data.Vector.Unboxed (Vector, Unbox)
import Linear.Vect
import Hammer.VoxBox
-- =======================================================================================
newtype VoxBoxExt a = VoxBoxExt (VoxBox a)
class (Unbox elem, Unbox (Pointer elem))=> RenderVox elem where
type Pointer elem :: *
renderVox :: VoxBoxExt a -> elem -> Pointer elem
instance RenderVox FaceVoxelPos where
type Pointer FaceVoxelPos = (Int, Int, Int, Int)
renderVox = renderFacePos
instance RenderVox EdgeVoxelPos where
type Pointer EdgeVoxelPos = (Int, Int)
renderVox = renderEdgePos
instance RenderVox VoxelPos where
type Pointer VoxelPos = Int
renderVox = renderVoxelPos
renderVoxelVolume :: VoxBoxExt a -> VoxelPos -> (((Int, Int), (Int, Int)), ((Int, Int), (Int, Int)))
renderVoxelVolume (VoxBoxExt vbox) pos = let
e p = case getVoxelID (dimension vbox) p of
Just x -> x
_ -> error ("[VTK.VoxBox] " ++ show pos ++ show (dimension vbox))
f000 = e
f100 = e . (#+# VoxelPos 1 0 0)
f010 = e . (#+# VoxelPos 0 1 0)
f110 = e . (#+# VoxelPos 1 1 0)
f001 = e . (#+# VoxelPos 0 0 1)
f101 = e . (#+# VoxelPos 1 0 1)
f011 = e . (#+# VoxelPos 0 1 1)
f111 = e . (#+# VoxelPos 1 1 1)
-- face struct -> (((rtf, rbf), (ltf, lbf)), ((rtb, rbb), (ltb, lbb)))
in (((f110 pos, f100 pos), (f010 pos, f000 pos)), ((f111 pos, f101 pos), (f011 pos, f001 pos)))
renderFacePos :: VoxBoxExt a -> FaceVoxelPos -> (Int, Int, Int, Int)
renderFacePos (VoxBoxExt vbox) face = let
e p = case getVoxelID (dimension vbox) p of
Just x -> x
_ -> error ("[VTK.VoxBox] " ++ show face ++ show (dimension vbox))
f000 = e
f100 = e . (#+# VoxelPos 1 0 0)
f010 = e . (#+# VoxelPos 0 1 0)
f110 = e . (#+# VoxelPos 1 1 0)
f001 = e . (#+# VoxelPos 0 0 1)
f101 = e . (#+# VoxelPos 1 0 1)
f011 = e . (#+# VoxelPos 0 1 1)
in case face of
Fx p -> (f000 p, f010 p, f011 p, f001 p)
Fy p -> (f000 p, f100 p, f101 p, f001 p)
Fz p -> (f000 p, f100 p, f110 p, f010 p)
renderEdgePos :: VoxBoxExt a -> EdgeVoxelPos -> (Int, Int)
renderEdgePos (VoxBoxExt vbox) edge = let
e p = case getVoxelID (dimension vbox) p of
Just x -> x
_ -> error ("[VTK.VoxBox] " ++ show edge ++ show (dimension vbox))
f000 = e
f100 = e . (#+# VoxelPos 1 0 0)
f010 = e . (#+# VoxelPos 0 1 0)
f001 = e . (#+# VoxelPos 0 0 1)
in case edge of
Ex p -> (f000 p, f100 p)
Ey p -> (f000 p, f010 p)
Ez p -> (f000 p, f001 p)
renderVoxelPos :: VoxBoxExt a -> VoxelPos -> Int
renderVoxelPos (VoxBoxExt vbox) p = case getVoxelID (dimension vbox) p of
Just x -> x
_ -> error ("[VTK.VoxBox] " ++ show p ++ show (dimension vbox))
-- | Extends the range ('VoxBoxDim') of an given 'VoxBox' in order to calculate all voxel
-- corner points. See 'getVoxBoxCornersPoints'.
getExtendedVoxBox :: VoxBox a -> VoxBoxExt a
getExtendedVoxBox vbox = let
func (VoxBoxDim x y z) = VoxBoxDim (x+1) (y+1) (z+1)
range = let vbr = dimension vbox
in vbr { vbrDim = func $ vbrDim vbr}
in VoxBoxExt $ vbox { dimension = range }
-- | Calculate all the voxel's corner points (vertices from voxel box) by calculating the
-- base point of each 'VoxelPos' in a extended range.
getVoxBoxCornersPoints :: VoxBoxExt a -> Vector Vec3D
getVoxBoxCornersPoints (VoxBoxExt vbox) = let
dimData = dimension vbox
origin = vbrOrigin dimData
size = sizeVoxBoxRange dimData
VoxBoxDim dbx dby _ = vbrDim dimData
foo i = let
(z, rz) = i `quotRem` (dbx * dby)
(y, ry) = rz `quotRem` dbx
x = ry
in evalVoxelPos vbox (origin #+# VoxelPos x y z)
in U.generate size foo
|
lostbean/Hammer
|
src/Hammer/VoxBox/Render.hs
|
gpl-3.0
| 3,905
| 0
| 17
| 936
| 1,526
| 802
| 724
| 91
| 4
|
module Main ( main ) where
import qualified SteamQuota as SQ ( main )
main :: IO ()
main = SQ.main
|
nikitaDanilenko/steamQuota
|
Main.hs
|
gpl-3.0
| 100
| 0
| 6
| 22
| 37
| 23
| 14
| 4
| 1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Module : UHA_Utils
License : GPL
Maintainer : helium@cs.uu.nl
Stability : experimental
Portability : portable
Utilities to extract data from the syntax tree
-}
module Helium.Syntax.UHA_Utils where
--import Helium.UHA_Range(noRange, getNameRange)
import Helium.Syntax.UHA_Range --altered for Holmes
import Data.Maybe --added for Holmes
import Helium.Syntax.UHA_Syntax --added for Holmes
import Lvm.Common.Id(Id, idFromString, stringFromId)
import Data.Char
import Top.Types(isTupleConstructor)
import Helium.Utils.Utils(internalError)
instance Eq Name where
n1 == n2 = getNameName n1 == getNameName n2
instance Ord Name where
n1 <= n2 = getNameName n1 <= getNameName n2
instance Show Name where
show = getNameName
--------------------------------------------------------------
-- NameWithRange
newtype NameWithRange = NameWithRange { nameWithRangeToName :: Name }
instance Show NameWithRange where
show (NameWithRange name) =
show name ++ " at " ++ show (getNameRange name)
instance Eq NameWithRange where
NameWithRange name1 == NameWithRange name2 =
(name1, getNameRange name1) == (name2, getNameRange name2)
instance Ord NameWithRange where
NameWithRange name1 <= NameWithRange name2 =
(name1, getNameRange name1) <= (name2, getNameRange name2)
--------------------------------------------------------------
getNameName :: Name -> String -- !!!Name
getNameName (Name_Identifier _ _ name) = name
getNameName (Name_Operator _ _ name) = name
getNameName (Name_Special _ _ name) = name
-- added for Holmes
getHolmesName :: String -> Name -> String -- !!!Name
getHolmesName altname (Name_Identifier range _ name) = getFrom range altname ++ "." ++ name
getHolmesName altname (Name_Operator range _ name) = getFrom range altname ++ "." ++ name
getHolmesName altname (Name_Special range _ name) = getFrom range altname ++ "." ++ name
getFrom :: Range -> [Char] -> [Char]
getFrom range altname = if result == "" then altname else result
where
result = snd $ checkRange range
checkRange _ = fromMaybe ("","") moduleFI
moduleFI = modulesFromImportRange range
getModuleName :: Module -> String -- added for Holmes
getModuleName (Module_Module _ MaybeName_Nothing _ _) = ""
getModuleName (Module_Module _ (MaybeName_Just name) _ _) = show name
idFromName :: Name -> Id -- !!!Name
idFromName (Name_Special _ _ s) = idFromString s
idFromName (Name_Identifier _ _ s) = idFromString s
idFromName (Name_Operator _ _ s) = idFromString s
nameFromId :: Id -> Name
nameFromId = nameFromString . stringFromId
nameFromString :: String -> Name -- !!!Name
nameFromString str@(first:_)
| isAlpha first = Name_Identifier noRange [] str
| str == "[]" || isTupleConstructor str || str == "->"
= Name_Special noRange [] str
| otherwise = Name_Operator noRange [] str
nameFromString _ = internalError "UHA_Utils" "nameFromString" "empty string"
isOperatorName :: Name -> Bool -- !!!Name
isOperatorName (Name_Operator{}) = True
isOperatorName _ = False
isConstructor :: Name -> Bool -- !!!Name
isConstructor name =
case name of
Name_Operator _ _ (':':_) -> True
Name_Identifier _ _ (first:_) -> isUpper first
Name_Special _ _ "()" -> True
Name_Special _ _ "[]" -> True
_ -> False
isIdentifierName :: Name -> Bool -- !!!Name
isIdentifierName (Name_Identifier{}) = True
isIdentifierName _ = False
showNameAsOperator :: Name -> String
showNameAsOperator name
| isIdentifierName name = "`"++show name++"`"
| otherwise = show name
showNameAsVariable :: Name -> String
showNameAsVariable name
| isOperatorName name = "("++show name++")"
| otherwise = show name
stringFromImportDeclaration :: ImportDeclaration -> String
stringFromImportDeclaration importDecl =
case importDecl of
ImportDeclaration_Import _ _ n _ _ -> getNameName n
ImportDeclaration_Empty _ ->
internalError "UHA_Utils" "stringFromImportDeclaration" "empty import declaration"
-- TODO: daan
intUnaryMinusName, floatUnaryMinusName, enumFromName, enumFromToName, enumFromThenName, enumFromThenToName :: Name
intUnaryMinusName = nameFromString "$negate"
floatUnaryMinusName = nameFromString "$floatUnaryMinus"
enumFromName = nameFromString "$enumFrom"
enumFromToName = nameFromString "$enumFromTo"
enumFromThenName = nameFromString "$enumFromThen"
enumFromThenToName = nameFromString "$enumFromThenTo"
patternVars :: Pattern -> [Name]
patternVars p = case p of
Pattern_Literal _ _ -> []
Pattern_Variable _ n -> [n]
Pattern_Constructor _ _ ps -> concatMap patternVars ps
Pattern_Parenthesized _ pat -> patternVars pat
Pattern_InfixConstructor _ p1 _ p2 -> concatMap patternVars [p1, p2]
Pattern_List _ ps -> concatMap patternVars ps
Pattern_Tuple _ ps -> concatMap patternVars ps
Pattern_Negate _ _ -> []
Pattern_As _ n pat -> n : patternVars pat
Pattern_Wildcard _ -> []
Pattern_Irrefutable _ pat -> patternVars pat
Pattern_NegateFloat _ _ -> []
_ -> internalError "UHA_Utils" "patternVars" "unsupported kind of pattern"
--Extract the name(s) of a declaration
nameOfDeclaration :: Declaration -> Names
nameOfDeclaration d = case d of
Declaration_Class _ _ (SimpleType_SimpleType _ n _) _ -> [n]
Declaration_Data _ _ (SimpleType_SimpleType _ n _) _ _ -> [n]
Declaration_Default _ _ -> [] --What does the Default do, it is not created by the parser...
Declaration_Empty _ -> []
Declaration_Fixity _ _ _ ns -> ns
Declaration_FunctionBindings _ fb -> [head $ concatMap nameOfFunctionBinding fb]
Declaration_Instance _ _ n _ _ -> [n]
Declaration_Newtype _ _ (SimpleType_SimpleType _ n _) _ _ -> [n]
Declaration_PatternBinding _ _ _ -> [] --Not entirely sure whether this is correct or not (a directly declared pattern is a binding to the names in the pattern...)
Declaration_Type _ (SimpleType_SimpleType _ n _) _ -> [n]
Declaration_TypeSignature _ ns _ -> ns
Declaration_Hole _ _ -> []
nameOfFunctionBinding :: FunctionBinding -> Names
nameOfFunctionBinding (FunctionBinding_FunctionBinding _ lhs _) = nameOfLeftHandSide lhs
nameOfFunctionBinding (FunctionBinding_Hole _ _) = []
nameOfFunctionBinding (FunctionBinding_Feedback _ _ fb) = nameOfFunctionBinding fb -- Check: Bastiaan
nameOfLeftHandSide :: LeftHandSide -> Names
nameOfLeftHandSide lhs = case lhs of
LeftHandSide_Function _ n _ -> [n]
LeftHandSide_Infix _ _ n _ -> [n]
LeftHandSide_Parenthesized _ l _ -> nameOfLeftHandSide l
|
roberth/uu-helium
|
src/Helium/Syntax/UHA_Utils.hs
|
gpl-3.0
| 7,364
| 0
| 11
| 1,976
| 1,831
| 922
| 909
| 127
| 13
|
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Yesod.Default.Config
import Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Control.Applicative
import Settings.Development
import Data.Default (def)
import Text.Hamlet
-- Static setting below. Changing these requires a recompile
-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticDir :: FilePath
staticDir = "static"
-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Foundation.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Foundation.hs
staticRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/static|]
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
{ wfsHamletSettings = defaultHamletSettings
{ hamletNewlines = AlwaysNewlines
}
}
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if development then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
data Extra = Extra
{ extraCopyright :: Text
, extraAnalytics :: Maybe Text -- ^ Google Analytics
, auditStoreDir :: Text
, checkpointInterval :: Int
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "copyright"
<*> o .:? "analytics"
<*> o .: "auditStoreDir"
<*> o .: "checkpointInterval"
|
c0c0n3/audidoza
|
Settings.hs
|
gpl-3.0
| 2,734
| 0
| 12
| 500
| 297
| 186
| 111
| -1
| -1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Khan.CLI.Metadata (commands) where
-- Module : Khan.CLI.Metadata
-- Copyright : (c) 2013 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
import Data.Aeson (Value(String))
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as LBS
import qualified Data.HashMap.Strict as Map
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Lazy.IO as LText
import Data.Text.Manipulate
import Khan.Internal
import qualified Khan.Model.Ansible.Serialisation as Ansible
import qualified Khan.Model.Tag as Tag
import Khan.Prelude
import Network.AWS
import Network.AWS.EC2.Metadata (Dynamic(..), toPath)
import qualified Network.AWS.EC2.Metadata as Meta
data Describe = Describe
{ dMultiLine :: !Bool
, dForce :: !Bool
}
describeParser :: Parser Describe
describeParser = Describe
<$> switchOption "multiline" False
"Write each output KEY=VALUE on a separate line."
<*> switchOption "force" False
"Force update of any previously cached results."
instance Options Describe where
discover False _ _ =
throwError "khan metadata can only be run on an EC2 instance."
discover True _ d =
return d
commands :: Mod CommandFields Command
commands = command "metadata" describe describeParser
"Collect and display various metadata about the running instance."
describe :: Common -> Describe -> AWS ()
describe Common{..} Describe{..} = do
bs <- liftEitherT $ Meta.dynamic Document
debug "Received dynamic document:\n{}" [Text.decodeUtf8 bs]
doc <- filtered <$> decode bs
iid <- instanceId doc
ts <- bool (Tag.cached cCache iid) (Tag.require iid) dForce
liftIO . LText.putStrLn . renderEnv dMultiLine $
toEnv ts <> hostVars ts <> doc
where
decode = noteError "Unable to decode: "
. Aeson.decode
. LBS.fromStrict
filtered m =
let key = awsPrefix . Text.toUpper . toSnake
in Map.fromList [(key k, v) | (k, Just v) <- Map.toList m]
instanceId = lookupKey (awsPrefix "INSTANCE_ID")
awsPrefix = mappend "AWS_"
lookupKey k = noteError ("Unable to find " <> k <> " in: ") . Map.lookup k
noteError e = hoistError
. note (toError . Text.unpack $ e
<> "http://169.254.169.254/latest/dynamic/"
<> toPath Document)
hostVars =
let f (k, String v) = Just (Text.toUpper k, v)
f _ = Nothing
in Map.fromList . mapMaybe f . Ansible.hostVars cRegion . names
|
brendanhay/khan
|
khan-cli/Khan/CLI/Metadata.hs
|
mpl-2.0
| 3,260
| 0
| 14
| 930
| 696
| 378
| 318
| 66
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.RegionAutoscalers.Update
-- 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 an autoscaler in the specified project using the data included
-- in the request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionAutoscalers.update@.
module Network.Google.Resource.Compute.RegionAutoscalers.Update
(
-- * REST Resource
RegionAutoscalersUpdateResource
-- * Creating a Request
, regionAutoscalersUpdate
, RegionAutoscalersUpdate
-- * Request Lenses
, rauRequestId
, rauProject
, rauPayload
, rauAutoscaler
, rauRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.regionAutoscalers.update@ method which the
-- 'RegionAutoscalersUpdate' request conforms to.
type RegionAutoscalersUpdateResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"autoscalers" :>
QueryParam "requestId" Text :>
QueryParam "autoscaler" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Autoscaler :> Put '[JSON] Operation
-- | Updates an autoscaler in the specified project using the data included
-- in the request.
--
-- /See:/ 'regionAutoscalersUpdate' smart constructor.
data RegionAutoscalersUpdate =
RegionAutoscalersUpdate'
{ _rauRequestId :: !(Maybe Text)
, _rauProject :: !Text
, _rauPayload :: !Autoscaler
, _rauAutoscaler :: !(Maybe Text)
, _rauRegion :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegionAutoscalersUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rauRequestId'
--
-- * 'rauProject'
--
-- * 'rauPayload'
--
-- * 'rauAutoscaler'
--
-- * 'rauRegion'
regionAutoscalersUpdate
:: Text -- ^ 'rauProject'
-> Autoscaler -- ^ 'rauPayload'
-> Text -- ^ 'rauRegion'
-> RegionAutoscalersUpdate
regionAutoscalersUpdate pRauProject_ pRauPayload_ pRauRegion_ =
RegionAutoscalersUpdate'
{ _rauRequestId = Nothing
, _rauProject = pRauProject_
, _rauPayload = pRauPayload_
, _rauAutoscaler = Nothing
, _rauRegion = pRauRegion_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
rauRequestId :: Lens' RegionAutoscalersUpdate (Maybe Text)
rauRequestId
= lens _rauRequestId (\ s a -> s{_rauRequestId = a})
-- | Project ID for this request.
rauProject :: Lens' RegionAutoscalersUpdate Text
rauProject
= lens _rauProject (\ s a -> s{_rauProject = a})
-- | Multipart request metadata.
rauPayload :: Lens' RegionAutoscalersUpdate Autoscaler
rauPayload
= lens _rauPayload (\ s a -> s{_rauPayload = a})
-- | Name of the autoscaler to update.
rauAutoscaler :: Lens' RegionAutoscalersUpdate (Maybe Text)
rauAutoscaler
= lens _rauAutoscaler
(\ s a -> s{_rauAutoscaler = a})
-- | Name of the region scoping this request.
rauRegion :: Lens' RegionAutoscalersUpdate Text
rauRegion
= lens _rauRegion (\ s a -> s{_rauRegion = a})
instance GoogleRequest RegionAutoscalersUpdate where
type Rs RegionAutoscalersUpdate = Operation
type Scopes RegionAutoscalersUpdate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient RegionAutoscalersUpdate'{..}
= go _rauProject _rauRegion _rauRequestId
_rauAutoscaler
(Just AltJSON)
_rauPayload
computeService
where go
= buildClient
(Proxy :: Proxy RegionAutoscalersUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/RegionAutoscalers/Update.hs
|
mpl-2.0
| 5,234
| 0
| 18
| 1,186
| 639
| 380
| 259
| 97
| 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.ProximityBeacon.Beacons.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)
--
-- Searches the beacon registry for beacons that match the given search
-- criteria. Only those beacons that the client has permission to list will
-- be returned. Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **viewer**, **Is owner** or **Can edit**
-- permissions in the Google Developers Console project.
--
-- /See:/ <https://developers.google.com/beacons/proximity/ Proximity Beacon API Reference> for @proximitybeacon.beacons.list@.
module Network.Google.Resource.ProximityBeacon.Beacons.List
(
-- * REST Resource
BeaconsListResource
-- * Creating a Request
, beaconsList
, BeaconsList
-- * Request Lenses
, blXgafv
, blUploadProtocol
, blAccessToken
, blUploadType
, blQ
, blPageToken
, blProjectId
, blPageSize
, blCallback
) where
import Network.Google.Prelude
import Network.Google.ProximityBeacon.Types
-- | A resource alias for @proximitybeacon.beacons.list@ method which the
-- 'BeaconsList' request conforms to.
type BeaconsListResource =
"v1beta1" :>
"beacons" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "q" Text :>
QueryParam "pageToken" Text :>
QueryParam "projectId" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListBeaconsResponse
-- | Searches the beacon registry for beacons that match the given search
-- criteria. Only those beacons that the client has permission to list will
-- be returned. Authenticate using an [OAuth access
-- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2)
-- from a signed-in user with **viewer**, **Is owner** or **Can edit**
-- permissions in the Google Developers Console project.
--
-- /See:/ 'beaconsList' smart constructor.
data BeaconsList =
BeaconsList'
{ _blXgafv :: !(Maybe Xgafv)
, _blUploadProtocol :: !(Maybe Text)
, _blAccessToken :: !(Maybe Text)
, _blUploadType :: !(Maybe Text)
, _blQ :: !(Maybe Text)
, _blPageToken :: !(Maybe Text)
, _blProjectId :: !(Maybe Text)
, _blPageSize :: !(Maybe (Textual Int32))
, _blCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BeaconsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'blXgafv'
--
-- * 'blUploadProtocol'
--
-- * 'blAccessToken'
--
-- * 'blUploadType'
--
-- * 'blQ'
--
-- * 'blPageToken'
--
-- * 'blProjectId'
--
-- * 'blPageSize'
--
-- * 'blCallback'
beaconsList
:: BeaconsList
beaconsList =
BeaconsList'
{ _blXgafv = Nothing
, _blUploadProtocol = Nothing
, _blAccessToken = Nothing
, _blUploadType = Nothing
, _blQ = Nothing
, _blPageToken = Nothing
, _blProjectId = Nothing
, _blPageSize = Nothing
, _blCallback = Nothing
}
-- | V1 error format.
blXgafv :: Lens' BeaconsList (Maybe Xgafv)
blXgafv = lens _blXgafv (\ s a -> s{_blXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
blUploadProtocol :: Lens' BeaconsList (Maybe Text)
blUploadProtocol
= lens _blUploadProtocol
(\ s a -> s{_blUploadProtocol = a})
-- | OAuth access token.
blAccessToken :: Lens' BeaconsList (Maybe Text)
blAccessToken
= lens _blAccessToken
(\ s a -> s{_blAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
blUploadType :: Lens' BeaconsList (Maybe Text)
blUploadType
= lens _blUploadType (\ s a -> s{_blUploadType = a})
-- | Filter query string that supports the following field filters: *
-- **description:\`\"\"\`** For example: **description:\"Room 3\"** Returns
-- beacons whose description matches tokens in the string \"Room 3\" (not
-- necessarily that exact string). The string must be double-quoted. *
-- **status:\`\`** For example: **status:active** Returns beacons whose
-- status matches the given value. Values must be one of the Beacon.Status
-- enum values (case insensitive). Accepts multiple filters which will be
-- combined with OR logic. * **stability:\`\`** For example:
-- **stability:mobile** Returns beacons whose expected stability matches
-- the given value. Values must be one of the Beacon.Stability enum values
-- (case insensitive). Accepts multiple filters which will be combined with
-- OR logic. * **place\\_id:\`\"\"\`** For example:
-- **place\\_id:\"ChIJVSZzVR8FdkgRXGmmm6SslKw=\"** Returns beacons
-- explicitly registered at the given place, expressed as a Place ID
-- obtained from [Google Places API](\/places\/place-id). Does not match
-- places inside the given place. Does not consider the beacon\'s actual
-- location (which may be different from its registered place). Accepts
-- multiple filters that will be combined with OR logic. The place ID must
-- be double-quoted. * **registration\\_time\`[\<|>|\<=|>=]\`** For
-- example: **registration\\_time>=1433116800** Returns beacons whose
-- registration time matches the given filter. Supports the operators: \<,
-- >, \<=, and >=. Timestamp must be expressed as an integer number of
-- seconds since midnight January 1, 1970 UTC. Accepts at most two filters
-- that will be combined with AND logic, to support \"between\" semantics.
-- If more than two are supplied, the latter ones are ignored. * **lat:\`
-- lng: radius:\`** For example: **lat:51.1232343 lng:-1.093852
-- radius:1000** Returns beacons whose registered location is within the
-- given circle. When any of these fields are given, all are required.
-- Latitude and longitude must be decimal degrees between -90.0 and 90.0
-- and between -180.0 and 180.0 respectively. Radius must be an integer
-- number of meters between 10 and 1,000,000 (1000 km). *
-- **property:\`\"=\"\`** For example: **property:\"battery-type=CR2032\"**
-- Returns beacons which have a property of the given name and value.
-- Supports multiple filters which will be combined with OR logic. The
-- entire name=value string must be double-quoted as one string. *
-- **attachment\\_type:\`\"\"\`** For example:
-- **attachment_type:\"my-namespace\/my-type\"** Returns beacons having at
-- least one attachment of the given namespaced type. Supports \"any within
-- this namespace\" via the partial wildcard syntax: \"my-namespace\/*\".
-- Supports multiple filters which will be combined with OR logic. The
-- string must be double-quoted. * **indoor\\_level:\`\"\"\`** For example:
-- **indoor\\_level:\"1\"** Returns beacons which are located on the given
-- indoor level. Accepts multiple filters that will be combined with OR
-- logic. Multiple filters on the same field are combined with OR logic
-- (except registration_time which is combined with AND logic). Multiple
-- filters on different fields are combined with AND logic. Filters should
-- be separated by spaces. As with any HTTP query string parameter, the
-- whole filter expression must be URL-encoded. Example REST request: \`GET
-- \/v1beta1\/beacons?q=status:active%20lat:51.123%20lng:-1.095%20radius:1000\`
blQ :: Lens' BeaconsList (Maybe Text)
blQ = lens _blQ (\ s a -> s{_blQ = a})
-- | A pagination token obtained from a previous request to list beacons.
blPageToken :: Lens' BeaconsList (Maybe Text)
blPageToken
= lens _blPageToken (\ s a -> s{_blPageToken = a})
-- | The project id to list beacons under. If not present then the project
-- credential that made the request is used as the project. Optional.
blProjectId :: Lens' BeaconsList (Maybe Text)
blProjectId
= lens _blProjectId (\ s a -> s{_blProjectId = a})
-- | The maximum number of records to return for this request, up to a
-- server-defined upper limit.
blPageSize :: Lens' BeaconsList (Maybe Int32)
blPageSize
= lens _blPageSize (\ s a -> s{_blPageSize = a}) .
mapping _Coerce
-- | JSONP
blCallback :: Lens' BeaconsList (Maybe Text)
blCallback
= lens _blCallback (\ s a -> s{_blCallback = a})
instance GoogleRequest BeaconsList where
type Rs BeaconsList = ListBeaconsResponse
type Scopes BeaconsList =
'["https://www.googleapis.com/auth/userlocation.beacon.registry"]
requestClient BeaconsList'{..}
= go _blXgafv _blUploadProtocol _blAccessToken
_blUploadType
_blQ
_blPageToken
_blProjectId
_blPageSize
_blCallback
(Just AltJSON)
proximityBeaconService
where go
= buildClient (Proxy :: Proxy BeaconsListResource)
mempty
|
brendanhay/gogol
|
gogol-proximitybeacon/gen/Network/Google/Resource/ProximityBeacon/Beacons/List.hs
|
mpl-2.0
| 9,696
| 0
| 19
| 1,972
| 1,021
| 613
| 408
| 130
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SWF.PollForDecisionTask
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Used by deciders to get a 'DecisionTask' from the specified decision 'taskList'.
-- A decision task may be returned for any open workflow execution that is using
-- the specified task list. The task includes a paginated view of the history of
-- the workflow execution. The decider should use the workflow type and the
-- history to determine how to properly handle the task.
--
-- This action initiates a long poll, where the service holds the HTTP
-- connection open and responds as soon a task becomes available. If no decision
-- task is available in the specified task list before the timeout of 60 seconds
-- expires, an empty result is returned. An empty result, in this context, means
-- that a DecisionTask is returned, but that the value of taskToken is an empty
-- string.
--
-- Deciders should set their client side socket timeout to at least 70 seconds
-- (10 seconds higher than the timeout). Because the number of workflow history
-- events for a single workflow execution might be very large, the result
-- returned might be split up across a number of pages. To retrieve subsequent
-- pages, make additional calls to 'PollForDecisionTask' using the 'nextPageToken'
-- returned by the initial call. Note that you do not call 'GetWorkflowExecutionHistory' with this 'nextPageToken'. Instead, call 'PollForDecisionTask' again. Access
-- Control
--
-- You can use IAM policies to control this action's access to Amazon SWF
-- resources as follows:
--
-- Use a 'Resource' element with the domain name to limit the action to only
-- specified domains. Use an 'Action' element to allow or deny permission to call
-- this action. Constrain the 'taskList.name' parameter by using a Condition
-- element with the 'swf:taskList.name' key to allow the action to access only
-- certain task lists. If the caller does not have sufficient permissions to
-- invoke the action, or the parameter values fall outside the specified
-- constraints, the action fails. The associated event attribute's cause
-- parameter will be set to OPERATION_NOT_PERMITTED. For details and example IAM
-- policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_PollForDecisionTask.html>
module Network.AWS.SWF.PollForDecisionTask
(
-- * Request
PollForDecisionTask
-- ** Request constructor
, pollForDecisionTask
-- ** Request lenses
, pfdtDomain
, pfdtIdentity
, pfdtMaximumPageSize
, pfdtNextPageToken
, pfdtReverseOrder
, pfdtTaskList
-- * Response
, PollForDecisionTaskResponse
-- ** Response constructor
, pollForDecisionTaskResponse
-- ** Response lenses
, pfdtrEvents
, pfdtrNextPageToken
, pfdtrPreviousStartedEventId
, pfdtrStartedEventId
, pfdtrTaskToken
, pfdtrWorkflowExecution
, pfdtrWorkflowType
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SWF.Types
import qualified GHC.Exts
data PollForDecisionTask = PollForDecisionTask
{ _pfdtDomain :: Text
, _pfdtIdentity :: Maybe Text
, _pfdtMaximumPageSize :: Maybe Nat
, _pfdtNextPageToken :: Maybe Text
, _pfdtReverseOrder :: Maybe Bool
, _pfdtTaskList :: TaskList
} deriving (Eq, Read, Show)
-- | 'PollForDecisionTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pfdtDomain' @::@ 'Text'
--
-- * 'pfdtIdentity' @::@ 'Maybe' 'Text'
--
-- * 'pfdtMaximumPageSize' @::@ 'Maybe' 'Natural'
--
-- * 'pfdtNextPageToken' @::@ 'Maybe' 'Text'
--
-- * 'pfdtReverseOrder' @::@ 'Maybe' 'Bool'
--
-- * 'pfdtTaskList' @::@ 'TaskList'
--
pollForDecisionTask :: Text -- ^ 'pfdtDomain'
-> TaskList -- ^ 'pfdtTaskList'
-> PollForDecisionTask
pollForDecisionTask p1 p2 = PollForDecisionTask
{ _pfdtDomain = p1
, _pfdtTaskList = p2
, _pfdtIdentity = Nothing
, _pfdtNextPageToken = Nothing
, _pfdtMaximumPageSize = Nothing
, _pfdtReverseOrder = Nothing
}
-- | The name of the domain containing the task lists to poll.
pfdtDomain :: Lens' PollForDecisionTask Text
pfdtDomain = lens _pfdtDomain (\s a -> s { _pfdtDomain = a })
-- | Identity of the decider making the request, which is recorded in the
-- DecisionTaskStarted event in the workflow history. This enables diagnostic
-- tracing when problems arise. The form of this identity is user defined.
pfdtIdentity :: Lens' PollForDecisionTask (Maybe Text)
pfdtIdentity = lens _pfdtIdentity (\s a -> s { _pfdtIdentity = a })
-- | The maximum number of results that will be returned per call. 'nextPageToken'
-- can be used to obtain futher pages of results. The default is 100, which is
-- the maximum allowed page size. You can, however, specify a page size /smaller/
-- than 100.
--
-- This is an upper limit only; the actual number of results returned per call
-- may be fewer than the specified maximum.
pfdtMaximumPageSize :: Lens' PollForDecisionTask (Maybe Natural)
pfdtMaximumPageSize =
lens _pfdtMaximumPageSize (\s a -> s { _pfdtMaximumPageSize = a })
. mapping _Nat
-- | If a 'NextPageToken' was returned by a previous call, there are more results
-- available. To retrieve the next page of results, make the call again using
-- the returned token in 'nextPageToken'. Keep all other arguments unchanged.
--
-- The configured 'maximumPageSize' determines how many results can be returned
-- in a single call.
--
-- The 'nextPageToken' returned by this action cannot be used with 'GetWorkflowExecutionHistory' to get the next page. You must call 'PollForDecisionTask' again (with the 'nextPageToken') to retrieve the next page of history records. Calling 'PollForDecisionTask'
-- with a 'nextPageToken' will not return a new decision task..
pfdtNextPageToken :: Lens' PollForDecisionTask (Maybe Text)
pfdtNextPageToken =
lens _pfdtNextPageToken (\s a -> s { _pfdtNextPageToken = a })
-- | When set to 'true', returns the events in reverse order. By default the results
-- are returned in ascending order of the 'eventTimestamp' of the events.
pfdtReverseOrder :: Lens' PollForDecisionTask (Maybe Bool)
pfdtReverseOrder = lens _pfdtReverseOrder (\s a -> s { _pfdtReverseOrder = a })
-- | Specifies the task list to poll for decision tasks.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '/' (slash), '|' (vertical bar), or any control characters
-- (\u0000-\u001f | \u007f - \u009f). Also, it must not contain the literal
-- string quotarnquot.
pfdtTaskList :: Lens' PollForDecisionTask TaskList
pfdtTaskList = lens _pfdtTaskList (\s a -> s { _pfdtTaskList = a })
data PollForDecisionTaskResponse = PollForDecisionTaskResponse
{ _pfdtrEvents :: List "events" HistoryEvent
, _pfdtrNextPageToken :: Maybe Text
, _pfdtrPreviousStartedEventId :: Maybe Integer
, _pfdtrStartedEventId :: Integer
, _pfdtrTaskToken :: Text
, _pfdtrWorkflowExecution :: WorkflowExecution
, _pfdtrWorkflowType :: WorkflowType
} deriving (Eq, Read, Show)
-- | 'PollForDecisionTaskResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pfdtrEvents' @::@ ['HistoryEvent']
--
-- * 'pfdtrNextPageToken' @::@ 'Maybe' 'Text'
--
-- * 'pfdtrPreviousStartedEventId' @::@ 'Maybe' 'Integer'
--
-- * 'pfdtrStartedEventId' @::@ 'Integer'
--
-- * 'pfdtrTaskToken' @::@ 'Text'
--
-- * 'pfdtrWorkflowExecution' @::@ 'WorkflowExecution'
--
-- * 'pfdtrWorkflowType' @::@ 'WorkflowType'
--
pollForDecisionTaskResponse :: Text -- ^ 'pfdtrTaskToken'
-> Integer -- ^ 'pfdtrStartedEventId'
-> WorkflowExecution -- ^ 'pfdtrWorkflowExecution'
-> WorkflowType -- ^ 'pfdtrWorkflowType'
-> PollForDecisionTaskResponse
pollForDecisionTaskResponse p1 p2 p3 p4 = PollForDecisionTaskResponse
{ _pfdtrTaskToken = p1
, _pfdtrStartedEventId = p2
, _pfdtrWorkflowExecution = p3
, _pfdtrWorkflowType = p4
, _pfdtrEvents = mempty
, _pfdtrNextPageToken = Nothing
, _pfdtrPreviousStartedEventId = Nothing
}
-- | A paginated list of history events of the workflow execution. The decider
-- uses this during the processing of the decision task.
pfdtrEvents :: Lens' PollForDecisionTaskResponse [HistoryEvent]
pfdtrEvents = lens _pfdtrEvents (\s a -> s { _pfdtrEvents = a }) . _List
-- | If a 'NextPageToken' was returned by a previous call, there are more results
-- available. To retrieve the next page of results, make the call again using
-- the returned token in 'nextPageToken'. Keep all other arguments unchanged.
--
-- The configured 'maximumPageSize' determines how many results can be returned
-- in a single call.
pfdtrNextPageToken :: Lens' PollForDecisionTaskResponse (Maybe Text)
pfdtrNextPageToken =
lens _pfdtrNextPageToken (\s a -> s { _pfdtrNextPageToken = a })
-- | The id of the DecisionTaskStarted event of the previous decision task of this
-- workflow execution that was processed by the decider. This can be used to
-- determine the events in the history new since the last decision task received
-- by the decider.
pfdtrPreviousStartedEventId :: Lens' PollForDecisionTaskResponse (Maybe Integer)
pfdtrPreviousStartedEventId =
lens _pfdtrPreviousStartedEventId
(\s a -> s { _pfdtrPreviousStartedEventId = a })
-- | The id of the 'DecisionTaskStarted' event recorded in the history.
pfdtrStartedEventId :: Lens' PollForDecisionTaskResponse Integer
pfdtrStartedEventId =
lens _pfdtrStartedEventId (\s a -> s { _pfdtrStartedEventId = a })
-- | The opaque string used as a handle on the task. This token is used by workers
-- to communicate progress and response information back to the system about the
-- task.
pfdtrTaskToken :: Lens' PollForDecisionTaskResponse Text
pfdtrTaskToken = lens _pfdtrTaskToken (\s a -> s { _pfdtrTaskToken = a })
-- | The workflow execution for which this decision task was created.
pfdtrWorkflowExecution :: Lens' PollForDecisionTaskResponse WorkflowExecution
pfdtrWorkflowExecution =
lens _pfdtrWorkflowExecution (\s a -> s { _pfdtrWorkflowExecution = a })
-- | The type of the workflow execution for which this decision task was created.
pfdtrWorkflowType :: Lens' PollForDecisionTaskResponse WorkflowType
pfdtrWorkflowType =
lens _pfdtrWorkflowType (\s a -> s { _pfdtrWorkflowType = a })
instance ToPath PollForDecisionTask where
toPath = const "/"
instance ToQuery PollForDecisionTask where
toQuery = const mempty
instance ToHeaders PollForDecisionTask
instance ToJSON PollForDecisionTask where
toJSON PollForDecisionTask{..} = object
[ "domain" .= _pfdtDomain
, "taskList" .= _pfdtTaskList
, "identity" .= _pfdtIdentity
, "nextPageToken" .= _pfdtNextPageToken
, "maximumPageSize" .= _pfdtMaximumPageSize
, "reverseOrder" .= _pfdtReverseOrder
]
instance AWSRequest PollForDecisionTask where
type Sv PollForDecisionTask = SWF
type Rs PollForDecisionTask = PollForDecisionTaskResponse
request = post "PollForDecisionTask"
response = jsonResponse
instance FromJSON PollForDecisionTaskResponse where
parseJSON = withObject "PollForDecisionTaskResponse" $ \o -> PollForDecisionTaskResponse
<$> o .:? "events" .!= mempty
<*> o .:? "nextPageToken"
<*> o .:? "previousStartedEventId"
<*> o .: "startedEventId"
<*> o .: "taskToken"
<*> o .: "workflowExecution"
<*> o .: "workflowType"
instance AWSPager PollForDecisionTask where
page rq rs
| stop (rs ^. pfdtrNextPageToken) = Nothing
| otherwise = (\x -> rq & pfdtNextPageToken ?~ x)
<$> (rs ^. pfdtrNextPageToken)
|
dysinger/amazonka
|
amazonka-swf/gen/Network/AWS/SWF/PollForDecisionTask.hs
|
mpl-2.0
| 13,123
| 0
| 22
| 2,742
| 1,368
| 829
| 539
| 140
| 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.CloudAsset.BatchGetAssetsHistory
-- 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)
--
-- Batch gets the update history of assets that overlap a time window. For
-- RESOURCE content, this API outputs history with asset in both non-delete
-- or deleted status. For IAM_POLICY content, this API outputs history when
-- the asset and its attached IAM POLICY both exist. This can create gaps
-- in the output history. If a specified asset does not exist, this API
-- returns an INVALID_ARGUMENT error.
--
-- /See:/ <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/quickstart-cloud-asset-inventory Cloud Asset API Reference> for @cloudasset.batchGetAssetsHistory@.
module Network.Google.Resource.CloudAsset.BatchGetAssetsHistory
(
-- * REST Resource
BatchGetAssetsHistoryResource
-- * Creating a Request
, batchGetAssetsHistory
, BatchGetAssetsHistory
-- * Request Lenses
, bgahParent
, bgahXgafv
, bgahReadTimeWindowEndTime
, bgahUploadProtocol
, bgahAccessToken
, bgahUploadType
, bgahAssetNames
, bgahReadTimeWindowStartTime
, bgahContentType
, bgahCallback
) where
import Network.Google.CloudAsset.Types
import Network.Google.Prelude
-- | A resource alias for @cloudasset.batchGetAssetsHistory@ method which the
-- 'BatchGetAssetsHistory' request conforms to.
type BatchGetAssetsHistoryResource =
"v1" :>
CaptureMode "parent" "batchGetAssetsHistory" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "readTimeWindow.endTime" DateTime' :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParams "assetNames" Text :>
QueryParam "readTimeWindow.startTime" DateTime' :>
QueryParam "contentType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] BatchGetAssetsHistoryResponse
-- | Batch gets the update history of assets that overlap a time window. For
-- RESOURCE content, this API outputs history with asset in both non-delete
-- or deleted status. For IAM_POLICY content, this API outputs history when
-- the asset and its attached IAM POLICY both exist. This can create gaps
-- in the output history. If a specified asset does not exist, this API
-- returns an INVALID_ARGUMENT error.
--
-- /See:/ 'batchGetAssetsHistory' smart constructor.
data BatchGetAssetsHistory =
BatchGetAssetsHistory'
{ _bgahParent :: !Text
, _bgahXgafv :: !(Maybe Xgafv)
, _bgahReadTimeWindowEndTime :: !(Maybe DateTime')
, _bgahUploadProtocol :: !(Maybe Text)
, _bgahAccessToken :: !(Maybe Text)
, _bgahUploadType :: !(Maybe Text)
, _bgahAssetNames :: !(Maybe [Text])
, _bgahReadTimeWindowStartTime :: !(Maybe DateTime')
, _bgahContentType :: !(Maybe Text)
, _bgahCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BatchGetAssetsHistory' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bgahParent'
--
-- * 'bgahXgafv'
--
-- * 'bgahReadTimeWindowEndTime'
--
-- * 'bgahUploadProtocol'
--
-- * 'bgahAccessToken'
--
-- * 'bgahUploadType'
--
-- * 'bgahAssetNames'
--
-- * 'bgahReadTimeWindowStartTime'
--
-- * 'bgahContentType'
--
-- * 'bgahCallback'
batchGetAssetsHistory
:: Text -- ^ 'bgahParent'
-> BatchGetAssetsHistory
batchGetAssetsHistory pBgahParent_ =
BatchGetAssetsHistory'
{ _bgahParent = pBgahParent_
, _bgahXgafv = Nothing
, _bgahReadTimeWindowEndTime = Nothing
, _bgahUploadProtocol = Nothing
, _bgahAccessToken = Nothing
, _bgahUploadType = Nothing
, _bgahAssetNames = Nothing
, _bgahReadTimeWindowStartTime = Nothing
, _bgahContentType = Nothing
, _bgahCallback = Nothing
}
-- | Required. The relative name of the root asset. It can only be an
-- organization number (such as \"organizations\/123\"), a project ID (such
-- as \"projects\/my-project-id\")\", or a project number (such as
-- \"projects\/12345\").
bgahParent :: Lens' BatchGetAssetsHistory Text
bgahParent
= lens _bgahParent (\ s a -> s{_bgahParent = a})
-- | V1 error format.
bgahXgafv :: Lens' BatchGetAssetsHistory (Maybe Xgafv)
bgahXgafv
= lens _bgahXgafv (\ s a -> s{_bgahXgafv = a})
-- | End time of the time window (inclusive). Current timestamp if not
-- specified.
bgahReadTimeWindowEndTime :: Lens' BatchGetAssetsHistory (Maybe UTCTime)
bgahReadTimeWindowEndTime
= lens _bgahReadTimeWindowEndTime
(\ s a -> s{_bgahReadTimeWindowEndTime = a})
. mapping _DateTime
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bgahUploadProtocol :: Lens' BatchGetAssetsHistory (Maybe Text)
bgahUploadProtocol
= lens _bgahUploadProtocol
(\ s a -> s{_bgahUploadProtocol = a})
-- | OAuth access token.
bgahAccessToken :: Lens' BatchGetAssetsHistory (Maybe Text)
bgahAccessToken
= lens _bgahAccessToken
(\ s a -> s{_bgahAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bgahUploadType :: Lens' BatchGetAssetsHistory (Maybe Text)
bgahUploadType
= lens _bgahUploadType
(\ s a -> s{_bgahUploadType = a})
-- | A list of the full names of the assets. For example:
-- \`\/\/compute.googleapis.com\/projects\/my_project_123\/zones\/zone1\/instances\/instance1\`.
-- See [Resource
-- Names](https:\/\/cloud.google.com\/apis\/design\/resource_names#full_resource_name)
-- and [Resource Name
-- Format](https:\/\/cloud.google.com\/resource-manager\/docs\/cloud-asset-inventory\/resource-name-format)
-- for more info. The request becomes a no-op if the asset name list is
-- empty, and the max size of the asset name list is 100 in one request.
bgahAssetNames :: Lens' BatchGetAssetsHistory [Text]
bgahAssetNames
= lens _bgahAssetNames
(\ s a -> s{_bgahAssetNames = a})
. _Default
. _Coerce
-- | Start time of the time window (exclusive).
bgahReadTimeWindowStartTime :: Lens' BatchGetAssetsHistory (Maybe UTCTime)
bgahReadTimeWindowStartTime
= lens _bgahReadTimeWindowStartTime
(\ s a -> s{_bgahReadTimeWindowStartTime = a})
. mapping _DateTime
-- | Required. The content type.
bgahContentType :: Lens' BatchGetAssetsHistory (Maybe Text)
bgahContentType
= lens _bgahContentType
(\ s a -> s{_bgahContentType = a})
-- | JSONP
bgahCallback :: Lens' BatchGetAssetsHistory (Maybe Text)
bgahCallback
= lens _bgahCallback (\ s a -> s{_bgahCallback = a})
instance GoogleRequest BatchGetAssetsHistory where
type Rs BatchGetAssetsHistory =
BatchGetAssetsHistoryResponse
type Scopes BatchGetAssetsHistory =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient BatchGetAssetsHistory'{..}
= go _bgahParent _bgahXgafv
_bgahReadTimeWindowEndTime
_bgahUploadProtocol
_bgahAccessToken
_bgahUploadType
(_bgahAssetNames ^. _Default)
_bgahReadTimeWindowStartTime
_bgahContentType
_bgahCallback
(Just AltJSON)
cloudAssetService
where go
= buildClient
(Proxy :: Proxy BatchGetAssetsHistoryResource)
mempty
|
brendanhay/gogol
|
gogol-cloudasset/gen/Network/Google/Resource/CloudAsset/BatchGetAssetsHistory.hs
|
mpl-2.0
| 8,315
| 0
| 19
| 1,878
| 1,065
| 621
| 444
| 153
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.