code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE FlexibleContexts #-}
-- | Common pitch.
module Music.Pitch.Common.Pitch
(
-- * Accidentals
Accidental,
natural,
flat,
sharp,
doubleFlat,
doubleSharp,
-- ** Inspecting accidentals
isNatural,
isFlattened,
isSharpened,
isStandardAccidental,
-- ** Name
Name(..),
-- * Pitch
Pitch,
mkPitch,
name,
accidental,
-- ** Diatonic and chromatic pitch
upDiatonicP,
downDiatonicP,
upChromaticP,
downChromaticP,
invertDiatonicallyP,
invertChromaticallyP,
) where
import Control.Applicative
import Control.Monad
import Control.Lens hiding (simple)
import Data.AffineSpace
import Data.AffineSpace.Point
import qualified Data.Char as Char
import Data.Either
import qualified Data.List as List
import Data.Maybe
import Data.Semigroup
import Data.Typeable
import Data.Fixed (HasResolution(..), Fixed(..))
import Data.Ratio
import Data.VectorSpace
import Data.Aeson (ToJSON (..), FromJSON(..))
import qualified Data.Aeson
import Music.Pitch.Absolute
import Music.Pitch.Alterable
import Music.Pitch.Augmentable
import Music.Pitch.Common.Types
import Music.Pitch.Common.Number
import Music.Pitch.Common.Interval
import Music.Pitch.Common.Semitones
import Music.Pitch.Literal
sharp, flat, natural, doubleFlat, doubleSharp :: Accidental
-- | The double sharp accidental.
doubleSharp = 2
-- | The sharp accidental.
sharp = 1
-- | The natural accidental.
natural = 0
-- | The flat accidental.
flat = -1
-- | The double flat accidental.
doubleFlat = -2
isNatural, isSharpened, isFlattened :: Accidental -> Bool
-- | Returns whether this is a natural accidental.
isNatural = (== 0)
-- | Returns whether this is a sharp, double sharp etc.
isSharpened = (> 0)
-- | Returns whether this is a flat, double flat etc.
isFlattened = (< 0)
-- | Returns whether this is a standard accidental, i.e.
-- either a double flat, flat, natural, sharp or double sharp.
isStandardAccidental :: Accidental -> Bool
isStandardAccidental a = abs a < 2
-- was: isStandard
-- instance IsPitch Pitch where
-- fromPitch (PitchL (c, a, o)) =
-- Pitch $ (\a b -> (fromIntegral a, fromIntegral b)^.interval') (qual a) c ^+^ (_P8^* fromIntegral o)
-- where
-- qual Nothing = 0
-- qual (Just n) = round n
instance Enum Pitch where
toEnum = Pitch . (\a b -> (fromIntegral a, fromIntegral b)^.interval') 0 . fromIntegral
fromEnum = fromIntegral . pred . number . (.-. middleC)
instance Alterable Pitch where
sharpen (Pitch a) = Pitch (augment a)
flatten (Pitch a) = Pitch (diminish a)
instance Show Pitch where
show p = showName (name p) ++ showAccidental (accidental p) ++ showOctave (octaves $ getPitch p)
where
showName = fmap Char.toLower . show
showOctave n
| n > 0 = replicate (fromIntegral n) '\''
| otherwise = replicate (negate $ fromIntegral n) '_'
showAccidental n
| n > 0 = replicate (fromIntegral n) 's'
| otherwise = replicate (negate $ fromIntegral n) 'b'
instance Num Pitch where
Pitch a + Pitch b = Pitch (a + b)
negate (Pitch a) = Pitch (negate a)
abs (Pitch a) = Pitch (abs a)
(*) = error "Music.Pitch.Common.Pitch: no overloading for (*)"
signum = error "Music.Pitch.Common.Pitch: no overloading for signum"
fromInteger = toEnum . fromInteger
instance ToJSON Pitch where
toJSON = toJSON . (.-. middleC)
instance IsPitch Int where
fromPitch x = fromIntegral (fromPitch x :: Integer)
instance IsPitch Word where
fromPitch x = fromIntegral (fromPitch x :: Integer)
instance IsPitch Float where
fromPitch x = realToFrac (fromPitch x :: Double)
instance HasResolution a => IsPitch (Fixed a) where
fromPitch x = realToFrac (fromPitch x :: Double)
instance Integral a => IsPitch (Ratio a) where
fromPitch x = realToFrac (fromPitch x :: Double)
instance IsPitch Double where
fromPitch p = fromIntegral . semitones $ (p .-. c)
instance IsPitch Integer where
fromPitch p = fromIntegral . semitones $ (p .-. c)
instance IsPitch Pitch where
fromPitch = id
-- TODO bootstrapping, remove when/if possible
middleC = c
instance FromJSON Pitch where
parseJSON = fmap (middleC .+^) . parseJSON
-- |
-- Creates a pitch from name accidental.
--
mkPitch :: Name -> Accidental -> Pitch
mkPitch name acc = Pitch $ (\a b -> (fromIntegral a, fromIntegral b)^.interval') (fromIntegral acc) (fromEnum name)
-- |
-- Returns the name of a pitch.
--
-- To convert a pitch to a numeric type, use 'octaves', 'steps' or 'semitones'
-- on the relevant interval type, for example:
--
-- @
-- semitones ('a\'' .-. 'c')
-- @
--
name :: Pitch -> Name
name x
| i == 7 = toEnum 0 -- Arises for flat C etc.
| 0 <= i && i <= 6 = toEnum i
| otherwise = error $ "Pitch.name: Bad value " ++ show i
where
i = (fromIntegral . pred . number . simple . getPitch) x
-- |
-- Returns the accidental of a pitch.
--
-- See also 'octaves', and 'steps' and 'semitones'.
--
accidental :: Pitch -> Accidental
accidental = fromIntegral . intervalDiff . simple . getPitch
where
intervalDiff = view (from interval'._1)
upChromaticP :: Pitch -> ChromaticSteps -> Pitch -> Pitch
upChromaticP origin n = relative origin $ (_alteration +~ n)
downChromaticP :: Pitch -> ChromaticSteps -> Pitch -> Pitch
downChromaticP origin n = relative origin $ (_alteration -~ n)
upDiatonicP :: Pitch -> DiatonicSteps -> Pitch -> Pitch
upDiatonicP origin n = relative origin $ (_steps +~ n)
downDiatonicP :: Pitch -> DiatonicSteps -> Pitch -> Pitch
downDiatonicP origin n = relative origin $ (_steps -~ n)
invertDiatonicallyP :: Pitch -> Pitch -> Pitch
invertDiatonicallyP origin = relative origin $ (_steps %~ negate)
invertChromaticallyP :: Pitch -> Pitch -> Pitch
invertChromaticallyP origin = relative origin $ (_alteration %~ negate)
| music-suite/music-pitch | src/Music/Pitch/Common/Pitch.hs | bsd-3-clause | 6,271 | 0 | 13 | 1,609 | 1,558 | 858 | 700 | 126 | 1 |
module DocgenSpec where
import qualified Pact.Docgen as Docgen
import Test.Hspec
spec :: Spec
spec = runIO Docgen.main
| kadena-io/pact | tests/DocgenSpec.hs | bsd-3-clause | 131 | 0 | 6 | 29 | 32 | 20 | 12 | 5 | 1 |
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
-- | Entrypoint for normalizations for CoreS.AST.
-- This should be imported when writing normalizers.
-- It reexports CoreS.AST, Norm.NormM, NormalizationStrategies.
module Norm.NormCS (
NormalizerCU
, NormCUR
, NormCUA
, module RE
) where
import CoreS.AST as RE
import CoreS.ASTUtils as RE
import Norm.NormM as RE
import NormalizationStrategies as RE
-- | Normalizer for CompilationUnit.
type NormalizerCU = Normalizer CompilationUnit
-- | NormalizationRule for CompilationUnit:s.
-- This is the top level normalizer.
type NormCUR = NormalizationRule CompilationUnit
-- | Normalization arrow for CompilationUnit:s.
-- This is the top level normalizer arrow.
type NormCUA = NormArr CompilationUnit | DATX02-17-26/DATX02-17-26 | libsrc/Norm/NormCS.hs | gpl-2.0 | 1,570 | 0 | 5 | 301 | 83 | 57 | 26 | 12 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module DetailedTx where
import Data.Aeson hiding (decode')
import Data.Aeson.Types (Pair)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text as T
import Network.Haskoin.Crypto (pubKeyAddr,addrToBase58,derivePubKey,toWif)
import Network.Haskoin.Transaction (txHash)
import Network.Haskoin.Internals (Tx(..), TxIn(..), TxOut(..)
,scriptSender, scriptRecipient
,XPrvKey(..),XPubKey(..)
,xPrvIsHard,xPrvChild,xPubIsHard,xPubChild
)
import Network.Haskoin.Util (eitherToMaybe,decode')
import Utils (putHex)
import PrettyScript (showDoc, prettyScript)
(.=$) :: T.Text -> String -> Pair
(.=$) x y = x .= y
newtype DetailedTx = DetailedTx { _unDetailedTx :: Tx }
newtype DetailedTxIn = DetailedTxIn { _unDetailedTxIn :: TxIn }
newtype DetailedTxOut = DetailedTxOut { _unDetailedTxOut :: TxOut }
newtype DetailedXPrvKey = DetailedXPrvKey { _unDetailedXPrvKey :: XPrvKey }
newtype DetailedXPubKey = DetailedXPubKey { _unDetailedXPubKey :: XPubKey }
instance ToJSON DetailedTx where
toJSON (DetailedTx tx) =
object
["hash" .= txHash tx
,"version" .= txVersion tx
,"locktime" .= txLockTime tx
,"inputs" .= map DetailedTxIn (txIn tx)
,"outputs" .= map DetailedTxOut (txOut tx)
]
instance ToJSON DetailedTxIn where
toJSON (DetailedTxIn i) =
object
["previous_output" .= prevOutput i
,"script" .= showDoc (prettyScript script)
,"sequence" .= txInSequence i
,"address" .= eitherToMaybe (scriptSender script)
]
where script = decode' $ scriptInput i
instance ToJSON DetailedTxOut where
toJSON (DetailedTxOut o) =
object
["value" .= outValue o
,"script" .= showDoc (prettyScript script)
,"address" .= eitherToMaybe (scriptRecipient script)
]
where script = decode' $ scriptOutput o
instance ToJSON DetailedXPrvKey where
toJSON (DetailedXPrvKey k) =
object
["type" .=$ "xprv"
,"depth" .= xPrvDepth k
,"parent" .= xPrvParent k
,"index" .= object ["value" .= xPrvIndex k
,(if xPrvIsHard k then "hard" else "soft") .= xPrvChild k
]
,"chain" .= xPrvChain k
,"prvkey" .= toWif (xPrvKey k)
,"pubkey" .=$ putHex pub
,"address" .= addrToBase58 addr
]
where pub = derivePubKey (xPrvKey k)
addr = pubKeyAddr pub
instance ToJSON DetailedXPubKey where
toJSON (DetailedXPubKey k) =
object
["type" .=$ "xpub"
,"depth" .= xPubDepth k
,"parent" .= xPubParent k
,"index" .= object ["value" .= xPubIndex k
,(if xPubIsHard k then "hard" else "soft") .= xPubChild k
]
,"chain" .= xPubChain k
,"pubkey" .=$ putHex pub
,"address" .= addrToBase58 addr
]
where pub = xPubKey k
addr = pubKeyAddr pub
txDetailedJSON :: Tx -> LBS.ByteString
txDetailedJSON = encode . toJSON . DetailedTx
| haskoin/hx | DetailedTx.hs | gpl-3.0 | 3,195 | 0 | 14 | 945 | 864 | 478 | 386 | 74 | 1 |
main = f "abc\ndef"
f "abc\ndef" = 3
| roberth/uu-helium | test/correct/EscapeInString.hs | gpl-3.0 | 38 | 0 | 5 | 9 | 17 | 8 | 9 | 2 | 1 |
{-
Copyright 2012-2013 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# Language FlexibleInstances, TypeSynonymInstances #-}
module Plush.Run.Posix.Utilities (
-- * Input convenience functions
PosixInStr(..),
readAllFile,
writeAllFile,
-- * Output convenience functions
-- $outstr
PosixOutStr(..),
outStr, outStrLn, errStr, errStrLn, jsonOut,
writeStr, writeStrLn,
-- * File and directory existance
doesFileExist, doesDirectoryExist,
createPath,
-- * Path simplification
simplifyPath, reducePath,
) where
import Control.Monad.Exception (bracket, catchIOError)
import Control.Monad (unless)
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Encoding as LT
import System.FilePath
import qualified System.Posix.Files as P
import Plush.Run.Posix
-- | String like classes that can be used with 'readAll' and friends.
-- Instances for strings use lenient UTF-8 decoding.
class PosixInStr s where
fromByteString :: L.ByteString -> s
instance PosixInStr B.ByteString where
fromByteString = B.concat . L.toChunks
instance PosixInStr L.ByteString where
fromByteString = id
instance PosixInStr String where
fromByteString = LT.unpack . fromByteString
instance PosixInStr LT.Text where
fromByteString = LT.decodeUtf8With T.lenientDecode
instance PosixInStr T.Text where
fromByteString = LT.toStrict . fromByteString
-- | Read all of a file.
readAllFile :: (PosixLike m, PosixInStr s) => FilePath -> m s
readAllFile fp = fmap fromByteString $ bracket open closeFd readAll
where
open = openFd fp ReadOnly Nothing defaultFileFlags
-- | Write all of a file.
writeAllFile :: (PosixLike m, PosixOutStr s) => FilePath -> s -> m ()
writeAllFile fp s = bracket open closeFd (flip write $ toByteString s)
where
open = openFd fp WriteOnly (Just ownerRWMode) fileFlags
ownerRWMode = P.ownerReadMode `P.unionFileModes` P.ownerWriteMode
fileFlags = defaultFileFlags { trunc = True }
-- $outstr
-- Use these in place of 'putStr' and 'putStrLn', (as well as
-- 'hPutStr' and 'hPutStrLn').
-- Note that these are unbuffered.
-- | String like classes that can be used with 'outStr' and friends.
class PosixOutStr s where
toByteString :: s -> L.ByteString
toByteStringLn :: s -> L.ByteString
toByteStringLn = flip L.snoc nl . toByteString
where nl = toEnum $ fromEnum '\n'
instance PosixOutStr B.ByteString where
toByteString = L.fromChunks . (:[])
instance PosixOutStr L.ByteString where
toByteString = id
instance PosixOutStr String where
toByteString = toByteString . LT.pack
toByteStringLn = toByteStringLn . LT.pack
instance PosixOutStr LT.Text where
toByteString = LT.encodeUtf8
toByteStringLn = LT.encodeUtf8 . flip LT.snoc '\n'
instance PosixOutStr T.Text where
toByteString = L.fromChunks . (:[]) . T.encodeUtf8
toByteStringLn = L.fromChunks . (:[B.singleton nl]) . T.encodeUtf8
where nl = toEnum $ fromEnum '\n'
writeStr, writeStrLn :: (PosixOutStr s, PosixLike m) => Fd -> s -> m ()
writeStr fd = write fd . toByteString
writeStrLn fd = write fd . toByteStringLn
outStr, outStrLn, errStr, errStrLn :: (PosixOutStr s, PosixLike m) => s -> m ()
outStr = writeStr stdOutput
errStr = writeStr stdError
outStrLn = writeStrLn stdOutput
errStrLn = writeStrLn stdError
jsonOut :: (A.ToJSON a, PosixLike m) => a -> m ()
jsonOut = write stdJsonOutput . A.encode
-- | Safe query, in that all 'IOError's are mapped to 'False'. For example, if
-- the file does exist, but the user can't read it, this will return 'False'.
doesFileExist :: (PosixLike m) => FilePath -> m Bool
doesFileExist fp =
catchIOError (getFileStatus fp >>= return . isRegularFile) (\_ -> return False)
-- | Safe query, in that all 'IOError's are mapped to 'False'. For example, if
-- the dir does exist, but the user can't read it, this will return 'False'.
doesDirectoryExist :: (PosixLike m) => FilePath -> m Bool
doesDirectoryExist fp =
catchIOError (getFileStatus fp >>= return . isDirectory) (\_ -> return False)
-- | Try to ensure that a directory, and all its parents exist, creating them
-- if needed with the given access mode. Note that due to permissions or other
-- issues this can fail with various thrown excpetions.
createPath :: (PosixLike m) => FilePath -> FileMode -> m ()
createPath fp mode = do
s <- (isDirectory `fmap` getFileStatus fp)
`catchIOError` (const $ return False)
unless s $ do
createPath (takeDirectory fp) mode
createDirectory fp mode
-- | Simplify a file path, elminiating . and .. components (if possible)
simplifyPath :: FilePath -> FilePath
simplifyPath = joinPath . reverse . reducePath
-- | Reduce the path, elminiating . and .. components if possible.
-- Returns a list of path elements, in reverse order. Each has no slash,
-- except the last, which is a single slash if the path is absolute.
reducePath :: FilePath -> [String]
reducePath = simp [] . splitDirectories
where
simp ys [] = ys
simp ys (('/':_):xs) = simp ("/":ys) xs
simp ys ( ".":xs) = simp ys xs
simp ya@(y:ys) ("..":xs)
| y == "/" = simp ya xs
| y /= ".." = simp ys xs
simp ys ( x:xs) = simp (x:ys) xs
| mzero/plush | src/Plush/Run/Posix/Utilities.hs | apache-2.0 | 6,077 | 0 | 12 | 1,235 | 1,361 | 751 | 610 | 97 | 5 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section{@Vars@: Variables}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
-- |
-- #name_types#
-- GHC uses several kinds of name internally:
--
-- * 'OccName.OccName': see "OccName#name_types"
--
-- * 'RdrName.RdrName': see "RdrName#name_types"
--
-- * 'Name.Name': see "Name#name_types"
--
-- * 'Id.Id': see "Id#name_types"
--
-- * 'Var.Var' is a synonym for the 'Id.Id' type but it may additionally
-- potentially contain type variables, which have a 'TypeRep.Kind'
-- rather than a 'TypeRep.Type' and only contain some extra
-- details during typechecking.
--
-- These 'Var.Var' names may either be global or local, see "Var#globalvslocal"
--
-- #globalvslocal#
-- Global 'Id's and 'Var's are those that are imported or correspond
-- to a data constructor, primitive operation, or record selectors.
-- Local 'Id's and 'Var's are those bound within an expression
-- (e.g. by a lambda) or at the top level of the module being compiled.
module Eta.BasicTypes.Var (
-- * The main data type and synonyms
Var, CoVar, Id, DictId, DFunId, EvVar, EqVar, EvId, IpId,
TyVar, TypeVar, KindVar, TKVar, TyCoVar,
-- ** Taking 'Var's apart
varName, varUnique, varType,
-- ** Modifying 'Var's
setVarName, setVarUnique, setVarType,
-- ** Constructing, taking apart, modifying 'Id's
mkGlobalVar, mkLocalVar, mkExportedLocalVar, mkCoVar,
idInfo, idDetails,
lazySetIdInfo, setIdDetails, globaliseId,
setIdExported, setIdNotExported,
-- ** Predicates
isId, isTKVar, isTyVar, isTcTyVar,
isLocalVar, isLocalId,
isGlobalId, isExportedId,
mustHaveLocalBinding,
-- ** Constructing 'TyVar's
mkTyVar, mkTcTyVar, mkKindVar,
-- ** Taking 'TyVar's apart
tyVarName, tyVarKind, tcTyVarDetails, setTcTyVarDetails,
-- ** Modifying 'TyVar's
setTyVarName, setTyVarUnique, setTyVarKind, updateTyVarKind,
updateTyVarKindM
) where
#include "HsVersions.h"
import {-# SOURCE #-} Eta.Types.TypeRep( Type, Kind, SuperKind )
import {-# SOURCE #-} Eta.TypeCheck.TcType( TcTyVarDetails, pprTcTyVarDetails )
import {-# SOURCE #-} Eta.BasicTypes.IdInfo( IdDetails, IdInfo, coVarDetails, vanillaIdInfo, pprIdDetails )
import Eta.BasicTypes.Name hiding (varName)
import Eta.BasicTypes.Unique
import Eta.Utils.Util
import Eta.Utils.FastString
import Eta.Utils.Outputable
import Data.Data
{-
************************************************************************
* *
Synonyms
* *
************************************************************************
-- These synonyms are here and not in Id because otherwise we need a very
-- large number of SOURCE imports of Id.hs :-(
-}
type Id = Var -- A term-level identifier
type TyVar = Var -- Type *or* kind variable (historical)
type TKVar = Var -- Type *or* kind variable (historical)
type TypeVar = Var -- Definitely a type variable
type KindVar = Var -- Definitely a kind variable
-- See Note [Kind and type variables]
-- See Note [Evidence: EvIds and CoVars]
type EvId = Id -- Term-level evidence: DictId, IpId, or EqVar
type EvVar = EvId -- ...historical name for EvId
type DFunId = Id -- A dictionary function
type DictId = EvId -- A dictionary variable
type IpId = EvId -- A term-level implicit parameter
type EqVar = EvId -- Boxed equality evidence
type CoVar = Id -- See Note [Evidence: EvIds and CoVars]
-- | Type or Coercion Variable
type TyCoVar = Id -- Type, *or* coercion variable
-- predicate: isTyCoVar
{-
Note [Evidence: EvIds and CoVars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* An EvId (evidence Id) is a *boxed*, term-level evidence variable
(dictionary, implicit parameter, or equality).
* A CoVar (coercion variable) is an *unboxed* term-level evidence variable
of type (t1 ~# t2). So it's the unboxed version of an EqVar.
* Only CoVars can occur in Coercions, EqVars appear in TcCoercions.
* DictId, IpId, and EqVar are synonyms when we know what kind of
evidence we are talking about. For example, an EqVar has type (t1 ~ t2).
Note [Kind and type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Before kind polymorphism, TyVar were used to mean type variables. Now
they are use to mean kind *or* type variables. KindVar is used when we
know for sure that it is a kind variable. In future, we might want to
go over the whole compiler code to use:
- TKVar to mean kind or type variables
- TypeVar to mean type variables only
- KindVar to mean kind variables
************************************************************************
* *
\subsection{The main data type declarations}
* *
************************************************************************
Every @Var@ has a @Unique@, to uniquify it and for fast comparison, a
@Type@, and an @IdInfo@ (non-essential info about it, e.g.,
strictness). The essential info about different kinds of @Vars@ is
in its @VarDetails@.
-}
-- | Essentially a typed 'Name', that may also contain some additional information
-- about the 'Var' and it's use sites.
data Var
= TyVar { -- Type and kind variables
-- see Note [Kind and type variables]
varName :: !Name,
realUnique :: {-# UNPACK #-} !Int,
-- ^ Key for fast comparison
-- Identical to the Unique in the name,
-- cached here for speed
varType :: Kind -- ^ The type or kind of the 'Var' in question
}
| TcTyVar { -- Used only during type inference
-- Used for kind variables during
-- inference, as well
varName :: !Name,
realUnique :: {-# UNPACK #-} !Int,
varType :: Kind,
tc_tv_details :: TcTyVarDetails }
| Id {
varName :: !Name,
realUnique :: {-# UNPACK #-} !Int,
varType :: Type,
idScope :: IdScope,
id_details :: IdDetails, -- Stable, doesn't change
id_info :: IdInfo } -- Unstable, updated by simplifier
deriving Typeable
data IdScope -- See Note [GlobalId/LocalId]
= GlobalId
| LocalId ExportFlag
data ExportFlag
= NotExported -- ^ Not exported: may be discarded as dead code.
| Exported -- ^ Exported: kept alive
{-
Note [GlobalId/LocalId]
~~~~~~~~~~~~~~~~~~~~~~~
A GlobalId is
* always a constant (top-level)
* imported, or data constructor, or primop, or record selector
* has a Unique that is globally unique across the whole
GHC invocation (a single invocation may compile multiple modules)
* never treated as a candidate by the free-variable finder;
it's a constant!
A LocalId is
* bound within an expression (lambda, case, local let(rec))
* or defined at top level in the module being compiled
* always treated as a candidate by the free-variable finder
After CoreTidy, top-level LocalIds are turned into GlobalIds
-}
instance Outputable Var where
ppr var = ppr (varName var) <> getPprStyle (ppr_debug var)
ppr_debug :: Var -> PprStyle -> SDoc
ppr_debug (TyVar {}) sty
| debugStyle sty = brackets (ptext (sLit "tv"))
ppr_debug (TcTyVar {tc_tv_details = d}) sty
| dumpStyle sty || debugStyle sty = brackets (pprTcTyVarDetails d)
ppr_debug (Id { idScope = s, id_details = d }) sty
| debugStyle sty = brackets (ppr_id_scope s <> pprIdDetails d)
ppr_debug _ _ = empty
ppr_id_scope :: IdScope -> SDoc
ppr_id_scope GlobalId = ptext (sLit "gid")
ppr_id_scope (LocalId Exported) = ptext (sLit "lidx")
ppr_id_scope (LocalId NotExported) = ptext (sLit "lid")
instance NamedThing Var where
getName = varName
instance Uniquable Var where
getUnique = varUnique
instance Eq Var where
a == b = realUnique a == realUnique b
instance Ord Var where
a <= b = realUnique a <= realUnique b
a < b = realUnique a < realUnique b
a >= b = realUnique a >= realUnique b
a > b = realUnique a > realUnique b
a `compare` b = a `nonDetCmpVar` b
-- | Compare Vars by their Uniques.
-- This is what Ord Var does, provided here to make it explicit at the
-- call-site that it can introduce non-determinism.
-- See Note [Unique Determinism]
nonDetCmpVar :: Var -> Var -> Ordering
nonDetCmpVar a b = varUnique a `nonDetCmpUnique` varUnique b
instance Data Var where
-- don't traverse?
toConstr _ = abstractConstr "Var"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Var"
varUnique :: Var -> Unique
varUnique var = mkUniqueGrimily (realUnique var)
setVarUnique :: Var -> Unique -> Var
setVarUnique var uniq
= var { realUnique = getKey uniq,
varName = setNameUnique (varName var) uniq }
setVarName :: Var -> Name -> Var
setVarName var new_name
= var { realUnique = getKey (getUnique new_name),
varName = new_name }
setVarType :: Id -> Type -> Id
setVarType id ty = id { varType = ty }
{-
************************************************************************
* *
\subsection{Type and kind variables}
* *
************************************************************************
-}
tyVarName :: TyVar -> Name
tyVarName = varName
tyVarKind :: TyVar -> Kind
tyVarKind = varType
setTyVarUnique :: TyVar -> Unique -> TyVar
setTyVarUnique = setVarUnique
setTyVarName :: TyVar -> Name -> TyVar
setTyVarName = setVarName
setTyVarKind :: TyVar -> Kind -> TyVar
setTyVarKind tv k = tv {varType = k}
updateTyVarKind :: (Kind -> Kind) -> TyVar -> TyVar
updateTyVarKind update tv = tv {varType = update (tyVarKind tv)}
updateTyVarKindM :: (Monad m) => (Kind -> m Kind) -> TyVar -> m TyVar
updateTyVarKindM update tv
= do { k' <- update (tyVarKind tv)
; return $ tv {varType = k'} }
mkTyVar :: Name -> Kind -> TyVar
mkTyVar name kind = TyVar { varName = name
, realUnique = getKey (nameUnique name)
, varType = kind
}
mkTcTyVar :: Name -> Kind -> TcTyVarDetails -> TyVar
mkTcTyVar name kind details
= -- NB: 'kind' may be a coercion kind; cf, 'TcMType.newMetaCoVar'
TcTyVar { varName = name,
realUnique = getKey (nameUnique name),
varType = kind,
tc_tv_details = details
}
tcTyVarDetails :: TyVar -> TcTyVarDetails
tcTyVarDetails (TcTyVar { tc_tv_details = details }) = details
tcTyVarDetails var = pprPanic "tcTyVarDetails" (ppr var)
setTcTyVarDetails :: TyVar -> TcTyVarDetails -> TyVar
setTcTyVarDetails tv details = tv { tc_tv_details = details }
mkKindVar :: Name -> SuperKind -> KindVar
-- mkKindVar take a SuperKind as argument because we don't have access
-- to superKind here.
mkKindVar name kind = TyVar
{ varName = name
, realUnique = getKey (nameUnique name)
, varType = kind }
{-
************************************************************************
* *
\subsection{Ids}
* *
************************************************************************
-}
idInfo :: Id -> IdInfo
idInfo (Id { id_info = info }) = info
idInfo other = pprPanic "idInfo" (ppr other)
idDetails :: Id -> IdDetails
idDetails (Id { id_details = details }) = details
idDetails other = pprPanic "idDetails" (ppr other)
-- The next three have a 'Var' suffix even though they always build
-- Ids, because Id.lhs uses 'mkGlobalId' etc with different types
mkGlobalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
mkGlobalVar details name ty info
= mk_id name ty GlobalId details info
mkLocalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
mkLocalVar details name ty info
= mk_id name ty (LocalId NotExported) details info
mkCoVar :: Name -> Type -> CoVar
-- Coercion variables have no IdInfo
mkCoVar name ty = mk_id name ty (LocalId NotExported) coVarDetails vanillaIdInfo
-- | Exported 'Var's will not be removed as dead code
mkExportedLocalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
mkExportedLocalVar details name ty info
= mk_id name ty (LocalId Exported) details info
mk_id :: Name -> Type -> IdScope -> IdDetails -> IdInfo -> Id
mk_id name ty scope details info
= Id { varName = name,
realUnique = getKey (nameUnique name),
varType = ty,
idScope = scope,
id_details = details,
id_info = info }
-------------------
lazySetIdInfo :: Id -> IdInfo -> Var
lazySetIdInfo id info = id { id_info = info }
setIdDetails :: Id -> IdDetails -> Id
setIdDetails id details = id { id_details = details }
globaliseId :: Id -> Id
-- ^ If it's a local, make it global
globaliseId id = id { idScope = GlobalId }
setIdExported :: Id -> Id
-- ^ Exports the given local 'Id'. Can also be called on global 'Id's, such as data constructors
-- and class operations, which are born as global 'Id's and automatically exported
setIdExported id@(Id { idScope = LocalId {} }) = id { idScope = LocalId Exported }
setIdExported id@(Id { idScope = GlobalId }) = id
setIdExported tv = pprPanic "setIdExported" (ppr tv)
setIdNotExported :: Id -> Id
-- ^ We can only do this to LocalIds
setIdNotExported id = ASSERT( isLocalId id )
id { idScope = LocalId NotExported }
{-
************************************************************************
* *
\subsection{Predicates over variables}
* *
************************************************************************
-}
isTyVar :: Var -> Bool
isTyVar = isTKVar -- Historical
isTKVar :: Var -> Bool -- True of both type and kind variables
isTKVar (TyVar {}) = True
isTKVar (TcTyVar {}) = True
isTKVar _ = False
isTcTyVar :: Var -> Bool
isTcTyVar (TcTyVar {}) = True
isTcTyVar _ = False
isId :: Var -> Bool
isId (Id {}) = True
isId _ = False
isLocalId :: Var -> Bool
isLocalId (Id { idScope = LocalId _ }) = True
isLocalId _ = False
-- | 'isLocalVar' returns @True@ for type variables as well as local 'Id's
-- These are the variables that we need to pay attention to when finding free
-- variables, or doing dependency analysis.
isLocalVar :: Var -> Bool
isLocalVar v = not (isGlobalId v)
isGlobalId :: Var -> Bool
isGlobalId (Id { idScope = GlobalId }) = True
isGlobalId _ = False
-- | 'mustHaveLocalBinding' returns @True@ of 'Id's and 'TyVar's
-- that must have a binding in this module. The converse
-- is not quite right: there are some global 'Id's that must have
-- bindings, such as record selectors. But that doesn't matter,
-- because it's only used for assertions
mustHaveLocalBinding :: Var -> Bool
mustHaveLocalBinding var = isLocalVar var
-- | 'isExportedIdVar' means \"don't throw this away\"
isExportedId :: Var -> Bool
isExportedId (Id { idScope = GlobalId }) = True
isExportedId (Id { idScope = LocalId Exported}) = True
isExportedId _ = False
| rahulmutt/ghcvm | compiler/Eta/BasicTypes/Var.hs | bsd-3-clause | 15,903 | 0 | 11 | 4,343 | 2,611 | 1,469 | 1,142 | 215 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Snap.Snaplet.Config where
------------------------------------------------------------------------------
import Data.Function (on)
import Data.Maybe (fromMaybe)
import Data.Monoid (Last(..), getLast)
#if MIN_VERSION_base(4,7,0)
import Data.Typeable.Internal (Typeable)
#else
import Data.Typeable (Typeable, TyCon, mkTyCon,
mkTyConApp, typeOf)
#endif
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid, mappend, mempty)
#endif
import System.Console.GetOpt (OptDescr(Option), ArgDescr(ReqArg))
------------------------------------------------------------------------------
import Snap.Core
import Snap.Http.Server.Config (Config, fmapOpt, setOther, getOther, optDescrs
,extendedCommandLineConfig)
------------------------------------------------------------------------------
-- | AppConfig contains the config options for command line arguments in
-- snaplet-based apps.
newtype AppConfig = AppConfig { appEnvironment :: Maybe String }
#if MIN_VERSION_base(4,7,0)
deriving Typeable
#else
------------------------------------------------------------------------------
-- | AppConfig has a manual instance of Typeable due to limitations in the
-- tools available before GHC 7.4, and the need to make dynamic loading
-- tractable. When support for earlier versions of GHC is dropped, the
-- dynamic loader package can be updated so that manual Typeable instances
-- are no longer needed.
appConfigTyCon :: TyCon
appConfigTyCon = mkTyCon "Snap.Snaplet.Config.AppConfig"
{-# NOINLINE appConfigTyCon #-}
instance Typeable AppConfig where
typeOf _ = mkTyConApp appConfigTyCon []
#endif
------------------------------------------------------------------------------
instance Monoid AppConfig where
mempty = AppConfig Nothing
mappend a b = AppConfig
{ appEnvironment = ov appEnvironment a b
}
where
ov f x y = getLast $! (mappend `on` (Last . f)) x y
------------------------------------------------------------------------------
-- | Command line options for snaplet applications.
appOpts :: AppConfig -> [OptDescr (Maybe (Config m AppConfig))]
appOpts defaults = map (fmapOpt $ fmap (flip setOther mempty))
[ Option ['e'] ["environment"]
(ReqArg setter "ENVIRONMENT")
$ "runtime environment to use" ++ defaultC appEnvironment
]
where
setter s = Just $ mempty { appEnvironment = Just s}
defaultC f = maybe "" ((", default " ++) . show) $ f defaults
------------------------------------------------------------------------------
-- | Calls snap-server's extendedCommandLineConfig to add snaplet options to
-- the built-in server command line options.
commandLineAppConfig :: MonadSnap m
=> Config m AppConfig
-> IO (Config m AppConfig)
commandLineAppConfig defaults =
extendedCommandLineConfig (appOpts appDefaults ++ optDescrs defaults)
mappend defaults
where
appDefaults = fromMaybe mempty $ getOther defaults
| sopvop/snap | src/Snap/Snaplet/Config.hs | bsd-3-clause | 3,302 | 0 | 13 | 726 | 474 | 270 | 204 | 39 | 1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE UnboxedTuples #-}
-----------------------------------------------------------------------------
-- |
-- Module : Debug.Trace
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Functions for tracing and monitoring execution.
--
-- These can be useful for investigating bugs or performance problems.
-- They should /not/ be used in production code.
--
-----------------------------------------------------------------------------
module Debug.Trace (
-- * Tracing
-- $tracing
trace,
traceId,
traceShow,
traceShowId,
-- traceStack, TODO: Implement!
traceIO,
traceM,
traceShowM,
putTraceMsg,
-- * Eventlog tracing
-- $eventlog_tracing
-- traceEvent, TODO: Implement!
-- traceEventIO,
-- * Execution phase markers
-- $markers
-- traceMarker, -- TODO: Implement!
-- traceMarkerIO,
) where
import System.IO.Unsafe
import Foreign.C.String
import GHC.Base
import qualified GHC.Foreign
import GHC.IO.Encoding
import GHC.Ptr
import GHC.Show
--import GHC.Stack
import Data.List
-- $tracing
--
-- The 'trace', 'traceShow' and 'traceIO' functions print messages to an output
-- stream. They are intended for \"printf debugging\", that is: tracing the flow
-- of execution and printing interesting values.
--
-- All these functions evaluate the message completely before printing
-- it; so if the message is not fully defined, none of it will be
-- printed.
--
-- The usual output stream is 'System.IO.stderr'. For Windows GUI applications
-- (that have no stderr) the output is directed to the Windows debug console.
-- Some implementations of these functions may decorate the string that\'s
-- output to indicate that you\'re tracing.
-- | The 'traceIO' function outputs the trace message from the IO monad.
-- This sequences the output with respect to other IO actions.
--
-- @since 4.5.0.0
traceIO :: String -> IO ()
traceIO msg = do
withCString "%s\n" $ \cfmt -> do
-- NB: debugBelch can't deal with null bytes, so filter them
-- out so we don't accidentally truncate the message. See Trac #9395
let (nulls, msg') = partition (=='\0') msg
withCString msg' $ \cmsg ->
debugBelch cfmt cmsg
when (not (null nulls)) $
withCString "WARNING: previous trace message had null bytes" $ \cmsg ->
debugBelch cfmt cmsg
-- don't use debugBelch() directly, because we cannot call varargs functions
-- using the FFI.
debugBelch :: CString -> CString -> IO ()
debugBelch = undefined
-- |
putTraceMsg :: String -> IO ()
putTraceMsg = traceIO
{-# DEPRECATED putTraceMsg "Use 'Debug.Trace.traceIO'" #-} -- deprecated in 7.4
{-# NOINLINE trace #-}
{-|
The 'trace' function outputs the trace message given as its first argument,
before returning the second argument as its result.
For example, this returns the value of @f x@ but first outputs the message.
> trace ("calling f with x = " ++ show x) (f x)
The 'trace' function should /only/ be used for debugging, or for monitoring
execution. The function is not referentially transparent: its type indicates
that it is a pure function but it has the side effect of outputting the
trace message.
-}
trace :: String -> a -> a
trace string expr = unsafePerformIO $ do
traceIO string
return expr
{-|
Like 'trace' but returns the message instead of a third value.
@since 4.7.0.0
-}
traceId :: String -> String
traceId a = trace a a
{-|
Like 'trace', but uses 'show' on the argument to convert it to a 'String'.
This makes it convenient for printing the values of interesting variables or
expressions inside a function. For example here we print the value of the
variables @x@ and @z@:
> f x y =
> traceShow (x, z) $ result
> where
> z = ...
> ...
-}
traceShow :: (Show a) => a -> b -> b
traceShow = trace . show
{-|
Like 'traceShow' but returns the shown value instead of a third value.
@since 4.7.0.0
-}
traceShowId :: (Show a) => a -> a
traceShowId a = trace (show a) a
{-|
Like 'trace' but returning unit in an arbitrary monad. Allows for convenient
use in do-notation. Note that the application of 'trace' is not an action in the
monad, as 'traceIO' is in the 'IO' monad.
> ... = do
> x <- ...
> traceM $ "x: " ++ show x
> y <- ...
> traceM $ "y: " ++ show y
@since 4.7.0.0
-}
traceM :: (Monad m) => String -> m ()
traceM string = trace string $ return ()
{-|
Like 'traceM', but uses 'show' on the argument to convert it to a 'String'.
> ... = do
> x <- ...
> traceMShow $ x
> y <- ...
> traceMShow $ x + y
@since 4.7.0.0
-}
traceShowM :: (Show a, Monad m) => a -> m ()
traceShowM = traceM . show
-- | like 'trace', but additionally prints a call stack if one is
-- available.
--
-- In the current GHC implementation, the call stack is only
-- availble if the program was compiled with @-prof@; otherwise
-- 'traceStack' behaves exactly like 'trace'. Entries in the call
-- stack correspond to @SCC@ annotations, so it is a good idea to use
-- @-fprof-auto@ or @-fprof-auto-calls@ to add SCC annotations automatically.
--
-- @since 4.5.0.0
-- traceStack :: String -> a -> a
-- traceStack str expr = unsafePerformIO $ do
-- traceIO str
-- stack <- currentCallStack
-- when (not (null stack)) $ traceIO (renderStack stack)
-- return expr
-- $eventlog_tracing
--
-- Eventlog tracing is a performance profiling system. These functions emit
-- extra events into the eventlog. In combination with eventlog profiling
-- tools these functions can be used for monitoring execution and
-- investigating performance problems.
--
-- Currently only GHC provides eventlog profiling, see the GHC user guide for
-- details on how to use it. These function exists for other Haskell
-- implementations but no events are emitted. Note that the string message is
-- always evaluated, whether or not profiling is available or enabled.
-- {-# NOINLINE traceEvent #-}
-- | The 'traceEvent' function behaves like 'trace' with the difference that
-- the message is emitted to the eventlog, if eventlog profiling is available
-- and enabled at runtime.
--
-- It is suitable for use in pure code. In an IO context use 'traceEventIO'
-- instead.
--
-- Note that when using GHC's SMP runtime, it is possible (but rare) to get
-- duplicate events emitted if two CPUs simultaneously evaluate the same thunk
-- that uses 'traceEvent'.
--
-- @since 4.5.0.0
-- traceEvent :: String -> a -> a
-- traceEvent msg expr = unsafeDupablePerformIO $ do
-- traceEventIO msg
-- return expr
-- | The 'traceEventIO' function emits a message to the eventlog, if eventlog
-- profiling is available and enabled at runtime.
--
-- Compared to 'traceEvent', 'traceEventIO' sequences the event with respect to
-- other IO actions.
--
-- @since 4.5.0.0
-- traceEventIO :: String -> IO ()
-- traceEventIO msg =
-- GHC.Foreign.withCString utf8 msg $ \(Ptr p) -> IO $ \s ->
-- case traceEvent# p s of s' -> (# s', () #)
-- $markers
--
-- When looking at a profile for the execution of a program we often want to
-- be able to mark certain points or phases in the execution and see that
-- visually in the profile.
-- For example, a program might have several distinct phases with different
-- performance or resource behaviour in each phase. To properly interpret the
-- profile graph we really want to see when each phase starts and ends.
--
-- Markers let us do this: we can annotate the program to emit a marker at
-- an appropriate point during execution and then see that in a profile.
--
-- Currently this feature is only supported in GHC by the eventlog tracing
-- system, but in future it may also be supported by the heap profiling or
-- other profiling tools. These function exists for other Haskell
-- implementations but they have no effect. Note that the string message is
-- always evaluated, whether or not profiling is available or enabled.
-- {-# NOINLINE traceMarker #-}
-- | The 'traceMarker' function emits a marker to the eventlog, if eventlog
-- profiling is available and enabled at runtime. The @String@ is the name of
-- the marker. The name is just used in the profiling tools to help you keep
-- clear which marker is which.
--
-- This function is suitable for use in pure code. In an IO context use
-- 'traceMarkerIO' instead.
--
-- Note that when using GHC's SMP runtime, it is possible (but rare) to get
-- duplicate events emitted if two CPUs simultaneously evaluate the same thunk
-- that uses 'traceMarker'.
--
-- @since 4.7.0.0
-- traceMarker :: String -> a -> a
-- traceMarker msg expr = unsafeDupablePerformIO $ do
-- traceMarkerIO msg
-- return expr
-- | The 'traceMarkerIO' function emits a marker to the eventlog, if eventlog
-- profiling is available and enabled at runtime.
--
-- Compared to 'traceMarker', 'traceMarkerIO' sequences the event with respect to
-- other IO actions.
--
-- @since 4.7.0.0
-- traceMarkerIO :: String -> IO ()
-- traceMarkerIO msg =
-- GHC.Foreign.withCString utf8 msg $ \(Ptr p) -> IO $ \s ->
-- case traceMarker# p s of s' -> (# s', () #)
| alexander-at-github/eta | libraries/base/Debug/Trace.hs | bsd-3-clause | 9,371 | 0 | 17 | 1,898 | 615 | 401 | 214 | 50 | 1 |
module Card.Json where
import Data.Aeson
import Data.Maybe
import qualified Network.Wreq as W
import Control.Monad.Ether.Implicit
import Control.Monad.Trans
import Control.Lens
import Config
import Card.Type
import qualified Data.ByteString.Lazy as BS
import System.Log.Logger
import Control.Concurrent.STM
import System.Directory (doesFileExist)
downloadSet :: (MonadConfig m, MonadIO m) => m ()
downloadSet = do
liftIO $ infoM rootLoggerName "Downloading cards.json..."
tcfg <- ask
let atomcfg = liftIO . atomically . readTVar $ tcfg
url <- jsonURL <$> atomcfg
folder <- dataFol <$> atomcfg
r <- liftIO . W.get $ url
liftIO $ BS.writeFile (folder ++ "cards.json") (r ^. W.responseBody)
liftIO $ infoM rootLoggerName "Downloaded cards.json"
downloadSetIfMissing :: (MonadConfig m, MonadIO m) => m ()
downloadSetIfMissing = do
tcfg <- ask
let atomcfg = liftIO . atomically . readTVar $ tcfg
folder <- dataFol <$> atomcfg
exist <- liftIO . doesFileExist $ folder ++ "cards.json"
unless exist downloadSet
readCards :: (MonadConfig m, MonadIO m) => m [Card]
readCards = do
tcfg <- ask
let atomcfg = liftIO . atomically . readTVar $ tcfg
folder <- dataFol <$> atomcfg
(o :: Maybe [Value]) <- liftIO $ decode <$> BS.readFile (folder ++ "cards.json")
let c :: [Card]
c = maybe [] (mapMaybe (decode . encode)) o
liftIO . infoM rootLoggerName $ "Loaded card database of total " ++ show (length c) ++ " cards"
return c
| hithroc/hsvkbot | src/Card/Json.hs | bsd-3-clause | 1,502 | 0 | 14 | 307 | 514 | 263 | 251 | -1 | -1 |
-- Simple data type to keep track of character positions
-- within a text file or other text stream.
module Pos where
-- Basic position indicator data type: filename, line number, column number.
data Pos = Pos {
posFile :: !String,
posLine :: !Int,
posCol :: !Int
}
-- Incrementally compute the next position in a text file
-- if 'c' is the character at the current position.
-- Follows the standard convention of 8-character tab stops.
nextPos (Pos file line col) c =
if c == '\n' then Pos file (line + 1) 1
else if c == '\t' then Pos file line ((div (col + 8 - 1) 8) * 8 + 1)
else Pos file line (col + 1)
-- Two positions are equal if each of their elements are equal.
instance Eq Pos where
Pos f1 l1 c1 == Pos f2 l2 c2 =
f1 == f2 && l1 == l2 && c1 == c2
-- Two positions are ordered by line number, then column number.
instance Ord Pos where
Pos f1 l1 c1 <= Pos f2 l2 c2 =
(l1 < l2) || (l1 == l2 && c1 <= c2)
-- Standard way to display positions - "file:line:col"
instance Show Pos where
show (Pos file line col) = file ++ ":" ++ show line ++ ":" ++ show col
-- Show a position relative to a base position.
-- If the new position is in the same line, just show its column number;
-- otherwise if the new position is in the same file,
-- just show its line and column numbers;
-- otherwise show the complete new position.
showPosRel (Pos file line col) (Pos file' line' col') =
if (file == file')
then if (line == line')
then "column " ++ show col'
else "line " ++ show line' ++ ", column " ++ show col'
else show (Pos file' line' col')
| YoshikuniJujo/lojbanXiragan | src/Pos.hs | bsd-3-clause | 1,572 | 36 | 15 | 351 | 451 | 236 | 215 | 29 | 3 |
{-# LANGUAGE CPP #-}
-- | This module provides an interface for typechecker plugins to
-- access select functions of the 'TcM', principally those to do with
-- reading parts of the state.
module TcPluginM (
#ifdef GHCI
-- * Basic TcPluginM functionality
TcPluginM,
tcPluginIO,
tcPluginTrace,
unsafeTcPluginTcM,
-- * Finding Modules and Names
FindResult(..),
findImportedModule,
lookupOrig,
-- * Looking up Names in the typechecking environment
tcLookupGlobal,
tcLookupTyCon,
tcLookupDataCon,
tcLookupClass,
tcLookup,
tcLookupId,
-- * Getting the TcM state
getTopEnv,
getEnvs,
getInstEnvs,
getFamInstEnvs,
matchFam,
-- * Type variables
newUnique,
newFlexiTyVar,
isTouchableTcPluginM,
-- * Zonking
zonkTcType,
zonkCt,
-- * Creating constraints
newWanted,
newDerived,
newGiven,
newCoercionHole,
-- * Manipulating evidence bindings
newEvVar,
setEvBind,
getEvBindsTcPluginM,
getEvBindsTcPluginM_maybe
#endif
) where
#ifdef GHCI
import qualified TcRnMonad as TcM
import qualified TcSMonad as TcS
import qualified TcEnv as TcM
import qualified TcMType as TcM
import qualified FamInst as TcM
import qualified IfaceEnv
import qualified Finder
import FamInstEnv ( FamInstEnv )
import TcRnMonad ( TcGblEnv, TcLclEnv, Ct, CtLoc, TcPluginM
, unsafeTcPluginTcM, getEvBindsTcPluginM_maybe
, liftIO, traceTc )
import TcMType ( TcTyVar, TcType )
import TcEnv ( TcTyThing )
import TcEvidence ( TcCoercion, CoercionHole
, EvTerm, EvBind, EvBindsVar, mkGivenEvBind )
import TcRnTypes ( CtEvidence(..) )
import Var ( EvVar )
import Module
import Name
import TyCon
import DataCon
import Class
import HscTypes
import Outputable
import Type
import Id
import InstEnv
import FastString
import Maybes
import Unique
-- | Perform some IO, typically to interact with an external tool.
tcPluginIO :: IO a -> TcPluginM a
tcPluginIO a = unsafeTcPluginTcM (liftIO a)
-- | Output useful for debugging the compiler.
tcPluginTrace :: String -> SDoc -> TcPluginM ()
tcPluginTrace a b = unsafeTcPluginTcM (traceTc a b)
findImportedModule :: ModuleName -> Maybe FastString -> TcPluginM FindResult
findImportedModule mod_name mb_pkg = do
hsc_env <- getTopEnv
tcPluginIO $ Finder.findImportedModule hsc_env mod_name mb_pkg
lookupOrig :: Module -> OccName -> TcPluginM Name
lookupOrig mod = unsafeTcPluginTcM . IfaceEnv.lookupOrig mod
tcLookupGlobal :: Name -> TcPluginM TyThing
tcLookupGlobal = unsafeTcPluginTcM . TcM.tcLookupGlobal
tcLookupTyCon :: Name -> TcPluginM TyCon
tcLookupTyCon = unsafeTcPluginTcM . TcM.tcLookupTyCon
tcLookupDataCon :: Name -> TcPluginM DataCon
tcLookupDataCon = unsafeTcPluginTcM . TcM.tcLookupDataCon
tcLookupClass :: Name -> TcPluginM Class
tcLookupClass = unsafeTcPluginTcM . TcM.tcLookupClass
tcLookup :: Name -> TcPluginM TcTyThing
tcLookup = unsafeTcPluginTcM . TcM.tcLookup
tcLookupId :: Name -> TcPluginM Id
tcLookupId = unsafeTcPluginTcM . TcM.tcLookupId
getTopEnv :: TcPluginM HscEnv
getTopEnv = unsafeTcPluginTcM TcM.getTopEnv
getEnvs :: TcPluginM (TcGblEnv, TcLclEnv)
getEnvs = unsafeTcPluginTcM TcM.getEnvs
getInstEnvs :: TcPluginM InstEnvs
getInstEnvs = unsafeTcPluginTcM TcM.tcGetInstEnvs
getFamInstEnvs :: TcPluginM (FamInstEnv, FamInstEnv)
getFamInstEnvs = unsafeTcPluginTcM TcM.tcGetFamInstEnvs
matchFam :: TyCon -> [Type]
-> TcPluginM (Maybe (TcCoercion, TcType))
matchFam tycon args = unsafeTcPluginTcM $ TcS.matchFamTcM tycon args
newUnique :: TcPluginM Unique
newUnique = unsafeTcPluginTcM TcM.newUnique
newFlexiTyVar :: Kind -> TcPluginM TcTyVar
newFlexiTyVar = unsafeTcPluginTcM . TcM.newFlexiTyVar
isTouchableTcPluginM :: TcTyVar -> TcPluginM Bool
isTouchableTcPluginM = unsafeTcPluginTcM . TcM.isTouchableTcM
zonkTcType :: TcType -> TcPluginM TcType
zonkTcType = unsafeTcPluginTcM . TcM.zonkTcType
zonkCt :: Ct -> TcPluginM Ct
zonkCt = unsafeTcPluginTcM . TcM.zonkCt
-- | Create a new wanted constraint.
newWanted :: CtLoc -> PredType -> TcPluginM CtEvidence
newWanted loc pty
= unsafeTcPluginTcM (TcM.newWanted (TcM.ctLocOrigin loc) Nothing pty)
-- | Create a new derived constraint.
newDerived :: CtLoc -> PredType -> TcPluginM CtEvidence
newDerived loc pty = return CtDerived { ctev_pred = pty, ctev_loc = loc }
-- | Create a new given constraint, with the supplied evidence. This
-- must not be invoked from 'tcPluginInit' or 'tcPluginStop', or it
-- will panic.
newGiven :: CtLoc -> PredType -> EvTerm -> TcPluginM CtEvidence
newGiven loc pty evtm = do
new_ev <- newEvVar pty
setEvBind $ mkGivenEvBind new_ev evtm
return CtGiven { ctev_pred = pty, ctev_evar = new_ev, ctev_loc = loc }
-- | Create a fresh evidence variable.
newEvVar :: PredType -> TcPluginM EvVar
newEvVar = unsafeTcPluginTcM . TcM.newEvVar
-- | Create a fresh coercion hole.
newCoercionHole :: TcPluginM CoercionHole
newCoercionHole = unsafeTcPluginTcM $ TcM.newCoercionHole
-- | Bind an evidence variable. This must not be invoked from
-- 'tcPluginInit' or 'tcPluginStop', or it will panic.
setEvBind :: EvBind -> TcPluginM ()
setEvBind ev_bind = do
tc_evbinds <- getEvBindsTcPluginM
unsafeTcPluginTcM $ TcM.addTcEvBind tc_evbinds ev_bind
-- | Access the 'EvBindsVar' carried by the 'TcPluginM' during
-- constraint solving. This must not be invoked from 'tcPluginInit'
-- or 'tcPluginStop', or it will panic.
getEvBindsTcPluginM :: TcPluginM EvBindsVar
getEvBindsTcPluginM = fmap (expectJust oops) getEvBindsTcPluginM_maybe
where
oops = "plugin attempted to read EvBindsVar outside the constraint solver"
#endif
| GaloisInc/halvm-ghc | compiler/typecheck/TcPluginM.hs | bsd-3-clause | 5,886 | 0 | 10 | 1,208 | 1,140 | 641 | 499 | 2 | 0 |
module Language.Lua.Parser
( A.parseText
, A.parseNamedText
, parseFile
, A.parseTokens
, stat
, exp
, chunk
) where
import Control.Monad (liftM)
import Prelude hiding (exp)
import qualified Language.Lua.Annotated.Parser as A
import Language.Lua.Annotated.Lexer (SourceRange)
import Language.Lua.Annotated.Simplify
import Language.Lua.Syntax
parseFile :: FilePath -> IO (Either (SourceRange,String) Block)
parseFile = liftM (liftM sBlock) . A.parseFile
stat :: A.Parser Stat
stat = fmap sStat A.stat
exp :: A.Parser Exp
exp = fmap sExp A.exp
chunk :: A.Parser Block
chunk = fmap sBlock A.chunk
| yav/language-lua | src/Language/Lua/Parser.hs | bsd-3-clause | 710 | 0 | 9 | 195 | 202 | 117 | 85 | 22 | 1 |
-- | Tools for parsing a SGF string.
module Sgf (
parseSgf
) where
import Control.Applicative
import Data.Attoparsec.Combinator
import Data.Attoparsec.Text
import Data.Char (isUpper, isSpace)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Tree (Tree(..))
import Data.Text (Text)
import qualified Data.Text as T
-- | A tree of nodes.
type SgfTree = Tree SgfNode
-- | A node is a property list, each key can only occur once.
--
-- Keys may have multiple values associated with them.
type SgfNode = Map Text [Text]
-- | Attempt to parse the given tree in SGF form.
--
-- Returns Nothing if the input wasn't valid SGF.
parseSgf :: Text -> Maybe SgfTree
parseSgf = either (const Nothing) Just . parseOnly tree
tree :: Parser SgfTree
tree = makeSgfTree <$> (char '(' *> many1 node)
<*> (many tree <* char ')')
node :: Parser SgfNode
node = char ';' *> (Map.fromList <$> many prop)
prop :: Parser (Text, [Text])
prop = (,) <$> (T.pack <$> many1 (satisfy isUpper)) <*> many1 val
-- | Parse a value, complete with brackets.
--
-- This is a bit tricky as there are escape sequences to take into account.
--
-- We'll use a simple folder with one bit of state: whether the last
val :: Parser Text
val = char '[' *> worker [] False
where
-- 'bs' = previous character was a backslash
worker acc bs = do
c <- anyChar
case c of
']' | not bs -> return . T.pack . reverse $ acc
'\\' | not bs -> worker acc True
'\n' | bs -> worker acc False -- remove soft newline
_ | isSpace c -> worker (' ' : acc) False
_ -> worker (c : acc) False
-- | Create an 'SgfTree' from a list of nodes and subtrees.
--
-- This does the expansion of a ";n1;n2;n3(;n4)(;n5)" node list to
-- a tree structure with depth 4 where the n3 tree node has two children
-- and the n1 and n2 node each have one child.
makeSgfTree :: [SgfNode] -> [SgfTree] -> SgfTree
makeSgfTree [] _ = error "absurd" -- Can't happen due to 'many1 node' in 'tree'
makeSgfTree [n] trees = Node n trees
makeSgfTree (h:t) trees = Node h [makeSgfTree t trees]
| pminten/xhaskell | sgf-parsing/example.hs | mit | 2,237 | 0 | 16 | 607 | 547 | 293 | 254 | 36 | 5 |
{-# LANGUAGE FlexibleContexts #-}
module Control.Search.Combinator.Until (until,limit,glimit) where
import Prelude hiding (until)
import Data.Int
import Control.Search.Language
import Control.Search.GeneratorInfo
import Control.Search.MemoReader
import Control.Search.Generator
import Control.Search.Combinator.Failure
import Control.Search.Stat
import Control.Monatron.Monatron hiding (Abort, L, state, cont)
import Control.Monatron.Zipper hiding (i,r)
untilLoop :: (Evalable m, ReaderM SeqPos m) => Stat -> Int -> (Eval m) -> (Eval m) -> Eval m
untilLoop cond uid lsuper' rsuper = commentEval c
where c = Eval { structs = structs lsuper @++@ structs rsuper @++@ mystructs
, toString = "until" ++ show uid ++ "(" ++ show cond ++ "," ++ toString lsuper' ++ "," ++ toString rsuper ++ ")"
, treeState_ = [entry ("is_fst",Bool,assign true)
,("until_union", Union [(SType s3,"fst"),(SType s4,"snd")],
\i ->
let j = xpath i FirstS
in initSubEvalState j s1 fs1 FirstS)
]
, initH = \i -> inits lsuper (i `xpath` FirstS)
, evalState_ = [("until_complete",Bool,const $ return true)]
, pushLeftH = push pushLeft
, pushRightH = push pushRight
, nextSameH = \i -> let j = i `withBase` "popped_estate"
in do let nS1 = local (const FirstS) $ inSeq nextSame i
let nS2 = local (const SecondS) $ inSeq nextSame i
let nD1 = local (const FirstS) $ inSeq nextDiff i
let nD2 = local (const SecondS) $ inSeq nextDiff i
swfst i (swfst j nS1 nD1) (swfst j nD2 nS2)
, nextDiffH = inSeq nextDiff
, -- MAIN ENTRY POINT FOR NEW NODE
-- if (fst) {
-- if (seq_union.fst.evalState->cont) {
-- } else {
-- }
-- } else {
-- if (seq_union.snd.evalState->cont) {
-- } else {
-- }
-- }
bodyH = \i ->
let f y z iscomplete pos =
do compl <- iscomplete (i `xpath` pos)
let j = i `xpath` pos `onAbort` (comment "untilLoop.bodyE" >>> dec_ref i j compl pos)
bodyE z j
in do let s1 = local (const FirstS) $ f in1 lsuper liscomplete FirstS
s2 = local (const SecondS) $ f in2 rsuper riscomplete SecondS
swfst i s1 s2
, addH = inSeq $ addE
, failH = \i -> inSeq' (\super j iscomplete pos -> iscomplete j >>= \compl -> (failE super j @>>>@ return (dec_ref i j compl pos))) i
, returnH = \i -> inSeq' (\super j iscomplete pos -> iscomplete j >>= \compl -> (returnE super (j `onCommit` dec_ref i j compl pos))) i
-- , continue = \_ -> return true
-- IF THE CURRENT STATUS IS NOT FAILED
-- EITHER (is_fst)
-- if (<CONDITION>) { // SWITCH TO NEW SEARCH
-- } else {
-- <TRY-REC>
-- }
-- OR (!is_fst)
, tryH = tryX tryE
, startTryH = tryX startTryE
, tryLH = \i -> inSeq' (\super j iscomplete pos -> iscomplete j >>= \compl -> (tryE_ super j @>>>@ return (dec_ref i j compl pos))) i
, boolArraysE = boolArraysE lsuper ++ boolArraysE rsuper
, intArraysE = intArraysE lsuper ++ intArraysE rsuper
, intVarsE = intVarsE lsuper ++ intVarsE rsuper
, deleteH = error "untilLoop.deleteE NOT YET IMPLEMENTED"
, canBranch = canBranch lsuper >>= \l -> canBranch rsuper >>= \r -> return (l || r)
, complete = \i -> return $ estate i @=> "until_complete"
-- , complete = const $ return false
}
needSide_ = \pos stmY stmN -> case pos of { FirstS -> if (length (evalState_ lsuper) == 0) then stmN else stmY;
SecondS -> if (length (evalState_ rsuper) == 0) then stmN else stmY;
}
needSide :: Monoid m => SeqPos -> m -> m
needSide = \pos stm -> needSide_ pos stm mempty
mystructs = ([s1,s2],[s3,s4])
s1 = Struct ("LeftEvalState" ++ show uid) $ needSide FirstS $ {- (Bool, "cont") : -} (Int, "ref_count_until" ++ show uid) : [(ty, field) | (field,ty,_) <- evalState_ lsuper]
fs1 = [(field,init) | (field,ty,init) <- evalState_ lsuper ]
s2 = Struct ("RightEvalState" ++ show uid) $ needSide SecondS $ {- (Bool, "cont") : -} (Int, "ref_count_until" ++ show uid) : [(ty, field) | (field,ty,_) <- evalState_ rsuper]
fs2 = [(field,init) | (field,ty,init) <- evalState_ rsuper ]
s3 = Struct ("LeftTreeState" ++ show uid) $ needSide FirstS [(Pointer $ SType s1, "evalState")] ++ [(ty, field) | (field,ty,_) <- treeState_ lsuper]
fs3 = [(field,init) | (field,ty,init) <- treeState_ lsuper]
s4 = Struct ("RightTreeState" ++ show uid) $ needSide SecondS [(Pointer $ SType s2, "evalState")] ++ [(ty, field) | (field,ty,_) <- treeState_ rsuper]
xpath i FirstS = withPath i in1 (Pointer $ SType s1) (Pointer $ SType s3)
xpath i SecondS = withPath i in2 (Pointer $ SType s2) (Pointer $ SType s4)
in1 = \state -> state @-> "until_union" @-> "fst"
in2 = \state -> state @-> "until_union" @-> "snd"
is_fst = \i -> tstate i @-> "is_fst"
withSeq f = seqSwitch (f lsuper in1) (f rsuper in2)
withSeq_ f = seqSwitch (f lsuper in1 FirstS) (f rsuper in2 SecondS)
inSeq f = \i -> withSeq_ $ \super ins pos -> f super (i `xpath` pos)
inSeq' f = \i -> seqSwitch (f lsuper (i `xpath` FirstS) liscomplete FirstS)
(f rsuper (i `xpath` SecondS) riscomplete SecondS)
dec_ref = \i j iscomplete pos -> needSide_ pos (dec (ref_countx j $ "until" ++ show uid) >>>
ifthen (ref_countx j ("until" ++ show uid) @== 0) (
{- DebugValue ("until" ++ show uid ++ ": left branch finished with complete") iscomplete
>>> DebugValue ("until" ++ show uid ++ ": until's previous completeness was") (complet i)
>>> -} (complet i <== (complet i &&& iscomplete)) >>> Delete (estate j)
)
) (complet i <== (complet i &&& iscomplete))
push dir = \i -> seqSwitch (push1 dir i) (push2 dir i)
push1 dir = \i ->
let j = i `xpath` FirstS
in dir lsuper (j `onCommit` ( mkCopy i "is_fst"
>>> mkCopy j "evalState"
>>> inc (ref_countx j $ "until" ++ show uid)
))
push2 dir = \i ->
let j = i `xpath` SecondS
in dir rsuper (j `onCommit` ( mkCopy i "is_fst"
>>> mkCopy j "evalState"
>>> inc (ref_countx j $ "until" ++ show uid)
))
lsuper = evalStat cond lsuper'
complet = \i -> estate i @=> "until_complete"
liscomplete = complete lsuper'
riscomplete = complete rsuper
initSubEvalState = \j s fs pos -> return (needSide pos ( (estate j <== New s)
>>> (ref_countx j ("until" ++ show uid) <== 1)
-- >>> (cont j <== true)
)
)
@>>>@ inite fs j
tryX = \x i -> do lc <- liscomplete (i `xpath` FirstS)
rc <- riscomplete (i `xpath` SecondS)
let j1 = i `xpath` FirstS `onAbort` (comment "untilLoop.tryE j1" >>> dec_ref i j1 lc FirstS)
j2 = i `xpath` SecondS `onAbort` (comment "untilLoop.tryE j2" >>> dec_ref i j2 rc SecondS)
j2b = i `xpath` SecondS `onAbort` (comment "untilLoop.tryE j2b" >>> dec_ref i j2b rc SecondS)
seqSwitch (x lsuper j1 >>= \try1 ->
deleteE lsuper j1 >>= \delete1 ->
(local (const SecondS) $
do stmt1 <- inits rsuper j2b
stmt2 <- startTryE rsuper j2b
ini <- initSubEvalState j2b s2 fs2 SecondS
return ( delete1
>>> dec_ref i j1 lc FirstS
>>> (is_fst i <== false)
>>> ini
>>> comment "initTreeState_ j2b rsuper"
>>> stmt1
>>> comment "tryE rsuper j2b"
>>> comment ("length: " ++ show (length (abort_ j2b)))
>>> stmt2)
) >>= \start2 -> readStat cond >>= \r -> return $ IfThenElse (r j1) ({- (DebugOutput $ "until" ++ show uid ++ " switches") >>> -} start2) try1
)
(x rsuper j2)
swfst i t e = do b1 <- canBranch lsuper
b2 <- canBranch rsuper
if (b1 && b2) then do { tt <- t; ee <- e; return $ IfThenElse (is_fst i) tt ee }
else if b1 then t
else e
limit :: Int32 -> Stat -> Search -> Search
limit n stat s = until (stat #>= constStat (const (IVal n))) s failure
glimit :: Stat -> Search -> Search
glimit cond s = until (cond) s failure
until
:: Stat
-> Search
-> Search
-> Search
until cond s1 s2 =
case s1 of
Search { mkeval = evals1, runsearch = runs1 } ->
case s2 of
Search { mkeval = evals2, runsearch = runs2 } ->
Search { mkeval =
\super -> do { s2' <- evals2 $ mapE (L . L . L . mmap (mmap runL . runL) . runL) super
; s1' <- evals1 $ mapE (L . L . mmap (mmap runL . runL) . runL) super
; uid <- get
; put (uid + 1)
; return $ mapE (L . mmap L . runL) $ memoLoop $
untilLoop cond uid (mapE ({- L . mmap (mmap L) . runL . runL-} mmap L . runL) s1')
(mapE ({- L . mmap (mmap L) . runL . runL . runL-} mmap L . runL . runL) s2')
}
, runsearch = runs2 . runs1 . runL . rReaderT FirstS . runL
}
| neothemachine/monadiccp | src/Control/Search/Combinator/Until.hs | bsd-3-clause | 12,045 | 25 | 32 | 5,636 | 3,358 | 1,767 | 1,591 | 146 | 7 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
module TestService_Iface where
import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..),
Eq, Show, Ord,
concat, error, fromIntegral, fromEnum, length, map,
maybe, not, null, otherwise, return, show, toEnum,
enumFromTo, Bounded, minBound, maxBound, seq, succ,
pred, enumFrom, enumFromThen, enumFromThenTo,
(.), (&&), (||), (==), (++), ($), (-), (>>=), (>>))
import qualified Control.Applicative as Applicative (ZipList(..))
import Control.Applicative ( (<*>) )
import qualified Control.DeepSeq as DeepSeq
import qualified Control.Exception as Exception
import qualified Control.Monad as Monad ( liftM, ap, when )
import qualified Data.ByteString.Lazy as BS
import Data.Functor ( (<$>) )
import qualified Data.Hashable as Hashable
import qualified Data.Int as Int
import Data.List
import qualified Data.Maybe as Maybe (catMaybes)
import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified Data.Typeable as Typeable ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) )
import qualified Test.QuickCheck as QuickCheck ( elements )
import qualified Thrift
import qualified Thrift.Types as Types
import qualified Thrift.Serializable as Serializable
import qualified Thrift.Arbitraries as Arbitraries
import qualified Module_Types
class TestService_Iface a where
init :: a -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> Int.Int64 -> IO Int.Int64
| getyourguide/fbthrift | thrift/compiler/test/fixtures/service-fuzzer/gen-hs/TestService_Iface.hs | apache-2.0 | 2,451 | 0 | 25 | 448 | 540 | 364 | 176 | 41 | 0 |
import StackTest
main :: IO ()
main = do
removeFileIgnore "stack.yaml"
removeFileIgnore "issue3397.cabal"
stack ["init", "--solver", "--resolver", "ghc-8.0.2"]
stack ["solver", "--update-config"]
| anton-dessiatov/stack | test/integration/tests/3397-ghc-solver/Main.hs | bsd-3-clause | 205 | 0 | 8 | 30 | 61 | 30 | 31 | 7 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, MagicHash
, UnboxedTuples
#-}
{-# LANGUAGE CApiFFI #-}
-- We believe we could deorphan this module, by moving lots of things
-- around, but we haven't got there yet:
{-# OPTIONS_GHC -Wno-orphans #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Float
-- Copyright : (c) The University of Glasgow 1994-2002
-- Portions obtained from hbc (c) Lennart Augusstson
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The types 'Float' and 'Double', and the classes 'Floating' and 'RealFloat'.
--
-----------------------------------------------------------------------------
#include "ieee-flpt.h"
module GHC.Float
( module GHC.Float
, Float(..), Double(..), Float#, Double#
, double2Int, int2Double, float2Int, int2Float
-- * Monomorphic equality operators
-- | See GHC.Classes#matching_overloaded_methods_in_rules
, eqFloat, eqDouble
) where
import Data.Maybe
import Data.Bits
import GHC.Base
import GHC.List
import GHC.Enum
import GHC.Show
import GHC.Num
import GHC.Real
import GHC.Arr
import GHC.Float.RealFracMethods
import GHC.Float.ConversionUtils
import GHC.Integer.Logarithms ( integerLogBase# )
import GHC.Integer.Logarithms.Internals
infixr 8 **
------------------------------------------------------------------------
-- Standard numeric classes
------------------------------------------------------------------------
-- | Trigonometric and hyperbolic functions and related functions.
class (Fractional a) => Floating a where
pi :: a
exp, log, sqrt :: a -> a
(**), logBase :: a -> a -> a
sin, cos, tan :: a -> a
asin, acos, atan :: a -> a
sinh, cosh, tanh :: a -> a
asinh, acosh, atanh :: a -> a
-- | @'log1p' x@ computes @'log' (1 + x)@, but provides more precise
-- results for small (absolute) values of @x@ if possible.
--
-- @since 4.9.0.0
log1p :: a -> a
-- | @'expm1' x@ computes @'exp' x - 1@, but provides more precise
-- results for small (absolute) values of @x@ if possible.
--
-- @since 4.9.0.0
expm1 :: a -> a
-- | @'log1pexp' x@ computes @'log' (1 + 'exp' x)@, but provides more
-- precise results if possible.
--
-- Examples:
--
-- * if @x@ is a large negative number, @'log' (1 + 'exp' x)@ will be
-- imprecise for the reasons given in 'log1p'.
--
-- * if @'exp' x@ is close to @-1@, @'log' (1 + 'exp' x)@ will be
-- imprecise for the reasons given in 'expm1'.
--
-- @since 4.9.0.0
log1pexp :: a -> a
-- | @'log1mexp' x@ computes @'log' (1 - 'exp' x)@, but provides more
-- precise results if possible.
--
-- Examples:
--
-- * if @x@ is a large negative number, @'log' (1 - 'exp' x)@ will be
-- imprecise for the reasons given in 'log1p'.
--
-- * if @'exp' x@ is close to @1@, @'log' (1 - 'exp' x)@ will be
-- imprecise for the reasons given in 'expm1'.
--
-- @since 4.9.0.0
log1mexp :: a -> a
{-# INLINE (**) #-}
{-# INLINE logBase #-}
{-# INLINE sqrt #-}
{-# INLINE tan #-}
{-# INLINE tanh #-}
x ** y = exp (log x * y)
logBase x y = log y / log x
sqrt x = x ** 0.5
tan x = sin x / cos x
tanh x = sinh x / cosh x
{-# INLINE log1p #-}
{-# INLINE expm1 #-}
{-# INLINE log1pexp #-}
{-# INLINE log1mexp #-}
log1p x = log (1 + x)
expm1 x = exp x - 1
log1pexp x = log1p (exp x)
log1mexp x = log1p (negate (exp x))
-- | Efficient, machine-independent access to the components of a
-- floating-point number.
class (RealFrac a, Floating a) => RealFloat a where
-- | a constant function, returning the radix of the representation
-- (often @2@)
floatRadix :: a -> Integer
-- | a constant function, returning the number of digits of
-- 'floatRadix' in the significand
floatDigits :: a -> Int
-- | a constant function, returning the lowest and highest values
-- the exponent may assume
floatRange :: a -> (Int,Int)
-- | The function 'decodeFloat' applied to a real floating-point
-- number returns the significand expressed as an 'Integer' and an
-- appropriately scaled exponent (an 'Int'). If @'decodeFloat' x@
-- yields @(m,n)@, then @x@ is equal in value to @m*b^^n@, where @b@
-- is the floating-point radix, and furthermore, either @m@ and @n@
-- are both zero or else @b^(d-1) <= 'abs' m < b^d@, where @d@ is
-- the value of @'floatDigits' x@.
-- In particular, @'decodeFloat' 0 = (0,0)@. If the type
-- contains a negative zero, also @'decodeFloat' (-0.0) = (0,0)@.
-- /The result of/ @'decodeFloat' x@ /is unspecified if either of/
-- @'isNaN' x@ /or/ @'isInfinite' x@ /is/ 'True'.
decodeFloat :: a -> (Integer,Int)
-- | 'encodeFloat' performs the inverse of 'decodeFloat' in the
-- sense that for finite @x@ with the exception of @-0.0@,
-- @'uncurry' 'encodeFloat' ('decodeFloat' x) = x@.
-- @'encodeFloat' m n@ is one of the two closest representable
-- floating-point numbers to @m*b^^n@ (or @±Infinity@ if overflow
-- occurs); usually the closer, but if @m@ contains too many bits,
-- the result may be rounded in the wrong direction.
encodeFloat :: Integer -> Int -> a
-- | 'exponent' corresponds to the second component of 'decodeFloat'.
-- @'exponent' 0 = 0@ and for finite nonzero @x@,
-- @'exponent' x = snd ('decodeFloat' x) + 'floatDigits' x@.
-- If @x@ is a finite floating-point number, it is equal in value to
-- @'significand' x * b ^^ 'exponent' x@, where @b@ is the
-- floating-point radix.
-- The behaviour is unspecified on infinite or @NaN@ values.
exponent :: a -> Int
-- | The first component of 'decodeFloat', scaled to lie in the open
-- interval (@-1@,@1@), either @0.0@ or of absolute value @>= 1\/b@,
-- where @b@ is the floating-point radix.
-- The behaviour is unspecified on infinite or @NaN@ values.
significand :: a -> a
-- | multiplies a floating-point number by an integer power of the radix
scaleFloat :: Int -> a -> a
-- | 'True' if the argument is an IEEE \"not-a-number\" (NaN) value
isNaN :: a -> Bool
-- | 'True' if the argument is an IEEE infinity or negative infinity
isInfinite :: a -> Bool
-- | 'True' if the argument is too small to be represented in
-- normalized format
isDenormalized :: a -> Bool
-- | 'True' if the argument is an IEEE negative zero
isNegativeZero :: a -> Bool
-- | 'True' if the argument is an IEEE floating point number
isIEEE :: a -> Bool
-- | a version of arctangent taking two real floating-point arguments.
-- For real floating @x@ and @y@, @'atan2' y x@ computes the angle
-- (from the positive x-axis) of the vector from the origin to the
-- point @(x,y)@. @'atan2' y x@ returns a value in the range [@-pi@,
-- @pi@]. It follows the Common Lisp semantics for the origin when
-- signed zeroes are supported. @'atan2' y 1@, with @y@ in a type
-- that is 'RealFloat', should return the same value as @'atan' y@.
-- A default definition of 'atan2' is provided, but implementors
-- can provide a more accurate implementation.
atan2 :: a -> a -> a
exponent x = if m == 0 then 0 else n + floatDigits x
where (m,n) = decodeFloat x
significand x = encodeFloat m (negate (floatDigits x))
where (m,_) = decodeFloat x
scaleFloat 0 x = x
scaleFloat k x
| isFix = x
| otherwise = encodeFloat m (n + clamp b k)
where (m,n) = decodeFloat x
(l,h) = floatRange x
d = floatDigits x
b = h - l + 4*d
-- n+k may overflow, which would lead
-- to wrong results, hence we clamp the
-- scaling parameter.
-- If n + k would be larger than h,
-- n + clamp b k must be too, simliar
-- for smaller than l - d.
-- Add a little extra to keep clear
-- from the boundary cases.
isFix = x == 0 || isNaN x || isInfinite x
atan2 y x
| x > 0 = atan (y/x)
| x == 0 && y > 0 = pi/2
| x < 0 && y > 0 = pi + atan (y/x)
|(x <= 0 && y < 0) ||
(x < 0 && isNegativeZero y) ||
(isNegativeZero x && isNegativeZero y)
= -atan2 (-y) x
| y == 0 && (x < 0 || isNegativeZero x)
= pi -- must be after the previous test on zero y
| x==0 && y==0 = y -- must be after the other double zero tests
| otherwise = x + y -- x or y is a NaN, return a NaN (via +)
------------------------------------------------------------------------
-- Float
------------------------------------------------------------------------
instance Num Float where
(+) x y = plusFloat x y
(-) x y = minusFloat x y
negate x = negateFloat x
(*) x y = timesFloat x y
abs x | x == 0 = 0 -- handles (-0.0)
| x > 0 = x
| otherwise = negateFloat x
signum x | x > 0 = 1
| x < 0 = negateFloat 1
| otherwise = x -- handles 0.0, (-0.0), and NaN
{-# INLINE fromInteger #-}
fromInteger i = F# (floatFromInteger i)
instance Real Float where
toRational (F# x#) =
case decodeFloat_Int# x# of
(# m#, e# #)
| isTrue# (e# >=# 0#) ->
(smallInteger m# `shiftLInteger` e#) :% 1
| isTrue# ((int2Word# m# `and#` 1##) `eqWord#` 0##) ->
case elimZerosInt# m# (negateInt# e#) of
(# n, d# #) -> n :% shiftLInteger 1 d#
| otherwise ->
smallInteger m# :% shiftLInteger 1 (negateInt# e#)
instance Fractional Float where
(/) x y = divideFloat x y
{-# INLINE fromRational #-}
fromRational (n:%d) = rationalToFloat n d
recip x = 1.0 / x
rationalToFloat :: Integer -> Integer -> Float
{-# NOINLINE [1] rationalToFloat #-}
rationalToFloat n 0
| n == 0 = 0/0
| n < 0 = (-1)/0
| otherwise = 1/0
rationalToFloat n d
| n == 0 = encodeFloat 0 0
| n < 0 = -(fromRat'' minEx mantDigs (-n) d)
| otherwise = fromRat'' minEx mantDigs n d
where
minEx = FLT_MIN_EXP
mantDigs = FLT_MANT_DIG
-- RULES for Integer and Int
{-# RULES
"properFraction/Float->Integer" properFraction = properFractionFloatInteger
"truncate/Float->Integer" truncate = truncateFloatInteger
"floor/Float->Integer" floor = floorFloatInteger
"ceiling/Float->Integer" ceiling = ceilingFloatInteger
"round/Float->Integer" round = roundFloatInteger
"properFraction/Float->Int" properFraction = properFractionFloatInt
"truncate/Float->Int" truncate = float2Int
"floor/Float->Int" floor = floorFloatInt
"ceiling/Float->Int" ceiling = ceilingFloatInt
"round/Float->Int" round = roundFloatInt
#-}
instance RealFrac Float where
-- ceiling, floor, and truncate are all small
{-# INLINE [1] ceiling #-}
{-# INLINE [1] floor #-}
{-# INLINE [1] truncate #-}
-- We assume that FLT_RADIX is 2 so that we can use more efficient code
#if FLT_RADIX != 2
#error FLT_RADIX must be 2
#endif
properFraction (F# x#)
= case decodeFloat_Int# x# of
(# m#, n# #) ->
let m = I# m#
n = I# n#
in
if n >= 0
then (fromIntegral m * (2 ^ n), 0.0)
else let i = if m >= 0 then m `shiftR` negate n
else negate (negate m `shiftR` negate n)
f = m - (i `shiftL` negate n)
in (fromIntegral i, encodeFloat (fromIntegral f) n)
truncate x = case properFraction x of
(n,_) -> n
round x = case properFraction x of
(n,r) -> let
m = if r < 0.0 then n - 1 else n + 1
half_down = abs r - 0.5
in
case (compare half_down 0.0) of
LT -> n
EQ -> if even n then n else m
GT -> m
ceiling x = case properFraction x of
(n,r) -> if r > 0.0 then n + 1 else n
floor x = case properFraction x of
(n,r) -> if r < 0.0 then n - 1 else n
instance Floating Float where
pi = 3.141592653589793238
exp x = expFloat x
log x = logFloat x
sqrt x = sqrtFloat x
sin x = sinFloat x
cos x = cosFloat x
tan x = tanFloat x
asin x = asinFloat x
acos x = acosFloat x
atan x = atanFloat x
sinh x = sinhFloat x
cosh x = coshFloat x
tanh x = tanhFloat x
(**) x y = powerFloat x y
logBase x y = log y / log x
asinh x = log (x + sqrt (1.0+x*x))
acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
atanh x = 0.5 * log ((1.0+x) / (1.0-x))
log1p = log1pFloat
expm1 = expm1Float
log1mexp a
| a <= log 2 = log (negate (expm1Float a))
| otherwise = log1pFloat (negate (exp a))
{-# INLINE log1mexp #-}
log1pexp a
| a <= 18 = log1pFloat (exp a)
| a <= 100 = a + exp (negate a)
| otherwise = a
{-# INLINE log1pexp #-}
instance RealFloat Float where
floatRadix _ = FLT_RADIX -- from float.h
floatDigits _ = FLT_MANT_DIG -- ditto
floatRange _ = (FLT_MIN_EXP, FLT_MAX_EXP) -- ditto
decodeFloat (F# f#) = case decodeFloat_Int# f# of
(# i, e #) -> (smallInteger i, I# e)
encodeFloat i (I# e) = F# (encodeFloatInteger i e)
exponent x = case decodeFloat x of
(m,n) -> if m == 0 then 0 else n + floatDigits x
significand x = case decodeFloat x of
(m,_) -> encodeFloat m (negate (floatDigits x))
scaleFloat 0 x = x
scaleFloat k x
| isFix = x
| otherwise = case decodeFloat x of
(m,n) -> encodeFloat m (n + clamp bf k)
where bf = FLT_MAX_EXP - (FLT_MIN_EXP) + 4*FLT_MANT_DIG
isFix = x == 0 || isFloatFinite x == 0
isNaN x = 0 /= isFloatNaN x
isInfinite x = 0 /= isFloatInfinite x
isDenormalized x = 0 /= isFloatDenormalized x
isNegativeZero x = 0 /= isFloatNegativeZero x
isIEEE _ = True
instance Show Float where
showsPrec x = showSignedFloat showFloat x
showList = showList__ (showsPrec 0)
------------------------------------------------------------------------
-- Double
------------------------------------------------------------------------
instance Num Double where
(+) x y = plusDouble x y
(-) x y = minusDouble x y
negate x = negateDouble x
(*) x y = timesDouble x y
abs x | x == 0 = 0 -- handles (-0.0)
| x > 0 = x
| otherwise = negateDouble x
signum x | x > 0 = 1
| x < 0 = negateDouble 1
| otherwise = x -- handles 0.0, (-0.0), and NaN
{-# INLINE fromInteger #-}
fromInteger i = D# (doubleFromInteger i)
instance Real Double where
toRational (D# x#) =
case decodeDoubleInteger x# of
(# m, e# #)
| isTrue# (e# >=# 0#) ->
shiftLInteger m e# :% 1
| isTrue# ((integerToWord m `and#` 1##) `eqWord#` 0##) ->
case elimZerosInteger m (negateInt# e#) of
(# n, d# #) -> n :% shiftLInteger 1 d#
| otherwise ->
m :% shiftLInteger 1 (negateInt# e#)
instance Fractional Double where
(/) x y = divideDouble x y
{-# INLINE fromRational #-}
fromRational (n:%d) = rationalToDouble n d
recip x = 1.0 / x
rationalToDouble :: Integer -> Integer -> Double
{-# NOINLINE [1] rationalToDouble #-}
rationalToDouble n 0
| n == 0 = 0/0
| n < 0 = (-1)/0
| otherwise = 1/0
rationalToDouble n d
| n == 0 = encodeFloat 0 0
| n < 0 = -(fromRat'' minEx mantDigs (-n) d)
| otherwise = fromRat'' minEx mantDigs n d
where
minEx = DBL_MIN_EXP
mantDigs = DBL_MANT_DIG
instance Floating Double where
pi = 3.141592653589793238
exp x = expDouble x
log x = logDouble x
sqrt x = sqrtDouble x
sin x = sinDouble x
cos x = cosDouble x
tan x = tanDouble x
asin x = asinDouble x
acos x = acosDouble x
atan x = atanDouble x
sinh x = sinhDouble x
cosh x = coshDouble x
tanh x = tanhDouble x
(**) x y = powerDouble x y
logBase x y = log y / log x
asinh x = log (x + sqrt (1.0+x*x))
acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
atanh x = 0.5 * log ((1.0+x) / (1.0-x))
log1p = log1pDouble
expm1 = expm1Double
log1mexp a
| a <= log 2 = log (negate (expm1Double a))
| otherwise = log1pDouble (negate (exp a))
{-# INLINE log1mexp #-}
log1pexp a
| a <= 18 = log1pDouble (exp a)
| a <= 100 = a + exp (negate a)
| otherwise = a
{-# INLINE log1pexp #-}
-- RULES for Integer and Int
{-# RULES
"properFraction/Double->Integer" properFraction = properFractionDoubleInteger
"truncate/Double->Integer" truncate = truncateDoubleInteger
"floor/Double->Integer" floor = floorDoubleInteger
"ceiling/Double->Integer" ceiling = ceilingDoubleInteger
"round/Double->Integer" round = roundDoubleInteger
"properFraction/Double->Int" properFraction = properFractionDoubleInt
"truncate/Double->Int" truncate = double2Int
"floor/Double->Int" floor = floorDoubleInt
"ceiling/Double->Int" ceiling = ceilingDoubleInt
"round/Double->Int" round = roundDoubleInt
#-}
instance RealFrac Double where
-- ceiling, floor, and truncate are all small
{-# INLINE [1] ceiling #-}
{-# INLINE [1] floor #-}
{-# INLINE [1] truncate #-}
properFraction x
= case (decodeFloat x) of { (m,n) ->
if n >= 0 then
(fromInteger m * 2 ^ n, 0.0)
else
case (quotRem m (2^(negate n))) of { (w,r) ->
(fromInteger w, encodeFloat r n)
}
}
truncate x = case properFraction x of
(n,_) -> n
round x = case properFraction x of
(n,r) -> let
m = if r < 0.0 then n - 1 else n + 1
half_down = abs r - 0.5
in
case (compare half_down 0.0) of
LT -> n
EQ -> if even n then n else m
GT -> m
ceiling x = case properFraction x of
(n,r) -> if r > 0.0 then n + 1 else n
floor x = case properFraction x of
(n,r) -> if r < 0.0 then n - 1 else n
instance RealFloat Double where
floatRadix _ = FLT_RADIX -- from float.h
floatDigits _ = DBL_MANT_DIG -- ditto
floatRange _ = (DBL_MIN_EXP, DBL_MAX_EXP) -- ditto
decodeFloat (D# x#)
= case decodeDoubleInteger x# of
(# i, j #) -> (i, I# j)
encodeFloat i (I# j) = D# (encodeDoubleInteger i j)
exponent x = case decodeFloat x of
(m,n) -> if m == 0 then 0 else n + floatDigits x
significand x = case decodeFloat x of
(m,_) -> encodeFloat m (negate (floatDigits x))
scaleFloat 0 x = x
scaleFloat k x
| isFix = x
| otherwise = case decodeFloat x of
(m,n) -> encodeFloat m (n + clamp bd k)
where bd = DBL_MAX_EXP - (DBL_MIN_EXP) + 4*DBL_MANT_DIG
isFix = x == 0 || isDoubleFinite x == 0
isNaN x = 0 /= isDoubleNaN x
isInfinite x = 0 /= isDoubleInfinite x
isDenormalized x = 0 /= isDoubleDenormalized x
isNegativeZero x = 0 /= isDoubleNegativeZero x
isIEEE _ = True
instance Show Double where
showsPrec x = showSignedFloat showFloat x
showList = showList__ (showsPrec 0)
------------------------------------------------------------------------
-- Enum instances
------------------------------------------------------------------------
{-
The @Enum@ instances for Floats and Doubles are slightly unusual.
The @toEnum@ function truncates numbers to Int. The definitions
of @enumFrom@ and @enumFromThen@ allow floats to be used in arithmetic
series: [0,0.1 .. 1.0]. However, roundoff errors make these somewhat
dubious. This example may have either 10 or 11 elements, depending on
how 0.1 is represented.
NOTE: The instances for Float and Double do not make use of the default
methods for @enumFromTo@ and @enumFromThenTo@, as these rely on there being
a `non-lossy' conversion to and from Ints. Instead we make use of the
1.2 default methods (back in the days when Enum had Ord as a superclass)
for these (@numericEnumFromTo@ and @numericEnumFromThenTo@ below.)
-}
instance Enum Float where
succ x = x + 1
pred x = x - 1
toEnum = int2Float
fromEnum = fromInteger . truncate -- may overflow
enumFrom = numericEnumFrom
enumFromTo = numericEnumFromTo
enumFromThen = numericEnumFromThen
enumFromThenTo = numericEnumFromThenTo
instance Enum Double where
succ x = x + 1
pred x = x - 1
toEnum = int2Double
fromEnum = fromInteger . truncate -- may overflow
enumFrom = numericEnumFrom
enumFromTo = numericEnumFromTo
enumFromThen = numericEnumFromThen
enumFromThenTo = numericEnumFromThenTo
------------------------------------------------------------------------
-- Printing floating point
------------------------------------------------------------------------
-- | Show a signed 'RealFloat' value to full precision
-- using standard decimal notation for arguments whose absolute value lies
-- between @0.1@ and @9,999,999@, and scientific notation otherwise.
showFloat :: (RealFloat a) => a -> ShowS
showFloat x = showString (formatRealFloat FFGeneric Nothing x)
-- These are the format types. This type is not exported.
data FFFormat = FFExponent | FFFixed | FFGeneric
-- This is just a compatibility stub, as the "alt" argument formerly
-- didn't exist.
formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
formatRealFloat fmt decs x = formatRealFloatAlt fmt decs False x
formatRealFloatAlt :: (RealFloat a) => FFFormat -> Maybe Int -> Bool -> a
-> String
formatRealFloatAlt fmt decs alt x
| isNaN x = "NaN"
| isInfinite x = if x < 0 then "-Infinity" else "Infinity"
| x < 0 || isNegativeZero x = '-':doFmt fmt (floatToDigits (toInteger base) (-x))
| otherwise = doFmt fmt (floatToDigits (toInteger base) x)
where
base = 10
doFmt format (is, e) =
let ds = map intToDigit is in
case format of
FFGeneric ->
doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
(is,e)
FFExponent ->
case decs of
Nothing ->
let show_e' = show (e-1) in
case ds of
"0" -> "0.0e0"
[d] -> d : ".0e" ++ show_e'
(d:ds') -> d : '.' : ds' ++ "e" ++ show_e'
[] -> errorWithoutStackTrace "formatRealFloat/doFmt/FFExponent: []"
Just dec ->
let dec' = max dec 1 in
case is of
[0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
_ ->
let
(ei,is') = roundTo base (dec'+1) is
(d:ds') = map intToDigit (if ei > 0 then init is' else is')
in
d:'.':ds' ++ 'e':show (e-1+ei)
FFFixed ->
let
mk0 ls = case ls of { "" -> "0" ; _ -> ls}
in
case decs of
Nothing
| e <= 0 -> "0." ++ replicate (-e) '0' ++ ds
| otherwise ->
let
f 0 s rs = mk0 (reverse s) ++ '.':mk0 rs
f n s "" = f (n-1) ('0':s) ""
f n s (r:rs) = f (n-1) (r:s) rs
in
f e "" ds
Just dec ->
let dec' = max dec 0 in
if e >= 0 then
let
(ei,is') = roundTo base (dec' + e) is
(ls,rs) = splitAt (e+ei) (map intToDigit is')
in
mk0 ls ++ (if null rs && not alt then "" else '.':rs)
else
let
(ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
in
d : (if null ds' && not alt then "" else '.':ds')
roundTo :: Int -> Int -> [Int] -> (Int,[Int])
roundTo base d is =
case f d True is of
x@(0,_) -> x
(1,xs) -> (1, 1:xs)
_ -> errorWithoutStackTrace "roundTo: bad Value"
where
b2 = base `quot` 2
f n _ [] = (0, replicate n 0)
f 0 e (x:xs) | x == b2 && e && all (== 0) xs = (0, []) -- Round to even when at exactly half the base
| otherwise = (if x >= b2 then 1 else 0, [])
f n _ (i:xs)
| i' == base = (1,0:ds)
| otherwise = (0,i':ds)
where
(c,ds) = f (n-1) (even i) xs
i' = c + i
-- Based on "Printing Floating-Point Numbers Quickly and Accurately"
-- by R.G. Burger and R.K. Dybvig in PLDI 96.
-- This version uses a much slower logarithm estimator. It should be improved.
-- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
-- and returns a list of digits and an exponent.
-- In particular, if @x>=0@, and
--
-- > floatToDigits base x = ([d1,d2,...,dn], e)
--
-- then
--
-- (1) @n >= 1@
--
-- (2) @x = 0.d1d2...dn * (base**e)@
--
-- (3) @0 <= di <= base-1@
floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
floatToDigits _ 0 = ([0], 0)
floatToDigits base x =
let
(f0, e0) = decodeFloat x
(minExp0, _) = floatRange x
p = floatDigits x
b = floatRadix x
minExp = minExp0 - p -- the real minimum exponent
-- Haskell requires that f be adjusted so denormalized numbers
-- will have an impossibly low exponent. Adjust for this.
(f, e) =
let n = minExp - e0 in
if n > 0 then (f0 `quot` (expt b n), e0+n) else (f0, e0)
(r, s, mUp, mDn) =
if e >= 0 then
let be = expt b e in
if f == expt b (p-1) then
(f*be*b*2, 2*b, be*b, be) -- according to Burger and Dybvig
else
(f*be*2, 2, be, be)
else
if e > minExp && f == expt b (p-1) then
(f*b*2, expt b (-e+1)*2, b, 1)
else
(f*2, expt b (-e)*2, 1, 1)
k :: Int
k =
let
k0 :: Int
k0 =
if b == 2 && base == 10 then
-- logBase 10 2 is very slightly larger than 8651/28738
-- (about 5.3558e-10), so if log x >= 0, the approximation
-- k1 is too small, hence we add one and need one fixup step less.
-- If log x < 0, the approximation errs rather on the high side.
-- That is usually more than compensated for by ignoring the
-- fractional part of logBase 2 x, but when x is a power of 1/2
-- or slightly larger and the exponent is a multiple of the
-- denominator of the rational approximation to logBase 10 2,
-- k1 is larger than logBase 10 x. If k1 > 1 + logBase 10 x,
-- we get a leading zero-digit we don't want.
-- With the approximation 3/10, this happened for
-- 0.5^1030, 0.5^1040, ..., 0.5^1070 and values close above.
-- The approximation 8651/28738 guarantees k1 < 1 + logBase 10 x
-- for IEEE-ish floating point types with exponent fields
-- <= 17 bits and mantissae of several thousand bits, earlier
-- convergents to logBase 10 2 would fail for long double.
-- Using quot instead of div is a little faster and requires
-- fewer fixup steps for negative lx.
let lx = p - 1 + e0
k1 = (lx * 8651) `quot` 28738
in if lx >= 0 then k1 + 1 else k1
else
-- f :: Integer, log :: Float -> Float,
-- ceiling :: Float -> Int
ceiling ((log (fromInteger (f+1) :: Float) +
fromIntegral e * log (fromInteger b)) /
log (fromInteger base))
--WAS: fromInt e * log (fromInteger b))
fixup n =
if n >= 0 then
if r + mUp <= expt base n * s then n else fixup (n+1)
else
if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
in
fixup k0
gen ds rn sN mUpN mDnN =
let
(dn, rn') = (rn * base) `quotRem` sN
mUpN' = mUpN * base
mDnN' = mDnN * base
in
case (rn' < mDnN', rn' + mUpN' > sN) of
(True, False) -> dn : ds
(False, True) -> dn+1 : ds
(True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
(False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
rds =
if k >= 0 then
gen [] r (s * expt base k) mUp mDn
else
let bk = expt base (-k) in
gen [] (r * bk) s (mUp * bk) (mDn * bk)
in
(map fromIntegral (reverse rds), k)
------------------------------------------------------------------------
-- Converting from a Rational to a RealFloa
------------------------------------------------------------------------
{-
[In response to a request for documentation of how fromRational works,
Joe Fasel writes:] A quite reasonable request! This code was added to
the Prelude just before the 1.2 release, when Lennart, working with an
early version of hbi, noticed that (read . show) was not the identity
for floating-point numbers. (There was a one-bit error about half the
time.) The original version of the conversion function was in fact
simply a floating-point divide, as you suggest above. The new version
is, I grant you, somewhat denser.
Unfortunately, Joe's code doesn't work! Here's an example:
main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
This program prints
0.0000000000000000
instead of
1.8217369128763981e-300
Here's Joe's code:
\begin{pseudocode}
fromRat :: (RealFloat a) => Rational -> a
fromRat x = x'
where x' = f e
-- If the exponent of the nearest floating-point number to x
-- is e, then the significand is the integer nearest xb^(-e),
-- where b is the floating-point radix. We start with a good
-- guess for e, and if it is correct, the exponent of the
-- floating-point number we construct will again be e. If
-- not, one more iteration is needed.
f e = if e' == e then y else f e'
where y = encodeFloat (round (x * (1 % b)^^e)) e
(_,e') = decodeFloat y
b = floatRadix x'
-- We obtain a trial exponent by doing a floating-point
-- division of x's numerator by its denominator. The
-- result of this division may not itself be the ultimate
-- result, because of an accumulation of three rounding
-- errors.
(s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
/ fromInteger (denominator x))
\end{pseudocode}
Now, here's Lennart's code (which works):
-}
-- | Converts a 'Rational' value into any type in class 'RealFloat'.
{-# RULES
"fromRat/Float" fromRat = (fromRational :: Rational -> Float)
"fromRat/Double" fromRat = (fromRational :: Rational -> Double)
#-}
{-# NOINLINE [1] fromRat #-}
fromRat :: (RealFloat a) => Rational -> a
-- Deal with special cases first, delegating the real work to fromRat'
fromRat (n :% 0) | n > 0 = 1/0 -- +Infinity
| n < 0 = -1/0 -- -Infinity
| otherwise = 0/0 -- NaN
fromRat (n :% d) | n > 0 = fromRat' (n :% d)
| n < 0 = - fromRat' ((-n) :% d)
| otherwise = encodeFloat 0 0 -- Zero
-- Conversion process:
-- Scale the rational number by the RealFloat base until
-- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
-- Then round the rational to an Integer and encode it with the exponent
-- that we got from the scaling.
-- To speed up the scaling process we compute the log2 of the number to get
-- a first guess of the exponent.
fromRat' :: (RealFloat a) => Rational -> a
-- Invariant: argument is strictly positive
fromRat' x = r
where b = floatRadix r
p = floatDigits r
(minExp0, _) = floatRange r
minExp = minExp0 - p -- the real minimum exponent
xMax = toRational (expt b p)
p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
-- if x = n/d and ln = integerLogBase b n, ld = integerLogBase b d,
-- then b^(ln-ld-1) < x < b^(ln-ld+1)
f = if p0 < 0 then 1 :% expt b (-p0) else expt b p0 :% 1
x0 = x / f
-- if ln - ld >= minExp0, then b^(p-1) < x0 < b^(p+1), so there's at most
-- one scaling step needed, otherwise, x0 < b^p and no scaling is needed
(x', p') = if x0 >= xMax then (x0 / toRational b, p0+1) else (x0, p0)
r = encodeFloat (round x') p'
-- Exponentiation with a cache for the most common numbers.
minExpt, maxExpt :: Int
minExpt = 0
maxExpt = 1100
expt :: Integer -> Int -> Integer
expt base n =
if base == 2 && n >= minExpt && n <= maxExpt then
expts!n
else
if base == 10 && n <= maxExpt10 then
expts10!n
else
base^n
expts :: Array Int Integer
expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
maxExpt10 :: Int
maxExpt10 = 324
expts10 :: Array Int Integer
expts10 = array (minExpt,maxExpt10) [(n,10^n) | n <- [minExpt .. maxExpt10]]
-- Compute the (floor of the) log of i in base b.
-- Simplest way would be just divide i by b until it's smaller then b, but that would
-- be very slow! We are just slightly more clever, except for base 2, where
-- we take advantage of the representation of Integers.
-- The general case could be improved by a lookup table for
-- approximating the result by integerLog2 i / integerLog2 b.
integerLogBase :: Integer -> Integer -> Int
integerLogBase b i
| i < b = 0
| b == 2 = I# (integerLog2# i)
| otherwise = I# (integerLogBase# b i)
{-
Unfortunately, the old conversion code was awfully slow due to
a) a slow integer logarithm
b) repeated calculation of gcd's
For the case of Rational's coming from a Float or Double via toRational,
we can exploit the fact that the denominator is a power of two, which for
these brings a huge speedup since we need only shift and add instead
of division.
The below is an adaption of fromRat' for the conversion to
Float or Double exploiting the known floatRadix and avoiding
divisions as much as possible.
-}
{-# SPECIALISE fromRat'' :: Int -> Int -> Integer -> Integer -> Float,
Int -> Int -> Integer -> Integer -> Double #-}
fromRat'' :: RealFloat a => Int -> Int -> Integer -> Integer -> a
-- Invariant: n and d strictly positive
fromRat'' minEx@(I# me#) mantDigs@(I# md#) n d =
case integerLog2IsPowerOf2# d of
(# ld#, pw# #)
| isTrue# (pw# ==# 0#) ->
case integerLog2# n of
ln# | isTrue# (ln# >=# (ld# +# me# -# 1#)) ->
-- this means n/d >= 2^(minEx-1), i.e. we are guaranteed to get
-- a normalised number, round to mantDigs bits
if isTrue# (ln# <# md#)
then encodeFloat n (I# (negateInt# ld#))
else let n' = n `shiftR` (I# (ln# +# 1# -# md#))
n'' = case roundingMode# n (ln# -# md#) of
0# -> n'
2# -> n' + 1
_ -> case fromInteger n' .&. (1 :: Int) of
0 -> n'
_ -> n' + 1
in encodeFloat n'' (I# (ln# -# ld# +# 1# -# md#))
| otherwise ->
-- n/d < 2^(minEx-1), a denorm or rounded to 2^(minEx-1)
-- the exponent for encoding is always minEx-mantDigs
-- so we must shift right by (minEx-mantDigs) - (-ld)
case ld# +# (me# -# md#) of
ld'# | isTrue# (ld'# <=# 0#) -> -- we would shift left, so we don't shift
encodeFloat n (I# ((me# -# md#) -# ld'#))
| isTrue# (ld'# <=# ln#) ->
let n' = n `shiftR` (I# ld'#)
in case roundingMode# n (ld'# -# 1#) of
0# -> encodeFloat n' (minEx - mantDigs)
1# -> if fromInteger n' .&. (1 :: Int) == 0
then encodeFloat n' (minEx-mantDigs)
else encodeFloat (n' + 1) (minEx-mantDigs)
_ -> encodeFloat (n' + 1) (minEx-mantDigs)
| isTrue# (ld'# ># (ln# +# 1#)) -> encodeFloat 0 0 -- result of shift < 0.5
| otherwise -> -- first bit of n shifted to 0.5 place
case integerLog2IsPowerOf2# n of
(# _, 0# #) -> encodeFloat 0 0 -- round to even
(# _, _ #) -> encodeFloat 1 (minEx - mantDigs)
| otherwise ->
let ln = I# (integerLog2# n)
ld = I# ld#
-- 2^(ln-ld-1) < n/d < 2^(ln-ld+1)
p0 = max minEx (ln - ld)
(n', d')
| p0 < mantDigs = (n `shiftL` (mantDigs - p0), d)
| p0 == mantDigs = (n, d)
| otherwise = (n, d `shiftL` (p0 - mantDigs))
-- if ln-ld < minEx, then n'/d' < 2^mantDigs, else
-- 2^(mantDigs-1) < n'/d' < 2^(mantDigs+1) and we
-- may need one scaling step
scale p a b
| (b `shiftL` mantDigs) <= a = (p+1, a, b `shiftL` 1)
| otherwise = (p, a, b)
(p', n'', d'') = scale (p0-mantDigs) n' d'
-- n''/d'' < 2^mantDigs and p' == minEx-mantDigs or n''/d'' >= 2^(mantDigs-1)
rdq = case n'' `quotRem` d'' of
(q,r) -> case compare (r `shiftL` 1) d'' of
LT -> q
EQ -> if fromInteger q .&. (1 :: Int) == 0
then q else q+1
GT -> q+1
in encodeFloat rdq p'
------------------------------------------------------------------------
-- Floating point numeric primops
------------------------------------------------------------------------
-- Definitions of the boxed PrimOps; these will be
-- used in the case of partial applications, etc.
plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
plusFloat (F# x) (F# y) = F# (plusFloat# x y)
minusFloat (F# x) (F# y) = F# (minusFloat# x y)
timesFloat (F# x) (F# y) = F# (timesFloat# x y)
divideFloat (F# x) (F# y) = F# (divideFloat# x y)
negateFloat :: Float -> Float
negateFloat (F# x) = F# (negateFloat# x)
gtFloat, geFloat, ltFloat, leFloat :: Float -> Float -> Bool
gtFloat (F# x) (F# y) = isTrue# (gtFloat# x y)
geFloat (F# x) (F# y) = isTrue# (geFloat# x y)
ltFloat (F# x) (F# y) = isTrue# (ltFloat# x y)
leFloat (F# x) (F# y) = isTrue# (leFloat# x y)
expFloat, logFloat, sqrtFloat :: Float -> Float
sinFloat, cosFloat, tanFloat :: Float -> Float
asinFloat, acosFloat, atanFloat :: Float -> Float
sinhFloat, coshFloat, tanhFloat :: Float -> Float
expFloat (F# x) = F# (expFloat# x)
logFloat (F# x) = F# (logFloat# x)
sqrtFloat (F# x) = F# (sqrtFloat# x)
sinFloat (F# x) = F# (sinFloat# x)
cosFloat (F# x) = F# (cosFloat# x)
tanFloat (F# x) = F# (tanFloat# x)
asinFloat (F# x) = F# (asinFloat# x)
acosFloat (F# x) = F# (acosFloat# x)
atanFloat (F# x) = F# (atanFloat# x)
sinhFloat (F# x) = F# (sinhFloat# x)
coshFloat (F# x) = F# (coshFloat# x)
tanhFloat (F# x) = F# (tanhFloat# x)
powerFloat :: Float -> Float -> Float
powerFloat (F# x) (F# y) = F# (powerFloat# x y)
-- definitions of the boxed PrimOps; these will be
-- used in the case of partial applications, etc.
plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
plusDouble (D# x) (D# y) = D# (x +## y)
minusDouble (D# x) (D# y) = D# (x -## y)
timesDouble (D# x) (D# y) = D# (x *## y)
divideDouble (D# x) (D# y) = D# (x /## y)
negateDouble :: Double -> Double
negateDouble (D# x) = D# (negateDouble# x)
gtDouble, geDouble, leDouble, ltDouble :: Double -> Double -> Bool
gtDouble (D# x) (D# y) = isTrue# (x >## y)
geDouble (D# x) (D# y) = isTrue# (x >=## y)
ltDouble (D# x) (D# y) = isTrue# (x <## y)
leDouble (D# x) (D# y) = isTrue# (x <=## y)
double2Float :: Double -> Float
double2Float (D# x) = F# (double2Float# x)
float2Double :: Float -> Double
float2Double (F# x) = D# (float2Double# x)
expDouble, logDouble, sqrtDouble :: Double -> Double
sinDouble, cosDouble, tanDouble :: Double -> Double
asinDouble, acosDouble, atanDouble :: Double -> Double
sinhDouble, coshDouble, tanhDouble :: Double -> Double
expDouble (D# x) = D# (expDouble# x)
logDouble (D# x) = D# (logDouble# x)
sqrtDouble (D# x) = D# (sqrtDouble# x)
sinDouble (D# x) = D# (sinDouble# x)
cosDouble (D# x) = D# (cosDouble# x)
tanDouble (D# x) = D# (tanDouble# x)
asinDouble (D# x) = D# (asinDouble# x)
acosDouble (D# x) = D# (acosDouble# x)
atanDouble (D# x) = D# (atanDouble# x)
sinhDouble (D# x) = D# (sinhDouble# x)
coshDouble (D# x) = D# (coshDouble# x)
tanhDouble (D# x) = D# (tanhDouble# x)
powerDouble :: Double -> Double -> Double
powerDouble (D# x) (D# y) = D# (x **## y)
foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
foreign import ccall unsafe "isFloatFinite" isFloatFinite :: Float -> Int
foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
foreign import ccall unsafe "isDoubleFinite" isDoubleFinite :: Double -> Int
------------------------------------------------------------------------
-- libm imports for extended floating
------------------------------------------------------------------------
foreign import capi unsafe "math.h log1p" log1pDouble :: Double -> Double
foreign import capi unsafe "math.h expm1" expm1Double :: Double -> Double
foreign import capi unsafe "math.h log1pf" log1pFloat :: Float -> Float
foreign import capi unsafe "math.h expm1f" expm1Float :: Float -> Float
------------------------------------------------------------------------
-- Coercion rules
------------------------------------------------------------------------
word2Double :: Word -> Double
word2Double (W# w) = D# (word2Double# w)
word2Float :: Word -> Float
word2Float (W# w) = F# (word2Float# w)
{-# RULES
"fromIntegral/Int->Float" fromIntegral = int2Float
"fromIntegral/Int->Double" fromIntegral = int2Double
"fromIntegral/Word->Float" fromIntegral = word2Float
"fromIntegral/Word->Double" fromIntegral = word2Double
"realToFrac/Float->Float" realToFrac = id :: Float -> Float
"realToFrac/Float->Double" realToFrac = float2Double
"realToFrac/Double->Float" realToFrac = double2Float
"realToFrac/Double->Double" realToFrac = id :: Double -> Double
"realToFrac/Int->Double" realToFrac = int2Double -- See Note [realToFrac int-to-float]
"realToFrac/Int->Float" realToFrac = int2Float -- ..ditto
#-}
{-
Note [realToFrac int-to-float]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Don found that the RULES for realToFrac/Int->Double and simliarly
Float made a huge difference to some stream-fusion programs. Here's
an example
import Data.Array.Vector
n = 40000000
main = do
let c = replicateU n (2::Double)
a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double
print (sumU (zipWithU (*) c a))
Without the RULE we get this loop body:
case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->
case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->
Main.$s$wfold
(+# sc_sY4 1)
(+# wild_X1i 1)
(+## sc2_sY6 (*## 2.0 ipv_sW3))
And with the rule:
Main.$s$wfold
(+# sc_sXT 1)
(+# wild_X1h 1)
(+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))
The running time of the program goes from 120 seconds to 0.198 seconds
with the native backend, and 0.143 seconds with the C backend.
A few more details in Trac #2251, and the patch message
"Add RULES for realToFrac from Int".
-}
-- Utils
showSignedFloat :: (RealFloat a)
=> (a -> ShowS) -- ^ a function that can show unsigned values
-> Int -- ^ the precedence of the enclosing context
-> a -- ^ the value to show
-> ShowS
showSignedFloat showPos p x
| x < 0 || isNegativeZero x
= showParen (p > 6) (showChar '-' . showPos (-x))
| otherwise = showPos x
{-
We need to prevent over/underflow of the exponent in encodeFloat when
called from scaleFloat, hence we clamp the scaling parameter.
We must have a large enough range to cover the maximum difference of
exponents returned by decodeFloat.
-}
clamp :: Int -> Int -> Int
clamp bd k = max (-bd) (min bd k)
| tolysz/prepare-ghcjs | spec-lts8/base/GHC/Float.hs | bsd-3-clause | 48,135 | 29 | 29 | 16,112 | 10,847 | 5,751 | 5,096 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, FunctionalDependencies #-}
{-| Implementation of the Ganeti Instance config object.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Objects.Nic where
import qualified Data.ByteString.UTF8 as UTF8
import Ganeti.THH
import Ganeti.THH.Field
import Ganeti.Types
$(buildParam "Nic" "nicp"
[ simpleField "mode" [t| NICMode |]
, simpleField "link" [t| String |]
, simpleField "vlan" [t| String |]
])
$(buildObject "PartialNic" "nic" $
[ simpleField "mac" [t| String |]
, optionalField $ simpleField "ip" [t| String |]
, simpleField "nicparams" [t| PartialNicParams |]
, optionalField $ simpleField "network" [t| String |]
, optionalField $ simpleField "name" [t| String |]
] ++ uuidFields)
instance UuidObject PartialNic where
uuidOf = UTF8.toString . nicUuid
| andir/ganeti | src/Ganeti/Objects/Nic.hs | bsd-2-clause | 2,083 | 0 | 11 | 337 | 196 | 120 | 76 | 19 | 0 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, DeriveGeneric #-}
{-# OPTIONS_GHC -Wall #-}
import Control.Distributed.Process hiding (Message)
import Control.Distributed.Process.Closure
import Control.Monad
import Text.Printf
import GHC.Generics (Generic)
import Data.Binary
import Data.Typeable
import DistribUtils
-- <<Message
data Message = Ping (SendPort ProcessId)
deriving (Typeable, Generic)
instance Binary Message
-- >>
-- <<pingServer
pingServer :: Process ()
pingServer = do
Ping chan <- expect
say $ printf "ping received from %s" (show chan)
mypid <- getSelfPid
sendChan chan mypid
-- >>
-- <<remotable
remotable ['pingServer]
-- >>
-- <<master
master :: [NodeId] -> Process ()
master peers = do
ps <- forM peers $ \nid -> do
say $ printf "spawning on %s" (show nid)
spawn nid $(mkStaticClosure 'pingServer)
ports <- forM ps $ \pid -> do
say $ printf "pinging %s" (show pid)
(sendport,recvport) <- newChan
send pid (Ping sendport)
return recvport
oneport <- mergePortsBiased ports -- <1>
waitForPongs oneport ps -- <2>
say "All pongs successfully received"
terminate
waitForPongs :: ReceivePort ProcessId -> [ProcessId] -> Process ()
waitForPongs _ [] = return ()
waitForPongs port ps = do
pid <- receiveChan port
waitForPongs port (filter (/= pid) ps)
-- >>
-- <<main
main :: IO ()
main = distribMain master Main.__remoteTable
-- >>
| prt2121/haskell-practice | parconc/distrib-ping/ping-tc-merge.hs | apache-2.0 | 1,443 | 0 | 15 | 292 | 446 | 224 | 222 | 41 | 1 |
{-# LANGUAGE TypeFamilies #-}
module T4093a where
type family Foo x
type instance Foo () = Maybe ()
hang :: (Foo e ~ Maybe e) => Foo e
hang = Just ()
-- Type is not ambiguous; should get a complaint
-- for (e ~ ()) arising from the Just ()
{- Ambiguity check
[G] Foo e ~ Maybe e
[W] Foo e ~ Foo e0
[W] Foo e0 ~ Maybe e0
---
[G] Foo e ~ fsk
[G] fsk ~ Maybe e
[W] Foo e ~ fmv1
[W] Foo e0 ~ fmv2
[W] fmv1 ~ fmv2
[W] fmv2 ~ Maybe e0
---> fmv1 := fsk
[G] Foo e ~ fsk
[G] fsk ~ Maybe e
[W] Foo e0 ~ fmv2
[W] fsk ~ fmv2
[W] fmv2 ~ Maybe e0
--->
[G] Foo e ~ fsk
[G] fsk ~ Maybe e
[W] Foo e0 ~ fmv2
[W] fmv2 ~ Maybe e
[W] fmv2 ~ Maybe e0
Now the question is whether we get a derived equality e ~ e0. Currently
we don't, but we easily could. But then we'd need to be careful not to
report insoluble Int ~ Bool if we had
F a ~ Int, F a ~ Bool
-}
| urbanslug/ghc | testsuite/tests/indexed-types/should_fail/T4093a.hs | bsd-3-clause | 872 | 0 | 8 | 239 | 66 | 37 | 29 | 6 | 1 |
{-# LANGUAGE MagicHash , UnboxedTuples #-}
module T8598(fun) where
import GHC.Float (Double(..))
import GHC.Integer (decodeDoubleInteger, encodeDoubleInteger)
-- Float.scaleFloat for Doubles, slightly simplified
fun :: Double -> Double
fun x | isFix = x
| otherwise = case x of
(D# x#) -> case decodeDoubleInteger x# of
(# i, j #) -> D# (encodeDoubleInteger i j)
where
isFix = isDoubleFinite x == 0
foreign import ccall unsafe "isDoubleFinite" isDoubleFinite :: Double -> Int
| urbanslug/ghc | testsuite/tests/stranal/sigs/T8598.hs | bsd-3-clause | 529 | 0 | 14 | 125 | 147 | 79 | 68 | 11 | 1 |
{-# OPTIONS_HADDOCK hide #-}
module BlasCTypes (BlasInt, BlasIndex) where
import Prelude ()
import Foreign.C.Types (CInt, CSize)
-- Here, we define some aliases for the C types in case the Blas
-- implementation decides to use some non-standard types.
-- This is the main integral type used by the CBlas interface. Usually, this
-- corresponds the `int` type in C. However, some implementations may offer
-- an alternative interface that uses a different type (e.g. `int64`).
type BlasInt = CInt
-- This is the integral type used for indices returned by `iamax` functions.
-- Usually, this corresponds to the `size_t` type in C. In CBlas, this is
-- referred to as `CBLAS_INDEX`.
type BlasIndex = CSize
| Rufflewind/blas-hs | src/BlasCTypes.hs | mit | 709 | 0 | 5 | 121 | 53 | 38 | 15 | 6 | 0 |
module Colin.Resource.Load.Texture (loadTexture, readTexture) where
import Graphics.Rendering.OpenGL
import Foreign.ForeignPtr (withForeignPtr)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as L (ByteString)
import Codec.Picture.Repa
import Data.Array.Repa (extent)
import Data.Array.Repa.Index
loadTexture :: FilePath -> IO (TextureObject, Size)
loadTexture fp = do
eimg <- readImageRGBA fp
case eimg of
Left s -> error s
Right img -> texFromImage img
readTexture :: ByteString -> IO (TextureObject, Size)
readTexture fp = do
case decodeImageRGBA fp of
Left s -> error s
Right img -> texFromImage img
texFromImage img = do
(t:_) <- genObjectNames 1
textureBinding Texture2D $= Just t
textureWrapMode Texture2D S $= (Repeated, Repeat)
textureWrapMode Texture2D T $= (Repeated, Repeat)
textureFilter Texture2D $= ((Nearest, Nothing), Nearest)
let (p, _, _) = toForeignPtr img
s@(Size w h) = size $ (extent . imgData) img
texImage w h p
return (t, s)
where
size (_ :. h :. w :. _) = Size (fromIntegral w) (fromIntegral h)
texImage width height ptr = withForeignPtr ptr $ \p -> texImage2D Nothing NoProxy 0 RGBA8 (TextureSize2D width height) 0 $ PixelData ABGR UnsignedByte p
| scan/Colin | src/Colin/Resource/Load/Texture.hs | mit | 1,313 | 0 | 13 | 285 | 476 | 244 | 232 | 31 | 2 |
module Models.ColumnTypes where
import ClassyPrelude.Yesod
data ReadableType = Book
| Paper
deriving (Show, Read, Eq)
data ReadingStatus = Unread
| ToRead
| Reading
| DoneReading
deriving (Show, Read, Eq)
instance PathPiece ReadingStatus where
fromPathPiece t | t == "unread" = Just Unread
| t == "to-read" = Just ToRead
| t == "reading" = Just Reading
| t == "done-reading" = Just DoneReading
| otherwise = Nothing
toPathPiece Unread = "unread"
toPathPiece ToRead = "to-read"
toPathPiece Reading = "reading"
toPathPiece DoneReading = "done-reading"
derivePersistField "ReadableType"
derivePersistField "ReadingStatus"
| darthdeus/reedink | Models/ColumnTypes.hs | mit | 823 | 0 | 9 | 291 | 197 | 97 | 100 | -1 | -1 |
module CombineSpec where
import Test.Hspec
import Combine
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "combinations" $
it "should give 4 for sample input" $
combinations [20,15,10,5,5] 25 `shouldBe` 4
describe "combinationsMinimum" $
it "should give 2 for sample input" $
combinationsMinimum [20,15,10,5,5] 25 `shouldBe` 3
| corajr/adventofcode2015 | 17/test/CombineSpec.hs | mit | 371 | 0 | 10 | 81 | 126 | 69 | 57 | 13 | 1 |
{-# LANGUAGE BangPatterns #-}
module Life ( Board
, Generation(..)
, randomBoard
, nextGeneration
, getCoords
, countAlive
) where
import System.Random
import qualified Data.Vector.Unboxed as U
-- Way too many object created if we use boxed vector
--type Board = V.Vector Int
type Board = U.Vector Int
type Width = Int
type Height = Int
data Generation = Generation { width :: !Int
, height :: !Int
, cellWidth :: !Float
, genPerSec :: !Int
, board :: !Board
}
randomBoard :: Width -> Height -> StdGen -> Board
randomBoard w h = U.take (w * h) . U.unfoldr (Just . randomR (0, 1))
nextGeneration :: Generation -> Generation
nextGeneration gen@(Generation w h cw gps brd) =
Generation w h cw gps (U.imap (nextCell gen) brd)
{-# INLINE getCoords #-}
getCoords :: Generation -> Int -> (Int, Int)
getCoords (Generation w _ _ _ _) !idx = idx `quotRem` w
{-# INLINE fromCoords #-}
fromCoords :: Generation -> (Int, Int) -> Int
fromCoords (Generation w _ _ _ _) (!x, !y) = x + (y * w)
countAlive :: Generation -> Int
countAlive (Generation _ _ _ _ brd) = U.sum brd
{-# INLINE nextCell #-}
nextCell :: Generation -> Int -> Int -> Int
nextCell gen@(Generation _ _ _ _ brd) !idx !state
| nc < 2 || nc > 3 = 0
| nc == 3 = 1
| otherwise = state
where
(!x, !y) = getCoords gen idx
{-
-- this way it creates a huge allocation rate
nc = L.sum [ gn neg neg, gn zro neg, gn pos neg
, gn neg zro, 0 , gn pos zro
, gn neg pos, gn zro pos, gn pos pos]
-}
!nc = gn neg neg + gn zro neg + gn pos neg
+ gn neg zro + gn zro zro + gn pos zro
+ gn neg pos + gn zro pos + gn pos pos
gn !mx !my
| midx < 0 = 0
| midx >= U.length brd = 0
| otherwise = brd U.! midx
where
!midx = fromCoords gen (x + mx, y + my)
!neg = -1
!pos = 1
!zro = 0
| ksaveljev/game-of-life | src/Life.hs | mit | 2,086 | 0 | 15 | 741 | 688 | 354 | 334 | 58 | 1 |
{-# LANGUAGE MultiParamTypeClasses, NamedFieldPuns, FlexibleInstances,
FlexibleContexts, UndecidableInstances #-}
-- | Fresh name monad.
module Fresh where
import Control.Monad.State
import qualified Abstract as A
import ListEnv as Env
type Renaming = Env A.UID A.Name -- Map A.Name A.Name
class MonadFresh m where
fresh :: A.Name -> m A.Name -- ^ return a fresh name variant
renaming :: m Renaming
data FreshSt = FreshSt
{ nextId :: A.UID
, nameMap :: Renaming
}
instance MonadState FreshSt m => MonadFresh m where
fresh x = do
FreshSt { nextId, nameMap } <- get
let y = x { A.uid = nextId }
put $ FreshSt { nextId = nextId - 1
, nameMap = Env.update nameMap (A.uid x) y
}
return y
renaming = gets nameMap
| andreasabel/helf | src/Fresh.hs | mit | 794 | 0 | 14 | 210 | 212 | 116 | 96 | 21 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
module AI.Clustering.KMeans
( KMeans(..)
, KMeansOpts(..)
, defaultKMeansOpts
, kmeans
, kmeansBy
-- * Initialization methods
, Method(..)
, decode
-- * References
-- $references
) where
import Control.Monad (forM_)
import Control.Monad.Primitive (PrimMonad, PrimState)
import qualified Data.Matrix.Unboxed as MU
import Data.Matrix.Class (unsafeTakeRow)
import qualified Data.Matrix.Unboxed.Mutable as MM
import Data.Ord (comparing)
import qualified Data.Vector as V
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Data.List (minimumBy, foldl')
import System.Random.MWC (Gen, initialize)
import Control.Monad.ST (runST)
import AI.Clustering.KMeans.Types
import AI.Clustering.KMeans.Internal (sumSquares, forgy, kmeansPP)
-- | Perform K-means clustering
kmeans :: Int -- ^ The number of clusters
-> MU.Matrix Double -- ^ Input data stored as rows in a matrix
-> KMeansOpts
-> KMeans (U.Vector Double)
kmeans k mat opts
| containNaN = error "Input data contains NaN."
| otherwise = KMeans member cs grps sse'
where
containNaN = U.any isNaN $ MU.flatten mat
(member, cs, sse') = kmeans' initial (kmeansMaxIter opts) dat fn
grps = if kmeansClusters opts
then Just $ decode member $ MU.toRows mat
else Nothing
dat = U.enumFromN 0 $ MU.rows mat
fn = unsafeTakeRow mat
initial = runST $ do
gen <- initialize $ kmeansSeed opts
case kmeansMethod opts of
Forgy -> forgy gen k dat fn
KMeansPP -> kmeansPP gen k dat fn
Centers c -> return c
{-# INLINE kmeans #-}
-- | Perform K-means clustering, using a feature extraction function
kmeansBy :: G.Vector v a
=> Int -- ^ The number of clusters
-> v a -- ^ Input data
-> (a -> U.Vector Double)
-> KMeansOpts
-> KMeans a
kmeansBy k dat fn opts
| containNaN = error "Input data contains NaN."
| otherwise = KMeans member cs grps sse'
where
containNaN = G.foldl (\acc x -> acc || U.any isNaN (fn x)) False dat
(member, cs, sse') = kmeans' initial (kmeansMaxIter opts) dat fn
grps = if kmeansClusters opts
then Just $ decode member $ G.toList dat
else Nothing
initial = runST $ do
gen <- initialize $ kmeansSeed opts
case kmeansMethod opts of
Forgy -> forgy gen k dat fn
KMeansPP -> kmeansPP gen k dat fn
Centers c -> return c
{-# INLINE kmeansBy #-}
-- | K-means algorithm
kmeans' :: G.Vector v a
=> MU.Matrix Double -- ^ Initial set of k centroids
-> Int -- ^ Max inter
-> v a -- ^ Input data
-> (a -> U.Vector Double) -- ^ Feature extraction function
-> (U.Vector Int, MU.Matrix Double, Double)
kmeans' initial maxiter dat fn
| U.length (fn $ G.head dat) /= d = error "Dimension mismatched."
| otherwise = (member, centers, U.sum $ U.imap ( \i x -> sqrt $ sumSquares
(fn $ dat G.! i) (centers `MU.takeRow` x) ) member )
where
(member, centers) = loop 0 initial U.empty
loop !iter means membership
| iter >= maxiter || membership' == membership = (membership, means)
| otherwise = loop (iter+1) (update membership') membership'
where
membership' = assign means
-- Assignment step
assign means = U.generate n $ \i ->
let x = fn $ G.unsafeIndex dat i
f (!min', !j') j = let d = sumSquares x $ means `unsafeTakeRow` j
in if d < min' then (d, j) else (min', j')
in snd $ foldl' f (1/0, -1) [0..k-1]
-- Update step
update membership = MU.create $ do
m <- MM.replicate (k,d) 0.0
count <- UM.replicate k (0 :: Int)
forM_ [0..n-1] $ \i -> do
let x = membership `U.unsafeIndex` i
vec = fn $ dat `G.unsafeIndex` i
UM.unsafeModify count (+1) x
forM_ [0..d-1] $ \j ->
MM.unsafeRead m (x,j) >>=
MM.unsafeWrite m (x,j) . (+ (vec `U.unsafeIndex` j))
-- normalize
forM_ [0..k-1] $ \i -> do
c <- UM.unsafeRead count i
forM_ [0..d-1] $ \j ->
MM.unsafeRead m (i,j) >>= MM.unsafeWrite m (i,j) . (/fromIntegral c)
return m
n = G.length dat
k = MU.rows initial
d = MU.cols initial
{-# INLINE kmeans' #-}
-- | Assign data to clusters based on KMeans result
decode :: U.Vector Int -> [a] -> [[a]]
decode member xs = V.toList $ V.create $ do
v <- VM.replicate n []
forM_ (zip (U.toList member) xs) $ \(i,x) ->
VM.unsafeRead v i >>= VM.unsafeWrite v i . (x:)
return v
where
n = U.maximum member + 1
{-# INLINE decode #-}
-- $references
--
-- Arthur, D. and Vassilvitskii, S. (2007). k-means++: the advantages of careful
-- seeding. Proceedings of the eighteenth annual ACM-SIAM symposium on Discrete
-- algorithms. Society for Industrial and Applied Mathematics Philadelphia, PA,
-- USA. pp. 1027–1035.
| kaizhang/clustering | src/AI/Clustering/KMeans.hs | mit | 5,323 | 0 | 19 | 1,573 | 1,692 | 898 | 794 | 115 | 4 |
{-# htermination mapMaybe :: (a -> Maybe b) -> [a] -> [b] #-}
import Maybe
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Maybe_mapMaybe_1.hs | mit | 75 | 0 | 3 | 15 | 5 | 3 | 2 | 1 | 0 |
import System.IO
import Data.List
import Data.Char
main = do
handle <- openFile "day3input.txt" ReadMode
contents <- hGetContents handle
let splitContent = words contents
result = compute splitContent
print result
hClose handle
compute :: [String] -> Int
compute input = length $ filter validTriangle tripleList
where tripleList = collect3 $ map read input
validTriangle :: [Int] -> Bool
validTriangle lengths = sumGreater $ sort lengths
sumGreater :: [Int] -> Bool
sumGreater (a:b:c:[]) = a + b > c
collect3 :: [Int] -> [[Int]]
collect3 [] = []
collect3 list = take 3 list : collect3 (drop 3 list) | aBhallo/AoC2016 | Day 3/day3part1.hs | mit | 677 | 0 | 10 | 175 | 250 | 125 | 125 | 20 | 1 |
module Main where
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Data.Word (Word64)
import System.Random.SplitMix.Gen
import System.Random.SplitMix.MathOperations (c_mix64, c_mixGamma, xorShift33)
prop_xorShift33SelfInvertible i = i == (xorShift33 $ xorShift33 i)
unmix64 :: Word64 -> Word64
unmix64 = xorShift33 . secondRoundUnmix64 . firstRoundUnmix64
firstRoundUnmix64 = (* 0x9cb4b2f8129337db) . xorShift33
secondRoundUnmix64 = (* 0x4f74430c22a54005) . xorShift33
prop_mix64unmix64InvertibleCommutative i = (c_mix64 $ unmix64 i) == (unmix64 $ c_mix64 i)
prop_seedGammaPreservation :: SplitMix64 -> Bool
prop_seedGammaPreservation gen = seed == unmix64 q && gamma == (unmix64 q - unmix64 p)
where
(p, newGen) = nextInt64 gen
(q, newGen') = nextInt64 newGen
(seed, gamma) = toSeedGamma newGen'
prop_resultOfMixGammaShouldAlwaysBeOdd :: Word64 -> Bool
prop_resultOfMixGammaShouldAlwaysBeOdd = odd . c_mixGamma
prop_gammaIsAlwaysOdd :: SplitMix64 -> Bool
prop_gammaIsAlwaysOdd = odd . snd . toSeedGamma
main :: IO ()
main = defaultMain allTests
allTests = [mathOperationTests,
splitMixOperationsTests]
mathOperationTests = testGroup "MathOperations"
[testProperty "xorShift33 is an inverse to itself" prop_xorShift33SelfInvertible,
testProperty "unmix64 inverts mix64 and commutes with it" prop_mix64unmix64InvertibleCommutative]
splitMixOperationsTests = testGroup "SplitMix operations"
[testProperty "seedAndGamma should be preserved after nextInt64 calls" prop_seedGammaPreservation,
testProperty "mixGamma function should always return odd gammas" prop_resultOfMixGammaShouldAlwaysBeOdd,
testProperty "gamma should always be odd" prop_gammaIsAlwaysOdd]
| nkartashov/SplitMix | tests/Main.hs | mit | 1,778 | 0 | 8 | 237 | 390 | 214 | 176 | 32 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module Mint.Account (mintAccounts) where
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens (key)
import qualified Data.Text as Text
import Database.HDBC
import Database.HDBC.Sqlite3
import GHC.Generics
import Network.URI
import qualified Network.Wreq as Wreq
import qualified Settings
import Util
data JsonAccount = JsonAccount { name :: String
, value :: Float
, isActive :: Bool
} deriving (Show, Generic)
instance FromJSON JsonAccount
mintAccounts :: Wreq.Options -> IO ()
mintAccounts tokenSession = do
let accountUrl = Settings.mintHostname ++ "/bundledServiceController.xevent?legacy=false"
let accountJson = "[{"
++ "\"id\": \"1\","
++ "\"service\": \"MintAccountService\","
++ "\"task\": \"getAccountsSortedByBalanceDescending\","
++ "\"args\": {"
++ "\"types\": ["
++ "\"BANK\","
++ "\"CREDIT\","
++ "\"INVESTMENT\","
++ "\"LOAN\","
++ "\"MORTGAGE\","
++ "\"OTHER_PROPERTY\","
++ "\"REAL_ESTATE\","
++ "\"VEHICLE\","
++ "\"UNCLASSIFIED\""
++ "]"
++ "}"
++ "}]"
response <- Wreq.postWith tokenSession accountUrl ["input" Wreq.:= Text.pack accountJson]
let resultMaybe = response ^? Wreq.responseBody . key "response" . key "1" . key "response"
case fmap fromJSON resultMaybe :: Maybe (Result [JsonAccount]) of
Just (Success jsonAccounts) -> updateAccounts $ filter isActive jsonAccounts
Just (Error message) -> putStrLn ("Error: could not decode account JSON response. " ++ message)
Nothing -> putStrLn "Error: could not decode account JSON response."
updateAccounts :: [JsonAccount] -> IO ()
updateAccounts jsonAccounts = do
conn <- getDbConnection
run conn "DELETE FROM account" []
commit conn
mapM_ (insertAccount conn) jsonAccounts
commit conn
disconnect conn
insertAccount :: Connection -> JsonAccount -> IO Integer
insertAccount conn jsonAccount = do
let balance = (truncate $ value jsonAccount * 100) :: Integer
let accountName = (toSql . name) jsonAccount
run conn "INSERT INTO account (balance, name) VALUES (?, ?)" [toSql balance, toSql accountName]
| jpotterm/manila-hs | src/Mint/Account.hs | cc0-1.0 | 2,671 | 0 | 26 | 904 | 558 | 282 | 276 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
import Control.DeepSeq (($!!))
import qualified Data.ByteString as BS
import Data.List (sort)
import Data.Time (DiffTime)
import Data.Word (Word32)
import Network.Pcap (openOffline, setFilter, dispatchBS,
PktHdr, PcapHandle, nextBS, hdrWireLength)
import qualified ParserGen.Parser as P
import System.Environment (getArgs, getProgName)
import Kospi
main :: IO ()
main = do
args <- getArgs
case args of
["-r", f] -> capture f True
[f] -> capture f False
_ -> do name <- getProgName
putStrLn $ "Usage: " ++ name ++ " [-r] "
++ "<dump.pcap>"
filterStr :: String
filterStr = "udp port 15515 or udp port 15516 and len == 257"
capture :: String -> Bool -> IO ()
capture !f !reorder = do
hdl <- openOffline f
let nmask = 0 :: Word32 -- capture _all_ the internet
setFilter hdl filterStr True nmask
if not reorder
then do dispatchBS hdl (-1) printPackets
return ()
else reorderPackets hdl
printPackets :: PktHdr -> BS.ByteString -> IO ()
printPackets !pkt !bs = do
let !(Right !q) = P.parse parseQuote bs
putStrLn $ show (pktToDiff pkt, q)
reorderPackets :: PcapHandle -> IO ()
reorderPackets !hdl = go maxDiff minDiff []
where
go !min !max !xs
| max - min >= diffSec = do mapM_ (putStrLn . show) $! sort xs
go maxDiff minDiff []
| otherwise
= do (!pkt, !bs) <- nextBS hdl
if hdrWireLength pkt == 0
then mapM_ (putStrLn . show) $! sort xs
else do let !pktTime = pktToDiff pkt
let !(Right !q) = P.parse parseQuote bs
let (nMin, nMax) = newMinMax min max
(qAcceptTime q) pktTime
go nMin nMax $!! (pktTime, q):xs
newMinMax :: DiffTime -> DiffTime -> DiffTime -> DiffTime ->
(DiffTime, DiffTime)
{-# INLINE newMinMax #-}
newMinMax !minn !maxx !qt !pt = let !mi = min minn qt
!ma = max maxx pt
in (mi, ma)
| agremm/Kospi | parsergen/seq/Main.hs | gpl-2.0 | 2,189 | 0 | 19 | 763 | 718 | 351 | 367 | 55 | 3 |
{- |
Module : $Header$
Description : Manchester syntax parser for OWL 2
Copyright : (c) DFKI GmbH, Uni Bremen 2007-2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Contains : Parser for the Manchester Syntax into Abstract Syntax of OWL 2
References : <http://www.w3.org/TR/2009/NOTE-owl2-manchester-syntax-20091027/>
-}
module OWL2.Parse where
import OWL2.AS
import OWL2.Symbols
import OWL2.Keywords
import OWL2.ColonKeywords
import Common.Keywords
import Common.Id
import Common.Lexer
import Common.Parsec
import Common.AnnoParser (commentLine)
import Common.Token (criticalKeywords)
import Common.Utils (nubOrd)
import qualified Common.IRI as IRI
import qualified Common.GlobalAnnotations as GA (PrefixMap)
import Text.ParserCombinators.Parsec
import Control.Monad (liftM2)
import Data.Char
import qualified Data.Map as Map
characters :: [Character]
characters = [minBound .. maxBound]
-- | OWL and CASL structured keywords including 'andS' and 'notS'
owlKeywords :: [String]
owlKeywords = notS : stringS : map show entityTypes
++ map show characters ++ keywords ++ criticalKeywords
ncNameStart :: Char -> Bool
ncNameStart c = isAlpha c || c == '_'
-- | rfc3987 plus '+' from scheme (scheme does not allow the dots)
ncNameChar :: Char -> Bool
ncNameChar c = isAlphaNum c || elem c ".+-_\183"
prefix :: CharParser st String
prefix = satisfy ncNameStart <:> many (satisfy ncNameChar)
iunreserved :: Char -> Bool
iunreserved c = isAlphaNum c || elem c "-._~" || ord c >= 160 && ord c <= 55295
-- maybe lower case hex-digits should be illegal
pctEncoded :: CharParser st String
pctEncoded = char '%' <:> hexDigit <:> single hexDigit
{- comma and parens are removed here
but would cause no problems for full IRIs within angle brackets -}
subDelims :: Char -> Bool
subDelims c = elem c "!$&'*+;="
iunreservedSubDelims :: String -> CharParser st Char
iunreservedSubDelims cs =
satisfy $ \ c -> iunreserved c || subDelims c || elem c cs
iunreservedPctEncodedSubDelims :: String -> CharParser st String
iunreservedPctEncodedSubDelims cs =
single (iunreservedSubDelims cs) <|> pctEncoded
ipChar :: CharParser st String
ipChar = iunreservedPctEncodedSubDelims ":@"
ifragment :: CharParser st String
ifragment = flat $ many (ipChar <|> single (char '/' <|> char '?'))
iquery :: CharParser st String
iquery = ifragment -- ignore iprivate
iregName :: CharParser st String
iregName = flat $ many $ iunreservedPctEncodedSubDelims ""
iuserinfo :: CharParser st String
iuserinfo = flat $ many $ iunreservedPctEncodedSubDelims ":"
-- | parse zero or at most n consecutive arguments
atMost :: Int -> GenParser tok st a -> GenParser tok st [a]
atMost n p = if n <= 0 then return [] else
p <:> atMost (n - 1) p <|> return []
-- | parse at least one but at most n conse
atMost1 :: Int -> GenParser tok st a -> GenParser tok st [a]
atMost1 n p = p <:> atMost (n - 1) p
decOctet :: CharParser st String
decOctet = atMost 3 digit
`checkWith` \ s -> let v = value 10 s in v <= 255 &&
(if v == 0 then s == "0" else take 1 s /= "0")
iPv4Adress :: CharParser st String
iPv4Adress = decOctet <++> string "."
<++> decOctet <++> string "."
<++> decOctet <++> string "."
<++> decOctet
ihost :: CharParser st String
ihost = iregName <|> iPv4Adress -- or ipLiteral
port :: CharParser st String
port = many digit
iauthority :: CharParser st String
iauthority = optionL (try $ iuserinfo <++> string "@") <++> ihost
<++> optionL (char ':' <:> port)
isegment :: CharParser st String
isegment = flat $ many ipChar
isegmentNz :: CharParser st String
isegmentNz = flat $ many1 ipChar
ipathAbempty :: CharParser st String
ipathAbempty = flat $ many (char '/' <:> isegment)
ipathAbsolute :: CharParser st String
ipathAbsolute = char '/' <:> optionL (isegmentNz <++> ipathAbempty)
{- within abbreviated IRIs only ipath-noscheme should be used
that excludes colons via isegment-nz-nc -}
ipathRootless :: CharParser st String
ipathRootless = isegmentNz <++> ipathAbempty
iauthorityWithPath :: CharParser st String
iauthorityWithPath = tryString "//" <++> iauthority <++> ipathAbempty
optQueryOrFrag :: CharParser st String
optQueryOrFrag = optionL (char '?' <:> iquery)
<++> optionL (char '#' <:> ifragment)
-- | covers irelative-part (therefore we omit curie)
ihierPart :: CharParser st String
ihierPart =
iauthorityWithPath <|> ipathAbsolute <|> ipathRootless
hierPartWithOpts :: CharParser st String
hierPartWithOpts = (char '#' <:> ifragment) <|> ihierPart <++> optQueryOrFrag
skips :: CharParser st a -> CharParser st a
skips = (<< skipMany
(forget space <|> forget commentLine <|> nestCommentOut <?> ""))
abbrIriNoPos :: CharParser st QName
abbrIriNoPos = try $ do
pre <- try $ prefix << char ':'
r <- hierPartWithOpts <|> return "" -- allow an empty local part
return nullQName { namePrefix = pre, localPart = r }
<|> fmap mkQName hierPartWithOpts
abbrIri :: CharParser st QName
abbrIri = do
p <- getPos
q <- abbrIriNoPos
return q { iriPos = Range [p],
iriType = if namePrefix q == "_" then NodeID else Abbreviated }
fullIri :: CharParser st QName
fullIri = do
char '<'
QN pre r _ _ p <- abbrIri
char '>'
return $ QN pre r Full (if null pre then r else pre ++ ":" ++ r) p
uriQ :: CharParser st QName
uriQ = fullIri <|> abbrIri
uriP :: CharParser st QName
uriP =
skips $ try $ checkWithUsing showQN uriQ $ \ q -> let p = namePrefix q in
if null p then notElem (localPart q) owlKeywords
else notElem p $ map (takeWhile (/= ':'))
$ colonKeywords
++ [ show d ++ e | d <- equivOrDisjointL, e <- [classesC, propertiesC]]
extEntity :: CharParser st ExtEntityType
extEntity =
fmap EntityType entityType
<|> option AnyEntity (pkeyword "Prefix" >> return Prefix)
symbItem :: GenParser Char st SymbItems
symbItem = do
ext <- extEntity
i <- uriP
return $ SymbItems ext [i]
symbItems :: GenParser Char st SymbItems
symbItems = do
ext <- extEntity
iris <- symbs
return $ SymbItems ext iris
-- | parse a comma separated list of uris
symbs :: GenParser Char st [IRI]
symbs = uriP >>= \ u -> do
commaP `followedWith` uriP
us <- symbs
return $ u : us
<|> return [u]
-- | parse a possibly kinded list of comma separated symbol pairs
symbMapItems :: GenParser Char st SymbMapItems
symbMapItems = do
ext <- extEntity
iris <- symbPairs
return $ SymbMapItems ext iris
-- | parse a comma separated list of uri pairs
symbPairs :: GenParser Char st [(IRI, Maybe IRI)]
symbPairs = uriPair >>= \ u -> do
commaP `followedWith` uriP
us <- symbPairs
return $ u : us
<|> return [u]
uriPair :: GenParser Char st (IRI, Maybe IRI)
uriPair = uriP >>= \ u -> do
pToken $ toKey mapsTo
u2 <- uriP
return (u, Just u2)
<|> return (u, Nothing)
datatypeUri :: CharParser st QName
datatypeUri = fmap mkQName (choice $ map keyword datatypeKeys) <|> uriP
optSign :: CharParser st Bool
optSign = option False $ fmap (== '-') (oneOf "+-")
postDecimal :: CharParser st NNInt
postDecimal = char '.' >> option zeroNNInt getNNInt
getNNInt :: CharParser st NNInt
getNNInt = fmap (NNInt . map digitToInt) getNumber
intLit :: CharParser st IntLit
intLit = do
b <- optSign
n <- getNNInt
return $ negNNInt b n
decimalLit :: CharParser st DecLit
decimalLit = liftM2 DecLit intLit $ option zeroNNInt postDecimal
floatDecimal :: CharParser st DecLit
floatDecimal = do
n <- getNNInt
f <- option zeroNNInt postDecimal
return $ DecLit (negNNInt False n) f
<|> do
n <- postDecimal
return $ DecLit zeroInt n
floatingPointLit :: CharParser st FloatLit
floatingPointLit = do
b <- optSign
d <- floatDecimal
i <- option zeroInt (oneOf "eE" >> intLit)
optionMaybe $ oneOf "fF"
return $ FloatLit (negDec b d) i
languageTag :: CharParser st String
languageTag = atMost1 4 letter
<++> flat (many $ char '-' <:> atMost1 8 alphaNum)
rmQuotes :: String -> String
rmQuotes s = case s of
_ : tl@(_ : _) -> init tl
_ -> error "rmQuotes"
stringLiteral :: CharParser st Literal
stringLiteral = do
s <- fmap rmQuotes stringLit
do
string cTypeS
d <- datatypeUri
return $ Literal s $ Typed d
<|> do
string asP
t <- skips $ optionMaybe languageTag
return $ Literal s $ Untyped t
<|> skips (return $ Literal s $ Typed $ mkQName stringS)
literal :: CharParser st Literal
literal = do
f <- skips $ try floatingPointLit
<|> fmap decToFloat decimalLit
return $ NumberLit f
<|> stringLiteral
-- * description
owlClassUri :: CharParser st QName
owlClassUri = uriP
individualUri :: CharParser st QName
individualUri = uriP
individual :: CharParser st Individual
individual = do
i <- individualUri
return $ if namePrefix i == "_" then i {iriType = NodeID}
else i
skipChar :: Char -> CharParser st ()
skipChar = forget . skips . char
parensP :: CharParser st a -> CharParser st a
parensP = between (skipChar '(') (skipChar ')')
bracesP :: CharParser st a -> CharParser st a
bracesP = between (skipChar '{') (skipChar '}')
bracketsP :: CharParser st a -> CharParser st a
bracketsP = between (skipChar '[') (skipChar ']')
commaP :: CharParser st ()
commaP = forget $ skipChar ','
sepByComma :: CharParser st a -> CharParser st [a]
sepByComma p = sepBy1 p commaP
-- | plain string parser with skip
pkeyword :: String -> CharParser st ()
pkeyword s = forget . keywordNotFollowedBy s $ alphaNum <|> char '/'
keywordNotFollowedBy :: String -> CharParser st Char -> CharParser st String
keywordNotFollowedBy s c = skips $ try $ string s << notFollowedBy c
-- | keyword not followed by any alphanum
keyword :: String -> CharParser st String
keyword s = keywordNotFollowedBy s (alphaNum <|> char '_')
-- base OWLClass excluded
atomic :: CharParser st ClassExpression
atomic = parensP description
<|> fmap ObjectOneOf (bracesP $ sepByComma individual)
objectPropertyExpr :: CharParser st ObjectPropertyExpression
objectPropertyExpr = do
keyword inverseS
fmap ObjectInverseOf objectPropertyExpr
<|> fmap ObjectProp uriP
-- creating the facet-value pairs
facetValuePair :: CharParser st (ConstrainingFacet, RestrictionValue)
facetValuePair = do
df <- choice $ map (\ f -> keyword (showFacet f) >> return f)
[ LENGTH
, MINLENGTH
, MAXLENGTH
, PATTERN
, TOTALDIGITS
, FRACTIONDIGITS ] ++ map
(\ f -> keywordNotFollowedBy (showFacet f) (oneOf "<>=")
>> return f)
[ MININCLUSIVE
, MINEXCLUSIVE
, MAXINCLUSIVE
, MAXEXCLUSIVE ]
rv <- literal
return (facetToIRI df, rv)
-- it returns DataType Datatype or DatatypeRestriction Datatype [facetValuePair]
dataRangeRestriction :: CharParser st DataRange
dataRangeRestriction = do
e <- datatypeUri
option (DataType e []) $ fmap (DataType e) $ bracketsP
$ sepByComma facetValuePair
dataConjunct :: CharParser st DataRange
dataConjunct = fmap (mkDataJunction IntersectionOf)
$ sepBy1 dataPrimary $ keyword andS
dataRange :: CharParser st DataRange
dataRange = fmap (mkDataJunction UnionOf)
$ sepBy1 dataConjunct $ keyword orS
dataPrimary :: CharParser st DataRange
dataPrimary = do
keyword notS
fmap DataComplementOf dataPrimary
<|> fmap DataOneOf (bracesP $ sepByComma literal)
<|> dataRangeRestriction
mkDataJunction :: JunctionType -> [DataRange] -> DataRange
mkDataJunction ty ds = case nubOrd ds of
[] -> error "mkObjectJunction"
[x] -> x
ns -> DataJunction ty ns
-- parses "some" or "only"
someOrOnly :: CharParser st QuantifierType
someOrOnly = choice
$ map (\ f -> keyword (showQuantifierType f) >> return f)
[AllValuesFrom, SomeValuesFrom]
-- locates the keywords "min" "max" "exact" and their argument
card :: CharParser st (CardinalityType, Int)
card = do
c <- choice $ map (\ f -> keywordNotFollowedBy (showCardinalityType f) letter
>> return f)
[MinCardinality, MaxCardinality, ExactCardinality]
n <- skips getNumber
return (c, value 10 n)
-- tries to parse either a QName or a literal
individualOrConstant :: CharParser st (Either Individual Literal)
individualOrConstant = fmap Right literal <|> fmap Left individual
{- | applies the previous one to a list separated by commas
(the list needs to be all of the same type, of course) -}
individualOrConstantList :: CharParser st (Either [Individual] [Literal])
individualOrConstantList = do
ioc <- individualOrConstant
case ioc of
Left u -> fmap (Left . (u :)) $ optionL
$ commaP >> sepByComma individual
Right c -> fmap (Right . (c :)) $ optionL
$ commaP >> sepByComma literal
primaryOrDataRange :: CharParser st (Either ClassExpression DataRange)
primaryOrDataRange = do
ns <- many $ keyword notS -- allows multiple not before primary
ed <- do
u <- datatypeUri
fmap Left (restrictionAny $ ObjectProp u)
<|> fmap (Right . DataType u)
(bracketsP $ sepByComma facetValuePair)
<|> return (if isDatatypeKey u
then Right $ DataType u []
else Left $ Expression u) -- could still be a datatypeUri
<|> do
e <- bracesP individualOrConstantList
return $ case e of
Left us -> Left $ ObjectOneOf us
Right cs -> Right $ DataOneOf cs
<|> fmap Left restrictionOrAtomic
return $ if even (length ns) then ed else
case ed of
Left d -> Left $ ObjectComplementOf d
Right d -> Right $ DataComplementOf d
mkObjectJunction :: JunctionType -> [ClassExpression] -> ClassExpression
mkObjectJunction ty ds = case nubOrd ds of
[] -> error "mkObjectJunction"
[x] -> x
ns -> ObjectJunction ty ns
restrictionAny :: ObjectPropertyExpression -> CharParser st ClassExpression
restrictionAny opExpr = do
keyword valueS
e <- individualOrConstant
case e of
Left u -> return $ ObjectHasValue opExpr u
Right c -> case opExpr of
ObjectProp dpExpr -> return $ DataHasValue dpExpr c
_ -> unexpected "literal"
<|> do
keyword selfS
return $ ObjectHasSelf opExpr
<|> do -- sugar
keyword onlysomeS
ds <- bracketsP $ sepByComma description
let as = map (ObjectValuesFrom SomeValuesFrom opExpr) ds
o = ObjectValuesFrom AllValuesFrom opExpr
$ mkObjectJunction UnionOf ds
return $ mkObjectJunction IntersectionOf $ o : as
<|> do -- sugar
keyword hasS
iu <- individual
return $ ObjectValuesFrom SomeValuesFrom opExpr $ ObjectOneOf [iu]
<|> do
v <- someOrOnly
pr <- primaryOrDataRange
case pr of
Left p -> return $ ObjectValuesFrom v opExpr p
Right r -> case opExpr of
ObjectProp dpExpr -> return $ DataValuesFrom v dpExpr r
_ -> unexpected $ "dataRange after " ++ showQuantifierType v
<|> do
(c, n) <- card
mp <- optionMaybe primaryOrDataRange
case mp of
Nothing -> return $ ObjectCardinality $ Cardinality c n opExpr Nothing
Just pr -> case pr of
Left p ->
return $ ObjectCardinality $ Cardinality c n opExpr $ Just p
Right r -> case opExpr of
ObjectProp dpExpr ->
return $ DataCardinality $ Cardinality c n dpExpr $ Just r
_ -> unexpected $ "dataRange after " ++ showCardinalityType c
restriction :: CharParser st ClassExpression
restriction = objectPropertyExpr >>= restrictionAny
restrictionOrAtomic :: CharParser st ClassExpression
restrictionOrAtomic = do
opExpr <- objectPropertyExpr
restrictionAny opExpr <|> case opExpr of
ObjectProp euri -> return $ Expression euri
_ -> unexpected "inverse object property"
<|> atomic
optNot :: (a -> a) -> CharParser st a -> CharParser st a
optNot f p = (keyword notS >> fmap f p) <|> p
primary :: CharParser st ClassExpression
primary = optNot ObjectComplementOf restrictionOrAtomic
conjunction :: CharParser st ClassExpression
conjunction = do
curi <- fmap Expression $ try (owlClassUri << keyword thatS)
rs <- sepBy1 (optNot ObjectComplementOf restriction) $ keyword andS
return $ mkObjectJunction IntersectionOf $ curi : rs
<|> fmap (mkObjectJunction IntersectionOf)
(sepBy1 primary $ keyword andS)
description :: CharParser st ClassExpression
description =
fmap (mkObjectJunction UnionOf) $ sepBy1 conjunction $ keyword orS
entityType :: CharParser st EntityType
entityType = choice $ map (\ f -> keyword (show f) >> return f)
entityTypes
{- | same as annotation Target in Manchester Syntax,
named annotation Value in Abstract Syntax -}
annotationValue :: CharParser st AnnotationValue
annotationValue = do
l <- literal
return $ AnnValLit l
<|> do
i <- individual
return $ AnnValue i
equivOrDisjointL :: [EquivOrDisjoint]
equivOrDisjointL = [Equivalent, Disjoint]
equivOrDisjoint :: CharParser st EquivOrDisjoint
equivOrDisjoint = choice
$ map (\ f -> pkeyword (showEquivOrDisjoint f) >> return f)
equivOrDisjointL
subPropertyKey :: CharParser st ()
subPropertyKey = pkeyword subPropertyOfC
characterKey :: CharParser st ()
characterKey = pkeyword characteristicsC
sameOrDifferent :: CharParser st SameOrDifferent
sameOrDifferent = choice
$ map (\ f -> pkeyword (showSameOrDifferent f) >> return f)
[Same, Different]
sameOrDifferentIndu :: CharParser st SameOrDifferent
sameOrDifferentIndu = (pkeyword sameIndividualC >> return Same)
<|> (pkeyword differentIndividualsC >> return Different)
equivOrDisjointKeyword :: String -> CharParser st EquivOrDisjoint
equivOrDisjointKeyword ext = choice
$ map (\ f -> pkeyword (show f ++ ext) >> return f)
equivOrDisjointL
objectPropertyCharacter :: CharParser st Character
objectPropertyCharacter =
choice $ map (\ f -> keyword (show f) >> return f) characters
domainOrRange :: CharParser st DomainOrRange
domainOrRange = choice
$ map (\ f -> pkeyword (showDomainOrRange f) >> return f)
[ADomain, ARange]
nsEntry :: CharParser st (String, QName)
nsEntry = do
pkeyword prefixC
p <- skips (option "" prefix << char ':')
i <- skips fullIri
return (p, i)
<|> do
pkeyword namespaceC
p <- skips prefix
i <- skips fullIri
return (p, i)
importEntry :: CharParser st QName
importEntry = pkeyword importC >> uriP
convertPrefixMap :: GA.PrefixMap -> Map.Map String String
convertPrefixMap = Map.map $ IRI.iriToStringUnsecure . IRI.setAngles False
| nevrenato/HetsAlloy | OWL2/Parse.hs | gpl-2.0 | 18,655 | 0 | 19 | 4,110 | 5,709 | 2,811 | 2,898 | 454 | 8 |
f' :: Maybe a -> Maybe b
f' Nothing = Nothing
f' (Just x) = Just (f x) | hmemcpy/milewski-ctfp-pdf | src/content/1.7/code/haskell/snippet03.hs | gpl-3.0 | 70 | 0 | 7 | 17 | 47 | 22 | 25 | 3 | 1 |
{-# LANGUAGE TypeOperators, GADTs, ScopedTypeVariables, Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Hoodle.Accessor
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Hoodle.Accessor where
import Control.Applicative
import Control.Lens (Simple,Lens,view,set)
import Control.Monad hiding (mapM_, forM_)
import qualified Control.Monad.State as St hiding (mapM_, forM_)
import Control.Monad.Trans
import Data.Foldable
import qualified Data.IntMap as M
import Graphics.UI.Gtk hiding (get,set)
-- from hoodle-platform
import Data.Hoodle.Generic
import Data.Hoodle.Select
import Graphics.Hoodle.Render.Type
-- from this package
-- import Hoodle.GUI.Menu
import Hoodle.GUI.Reflect
import Hoodle.ModelAction.Layer
import Hoodle.Type
import Hoodle.Type.Alias
import Hoodle.View.Coordinate
import Hoodle.Type.PageArrangement
--
import Prelude hiding (mapM_)
-- | update state
updateXState :: (HoodleState -> MainCoroutine HoodleState) -> MainCoroutine ()
updateXState action = St.put =<< action =<< St.get
-- |
getPenType :: MainCoroutine PenType
getPenType = view (penInfo.penType) <$> St.get
-- |
getCurrentPageCurr :: MainCoroutine (Page EditMode)
getCurrentPageCurr = do
xstate <- St.get
let hdlmodst = view hoodleModeState xstate
cinfobox = view currentCanvasInfo xstate
return $ forBoth' unboxBiAct (flip getCurrentPageFromHoodleModeState hdlmodst) cinfobox
-- |
getCurrentPageCvsId :: CanvasId -> MainCoroutine (Page EditMode)
getCurrentPageCvsId cid = do
xstate <- St.get
let hdlmodst = view hoodleModeState xstate
cinfobox = getCanvasInfo cid xstate
return $ forBoth' unboxBiAct (flip getCurrentPageFromHoodleModeState hdlmodst) cinfobox
-- |
getCurrentPageEitherFromHoodleModeState
:: CanvasInfo a -> HoodleModeState -> Either (Page EditMode) (Page SelectMode)
getCurrentPageEitherFromHoodleModeState cinfo hdlmodst =
let cpn = view currentPageNum cinfo
page = getCurrentPageFromHoodleModeState cinfo hdlmodst
in case hdlmodst of
ViewAppendState _hdl -> Left page
SelectState thdl ->
case view gselSelected thdl of
Nothing -> Left page
Just (n,tpage) -> if cpn == n
then Right tpage
else Left page
-- |
rItmsInCurrLyr :: MainCoroutine [RItem]
rItmsInCurrLyr = return . view gitems . getCurrentLayer =<< getCurrentPageCurr
-- |
otherCanvas :: HoodleState -> [Int]
otherCanvas = M.keys . getCanvasInfoMap
-- |
changeCurrentCanvasId :: CanvasId -> MainCoroutine HoodleState
changeCurrentCanvasId cid = do
xstate1 <- St.get
maybe (return xstate1)
(\xst -> do St.put xst
return xst)
(setCurrentCanvasId cid xstate1)
reflectViewModeUI
St.get
-- | apply an action to all canvases
applyActionToAllCVS :: (CanvasId -> MainCoroutine ()) -> MainCoroutine ()
applyActionToAllCVS action = do
xstate <- St.get
let cinfoMap = getCanvasInfoMap xstate
keys = M.keys cinfoMap
forM_ keys action
-- |
{-
printViewPortBBox :: CanvasId -> MainCoroutine ()
printViewPortBBox cid = do
cvsInfo <- return . getCanvasInfo cid =<< St.get
liftIO $ putStrLn $ show (unboxGet (viewInfo.pageArrangement.viewPortBBox) cvsInfo)
-}
-- |
{-
printViewPortBBoxAll :: MainCoroutine ()
printViewPortBBoxAll = do
xstate <- St.get
let cmap = getCanvasInfoMap xstate
cids = M.keys cmap
mapM_ printViewPortBBox cids
-}
-- |
{-
printViewPortBBoxCurr :: MainCoroutine ()
printViewPortBBoxCurr = do
cvsInfo <- return . view currentCanvasInfo =<< St.get
liftIO $ putStrLn $ show (unboxGet (viewInfo.pageArrangement.viewPortBBox) cvsInfo)
-}
-- |
{-
printModes :: CanvasId -> MainCoroutine ()
printModes cid = do
cvsInfo <- return . getCanvasInfo cid =<< St.get
liftIO $ printCanvasMode cid cvsInfo
-}
-- |
{-
printCanvasMode :: CanvasId -> CanvasInfoBox -> IO ()
printCanvasMode cid cvsInfo = do
let zmode = unboxGet (viewInfo.zoomMode) cvsInfo
f :: PageArrangement a -> String
f (SingleArrangement _ _ _) = "SingleArrangement"
f (ContinuousArrangement _ _ _ _) = "ContinuousArrangement"
g :: CanvasInfo a -> String
g cinfo = f . view (viewInfo.pageArrangement) $ cinfo
arrmode :: String
arrmode = boxAction g cvsInfo
incid = unboxGet canvasId cvsInfo
putStrLn $ show (cid,incid,zmode,arrmode)
-}
-- |
{-
printModesAll :: MainCoroutine ()
printModesAll = do
xstate <- St.get
let cmap = getCanvasInfoMap xstate
cids = M.keys cmap
mapM_ printModes cids
-}
-- |
getCanvasGeometryCvsId :: CanvasId -> HoodleState -> IO CanvasGeometry
getCanvasGeometryCvsId cid xstate = do
let cinfobox = getCanvasInfo cid xstate
cpn = PageNum . view (unboxLens currentPageNum) $ cinfobox
canvas = view (unboxLens drawArea) cinfobox
fsingle :: CanvasInfo a -> IO CanvasGeometry
fsingle = flip (makeCanvasGeometry cpn) canvas
. view (viewInfo.pageArrangement)
forBoth' unboxBiAct fsingle cinfobox
-- |
getGeometry4CurrCvs :: HoodleState -> IO CanvasGeometry
getGeometry4CurrCvs xstate = do
let cinfobox = view currentCanvasInfo xstate
cpn = PageNum . view (unboxLens currentPageNum) $ cinfobox
canvas = view (unboxLens drawArea) cinfobox
fsingle :: CanvasInfo a -> IO CanvasGeometry
fsingle = flip (makeCanvasGeometry cpn) canvas
. view (viewInfo.pageArrangement)
forBoth' unboxBiAct fsingle cinfobox
-- | update flag in HoodleState when corresponding toggle UI changed
updateFlagFromToggleUI :: String -- ^ UI toggle button id
-> Simple Lens HoodleState Bool -- ^ lens for flag
-> MainCoroutine Bool
updateFlagFromToggleUI toggleid lensforflag = do
xstate <- St.get
let ui = view gtkUIManager xstate
agr <- liftIO ( uiManagerGetActionGroups ui >>= \x ->
case x of
[] -> error "No action group? "
y:_ -> return y )
togglea <- liftIO (actionGroupGetAction agr toggleid)
>>= maybe (error "updateFlagFromToggleUI")
(return . castToToggleAction)
b <- liftIO $ toggleActionGetActive togglea
St.modify (set lensforflag b)
return b
-- | set toggle UI button to the corresponding HoodleState
setToggleUIForFlag :: String
-> Simple Lens HoodleState Bool -- ^ lens for flag
-> HoodleState
-> IO Bool
setToggleUIForFlag toggleid lensforflag xstate = do
let ui = view gtkUIManager xstate
b = view lensforflag xstate
agr <- uiManagerGetActionGroups ui >>= \x ->
case x of
[] -> error "No action group? "
y:_ -> return y
togglea <- actionGroupGetAction agr toggleid >>= \(Just x) ->
return (castToToggleAction x)
toggleActionSetActive togglea b
return b
| wavewave/hoodle-core | src/Hoodle/Accessor.hs | gpl-3.0 | 7,463 | 0 | 15 | 1,895 | 1,385 | 711 | 674 | 117 | 4 |
{-
Python5 — a hypothetic language
Copyright (C) 2015 - Yuriy Syrovetskiy
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE NoImplicitPrelude #-}
module Operator where
import Prelude ( ($) )
import Python5.Builtin
import Test.Tasty.HUnit.X
spec :: TestTree
spec = testCase "operators" $ do
1 / 2 @?= float(0.5)
17 // 3 @?= int(5)
2 ** 3 @?= int(8)
| cblp/python5 | python5/tests/Operator.hs | gpl-3.0 | 1,008 | 0 | 10 | 236 | 96 | 53 | 43 | 10 | 1 |
{-|
Module : Common.Db.FileAccess
Description : Read and write from files
Copyright : (C) Marcus Pedersén, 2014
License : GPLv3
Maintainer : [email protected]
Stability : Stable
Portability : Portable
Version : v1.0.0
Handles read and write from files in a generic way.
Saves files in a subdirectory named "db".
-}
module Common.Db.FileAccess where
import System.FilePath
import System.Directory
import System.IO
{-|
Saves string to given file on a new line.
If file or subdirectory does not exist,
directory and/or file will be created.
File is relative to execution directory
and will be saved at: db/filename.ext
-}
appendDataToFileLn :: String -> String -> IO ()
appendDataToFileLn str2write fileName = do
createDirectoryIfMissing True "db"
appendFile file $ str2write ++ "\n"
where
file = "db" ++ pathSeparator:(takeFileName fileName)
{-|
Reads a newline separated file
and returns an array of strings
where each string is a line in the file.
File is relative to execution directory
and must exist in subfolder "db".
-}
readFileLnSeparated :: String -> IO ([String])
readFileLnSeparated fileName = do
cont <- readFile file
length cont `seq` (return $ lines cont)
where file = "db" ++ pathSeparator:(takeFileName fileName)
{-|
Deletes given string line from
file if it exists.
File is relative to execution directory
and must exist in subfolder "db".
-}
deleteLnFromFile :: String -> String -> IO ()
deleteLnFromFile str2del fileName = do
strings <- readFileLnSeparated fileName
writeFile file . unlines $ delStr str2del strings
where file = "db" ++ pathSeparator:(takeFileName fileName)
delStr str (x:xs)
| str == x = delStr str xs
| otherwise = x:delStr str xs
delStr _ [] = []
| xmarcux/MyOfficeState | src/Common/Db/FileAccess.hs | gpl-3.0 | 1,831 | 0 | 10 | 409 | 318 | 159 | 159 | 23 | 2 |
module Response.Graph
(graphResponse) where
import Happstack.Server
import MasterTemplate
import Scripts
import Text.Blaze ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
graphResponse :: ServerPart Response
graphResponse =
ok $ toResponse $
masterTemplate "Courseography - Graph"
[]
(do
header "graph"
H.div ! A.id "container" $ ""
)
graphScripts
| Courseography/courseography | app/Response/Graph.hs | gpl-3.0 | 512 | 0 | 13 | 166 | 112 | 65 | 47 | 17 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Testing.Types
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Testing.Types
(
-- * Service Configuration
testingService
-- * OAuth Scopes
, cloudPlatformReadOnlyScope
, cloudPlatformScope
-- * TestDetails
, TestDetails
, testDetails
, tdProgressMessages
, tdErrorMessage
-- * IntentFilter
, IntentFilter
, intentFilter
, ifActionNames
, ifMimeType
, ifCategoryNames
-- * IosTestSetup
, IosTestSetup
, iosTestSetup
, itsAdditionalIPas
, itsPullDirectories
, itsNetworkProFile
, itsPushFiles
-- * Shard
, Shard
, shard
, sShardIndex
, sTestTargetsForShard
, sNumShards
-- * TestExecution
, TestExecution
, testExecution
, teTestDetails
, teShard
, teState
, teEnvironment
, teTestSpecification
, teMatrixId
, teId
, teProjectId
, teToolResultsStep
, teTimestamp
-- * IosTestLoop
, IosTestLoop
, iosTestLoop
, itlScenarios
, itlAppBundleId
, itlAppIPa
-- * IosVersion
, IosVersion
, iosVersion
, ivMinorVersion
, ivMajorVersion
, ivSupportedXcodeVersionIds
, ivId
, ivTags
-- * IosDeviceList
, IosDeviceList
, iosDeviceList
, idlIosDevices
-- * RoboDirective
, RoboDirective
, roboDirective
, rdResourceName
, rdInputText
, rdActionType
-- * AndroidRuntimeConfiguration
, AndroidRuntimeConfiguration
, androidRuntimeConfiguration
, arcOrientations
, arcLocales
-- * XcodeVersion
, XcodeVersion
, xcodeVersion
, xvVersion
, xvTags
-- * SystraceSetup
, SystraceSetup
, systraceSetup
, ssDurationSeconds
-- * Distribution
, Distribution
, distribution
, dMeasurementTime
, dMarketShare
-- * TestMatrixState
, TestMatrixState (..)
-- * IosModel
, IosModel
, iosModel
, imFormFactor
, imScreenX
, imScreenDensity
, imName
, imSupportedVersionIds
, imScreenY
, imId
, imDeviceCapabilities
, imTags
-- * APK
, APK
, aPK
, aPackageName
, aLocation
-- * NetworkConfigurationCatalog
, NetworkConfigurationCatalog
, networkConfigurationCatalog
, nccConfigurations
-- * TestMatrixInvalidMatrixDetails
, TestMatrixInvalidMatrixDetails (..)
-- * IosDevice
, IosDevice
, iosDevice
, idLocale
, idIosModelId
, idIosVersionId
, idOrientation
-- * GetAPKDetailsResponse
, GetAPKDetailsResponse
, getAPKDetailsResponse
, gapkdrAPKDetail
-- * AndroidRoboTest
, AndroidRoboTest
, androidRoboTest
, artRoboDirectives
, artRoboScript
, artStartingIntents
, artAppInitialActivity
, artMaxSteps
, artRoboMode
, artAppPackageId
, artAppBundle
, artAppAPK
, artMaxDepth
-- * FileReference
, FileReference
, fileReference
, frGcsPath
-- * Environment
, Environment
, environment
, eIosDevice
, eAndroidDevice
-- * ToolResultsHistory
, ToolResultsHistory
, toolResultsHistory
, trhHistoryId
, trhProjectId
-- * TestEnvironmentCatalog
, TestEnvironmentCatalog
, testEnvironmentCatalog
, tecSoftwareCatalog
, tecNetworkConfigurationCatalog
, tecAndroidDeviceCatalog
, tecIosDeviceCatalog
, tecDeviceIPBlockCatalog
-- * Locale
, Locale
, locale
, lName
, lId
, lRegion
, lTags
-- * AndroidDeviceCatalog
, AndroidDeviceCatalog
, androidDeviceCatalog
, adcVersions
, adcModels
, adcRuntimeConfiguration
-- * AndroidInstrumentationTestOrchestratorOption
, AndroidInstrumentationTestOrchestratorOption (..)
-- * IosDeviceFile
, IosDeviceFile
, iosDeviceFile
, idfDevicePath
, idfBundleId
, idfContent
-- * TestExecutionState
, TestExecutionState (..)
-- * TestEnvironmentCatalogGetEnvironmentType
, TestEnvironmentCatalogGetEnvironmentType (..)
-- * TestSpecification
, TestSpecification
, testSpecification
, tsIosTestSetup
, tsIosTestLoop
, tsTestTimeout
, tsAndroidRoboTest
, tsDisableVideoRecording
, tsAndroidInstrumentationTest
, tsIosXcTest
, tsDisablePerformanceMetrics
, tsTestSetup
, tsAndroidTestLoop
-- * TestTargetsForShard
, TestTargetsForShard
, testTargetsForShard
, ttfsTestTargets
-- * TestMatrixOutcomeSummary
, TestMatrixOutcomeSummary (..)
-- * ProvidedSoftwareCatalog
, ProvidedSoftwareCatalog
, providedSoftwareCatalog
, pscOrchestratorVersion
, pscAndroidxOrchestratorVersion
-- * TrafficRule
, TrafficRule
, trafficRule
, trPacketLossRatio
, trPacketDuplicationRatio
, trBandwidth
, trBurst
, trDelay
-- * IosDeviceCatalog
, IosDeviceCatalog
, iosDeviceCatalog
, idcXcodeVersions
, idcVersions
, idcModels
, idcRuntimeConfiguration
-- * GoogleAuto
, GoogleAuto
, googleAuto
-- * DeviceIPBlockForm
, DeviceIPBlockForm (..)
-- * CancelTestMatrixResponseTestState
, CancelTestMatrixResponseTestState (..)
-- * Account
, Account
, account
, aGoogleAuto
-- * RoboDirectiveActionType
, RoboDirectiveActionType (..)
-- * StartActivityIntent
, StartActivityIntent
, startActivityIntent
, saiURI
, saiCategories
, saiAction
-- * IosModelFormFactor
, IosModelFormFactor (..)
-- * RoboStartingIntent
, RoboStartingIntent
, roboStartingIntent
, rsiLauncherActivity
, rsiStartActivity
, rsiTimeout
-- * Date
, Date
, date
, dDay
, dYear
, dMonth
-- * RegularFile
, RegularFile
, regularFile
, rfDevicePath
, rfContent
-- * AndroidModel
, AndroidModel
, androidModel
, amThumbnailURL
, amSupportedAbis
, amManufacturer
, amCodename
, amLowFpsVideoRecording
, amFormFactor
, amBrand
, amScreenX
, amScreenDensity
, amName
, amSupportedVersionIds
, amScreenY
, amId
, amForm
, amTags
-- * ClientInfo
, ClientInfo
, clientInfo
, ciName
, ciClientInfoDetails
-- * AndroidModelFormFactor
, AndroidModelFormFactor (..)
-- * ShardingOption
, ShardingOption
, shardingOption
, soUniformSharding
, soManualSharding
-- * AndroidModelForm
, AndroidModelForm (..)
-- * Xgafv
, Xgafv (..)
-- * APKManifest
, APKManifest
, aPKManifest
, apkmApplicationLabel
, apkmMinSdkVersion
, apkmTargetSdkVersion
, apkmPackageName
, apkmIntentFilters
, apkmMaxSdkVersion
, apkmUsesPermission
-- * AppBundle
, AppBundle
, appBundle
, abBundleLocation
-- * AndroidInstrumentationTest
, AndroidInstrumentationTest
, androidInstrumentationTest
, aitTestTargets
, aitTestRunnerClass
, aitAppPackageId
, aitTestAPK
, aitShardingOption
, aitOrchestratorOption
, aitAppBundle
, aitAppAPK
, aitTestPackageId
-- * TestMatrix
, TestMatrix
, testMatrix
, tmState
, tmTestMatrixId
, tmTestSpecification
, tmOutcomeSummary
, tmFlakyTestAttempts
, tmClientInfo
, tmTestExecutions
, tmFailFast
, tmResultStorage
, tmInvalidMatrixDetails
, tmProjectId
, tmEnvironmentMatrix
, tmTimestamp
-- * CancelTestMatrixResponse
, CancelTestMatrixResponse
, cancelTestMatrixResponse
, ctmrTestState
-- * ToolResultsExecution
, ToolResultsExecution
, toolResultsExecution
, treExecutionId
, treHistoryId
, treProjectId
-- * UniformSharding
, UniformSharding
, uniformSharding
, usNumShards
-- * IosXcTest
, IosXcTest
, iosXcTest
, ixtXctestrun
, ixtXcodeVersion
, ixtTestSpecialEntitlements
, ixtAppBundleId
, ixtTestsZip
-- * ResultStorage
, ResultStorage
, resultStorage
, rsToolResultsHistory
, rsResultsURL
, rsToolResultsExecution
, rsGoogleCloudStorage
-- * AndroidMatrix
, AndroidMatrix
, androidMatrix
, amAndroidModelIds
, amAndroidVersionIds
, amOrientations
, amLocales
-- * ToolResultsStep
, ToolResultsStep
, toolResultsStep
, trsExecutionId
, trsStepId
, trsHistoryId
, trsProjectId
-- * DeviceIPBlock
, DeviceIPBlock
, deviceIPBlock
, dibAddedDate
, dibBlock
, dibForm
-- * LauncherActivityIntent
, LauncherActivityIntent
, launcherActivityIntent
-- * APKDetail
, APKDetail
, aPKDetail
, apkdAPKManifest
-- * AndroidDevice
, AndroidDevice
, androidDevice
, adAndroidVersionId
, adLocale
, adAndroidModelId
, adOrientation
-- * EnvironmentVariable
, EnvironmentVariable
, environmentVariable
, evValue
, evKey
-- * DeviceIPBlockCatalog
, DeviceIPBlockCatalog
, deviceIPBlockCatalog
, dibcIPBlocks
-- * Orientation
, Orientation
, orientation
, oName
, oId
, oTags
-- * EnvironmentMatrix
, EnvironmentMatrix
, environmentMatrix
, emIosDeviceList
, emAndroidMatrix
, emAndroidDeviceList
-- * DeviceFile
, DeviceFile
, deviceFile
, dfRegularFile
, dfObbFile
-- * ManualSharding
, ManualSharding
, manualSharding
, msTestTargetsForShard
-- * ClientInfoDetail
, ClientInfoDetail
, clientInfoDetail
, cidValue
, cidKey
-- * AndroidRoboTestRoboMode
, AndroidRoboTestRoboMode (..)
-- * NetworkConfiguration
, NetworkConfiguration
, networkConfiguration
, ncDownRule
, ncId
, ncUpRule
-- * IosRuntimeConfiguration
, IosRuntimeConfiguration
, iosRuntimeConfiguration
, ircOrientations
, ircLocales
-- * GoogleCloudStorage
, GoogleCloudStorage
, googleCloudStorage
, gcsGcsPath
-- * AndroidVersion
, AndroidVersion
, androidVersion
, avCodeName
, avDistribution
, avAPILevel
, avVersionString
, avId
, avReleaseDate
, avTags
-- * ObbFile
, ObbFile
, obbFile
, ofObb
, ofObbFileName
-- * AndroidTestLoop
, AndroidTestLoop
, androidTestLoop
, atlScenarios
, atlScenarioLabels
, atlAppPackageId
, atlAppBundle
, atlAppAPK
-- * AndroidDeviceList
, AndroidDeviceList
, androidDeviceList
, adlAndroidDevices
-- * TestSetup
, TestSetup
, testSetup
, tsDontAutograntPermissions
, tsSystrace
, tsAccount
, tsNetworkProFile
, tsEnvironmentVariables
, tsAdditionalAPKs
, tsFilesToPush
, tsDirectoriesToPull
) where
import Network.Google.Prelude
import Network.Google.Testing.Types.Product
import Network.Google.Testing.Types.Sum
-- | Default request referring to version 'v1' of the Cloud Testing API. This contains the host and root path used as a starting point for constructing service requests.
testingService :: ServiceConfig
testingService
= defaultService (ServiceId "testing:v1")
"testing.googleapis.com"
-- | View your data across Google Cloud Platform services
cloudPlatformReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform.read-only"]
cloudPlatformReadOnlyScope = Proxy
-- | See, edit, configure, and delete your Google Cloud Platform data
cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"]
cloudPlatformScope = Proxy
| brendanhay/gogol | gogol-testing/gen/Network/Google/Testing/Types.hs | mpl-2.0 | 12,112 | 0 | 7 | 3,309 | 1,451 | 1,001 | 450 | 420 | 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.KMS.RevokeGrant
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Revokes a grant. You can revoke a grant to actively deny operations that
-- depend on it.
--
-- <http://docs.aws.amazon.com/kms/latest/APIReference/API_RevokeGrant.html>
module Network.AWS.KMS.RevokeGrant
(
-- * Request
RevokeGrant
-- ** Request constructor
, revokeGrant
-- ** Request lenses
, rgGrantId
, rgKeyId
-- * Response
, RevokeGrantResponse
-- ** Response constructor
, revokeGrantResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.KMS.Types
import qualified GHC.Exts
data RevokeGrant = RevokeGrant
{ _rgGrantId :: Text
, _rgKeyId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'RevokeGrant' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rgGrantId' @::@ 'Text'
--
-- * 'rgKeyId' @::@ 'Text'
--
revokeGrant :: Text -- ^ 'rgKeyId'
-> Text -- ^ 'rgGrantId'
-> RevokeGrant
revokeGrant p1 p2 = RevokeGrant
{ _rgKeyId = p1
, _rgGrantId = p2
}
-- | Identifier of the grant to be revoked.
rgGrantId :: Lens' RevokeGrant Text
rgGrantId = lens _rgGrantId (\s a -> s { _rgGrantId = a })
-- | A unique identifier for the customer master key associated with the grant.
-- This value can be a globally unique identifier or the fully specified ARN to
-- a key. Key ARN Example -
-- arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012 Globally Unique Key ID Example - 12345678-1234-1234-123456789012
--
rgKeyId :: Lens' RevokeGrant Text
rgKeyId = lens _rgKeyId (\s a -> s { _rgKeyId = a })
data RevokeGrantResponse = RevokeGrantResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'RevokeGrantResponse' constructor.
revokeGrantResponse :: RevokeGrantResponse
revokeGrantResponse = RevokeGrantResponse
instance ToPath RevokeGrant where
toPath = const "/"
instance ToQuery RevokeGrant where
toQuery = const mempty
instance ToHeaders RevokeGrant
instance ToJSON RevokeGrant where
toJSON RevokeGrant{..} = object
[ "KeyId" .= _rgKeyId
, "GrantId" .= _rgGrantId
]
instance AWSRequest RevokeGrant where
type Sv RevokeGrant = KMS
type Rs RevokeGrant = RevokeGrantResponse
request = post "RevokeGrant"
response = nullResponse RevokeGrantResponse
| kim/amazonka | amazonka-kms/gen/Network/AWS/KMS/RevokeGrant.hs | mpl-2.0 | 3,384 | 0 | 9 | 774 | 425 | 260 | 165 | 55 | 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.Compute.Instances.Stop
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Stops a running instance, shutting it down cleanly, and allows you to
-- restart the instance at a later time. Stopped instances do not incur VM
-- usage charges while they are stopped. However, resources that the VM is
-- using, such as persistent disks and static IP addresses, will continue
-- to be charged until they are deleted. For more information, see Stopping
-- an instance.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.stop@.
module Network.Google.Resource.Compute.Instances.Stop
(
-- * REST Resource
InstancesStopResource
-- * Creating a Request
, instancesStop
, InstancesStop
-- * Request Lenses
, isRequestId
, isProject
, isZone
, isInstance
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instances.stop@ method which the
-- 'InstancesStop' request conforms to.
type InstancesStopResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instances" :>
Capture "instance" Text :>
"stop" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] Operation
-- | Stops a running instance, shutting it down cleanly, and allows you to
-- restart the instance at a later time. Stopped instances do not incur VM
-- usage charges while they are stopped. However, resources that the VM is
-- using, such as persistent disks and static IP addresses, will continue
-- to be charged until they are deleted. For more information, see Stopping
-- an instance.
--
-- /See:/ 'instancesStop' smart constructor.
data InstancesStop =
InstancesStop'
{ _isRequestId :: !(Maybe Text)
, _isProject :: !Text
, _isZone :: !Text
, _isInstance :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstancesStop' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'isRequestId'
--
-- * 'isProject'
--
-- * 'isZone'
--
-- * 'isInstance'
instancesStop
:: Text -- ^ 'isProject'
-> Text -- ^ 'isZone'
-> Text -- ^ 'isInstance'
-> InstancesStop
instancesStop pIsProject_ pIsZone_ pIsInstance_ =
InstancesStop'
{ _isRequestId = Nothing
, _isProject = pIsProject_
, _isZone = pIsZone_
, _isInstance = pIsInstance_
}
-- | 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).
isRequestId :: Lens' InstancesStop (Maybe Text)
isRequestId
= lens _isRequestId (\ s a -> s{_isRequestId = a})
-- | Project ID for this request.
isProject :: Lens' InstancesStop Text
isProject
= lens _isProject (\ s a -> s{_isProject = a})
-- | The name of the zone for this request.
isZone :: Lens' InstancesStop Text
isZone = lens _isZone (\ s a -> s{_isZone = a})
-- | Name of the instance resource to stop.
isInstance :: Lens' InstancesStop Text
isInstance
= lens _isInstance (\ s a -> s{_isInstance = a})
instance GoogleRequest InstancesStop where
type Rs InstancesStop = Operation
type Scopes InstancesStop =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient InstancesStop'{..}
= go _isProject _isZone _isInstance _isRequestId
(Just AltJSON)
computeService
where go
= buildClient (Proxy :: Proxy InstancesStopResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Instances/Stop.hs | mpl-2.0 | 5,113 | 5 | 19 | 1,179 | 564 | 342 | 222 | 84 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Data.Array (listArray)
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Matrix (saddlePoints)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "saddle-points" $
describe "saddlePoints" $ for_ cases test
where
test (description, xss, expected) = it description assertion
where
assertion = saddlePoints matrix `shouldBe` expected
rows = length xss
columns = length $ head xss
matrix = listArray ((0, 0), (rows - 1, columns - 1)) (concat xss)
-- As of 2016-09-12, there was no reference file
-- for the test cases in `exercism/x-common`.
cases = [ ("Example from README", [ [9, 8, 7]
, [5, 3, 2]
, [6, 6, 7] ], [(1, 0)] )
, ( "no saddle point", [ [2, 1]
, [1, 2] ], [] )
, ( "a saddle point", [ [1, 2]
, [3, 4] ], [(0, 1)] )
, ( "another saddle point", [ [18, 3, 39, 19, 91]
, [38, 10, 8, 77, 320]
, [ 3, 4, 8, 6, 7] ], [(2, 2)] )
, ("multiple saddle points", [ [4, 5, 4]
, [3, 5, 5]
, [1, 5, 4] ], [ (0, 1)
, (1, 1)
, (2, 1) ] )
]
| daewon/til | exercism/haskell/saddle-points/test/Tests.hs | mpl-2.0 | 1,732 | 0 | 12 | 805 | 510 | 316 | 194 | 31 | 1 |
module Send (
module Control.Concurrent, module Control.Concurrent.STM
, SenderChan, clearSender, senderThread
) where
import System.IO
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Helpers
type SenderChan = TChan String
chunkSend :: Integer -> Integer -> IO a -> IO ()
chunkSend delay burst f = loop 0 =<< getMicroTime where
maxWait = delay * burst
loop buf'' tlast = do
tnow <- getMicroTime
let buf = max 0 (buf'' - (tnow-tlast))
if buf <= maxWait
then f >> loop (buf+delay) tnow
else do
let wait = buf - maxWait
threadDelay $ fromIntegral wait
loop (buf-delay) (tnow+delay)
senderThread :: Handle -> SenderChan -> IO ()
senderThread sock buffer = chunkSend 2500000 4 $ do
string <- atomically $ readTChan buffer
hPutStrLn sock string
putStrLn $ "\x1B[31;1m<<\x1B[30;0m " ++ show string
clearSender :: SenderChan -> IO ()
clearSender buffer = atomically loop where
loop = do
isempty <- isEmptyTChan buffer
unless isempty $ do
readTChan buffer
loop
| DDOS-code/rivertam | src/Send.hs | agpl-3.0 | 1,038 | 8 | 16 | 204 | 379 | 189 | 190 | 33 | 2 |
import Network.MessagePackRpc.Client
ping :: RpcMethod (String -> IO String)
ping = method "ping"
main = do
conn <- connect "127.0.0.1" 9000
print =<< ping conn "haskell client calling."
| turkia/msgpack_rpc_server | examples/haskell/ping.hs | lgpl-3.0 | 194 | 0 | 8 | 35 | 62 | 30 | 32 | 6 | 1 |
{--
1. 2 + 2 * 3 -1
Prelude> 2 + 2 * 3 - 1
7
Prelude> 2 + (2 * 3) - 1
7
2.
Prelude> (^) 10 $ 1 + 1
100
Prelude> (1 + 1) ^ 10
1024
Prelude> 10 ^ (1 + 1)
100
3.
Prelude> 2 ^ 2 * 4 ^ 5 + 1
4097
Prelude> (2 ^ 2) * (4 ^ 5) + 1
4097
Prelude> ((2 ^ 2) * (4 ^ 5)) + 1
4097
Equivalent expressions
1. Same result
Prelude> 1 + 1
2
2. Same result
Prelude> 10 ^ 2
100
Prelude> 10 + 9 * 10
100
3. Different result
Prelude> 400 - 37
363
Prelude> (-) 37 400
-363
4. Different result
Prelude> 100 `div` 3
33
Prelude> 100 / 3
33.333333333333336
5. Different result
Prelude> 2 * 5 + 18
28
Prelude> 2 * (5 + 18)
46
More fun with functions
Prelude> z = 7
Prelude> x = y ^ 2
<interactive>:24:5: error: Variable not in scope: y
Prelude> y = z + 8
Prelude> x = y ^ 2
Prelude> waxOn = x * 5
Manual work here
z = 7
y = z + 8 = 15
x = y ^ 2 = 15 ^ 2 = 225
waxOn = x * 5 = 225 * 5 = 1125
1. 10 + waxOn = 1135
Prelude> 10 + waxOn
1135
(+10) waxOn = 1135
Prelude> (+10) waxOn
1135
(-) 15 waxOn = -1110
Prelude> (-) 15 waxOn
-1110
(-) waxOn 15 = 1110
Prelude> (-) waxOn 15
1110
2. and 3.
Prelude> triple x = x * 3
Prelude> triple waxOn
3375
--}
waxOn = x * 5
where z = 7
x = y ^ 2
y = z + 8
triple x = x * 3
waxOff x = triple x
{--
*Main> waxOff 10
30
*Main>
*Main> waxOff (-50)
-150
--}
| dmp1ce/Haskell-Programming-Exercises | Chapter 2/Chapter Exercises.hs | unlicense | 1,318 | 0 | 7 | 381 | 60 | 32 | 28 | 6 | 1 |
main :: IO ()
main = putStrLn "Benchmarks not yet implemented"
| mgattozzi/curryrs | haskell/benches/Benches.hs | apache-2.0 | 63 | 0 | 6 | 11 | 19 | 9 | 10 | 2 | 1 |
-- Copyright 2022 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module MLIR.AST.Dialect.Func
( module MLIR.AST.Dialect.Generated.Func
) where
import MLIR.AST.Dialect.Generated.Func
| google/mlir-hs | src/MLIR/AST/Dialect/Func.hs | apache-2.0 | 711 | 0 | 5 | 115 | 40 | 33 | 7 | 3 | 0 |
cdiv m n = ceiling $ (fromIntegral m) / (fromIntegral n)
ans' (a:[]) = []
ans' (a1:a2:as) = ((a2-a1-1)`cdiv`2):(ans' (a2:as))
ans [[n,m],a@(a1:as)] = maximum $ (a1-1):(ans' (a++[n+(n-al)]))
where
al = last a
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Int]]
o = ans i
print o
| a143753/AOJ | 1574.hs | apache-2.0 | 330 | 0 | 14 | 79 | 255 | 134 | 121 | 10 | 1 |
-- http://www.codewars.com/kata/547202bdf7587835d9000c46
{-# LANGUAGE NoImplicitPrelude #-}
module Monads where
import Prelude hiding (Monad, Identity, Maybe(..), State, Reader, Writer)
import Data.Monoid
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
data Identity a = Identity a
deriving (Show, Eq)
data Maybe a = Nothing | Just a
deriving (Show, Eq)
data State s a = State {runState :: s -> (a, s)}
data Reader s a = Reader {runReader :: s -> a }
data Writer w a = Writer {runWriter :: (w, a)}
instance Monad Identity where
return = Identity
(Identity v) >>= f = f v
instance Monad Maybe where
return = Just
Nothing >>= f = Nothing
(Just v) >>= f = f v
instance Monad (State s) where
return x = State (\s -> (x, s))
(State g) >>= f = State (\s -> let (a, s') = g s in runState (f a) s')
instance Monad (Reader s) where
return a = Reader (\_ -> a)
(Reader g) >>= f = Reader (\s -> (runReader . f . g) s s)
instance Monoid w => Monad (Writer w) where
return x = Writer (mempty, x)
(Writer (s, v)) >>= f = Writer (s `mappend` s', v') where
Writer (s', v') = f v
| Bodigrim/katas | src/haskell/B-Five-Fundamental-Monads.hs | bsd-2-clause | 1,134 | 0 | 13 | 266 | 556 | 300 | 256 | 31 | 0 |
module Drasil.SWHS.TMods (PhaseChange(Liquid), consThermE, latentHtE,
nwtnCooling, sensHtE, sensHtETemplate, tMods) where
import Language.Drasil
import Control.Lens ((^.))
import Theory.Drasil (TheoryModel, tm)
import Utils.Drasil
import Data.Drasil.Concepts.Documentation (system)
import Data.Drasil.Concepts.Math (equation, rate, rOfChng)
import Data.Drasil.Concepts.Physics (mechEnergy)
import Data.Drasil.Concepts.Thermodynamics (heatTrans, lawConsEnergy,
lawConvCooling, phaseChange, thermalEnergy)
import Data.Drasil.Quantities.Math (gradient)
import Data.Drasil.Quantities.PhysicalProperties (density, mass)
import Data.Drasil.Quantities.Physics (energy, time)
import Data.Drasil.Quantities.Thermodynamics (boilPt, heatCapSpec,
htFlux, latentHeat, meltPt, sensHeat, temp)
import Drasil.SWHS.Assumptions (assumpHTCC, assumpTEO)
import Drasil.SWHS.Concepts (transient)
import Drasil.SWHS.DataDefs (ddMeltFrac)
import Drasil.SWHS.References (incroperaEtAl2007)
import Drasil.SWHS.Unitals (deltaT, htCapL, htCapS, htCapV, htTransCoeff,
meltFrac, tau, tempEnv, thFluxVect, volHtGen)
tMods :: [TheoryModel]
tMods = [consThermE, sensHtE, latentHtE, nwtnCooling]
-------------------------
-- Theoretical Model 1 --
-------------------------
consThermE :: TheoryModel
consThermE = tm consThermERC
[qw thFluxVect, qw gradient, qw volHtGen,
qw density, qw heatCapSpec, qw temp, qw time] ([] :: [ConceptChunk])
[] [consThermERel] [] [consThemESrc] "consThermE" consThermENotes
consThermERC :: RelationConcept
consThermERC = makeRC "consThermERC"
(nounPhraseSP "Conservation of thermal energy") (lawConsEnergy ^. defn) consThermERel
consThermERel :: Relation
consThermERel = negate (sy gradient) $. sy thFluxVect + sy volHtGen $=
sy density * sy heatCapSpec * pderiv (sy temp) time
-- the second argument is a 'ShortName'...
consThemESrc :: Reference
consThemESrc = makeURI "consThemESrc"
"http://www.efunda.com/formulae/heat_transfer/conduction/overview_cond.cfm" $
shortname' "Fourier Law of Heat Conduction and Heat Equation"
consThermENotes :: [Sentence]
consThermENotes = map foldlSent [
[S "The above", phrase equation, S "gives the", phrase lawConsEnergy,
S "for", phrase transient, phrase heatTrans, S "in a given material"],
[S "For this", phrase equation, S "to apply" `sC` S "other forms" `sOf`
phrase energy `sC` S "such as", phrase mechEnergy `sC` S "are assumed",
S "to be negligible" `inThe` phrase system, sParen (makeRef2S assumpTEO)]]
-------------------------
-- Theoretical Model 2 --
-------------------------
sensHtE :: TheoryModel
sensHtE = sensHtETemplate AllPhases sensHtEdesc
data PhaseChange = AllPhases
| Liquid
sensHtETemplate :: PhaseChange -> Sentence -> TheoryModel
sensHtETemplate pc desc = tm (sensHtERC pc eqn desc)
[qw sensHeat, qw htCapS, qw mass,
qw deltaT, qw meltPt, qw temp, qw htCapL, qw boilPt, qw htCapV] ([] :: [ConceptChunk])
[] [eqn] [] [sensHtESrc] "sensHtE" [desc] where
eqn = sensHtEEqn pc
sensHtERC :: PhaseChange -> Relation -> Sentence -> RelationConcept
sensHtERC pc eqn desc = makeRC "sensHtERC" (nounPhraseSP ("Sensible heat energy" ++ case pc of
Liquid -> " (no state change)"
AllPhases -> "")) desc eqn
sensHtESrc :: Reference
sensHtESrc = makeURI "sensHtESrc"
"http://en.wikipedia.org/wiki/Sensible_heat" $
shortname' "Definition of Sensible Heat"
sensHtEEqn :: PhaseChange -> Relation
sensHtEEqn pChange = sy sensHeat $= case pChange of
Liquid -> liquidFormula
AllPhases -> incompleteCase [(sy htCapS * sy mass * sy deltaT,
sy temp $< sy meltPt), (liquidFormula, sy meltPt $< sy temp $<
sy boilPt), (sy htCapV * sy mass *
sy deltaT, sy boilPt $< sy temp)]
where
liquidFormula = sy htCapL * sy mass * sy deltaT
--When to call with C? When to call with U, S, Sy, etc? Sometimes confusing.
--Figured out why so many were defn and others were term. The unitals
-- were implemented incorrectly.
sensHtEdesc :: Sentence
sensHtEdesc = foldlSent [
atStart sensHeat :+: S "ing occurs as long as the material does not reach a",
phrase temp, S "where a", phrase phaseChange, S "occurs. A", phrase phaseChange,
S "occurs if" +:+. (E (sy temp $= sy boilPt) `sOr` E (sy temp $= sy meltPt)),
S "If this is the case" `sC` S "refer to", makeRef2S latentHtE]
--How to have new lines in the description?
--Can't have relation and eqn chunks together since they are called in a list
----You can, you just can't map "Definition" over a list
---- you have to do each separately
--How to have multiple possible equations?
--How to have conditions in the equation section?
-------------------------
-- Theoretical Model 3 --
-------------------------
latentHtE :: TheoryModel
latentHtE = tm latentHtERC
[qw latentHeat, qw time, qw tau] ([] :: [ConceptChunk])
[] [latHtEEqn] [] [latHtESrc] "latentHtE" latentHtENotes
latentHtERC :: RelationConcept
latentHtERC = makeRC "latentHtERC"
(nounPhraseSP "Latent heat energy") (latentHeat ^. defn) latHtEEqn
latHtEEqn :: Relation
latHtEEqn = apply1 latentHeat time $=
defint (eqSymb tau) 0 (sy time) (deriv (apply1 latentHeat tau) tau)
-- Integrals need dTau at end
latHtESrc :: Reference
latHtESrc = makeURI "latHtESrc" "http://en.wikipedia.org/wiki/Latent_heat" $
shortname' "Definition of Latent Heat"
latentHtENotes :: [Sentence]
latentHtENotes = map foldlSent [
[ch latentHeat `isThe` S "change" `sIn` phrase thermalEnergy,
sParen (phrase latentHeat +:+ phrase energy)],
[E latHtEEqn `isThe` phrase rOfChng `sOf` ch latentHeat,
S "with respect to", phrase time, ch tau],
[ch time `isThe` phrase time, S "elapsed" `sC` S "as long as the",
phrase phaseChange, S "is not complete"],
[S "status" `ofThe'` phrase phaseChange, S "depends on the",
phrase meltFrac, sParen (S "from" +:+ makeRef2S ddMeltFrac)],
[atStart latentHeat :+: S "ing stops when all material has changed to the new phase"]]
-------------------------
-- Theoretical Model 4 --
-------------------------
nwtnCooling :: TheoryModel
nwtnCooling = tm nwtnCoolingRC
[qw latentHeat, qw time, qw htTransCoeff, qw deltaT] ([] :: [ConceptChunk])
[] [nwtnCoolingEqn] [] [makeCiteInfo incroperaEtAl2007 $ Page [8]]
"nwtnCooling" nwtnCoolingNotes
nwtnCoolingRC :: RelationConcept
nwtnCoolingRC = makeRC "nwtnCoolingRC" (nounPhraseSP "Newton's law of cooling")
EmptyS nwtnCoolingEqn -- nwtnCoolingL
nwtnCoolingEqn :: Relation
nwtnCoolingEqn = apply1 htFlux time $= sy htTransCoeff * apply1 deltaT time
nwtnCoolingNotes :: [Sentence]
nwtnCoolingNotes = map foldlSent [
[atStart lawConvCooling +:+. S "describes convective cooling from a surface" +:
S "The law is stated as", S "the", phrase rate `sOf` S "heat loss from a body" `sIs`
S "proportional to the difference in", plural temp, S "between the body and its surroundings"],
[ch htTransCoeff, S "is assumed to be independent" `sOf` ch temp,
sParen (S "from" +:+ makeRef2S assumpHTCC)],
[E (apply1 deltaT time $= apply1 temp time - apply1 tempEnv time) `isThe`
S "time-dependant thermal gradient between the environment and the object"]]
| JacquesCarette/literate-scientific-software | code/drasil-example/Drasil/SWHS/TMods.hs | bsd-2-clause | 7,124 | 0 | 14 | 1,128 | 1,965 | 1,066 | 899 | 123 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{- | This module contains a faster implementation of dyadic rationals using
a fast arbitrary-precision floating-point library MPFR via haskel module Data.Rounded
-}
module Data.Approximate.Floating.HMPFR where
import Data.Approximate.ApproximateField hiding (prec)
import Data.Number.MPFR as MPFR
import Debug.Trace
import Prelude hiding (isNaN,isInfinite, div)
staged2mpfrRounding RoundUp = Up
staged2mpfrRounding RoundDown = Down
rnd = staged2mpfrRounding . rounding
prec :: Stage -> Precision
prec a = fromInteger (max 2 (toInteger (precision a)))
instance ApproximateField MPFR where
zero = MPFR.zero
appFromInteger = fromIntegerA Down 64 -- TODO
appFromRational_ s r = undefined --(fromRationalA (rnd s) (prec s) r, False) --TODO
appAdd s = add (rnd s) (prec s)
appSub s = sub (rnd s) (prec s)
appMul s = mul (rnd s) (prec s)
appNeg s = neg (rnd s) (prec s)
appInv s a = div (rnd s) (prec s) (fromIntegerA Near 2 1) a
appDiv s = div (rnd s) (prec s)
appAbs s = undefined -- TODO absD (rnd s) (prec s)
instance DyadicField MPFR where
posInf = setInf 2 1
negInf = setInf 2 (-1)
naN = setNaN 2
appGetExp a = traceShow (a,r) r
where r = -fromEnum (getExp a)
appPrec a = fromEnum $ getPrec a
appMul2 s = mul2i (rnd s) (prec s)
isUnordered a b = False -- TODO
| comius/haskell-fast-reals | src/Data/Approximate/Floating/HMPFR.hs | bsd-2-clause | 1,379 | 1 | 11 | 276 | 457 | 239 | 218 | 32 | 1 |
module Interpreter where
import Data.Array
import Data.Char
import Data.Maybe(fromMaybe, fromJust)
import qualified Data.Map as M
import Control.Monad.Reader
import Control.Monad.State
import AbsPascalis
import PrintPascalis
import ErrM
import MonadsFunctions
printDebug [] = return ()
printDebug (h:t) = do{putStr_IO h; printDebug t}
-- Type functions
getType :: EExp -> MRSIO Type
getType exp = case exp of
BTrue -> return TBool
BFalse -> return TBool
BNot _ -> return TBool
EOr _ _ -> return TBool
EAnd _ _ -> return TBool
EAss _ _ -> return TBool
ENAss _ _ -> return TBool
ELt _ _ -> return TBool
EGt _ _ -> return TBool
ELEt _ _ -> return TBool
EGEt _ _ -> return TBool
EAdd e _ -> getType e
ESub _ _ -> return TInt
EMul _ _ -> return TInt
EDiv _ _ -> return TInt
EInt _ -> return TInt
EChar _ -> return TChar
EStr _ -> return TStr
EFSub _ -> return TStr
ELSub _ _ -> return TStr
ERSub _ _ -> return TStr
ELRSub _ _ _ -> return TStr
EKey e _ -> do con_t <- getType e
return $ getContainerValueType con_t
ELen _ -> return TFunc
EOrd _ -> return TFunc
EArrI _ -> return (TArr TInt TInt)
EDict _ t1 t2-> return (TDict t1 t2)
EVar v -> askType v
Call (Ident "longitudo") _ -> return TInt
Call (Ident "ord") _ -> return TInt
Call id _ -> askType id
EFunc _ t _ _-> return t
e -> do putStr_Err $ "unknown type: " ++ show e
return TBool
getContainerKeyType :: Type -> Type
getContainerKeyType TStr = TInt
getContainerKeyType (TArr t1 t2) = t1
getContainerKeyType (TDict t1 t2) = t2
getContainerValueType :: Type -> Type
getContainerValueType TStr = TChar
getContainerValueType (TArr t1 t2) = t2
getContainerValueType (TDict t1 t2) = t2
-- converters utils functions
convertVar converter ident = do v <- askExp ident
converter v
intFromEInt :: EExp -> MRSIO Int
intFromEInt i = do int <- calcInt i
return $ fromIntegral $ int
concatenation (EStr s1) (EStr s2) = EStr (s1 ++ s2)
-- Converter functions
getConverter :: Type -> (EExp -> MRSIO EExp)
getConverter t = case t of
TBool -> calcBool
TInt -> calcExpInt
TChar -> calcChar
TStr -> calcString
TFunc -> calcFunc
TArr _ _ -> calcArr
TDict _ _ -> calcDict
calcBool :: EExp -> MRSIO EExp
calcBool exp = case exp of
-- bool expressions
BTrue -> return BTrue
BFalse -> return BFalse
BNot v -> do bexp <- calcBool v
if bexp == BTrue then
return BFalse
else
return BTrue
EAnd exp1 exp2 -> do bexp <- calcBool exp1
if bexp == BTrue then
calcBool exp2
else
return BFalse
EOr exp1 exp2 -> do bexp <- calcBool exp1
if bexp == BTrue then
return BTrue
else
calcBool exp2
EAss exp1 exp2 -> calcConvered (==) exp1 exp2
ENAss exp1 exp2 -> calcConvered (/=) exp1 exp2
ELt exp1 exp2 -> calcConvered (<) exp1 exp2
EGt exp1 exp2 -> calcConvered (>) exp1 exp2
ELEt exp1 exp2 -> calcConvered (<=) exp1 exp2
EGEt exp1 exp2 -> calcConvered (>=) exp1 exp2
EVar i -> convertVar calcBool i
e -> do putStr_IO $ "\n" ++ show e ++ "\n"
return Null
where
calcConvered func exp1 exp2 = do {
t1 <- getType exp1;
t2 <- getType exp2;
if t1 == t2 then
let converter = getConverter t1;
in do con1 <- converter exp1
con2 <- converter exp2
if func con1 con2 then
return BTrue
else
return BFalse
else
-- TODO handle errors
return BFalse
}
calcInt :: EExp -> MRSIO Integer
calcInt x = case x of
EVar ident -> convertVar calcInt ident
EAdd exp1 exp2 -> do n1 <- calcInt exp1
n2 <- calcInt exp2
return $ n1 + n2
ESub exp1 exp2 -> do n1 <- calcInt exp1
n2 <- calcInt exp2
return $ n1 - n2
EMul exp1 exp2 -> do n1 <- calcInt exp1
n2 <- calcInt exp2
return $ n1 * n2
EDiv exp1 exp2 -> do n1 <- calcInt exp1
n2 <- calcInt exp2
return $ n1 `div` n2
EInt n -> return n
Call id d -> do exp <- calcFunc (Call id d)
case exp of
EInt i -> return i
e -> do putStr_IO $ "calc int " ++ show e
return 0
EKey cont k -> getFromCont cont k
where
getFromCont (EArrI a) (EInt i1) = do i <- intFromEInt (EInt i1)
exp <- return $ a ! i
case exp of
EInt i -> return $ toInteger i
e -> do putStr_Err "Error type error"
return 0
getFromCont (EVar ident) key = do a <- askExp ident
getFromCont a key
getFromCont (EDict d t1 t2) key = if M.member key d then
do exp <- return $ fromJust $ M.lookup key d
case exp of
EInt i -> return $ toInteger i
e -> do putStr_Err $ "Error type error"
return 0
else
do putStr_Err $ "Dict " ++ show d ++ " doesn't have a key " ++ show key
return 0
getFromCont arr key = do cexp <- calcExp key
getFromCont arr cexp
calcExpInt :: EExp -> MRSIO EExp
calcExpInt exp = do int <- calcInt exp
return $ EInt $ toInteger int
calcChar :: EExp -> MRSIO EExp
calcChar (EChar c) = return $ EChar c
calcChar (EVar i) = convertVar calcChar i
calcChar (EKey container k) = getFromCont container k
where
getFromCont (EStr s) k = do i <- intFromEInt k
return $ EChar $ head $ drop i s
getFromCont (EVar ident) key = do a <- askExp ident
getFromCont a key
calcString :: EExp -> MRSIO EExp
calcString str = case str of
EStr s -> return $ EStr s
EAdd s1 s2 -> do
str1 <- calcString s1
str2 <- calcString s2
return $ concatenation str1 str2
EFSub s -> return s
ELSub (EStr s) l -> do i <- intFromEInt l
return $ EStr $ drop i s
ERSub (EStr s) l -> do i <- intFromEInt l
return $ EStr $ take i s
ELRSub (EStr s) l r -> do {
left <- intFromEInt l;
right <- intFromEInt r;
return $ EStr ((take (right - left)) $ drop left s)
}
EVar i -> convertVar calcString i
handleParams [] [] env = return env
handleParams (DParam id ty:tc) (exp:te) env = do {
calced <- calcExp exp;
tType <- getType calced;
loc <- alloc tType;
new_env <- return $ M.insert id loc env;
putToStore loc calced;
handleParams tc te new_env;
}
handleParams (DVar id1 ty:tc) (EVar id2:te) env = do {
loc <- getLoc id2;
new_env <- return $ M.insert id1 loc env;
handleParams tc te new_env;
}
handleFunc :: Exp -> [Exp] -> MRSIO Exp
handleFunc (EProc decls stmts env) params = do {
new_env <- handleParams decls params env;
exp <- runBlock new_env interpretStmts stmts;
return Null;
}
handleFunc (EFunc decls tType stmts env) params = do {
new_env <- handleParams decls params env;
runBlock new_env interpretStmts stmts;
}
calcFunc :: EExp -> MRSIO EExp
calcFunc (ELen (EStr s)) = return $ EInt (toInteger $ length s)
calcFunc (ELen (EArrI a))= return $ EInt (toInteger $ range_ $ bounds a)
where
range_ bounds = (snd bounds) - (fst bounds) + 1
calcFunc (ELen (EVar v)) = do exp <- calcExp (EVar v)
calcFunc (ELen exp)
calcFunc (EOrd (EChar c)) = return $ EInt (toInteger $ ord c)
calcFunc (EOrd (EVar v)) = do exp <- calcExp (EVar v)
calcFunc (EOrd exp)
calcFunc (Call (Ident "ord") h) = calcFunc $ EOrd $ head h
calcFunc (Call (Ident "longitudo") h) = calcFunc $ ELen $ head h
calcFunc (Call id params) = do exp <- askExp id
handleFunc exp params
-- Debug
calcFunc f = do putStr_Err $ "calc func " ++ show f
return Null
calcArr :: EExp -> MRSIO EExp
calcArr (EVar id) = askExp id
calcArr e = return e
calcDict :: EExp -> MRSIO EExp
calcDict (EVar id) = askExp id
calcDict e = return e
calcExp :: EExp -> MRSIO EExp
calcExp e = do t <- getType e
getConverter t e
rangeExp :: EExp -> EExp -> Int
rangeExp (EInt i1) (EInt i2) = fromInteger $ i2 - i1 + 1
nextExp :: EExp -> MRSIO EExp
nextExp (EInt i) = return (EInt (i + 1))
-- utils funcitons
showExp (EInt i) = show i
showExp (EStr s) = s
showExp (EChar s) = [s]
showExp (EArrI a) = show $ assocs a
showExp BTrue = "verum"
showExp BFalse = "falsum"
createArray :: EExp -> EExp -> Type -> EExp
createArray (EInt i1) (EInt i2) TInt = EArrI (array (fromInteger i1, fromInteger i2) [])
update_container :: Exp -> Exp -> Exp -> Exp
update_container (EStr s) (EInt i) (EChar c) = EStr (upd_con s i c)
where
upd_con (_:t) 0 c = (c:t)
upd_con (h:t) i c = (h:upd_con t (i - 1) c)
update_container (EDict d t1 t2) e1 e2 = EDict (M.insert e1 e2 d) t1 t2
update_container (EArrI a) (EInt i1) (EInt i2) = EArrI (a // [(fromInteger i1, EInt i2)])
createProcedure :: [Decl] -> [Stm] -> Env -> Exp
createProcedure params stmts env = (EProc params stmts env)
createFunction :: [Decl] -> Type -> [Stm] -> Env -> Exp
createFunction params tType stmts env = (EFunc params tType stmts env)
-- interpret declarations
iDecl :: [Decl] -> [Stm] -> MRSIO (Env, Exp)
iDecl ((DParam ind ty):tail) stm = iDecl ((DVar ind ty):tail) stm
iDecl ((DVar ind tType):tail) stm = do {
loc <- alloc tType;
case tType of
TDict t1 t2 -> do putToStore loc (EDict M.empty t1 t2)
localEnv (M.insert ind loc) (iDecl tail stm)
t -> localEnv (M.insert ind loc) (iDecl tail stm)
}
iDecl ((DAVar i e1 e2 t):tail) stm = do {
t1 <- getType e1;
t2 <- getType e2;
if t1 == t2 then
do
loc <- alloc (TArr t1 t);
exp1 <- calcExp e1;
exp2 <- calcExp e2;
putToStore loc (createArray e1 e2 t);
localEnv (M.insert i loc) (iDecl tail stm);
else
do -- TODO handle error here
env <- askEnv;
return (env, Null);
}
iDecl ((DProc ident params decl stmts):tail) stm = do {
env <- askEnv;
envParams <- runNewEnv env addParamsToEnv params ;
envParamsDecls <- runNewEnv envParams addDeclsToEnv decl;
loc <- alloc TFunc;
recursion_env <- return $ M.insert ident loc envParamsDecls;
putToStore loc (createProcedure params stmts recursion_env);
localEnv (M.insert ident loc) (iDecl tail stm);
}
where
-- TODO fix id
addParamsToEnv decl = iDecl decl []
addDeclsToEnv decl = iDecl decl []
iDecl ((DFunc ident params tType decl stmts):tail) stm = do {
env <- askEnv;
envParams <- runNewEnv env addParamsToEnv params ;
loc <- alloc TFunc;
recursion_env <- return $ M.insert ident loc envParams;
putToStore loc (createFunction params tType ((SDecl decl):stmts) recursion_env);
localEnv (M.insert ident loc) (iDecl tail stm);
}
where
-- TODO fix id
addParamsToEnv decl = iDecl decl []
iDecl [] stm = do exp <- interpretStmts stm
env <- askEnv
return (env, exp)
printParams [] = return ()
printParams (h:t) = do {
exp <- calcExp h;
putStr_IO $ showExp exp;
printParams t;
}
readVariable :: Type -> MRSIO Exp
readVariable TStr = do s <- getLine_IO
return $ EStr s
readVariable TChar = do c <- getChar_IO
return $ EChar c
readVariable TInt = get_ 0 1
where
get_ :: Int -> Int -> MRSIO Exp
get_ 0 n = do c <- getChar_IO
if isSpace c then
get_ 0 n
else
if c == '-' then
get_ 0 (n * (- 1))
else
if isDigit c then
get_ (ord c - 48) n
else
do putStr_Err $
"Read function error. Cannot read type: "
++ show TInt ++ " " ++ show c ++ " on input";
return Null
get_ i n = do c <- getChar_IO
if isDigit c then
get_ ((i * 10) + (ord c - 48)) n
else
if isSpace c then
return $ EInt $ toInteger (i * n)
else
do putStr_Err $
"Read function error. Cannot read type: "
++ show TInt ++ " " ++ show c ++ " on input";
return Null
-- interpret stmts ...
iStmt :: Stm -> MRSIO Exp
iStmt Skip = return Null
iStmt (SReturn exp) = do calced <- calcExp exp
return calced
iStmt (SExp value) = do interSExp value
where
interSExp (Call (Ident "incribo") params) = do printParams params
return Null
interSExp (Call ident params) = do exp <- askExp ident
result <- handleFunc exp params
return Null
iStmt (SIf exp stm) = do {
bexp <- calcBool exp;
if bexp == BTrue then
iStmt stm;
else
return Null;
}
iStmt (SIfElse exp stm1 stm2) = do {
bexp <- calcBool exp;
if bexp == BTrue then
iStmt stm1;
else
iStmt stm2;
}
iStmt (SSet ident (Call (Ident "lege") params)) = do printParams params
t <- askType ident
exp <- readVariable t
iStmt (SSet ident exp)
iStmt (SSet ident value) = do t1 <- askType ident
t2 <- getType value
if t2 == TFunc then
do exp <- calcExp value
t3 <- getType exp
if t1 == t3 then
do loc <- getLoc ident
putToStore loc exp
return Null
else
do putStr_Err $ show t3 ++ " cannot be set to " ++ show t1
return Null
else
if t1 == t2 then
do loc <- getLoc ident
-- Debug
exp <- calcExp value
putToStore loc exp
return Null
else
do putStr_IO $ show t2 ++ " cannot be set to " ++ show t1
return Null
iStmt (STSet ident key value) = do {
cont_t <- askType ident;
value_t <- getType value;
key_t <- getType key;
if value_t == getContainerValueType cont_t && key_t == getContainerKeyType cont_t then
do loc <- getLoc ident
container <- askExp ident
value_exp <- calcExp value
key_exp <- calcExp key
putToStore loc (update_container container key_exp value_exp)
return Null
else
-- TODO err
return Null
}
iStmt (SBlock stms) = do {
env <- askEnv;
store <- getStore;
runBlock env interpretStmts stms;
}
iStmt (SWhile exp stm) = do calced <- calcBool exp
if calced == BTrue then
do e <- iStmt stm
case e of
Null -> iStmt (SWhile exp stm)
e -> return e
else
return Null
iStmt (SFor ident exp1 exp2 stm) = do iStmt (SSet ident exp1)
cexp1 <- calcExp exp1
cexp2 <- calcExp exp2
doNTimes stm cexp1 (rangeExp cexp1 cexp2)
where
doNTimes stmt old 0 = return Null
doNTimes stmt old times = do {
next <- nextExp old;
exp <- iStmt stmt;
case exp of
Null -> do iStmt (SSet ident next);
doNTimes stmt next (times - 1)
e -> return e
}
interpretStmts :: [Stm] -> MRSIO Exp
interpretStmts [] = return Null
interpretStmts ((SDecl decls):restStms) = do env_exp <- iDecl decls restStms
return $ snd env_exp
interpretStmts (h:t) = do exp <- iStmt h
case exp of
Null -> interpretStmts t;
otherwise -> return exp;
interpretProg prog = runStateT (runReaderT (interpret_ prog) M.empty) M.empty
where
interpret_ :: Program -> MRSIO ()
interpret_ (Prog _ d i) = do env <- iDecl d i
return_IO
| andrzejgorski/pascalis | source/Interpreter.hs | bsd-3-clause | 18,521 | 0 | 18 | 7,969 | 6,200 | 2,940 | 3,260 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
module High.Functor where
import High.Category (Category)
data Functor :: ((* -> *) -> (* -> *) -> *) -> ((* -> *) -> (* -> *) -> *) -> ((* -> *) -> (* -> *)) -> * where
Functor ::
{ sourceCategory :: Category cat
, targetCategory :: Category dat
, fmap :: (forall f g. cat f g -> dat (h f) (h g))
} -> Functor cat dat h
| Hexirp/untypeclass | src/High/Functor.hs | bsd-3-clause | 473 | 0 | 13 | 122 | 184 | 105 | 79 | 12 | 0 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Aws.DynamoDB.Commands.DeleteTable
( DeleteTable(..)
, DeleteTableResponse(..)
, deleteTable
) where
import Aws.Core
import Aws.DynamoDB.Core
import Control.Applicative
import Control.Monad
import Data.Aeson
import qualified Data.Text as T
import qualified Test.QuickCheck as QC
data DeleteTable
= DeleteTable
{
delTableName :: TableName
}
deriving (Show, Eq)
instance ToJSON DeleteTable where
toJSON (DeleteTable a) =
object[
"TableName" .= a
]
instance FromJSON DeleteTable where
parseJSON (Object v) = DeleteTable <$> v .: "TableName"
parseJSON _ = mzero
instance QC.Arbitrary DeleteTable where
arbitrary = DeleteTable <$> QC.arbitrary
data DeleteTableResponse
= DeleteTableResponse {
deltrTableDescription::TableDescription
}deriving (Show,Eq)
instance ToJSON DeleteTableResponse where
toJSON(DeleteTableResponse a) = object["TableDescription" .= a]
instance FromJSON DeleteTableResponse where
parseJSON (Object v) =
DeleteTableResponse <$> v .: "TableDescription"
parseJSON _ = mzero
instance QC.Arbitrary DeleteTableResponse where
arbitrary = DeleteTableResponse <$> QC.arbitrary
deleteTable :: TableName -> DeleteTable
deleteTable = DeleteTable
instance SignQuery DeleteTable where
type ServiceConfiguration DeleteTable = DdbConfiguration
signQuery a@DeleteTable {..} = ddbSignQuery DdbQuery
{ ddbqMethod = Post
, ddbqRequest = ""
, ddbqQuery = []
, ddbqCommand = "DynamoDB_20120810.DeleteTable"
, ddbqBody = Just $ toJSON $ a
}
data DeleteTableResult = DeleteTableResult{
tableDescription :: TableDescription
}deriving(Show, Eq)
instance FromJSON DeleteTableResult where
parseJSON (Object v) = DeleteTableResult <$> v .: "TableDescription"
parseJSON _ = mzero
instance ResponseConsumer DeleteTable DeleteTableResponse where
type ResponseMetadata DeleteTableResponse = DdbMetadata
responseConsumer _ mref = ddbResponseConsumer mref $ \rsp -> cnv <$> jsonConsumer rsp
where
cnv (DeleteTableResult a) = DeleteTableResponse a
instance Transaction DeleteTable DeleteTableResponse
instance AsMemoryResponse DeleteTableResponse where
type MemoryResponse DeleteTableResponse = DeleteTableResponse
loadToMemory = return
| ywata/dynamodb | Aws/DynamoDB/Commands/DeleteTable.hs | bsd-3-clause | 2,593 | 0 | 10 | 592 | 562 | 309 | 253 | 64 | 1 |
{-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.Functions.F14
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- Raw functions from the
-- <http://www.opengl.org/registry/ OpenGL registry>.
--
--------------------------------------------------------------------------------
module Graphics.GL.Functions.F14 (
glGetVideouivNV,
glGetVkProcAddrNV,
glGetnColorTable,
glGetnColorTableARB,
glGetnCompressedTexImage,
glGetnCompressedTexImageARB,
glGetnConvolutionFilter,
glGetnConvolutionFilterARB,
glGetnHistogram,
glGetnHistogramARB,
glGetnMapdv,
glGetnMapdvARB,
glGetnMapfv,
glGetnMapfvARB,
glGetnMapiv,
glGetnMapivARB,
glGetnMinmax,
glGetnMinmaxARB,
glGetnPixelMapfv,
glGetnPixelMapfvARB,
glGetnPixelMapuiv,
glGetnPixelMapuivARB,
glGetnPixelMapusv,
glGetnPixelMapusvARB,
glGetnPolygonStipple,
glGetnPolygonStippleARB,
glGetnSeparableFilter,
glGetnSeparableFilterARB,
glGetnTexImage,
glGetnTexImageARB,
glGetnUniformdv,
glGetnUniformdvARB,
glGetnUniformfv,
glGetnUniformfvARB,
glGetnUniformfvEXT,
glGetnUniformfvKHR,
glGetnUniformi64vARB,
glGetnUniformiv,
glGetnUniformivARB,
glGetnUniformivEXT,
glGetnUniformivKHR,
glGetnUniformui64vARB,
glGetnUniformuiv,
glGetnUniformuivARB,
glGetnUniformuivKHR,
glGlobalAlphaFactorbSUN,
glGlobalAlphaFactordSUN,
glGlobalAlphaFactorfSUN,
glGlobalAlphaFactoriSUN,
glGlobalAlphaFactorsSUN,
glGlobalAlphaFactorubSUN,
glGlobalAlphaFactoruiSUN,
glGlobalAlphaFactorusSUN,
glHint,
glHintPGI,
glHistogram,
glHistogramEXT,
glIglooInterfaceSGIX,
glImageTransformParameterfHP,
glImageTransformParameterfvHP,
glImageTransformParameteriHP,
glImageTransformParameterivHP,
glImportMemoryFdEXT,
glImportMemoryWin32HandleEXT,
glImportMemoryWin32NameEXT,
glImportSemaphoreFdEXT,
glImportSemaphoreWin32HandleEXT,
glImportSemaphoreWin32NameEXT,
glImportSyncEXT,
glIndexFormatNV,
glIndexFuncEXT,
glIndexMask,
glIndexMaterialEXT,
glIndexPointer,
glIndexPointerEXT,
glIndexPointerListIBM,
glIndexd,
glIndexdv,
glIndexf,
glIndexfv,
glIndexi,
glIndexiv,
glIndexs,
glIndexsv,
glIndexub,
glIndexubv,
glIndexxOES,
glIndexxvOES,
glInitNames,
glInsertComponentEXT,
glInsertEventMarkerEXT,
glInstrumentsBufferSGIX,
glInterleavedArrays,
glInterpolatePathsNV,
glInvalidateBufferData,
glInvalidateBufferSubData,
glInvalidateFramebuffer,
glInvalidateNamedFramebufferData,
glInvalidateNamedFramebufferSubData,
glInvalidateSubFramebuffer
) where
import Control.Monad.IO.Class ( MonadIO(..) )
import Foreign.Ptr
import Graphics.GL.Foreign
import Graphics.GL.Types
import System.IO.Unsafe ( unsafePerformIO )
-- glGetVideouivNV -------------------------------------------------------------
glGetVideouivNV
:: MonadIO m
=> GLuint -- ^ @video_slot@.
-> GLenum -- ^ @pname@.
-> Ptr GLuint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLuint@.
-> m ()
glGetVideouivNV v1 v2 v3 = liftIO $ dyn392 ptr_glGetVideouivNV v1 v2 v3
{-# NOINLINE ptr_glGetVideouivNV #-}
ptr_glGetVideouivNV :: FunPtr (GLuint -> GLenum -> Ptr GLuint -> IO ())
ptr_glGetVideouivNV = unsafePerformIO $ getCommand "glGetVideouivNV"
-- glGetVkProcAddrNV -----------------------------------------------------------
glGetVkProcAddrNV
:: MonadIO m
=> Ptr GLchar -- ^ @name@ pointing to @COMPSIZE(name)@ elements of type @GLchar@.
-> m GLVULKANPROCNV
glGetVkProcAddrNV v1 = liftIO $ dyn467 ptr_glGetVkProcAddrNV v1
{-# NOINLINE ptr_glGetVkProcAddrNV #-}
ptr_glGetVkProcAddrNV :: FunPtr (Ptr GLchar -> IO GLVULKANPROCNV)
ptr_glGetVkProcAddrNV = unsafePerformIO $ getCommand "glGetVkProcAddrNV"
-- glGetnColorTable ------------------------------------------------------------
glGetnColorTable
:: MonadIO m
=> GLenum -- ^ @target@ of type [ColorTableTarget](Graphics-GL-Groups.html#ColorTableTarget).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @table@.
-> m ()
glGetnColorTable v1 v2 v3 v4 v5 = liftIO $ dyn468 ptr_glGetnColorTable v1 v2 v3 v4 v5
{-# NOINLINE ptr_glGetnColorTable #-}
ptr_glGetnColorTable :: FunPtr (GLenum -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnColorTable = unsafePerformIO $ getCommand "glGetnColorTable"
-- glGetnColorTableARB ---------------------------------------------------------
glGetnColorTableARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [ColorTableTarget](Graphics-GL-Groups.html#ColorTableTarget).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @table@ pointing to @bufSize@ elements of type @a@.
-> m ()
glGetnColorTableARB v1 v2 v3 v4 v5 = liftIO $ dyn468 ptr_glGetnColorTableARB v1 v2 v3 v4 v5
{-# NOINLINE ptr_glGetnColorTableARB #-}
ptr_glGetnColorTableARB :: FunPtr (GLenum -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnColorTableARB = unsafePerformIO $ getCommand "glGetnColorTableARB"
-- glGetnCompressedTexImage ----------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetCompressedTexImage.xhtml OpenGL 4.x>.
glGetnCompressedTexImage
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget).
-> GLint -- ^ @lod@.
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @pixels@.
-> m ()
glGetnCompressedTexImage v1 v2 v3 v4 = liftIO $ dyn469 ptr_glGetnCompressedTexImage v1 v2 v3 v4
{-# NOINLINE ptr_glGetnCompressedTexImage #-}
ptr_glGetnCompressedTexImage :: FunPtr (GLenum -> GLint -> GLsizei -> Ptr a -> IO ())
ptr_glGetnCompressedTexImage = unsafePerformIO $ getCommand "glGetnCompressedTexImage"
-- glGetnCompressedTexImageARB -------------------------------------------------
glGetnCompressedTexImageARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget).
-> GLint -- ^ @lod@.
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @img@ pointing to @bufSize@ elements of type @a@.
-> m ()
glGetnCompressedTexImageARB v1 v2 v3 v4 = liftIO $ dyn469 ptr_glGetnCompressedTexImageARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnCompressedTexImageARB #-}
ptr_glGetnCompressedTexImageARB :: FunPtr (GLenum -> GLint -> GLsizei -> Ptr a -> IO ())
ptr_glGetnCompressedTexImageARB = unsafePerformIO $ getCommand "glGetnCompressedTexImageARB"
-- glGetnConvolutionFilter -----------------------------------------------------
glGetnConvolutionFilter
:: MonadIO m
=> GLenum -- ^ @target@ of type [ConvolutionTarget](Graphics-GL-Groups.html#ConvolutionTarget).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @image@.
-> m ()
glGetnConvolutionFilter v1 v2 v3 v4 v5 = liftIO $ dyn468 ptr_glGetnConvolutionFilter v1 v2 v3 v4 v5
{-# NOINLINE ptr_glGetnConvolutionFilter #-}
ptr_glGetnConvolutionFilter :: FunPtr (GLenum -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnConvolutionFilter = unsafePerformIO $ getCommand "glGetnConvolutionFilter"
-- glGetnConvolutionFilterARB --------------------------------------------------
glGetnConvolutionFilterARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [ConvolutionTarget](Graphics-GL-Groups.html#ConvolutionTarget).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @image@ pointing to @bufSize@ elements of type @a@.
-> m ()
glGetnConvolutionFilterARB v1 v2 v3 v4 v5 = liftIO $ dyn468 ptr_glGetnConvolutionFilterARB v1 v2 v3 v4 v5
{-# NOINLINE ptr_glGetnConvolutionFilterARB #-}
ptr_glGetnConvolutionFilterARB :: FunPtr (GLenum -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnConvolutionFilterARB = unsafePerformIO $ getCommand "glGetnConvolutionFilterARB"
-- glGetnHistogram -------------------------------------------------------------
glGetnHistogram
:: MonadIO m
=> GLenum -- ^ @target@ of type [HistogramTargetEXT](Graphics-GL-Groups.html#HistogramTargetEXT).
-> GLboolean -- ^ @reset@ of type [Boolean](Graphics-GL-Groups.html#Boolean).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @values@.
-> m ()
glGetnHistogram v1 v2 v3 v4 v5 v6 = liftIO $ dyn470 ptr_glGetnHistogram v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glGetnHistogram #-}
ptr_glGetnHistogram :: FunPtr (GLenum -> GLboolean -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnHistogram = unsafePerformIO $ getCommand "glGetnHistogram"
-- glGetnHistogramARB ----------------------------------------------------------
glGetnHistogramARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [HistogramTargetEXT](Graphics-GL-Groups.html#HistogramTargetEXT).
-> GLboolean -- ^ @reset@ of type [Boolean](Graphics-GL-Groups.html#Boolean).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @values@ pointing to @bufSize@ elements of type @a@.
-> m ()
glGetnHistogramARB v1 v2 v3 v4 v5 v6 = liftIO $ dyn470 ptr_glGetnHistogramARB v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glGetnHistogramARB #-}
ptr_glGetnHistogramARB :: FunPtr (GLenum -> GLboolean -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnHistogramARB = unsafePerformIO $ getCommand "glGetnHistogramARB"
-- glGetnMapdv -----------------------------------------------------------------
glGetnMapdv
:: MonadIO m
=> GLenum -- ^ @target@ of type [MapTarget](Graphics-GL-Groups.html#MapTarget).
-> GLenum -- ^ @query@ of type [MapQuery](Graphics-GL-Groups.html#MapQuery).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLdouble -- ^ @v@.
-> m ()
glGetnMapdv v1 v2 v3 v4 = liftIO $ dyn471 ptr_glGetnMapdv v1 v2 v3 v4
{-# NOINLINE ptr_glGetnMapdv #-}
ptr_glGetnMapdv :: FunPtr (GLenum -> GLenum -> GLsizei -> Ptr GLdouble -> IO ())
ptr_glGetnMapdv = unsafePerformIO $ getCommand "glGetnMapdv"
-- glGetnMapdvARB --------------------------------------------------------------
glGetnMapdvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [MapTarget](Graphics-GL-Groups.html#MapTarget).
-> GLenum -- ^ @query@ of type [MapQuery](Graphics-GL-Groups.html#MapQuery).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLdouble -- ^ @v@ pointing to @bufSize@ elements of type @GLdouble@.
-> m ()
glGetnMapdvARB v1 v2 v3 v4 = liftIO $ dyn471 ptr_glGetnMapdvARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnMapdvARB #-}
ptr_glGetnMapdvARB :: FunPtr (GLenum -> GLenum -> GLsizei -> Ptr GLdouble -> IO ())
ptr_glGetnMapdvARB = unsafePerformIO $ getCommand "glGetnMapdvARB"
-- glGetnMapfv -----------------------------------------------------------------
glGetnMapfv
:: MonadIO m
=> GLenum -- ^ @target@ of type [MapTarget](Graphics-GL-Groups.html#MapTarget).
-> GLenum -- ^ @query@ of type [MapQuery](Graphics-GL-Groups.html#MapQuery).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @v@.
-> m ()
glGetnMapfv v1 v2 v3 v4 = liftIO $ dyn472 ptr_glGetnMapfv v1 v2 v3 v4
{-# NOINLINE ptr_glGetnMapfv #-}
ptr_glGetnMapfv :: FunPtr (GLenum -> GLenum -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnMapfv = unsafePerformIO $ getCommand "glGetnMapfv"
-- glGetnMapfvARB --------------------------------------------------------------
glGetnMapfvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [MapTarget](Graphics-GL-Groups.html#MapTarget).
-> GLenum -- ^ @query@ of type [MapQuery](Graphics-GL-Groups.html#MapQuery).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @v@ pointing to @bufSize@ elements of type @GLfloat@.
-> m ()
glGetnMapfvARB v1 v2 v3 v4 = liftIO $ dyn472 ptr_glGetnMapfvARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnMapfvARB #-}
ptr_glGetnMapfvARB :: FunPtr (GLenum -> GLenum -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnMapfvARB = unsafePerformIO $ getCommand "glGetnMapfvARB"
-- glGetnMapiv -----------------------------------------------------------------
glGetnMapiv
:: MonadIO m
=> GLenum -- ^ @target@ of type [MapTarget](Graphics-GL-Groups.html#MapTarget).
-> GLenum -- ^ @query@ of type [MapQuery](Graphics-GL-Groups.html#MapQuery).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLint -- ^ @v@.
-> m ()
glGetnMapiv v1 v2 v3 v4 = liftIO $ dyn473 ptr_glGetnMapiv v1 v2 v3 v4
{-# NOINLINE ptr_glGetnMapiv #-}
ptr_glGetnMapiv :: FunPtr (GLenum -> GLenum -> GLsizei -> Ptr GLint -> IO ())
ptr_glGetnMapiv = unsafePerformIO $ getCommand "glGetnMapiv"
-- glGetnMapivARB --------------------------------------------------------------
glGetnMapivARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [MapTarget](Graphics-GL-Groups.html#MapTarget).
-> GLenum -- ^ @query@ of type [MapQuery](Graphics-GL-Groups.html#MapQuery).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLint -- ^ @v@ pointing to @bufSize@ elements of type @GLint@.
-> m ()
glGetnMapivARB v1 v2 v3 v4 = liftIO $ dyn473 ptr_glGetnMapivARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnMapivARB #-}
ptr_glGetnMapivARB :: FunPtr (GLenum -> GLenum -> GLsizei -> Ptr GLint -> IO ())
ptr_glGetnMapivARB = unsafePerformIO $ getCommand "glGetnMapivARB"
-- glGetnMinmax ----------------------------------------------------------------
glGetnMinmax
:: MonadIO m
=> GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT).
-> GLboolean -- ^ @reset@ of type [Boolean](Graphics-GL-Groups.html#Boolean).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @values@.
-> m ()
glGetnMinmax v1 v2 v3 v4 v5 v6 = liftIO $ dyn470 ptr_glGetnMinmax v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glGetnMinmax #-}
ptr_glGetnMinmax :: FunPtr (GLenum -> GLboolean -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnMinmax = unsafePerformIO $ getCommand "glGetnMinmax"
-- glGetnMinmaxARB -------------------------------------------------------------
glGetnMinmaxARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT).
-> GLboolean -- ^ @reset@ of type [Boolean](Graphics-GL-Groups.html#Boolean).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @values@ pointing to @bufSize@ elements of type @a@.
-> m ()
glGetnMinmaxARB v1 v2 v3 v4 v5 v6 = liftIO $ dyn470 ptr_glGetnMinmaxARB v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glGetnMinmaxARB #-}
ptr_glGetnMinmaxARB :: FunPtr (GLenum -> GLboolean -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnMinmaxARB = unsafePerformIO $ getCommand "glGetnMinmaxARB"
-- glGetnPixelMapfv ------------------------------------------------------------
glGetnPixelMapfv
:: MonadIO m
=> GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @values@.
-> m ()
glGetnPixelMapfv v1 v2 v3 = liftIO $ dyn233 ptr_glGetnPixelMapfv v1 v2 v3
{-# NOINLINE ptr_glGetnPixelMapfv #-}
ptr_glGetnPixelMapfv :: FunPtr (GLenum -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnPixelMapfv = unsafePerformIO $ getCommand "glGetnPixelMapfv"
-- glGetnPixelMapfvARB ---------------------------------------------------------
glGetnPixelMapfvARB
:: MonadIO m
=> GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @values@ pointing to @bufSize@ elements of type @GLfloat@.
-> m ()
glGetnPixelMapfvARB v1 v2 v3 = liftIO $ dyn233 ptr_glGetnPixelMapfvARB v1 v2 v3
{-# NOINLINE ptr_glGetnPixelMapfvARB #-}
ptr_glGetnPixelMapfvARB :: FunPtr (GLenum -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnPixelMapfvARB = unsafePerformIO $ getCommand "glGetnPixelMapfvARB"
-- glGetnPixelMapuiv -----------------------------------------------------------
glGetnPixelMapuiv
:: MonadIO m
=> GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLuint -- ^ @values@.
-> m ()
glGetnPixelMapuiv v1 v2 v3 = liftIO $ dyn204 ptr_glGetnPixelMapuiv v1 v2 v3
{-# NOINLINE ptr_glGetnPixelMapuiv #-}
ptr_glGetnPixelMapuiv :: FunPtr (GLenum -> GLsizei -> Ptr GLuint -> IO ())
ptr_glGetnPixelMapuiv = unsafePerformIO $ getCommand "glGetnPixelMapuiv"
-- glGetnPixelMapuivARB --------------------------------------------------------
glGetnPixelMapuivARB
:: MonadIO m
=> GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLuint -- ^ @values@ pointing to @bufSize@ elements of type @GLuint@.
-> m ()
glGetnPixelMapuivARB v1 v2 v3 = liftIO $ dyn204 ptr_glGetnPixelMapuivARB v1 v2 v3
{-# NOINLINE ptr_glGetnPixelMapuivARB #-}
ptr_glGetnPixelMapuivARB :: FunPtr (GLenum -> GLsizei -> Ptr GLuint -> IO ())
ptr_glGetnPixelMapuivARB = unsafePerformIO $ getCommand "glGetnPixelMapuivARB"
-- glGetnPixelMapusv -----------------------------------------------------------
glGetnPixelMapusv
:: MonadIO m
=> GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLushort -- ^ @values@.
-> m ()
glGetnPixelMapusv v1 v2 v3 = liftIO $ dyn474 ptr_glGetnPixelMapusv v1 v2 v3
{-# NOINLINE ptr_glGetnPixelMapusv #-}
ptr_glGetnPixelMapusv :: FunPtr (GLenum -> GLsizei -> Ptr GLushort -> IO ())
ptr_glGetnPixelMapusv = unsafePerformIO $ getCommand "glGetnPixelMapusv"
-- glGetnPixelMapusvARB --------------------------------------------------------
glGetnPixelMapusvARB
:: MonadIO m
=> GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap).
-> GLsizei -- ^ @bufSize@.
-> Ptr GLushort -- ^ @values@ pointing to @bufSize@ elements of type @GLushort@.
-> m ()
glGetnPixelMapusvARB v1 v2 v3 = liftIO $ dyn474 ptr_glGetnPixelMapusvARB v1 v2 v3
{-# NOINLINE ptr_glGetnPixelMapusvARB #-}
ptr_glGetnPixelMapusvARB :: FunPtr (GLenum -> GLsizei -> Ptr GLushort -> IO ())
ptr_glGetnPixelMapusvARB = unsafePerformIO $ getCommand "glGetnPixelMapusvARB"
-- glGetnPolygonStipple --------------------------------------------------------
glGetnPolygonStipple
:: MonadIO m
=> GLsizei -- ^ @bufSize@.
-> Ptr GLubyte -- ^ @pattern@.
-> m ()
glGetnPolygonStipple v1 v2 = liftIO $ dyn475 ptr_glGetnPolygonStipple v1 v2
{-# NOINLINE ptr_glGetnPolygonStipple #-}
ptr_glGetnPolygonStipple :: FunPtr (GLsizei -> Ptr GLubyte -> IO ())
ptr_glGetnPolygonStipple = unsafePerformIO $ getCommand "glGetnPolygonStipple"
-- glGetnPolygonStippleARB -----------------------------------------------------
glGetnPolygonStippleARB
:: MonadIO m
=> GLsizei -- ^ @bufSize@.
-> Ptr GLubyte -- ^ @pattern@ pointing to @bufSize@ elements of type @GLubyte@.
-> m ()
glGetnPolygonStippleARB v1 v2 = liftIO $ dyn475 ptr_glGetnPolygonStippleARB v1 v2
{-# NOINLINE ptr_glGetnPolygonStippleARB #-}
ptr_glGetnPolygonStippleARB :: FunPtr (GLsizei -> Ptr GLubyte -> IO ())
ptr_glGetnPolygonStippleARB = unsafePerformIO $ getCommand "glGetnPolygonStippleARB"
-- glGetnSeparableFilter -------------------------------------------------------
glGetnSeparableFilter
:: MonadIO m
=> GLenum -- ^ @target@ of type [SeparableTargetEXT](Graphics-GL-Groups.html#SeparableTargetEXT).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @rowBufSize@.
-> Ptr a -- ^ @row@.
-> GLsizei -- ^ @columnBufSize@.
-> Ptr b -- ^ @column@.
-> Ptr c -- ^ @span@.
-> m ()
glGetnSeparableFilter v1 v2 v3 v4 v5 v6 v7 v8 = liftIO $ dyn476 ptr_glGetnSeparableFilter v1 v2 v3 v4 v5 v6 v7 v8
{-# NOINLINE ptr_glGetnSeparableFilter #-}
ptr_glGetnSeparableFilter :: FunPtr (GLenum -> GLenum -> GLenum -> GLsizei -> Ptr a -> GLsizei -> Ptr b -> Ptr c -> IO ())
ptr_glGetnSeparableFilter = unsafePerformIO $ getCommand "glGetnSeparableFilter"
-- glGetnSeparableFilterARB ----------------------------------------------------
glGetnSeparableFilterARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [SeparableTargetEXT](Graphics-GL-Groups.html#SeparableTargetEXT).
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @rowBufSize@.
-> Ptr a -- ^ @row@ pointing to @rowBufSize@ elements of type @a@.
-> GLsizei -- ^ @columnBufSize@.
-> Ptr b -- ^ @column@ pointing to @columnBufSize@ elements of type @b@.
-> Ptr c -- ^ @span@ pointing to @0@ elements of type @c@.
-> m ()
glGetnSeparableFilterARB v1 v2 v3 v4 v5 v6 v7 v8 = liftIO $ dyn476 ptr_glGetnSeparableFilterARB v1 v2 v3 v4 v5 v6 v7 v8
{-# NOINLINE ptr_glGetnSeparableFilterARB #-}
ptr_glGetnSeparableFilterARB :: FunPtr (GLenum -> GLenum -> GLenum -> GLsizei -> Ptr a -> GLsizei -> Ptr b -> Ptr c -> IO ())
ptr_glGetnSeparableFilterARB = unsafePerformIO $ getCommand "glGetnSeparableFilterARB"
-- glGetnTexImage --------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetTexImage.xhtml OpenGL 4.x>.
glGetnTexImage
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget).
-> GLint -- ^ @level@.
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @pixels@ pointing to @bufSize@ elements of type @a@.
-> m ()
glGetnTexImage v1 v2 v3 v4 v5 v6 = liftIO $ dyn477 ptr_glGetnTexImage v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glGetnTexImage #-}
ptr_glGetnTexImage :: FunPtr (GLenum -> GLint -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnTexImage = unsafePerformIO $ getCommand "glGetnTexImage"
-- glGetnTexImageARB -----------------------------------------------------------
glGetnTexImageARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget).
-> GLint -- ^ @level@.
-> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat).
-> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType).
-> GLsizei -- ^ @bufSize@.
-> Ptr a -- ^ @img@ pointing to @bufSize@ elements of type @a@.
-> m ()
glGetnTexImageARB v1 v2 v3 v4 v5 v6 = liftIO $ dyn477 ptr_glGetnTexImageARB v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glGetnTexImageARB #-}
ptr_glGetnTexImageARB :: FunPtr (GLenum -> GLint -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glGetnTexImageARB = unsafePerformIO $ getCommand "glGetnTexImageARB"
-- glGetnUniformdv -------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetUniform.xhtml OpenGL 4.x>.
glGetnUniformdv
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLdouble -- ^ @params@ pointing to @bufSize@ elements of type @GLdouble@.
-> m ()
glGetnUniformdv v1 v2 v3 v4 = liftIO $ dyn478 ptr_glGetnUniformdv v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformdv #-}
ptr_glGetnUniformdv :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLdouble -> IO ())
ptr_glGetnUniformdv = unsafePerformIO $ getCommand "glGetnUniformdv"
-- glGetnUniformdvARB ----------------------------------------------------------
glGetnUniformdvARB
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLdouble -- ^ @params@ pointing to @bufSize@ elements of type @GLdouble@.
-> m ()
glGetnUniformdvARB v1 v2 v3 v4 = liftIO $ dyn478 ptr_glGetnUniformdvARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformdvARB #-}
ptr_glGetnUniformdvARB :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLdouble -> IO ())
ptr_glGetnUniformdvARB = unsafePerformIO $ getCommand "glGetnUniformdvARB"
-- glGetnUniformfv -------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetUniform.xhtml OpenGL 4.x>.
glGetnUniformfv
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @params@ pointing to @bufSize@ elements of type @GLfloat@.
-> m ()
glGetnUniformfv v1 v2 v3 v4 = liftIO $ dyn479 ptr_glGetnUniformfv v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformfv #-}
ptr_glGetnUniformfv :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnUniformfv = unsafePerformIO $ getCommand "glGetnUniformfv"
-- glGetnUniformfvARB ----------------------------------------------------------
glGetnUniformfvARB
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @params@ pointing to @bufSize@ elements of type @GLfloat@.
-> m ()
glGetnUniformfvARB v1 v2 v3 v4 = liftIO $ dyn479 ptr_glGetnUniformfvARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformfvARB #-}
ptr_glGetnUniformfvARB :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnUniformfvARB = unsafePerformIO $ getCommand "glGetnUniformfvARB"
-- glGetnUniformfvEXT ----------------------------------------------------------
-- | This command is an alias for 'glGetnUniformfv'.
glGetnUniformfvEXT
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @params@ pointing to @bufSize@ elements of type @GLfloat@.
-> m ()
glGetnUniformfvEXT v1 v2 v3 v4 = liftIO $ dyn479 ptr_glGetnUniformfvEXT v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformfvEXT #-}
ptr_glGetnUniformfvEXT :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnUniformfvEXT = unsafePerformIO $ getCommand "glGetnUniformfvEXT"
-- glGetnUniformfvKHR ----------------------------------------------------------
-- | This command is an alias for 'glGetnUniformfv'.
glGetnUniformfvKHR
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLfloat -- ^ @params@ pointing to @bufSize@ elements of type @GLfloat@.
-> m ()
glGetnUniformfvKHR v1 v2 v3 v4 = liftIO $ dyn479 ptr_glGetnUniformfvKHR v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformfvKHR #-}
ptr_glGetnUniformfvKHR :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLfloat -> IO ())
ptr_glGetnUniformfvKHR = unsafePerformIO $ getCommand "glGetnUniformfvKHR"
-- glGetnUniformi64vARB --------------------------------------------------------
glGetnUniformi64vARB
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLint64 -- ^ @params@ pointing to @bufSize@ elements of type @GLint64@.
-> m ()
glGetnUniformi64vARB v1 v2 v3 v4 = liftIO $ dyn480 ptr_glGetnUniformi64vARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformi64vARB #-}
ptr_glGetnUniformi64vARB :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLint64 -> IO ())
ptr_glGetnUniformi64vARB = unsafePerformIO $ getCommand "glGetnUniformi64vARB"
-- glGetnUniformiv -------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetUniform.xhtml OpenGL 4.x>.
glGetnUniformiv
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLint -- ^ @params@ pointing to @bufSize@ elements of type @GLint@.
-> m ()
glGetnUniformiv v1 v2 v3 v4 = liftIO $ dyn481 ptr_glGetnUniformiv v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformiv #-}
ptr_glGetnUniformiv :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLint -> IO ())
ptr_glGetnUniformiv = unsafePerformIO $ getCommand "glGetnUniformiv"
-- glGetnUniformivARB ----------------------------------------------------------
glGetnUniformivARB
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLint -- ^ @params@ pointing to @bufSize@ elements of type @GLint@.
-> m ()
glGetnUniformivARB v1 v2 v3 v4 = liftIO $ dyn481 ptr_glGetnUniformivARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformivARB #-}
ptr_glGetnUniformivARB :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLint -> IO ())
ptr_glGetnUniformivARB = unsafePerformIO $ getCommand "glGetnUniformivARB"
-- glGetnUniformivEXT ----------------------------------------------------------
-- | This command is an alias for 'glGetnUniformiv'.
glGetnUniformivEXT
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLint -- ^ @params@ pointing to @bufSize@ elements of type @GLint@.
-> m ()
glGetnUniformivEXT v1 v2 v3 v4 = liftIO $ dyn481 ptr_glGetnUniformivEXT v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformivEXT #-}
ptr_glGetnUniformivEXT :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLint -> IO ())
ptr_glGetnUniformivEXT = unsafePerformIO $ getCommand "glGetnUniformivEXT"
-- glGetnUniformivKHR ----------------------------------------------------------
-- | This command is an alias for 'glGetnUniformiv'.
glGetnUniformivKHR
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLint -- ^ @params@ pointing to @bufSize@ elements of type @GLint@.
-> m ()
glGetnUniformivKHR v1 v2 v3 v4 = liftIO $ dyn481 ptr_glGetnUniformivKHR v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformivKHR #-}
ptr_glGetnUniformivKHR :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLint -> IO ())
ptr_glGetnUniformivKHR = unsafePerformIO $ getCommand "glGetnUniformivKHR"
-- glGetnUniformui64vARB -------------------------------------------------------
glGetnUniformui64vARB
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLuint64 -- ^ @params@ pointing to @bufSize@ elements of type @GLuint64@.
-> m ()
glGetnUniformui64vARB v1 v2 v3 v4 = liftIO $ dyn482 ptr_glGetnUniformui64vARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformui64vARB #-}
ptr_glGetnUniformui64vARB :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLuint64 -> IO ())
ptr_glGetnUniformui64vARB = unsafePerformIO $ getCommand "glGetnUniformui64vARB"
-- glGetnUniformuiv ------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetUniform.xhtml OpenGL 4.x>.
glGetnUniformuiv
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLuint -- ^ @params@ pointing to @bufSize@ elements of type @GLuint@.
-> m ()
glGetnUniformuiv v1 v2 v3 v4 = liftIO $ dyn483 ptr_glGetnUniformuiv v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformuiv #-}
ptr_glGetnUniformuiv :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLuint -> IO ())
ptr_glGetnUniformuiv = unsafePerformIO $ getCommand "glGetnUniformuiv"
-- glGetnUniformuivARB ---------------------------------------------------------
glGetnUniformuivARB
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLuint -- ^ @params@ pointing to @bufSize@ elements of type @GLuint@.
-> m ()
glGetnUniformuivARB v1 v2 v3 v4 = liftIO $ dyn483 ptr_glGetnUniformuivARB v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformuivARB #-}
ptr_glGetnUniformuivARB :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLuint -> IO ())
ptr_glGetnUniformuivARB = unsafePerformIO $ getCommand "glGetnUniformuivARB"
-- glGetnUniformuivKHR ---------------------------------------------------------
-- | This command is an alias for 'glGetnUniformuiv'.
glGetnUniformuivKHR
:: MonadIO m
=> GLuint -- ^ @program@.
-> GLint -- ^ @location@.
-> GLsizei -- ^ @bufSize@.
-> Ptr GLuint -- ^ @params@ pointing to @bufSize@ elements of type @GLuint@.
-> m ()
glGetnUniformuivKHR v1 v2 v3 v4 = liftIO $ dyn483 ptr_glGetnUniformuivKHR v1 v2 v3 v4
{-# NOINLINE ptr_glGetnUniformuivKHR #-}
ptr_glGetnUniformuivKHR :: FunPtr (GLuint -> GLint -> GLsizei -> Ptr GLuint -> IO ())
ptr_glGetnUniformuivKHR = unsafePerformIO $ getCommand "glGetnUniformuivKHR"
-- glGlobalAlphaFactorbSUN -----------------------------------------------------
glGlobalAlphaFactorbSUN
:: MonadIO m
=> GLbyte -- ^ @factor@.
-> m ()
glGlobalAlphaFactorbSUN v1 = liftIO $ dyn484 ptr_glGlobalAlphaFactorbSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactorbSUN #-}
ptr_glGlobalAlphaFactorbSUN :: FunPtr (GLbyte -> IO ())
ptr_glGlobalAlphaFactorbSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactorbSUN"
-- glGlobalAlphaFactordSUN -----------------------------------------------------
glGlobalAlphaFactordSUN
:: MonadIO m
=> GLdouble -- ^ @factor@.
-> m ()
glGlobalAlphaFactordSUN v1 = liftIO $ dyn84 ptr_glGlobalAlphaFactordSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactordSUN #-}
ptr_glGlobalAlphaFactordSUN :: FunPtr (GLdouble -> IO ())
ptr_glGlobalAlphaFactordSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactordSUN"
-- glGlobalAlphaFactorfSUN -----------------------------------------------------
glGlobalAlphaFactorfSUN
:: MonadIO m
=> GLfloat -- ^ @factor@.
-> m ()
glGlobalAlphaFactorfSUN v1 = liftIO $ dyn85 ptr_glGlobalAlphaFactorfSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactorfSUN #-}
ptr_glGlobalAlphaFactorfSUN :: FunPtr (GLfloat -> IO ())
ptr_glGlobalAlphaFactorfSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactorfSUN"
-- glGlobalAlphaFactoriSUN -----------------------------------------------------
glGlobalAlphaFactoriSUN
:: MonadIO m
=> GLint -- ^ @factor@.
-> m ()
glGlobalAlphaFactoriSUN v1 = liftIO $ dyn13 ptr_glGlobalAlphaFactoriSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactoriSUN #-}
ptr_glGlobalAlphaFactoriSUN :: FunPtr (GLint -> IO ())
ptr_glGlobalAlphaFactoriSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactoriSUN"
-- glGlobalAlphaFactorsSUN -----------------------------------------------------
glGlobalAlphaFactorsSUN
:: MonadIO m
=> GLshort -- ^ @factor@.
-> m ()
glGlobalAlphaFactorsSUN v1 = liftIO $ dyn485 ptr_glGlobalAlphaFactorsSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactorsSUN #-}
ptr_glGlobalAlphaFactorsSUN :: FunPtr (GLshort -> IO ())
ptr_glGlobalAlphaFactorsSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactorsSUN"
-- glGlobalAlphaFactorubSUN ----------------------------------------------------
glGlobalAlphaFactorubSUN
:: MonadIO m
=> GLubyte -- ^ @factor@.
-> m ()
glGlobalAlphaFactorubSUN v1 = liftIO $ dyn486 ptr_glGlobalAlphaFactorubSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactorubSUN #-}
ptr_glGlobalAlphaFactorubSUN :: FunPtr (GLubyte -> IO ())
ptr_glGlobalAlphaFactorubSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactorubSUN"
-- glGlobalAlphaFactoruiSUN ----------------------------------------------------
glGlobalAlphaFactoruiSUN
:: MonadIO m
=> GLuint -- ^ @factor@.
-> m ()
glGlobalAlphaFactoruiSUN v1 = liftIO $ dyn3 ptr_glGlobalAlphaFactoruiSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactoruiSUN #-}
ptr_glGlobalAlphaFactoruiSUN :: FunPtr (GLuint -> IO ())
ptr_glGlobalAlphaFactoruiSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactoruiSUN"
-- glGlobalAlphaFactorusSUN ----------------------------------------------------
glGlobalAlphaFactorusSUN
:: MonadIO m
=> GLushort -- ^ @factor@.
-> m ()
glGlobalAlphaFactorusSUN v1 = liftIO $ dyn487 ptr_glGlobalAlphaFactorusSUN v1
{-# NOINLINE ptr_glGlobalAlphaFactorusSUN #-}
ptr_glGlobalAlphaFactorusSUN :: FunPtr (GLushort -> IO ())
ptr_glGlobalAlphaFactorusSUN = unsafePerformIO $ getCommand "glGlobalAlphaFactorusSUN"
-- glHint ----------------------------------------------------------------------
-- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glHint.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man3/xhtml/glHint.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glHint.xhtml OpenGL 4.x>.
glHint
:: MonadIO m
=> GLenum -- ^ @target@ of type [HintTarget](Graphics-GL-Groups.html#HintTarget).
-> GLenum -- ^ @mode@ of type [HintMode](Graphics-GL-Groups.html#HintMode).
-> m ()
glHint v1 v2 = liftIO $ dyn54 ptr_glHint v1 v2
{-# NOINLINE ptr_glHint #-}
ptr_glHint :: FunPtr (GLenum -> GLenum -> IO ())
ptr_glHint = unsafePerformIO $ getCommand "glHint"
-- glHintPGI -------------------------------------------------------------------
glHintPGI
:: MonadIO m
=> GLenum -- ^ @target@ of type [HintTargetPGI](Graphics-GL-Groups.html#HintTargetPGI).
-> GLint -- ^ @mode@.
-> m ()
glHintPGI v1 v2 = liftIO $ dyn58 ptr_glHintPGI v1 v2
{-# NOINLINE ptr_glHintPGI #-}
ptr_glHintPGI :: FunPtr (GLenum -> GLint -> IO ())
ptr_glHintPGI = unsafePerformIO $ getCommand "glHintPGI"
-- glHistogram -----------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glHistogram.xml OpenGL 2.x>.
glHistogram
:: MonadIO m
=> GLenum -- ^ @target@ of type [HistogramTargetEXT](Graphics-GL-Groups.html#HistogramTargetEXT).
-> GLsizei -- ^ @width@.
-> GLenum -- ^ @internalformat@ of type [InternalFormat](Graphics-GL-Groups.html#InternalFormat).
-> GLboolean -- ^ @sink@ of type [Boolean](Graphics-GL-Groups.html#Boolean).
-> m ()
glHistogram v1 v2 v3 v4 = liftIO $ dyn488 ptr_glHistogram v1 v2 v3 v4
{-# NOINLINE ptr_glHistogram #-}
ptr_glHistogram :: FunPtr (GLenum -> GLsizei -> GLenum -> GLboolean -> IO ())
ptr_glHistogram = unsafePerformIO $ getCommand "glHistogram"
-- glHistogramEXT --------------------------------------------------------------
-- | This command is an alias for 'glHistogram'.
glHistogramEXT
:: MonadIO m
=> GLenum -- ^ @target@ of type [HistogramTargetEXT](Graphics-GL-Groups.html#HistogramTargetEXT).
-> GLsizei -- ^ @width@.
-> GLenum -- ^ @internalformat@ of type [InternalFormat](Graphics-GL-Groups.html#InternalFormat).
-> GLboolean -- ^ @sink@ of type [Boolean](Graphics-GL-Groups.html#Boolean).
-> m ()
glHistogramEXT v1 v2 v3 v4 = liftIO $ dyn488 ptr_glHistogramEXT v1 v2 v3 v4
{-# NOINLINE ptr_glHistogramEXT #-}
ptr_glHistogramEXT :: FunPtr (GLenum -> GLsizei -> GLenum -> GLboolean -> IO ())
ptr_glHistogramEXT = unsafePerformIO $ getCommand "glHistogramEXT"
-- glIglooInterfaceSGIX --------------------------------------------------------
glIglooInterfaceSGIX
:: MonadIO m
=> GLenum -- ^ @pname@ of type [IglooFunctionSelectSGIX](Graphics-GL-Groups.html#IglooFunctionSelectSGIX).
-> Ptr a -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @IglooParameterSGIX@.
-> m ()
glIglooInterfaceSGIX v1 v2 = liftIO $ dyn238 ptr_glIglooInterfaceSGIX v1 v2
{-# NOINLINE ptr_glIglooInterfaceSGIX #-}
ptr_glIglooInterfaceSGIX :: FunPtr (GLenum -> Ptr a -> IO ())
ptr_glIglooInterfaceSGIX = unsafePerformIO $ getCommand "glIglooInterfaceSGIX"
-- glImageTransformParameterfHP ------------------------------------------------
glImageTransformParameterfHP
:: MonadIO m
=> GLenum -- ^ @target@ of type [ImageTransformTargetHP](Graphics-GL-Groups.html#ImageTransformTargetHP).
-> GLenum -- ^ @pname@ of type [ImageTransformPNameHP](Graphics-GL-Groups.html#ImageTransformPNameHP).
-> GLfloat -- ^ @param@.
-> m ()
glImageTransformParameterfHP v1 v2 v3 = liftIO $ dyn168 ptr_glImageTransformParameterfHP v1 v2 v3
{-# NOINLINE ptr_glImageTransformParameterfHP #-}
ptr_glImageTransformParameterfHP :: FunPtr (GLenum -> GLenum -> GLfloat -> IO ())
ptr_glImageTransformParameterfHP = unsafePerformIO $ getCommand "glImageTransformParameterfHP"
-- glImageTransformParameterfvHP -----------------------------------------------
glImageTransformParameterfvHP
:: MonadIO m
=> GLenum -- ^ @target@ of type [ImageTransformTargetHP](Graphics-GL-Groups.html#ImageTransformTargetHP).
-> GLenum -- ^ @pname@ of type [ImageTransformPNameHP](Graphics-GL-Groups.html#ImageTransformPNameHP).
-> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@.
-> m ()
glImageTransformParameterfvHP v1 v2 v3 = liftIO $ dyn139 ptr_glImageTransformParameterfvHP v1 v2 v3
{-# NOINLINE ptr_glImageTransformParameterfvHP #-}
ptr_glImageTransformParameterfvHP :: FunPtr (GLenum -> GLenum -> Ptr GLfloat -> IO ())
ptr_glImageTransformParameterfvHP = unsafePerformIO $ getCommand "glImageTransformParameterfvHP"
-- glImageTransformParameteriHP ------------------------------------------------
glImageTransformParameteriHP
:: MonadIO m
=> GLenum -- ^ @target@ of type [ImageTransformTargetHP](Graphics-GL-Groups.html#ImageTransformTargetHP).
-> GLenum -- ^ @pname@ of type [ImageTransformPNameHP](Graphics-GL-Groups.html#ImageTransformPNameHP).
-> GLint -- ^ @param@.
-> m ()
glImageTransformParameteriHP v1 v2 v3 = liftIO $ dyn66 ptr_glImageTransformParameteriHP v1 v2 v3
{-# NOINLINE ptr_glImageTransformParameteriHP #-}
ptr_glImageTransformParameteriHP :: FunPtr (GLenum -> GLenum -> GLint -> IO ())
ptr_glImageTransformParameteriHP = unsafePerformIO $ getCommand "glImageTransformParameteriHP"
-- glImageTransformParameterivHP -----------------------------------------------
glImageTransformParameterivHP
:: MonadIO m
=> GLenum -- ^ @target@ of type [ImageTransformTargetHP](Graphics-GL-Groups.html#ImageTransformTargetHP).
-> GLenum -- ^ @pname@ of type [ImageTransformPNameHP](Graphics-GL-Groups.html#ImageTransformPNameHP).
-> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@.
-> m ()
glImageTransformParameterivHP v1 v2 v3 = liftIO $ dyn140 ptr_glImageTransformParameterivHP v1 v2 v3
{-# NOINLINE ptr_glImageTransformParameterivHP #-}
ptr_glImageTransformParameterivHP :: FunPtr (GLenum -> GLenum -> Ptr GLint -> IO ())
ptr_glImageTransformParameterivHP = unsafePerformIO $ getCommand "glImageTransformParameterivHP"
-- glImportMemoryFdEXT ---------------------------------------------------------
glImportMemoryFdEXT
:: MonadIO m
=> GLuint -- ^ @memory@.
-> GLuint64 -- ^ @size@.
-> GLenum -- ^ @handleType@ of type [ExternalHandleType](Graphics-GL-Groups.html#ExternalHandleType).
-> GLint -- ^ @fd@.
-> m ()
glImportMemoryFdEXT v1 v2 v3 v4 = liftIO $ dyn489 ptr_glImportMemoryFdEXT v1 v2 v3 v4
{-# NOINLINE ptr_glImportMemoryFdEXT #-}
ptr_glImportMemoryFdEXT :: FunPtr (GLuint -> GLuint64 -> GLenum -> GLint -> IO ())
ptr_glImportMemoryFdEXT = unsafePerformIO $ getCommand "glImportMemoryFdEXT"
-- glImportMemoryWin32HandleEXT ------------------------------------------------
glImportMemoryWin32HandleEXT
:: MonadIO m
=> GLuint -- ^ @memory@.
-> GLuint64 -- ^ @size@.
-> GLenum -- ^ @handleType@ of type [ExternalHandleType](Graphics-GL-Groups.html#ExternalHandleType).
-> Ptr a -- ^ @handle@.
-> m ()
glImportMemoryWin32HandleEXT v1 v2 v3 v4 = liftIO $ dyn490 ptr_glImportMemoryWin32HandleEXT v1 v2 v3 v4
{-# NOINLINE ptr_glImportMemoryWin32HandleEXT #-}
ptr_glImportMemoryWin32HandleEXT :: FunPtr (GLuint -> GLuint64 -> GLenum -> Ptr a -> IO ())
ptr_glImportMemoryWin32HandleEXT = unsafePerformIO $ getCommand "glImportMemoryWin32HandleEXT"
-- glImportMemoryWin32NameEXT --------------------------------------------------
glImportMemoryWin32NameEXT
:: MonadIO m
=> GLuint -- ^ @memory@.
-> GLuint64 -- ^ @size@.
-> GLenum -- ^ @handleType@ of type [ExternalHandleType](Graphics-GL-Groups.html#ExternalHandleType).
-> Ptr a -- ^ @name@.
-> m ()
glImportMemoryWin32NameEXT v1 v2 v3 v4 = liftIO $ dyn490 ptr_glImportMemoryWin32NameEXT v1 v2 v3 v4
{-# NOINLINE ptr_glImportMemoryWin32NameEXT #-}
ptr_glImportMemoryWin32NameEXT :: FunPtr (GLuint -> GLuint64 -> GLenum -> Ptr a -> IO ())
ptr_glImportMemoryWin32NameEXT = unsafePerformIO $ getCommand "glImportMemoryWin32NameEXT"
-- glImportSemaphoreFdEXT ------------------------------------------------------
glImportSemaphoreFdEXT
:: MonadIO m
=> GLuint -- ^ @semaphore@.
-> GLenum -- ^ @handleType@ of type [ExternalHandleType](Graphics-GL-Groups.html#ExternalHandleType).
-> GLint -- ^ @fd@.
-> m ()
glImportSemaphoreFdEXT v1 v2 v3 = liftIO $ dyn491 ptr_glImportSemaphoreFdEXT v1 v2 v3
{-# NOINLINE ptr_glImportSemaphoreFdEXT #-}
ptr_glImportSemaphoreFdEXT :: FunPtr (GLuint -> GLenum -> GLint -> IO ())
ptr_glImportSemaphoreFdEXT = unsafePerformIO $ getCommand "glImportSemaphoreFdEXT"
-- glImportSemaphoreWin32HandleEXT ---------------------------------------------
glImportSemaphoreWin32HandleEXT
:: MonadIO m
=> GLuint -- ^ @semaphore@.
-> GLenum -- ^ @handleType@ of type [ExternalHandleType](Graphics-GL-Groups.html#ExternalHandleType).
-> Ptr a -- ^ @handle@.
-> m ()
glImportSemaphoreWin32HandleEXT v1 v2 v3 = liftIO $ dyn492 ptr_glImportSemaphoreWin32HandleEXT v1 v2 v3
{-# NOINLINE ptr_glImportSemaphoreWin32HandleEXT #-}
ptr_glImportSemaphoreWin32HandleEXT :: FunPtr (GLuint -> GLenum -> Ptr a -> IO ())
ptr_glImportSemaphoreWin32HandleEXT = unsafePerformIO $ getCommand "glImportSemaphoreWin32HandleEXT"
-- glImportSemaphoreWin32NameEXT -----------------------------------------------
glImportSemaphoreWin32NameEXT
:: MonadIO m
=> GLuint -- ^ @semaphore@.
-> GLenum -- ^ @handleType@ of type [ExternalHandleType](Graphics-GL-Groups.html#ExternalHandleType).
-> Ptr a -- ^ @name@.
-> m ()
glImportSemaphoreWin32NameEXT v1 v2 v3 = liftIO $ dyn492 ptr_glImportSemaphoreWin32NameEXT v1 v2 v3
{-# NOINLINE ptr_glImportSemaphoreWin32NameEXT #-}
ptr_glImportSemaphoreWin32NameEXT :: FunPtr (GLuint -> GLenum -> Ptr a -> IO ())
ptr_glImportSemaphoreWin32NameEXT = unsafePerformIO $ getCommand "glImportSemaphoreWin32NameEXT"
-- glImportSyncEXT -------------------------------------------------------------
glImportSyncEXT
:: MonadIO m
=> GLenum -- ^ @external_sync_type@.
-> GLintptr -- ^ @external_sync@.
-> GLbitfield -- ^ @flags@.
-> m GLsync -- ^ of type @sync@.
glImportSyncEXT v1 v2 v3 = liftIO $ dyn493 ptr_glImportSyncEXT v1 v2 v3
{-# NOINLINE ptr_glImportSyncEXT #-}
ptr_glImportSyncEXT :: FunPtr (GLenum -> GLintptr -> GLbitfield -> IO GLsync)
ptr_glImportSyncEXT = unsafePerformIO $ getCommand "glImportSyncEXT"
-- glIndexFormatNV -------------------------------------------------------------
glIndexFormatNV
:: MonadIO m
=> GLenum -- ^ @type@.
-> GLsizei -- ^ @stride@.
-> m ()
glIndexFormatNV v1 v2 = liftIO $ dyn247 ptr_glIndexFormatNV v1 v2
{-# NOINLINE ptr_glIndexFormatNV #-}
ptr_glIndexFormatNV :: FunPtr (GLenum -> GLsizei -> IO ())
ptr_glIndexFormatNV = unsafePerformIO $ getCommand "glIndexFormatNV"
-- glIndexFuncEXT --------------------------------------------------------------
glIndexFuncEXT
:: MonadIO m
=> GLenum -- ^ @func@ of type [IndexFunctionEXT](Graphics-GL-Groups.html#IndexFunctionEXT).
-> GLclampf -- ^ @ref@ of type @ClampedFloat32@.
-> m ()
glIndexFuncEXT v1 v2 = liftIO $ dyn10 ptr_glIndexFuncEXT v1 v2
{-# NOINLINE ptr_glIndexFuncEXT #-}
ptr_glIndexFuncEXT :: FunPtr (GLenum -> GLclampf -> IO ())
ptr_glIndexFuncEXT = unsafePerformIO $ getCommand "glIndexFuncEXT"
-- glIndexMask -----------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndexMask.xml OpenGL 2.x>.
glIndexMask
:: MonadIO m
=> GLuint -- ^ @mask@ of type @MaskedColorIndexValueI@.
-> m ()
glIndexMask v1 = liftIO $ dyn3 ptr_glIndexMask v1
{-# NOINLINE ptr_glIndexMask #-}
ptr_glIndexMask :: FunPtr (GLuint -> IO ())
ptr_glIndexMask = unsafePerformIO $ getCommand "glIndexMask"
-- glIndexMaterialEXT ----------------------------------------------------------
glIndexMaterialEXT
:: MonadIO m
=> GLenum -- ^ @face@ of type [MaterialFace](Graphics-GL-Groups.html#MaterialFace).
-> GLenum -- ^ @mode@ of type [IndexMaterialParameterEXT](Graphics-GL-Groups.html#IndexMaterialParameterEXT).
-> m ()
glIndexMaterialEXT v1 v2 = liftIO $ dyn54 ptr_glIndexMaterialEXT v1 v2
{-# NOINLINE ptr_glIndexMaterialEXT #-}
ptr_glIndexMaterialEXT :: FunPtr (GLenum -> GLenum -> IO ())
ptr_glIndexMaterialEXT = unsafePerformIO $ getCommand "glIndexMaterialEXT"
-- glIndexPointer --------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndexPointer.xml OpenGL 2.x>.
glIndexPointer
:: MonadIO m
=> GLenum -- ^ @type@ of type [IndexPointerType](Graphics-GL-Groups.html#IndexPointerType).
-> GLsizei -- ^ @stride@.
-> Ptr a -- ^ @pointer@ pointing to @COMPSIZE(type,stride)@ elements of type @a@.
-> m ()
glIndexPointer v1 v2 v3 = liftIO $ dyn49 ptr_glIndexPointer v1 v2 v3
{-# NOINLINE ptr_glIndexPointer #-}
ptr_glIndexPointer :: FunPtr (GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glIndexPointer = unsafePerformIO $ getCommand "glIndexPointer"
-- glIndexPointerEXT -----------------------------------------------------------
glIndexPointerEXT
:: MonadIO m
=> GLenum -- ^ @type@ of type [IndexPointerType](Graphics-GL-Groups.html#IndexPointerType).
-> GLsizei -- ^ @stride@.
-> GLsizei -- ^ @count@.
-> Ptr a -- ^ @pointer@ pointing to @COMPSIZE(type,stride,count)@ elements of type @a@.
-> m ()
glIndexPointerEXT v1 v2 v3 v4 = liftIO $ dyn494 ptr_glIndexPointerEXT v1 v2 v3 v4
{-# NOINLINE ptr_glIndexPointerEXT #-}
ptr_glIndexPointerEXT :: FunPtr (GLenum -> GLsizei -> GLsizei -> Ptr a -> IO ())
ptr_glIndexPointerEXT = unsafePerformIO $ getCommand "glIndexPointerEXT"
-- glIndexPointerListIBM -------------------------------------------------------
glIndexPointerListIBM
:: MonadIO m
=> GLenum -- ^ @type@ of type [IndexPointerType](Graphics-GL-Groups.html#IndexPointerType).
-> GLint -- ^ @stride@.
-> Ptr (Ptr a) -- ^ @pointer@ pointing to @COMPSIZE(type,stride)@ elements of type @Ptr a@.
-> GLint -- ^ @ptrstride@.
-> m ()
glIndexPointerListIBM v1 v2 v3 v4 = liftIO $ dyn291 ptr_glIndexPointerListIBM v1 v2 v3 v4
{-# NOINLINE ptr_glIndexPointerListIBM #-}
ptr_glIndexPointerListIBM :: FunPtr (GLenum -> GLint -> Ptr (Ptr a) -> GLint -> IO ())
ptr_glIndexPointerListIBM = unsafePerformIO $ getCommand "glIndexPointerListIBM"
-- glIndexd --------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>. The vector equivalent of this command is 'glIndexdv'.
glIndexd
:: MonadIO m
=> GLdouble -- ^ @c@ of type @ColorIndexValueD@.
-> m ()
glIndexd v1 = liftIO $ dyn84 ptr_glIndexd v1
{-# NOINLINE ptr_glIndexd #-}
ptr_glIndexd :: FunPtr (GLdouble -> IO ())
ptr_glIndexd = unsafePerformIO $ getCommand "glIndexd"
-- glIndexdv -------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>.
glIndexdv
:: MonadIO m
=> Ptr GLdouble -- ^ @c@ pointing to @1@ element of type @ColorIndexValueD@.
-> m ()
glIndexdv v1 = liftIO $ dyn42 ptr_glIndexdv v1
{-# NOINLINE ptr_glIndexdv #-}
ptr_glIndexdv :: FunPtr (Ptr GLdouble -> IO ())
ptr_glIndexdv = unsafePerformIO $ getCommand "glIndexdv"
-- glIndexf --------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>. The vector equivalent of this command is 'glIndexfv'.
glIndexf
:: MonadIO m
=> GLfloat -- ^ @c@ of type @ColorIndexValueF@.
-> m ()
glIndexf v1 = liftIO $ dyn85 ptr_glIndexf v1
{-# NOINLINE ptr_glIndexf #-}
ptr_glIndexf :: FunPtr (GLfloat -> IO ())
ptr_glIndexf = unsafePerformIO $ getCommand "glIndexf"
-- glIndexfv -------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>.
glIndexfv
:: MonadIO m
=> Ptr GLfloat -- ^ @c@ pointing to @1@ element of type @ColorIndexValueF@.
-> m ()
glIndexfv v1 = liftIO $ dyn44 ptr_glIndexfv v1
{-# NOINLINE ptr_glIndexfv #-}
ptr_glIndexfv :: FunPtr (Ptr GLfloat -> IO ())
ptr_glIndexfv = unsafePerformIO $ getCommand "glIndexfv"
-- glIndexi --------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>. The vector equivalent of this command is 'glIndexiv'.
glIndexi
:: MonadIO m
=> GLint -- ^ @c@ of type @ColorIndexValueI@.
-> m ()
glIndexi v1 = liftIO $ dyn13 ptr_glIndexi v1
{-# NOINLINE ptr_glIndexi #-}
ptr_glIndexi :: FunPtr (GLint -> IO ())
ptr_glIndexi = unsafePerformIO $ getCommand "glIndexi"
-- glIndexiv -------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>.
glIndexiv
:: MonadIO m
=> Ptr GLint -- ^ @c@ pointing to @1@ element of type @ColorIndexValueI@.
-> m ()
glIndexiv v1 = liftIO $ dyn46 ptr_glIndexiv v1
{-# NOINLINE ptr_glIndexiv #-}
ptr_glIndexiv :: FunPtr (Ptr GLint -> IO ())
ptr_glIndexiv = unsafePerformIO $ getCommand "glIndexiv"
-- glIndexs --------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>. The vector equivalent of this command is 'glIndexsv'.
glIndexs
:: MonadIO m
=> GLshort -- ^ @c@ of type @ColorIndexValueS@.
-> m ()
glIndexs v1 = liftIO $ dyn485 ptr_glIndexs v1
{-# NOINLINE ptr_glIndexs #-}
ptr_glIndexs :: FunPtr (GLshort -> IO ())
ptr_glIndexs = unsafePerformIO $ getCommand "glIndexs"
-- glIndexsv -------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>.
glIndexsv
:: MonadIO m
=> Ptr GLshort -- ^ @c@ pointing to @1@ element of type @ColorIndexValueS@.
-> m ()
glIndexsv v1 = liftIO $ dyn48 ptr_glIndexsv v1
{-# NOINLINE ptr_glIndexsv #-}
ptr_glIndexsv :: FunPtr (Ptr GLshort -> IO ())
ptr_glIndexsv = unsafePerformIO $ getCommand "glIndexsv"
-- glIndexub -------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>. The vector equivalent of this command is 'glIndexubv'.
glIndexub
:: MonadIO m
=> GLubyte -- ^ @c@ of type @ColorIndexValueUB@.
-> m ()
glIndexub v1 = liftIO $ dyn486 ptr_glIndexub v1
{-# NOINLINE ptr_glIndexub #-}
ptr_glIndexub :: FunPtr (GLubyte -> IO ())
ptr_glIndexub = unsafePerformIO $ getCommand "glIndexub"
-- glIndexubv ------------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glIndex.xml OpenGL 2.x>.
glIndexubv
:: MonadIO m
=> Ptr GLubyte -- ^ @c@ pointing to @1@ element of type @ColorIndexValueUB@.
-> m ()
glIndexubv v1 = liftIO $ dyn108 ptr_glIndexubv v1
{-# NOINLINE ptr_glIndexubv #-}
ptr_glIndexubv :: FunPtr (Ptr GLubyte -> IO ())
ptr_glIndexubv = unsafePerformIO $ getCommand "glIndexubv"
-- glIndexxOES -----------------------------------------------------------------
glIndexxOES
:: MonadIO m
=> GLfixed -- ^ @component@.
-> m ()
glIndexxOES v1 = liftIO $ dyn87 ptr_glIndexxOES v1
{-# NOINLINE ptr_glIndexxOES #-}
ptr_glIndexxOES :: FunPtr (GLfixed -> IO ())
ptr_glIndexxOES = unsafePerformIO $ getCommand "glIndexxOES"
-- glIndexxvOES ----------------------------------------------------------------
glIndexxvOES
:: MonadIO m
=> Ptr GLfixed -- ^ @component@ pointing to @1@ element of type @GLfixed@.
-> m ()
glIndexxvOES v1 = liftIO $ dyn114 ptr_glIndexxvOES v1
{-# NOINLINE ptr_glIndexxvOES #-}
ptr_glIndexxvOES :: FunPtr (Ptr GLfixed -> IO ())
ptr_glIndexxvOES = unsafePerformIO $ getCommand "glIndexxvOES"
-- glInitNames -----------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glInitNames.xml OpenGL 2.x>.
glInitNames
:: MonadIO m
=> m ()
glInitNames = liftIO $ dyn11 ptr_glInitNames
{-# NOINLINE ptr_glInitNames #-}
ptr_glInitNames :: FunPtr (IO ())
ptr_glInitNames = unsafePerformIO $ getCommand "glInitNames"
-- glInsertComponentEXT --------------------------------------------------------
glInsertComponentEXT
:: MonadIO m
=> GLuint -- ^ @res@.
-> GLuint -- ^ @src@.
-> GLuint -- ^ @num@.
-> m ()
glInsertComponentEXT v1 v2 v3 = liftIO $ dyn109 ptr_glInsertComponentEXT v1 v2 v3
{-# NOINLINE ptr_glInsertComponentEXT #-}
ptr_glInsertComponentEXT :: FunPtr (GLuint -> GLuint -> GLuint -> IO ())
ptr_glInsertComponentEXT = unsafePerformIO $ getCommand "glInsertComponentEXT"
-- glInsertEventMarkerEXT ------------------------------------------------------
glInsertEventMarkerEXT
:: MonadIO m
=> GLsizei -- ^ @length@.
-> Ptr GLchar -- ^ @marker@.
-> m ()
glInsertEventMarkerEXT v1 v2 = liftIO $ dyn495 ptr_glInsertEventMarkerEXT v1 v2
{-# NOINLINE ptr_glInsertEventMarkerEXT #-}
ptr_glInsertEventMarkerEXT :: FunPtr (GLsizei -> Ptr GLchar -> IO ())
ptr_glInsertEventMarkerEXT = unsafePerformIO $ getCommand "glInsertEventMarkerEXT"
-- glInstrumentsBufferSGIX -----------------------------------------------------
glInstrumentsBufferSGIX
:: MonadIO m
=> GLsizei -- ^ @size@.
-> Ptr GLint -- ^ @buffer@ pointing to @size@ elements of type @GLint@.
-> m ()
glInstrumentsBufferSGIX v1 v2 = liftIO $ dyn222 ptr_glInstrumentsBufferSGIX v1 v2
{-# NOINLINE ptr_glInstrumentsBufferSGIX #-}
ptr_glInstrumentsBufferSGIX :: FunPtr (GLsizei -> Ptr GLint -> IO ())
ptr_glInstrumentsBufferSGIX = unsafePerformIO $ getCommand "glInstrumentsBufferSGIX"
-- glInterleavedArrays ---------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glInterleavedArrays.xml OpenGL 2.x>.
glInterleavedArrays
:: MonadIO m
=> GLenum -- ^ @format@ of type [InterleavedArrayFormat](Graphics-GL-Groups.html#InterleavedArrayFormat).
-> GLsizei -- ^ @stride@.
-> Ptr a -- ^ @pointer@ pointing to @COMPSIZE(format,stride)@ elements of type @a@.
-> m ()
glInterleavedArrays v1 v2 v3 = liftIO $ dyn49 ptr_glInterleavedArrays v1 v2 v3
{-# NOINLINE ptr_glInterleavedArrays #-}
ptr_glInterleavedArrays :: FunPtr (GLenum -> GLsizei -> Ptr a -> IO ())
ptr_glInterleavedArrays = unsafePerformIO $ getCommand "glInterleavedArrays"
-- glInterpolatePathsNV --------------------------------------------------------
glInterpolatePathsNV
:: MonadIO m
=> GLuint -- ^ @resultPath@ of type @Path@.
-> GLuint -- ^ @pathA@ of type @Path@.
-> GLuint -- ^ @pathB@ of type @Path@.
-> GLfloat -- ^ @weight@.
-> m ()
glInterpolatePathsNV v1 v2 v3 v4 = liftIO $ dyn496 ptr_glInterpolatePathsNV v1 v2 v3 v4
{-# NOINLINE ptr_glInterpolatePathsNV #-}
ptr_glInterpolatePathsNV :: FunPtr (GLuint -> GLuint -> GLuint -> GLfloat -> IO ())
ptr_glInterpolatePathsNV = unsafePerformIO $ getCommand "glInterpolatePathsNV"
-- glInvalidateBufferData ------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glInvalidateBufferData.xhtml OpenGL 4.x>.
glInvalidateBufferData
:: MonadIO m
=> GLuint -- ^ @buffer@.
-> m ()
glInvalidateBufferData v1 = liftIO $ dyn3 ptr_glInvalidateBufferData v1
{-# NOINLINE ptr_glInvalidateBufferData #-}
ptr_glInvalidateBufferData :: FunPtr (GLuint -> IO ())
ptr_glInvalidateBufferData = unsafePerformIO $ getCommand "glInvalidateBufferData"
-- glInvalidateBufferSubData ---------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glInvalidateBufferSubData.xhtml OpenGL 4.x>.
glInvalidateBufferSubData
:: MonadIO m
=> GLuint -- ^ @buffer@.
-> GLintptr -- ^ @offset@ of type @BufferOffset@.
-> GLsizeiptr -- ^ @length@ of type @BufferSize@.
-> m ()
glInvalidateBufferSubData v1 v2 v3 = liftIO $ dyn290 ptr_glInvalidateBufferSubData v1 v2 v3
{-# NOINLINE ptr_glInvalidateBufferSubData #-}
ptr_glInvalidateBufferSubData :: FunPtr (GLuint -> GLintptr -> GLsizeiptr -> IO ())
ptr_glInvalidateBufferSubData = unsafePerformIO $ getCommand "glInvalidateBufferSubData"
-- glInvalidateFramebuffer -----------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glInvalidateFramebuffer.xhtml OpenGL 4.x>.
glInvalidateFramebuffer
:: MonadIO m
=> GLenum -- ^ @target@ of type [FramebufferTarget](Graphics-GL-Groups.html#FramebufferTarget).
-> GLsizei -- ^ @numAttachments@.
-> Ptr GLenum -- ^ @attachments@ pointing to @numAttachments@ elements of type [InvalidateFramebufferAttachment](Graphics-GL-Groups.html#InvalidateFramebufferAttachment).
-> m ()
glInvalidateFramebuffer v1 v2 v3 = liftIO $ dyn234 ptr_glInvalidateFramebuffer v1 v2 v3
{-# NOINLINE ptr_glInvalidateFramebuffer #-}
ptr_glInvalidateFramebuffer :: FunPtr (GLenum -> GLsizei -> Ptr GLenum -> IO ())
ptr_glInvalidateFramebuffer = unsafePerformIO $ getCommand "glInvalidateFramebuffer"
-- glInvalidateNamedFramebufferData --------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glInvalidateFramebuffer.xhtml OpenGL 4.x>.
glInvalidateNamedFramebufferData
:: MonadIO m
=> GLuint -- ^ @framebuffer@.
-> GLsizei -- ^ @numAttachments@.
-> Ptr GLenum -- ^ @attachments@ pointing to elements of type [FramebufferAttachment](Graphics-GL-Groups.html#FramebufferAttachment).
-> m ()
glInvalidateNamedFramebufferData v1 v2 v3 = liftIO $ dyn293 ptr_glInvalidateNamedFramebufferData v1 v2 v3
{-# NOINLINE ptr_glInvalidateNamedFramebufferData #-}
ptr_glInvalidateNamedFramebufferData :: FunPtr (GLuint -> GLsizei -> Ptr GLenum -> IO ())
ptr_glInvalidateNamedFramebufferData = unsafePerformIO $ getCommand "glInvalidateNamedFramebufferData"
-- glInvalidateNamedFramebufferSubData -----------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glInvalidateSubFramebuffer.xhtml OpenGL 4.x>.
glInvalidateNamedFramebufferSubData
:: MonadIO m
=> GLuint -- ^ @framebuffer@.
-> GLsizei -- ^ @numAttachments@.
-> Ptr GLenum -- ^ @attachments@ pointing to elements of type [FramebufferAttachment](Graphics-GL-Groups.html#FramebufferAttachment).
-> GLint -- ^ @x@.
-> GLint -- ^ @y@.
-> GLsizei -- ^ @width@.
-> GLsizei -- ^ @height@.
-> m ()
glInvalidateNamedFramebufferSubData v1 v2 v3 v4 v5 v6 v7 = liftIO $ dyn497 ptr_glInvalidateNamedFramebufferSubData v1 v2 v3 v4 v5 v6 v7
{-# NOINLINE ptr_glInvalidateNamedFramebufferSubData #-}
ptr_glInvalidateNamedFramebufferSubData :: FunPtr (GLuint -> GLsizei -> Ptr GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
ptr_glInvalidateNamedFramebufferSubData = unsafePerformIO $ getCommand "glInvalidateNamedFramebufferSubData"
-- glInvalidateSubFramebuffer --------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glInvalidateSubFramebuffer.xhtml OpenGL 4.x>.
glInvalidateSubFramebuffer
:: MonadIO m
=> GLenum -- ^ @target@ of type [FramebufferTarget](Graphics-GL-Groups.html#FramebufferTarget).
-> GLsizei -- ^ @numAttachments@.
-> Ptr GLenum -- ^ @attachments@ pointing to @numAttachments@ elements of type [InvalidateFramebufferAttachment](Graphics-GL-Groups.html#InvalidateFramebufferAttachment).
-> GLint -- ^ @x@.
-> GLint -- ^ @y@.
-> GLsizei -- ^ @width@.
-> GLsizei -- ^ @height@.
-> m ()
glInvalidateSubFramebuffer v1 v2 v3 v4 v5 v6 v7 = liftIO $ dyn498 ptr_glInvalidateSubFramebuffer v1 v2 v3 v4 v5 v6 v7
{-# NOINLINE ptr_glInvalidateSubFramebuffer #-}
ptr_glInvalidateSubFramebuffer :: FunPtr (GLenum -> GLsizei -> Ptr GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
ptr_glInvalidateSubFramebuffer = unsafePerformIO $ getCommand "glInvalidateSubFramebuffer"
| haskell-opengl/OpenGLRaw | src/Graphics/GL/Functions/F14.hs | bsd-3-clause | 64,076 | 0 | 16 | 8,824 | 10,947 | 5,644 | 5,303 | 1,123 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Module : $Header$
Copyright : (c) 2015 Swinburne Software Innovation Lab
License : BSD3
Maintainer : Rhys Adams <[email protected]>
Stability : unstable
Portability : portable
Updating local state with data from the scheduler.
-}
module Eclogues.Threads.Update (loadSchedulerState, monitorCluster) where
import Eclogues.AppConfig (AppConfig)
import qualified Eclogues.AppConfig as Config
import qualified Eclogues.Monitoring.Cluster as CM
import Eclogues.Monitoring.Monitor (slaveResources)
import qualified Eclogues.Persist as Persist
import Eclogues.Scheduling.Run (
ScheduleConf (auroraURI), getSchedulerStatuses, requireSchedConf)
import Eclogues.State (activeJobs, updateJobs)
import qualified Eclogues.State.Monad as ES
import Eclogues.State.Types (AppState)
import Eclogues.Util (maybeDo)
import qualified Control.Concurrent.AdvSTM as STM
import qualified Control.Concurrent.AdvSTM.TChan as STM
import qualified Control.Concurrent.AdvSTM.TVar as STM
import Control.Exception (IOException, throwIO, try)
import Control.Lens ((^.))
import Control.Monad.Except (runExceptT)
import Control.Monad.Trans.Either (runEitherT)
import Data.Foldable (traverse_)
import qualified Data.HashMap.Lazy as HashMap
import Servant.Client (ServantError)
import Servant.Common.BaseUrl (BaseUrl)
import System.IO (hPutStrLn, stderr)
-- | Query the scheduler and run 'updateJobs'.
loadSchedulerState :: AppConfig -> STM.TVar AppState -> IO ()
loadSchedulerState conf stateV = do
schedConf <- STM.atomically $ requireSchedConf conf
(newStatusesRes, aJobs) <- do
state <- STM.atomically $ STM.readTVar stateV
let aJobs = activeJobs state
newStatusesRes <- try . runExceptT . getSchedulerStatuses schedConf $ HashMap.elems aJobs
pure (newStatusesRes, aJobs)
case newStatusesRes of
Right (Right newStatuses) -> STM.atomically $ do
state <- STM.readTVar stateV
let (_, ts) = ES.runState state $ updateJobs aJobs newStatuses
mapM_ (STM.writeTChan $ Config.schedChan conf) $ ts ^. ES.scheduleCommands
STM.writeTVar stateV $ ts ^. ES.appState
maybeDo $ STM.onCommit . Persist.atomically (Config.pctx conf) <$> ts ^. ES.persist
Left (ex :: IOException) ->
hPutStrLn stderr $ "Error connecting to Aurora at " ++ show (auroraURI schedConf) ++ "; retrying: " ++ show ex
Right (Left resp) -> throwIO resp
-- | Obtain estimated resources for all available sources and update job satisfiability.
monitorCluster :: STM.AdvSTM (Maybe BaseUrl) -> STM.TVar AppState -> STM.TVar (Maybe CM.Cluster) -> IO ()
monitorCluster urlM stateV clusterV = traverse_ go =<< STM.atomically urlM
where
go url = runEitherT (slaveResources url) >>= \case
Right cluster -> STM.atomically $ do
STM.writeTVar clusterV (Just cluster)
state <- STM.readTVar stateV
let (_, ts) = ES.runState state $ CM.updateSatisfiabilities cluster state
STM.writeTVar stateV $ ts ^. ES.appState
Left (ex :: ServantError) -> do
hPutStrLn stderr $ "Error connecting to health monitor at " ++ show url ++ "; retrying: " ++ show ex
STM.atomically $ do
STM.writeTVar clusterV Nothing
state <- STM.readTVar stateV
let (_, ts) = ES.runState state $ CM.allSatisfyUnknown state
STM.writeTVar stateV $ ts ^. ES.appState
| futufeld/eclogues | eclogues-impl/app/api/Eclogues/Threads/Update.hs | bsd-3-clause | 3,552 | 0 | 21 | 737 | 929 | 485 | 444 | -1 | -1 |
{-# OPTIONS -Wall #-}
{-
@author: Wojciech Jedynak ([email protected])
-}
module Pages where
import Data.Char
import Data.Function
import Data.List
import Text.Printf
import Text.XHtml hiding (dir, color, black, white, lang, link)
import Configuration
import Data.SGF.Types hiding (moves)
import Lang (Language, Messages, allLanguages, capitalize)
import qualified Lang as L
----------------------------------------------------
-- A type for storing the basic data about urls --
----------------------------------------------------
type MovesSoFar = String
data UrlBuilders = UrlBuilders { mainPageUrl :: Language -> String
, moveBrowserMainUrl :: Language -> String
, moveBrowserMakeUrl :: Language -> MovesSoFar -> String
, gameBrowserMakeUrl :: Language -> MovesSoFar -> String
, gameDetailsMakeUrl :: Language -> Int -> String
, configureUrl :: Language -> String
, rebuildUrl :: Language -> String
, gameDownloadLink :: FilePath -> String
, imagesMakeUrl :: String -> String
, cssUrls :: [String]
, jsUrls :: [String]
, language :: Messages
}
-----------------------
-- A common header --
-----------------------
htmlHeader :: UrlBuilders -> Html
htmlHeader urlBuilder = header << ((thetitle << L.title lang)
+++ concatHtml (map buildCss $ cssUrls urlBuilder)
+++ script ! [thetype "text/javascript"] << eidogoConfig
+++ script ! [thetype "text/javascript", src eidogoLangPath] << noHtml
+++ concatHtml (map buildScript $ jsUrls urlBuilder)
+++ progressBar
)
where
progressBar = noHtml -- -}primHtml "<style> .ui-progressbar-value { background-image: url(/public/img/pbar-ani.gif); } </style>"
buildCss css = (thelink ! [href css] ! [thetype "text/css"] ! [rel "stylesheet"] << noHtml)
buildScript url = script ! [thetype "text/javascript", src url] << noHtml
lang = language urlBuilder
eidogoLangPath = printf "/public/eidogo/player/i18n/%s.js" (L.langName lang)
eidogoConfig = primHtml " \
\ eidogoConfig = { \
\ theme: \"standard\", \
\ mode: \"view\", \
\ showComments: true, \
\ showPlayerInfo: false, \
\ showGameInfo: false, \
\ showTools: false, \
\ showOptions: true, \
\ showNavTree: false, \
\ markCurrent: true, \
\ markVariations: false, \
\ markNext: false, \
\ problemMode: false, \
\ enableShortcuts: false \
\ };"
---------------------------------
-- Header used in most pages --
---------------------------------
globalHeader :: UrlBuilders -> (Language -> String) -> Html
globalHeader urlBuilder makeUrl = dI "menu" (linksMenu +++ flagsMenu) where
linksMenu = dI "links" (unordList [pStartPageLink, pHomePageLink])
flagsMenu = dI "flags" (unordList $ map makeFlag allLanguages)
pHomePageLink = anchor ! [href (moveBrowserMainUrl urlBuilder lName)] << L.backToMain lang
pStartPageLink = anchor ! [href (mainPageUrl urlBuilder lName)] << L.startPage lang
lang = language urlBuilder
lName = L.langName lang
makeFlag langStr = anchor ! [href (makeUrl langStr) ]
<< (thespan ! [theclass "flag"] $ (image ! [width "36" , height "24" ,
src (imagesMakeUrl urlBuilder (langStr ++ "_flag.gif"))]))
--flags = dI "flags" $ concatHtml $ intersperse (primHtml " ") $ map makeFlag allLanguages
---------------------
-- The main page --
---------------------
mainPage :: UrlBuilders -> Html
mainPage urlBuilder = pHeader +++ pBody where
lang = language urlBuilder
lName = L.langName lang
pHeader = htmlHeader urlBuilder
makeFlag langStr = anchor ! [href (mainPageUrl urlBuilder langStr) ]
<< image ! [width "180" , height "120" , src (imagesMakeUrl urlBuilder (langStr ++ "_flag.gif"))]
pBody = body $ concatHtml [ welcome
, flags
, hr
, anchor ! [htmlAttr "href" mvBrowserJS] << L.goToMovesBrowser lang
, br , br
, anchor ! [href (configureUrl urlBuilder lName)] << L.config lang
, br , br
, anchor ! [htmlAttr "href" rebuildJS] << L.rebuild lang
]
moveBrowserUrl = moveBrowserMakeUrl urlBuilder lName []
rebldUrl = rebuildUrl urlBuilder lName
rebuildJS = primHtml $ printf "javascript:rebuildConfirm('%s','%s')" (L.confirm lang) rebldUrl
mvBrowserJS = primHtml $ printf "javascript:checkDB('%s','%s', '%s')" (L.noDB lang) moveBrowserUrl rebldUrl
flags = (concatHtml $ intersperse (primHtml " ") $ map makeFlag allLanguages)
welcome = h1 << (L.welcome lang)
--pLinkToMoveBrowser = anchor ! [href (moveBrowserMainUrl urlBuilder)] << h3 << L.goToMovesBrowser lang
-------------------------------------------------------
-- The page that is displayed during DB rebuilding --
-------------------------------------------------------
rebuildingPage :: Int -> Int -> Int -> UrlBuilders -> Html
rebuildingPage sampleSize timeSample totalSize urlBuilder = pHeader +++ pBody where
lang = language urlBuilder
pHeader = htmlHeader urlBuilder
pBody = body ! [strAttr "onLoad" statusFunc ] <<
concatHtml [ gamesCount
, progress
, timeLeft
]
statusFunc = printf "checkStatus(%d, %d, %d)" sampleSize timeSample totalSize
gamesCount = h1 $ primHtml $ (L.gamesToProcess lang) ++ show totalSize
progress = dI "progress" (h1 (thespan ! [identifier "percent"] << noHtml) +++ dI "progressbar" << noHtml)
timeLeft = h1 ((L.timeLeft lang) +++ thespan ! [identifier "timeLeft"] << noHtml)
------------------------------
-- The games browser page --
------------------------------
gameBrowserPage :: [(Int, FilePath, String, String, String, String, String)] -> (Int, Int, Int) -> String -> UrlBuilders -> Html
gameBrowserPage gameInfos (allGames, bWin, wWin) movesSoFar urlBuilder = pHeader +++ pBody where
lang = language urlBuilder
pHeader = htmlHeader urlBuilder
pBody = body $ concatHtml [ globalHeader urlBuilder (\l -> gameBrowserMakeUrl urlBuilder l movesSoFar)
, navigation
, hr
, dI "gameListTable" gameList
]
navigation = concatHtml [ currentPosition , br , br
, numberOfGames , br , br
, currentPositionWinningChance , br , br
, numberOfShownGames
]
blacksTurn = length movesSoFar `mod` 4 == 0
percentage = (100 * current) `div` allGames where
current = if blacksTurn then bWin else wWin
currentPosition = anchor ! [ href mBrowserUrl] << primHtml (L.showCurrentPosition lang) where
mBrowserUrl = moveBrowserMakeUrl urlBuilder (L.langName lang) movesSoFar
numberOfGames = primHtml $ printf "%s %d" (L.numberOfGames lang) allGames
currentPositionWinningChance = primHtml $ printf "%s %d%%" (L.chanceOfWinning lang) percentage
numberOfShownGames = primHtml $ printf "%s %d" (L.noOfShownGames lang) (length gameInfos)
makeLink (gameId, gamePath, winner, bName, wName, bRank, wRank) =
tr $ concatHtml $ map td (map primHtml [show gameId, bName, bRank, wName, wRank, winner] ++ [link]) where
link = anchor ! [href url] << primHtml gamePath
url = gameDetailsMakeUrl urlBuilder (L.langName lang) gameId
gameList = table << (tHeader +++ (concatHtml $ map makeLink gameInfos))
tHeader = tr $ concatHtml $ map (\l -> th << l) labels
labels = map (flip ($) lang) [L.number, L.black, L.blackRank, L.white, L.whiteRank, L.winner, L.link]
-----------------------------
-- The game details page --
-----------------------------
type GameId = Int
gameDetailsPage :: GameId -> SGF -> FilePath -> MovesSoFar -> UrlBuilders -> Html
gameDetailsPage gameId game path movesSoFar urlBuilder = pHeader +++ pBody where
lang = language urlBuilder
pHeader = htmlHeader urlBuilder
pBody = body $ concatHtml [ globalHeader urlBuilder (\l -> gameDetailsMakeUrl urlBuilder l gameId)
, gameInContext
, hr
, dI "gameLeft" $ concatHtml [ gameSummary
, br
, downloadGame
, br
, br
, finalPosition
, italics $ primHtml(L.finalPosition lang)
]
, dI "gameRight" eidogo
]
gameInContext = anchor ! [href mBrowserUrl] << (L.showInContext lang) where
mBrowserUrl = moveBrowserMakeUrl urlBuilder (L.langName lang) movesSoFar
eidogo = dC "eidogo-player-auto" ! [strAttr "sgf" (gameDownloadLink urlBuilder path)] << noHtml
downloadGame = anchor ! [href (gameDownloadLink urlBuilder path)] << (L.downloadSgf lang)
--movesSoFar = getMovesStr game
finalPosition = board urlBuilder True [] movesSoFar
(blk, wht, res, dt) = sgfSummary game
result =
case res of
Unfinished -> L.noResult lang
Win Black _ -> "B+"
Win White _ -> "W+"
Draw -> error "Found a draw: impossible case!"
gameSummary = dI "gameSummary" $ table << bData
labels = [capitalize (L.black lang), capitalize (L.white lang), L.result lang, L.date lang]
values = [blk, wht, result, dt]
bData = map (\(l,v) -> tr << ((td << (l ++ ":")) +++ (td << v))) (zip labels values)
-------------------------------
-- The configuration forms --
-------------------------------
configForm :: Configuration -> UrlBuilders -> Html
configForm configuration urlBuilder = pHeader +++ pBody where
pHeader = htmlHeader urlBuilder
lang = language urlBuilder
pBody = body $ concatHtml [ globalHeader urlBuilder (configureUrl urlBuilder)
, h1 << L.configurationForm lang
, cForm
]
cForm = form ! [method "POST"] $ concatHtml [ primHtml sqliteLabel
, br
, sqlitePath
, br
, br
, primHtml dirsLabel
, br
, dirsForm
, br
, submitButton
]
sqliteLabel = L.sqlite3Location lang
sqlitePath = primHtml $ printf "<textarea name=\"sqlitePath\" cols=\"100\" rows=\"1\">%s</textarea>" dbPath
dbPath =
case dbServer configuration of
-- PostgreSQL -> ""
Sqlite3 p -> p
dirsLabel = L.sgfDirectories lang
dirsForm = primHtml $ printf "<textarea name=\"dirs\" cols=\"100\" rows=\"10\">%s</textarea>" (unlines (gameDirs configuration))
submitButton = submit "action" (L.submitChanges lang)
--dbLabel = L.databaseLabel lang
--dbSelectForm = select ! [name "dbServer"] $ concatHtml $ map makeOption ["PostgreSQL", "SQLite3"] where
{-
-- primHtml dbLabel
-- , br
-- , dbSelectForm
-- , br
-- , br
-- ,
currentDb =
case dbServer configuration of
PostgreSQL -> "postgresql"
Sqlite3 _ -> "sqlite3"
makeOption dbName = option ! [value lowered] ! attrs $ primHtml dbName where
lowered = map toLower dbName
attrs = if lowered == currentDb then [selected] else []
-}
-----------------------------
-- The move browser page --
-----------------------------
moveBrowser :: Int -> (Int, Int, Int) -> [(String, Int, Int, Int)] -> String -> UrlBuilders -> Html
moveBrowser count (allGames, bWin, wWin) moves movesSoFar urlBuilder = pHeader +++ pBody where
lang = language urlBuilder
pHeader = htmlHeader urlBuilder
pBody = body $ concatHtml [ globalHeader urlBuilder (\l -> moveBrowserMakeUrl urlBuilder l movesSoFar)
, currentStatistics
, hr
, dI "boardInfo" $ boardDiv +++ infoDiv
, dI "tables" $ leftTable +++ rightTable
]
-- main parts of pBody
infoDiv = dI "infoBox" $ concatHtml [ movesSoFarField
, playerToMove
, takeBackLink
, resetMovesField
]
boardDiv = board urlBuilder True candidates movesSoFar
-- smaller parts
currentStatistics = concatHtml [ primHtml $ L.gamesInDb lang count
, br , br
, currentPositionWinningChance
, br , br
, numberOfGames
, br , br
, matchingGames
]
percentage = (100 * current) `div` allGames where
current = if blacksTurn then bWin else wWin
currentPositionWinningChance = primHtml $ printf "%s %d%%" (L.chanceOfWinning lang) percentage
numberOfGames = primHtml $ printf "%s %d" (L.numberOfGames lang) allGames
matchingGames = anchor ! [href gamesUrl] << primHtml (L.matchingGamesList lang) where
gamesUrl = gameBrowserMakeUrl urlBuilder langName movesSoFar
langName = L.langName (language urlBuilder)
takeBackLink
| null movesSoFar = noHtml
| otherwise = anchor ! [href (moveBrowserMakeUrl urlBuilder langName (init (init movesSoFar)))]
<< h3 << L.takeBackMove lang
resetMovesField
| null movesSoFar = noHtml
| otherwise = anchor ! [href (moveBrowserMakeUrl urlBuilder langName [])] << h3 << L.resetMoves lang
noMoves = length movesSoFar `div` 2
movesSoFarField = h4 << (L.numberOfMoves lang ++ show noMoves)
playerToMoveStr = if blacksTurn then L.black lang else L.white lang
playerToMove = h4 << (L.playerToMove lang ++ playerToMoveStr)
candidates = map (\(a,_,_,_) -> a) moves
leftTable = dI "leftTable" << (pH1 +++ pMoves movesTotal)
rightTable = dI "rightTable" << (pH2 +++ pMoves movesPercentage)
pH1 = h4 << L.movesByTotalCount lang
pH2 = h4 << L.movesByWinPercentage lang
movesTotal = reverse $ sortBy (compare `on` (\(_,t,_,_) -> t)) moves
movesPercentage = reverse $ sortBy (compare `on` selector) moves
selector (_,t,b,w) =
let c = if blacksTurn then b else w
in (1000*c) `div` t
pMoves mvs = table << (tHeader +++ concatHtml (map makeRow mvs))
blacksTurn = length movesSoFar `mod` 4 == 0
tHeader = concatHtml [ th << L.move lang
, th << L.totalPlayed lang
, th << L.blackWins lang
, th << L.whiteWins lang
, th << (if blacksTurn then L.blackWinningPerc lang else L.whiteWinningPerc lang)
]
makeRow (move, cnt, blk, wht) = tr ! [ identifier trid] << concatHtml [ td << moveField
, td << countField
, td << show blk
, td << show wht
, td << localPercentage
] where
localPercentage = show ((100 * current) `div` cnt) ++ "%"
current = if blacksTurn then blk else wht
url = moveBrowserMakeUrl urlBuilder langName $ movesSoFar ++ move
countField = anchor ! [href gamesUrl ] << show cnt where
gamesUrl = gameBrowserMakeUrl urlBuilder langName $ movesSoFar ++ move
moveField
| null move = anchor ! [href gameDetailsUrl] << L.gameOver lang
| otherwise = anchor ! [href url] << thespan ! attrs << (moveStrToCoordinates move) where
gameDetailsUrl = gameBrowserMakeUrl urlBuilder langName movesSoFar
attrs = [ identifier idd
, strAttr "onMouseover" (printf "lstMouseOver(\"%s\",\"%s\")" imgUrl move)
, strAttr "onMouseout" (printf "lstMouseOut(\"%s\")" move)
]
imgUrl = imagesMakeUrl urlBuilder $ if blacksTurn then moveFromColor B else moveFromColor W
idd = "lst" ++ move
trid = "tr" ++ move
----------------------------------------
-- Functions for drawing a go board --
----------------------------------------
type Point = (Int, Int)
{- 91 11
99 19 -}
-- |Returns the name of the image that should be used in the given point (assuming it's an empty intersection)
imageFromPoint :: Point -> String
imageFromPoint (1,1) = "ur.gif"
imageFromPoint (9,1) = "ul.gif"
imageFromPoint (9,9) = "dl.gif"
imageFromPoint (1,9) = "dr.gif"
imageFromPoint (_,1) = "u.gif"
imageFromPoint (_,9) = "d.gif"
imageFromPoint (1,_) = "er.gif"
imageFromPoint (9,_) = "el.gif"
imageFromPoint _ = "e.gif"
data Color = B | W
otherColor :: Color -> Color
otherColor B = W
otherColor W = B
imageFromColor :: Color -> String
imageFromColor B = "b.gif"
imageFromColor W = "w.gif"
moveFromColor :: Color -> String
moveFromColor B = "bm.gif"
moveFromColor W = "wm.gif"
parseMoves :: String -> [(Point, Color)]
parseMoves = parseMoves' B
parseMoves' :: Color -> String -> [(Point, Color)]
parseMoves' color (x:y:rest) = ((digitToInt x, digitToInt y), color) : parseMoves' (otherColor color) rest
parseMoves' _ _ = []
getImage :: Point -> String -> String
getImage point str =
case lookup point (parseMoves str) of
Nothing -> imageFromPoint point
Just color -> imageFromColor color
getIntersect :: String -> String -> UrlBuilders -> Bool -> [Point] -> Point -> String -> Html
getIntersect _ _ urlBuilder False _ point str = image ! [src (imagesMakeUrl urlBuilder $ (getImage point str))]
getIntersect imgUrl url urlBuilder True candidates point@(i,j) str
| point `elem` candidates =
let
move = show i ++ show j
attrs = [ identifier $ "brd" ++ move
, strAttr "onMouseover" (printf "brdMouseOver(\"%s\", \"%s\")" imgUrl move)
, strAttr "onMouseout" (printf "brdMouseOut(%s)" move)
]
in
anchor ! [href url] << thespan ! attrs << primHtml "x"
| otherwise = getIntersect imgUrl url urlBuilder False candidates point str
board :: UrlBuilders -> Bool -> [String] -> String -> Html
board urlBuilder displayCand moves movesSoFar = dI "boardTable" $ tbl where
tbl = table ! [border 0] ! [cellspacing 0] ! [cellpadding 0] << (bHeader +++ concatHtml (map row [1..9]))
bHeader = tr << map (\n -> td << primHtml [n]) ['A'..'I']
row j = tr << (concatHtml (map field (reverse [1..9])) +++ td << primHtml (show (10-j))) where
field i = td << getIntersect imgUrl url urlBuilder displayCand candMoves (i,j) movesSoFar where
imgUrl = imagesMakeUrl urlBuilder (if length movesSoFar `mod` 4 == 0 then moveFromColor B else moveFromColor W)
url = moveBrowserMakeUrl urlBuilder langName $ movesSoFar ++ show i ++ show j
langName = L.langName (language urlBuilder)
candMoves = map (\[a,b] -> (digitToInt a, digitToInt b)) moves'
moves' = filter ((==2) . length) moves
--------------------------------------
-- HTML building-oriented helpers --
--------------------------------------
dI :: String -> Html -> Html
dI x = thediv ! [identifier x]
dC :: String -> Html -> Html
dC x = thediv ! [theclass x]
| wjzz/GoStat | src/Pages.hs | bsd-3-clause | 21,698 | 23 | 19 | 7,758 | 5,144 | 2,764 | 2,380 | 298 | 7 |
------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) Amy de Buitléir 2012-2016
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Runs the QuickCheck tests.
--
------------------------------------------------------------------------
module Main where
import ALife.Creatur.Wain.UIVector.Cluster.ActionQC (test)
import ALife.Creatur.Wain.UIVector.Cluster.ExperimentQC (test)
import Test.Framework as TF (defaultMain, Test)
tests :: [TF.Test]
tests =
[
-- In increasing order of complexity
ALife.Creatur.Wain.UIVector.Cluster.ActionQC.test,
ALife.Creatur.Wain.UIVector.Cluster.ExperimentQC.test
]
main :: IO ()
main = defaultMain tests
| mhwombat/exp-uivector-cluster-wains | test/Main.hs | bsd-3-clause | 803 | 0 | 6 | 118 | 113 | 80 | 33 | 11 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] en
[@ISO639-2B@] eng
[@ISO639-3@] eng
[@Native name@] English
[@English name@] English
-}
module Text.Numeral.Language.ENG.TestData
( gb_cardinals, gb_ordinals
, us_cardinals, us_ordinals
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Prelude ( Num )
import "base-unicode-symbols" Data.Monoid.Unicode ( (⊕) )
import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
import "text" Data.Text ( Text )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
-- Sources: http://en.wikipedia.org/wiki/List_of_numbers
en_cardinals ∷ (Num i) ⇒ [(i, Text)]
en_cardinals =
[ (0, "zero")
, (1, "one")
, (2, "two")
, (3, "three")
, (4, "four")
, (5, "five")
, (6, "six")
, (7, "seven")
, (8, "eight")
, (9, "nine")
, (10, "ten")
, (11, "eleven")
, (12, "twelve")
, (13, "thirteen")
, (14, "fourteen")
, (15, "fifteen")
, (16, "sixteen")
, (17, "seventeen")
, (18, "eighteen")
, (19, "nineteen")
, (20, "twenty")
, (21, "twenty-one")
, (22, "twenty-two")
, (23, "twenty-three")
, (24, "twenty-four")
, (25, "twenty-five")
, (26, "twenty-six")
, (27, "twenty-seven")
, (28, "twenty-eight")
, (29, "twenty-nine")
, (30, "thirty")
, (31, "thirty-one")
, (32, "thirty-two")
, (33, "thirty-three")
, (34, "thirty-four")
, (35, "thirty-five")
, (36, "thirty-six")
, (37, "thirty-seven")
, (38, "thirty-eight")
, (39, "thirty-nine")
, (40, "forty")
, (41, "forty-one")
, (42, "forty-two")
, (43, "forty-three")
, (44, "forty-four")
, (45, "forty-five")
, (46, "forty-six")
, (47, "forty-seven")
, (48, "forty-eight")
, (49, "forty-nine")
, (50, "fifty")
, (51, "fifty-one")
, (52, "fifty-two")
, (53, "fifty-three")
, (54, "fifty-four")
, (55, "fifty-five")
, (56, "fifty-six")
, (57, "fifty-seven")
, (58, "fifty-eight")
, (59, "fifty-nine")
, (60, "sixty")
, (61, "sixty-one")
, (62, "sixty-two")
, (63, "sixty-three")
, (64, "sixty-four")
, (65, "sixty-five")
, (66, "sixty-six")
, (67, "sixty-seven")
, (68, "sixty-eight")
, (69, "sixty-nine")
, (70, "seventy")
, (71, "seventy-one")
, (72, "seventy-two")
, (73, "seventy-three")
, (74, "seventy-four")
, (75, "seventy-five")
, (76, "seventy-six")
, (77, "seventy-seven")
, (78, "seventy-eight")
, (79, "seventy-nine")
, (80, "eighty")
, (81, "eighty-one")
, (82, "eighty-two")
, (83, "eighty-three")
, (84, "eighty-four")
, (85, "eighty-five")
, (86, "eighty-six")
, (87, "eighty-seven")
, (88, "eighty-eight")
, (89, "eighty-nine")
, (90, "ninety")
, (91, "ninety-one")
, (92, "ninety-two")
, (93, "ninety-three")
, (94, "ninety-four")
, (95, "ninety-five")
, (96, "ninety-six")
, (97, "ninety-seven")
, (98, "ninety-eight")
, (99, "ninety-nine")
, (100, "one hundred")
]
en_ordinals ∷ (Num i) ⇒ [(i, Text)]
en_ordinals =
[ (0, "zeroth")
, (1, "first")
, (2, "second")
, (3, "third")
, (4, "fourth")
, (5, "fifth")
, (6, "sixth")
, (7, "seventh")
, (8, "eighth")
, (9, "ninth")
, (10, "tenth")
, (11, "eleventh")
, (12, "twelfth")
, (13, "thirteenth")
, (14, "fourteenth")
, (15, "fifteenth")
, (16, "sixteenth")
, (17, "seventeenth")
, (18, "eighteenth")
, (19, "nineteenth")
, (20, "twentieth")
, (21, "twenty-first")
, (22, "twenty-second")
, (23, "twenty-third")
, (24, "twenty-fourth")
, (25, "twenty-fifth")
, (26, "twenty-sixth")
, (27, "twenty-seventh")
, (28, "twenty-eighth")
, (29, "twenty-ninth")
, (30, "thirtieth")
, (31, "thirty-first")
, (32, "thirty-second")
, (33, "thirty-third")
, (34, "thirty-fourth")
, (35, "thirty-fifth")
, (36, "thirty-sixth")
, (37, "thirty-seventh")
, (38, "thirty-eighth")
, (39, "thirty-ninth")
, (40, "fortieth")
, (41, "forty-first")
, (42, "forty-second")
, (43, "forty-third")
, (44, "forty-fourth")
, (45, "forty-fifth")
, (46, "forty-sixth")
, (47, "forty-seventh")
, (48, "forty-eighth")
, (49, "forty-ninth")
, (50, "fiftieth")
, (51, "fifty-first")
, (52, "fifty-second")
, (53, "fifty-third")
, (54, "fifty-fourth")
, (55, "fifty-fifth")
, (56, "fifty-sixth")
, (57, "fifty-seventh")
, (58, "fifty-eighth")
, (59, "fifty-ninth")
, (60, "sixtieth")
, (61, "sixty-first")
, (62, "sixty-second")
, (63, "sixty-third")
, (64, "sixty-fourth")
, (65, "sixty-fifth")
, (66, "sixty-sixth")
, (67, "sixty-seventh")
, (68, "sixty-eighth")
, (69, "sixty-ninth")
, (70, "seventieth")
, (71, "seventy-first")
, (72, "seventy-second")
, (73, "seventy-third")
, (74, "seventy-fourth")
, (75, "seventy-fifth")
, (76, "seventy-sixth")
, (77, "seventy-seventh")
, (78, "seventy-eighth")
, (79, "seventy-ninth")
, (80, "eightieth")
, (81, "eighty-first")
, (82, "eighty-second")
, (83, "eighty-third")
, (84, "eighty-fourth")
, (85, "eighty-fifth")
, (86, "eighty-sixth")
, (87, "eighty-seventh")
, (88, "eighty-eighth")
, (89, "eighty-ninth")
, (90, "ninetieth")
, (91, "ninety-first")
, (92, "ninety-second")
, (93, "ninety-third")
, (94, "ninety-fourth")
, (95, "ninety-fifth")
, (96, "ninety-sixth")
, (97, "ninety-seventh")
, (98, "ninety-eighth")
, (99, "ninety-ninth")
, (100, "one hundreth")
]
gb_cardinals ∷ (Num i) ⇒ TestData i
gb_cardinals =
[ ( "default"
, defaultInflection
, en_cardinals
⊕ [ (-1, "minus one")
, (101, "one hundred and one")
, (110, "one hundred and ten")
, (111, "one hundred and eleven")
, (120, "one hundred and twenty")
, (121, "one hundred and twenty-one")
, (144, "one hundred and forty-four")
, (200, "two hundred")
, (300, "three hundred")
, (666, "six hundred and sixty-six")
, (1000, "one thousand")
, (1001, "one thousand and one")
, (1010, "one thousand and ten")
, (1011, "one thousand and eleven")
, (1024, "one thousand and twenty-four")
, (1100, "one thousand one hundred")
, (1728, "one thousand seven hundred and twenty-eight")
, (2000, "two thousand")
, (10000, "ten thousand")
, (100000, "one hundred thousand")
, (500000, "five hundred thousand")
, (1000000, "one million")
, (1048576, "one million forty-eight thousand five hundred and seventy-six")
, (10000000, "ten million")
]
)
]
gb_ordinals ∷ (Num i) ⇒ TestData i
gb_ordinals =
[ ( "default"
, defaultInflection
, en_ordinals
⊕ [ (101, "one hundred and first")
, (110, "one hundred and tenth")
, (111, "one hundred and eleventh")
, (120, "one hundred and twentieth")
, (121, "one hundred and twenty-first")
, (144, "one hundred and forty-fourth")
, (200, "two hundreth")
, (300, "three hundreth")
, (666, "six hundred and sixty-sixth")
, (1000, "one thousandth")
, (1001, "one thousand and first")
, (1010, "one thousand and tenth")
, (1011, "one thousand and eleventh")
, (1024, "one thousand and twenty-fourth")
, (1100, "one thousand one hundreth")
, (1728, "one thousand seven hundred and twenty-eighth")
, (2000, "two thousandth")
, (10000, "ten thousandth")
, (100000, "one hundred thousandth")
, (500000, "five hundred thousandth")
, (1000000, "one millionth")
, (1048576, "one million forty-eight thousand five hundred and seventy-sixth")
, (10000000, "ten millionth")
]
)
]
us_cardinals ∷ (Num i) ⇒ TestData i
us_cardinals =
[ ( "default"
, defaultInflection
, en_cardinals
⊕ [ (-1, "negative one")
, (101, "one hundred one")
, (110, "one hundred ten")
, (111, "one hundred eleven")
, (120, "one hundred twenty")
, (121, "one hundred twenty-one")
, (144, "one hundred forty-four")
, (200, "two hundred")
, (300, "three hundred")
, (666, "six hundred sixty-six")
, (1000, "one thousand")
, (1001, "one thousand one")
, (1010, "one thousand ten")
, (1011, "one thousand eleven")
, (1024, "one thousand twenty-four")
, (1100, "one thousand one hundred")
, (1728, "one thousand seven hundred twenty-eight")
, (2000, "two thousand")
, (10000, "ten thousand")
, (100000, "one hundred thousand")
, (500000, "five hundred thousand")
, (1000000, "one million")
, (1048576, "one million forty-eight thousand five hundred seventy-six")
, (10000000, "ten million")
]
)
]
us_ordinals ∷ (Num i) ⇒ TestData i
us_ordinals =
[ ( "default"
, defaultInflection
, en_ordinals
⊕ [ (101, "one hundred first")
, (110, "one hundred tenth")
, (111, "one hundred eleventh")
, (120, "one hundred twentieth")
, (121, "one hundred twenty-first")
, (144, "one hundred forty-fourth")
, (200, "two hundreth")
, (300, "three hundreth")
, (666, "six hundred sixty-sixth")
, (1000, "one thousandth")
, (1001, "one thousand first")
, (1010, "one thousand tenth")
, (1011, "one thousand eleventh")
, (1024, "one thousand twenty-fourth")
, (1100, "one thousand one hundreth")
, (1728, "one thousand seven hundred twenty-eighth")
, (2000, "two thousandth")
, (10000, "ten thousandth")
, (100000, "one hundred thousandth")
, (500000, "five hundred thousandth")
, (1000000, "one millionth")
, (1048576, "one million forty-eight thousand five hundred seventy-sixth")
, (10000000, "ten millionth")
]
)
]
| telser/numerals | src-test/Text/Numeral/Language/ENG/TestData.hs | bsd-3-clause | 10,420 | 0 | 10 | 2,612 | 2,971 | 1,969 | 1,002 | 333 | 1 |
module IRTS.CodegenCilSpec where
import Control.Applicative ((<$>))
import Control.Arrow ((>>>))
import Control.Monad (forM_)
import Control.Monad.Trans.Except (ExceptT, runExceptT)
import Control.Monad.Trans.State.Strict (StateT, evalStateT)
import IRTS.CodegenCil
import IRTS.CodegenCommon
import IRTS.Compiler
import Idris.AbsSyntax
import Idris.ElabDecls
import Idris.REPL
import System.Directory
import System.Exit
import System.FilePath
import System.Info (os)
import System.Process
import Test.Hspec
import qualified Test.Hspec as H
spec :: Spec
spec = describe "idris-cil" $ do
files <- H.runIO testCaseFiles
H.runIO $ compileToBytecode files
parallel $ forM_ files testCaseForFile
testCaseFiles :: IO [FilePath]
testCaseFiles = do
cd <- getCurrentDirectory
listFilesWithExtension ".idr" (cd </> "test/cases")
testCaseForFile :: FilePath -> Spec
testCaseForFile f =
it ("can compile `" ++ takeBaseName f ++ "'") $ do
output <- exec f
expected <- firstCommentIn f
output `shouldBe` expected
listFilesWithExtension :: String -> FilePath -> IO [FilePath]
listFilesWithExtension ext dir = do
files <- getDirectoryContents dir
return $ map (dir </>) $ filter ((== ext) . takeExtension) files
firstCommentIn :: FilePath -> IO String
firstCommentIn f = takeComment <$> readFile f
where takeComment = lines >>> takeWhile (/= "-}") >>> drop 1 >>> unlines
exec :: FilePath -> IO String
exec input = do
ci <- compileCodegenInfo input output
codegenCil ci
peverify output
mono output
where output = replaceExtension input "exe"
compileToBytecode :: [FilePath] -> IO ()
compileToBytecode files = traceProcess "idris" (options ++ files)
where options = ["--typeintype", "--check", "--quiet", "-p", "cil", "-p", "contrib"]
evalIdris :: Monad m => IState -> StateT IState (ExceptT e m) a -> m (Either e a)
evalIdris istate prog = runExceptT $ evalStateT prog istate
compileCodegenInfo :: String -> String -> IO CodegenInfo
compileCodegenInfo input output = do
Right ci <- evalIdris idrisInit $ codegenInfoFrom [bytecodeFile] output
return ci
where bytecodeFile = replaceExtension input "ibc"
codegenInfoFrom :: [FilePath] -> FilePath -> Idris CodegenInfo
codegenInfoFrom inputs output = do
elabPrims
_ <- loadInputs inputs Nothing
mainProg <- elabMain
compile (Via "cil") output (Just mainProg)
mono :: String -> IO String
mono exe = if os == "mingw32"
then readProcess exe [] ""
else readProcess "mono" [exe] ""
peverify :: String -> IO ()
peverify exe = traceProcess "peverify" [exe]
traceProcess :: String -> [String] -> IO ()
traceProcess exe args = do
(code, stdout, stderr) <- readProcessWithExitCode exe args ""
case code of
ExitFailure _ -> error $ exe ++ " error: " ++ stdout ++ stderr
_ -> return ()
| BartAdv/idris-cil | test/IRTS/CodegenCilSpec.hs | bsd-3-clause | 2,996 | 0 | 13 | 679 | 943 | 482 | 461 | 76 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.ClearBufferObject
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.ClearBufferObject (
-- * Extension Support
glGetARBClearBufferObject,
gl_ARB_clear_buffer_object,
-- * Functions
glClearBufferData,
glClearBufferSubData
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/ARB/ClearBufferObject.hs | bsd-3-clause | 655 | 0 | 4 | 89 | 47 | 36 | 11 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
module Game.Monsters.MBerserk where
import Control.Lens (use, preuse, ix, (^.), (.=), zoom, (%=), (&), (.~), (%~))
import Control.Monad (void, unless, liftM, when)
import Data.Bits ((.&.), (.|.))
import Linear (V3(..), _x)
import qualified Data.Vector as V
import {-# SOURCE #-} Game.GameImportT
import Game.LevelLocalsT
import Game.GameLocalsT
import Game.CVarT
import Game.SpawnTempT
import Game.EntityStateT
import Game.EdictT
import Game.GClientT
import Game.MoveInfoT
import Game.ClientPersistantT
import Game.ClientRespawnT
import Game.MonsterInfoT
import Game.PlayerStateT
import Types
import QuakeRef
import QuakeState
import CVarVariables
import Game.Adapters
import qualified Constants
import qualified Game.GameAI as GameAI
import qualified Game.GameMisc as GameMisc
import qualified Game.GameWeapon as GameWeapon
import qualified Game.GameUtil as GameUtil
import qualified Util.Lib as Lib
modelScale :: Float
modelScale = 1.0
frameStand1 :: Int
frameStand1 = 0
frameStand5 :: Int
frameStand5 = 4
frameStandB1 :: Int
frameStandB1 = 5
frameStandB20 :: Int
frameStandB20 = 24
frameWalkC1 :: Int
frameWalkC1 = 25
frameWalkC11 :: Int
frameWalkC11 = 35
frameRun1 :: Int
frameRun1 = 36
frameRun6 :: Int
frameRun6 = 41
frameAttC1 :: Int
frameAttC1 = 76
frameAttC8 :: Int
frameAttC8 = 83
frameAttC9 :: Int
frameAttC9 = 84
frameAttC20 :: Int
frameAttC20 = 95
frameAttC21 :: Int
frameAttC21 = 96
frameAttC34 :: Int
frameAttC34 = 109
framePainC1 :: Int
framePainC1 = 199
framePainC4 :: Int
framePainC4 = 202
framePainB1 :: Int
framePainB1 = 203
framePainB20 :: Int
framePainB20 = 222
frameDeath1 :: Int
frameDeath1 = 223
frameDeath13 :: Int
frameDeath13 = 235
frameDeathC1 :: Int
frameDeathC1 = 236
frameDeathC8 :: Int
frameDeathC8 = 243
berserkSight :: EntInteract
berserkSight =
GenericEntInteract "berserk_sight" $ \selfRef _ -> do
soundSight <- use $ mBerserkGlobals.mBerserkSoundSight
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanVoice soundSight 1 Constants.attnNorm 0
return True
berserkSearch :: EntThink
berserkSearch =
GenericEntThink "berserk_search" $ \selfRef -> do
soundSearch <- use $ mBerserkGlobals.mBerserkSoundSearch
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanVoice soundSearch 1 Constants.attnNorm 0
return True
berserkFidget :: EntThink
berserkFidget =
GenericEntThink "berserk_fidget" $ \selfRef -> do
self <- readRef selfRef
if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0
then
return True
else do
r <- Lib.randomF
if r > 0.15
then
return True
else do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just berserkMoveStandFidget)
soundIdle <- use $ mBerserkGlobals.mBerserkSoundIdle
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanWeapon soundIdle 1 Constants.attnIdle 0
return True
berserkFramesStand :: V.Vector MFrameT
berserkFramesStand =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 (Just berserkFidget)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
berserkMoveStand :: MMoveT
berserkMoveStand = MMoveT "berserkMoveStand" frameStand1 frameStand5 berserkFramesStand Nothing
berserkStand :: EntThink
berserkStand =
GenericEntThink "berserk_stand" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just berserkMoveStand)
return True
berserkFramesStandFidget :: V.Vector MFrameT
berserkFramesStandFidget =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
berserkMoveStandFidget :: MMoveT
berserkMoveStandFidget = MMoveT "berserkMoveStandFidget" frameStandB1 frameStandB20 berserkFramesStandFidget (Just berserkStand)
berserkFramesWalk :: V.Vector MFrameT
berserkFramesWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 9.1 Nothing
, MFrameT (Just GameAI.aiWalk) 6.3 Nothing
, MFrameT (Just GameAI.aiWalk) 4.9 Nothing
, MFrameT (Just GameAI.aiWalk) 6.7 Nothing
, MFrameT (Just GameAI.aiWalk) 6.0 Nothing
, MFrameT (Just GameAI.aiWalk) 8.2 Nothing
, MFrameT (Just GameAI.aiWalk) 7.2 Nothing
, MFrameT (Just GameAI.aiWalk) 6.1 Nothing
, MFrameT (Just GameAI.aiWalk) 4.9 Nothing
, MFrameT (Just GameAI.aiWalk) 4.7 Nothing
, MFrameT (Just GameAI.aiWalk) 4.7 Nothing
, MFrameT (Just GameAI.aiWalk) 4.8 Nothing
]
berserkMoveWalk :: MMoveT
berserkMoveWalk = MMoveT "berserkMoveWalk" frameWalkC1 frameWalkC11 berserkFramesWalk Nothing
berserkWalk :: EntThink
berserkWalk =
GenericEntThink "berserk_walk" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just berserkMoveWalk)
return True
{-
-
- **************************** SKIPPED THIS FOR NOW!
- ****************************
-
- Running . Arm raised in air
-
- void() berserk_runb1 =[ $r_att1 , berserk_runb2 ] {ai_run(21);}; void()
- berserk_runb2 =[ $r_att2 , berserk_runb3 ] {ai_run(11);}; void()
- berserk_runb3 =[ $r_att3 , berserk_runb4 ] {ai_run(21);}; void()
- berserk_runb4 =[ $r_att4 , berserk_runb5 ] {ai_run(25);}; void()
- berserk_runb5 =[ $r_att5 , berserk_runb6 ] {ai_run(18);}; void()
- berserk_runb6 =[ $r_att6 , berserk_runb7 ] {ai_run(19);}; // running with
- arm in air : start loop void() berserk_runb7 =[ $r_att7 , berserk_runb8 ]
- {ai_run(21);}; void() berserk_runb8 =[ $r_att8 , berserk_runb9 ]
- {ai_run(11);}; void() berserk_runb9 =[ $r_att9 , berserk_runb10 ]
- {ai_run(21);}; void() berserk_runb10 =[ $r_att10 , berserk_runb11 ]
- {ai_run(25);}; void() berserk_runb11 =[ $r_att11 , berserk_runb12 ]
- {ai_run(18);}; void() berserk_runb12 =[ $r_att12 , berserk_runb7 ]
- {ai_run(19);}; // running with arm in air : end loop
-}
berserkFramesRun1 :: V.Vector MFrameT
berserkFramesRun1 =
V.fromList [ MFrameT (Just GameAI.aiRun) 21 Nothing
, MFrameT (Just GameAI.aiRun) 11 Nothing
, MFrameT (Just GameAI.aiRun) 21 Nothing
, MFrameT (Just GameAI.aiRun) 25 Nothing
, MFrameT (Just GameAI.aiRun) 18 Nothing
, MFrameT (Just GameAI.aiRun) 19 Nothing
]
berserkMoveRun1 :: MMoveT
berserkMoveRun1 = MMoveT "berserkMoveRun1" frameRun1 frameRun6 berserkFramesRun1 Nothing
berserkRun :: EntThink
berserkRun =
GenericEntThink "berserk_run" $ \selfRef -> do
self <- readRef selfRef
let action = if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0
then berserkMoveStand
else berserkMoveRun1
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
berserkAttackSpike :: EntThink
berserkAttackSpike =
GenericEntThink "berserk_attack_spike" $ \selfRef -> do
r <- Lib.rand
let n = r `mod` 6 + 15
aim = V3 (fromIntegral Constants.meleeDistance) 0 (-24)
void $ GameWeapon.fireHit selfRef aim (fromIntegral n) 400
-- Faster attack -- upwards and backwards
return True
berserkSwing :: EntThink
berserkSwing =
GenericEntThink "berserk_swing" $ \selfRef -> do
soundPunch <- use $ mBerserkGlobals.mBerserkSoundPunch
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanWeapon soundPunch 1 Constants.attnNorm 0
return True
berserkFramesAttackSpike :: V.Vector MFrameT
berserkFramesAttackSpike =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just berserkSwing)
, MFrameT (Just GameAI.aiCharge) 0 (Just berserkAttackSpike)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
]
berserkMoveAttackSpike :: MMoveT
berserkMoveAttackSpike = MMoveT "berserkMoveAttackSpike" frameAttC1 frameAttC8 berserkFramesAttackSpike (Just berserkRun)
berserkAttackClub :: EntThink
berserkAttackClub =
GenericEntThink "berserk_attack_club" $ \selfRef -> do
self <- readRef selfRef
r <- Lib.rand
let n = r `mod` 6 + 5
aim = V3 (fromIntegral Constants.meleeDistance) (self^.eMins._x) (-4)
void $ GameWeapon.fireHit selfRef aim (fromIntegral n) 400 -- slower attack
return True
berserkFramesAttackClub :: V.Vector MFrameT
berserkFramesAttackClub =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just berserkSwing)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just berserkAttackClub)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
]
berserkMoveAttackClub :: MMoveT
berserkMoveAttackClub = MMoveT "berserkMoveAttackClub" frameAttC9 frameAttC20 berserkFramesAttackClub (Just berserkRun)
berserkStrike :: EntThink
berserkStrike =
GenericEntThink "berserk_strike" $ \_ -> return True
berserkFramesAttackStrike :: V.Vector MFrameT
berserkFramesAttackStrike =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 (Just berserkSwing)
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 (Just berserkStrike)
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 9.7 Nothing
, MFrameT (Just GameAI.aiMove) 13.6 Nothing
]
berserkMoveAttackStrike :: MMoveT
berserkMoveAttackStrike = MMoveT "berserkMoveAttackStrike" frameAttC21 frameAttC34 berserkFramesAttackStrike (Just berserkRun)
berserkMelee :: EntThink
berserkMelee =
GenericEntThink "berserk_melee" $ \selfRef -> do
r <- Lib.rand
let action = if r .&. 1 == 0
then berserkMoveAttackSpike
else berserkMoveAttackClub
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
{-
- void() berserk_atke1 =[ $r_attb1, berserk_atke2 ] {ai_run(9);}; void()
- berserk_atke2 =[ $r_attb2, berserk_atke3 ] {ai_run(6);}; void()
- berserk_atke3 =[ $r_attb3, berserk_atke4 ] {ai_run(18.4);}; void()
- berserk_atke4 =[ $r_attb4, berserk_atke5 ] {ai_run(25);}; void()
- berserk_atke5 =[ $r_attb5, berserk_atke6 ] {ai_run(14);}; void()
- berserk_atke6 =[ $r_attb6, berserk_atke7 ] {ai_run(20);}; void()
- berserk_atke7 =[ $r_attb7, berserk_atke8 ] {ai_run(8.5);}; void()
- berserk_atke8 =[ $r_attb8, berserk_atke9 ] {ai_run(3);}; void()
- berserk_atke9 =[ $r_attb9, berserk_atke10 ] {ai_run(17.5);}; void()
- berserk_atke10 =[ $r_attb10, berserk_atke11 ] {ai_run(17);}; void()
- berserk_atke11 =[ $r_attb11, berserk_atke12 ] {ai_run(9);}; void()
- berserk_atke12 =[ $r_attb12, berserk_atke13 ] {ai_run(25);}; void()
- berserk_atke13 =[ $r_attb13, berserk_atke14 ] {ai_run(3.7);}; void()
- berserk_atke14 =[ $r_attb14, berserk_atke15 ] {ai_run(2.6);}; void()
- berserk_atke15 =[ $r_attb15, berserk_atke16 ] {ai_run(19);}; void()
- berserk_atke16 =[ $r_attb16, berserk_atke17 ] {ai_run(25);}; void()
- berserk_atke17 =[ $r_attb17, berserk_atke18 ] {ai_run(19.6);}; void()
- berserk_atke18 =[ $r_attb18, berserk_run1 ] {ai_run(7.8);};
-}
berserkFramesPain1 :: V.Vector MFrameT
berserkFramesPain1 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
berserkMovePain1 :: MMoveT
berserkMovePain1 = MMoveT "berserkMovePain1" framePainC1 framePainC4 berserkFramesPain1 (Just berserkRun)
berserkFramesPain2 :: V.Vector MFrameT
berserkFramesPain2 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
berserkMovePain2 :: MMoveT
berserkMovePain2 = MMoveT "berserkMovePain2" framePainB1 framePainB20 berserkFramesPain2 (Just berserkRun)
berserkPain :: EntPain
berserkPain =
GenericEntPain "berserk_pain" $ \selfRef _ _ damage -> do
self <- readRef selfRef
when ((self^.eHealth) < (self^.eMaxHealth) `div` 2) $
modifyRef selfRef (\v -> v & eEntityState.esSkinNum .~ 1)
levelTime <- use $ gameBaseGlobals.gbLevel.llTime
unless (levelTime < (self^.ePainDebounceTime)) $ do
modifyRef selfRef (\v -> v & ePainDebounceTime .~ levelTime + 3)
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundPain <- use $ mBerserkGlobals.mBerserkSoundPain
sound (Just selfRef) Constants.chanVoice soundPain 1 Constants.attnNorm 0
skillValue <- liftM (^.cvValue) skillCVar
unless (skillValue == 3) $ do -- no pain anims in nightmare
r <- Lib.randomF
let currentMove = if damage < 20 || r < 0.5
then berserkMovePain1
else berserkMovePain2
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just currentMove)
berserkDead :: EntThink
berserkDead =
GenericEntThink "berserk_dead" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMins .~ V3 (-16) (-16) (-24)
& eMaxs .~ V3 16 16 (-8)
& eMoveType .~ Constants.moveTypeToss
& eSvFlags %~ (.|. Constants.svfDeadMonster)
& eNextThink .~ 0)
linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity
linkEntity selfRef
return True
berserkFramesDeath1 :: V.Vector MFrameT
berserkFramesDeath1 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
berserkMoveDeath1 :: MMoveT
berserkMoveDeath1 = MMoveT "berserkMoveDeath1" frameDeath1 frameDeath13 berserkFramesDeath1 (Just berserkDead)
berserkFramesDeath2 :: V.Vector MFrameT
berserkFramesDeath2 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
berserkMoveDeath2 :: MMoveT
berserkMoveDeath2 = MMoveT "berserkMoveDeath2" frameDeathC1 frameDeathC8 berserkFramesDeath2 (Just berserkDead)
berserkDie :: EntDie
berserkDie =
GenericEntDie "berserk_die" $ \selfRef _ _ damage _ -> do
self <- readRef selfRef
gameImport <- use $ gameBaseGlobals.gbGameImport
let sound = gameImport^.giSound
soundIndex = gameImport^.giSoundIndex
if | (self^.eHealth) < (self^.eGibHealth) -> do
soundIdx <- soundIndex (Just "misc/udeath.wav")
sound (Just selfRef) Constants.chanVoice soundIdx 1 Constants.attnNorm 0
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwHead selfRef "models/objects/gibs/head2/tris.md2" damage Constants.gibOrganic
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead)
| (self^.eDeadFlag) == Constants.deadDead ->
return ()
| otherwise -> do
soundDie <- use $ mBerserkGlobals.mBerserkSoundDie
sound (Just selfRef) Constants.chanVoice soundDie 1 Constants.attnNorm 0
let currentMove = if damage >= 50
then berserkMoveDeath1
else berserkMoveDeath2
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead
& eTakeDamage .~ Constants.damageYes
& eMonsterInfo.miCurrentMove .~ Just currentMove)
{-
- QUAKED monster_berserk (1 .5 0) (-16 -16 -24) (16 16 32) Ambush
- Trigger_Spawn Sight
-}
spMonsterBerserk :: Ref EdictT -> Quake ()
spMonsterBerserk selfRef = do
deathmatchValue <- liftM (^.cvValue) deathmatchCVar
if deathmatchValue /= 0
then
GameUtil.freeEdict selfRef
else do
gameImport <- use $ gameBaseGlobals.gbGameImport
let soundIndex = gameImport^.giSoundIndex
modelIndex = gameImport^.giModelIndex
linkEntity = gameImport^.giLinkEntity
soundIndex (Just "berserk/berpain2.wav") >>= (mBerserkGlobals.mBerserkSoundPain .=)
soundIndex (Just "berserk/berdeth2.wav") >>= (mBerserkGlobals.mBerserkSoundDie .=)
soundIndex (Just "berserk/beridle1.wav") >>= (mBerserkGlobals.mBerserkSoundIdle .=)
soundIndex (Just "berserk/attack.wav") >>= (mBerserkGlobals.mBerserkSoundPunch .=)
soundIndex (Just "berserk/bersrch1.wav") >>= (mBerserkGlobals.mBerserkSoundSearch .=)
soundIndex (Just "berserk/sight.wav") >>= (mBerserkGlobals.mBerserkSoundSight .=)
modelIdx <- modelIndex (Just "models/monsters/berserk/tris.md2")
modifyRef selfRef (\v -> v & eEntityState.esModelIndex .~ modelIdx
& eMins .~ V3 (-16) (-16) (-24)
& eMaxs .~ V3 16 16 32
& eMoveType .~ Constants.moveTypeStep
& eSolid .~ Constants.solidBbox
& eHealth .~ 240
& eGibHealth .~ (-60)
& eMass .~ 250
& ePain .~ Just berserkPain
& eDie .~ Just berserkDie
& eMonsterInfo.miStand .~ Just berserkStand
& eMonsterInfo.miWalk .~ Just berserkWalk
& eMonsterInfo.miRun .~ Just berserkRun
& eMonsterInfo.miDodge .~ Nothing
& eMonsterInfo.miAttack .~ Nothing
& eMonsterInfo.miMelee .~ Just berserkMelee
& eMonsterInfo.miSight .~ Just berserkSight
& eMonsterInfo.miSearch .~ Just berserkSearch
& eMonsterInfo.miCurrentMove .~ Just berserkMoveStand
& eMonsterInfo.miScale .~ modelScale)
linkEntity selfRef
void $ think GameAI.walkMonsterStart selfRef
| ksaveljev/hake-2 | src/Game/Monsters/MBerserk.hs | bsd-3-clause | 23,205 | 0 | 53 | 6,327 | 5,640 | 2,864 | 2,776 | -1 | -1 |
module ReadGhcProg where
import Data.Char
import Text.ParserCombinators.ReadP
import GHostCPU
-- getProgram :: String -> [Inst]
getProgram = map (fst . head . filter (null . snd) . readP_to_S parseInst)
. filter (not . null)
. map (trim . fst . break (';'==)) . lines . map toUpper
trim :: String -> String
trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace
parseInst :: ReadP Inst
parseInst = pMov
+++ pSop
+++ pBop
+++ pJmp
+++ pInt
+++ pHlt
pMov :: ReadP Inst
pMov = do
{ skipSpaces
; string "MOV"
; skipSpaces
; [a,b] <- sepBy1 parseArg (char ',')
; return (MOV a b)
}
pSop :: ReadP Inst
pSop = do
{ skipSpaces
; sop <- string "INC"+++string "DEC"
; a <- parseArg
; return (mkSop sop a)
}
mkSop :: String -> Arg -> Inst
mkSop "INC" = INC
mkSop "DEC" = DEC
pBop :: ReadP Inst
pBop = do
{ skipSpaces
; bop <- string "ADD"+++string "SUB"
+++string "MUL"+++string "DIV"
+++string "AND"+++string "OR"
+++string "XOR"
; skipSpaces
; [a,b] <- sepBy1 parseArg (char ',')
; return (mkBop bop a b)
}
mkBop :: String -> Dest -> Src -> Inst
mkBop bop = case bop of
"ADD" -> ADD
"SUB" -> SUB
"MUL" -> MUL
"DIV" -> DIV
"AND" -> AND
"OR" -> OR
"XOR" -> XOR
_ -> error "mkBop"
pJmp :: ReadP Inst
pJmp = do
{ skipSpaces
; jmp <- string "JLT"+++string "JEQ"+++string "JGT"
; skipSpaces
; lab <- many1 (satisfy isDigit)
; skipSpaces
; char ','
; skipSpaces
; [x,y] <- sepBy1 parseArg (char ',')
; return (mkJmp jmp (read lab) x y)
}
mkJmp :: String -> Targ -> X -> Y -> Inst
mkJmp jmp = case jmp of
"JLT" -> JLT
"JEQ" -> JEQ
"JGT" -> JGT
_ -> error "mkJmp"
pInt :: ReadP Inst
pInt = do
{ skipSpaces
; _ <- string "INT"
; skipSpaces
; s <- many1 (satisfy isDigit)
; return (INT (read s))
}
pHlt :: ReadP Inst
pHlt = do
{ skipSpaces
; _ <- string "HLT"
; return HLT
}
parseArg :: ReadP Arg
parseArg = argPC
+++ argReg
+++ argInd
+++ argConst
+++ argLoc
argPC :: ReadP Arg
argPC = skipSpaces >> string "PC" >>= \_ -> return ArgPC
argReg :: ReadP Arg
argReg = do
{ skipSpaces;
; c <- satisfy (`elem` "ABCDEFGH")
; skipSpaces;
; return (ArgReg c)
}
argInd :: ReadP Arg
argInd = do
{ skipSpaces;
; char '['
; skipSpaces;
; c <- satisfy (`elem` "ABCDEFGH")
; skipSpaces;
; char ']'
; skipSpaces;
; return (ArgInd c)
}
argConst :: ReadP Arg
argConst = do
{ skipSpaces
; num <- many1 (satisfy isDigit)
; return (ArgConst (read num))
}
argLoc :: ReadP Arg
argLoc = do
{ skipSpaces;
; char '['
; skipSpaces;
; num <- many1 (satisfy isDigit)
; skipSpaces;
; char ']'
; skipSpaces;
; return (ArgLoc (read num))
}
showArg :: Arg -> String
showArg ArgPC = "PC"
showArg (ArgReg r) = [r]
showArg (ArgInd r) = '[':r:"]"
showArg (ArgConst w) = show w
showArg (ArgLoc w) = '[':(show w++"]")
showInst :: Inst -> String
showInst (MOV d s) = "MOV "++showArg d++","++showArg s
showInst (INC d) = "INC "++showArg d
showInst (DEC d) = "DEC "++showArg d
showInst (ADD d s) = "ADD "++showArg d++","++showArg s
showInst (SUB d s) = "SUB "++showArg d++","++showArg s
showInst (MUL d s) = "MUL "++showArg d++","++showArg s
showInst (DIV d s) = "DIV "++showArg d++","++showArg s
showInst (AND d s) = "AND "++showArg d++","++showArg s
showInst (OR d s) = "OR "++showArg d++","++showArg s
showInst (XOR d s) = "XOR "++showArg d++","++showArg s
showInst (JLT lab x y) = "JEQ "++show lab++","++showArg x++","++showArg y
showInst (JEQ lab x y) = "JEQ "++show lab++","++showArg x++","++showArg y
showInst (JGT lab x y) = "JGT "++show lab++","++showArg x++","++showArg y
showInst (INT n) = "INT "++show n
showInst HLT = "HLT"
| msakai/icfpc2014 | ReadGhcProg.hs | bsd-3-clause | 4,074 | 10 | 15 | 1,241 | 1,753 | 866 | 887 | 142 | 8 |
module TicTacToe.Internal.Result where
import qualified TicTacToe.Data.Cell as C
import qualified TicTacToe.Internal.Matrix as M
data Result
= Tied
| Won
| InProgress
deriving (Eq, Show)
mkResult :: M.Matrix -> Result
mkResult m
| any M.isWinningSequence $ M.rowsOf m ++ M.columnsOf m ++ M.diagonalsOf m = Won
| all (all C.isMarked) (M.getCells m) = Tied
| otherwise = InProgress
| rodamber/haskell-tic-tac-toe | src/TicTacToe/Internal/Result.hs | bsd-3-clause | 403 | 0 | 12 | 80 | 145 | 77 | 68 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Portager (
module Portager.DSL
, PortageR
, portager
, runPortageR
) where
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.Trans.Reader (ReaderT, runReaderT)
import Data.Maybe (mapMaybe)
import Data.String (IsString(..))
import Data.Text (Text)
import qualified Data.Text as Text (lines, stripPrefix)
import qualified Data.Text.IO as Text (readFile)
import Portager.Options (Options(..), WorldSet, withOptions)
import Portager.Writes (createPortageSetConfig, writePortageSetConfigs)
import Portager.DSL
type PortageR a = ReaderT PortagerConfiguration Identity a
-- |Triggers Orphan Instances Warning.
-- It seems that wrapping it in a newtype is not worth the trouble.
instance IsString a => IsString (PortageR a) where
fromString = return . fromString
runPortageR :: PortagerConfiguration -> ReaderT PortagerConfiguration Identity a -> a
runPortageR cfg r = runIdentity $ runReaderT r cfg
parseWorldSets :: Text -> [WorldSet]
parseWorldSets = mapMaybe (Text.stripPrefix "@") . Text.lines
readWorldSets :: FilePath -> IO [WorldSet]
readWorldSets = fmap parseWorldSets . Text.readFile
portager :: PortagerConfiguration -> [PortageR PackageSet] -> IO ()
portager cfg ps = withOptions $ \opts -> do
ws <- readWorldSets (_worldSets opts)
runReaderT (writePortageSetConfigs ws $ map createPortageSetConfig $ runPortageR cfg $ sequence ps) opts
| j1r1k/portager | src/Portager.hs | bsd-3-clause | 1,507 | 0 | 14 | 211 | 397 | 223 | 174 | 31 | 1 |
{-+
This module defines the function #hlex2html#, which translates the output from
an early pass of the lexical analyzer to HTML. It can also make use of cross
reference information to link identifiers to their definitions.
The generated HTML is intended to be part of the body of a web page,
thus it does not include the #head# or #body# tags.
-}
module HLex2html({-hlex2html,-}hlex2html',simpleHlex2html) where
import RefsTypes --hiding (isDef)
import MUtils(apSnd)
import Char(isSpace{-,isAlpha-},isAlphaNum)
import HsTokens
import SrcLoc1
import LitTxt(toHTMLblock)
import PathUtils(normf)
import HLexTagModuleNames
import PrettyPrint(pp)
--------------------------------------------------------------------------------
type ModuleContext = (FilePath,[(FilePath,Module)]) -- (this,other) modules
type LexTokens = [(Token,(Pos,String))]
type URL = String
type HTML = String
simpleHlex2html :: LexTokens -> HTML
--hlex2html :: ModuleContext -> (Refs,LexTokens) -> HTML
hlex2html' :: (Module->URL) -> ModuleContext -> (Refs,LexTokens) -> HTML
--------------------------------------------------------------------------------
simpleHlex2html = hlex2html' undefined dummy . (,) []
where dummy = ("",[("",noModule)])
hlex2html' srcURL (thisf,fm) =
normal . tokens2html srcURL (thisf,thism,fm) . uncurry merge .
apSnd convModuleNames
where Just thism = lookup thisf fm
{-+
The functions #normal#, #pre#, and #code# implement a state machine that
handles the insertion of properly nested #pre# and #div# tags.
-}
-- Normal text mode, in which literate comments can be output:
normal [] = []
normal ((LiterateComment,(_,s)):ts) = toHTMLblock s++normal ts
normal ((Whitespace,(p,s)):ts) | noCodeOnLine (line p) ts = s++normal ts -- indented code??
normal ((Commentstart,(Pos{column=1},s1)):(Comment,(_,s2)):ts) =
preStart++cmntesc (s1++s2)++pre ts
normal ((Comment,ps1):(Whitespace,ps2):ts) | isBlockComment ps1 ps2 =
preStart++cmntesc (snd ps1++snd ps2)++pre ts
normal ts = codeStart++code ts
-- Inside a <pre> block, where blank lines and block comments can be output:
pre [] = preEnd
pre ((LiterateComment,(_,s)):ts) = preEnd++toHTMLblock s++normal ts
pre ((Whitespace,(_,s)):ts) = s++pre ts
pre ((Commentstart,(Pos{column=1},s1)):(Comment,(_,s2)):ts) =
cmntesc (s1++s2)++pre ts
pre ((Comment,ps1):(Whitespace,ps2):ts) | isBlockComment ps1 ps2 =
cmntesc (snd ps1++snd ps2)++pre ts
pre ts = preEnd++codeStart++code ts
-- Inside a code, where code and ordinary comments can be output:
code [] = codeEnd
code ((LiterateComment,(_,s)):ts) = codeEnd++toHTMLblock s++normal ts
code ((Commentstart,(_,s1)):(Comment,(_,s2)):ts) = cmntesc (s1++s2)++code ts
code ((Comment,ps1):(Whitespace,ps2):ts) | isBlockComment ps1 ps2 =
codeEnd++preStart++cmntesc (snd ps1++snd ps2)++pre ts
code ((Comment,(_,s)) :ts) = cmntesc s++code ts
code ((Whitespace,(_,s)) :ts) = s++code ts
code ((_,(_,s)):ts) = s++code ts
preStart = "<pre>"
preEnd = "</pre>"
codeStart = "<div class=code><pre>"
codeEnd = "</pre></div>"
isBlockComment (Pos{column=1},'{':'-':_) (_,s) | '\n' `elem` s = True
isBlockComment _ _ = False
noCodeOnLine l ts =
all ((`elem` notCode).fst) (takeWhile ((==l).line.fst.snd) ts)
where notCode = [LiterateComment,Whitespace{-,Commentstart,Comment-}]
cmntesc = cmnt . esc
--------------------------------------------------------------------------------
tokens2html srcURL rs = map (token2html srcURL rs)
token2html :: (Module->URL)->(FilePath,Module,[(FilePath,Module)])->
((Token,(Pos,String)),Maybe Orig)->
(Token,(Pos,String))
token2html _ _ ((LiterateComment,ps@(_,"> ")),_) = (Whitespace,ps)
token2html _ _ ((NestedComment,s),_) = nestedcomment s
token2html srcURL (thisf,thism,fm) ((t,(p,s)),r) = (t,(p,f (esc s)))
where
moduleLink s =
case [m|(f,m)<-fm,sameModuleName s m] of
[m] -> link (srcURL m)
_ -> modname
f = case t of
ModuleName -> if sameModuleName s thism || thism==noModule
then modname
else moduleLink s
ModuleAlias -> modname
Reservedid -> b
Reservedop -> b
Conid -> conp
Consym -> consymp
Qconid -> conp
Qconsym -> consymp
Varid -> varp
Specialid -> b
Varsym -> varsymp
Qvarid -> varp
Qvarsym -> varsymp
-- Literal -> lit -- obsolete
IntLit -> lit
FloatLit -> lit
CharLit -> lit
StringLit -> lit
{-
Whitespace ->
Special
-}
_ -> id
varp = var (info "var" "" p)
conp = con (info "con" "" p)
varsymp = var (info "var" "op" p)
consymp = con (info "con" "op" p)
modname = con (Nothing,[("class","mod")])
info cl op p =
case r of
Just (n,role,sp,rs) | n==s ->
(link,
(if isDef role
then (("id",rstarget sp rs):)
else id) $
[("class",ty++cl++op),("title",n++": "++title)])
where
ty = if isType sp then "t" else ""
ttag t = if isType t then "t" else "v"
link = case links of
[Just link] -> Just link
_ -> Nothing
title = case titles of
[] -> "not in scope"
_ -> unwords titles
(links,titles) = unzip (map shr rs)
sht T = "type"
sht V = "value"
sht Cl = "class"
sht (Co n) = "constructor of "++n
sht (Me n) = "method of class "++n
sht (Fi n) = "field of type "++n
shr (t,p) =
apSnd (("a "++sht t)++) $
if role==DP
then (Nothing," bound here")
else if isDef role
then (Nothing," defined here")
else shrp t p
shrp t (Left (m,n)) =
if m==thism
then (Just ("#"++tmangle t n)," defined in this module")
else (Just (srcURL m++"#"++tmangle t n)," defined in module "++pp m)
shrp _ (Right p'@(f,rc)) =
if p'==(thisf,p)
then (Nothing," defined here")
else if f==thisf
then (Just ("#"++shPos' rc),
" defined in this module at "++shPos rc)
else (Just (srcURL m++"#"++shPos' rc),
" defined in module "++pp m++" at "++show p')
where Just m = lookup (normf f) fm
--shpos (f,(y,x)) = show (SrcLoc f 0 y x) -- hmm
--shrc (y,x) = show y++":"++show x
--shrc' (y,x) = show y++"."++show x
rstarget t = rtarget t . head
rtarget t = either (gtarget t) ptarget . snd
gtarget t = tmangle t . snd
ptarget = shPos' . snd
tmangle t p = ttag t++mangle p
_ -> (Nothing,attrs)
where
attrs = if thism==noModule
then [("class",cl++op)]
else [("title","Hmm. Info missing")]
--isDef r = r `elem` [DT,DL,DP,DC]
b = ctx "b"
var (optl,as) = optlink optl . ctx' "var" as
con (optl,as) = optlink optl . ctx' "b" as
lit = ctx' "span" [("class","lit")]
optlink = maybe id link
link url = ctx' "a" [("href",url)]
cmnt = ctx' "span" [("class","cmnt")]
-- Some nested comments, {-+ ... -}, are treated like literate comments...
nestedcomment ps@(p,s) =
case s of
'{':'-':'+':c:s' | isSpace c ->
case reverse s' of
'}':'-':s -> (LiterateComment,(p,reverse s))
_ -> (NestedComment,ps) -- Can't happen
_ -> (NestedComment,ps)
ctx t s = tag t++s++endtag t
ctx' t as s = tag (t++shas as)++s++endtag t
where
shas = concatMap sha
sha (n,v) = ' ':n++"="++quote v
tag t = "<"++t++">"
endtag t = tag ('/':t)
esc = concatMap esc1
where esc1 '<' = "<"
esc1 '&' = "&"
esc1 c = [c]
quote s =
if all isAlphaNum s
then s
else '"':s++"\""
mangle = concatMap mangle1
where
mangle1 c = if isAlphaNum c
then [c]
else '.':show (fromEnum c) -- hmm
| forste/haReFork | tools/hs2html/HLex2html.hs | bsd-3-clause | 7,608 | 159 | 24 | 1,741 | 2,994 | 1,649 | 1,345 | 177 | 38 |
-- | Convenience module to import the specific rewriting function model
-- and combinator implementation known as /explicit/.
-- In package adp-multi-monadiccp, there is another
-- combinator implementation.
module ADP.Multi.Rewriting.All (module X) where
import ADP.Multi.Rewriting.Model as X
import ADP.Multi.Rewriting.Combinators() | adp-multi/adp-multi | src/ADP/Multi/Rewriting/All.hs | bsd-3-clause | 341 | 0 | 4 | 45 | 37 | 28 | 9 | 3 | 0 |
<ESC>:let g:haskell_indent_disable_case = 1
ah x = x
where
f x = case x of
1 -> if g x
then 2
else 3
4 -> if g x
then 5
else 6
_ -> if g x
then 7
else 8
g x = False
| itchyny/vim-haskell-indent | test/case/disable_case_caseif.in.hs | mit | 165 | 4 | 6 | 46 | 92 | 50 | 42 | -1 | -1 |
{-# OPTIONS_GHC -Wwarn #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Interface.ParseModuleHeader
-- Copyright : (c) Simon Marlow 2006, Isaac Dupree 2009
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Haddock.Interface.ParseModuleHeader (parseModuleHeader) where
import Control.Applicative ((<$>))
import Control.Monad (mplus)
import Data.Char
import DynFlags
import Haddock.Parser
import Haddock.Types
import RdrName
-- -----------------------------------------------------------------------------
-- Parsing module headers
-- NB. The headers must be given in the order Module, Description,
-- Copyright, License, Maintainer, Stability, Portability, except that
-- any or all may be omitted.
parseModuleHeader :: DynFlags -> String -> (HaddockModInfo RdrName, Doc RdrName)
parseModuleHeader dflags str0 =
let
getKey :: String -> String -> (Maybe String,String)
getKey key str = case parseKey key str of
Nothing -> (Nothing,str)
Just (value,rest) -> (Just value,rest)
(_moduleOpt,str1) = getKey "Module" str0
(descriptionOpt,str2) = getKey "Description" str1
(copyrightOpt,str3) = getKey "Copyright" str2
(licenseOpt,str4) = getKey "License" str3
(licenceOpt,str5) = getKey "Licence" str4
(maintainerOpt,str6) = getKey "Maintainer" str5
(stabilityOpt,str7) = getKey "Stability" str6
(portabilityOpt,str8) = getKey "Portability" str7
in (HaddockModInfo {
hmi_description = parseString dflags <$> descriptionOpt,
hmi_copyright = copyrightOpt,
hmi_license = licenseOpt `mplus` licenceOpt,
hmi_maintainer = maintainerOpt,
hmi_stability = stabilityOpt,
hmi_portability = portabilityOpt,
hmi_safety = Nothing,
hmi_language = Nothing, -- set in LexParseRn
hmi_extensions = [] -- also set in LexParseRn
}, parseParas dflags str8)
-- | This function is how we read keys.
--
-- all fields in the header are optional and have the form
--
-- [spaces1][field name][spaces] ":"
-- [text]"\n" ([spaces2][space][text]"\n" | [spaces]"\n")*
-- where each [spaces2] should have [spaces1] as a prefix.
--
-- Thus for the key "Description",
--
-- > Description : this is a
-- > rather long
-- >
-- > description
-- >
-- > The module comment starts here
--
-- the value will be "this is a .. description" and the rest will begin
-- at "The module comment".
parseKey :: String -> String -> Maybe (String,String)
parseKey key toParse0 =
do
let
(spaces0,toParse1) = extractLeadingSpaces toParse0
indentation = spaces0
afterKey0 <- extractPrefix key toParse1
let
afterKey1 = extractLeadingSpaces afterKey0
afterColon0 <- case snd afterKey1 of
':':afterColon -> return afterColon
_ -> Nothing
let
(_,afterColon1) = extractLeadingSpaces afterColon0
return (scanKey True indentation afterColon1)
where
scanKey :: Bool -> String -> String -> (String,String)
scanKey _ _ [] = ([],[])
scanKey isFirst indentation str =
let
(nextLine,rest1) = extractNextLine str
accept = isFirst || sufficientIndentation || allSpaces
sufficientIndentation = case extractPrefix indentation nextLine of
Just (c:_) | isSpace c -> True
_ -> False
allSpaces = case extractLeadingSpaces nextLine of
(_,[]) -> True
_ -> False
in
if accept
then
let
(scanned1,rest2) = scanKey False indentation rest1
scanned2 = case scanned1 of
"" -> if allSpaces then "" else nextLine
_ -> nextLine ++ "\n" ++ scanned1
in
(scanned2,rest2)
else
([],str)
extractLeadingSpaces :: String -> (String,String)
extractLeadingSpaces [] = ([],[])
extractLeadingSpaces (s@(c:cs))
| isSpace c =
let
(spaces1,cs1) = extractLeadingSpaces cs
in
(c:spaces1,cs1)
| otherwise = ([],s)
extractNextLine :: String -> (String,String)
extractNextLine [] = ([],[])
extractNextLine (c:cs)
| c == '\n' =
([],cs)
| otherwise =
let
(line,rest) = extractNextLine cs
in
(c:line,rest)
-- comparison is case-insensitive.
extractPrefix :: String -> String -> Maybe String
extractPrefix [] s = Just s
extractPrefix _ [] = Nothing
extractPrefix (c1:cs1) (c2:cs2)
| toUpper c1 == toUpper c2 = extractPrefix cs1 cs2
| otherwise = Nothing
| jgm/haddock | src/Haddock/Interface/ParseModuleHeader.hs | bsd-2-clause | 5,082 | 0 | 18 | 1,492 | 1,151 | 624 | 527 | 93 | 12 |
{-# LANGUAGE BangPatterns #-}
module Main (main) where
import Data.BEncode
import Data.ByteString as BS
import Data.Torrent
import Criterion.Main
tinyPath :: FilePath
tinyPath = "res/dapper-dvd-amd64.iso.torrent"
largePath :: FilePath
largePath = "res/pkg.torrent"
decoder :: ByteString -> Torrent
decoder bs = let Right r = decode bs in r
main :: IO ()
main = do
!tinyBin <- BS.readFile tinyPath
!largeBin <- BS.readFile largePath
defaultMain
[ bench "read/tiny" $ nf decoder tinyBin
, bench "read/large" $ nf decoder largeBin
] | DavidAlphaFox/bittorrent | bench/TorrentFile.hs | bsd-3-clause | 556 | 0 | 10 | 103 | 164 | 83 | 81 | 19 | 1 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module System.CPUTime (module M) where
import "base" System.CPUTime as M
| Ye-Yong-Chi/codeworld | codeworld-base/src/System/CPUTime.hs | apache-2.0 | 743 | 0 | 4 | 136 | 23 | 17 | 6 | 4 | 0 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Foreign
-- Copyright : (c) The University of Glasgow, 2008-2011
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable
--
-- Foreign marshalling support for CStrings with configurable encodings
--
-----------------------------------------------------------------------------
module GHC.Foreign (
-- * C strings with a configurable encoding
-- conversion of C strings into Haskell strings
--
peekCString,
peekCStringLen,
-- conversion of Haskell strings into C strings
--
newCString,
newCStringLen,
-- conversion of Haskell strings into C strings using temporary storage
--
withCString,
withCStringLen,
charIsRepresentable,
) where
import Foreign.Marshal.Array
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable
import Data.Word
-- Imports for the locale-encoding version of marshallers
import Data.Tuple (fst)
import Data.Maybe
import GHC.Show ( show )
import Foreign.Marshal.Alloc
import Foreign.ForeignPtr
import GHC.List
import GHC.Num
import GHC.Base
import GHC.IO
import GHC.IO.Exception
import GHC.IO.Buffer
import GHC.IO.Encoding.Types
c_DEBUG_DUMP :: Bool
c_DEBUG_DUMP = False
putDebugMsg :: String -> IO ()
putDebugMsg | c_DEBUG_DUMP = undefined --debugLn TODO: Replace with system.out.println
| otherwise = const (return ())
-- These definitions are identical to those in Foreign.C.String, but copied in here to avoid a cycle:
type CString = Ptr CChar
type CStringLen = (Ptr CChar, Int)
-- exported functions
-- ------------------
-- | Marshal a NUL terminated C string into a Haskell string.
--
peekCString :: TextEncoding -> CString -> IO String
peekCString enc cp = do
sz <- lengthArray0 nUL cp
peekEncodedCString enc (cp, sz * cCharSize)
-- | Marshal a C string with explicit length into a Haskell string.
--
peekCStringLen :: TextEncoding -> CStringLen -> IO String
peekCStringLen = peekEncodedCString
-- | Marshal a Haskell string into a NUL terminated C string.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCString :: TextEncoding -> String -> IO CString
newCString enc = liftM fst . newEncodedCString enc True
-- | Marshal a Haskell string into a C string (ie, character array) with
-- explicit length information.
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCStringLen :: TextEncoding -> String -> IO CStringLen
newCStringLen enc = newEncodedCString enc False
-- | Marshal a Haskell string into a NUL terminated C string using temporary
-- storage.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCString :: TextEncoding -> String -> (CString -> IO a) -> IO a
withCString enc s act = withEncodedCString enc True s $ \(cp, _sz) -> act cp
-- | Marshal a Haskell string into a C string (ie, character array)
-- in temporary storage, with explicit length information.
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCStringLen :: TextEncoding -> String -> (CStringLen -> IO a) -> IO a
withCStringLen enc = withEncodedCString enc False
-- | Determines whether a character can be accurately encoded in a 'CString'.
--
-- Pretty much anyone who uses this function is in a state of sin because
-- whether or not a character is encodable will, in general, depend on the
-- context in which it occurs.
charIsRepresentable :: TextEncoding -> Char -> IO Bool
charIsRepresentable enc c = withCString enc [c] (fmap (== [c]) . peekCString enc) `catchException` (\e -> let _ = e :: IOException in return False)
-- auxiliary definitions
-- ----------------------
-- C's end of string character
nUL :: CChar
nUL = 0
-- Size of a CChar in bytes
cCharSize :: Int
cCharSize = sizeOf (undefined :: CChar)
{-# INLINE peekEncodedCString #-}
peekEncodedCString :: TextEncoding -- ^ Encoding of CString
-> CStringLen
-> IO String -- ^ String in Haskell terms
peekEncodedCString (TextEncoding { mkTextDecoder = mk_decoder }) (p, sz_bytes)
= bracket mk_decoder close $ \decoder -> do
let chunk_size = sz_bytes `max` 1 -- Decode buffer chunk size in characters: one iteration only for ASCII
from0 <- fmap (\fp -> bufferAdd sz_bytes (emptyBuffer fp sz_bytes ReadBuffer)) $ newForeignPtr_ (castPtr p)
to <- newCharBuffer chunk_size WriteBuffer
let go iteration from = do
(why, from', to') <- encode decoder from to
if isEmptyBuffer from'
then
-- No input remaining: @why@ will be InputUnderflow, but we don't care
withBuffer to' $ peekArray (bufferElems to')
else do
-- Input remaining: what went wrong?
putDebugMsg ("peekEncodedCString: " ++ show iteration ++ " " ++ show why)
(from'', to'') <- case why of InvalidSequence -> recover decoder from' to' -- These conditions are equally bad because
InputUnderflow -> recover decoder from' to' -- they indicate malformed/truncated input
OutputUnderflow -> return (from', to') -- We will have more space next time round
putDebugMsg ("peekEncodedCString: from " ++ summaryBuffer from ++ " " ++ summaryBuffer from' ++ " " ++ summaryBuffer from'')
putDebugMsg ("peekEncodedCString: to " ++ summaryBuffer to ++ " " ++ summaryBuffer to' ++ " " ++ summaryBuffer to'')
to_chars <- withBuffer to'' $ peekArray (bufferElems to'')
fmap (to_chars++) $ go (iteration + 1) from''
go (0 :: Int) from0
{-# INLINE withEncodedCString #-}
withEncodedCString :: TextEncoding -- ^ Encoding of CString to create
-> Bool -- ^ Null-terminate?
-> String -- ^ String to encode
-> (CStringLen -> IO a) -- ^ Worker that can safely use the allocated memory
-> IO a
withEncodedCString (TextEncoding { mkTextEncoder = mk_encoder }) null_terminate s act
= bracket mk_encoder close $ \encoder -> withArrayLen s $ \sz p -> do
from <- fmap (\fp -> bufferAdd sz (emptyBuffer fp sz ReadBuffer)) $ newForeignPtr_ p
let go iteration to_sz_bytes = do
putDebugMsg ("withEncodedCString: " ++ show iteration)
allocaBytes to_sz_bytes $ \to_p -> do
mb_res <- tryFillBufferAndCall encoder null_terminate from to_p to_sz_bytes act
case mb_res of
Nothing -> go (iteration + 1) (to_sz_bytes * 2)
Just res -> return res
-- If the input string is ASCII, this value will ensure we only allocate once
go (0 :: Int) (cCharSize * (sz + 1))
{-# INLINE newEncodedCString #-}
newEncodedCString :: TextEncoding -- ^ Encoding of CString to create
-> Bool -- ^ Null-terminate?
-> String -- ^ String to encode
-> IO CStringLen
newEncodedCString (TextEncoding { mkTextEncoder = mk_encoder }) null_terminate s
= bracket mk_encoder close $ \encoder -> withArrayLen s $ \sz p -> do
from <- fmap (\fp -> bufferAdd sz (emptyBuffer fp sz ReadBuffer)) $ newForeignPtr_ p
let go iteration to_p to_sz_bytes = do
putDebugMsg ("newEncodedCString: " ++ show iteration)
mb_res <- tryFillBufferAndCall encoder null_terminate from to_p to_sz_bytes return
case mb_res of
Nothing -> do
let to_sz_bytes' = to_sz_bytes * 2
to_p' <- reallocBytes to_p to_sz_bytes'
go (iteration + 1) to_p' to_sz_bytes'
Just res -> return res
-- If the input string is ASCII, this value will ensure we only allocate once
let to_sz_bytes = cCharSize * (sz + 1)
to_p <- mallocBytes to_sz_bytes
go (0 :: Int) to_p to_sz_bytes
tryFillBufferAndCall :: TextEncoder dstate -> Bool -> Buffer Char -> Ptr Word8 -> Int
-> (CStringLen -> IO a) -> IO (Maybe a)
tryFillBufferAndCall encoder null_terminate from0 to_p to_sz_bytes act = do
to_fp <- newForeignPtr_ to_p
go (0 :: Int) (from0, emptyBuffer to_fp to_sz_bytes WriteBuffer)
where
go iteration (from, to) = do
(why, from', to') <- encode encoder from to
putDebugMsg ("tryFillBufferAndCall: " ++ show iteration ++ " " ++ show why ++ " " ++ summaryBuffer from ++ " " ++ summaryBuffer from')
if isEmptyBuffer from'
then if null_terminate && bufferAvailable to' == 0
then return Nothing -- We had enough for the string but not the terminator: ask the caller for more buffer
else do
-- Awesome, we had enough buffer
let bytes = bufferElems to'
withBuffer to' $ \to_ptr -> do
when null_terminate $ pokeElemOff to_ptr (bufR to') 0
fmap Just $ act (castPtr to_ptr, bytes) -- NB: the length information is specified as being in *bytes*
else case why of -- We didn't consume all of the input
InputUnderflow -> recover encoder from' to' >>= go (iteration + 1) -- These conditions are equally bad
InvalidSequence -> recover encoder from' to' >>= go (iteration + 1) -- since the input was truncated/invalid
OutputUnderflow -> return Nothing -- Oops, out of buffer during decoding: ask the caller for more
| alexander-at-github/eta | libraries/base/GHC/Foreign.hs | bsd-3-clause | 10,266 | 0 | 25 | 2,614 | 2,019 | 1,053 | 966 | 134 | 5 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Control.Search.MemoReader where
import Control.Search.Memo
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monatron.Monatron hiding (Abort, L, state, cont)
import Control.Monatron.Zipper hiding (i,r)
import Control.Monatron.MonadInfo
import Control.Monatron.IdT
newtype MemoReaderT r m a = MemoReaderT { unMemoReaderT :: Int -> ReaderT r m a }
instance MonadT (MemoReaderT r) where
lift m = MemoReaderT $ const $ lift m
tbind (MemoReaderT i) f = MemoReaderT (\n -> i n `tbind` (\r -> unMemoReaderT (f r) n))
instance MonadInfoT (MemoReaderT r) where
tminfo x = miInc "MemoReaderT" (minfo $ runReaderT undefined (unMemoReaderT x 0))
instance FMonadT (MemoReaderT s) where
tmap' d1 d2 g f (MemoReaderT m) = MemoReaderT (tmap' d1 d2 g f . m)
memoReaderT :: MemoM m => (e -> Int -> m a) -> MemoReaderT e m a
memoReaderT f = MemoReaderT (\n -> readerT (\e -> f e n))
deMemoReaderT :: MemoM m => e -> Int -> MemoReaderT e m a -> m a
deMemoReaderT e i (MemoReaderT f) = runReaderT e (f i)
runMemoReaderT :: (MemoM m, Show s) => s -> MemoReaderT s m a -> m a
runMemoReaderT s r =
do x1 <- getMemo
let l = Map.size (memoRead x1)
setMemo x1 { memoRead = Map.insert l (show s) $ memoRead x1 }
r <- deMemoReaderT s l r
x2 <- getMemo
setMemo x2 { memoRead = Map.delete l $ memoRead x2 }
return r
modelMemoReaderT :: (Show s, MemoM m) => Model (ReaderOp s) (MemoReaderT s m)
modelMemoReaderT (Ask g) = memoReaderT (\s n -> deMemoReaderT s n (g s))
modelMemoReaderT (InEnv s a) = memoReaderT (\_ n -> deMemoReaderT s n (do { m1 <- getMemo
; let oldVal = memoRead m1 Map.! n
; setMemo m1 { memoRead = Map.insert n (show s) (memoRead m1) }
; x <- a
; m2 <- getMemo
; setMemo m2 { memoRead = Map.insert n oldVal (memoRead m2) }
; return x
}
)
)
instance (MemoM m, Show s) => ReaderM s (MemoReaderT s m) where
readerModel = modelMemoReaderT
| neothemachine/monadiccp | src/Control/Search/MemoReader.hs | bsd-3-clause | 2,684 | 0 | 17 | 1,046 | 870 | 448 | 422 | 44 | 1 |
module C2 where
import D2 hiding (anotherFun)
anotherFun (x:xs) = sq x + anotherFun xs
anotherFun [] = 0
| kmate/HaRe | old/testing/duplication/C2_TokOut.hs | bsd-3-clause | 118 | 0 | 7 | 32 | 48 | 26 | 22 | 4 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Prelude
import qualified Foreign.Storable as Storable
import qualified Control.Monad.State.Strict as S
import Control.Monad.IO.Class
import Foreign.Marshal.Alloc (mallocBytes)
newtype Foo a = Foo a
intSize :: Int
intSize = Storable.sizeOf (undefined :: Int)
-- This 'go' loop should allocate nothing, because it specialises
-- for the shape of the state. But in 8.4 it did (Trac #14936)
slow :: Int -> IO ()
slow i = do let go 0 = pure ()
go j = do Foo (!a, !off) <- S.get
S.put (Foo (a+1, off))
go (j - 1)
S.evalStateT (go i) (Foo ((0::Int),(intSize::Int)))
main = do { slow (10 ^ 7); print "Done" }
| ghcjs/ghcjs | test/ghc/perf/t14936.hs | mit | 822 | 0 | 16 | 215 | 249 | 139 | 110 | 19 | 2 |
{-# LANGUAGE Trustworthy, ExplicitNamespaces #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Kind
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : not portable
--
-- Basic kinds
--
-- @since 4.9.0.0
-----------------------------------------------------------------------------
module Data.Kind ( Type, Constraint, type (*), type (★) ) where
import GHC.Types
| tolysz/prepare-ghcjs | spec-lts8/base/Data/Kind.hs | bsd-3-clause | 539 | 3 | 6 | 79 | 49 | 36 | 13 | 3 | 0 |
module Network.CURL720Spec where
import Network.CURL720
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
----------------------------
describe "curl_version" $ do
it "returns libcurl version string: \"libcurl/7.x.x ...\"" $ do
curl_version >>= (`shouldContain` "libcurl/7.")
| kkardzis/curlhs | test/Network/CURL720Spec.hs | isc | 318 | 0 | 14 | 58 | 78 | 42 | 36 | 10 | 1 |
-- Memcached interface.
-- Copyright (C) 2005 Evan Martin <[email protected]>
module Network.Memcache.Serializable(Serializable, toString, fromString) where
-- It'd be nice to use "show" for serialization, but when we
-- serialize a String we want to serialize it without the quotes.
-- TODO:
-- - allow serializing bytes as Ptr
-- to do this, add a "putToHandle", etc. method in Serializable
-- where the default uses toString, but for Ptr uses socket stuff.
--import Foreign.Marshal.Utils
--import Foreign.Storable (Storable, sizeOf)
class Serializable a where
toString :: a -> String
fromString :: String -> Maybe a
toStringL :: [a] -> String
fromStringL :: String -> [a]
toStringL = error "unimp"
fromStringL = error "unimp"
instance Serializable Char where
-- people will rarely want to serialize a single char,
-- but we define them for completeness.
toString x = [x]
fromString (c:[]) = Just c
fromString _ = Nothing
-- the real use is for serializing strings.
toStringL = id
fromStringL = id
-- ...do I really need to copy everything instance of Show?
instance Serializable Int where
toString = show
fromString = Just . read
instance (Serializable a) => Serializable [a] where
toString = toStringL
fromString = Just . fromStringL
-- vim: set ts=2 sw=2 et :
| alsonkemp/haskell-memcached | Network/Memcache/Serializable.hs | mit | 1,346 | 0 | 9 | 284 | 216 | 125 | 91 | 20 | 0 |
module HoSA.Data.Program.Pretty
(
prettyExpression
, prettyEquation
, prettyProgram
) where
import Data.List (partition, sortBy)
import qualified Data.Map as Map
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import HoSA.Utils (uniqueToInt,(//))
import HoSA.Data.MLTypes
import HoSA.Data.Program.CallSite
import HoSA.Data.Program.Equation
import HoSA.Data.Program.Expression (funs)
import HoSA.Data.Program.Types
----------------------------------------------------------------------
-- Utils
----------------------------------------------------------------------
ppTuple :: (PP.Pretty a, PP.Pretty b) => (a,b) -> PP.Doc
ppTuple (a,b) = PP.tupled [ PP.pretty a, PP.pretty b]
----------------------------------------------------------------------
-- Symbols
----------------------------------------------------------------------
instance PP.Pretty Symbol where
pretty f | defined f = PP.bold (PP.text (symName f))
| otherwise = PP.text (symName f)
instance PP.Pretty Variable where
pretty = PP.text . varName
instance PP.Pretty f => PP.Pretty (CtxSymbol f) where
pretty (CtxSym f u Nothing) | uniqueToInt u == 0 = PP.pretty f
pretty f = PP.pretty (csSymbol f) PP.<> PP.text "@" PP.<> loc where
loc = PP.hcat $ PP.punctuate (PP.text ".") (ppLoc `map` locations f)
ppLoc = PP.int . uniqueToInt
prettyExpression :: Bool -> (f -> PP.Doc) -> (v -> PP.Doc) -> Expression f v tp -> PP.Doc
prettyExpression showLabel ppFun ppVar = pp id where
pp _ (Var v _) = ppVar v
pp _ (Fun f _ l)
| showLabel = ppFun f PP.<> PP.text "@" PP.<> PP.int (uniqueToInt l)
| otherwise = ppFun f
pp _ (Pair _ t1 t2) = ppTuple (pp id t1, pp id t2)
pp par (Apply _ t1 t2) =
par (pp id t1 PP.</> pp PP.parens t2)
pp par (If _ tg tt te) =
par (PP.text "if" PP.<+> pp id tg
// PP.hang 2 (PP.text "then" PP.<+> pp id tt)
// PP.hang 2 (PP.text "else" PP.<+> pp id te))
pp par (LetP _ t1 ((x,_),(y,_)) t2) =
par (PP.align (PP.text "let" PP.<+> ppTuple (ppVar x, ppVar y)
PP.<+> PP.text "=" PP.<+> pp id t1
PP.<$> PP.hang 3 (PP.text "in" PP.<+> pp id t2)))
prettyEquation :: (f -> PP.Doc) -> (v -> PP.Doc) -> Equation f v tp -> PP.Doc
prettyEquation ppFun ppVar eqn = pp False (lhs eqn) PP.<+> PP.text "=" PP.</> ppDist (rhs eqn) where
pp showLabel = prettyExpression showLabel ppFun ppVar
ppDist (Distribution _ [(1,r)]) = pp False r
ppDist (Distribution d ls) =
PP.encloseSep (PP.text "{") (PP.text "}") (PP.text ";")
[ppRatio d p PP.<+> PP.text ":" PP.<+> pp False r | (p,r) <- ls ]
ppRatio d p = PP.int p PP.<> PP.text "/" PP.<> PP.int d
instance (PP.Pretty f, PP.Pretty v) => PP.Pretty (Expression f v tp) where
pretty = prettyExpression True PP.pretty PP.pretty
instance (PP.Pretty f, PP.Pretty v) => PP.Pretty (Equation f v tp) where
pretty = prettyEquation PP.pretty PP.pretty
instance (PP.Pretty f, PP.Pretty v) => PP.Pretty (TypedEquation f v) where
pretty TypedEquation{..} =
PP.group (PP.pretty eqEnv)
PP.<+> PP.text "⊦"
PP.</> PP.group (prettyEquation PP.pretty PP.pretty eqEqn
PP.<+> PP.text ":"
PP.</> PP.pretty eqTpe)
prettyProgram :: (IsSymbol f, Eq f, PP.Pretty f, PP.Pretty v, PP.Pretty d) => Program f v -> Map.Map f d -> PP.Doc
prettyProgram Program{..} sig =
PP.vcat [ ppDecl d tp
PP.<$> PP.vcat (PP.pretty `map` eqs)
PP.<$> PP.empty
| (d,tp) <- sortBy occurrence ds
, let eqs = [eq | eq <- untypedEquations, fst (definedSymbol eq) == d]
, not (null eqs)]
PP.<$> PP.text "where"
PP.<$> PP.indent 2 (PP.vcat [ppDecl c tp | (c,tp) <- cs, c `elem` fs])
-- PP.<$> if null mainFns
-- then PP.empty
-- else PP.text ""
-- PP.<$> (PP.text "main function(s):"
-- // PP.hang 2 (PP.hcat (PP.punctuate (PP.text ",") [PP.pretty f | f <- mainFns])))
where
ppDecl f tp = PP.pretty f PP.<+> PP.text "::" PP.<+> PP.pretty tp
occurrence (d1,_) (d2,_) = walk untypedEquations where
walk [] = EQ
walk (eq:eqs)
| fst (definedSymbol eq) == d1 = GT
| fst (definedSymbol eq) == d2 = LT
| otherwise = walk eqs
untypedEquations = eqEqn `map` equations
fs = concatMap (\ e -> funs (lhs e) ++ concatMap funs (rhss e)) untypedEquations
(ds,cs) = partition (isDefined . fst) (Map.toList sig)
instance (IsSymbol f, Eq f, PP.Pretty f, PP.Pretty v) => PP.Pretty (Program f v) where
pretty p = prettyProgram p (Map.map ren (signature p)) where
ren tp = rename (fvs tp) tp
instance (PP.Pretty f, PP.Pretty v) => PP.Pretty (TypingError f v) where
pretty (IncompatibleType rl t has expected) =
PP.text "Typing error in rule:"
PP.<$> PP.indent 2 (PP.pretty rl)
PP.<$> PP.text "The term" PP.<+> PP.pretty t
PP.<+> PP.text "has type"
PP.<+> PP.squotes (PP.pretty has)
PP.<> PP.text ", but" PP.<+> PP.squotes (PP.pretty expected) PP.<+> PP.text "is expected."
pretty (IllformedConstructorType c tp) =
PP.text "Illformed Constructor type for constructor" PP.<+> PP.squotes (PP.pretty c)
PP.<$> PP.indent 2 (PP.pretty tp)
pretty (LetPInLHS rl) =
PP.text "LetP in lhs encountered:"
PP.<$> PP.indent 2 (PP.pretty rl)
pretty (VariableUndefined rl v) =
PP.text "Variable" PP.<+> PP.squotes (PP.pretty v) PP.<+> PP.text "undefined:"
PP.<$> PP.indent 2 (PP.pretty rl)
pretty (ConstructorMissingSignature f) =
PP.text "The constructor" PP.<+> PP.squotes (PP.pretty f) PP.<+> PP.text "misses a type declaration."
| mzini/hosa | src/HoSA/Data/Program/Pretty.hs | mit | 5,750 | 0 | 18 | 1,389 | 2,384 | 1,195 | 1,189 | -1 | -1 |
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.Sugar.TypeClasses
-- Copyright : (c) Phil Freeman 2013
-- License : MIT
--
-- Maintainer : Phil Freeman <[email protected]>
-- Stability : experimental
-- Portability :
--
-- |
-- This module implements the desugaring pass which creates type synonyms for type class dictionaries
-- and dictionary expressions for type class instances.
--
-----------------------------------------------------------------------------
module Language.PureScript.Sugar.TypeClasses (
desugarTypeClasses
) where
import Language.PureScript.Declarations
import Language.PureScript.Names
import Language.PureScript.Types
import Language.PureScript.Sugar.CaseDeclarations
import Language.PureScript.Environment
import Language.PureScript.Errors
import Language.PureScript.Supply
import Language.PureScript.Pretty.Types (prettyPrintTypeAtom)
import qualified Language.PureScript.Constants as C
import Control.Applicative
import Control.Monad.Error
import Control.Monad.State
import Control.Arrow (first, second)
import Data.List ((\\))
import Data.Monoid ((<>))
import Data.Maybe (catMaybes, mapMaybe)
import qualified Data.Map as M
type MemberMap = M.Map (ModuleName, ProperName) Declaration
type Desugar = StateT MemberMap (SupplyT (Either ErrorStack))
-- |
-- Add type synonym declarations for type class dictionary types, and value declarations for type class
-- instance dictionary expressions.
--
desugarTypeClasses :: [Module] -> SupplyT (Either ErrorStack) [Module]
desugarTypeClasses = flip evalStateT M.empty . mapM desugarModule
desugarModule :: Module -> Desugar Module
desugarModule (Module name decls (Just exps)) = do
(newExpss, declss) <- unzip <$> mapM (desugarDecl name) decls
return $ Module name (concat declss) $ Just (exps ++ catMaybes newExpss)
desugarModule _ = error "Exports should have been elaborated in name desugaring"
{- Desugar type class and type class instance declarations
--
-- Type classes become type synonyms for their dictionaries, and type instances become dictionary declarations.
-- Additional values are generated to access individual members of a dictionary, with the appropriate type.
--
-- E.g. the following
--
-- module Test where
--
-- class Foo a where
-- foo :: a -> a
--
-- instance fooString :: Foo String where
-- foo s = s ++ s
--
-- instance fooArray :: (Foo a) => Foo [a] where
-- foo = map foo
--
-- {- Superclasses -}
--
-- class (Foo a) <= Sub a where
-- sub :: a
--
-- instance subString :: Sub String where
-- sub = ""
--
-- becomes
--
-- type Foo a = { foo :: a -> a }
--
-- foreign import foo "function foo(dict) {\
-- \ return dict.foo;\
-- \}" :: forall a. (Foo a) => a -> a
--
-- fooString :: {} -> Foo String
-- fooString _ = { foo: \s -> s ++ s }
--
-- fooArray :: forall a. (Foo a) => Foo [a]
-- fooArray = { foo: map foo }
--
-- {- Superclasses -}
--
-- ...
--
-- subString :: {} -> { __superclasses :: { "Foo": {} -> Foo String }, sub :: String }
-- subString _ = {
-- __superclasses: {
-- "Foo": \_ -> <dictionary placeholder to be inserted during type checking\>
-- }
-- sub: ""
-- }
-}
desugarDecl :: ModuleName -> Declaration -> Desugar (Maybe DeclarationRef, [Declaration])
desugarDecl mn d@(TypeClassDeclaration name args implies members) = do
modify (M.insert (mn, name) d)
return $ (Nothing, d : typeClassDictionaryDeclaration name args implies members : map (typeClassMemberToDictionaryAccessor mn name args) members)
desugarDecl mn d@(TypeInstanceDeclaration name deps className ty members) = do
desugared <- lift $ desugarCases members
dictDecl <- typeInstanceDictionaryDeclaration name mn deps className ty desugared
return $ (Just $ TypeInstanceRef name, [d, dictDecl])
desugarDecl mn (PositionedDeclaration pos d) = do
(dr, ds) <- rethrowWithPosition pos $ desugarDecl mn d
return (dr, map (PositionedDeclaration pos) ds)
desugarDecl _ other = return (Nothing, [other])
memberToNameAndType :: Declaration -> (Ident, Type)
memberToNameAndType (TypeDeclaration ident ty) = (ident, ty)
memberToNameAndType (PositionedDeclaration _ d) = memberToNameAndType d
memberToNameAndType _ = error "Invalid declaration in type class definition"
identToProperty :: Ident -> String
identToProperty (Ident name) = name
identToProperty (Op op) = op
typeClassDictionaryDeclaration :: ProperName -> [String] -> [(Qualified ProperName, [Type])] -> [Declaration] -> Declaration
typeClassDictionaryDeclaration name args implies members =
let superclassesType = TypeApp tyObject (rowFromList ([ (fieldName, function unit tySynApp)
| (index, (superclass, tyArgs)) <- zip [0..] implies
, let tySynApp = foldl TypeApp (TypeConstructor superclass) tyArgs
, let fieldName = mkSuperclassDictionaryName superclass index
], REmpty))
in TypeSynonymDeclaration name args (TypeApp tyObject $ rowFromList ((C.__superclasses, superclassesType) : map (first identToProperty . memberToNameAndType) members, REmpty))
typeClassMemberToDictionaryAccessor :: ModuleName -> ProperName -> [String] -> Declaration -> Declaration
typeClassMemberToDictionaryAccessor mn name args (TypeDeclaration ident ty) =
ValueDeclaration ident TypeClassAccessorImport [] Nothing $
TypedValue False (Abs (Left $ Ident "dict") (Accessor (runIdent ident) (Var $ Qualified Nothing (Ident "dict")))) $
moveQuantifiersToFront (quantify (ConstrainedType [(Qualified (Just mn) name, map TypeVar args)] ty))
typeClassMemberToDictionaryAccessor mn name args (PositionedDeclaration pos d) =
PositionedDeclaration pos $ typeClassMemberToDictionaryAccessor mn name args d
typeClassMemberToDictionaryAccessor _ _ _ _ = error "Invalid declaration in type class definition"
mkSuperclassDictionaryName :: Qualified ProperName -> Integer -> String
mkSuperclassDictionaryName pn index = show pn ++ "_" ++ show index
unit :: Type
unit = TypeApp tyObject REmpty
typeInstanceDictionaryDeclaration :: Ident -> ModuleName -> [(Qualified ProperName, [Type])] -> Qualified ProperName -> [Type] -> [Declaration] -> Desugar Declaration
typeInstanceDictionaryDeclaration name mn deps className tys decls =
rethrow (strMsg ("Error in type class instance " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys) ++ ":") <>) $ do
m <- get
-- Lookup the type arguments and member types for the type class
(TypeClassDeclaration _ args implies tyDecls) <- lift . lift $
maybe (Left $ mkErrorStack ("Type class " ++ show className ++ " is undefined") Nothing) Right $
M.lookup (qualify mn className) m
case mapMaybe declName tyDecls \\ mapMaybe declName decls of
x : _ -> throwError $ mkErrorStack ("Member '" ++ show x ++ "' has not been implemented") Nothing
[] -> do
let instanceTys = map memberToNameAndType tyDecls
-- Replace the type arguments with the appropriate types in the member types
let memberTypes = map (second (replaceAllTypeVars (zip args tys))) instanceTys
-- Create values for the type instance members
memberNames <- map (first identToProperty) <$> mapM (memberToNameAndValue memberTypes) decls
-- Create the type of the dictionary
-- The type is an object type, but depending on type instance dependencies, may be constrained.
-- The dictionary itself is an object literal, but for reasons related to recursion, the dictionary
-- must be guarded by at least one function abstraction. For that reason, if the dictionary has no
-- dependencies, we introduce an unnamed function parameter.
let superclasses = ObjectLiteral
[ (fieldName, Abs (Left (Ident "_")) (SuperClassDictionary superclass tyArgs))
| (index, (superclass, suTyArgs)) <- zip [0..] implies
, let tyArgs = map (replaceAllTypeVars (zip args tys)) suTyArgs
, let fieldName = mkSuperclassDictionaryName superclass index
]
let memberNames' = (C.__superclasses, superclasses) : memberNames
dictTy = foldl TypeApp (TypeConstructor className) tys
constrainedTy = quantify (if null deps then function unit dictTy else ConstrainedType deps dictTy)
dict = if null deps then Abs (Left (Ident "_")) (ObjectLiteral memberNames') else ObjectLiteral memberNames'
return $ ValueDeclaration name TypeInstanceDictionaryValue [] Nothing (TypedValue True dict constrainedTy)
where
declName :: Declaration -> Maybe Ident
declName (PositionedDeclaration _ d) = declName d
declName (ValueDeclaration ident _ _ _ _) = Just ident
declName (TypeDeclaration ident _) = Just ident
declName _ = Nothing
memberToNameAndValue :: [(Ident, Type)] -> Declaration -> Desugar (Ident, Value)
memberToNameAndValue tys' d@(ValueDeclaration ident _ _ _ _) = do
_ <- lift . lift . maybe (Left $ mkErrorStack ("Type class does not define member '" ++ show ident ++ "'") Nothing) Right $ lookup ident tys'
let memberValue = typeInstanceDictionaryEntryValue d
return (ident, memberValue)
memberToNameAndValue tys' (PositionedDeclaration pos d) = rethrowWithPosition pos $ do
(ident, val) <- memberToNameAndValue tys' d
return (ident, PositionedValue pos val)
memberToNameAndValue _ _ = error "Invalid declaration in type instance definition"
typeInstanceDictionaryEntryValue :: Declaration -> Value
typeInstanceDictionaryEntryValue (ValueDeclaration _ _ [] _ val) = val
typeInstanceDictionaryEntryValue (PositionedDeclaration pos d) = PositionedValue pos (typeInstanceDictionaryEntryValue d)
typeInstanceDictionaryEntryValue _ = error "Invalid declaration in type instance definition"
| bergmark/purescript | src/Language/PureScript/Sugar/TypeClasses.hs | mit | 9,982 | 3 | 20 | 1,960 | 2,227 | 1,157 | 1,070 | 108 | 11 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Hydraulic where
import Control.Lens
import Control.Lens.TH
import Control.Monad.Cont
import Control.Monad.Trans
import Control.Monad.RWS.Strict
import Data.ByteString (ByteString)
import Data.HashMap.Strict (HashMap)
import Data.Monoid (mempty)
import Data.Text (Text)
import Data.Time (UTCTime)
import Data.Void
import Pipes
import Network.HTTP.Types
import Network.HTTP.Types.Status
import Network.Wai
data ResourceState c = ResourceState
{ _resourceConfig :: c
, _resourceRequest :: Request
-- , _halt :: Response -> ContT Response IO () -- IO Response -> ContT Response IO Response
}
type ResourceHandler c = RWST Request () (ResourceState c) (ContT Response IO)
type HaltFlag c = ResourceHandler c Bool
data AuthResult
= Authorized
| Unauthorized
| Authenticate ByteString
class Haltable h r | h -> r where
checkHalt :: Status -> h -> Either Response r
data HaltStatus a
= Success a
| Error Text
| Halt Response
instance Haltable (HaltStatus a) a where
checkHalt s h = case h of
Success x -> Right x
Error issue -> Left undefined
Halt resp -> Left resp
instance Haltable Bool Bool where
checkHalt s h = if h
then Left undefined
else Right h
data Resource c a = Resource
{ _rResourceExists :: HaltFlag c
, _rIsServiceAvailable :: HaltFlag c
, _rIsAuthRequired :: HaltFlag c
, _rIsAuthorized :: ResourceHandler c (HaltStatus AuthResult)
, _rIsForbidden :: HaltFlag c
, _rAllowMissingPost :: HaltFlag c
, _rIsMalformedRequest :: HaltFlag c
, _rIsUriTooLong :: HaltFlag c
, _rIsKnownContentType :: HaltFlag c
, _rAreContentHeadersValid :: HaltFlag c
, _rIsEntityLengthValid :: HaltFlag c
, _rOptions :: ResourceHandler c [Header]
, _rAllowedMethods :: ResourceHandler c [Method]
, _rKnownMethods :: ResourceHandler c [Method]
, _rIsDeletionSuccessful :: HaltFlag c
, _rIsDeletionCompleted :: HaltFlag c
, _rPostIsCreate :: ResourceHandler c Bool
, _rCreatePath :: ResourceHandler c ByteString
, _rProcessPost :: HaltFlag c
, _rContentTypesProvided :: ResourceHandler c (HashMap ByteString (a -> ByteString))
, _rContentTypesAccepted :: ResourceHandler c (HashMap ByteString (ByteString -> Either Text a))
, _rCharsetsProvided :: ResourceHandler c (HashMap ByteString (ByteString -> ByteString))
, _rEncodingsProvided :: ResourceHandler c (HashMap ByteString (ByteString -> ByteString))
, _rVariances :: ResourceHandler c [Header]
, _rIsConflict :: ResourceHandler c Bool
, _rHasMultipleChoices :: HaltFlag c
, _rPreviouslyExisted :: HaltFlag c
, _rMovedPermanently :: ResourceHandler c (HaltStatus (Maybe ByteString))
, _rMovedTemporarily :: ResourceHandler c (HaltStatus (Maybe ByteString))
, _rLastModified :: ResourceHandler c (Maybe UTCTime)
, _rExpires :: ResourceHandler c (Maybe UTCTime)
, _rGenerateETag :: ResourceHandler c (Maybe ByteString)
, _rFinishRequest :: ResourceHandler c Bool
}
makeFieldsWith defaultFieldRules ''Resource
defaultResource :: Resource c a
defaultResource = Resource
{ _rIsServiceAvailable = return True
, _rResourceExists = return True
, _rIsAuthRequired = return True
, _rIsAuthorized = return $ Success Authorized
, _rIsForbidden = return False
, _rAllowMissingPost = return False
, _rIsMalformedRequest = return False
, _rIsUriTooLong = return False
-- known_content_type: true
-- valid_content_headers: true
, _rIsEntityLengthValid = return True
, _rOptions = return []
, _rAllowedMethods = return [methodGet, methodHead]
, _rKnownMethods = return [methodGet, methodHead, methodPost, methodPut, methodDelete, methodPatch, methodTrace, methodConnect, methodOptions]
, _rContentTypesProvided = return mempty
, _rContentTypesAccepted = return mempty
}
checkEarlyTerminators :: Haltable h r => (Status -> h -> ResourceHandler c r) -> ResourceHandler c ()
checkEarlyTerminators onHalt = do
rsrc <- ask
-- B13: Available?
onHalt serviceUnavailable503 =<< rsrc ^. isServiceAvailable
-- B12: Known method?
req <- fmap _resourceRequest get
onHalt notImplemented501 =<< fmap (elem $ requestMethod req) (rsrc ^. knownMethods)
-- B11: URI too long?
onHalt requestURITooLong414 =<< rsrc ^. isUriTooLong
-- B10: Is method allowed?
req <- fmap _resourceRequest get
onHalt methodNotAllowed405 =<< fmap (elem $ requestMethod req) (rsrc ^. allowedMethods)
-- B9: Malformed?
onHalt badRequest400 =<< rsrc ^. isMalformedRequest
-- B8: Authorized?
onHalt unauthorized401 =<< rsrc ^. isAuthorized
-- B7: Forbidden?
onHalt forbidden403 =<< rsrc ^. isForbidden
-- B6: Unknown or unsupported content header?
-- TODO: supported content header?
-- B5: Unknown Content-Type?
onHalt unsupportedMediaType415 =<< fmap not (rsrc ^. isKnownContentType)
-- B4: Request entity too large?
onHalt requestEntityTooLarge413 =<< fmap not (rsrc ^. isEntityLengthValid)
-- B3: OPTIONS?
-- TODO: options
return ()
checkAcceptHeaders :: Haltable h r => (Status -> h -> ResourceHandler c r) -> ResourceHandler c ()
checkAcceptHeaders onHalt = do
let unacceptable = onHalt notAcceptable406
-- C3: Accept exists?
-- TODO: acceptExists
-- True => C4: Acceptable media type available?
-- False =>
-- D4: Accept language exists?
-- True => D5: Acceptable language available?
-- False =>
-- D5
-- E5
-- E6
-- F6
-- F7
return ()
runHydraulic :: c -> Resource c a -> Request -> IO Response
runHydraulic c rsrc req = (flip runContT) return $ callCC $ \halt -> do
(r, ()) <- (flip evalRWST) req (ResourceState c req) $ do
let
onHalt :: Haltable h r => Status -> h -> ResourceHandler c r
onHalt s h = case checkHalt s h of
-- since halt exits the computation, we can restrict its type to `Response -> ResourceHandler c Void`
-- and then use vacuousM to work around monomorphism restrictions for its return type
Left resp -> vacuousM $ lift $ halt resp
Right x -> return x
checkEarlyTerminators onHalt
checkAcceptHeaders onHalt
return undefined
return r
| SaneApp/hydraulic | src/Hydraulic.hs | mit | 6,256 | 2 | 20 | 1,177 | 1,583 | 840 | 743 | 127 | 2 |
-- Credit card issuer checking
-- http://www.codewars.com/kata/5701e43f86306a615c001868
module Haskell.Codewars.CreditCardIssuer where
import Data.List (isPrefixOf)
getIssuer :: Int -> String
getIssuer n | length s == 16 && (any (`isPrefixOf` s) . map show $ [51..55]) = "Mastercard"
| length s == 15 && any (`isPrefixOf` s) ["34", "37"] = "AMEX"
| elem (length s) [13, 16] && isPrefixOf "4" s = "VISA"
| length s == 16 && isPrefixOf "6011" s = "Discover"
| otherwise = "Unknown"
where s = show n | gafiatulin/codewars | src/7 kyu/CreditCardIssuer.hs | mit | 558 | 0 | 13 | 142 | 197 | 102 | 95 | 9 | 1 |
-- | Instructions for the 8080 CPU
module Hask8080.Instructions where
import Control.Lens
import Hask8080.CPU (CPU, cycles, reg, reg16, regMem, nextByte, nextAddr)
import Hask8080.Types (Reg (..), Reg16 (..))
tick :: Int -> CPU ()
tick n = cycles += n
-- | MOV dest src
mov :: Reg -> Reg -> CPU ()
mov M r = tick 7 >> regMem HL <~ use (reg r)
mov r M = tick 7 >> reg r <~ use (regMem HL)
mov r1 r2 = tick 5 >> reg r1 <~ use (reg r2)
lxi :: Reg16 -> CPU ()
lxi rp = tick 10 >> reg16 rp <~ nextAddr
stax :: Reg16 -> CPU ()
stax rp = tick 7 >> regMem rp <~ use (reg A)
inr :: Reg -> CPU ()
inr M = tick 10 >> regMem HL += 1
inr r = tick 5 >> reg r += 1
inx :: Reg16 -> CPU ()
inx rp = tick 5 >> reg16 rp += 1
dcr :: Reg -> CPU ()
dcr M = tick 10 >> regMem HL -= 1
dcr r = tick 5 >> reg r -= 1
dcx :: Reg16 -> CPU ()
dcx rp = tick 5 >> reg16 rp += 1
mvi :: Reg -> CPU ()
mvi M = tick 10 >> regMem HL <~ nextByte
mvi r = tick 7 >> reg r <~ nextByte
ldax :: Reg16 -> CPU ()
ldax rp = tick 7 >> reg A <~ use (regMem rp)
nop :: CPU ()
nop = return ()
hlt :: CPU ()
hlt = error "halt"
dad :: Reg16 -> CPU ()
dad rp = do tick 10
a <- use (reg16 rp)
reg16 HL += a
add r = error "fatal: add not yet implemented"
adc r = error "fatal: adc not yet implemented"
sub r = error "fatal: sub not yet implemented"
sbb r = error "fatal: sbb not yet implemented"
ana r = error "fatal: ana not yet implemented"
xra r = error "fatal: xra not yet implemented"
ora r = error "fatal: ora not yet implemented"
cmp r = error "fatal: cmp not yet implemented"
rlc = error "fatal: rlc not yet implemented"
rrc = error "fatal: rcc not yet implemented"
ral = error "fatal: ral not yet implemented"
rar = error "fatal: rar not yet implemented"
push rp = error "fatal: push not yet implemented"
pop rp = error "fatal: pop not yet implemented"
xchg = error "fatal: xchg not yet implemented"
xthl = error "fatal: xthl not yet implemented"
adi = error "fatal: adi not yet implemented"
aci = error "fatal: aci not yet implemented"
sui = error "fatal: sui not yet implemented"
sbi = error "fatal: sbi not yet implemented"
ani = error "fatal: ani not yet implemented"
xri = error "fatal: xri not yet implemented"
ori = error "fatal: ori not yet implemented"
cpi = error "fatal: cpi not yet implemented"
sta = error "fatal: sta not yet implemented"
lda = error "fatal: lda not yet implemented"
shld = error "fatal: shld not yet implemented"
lhld = error "fatal: lhld not yet implemented"
pchl = error "fatal: pchl not yet implemented"
jnz = error "fatal: jnz not yet implemented"
jmp = error "fatal: jmp not yet implemented"
jz = error "fatal: jz not yet implemented"
jnc = error "fatal: jnc not yet implemented"
jc = error "fatal: jc not yet implemented"
jpo = error "fatal: jpo not yet implemented"
jpe = error "fatal: jpe not yet implemented"
jp = error "fatal: jp not yet implemented"
jm = error "fatal: jm not yet implemented"
cnz = error "fatal: cnz not yet implemented"
call = error "fatal: cmp not yet implemented"
cz = error "fatal: cz not yet implemented"
cnc = error "fatal: cnc not yet implemented"
cc = error "fatal: cc not yet implemented"
cpo = error "fatal: cpo not yet implemented"
cpe = error "fatal: cpe not yet implemented"
cp = error "fatal: cp not yet implemented"
cm = error "fatal: cm not yet implemented"
rnz = error "fatal: rnz not yet implemented"
ret = error "fatal: rmp not yet implemented"
rz = error "fatal: rz not yet implemented"
rnc = error "fatal: rnc not yet implemented"
rc = error "fatal: rc not yet implemented"
rpo = error "fatal: rpo not yet implemented"
rpe = error "fatal: rpe not yet implemented"
rp = error "fatal: rp not yet implemented"
rm = error "fatal: rm not yet implemented"
rst _ = error "fatal: rst not yet implemented"
ei = error "fatal: ei not yet implemented"
di = error "fatal: di not yet implemented"
in' = error "fatal: in' not yet implemented"
out = error "fatal: out not yet implemented"
| reinh/Hask8080 | src/Hask8080/Instructions.hs | mit | 4,695 | 0 | 10 | 1,577 | 1,190 | 580 | 610 | 98 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.TypeChecker
-- Copyright : (c) 2013-15 Phil Freeman, (c) 2014-15 Gary Burgess
-- License : MIT (http://opensource.org/licenses/MIT)
--
-- Maintainer : Phil Freeman <[email protected]>
-- Stability : experimental
-- Portability :
--
-- |
-- The top-level type checker, which checks all declarations in a module.
--
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module Language.PureScript.TypeChecker (
module T,
typeCheckModule
) where
import Prelude ()
import Prelude.Compat
import Language.PureScript.TypeChecker.Monad as T
import Language.PureScript.TypeChecker.Kinds as T
import Language.PureScript.TypeChecker.Types as T
import Language.PureScript.TypeChecker.Synonyms as T
import Data.Maybe
import Data.List (nub, (\\), sort, group)
import Data.Foldable (for_, traverse_)
import qualified Data.Map as M
import Control.Monad (when, unless, void, forM, forM_)
import Control.Monad.State.Class (MonadState(..), modify)
import Control.Monad.Error.Class (MonadError(..))
import Control.Monad.Writer.Class (MonadWriter(..))
import Language.PureScript.Crash
import Language.PureScript.Types
import Language.PureScript.Names
import Language.PureScript.Kinds
import Language.PureScript.AST
import Language.PureScript.TypeClassDictionaries
import Language.PureScript.Environment
import Language.PureScript.Errors
addDataType ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
DataDeclType ->
ProperName ->
[(String, Maybe Kind)] ->
[(ProperName, [Type])] ->
Kind ->
m ()
addDataType moduleName dtype name args dctors ctorKind = do
env <- getEnv
putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (ctorKind, DataType args dctors) (types env) }
for_ dctors $ \(dctor, tys) ->
warnAndRethrow (addHint (ErrorInDataConstructor dctor)) $
addDataConstructor moduleName dtype name (map fst args) dctor tys
addDataConstructor ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
DataDeclType ->
ProperName ->
[String] ->
ProperName ->
[Type] ->
m ()
addDataConstructor moduleName dtype name args dctor tys = do
env <- getEnv
traverse_ checkTypeSynonyms tys
let retTy = foldl TypeApp (TypeConstructor (Qualified (Just moduleName) name)) (map TypeVar args)
let dctorTy = foldr function retTy tys
let polyType = mkForAll args dctorTy
let fields = [Ident ("value" ++ show n) | n <- [0..(length tys - 1)]]
putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (dtype, name, polyType, fields) (dataConstructors env) }
addTypeSynonym ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
ProperName ->
[(String, Maybe Kind)] ->
Type ->
Kind ->
m ()
addTypeSynonym moduleName name args ty kind = do
env <- getEnv
checkTypeSynonyms ty
putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
, typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
valueIsNotDefined ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
Ident ->
m ()
valueIsNotDefined moduleName name = do
env <- getEnv
case M.lookup (moduleName, name) (names env) of
Just _ -> throwError . errorMessage $ RedefinedIdent name
Nothing -> return ()
addValue ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
Ident ->
Type ->
NameKind ->
m ()
addValue moduleName name ty nameKind = do
env <- getEnv
putEnv (env { names = M.insert (moduleName, name) (ty, nameKind, Defined) (names env) })
addTypeClass ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
ProperName ->
[(String, Maybe Kind)] ->
[Constraint] ->
[Declaration] ->
m ()
addTypeClass moduleName pn args implies ds =
let members = map toPair ds in
modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members, implies) (typeClasses . checkEnv $ st) } }
where
toPair (TypeDeclaration ident ty) = (ident, ty)
toPair (PositionedDeclaration _ _ d) = toPair d
toPair _ = internalError "Invalid declaration in TypeClassDeclaration"
addTypeClassDictionaries ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
Maybe ModuleName ->
M.Map (Qualified ProperName) (M.Map (Qualified Ident) TypeClassDictionaryInScope) ->
m ()
addTypeClassDictionaries mn entries =
modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = insertState st } }
where insertState st = M.insertWith (M.unionWith M.union) mn entries (typeClassDictionaries . checkEnv $ st)
checkDuplicateTypeArguments ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
[String] ->
m ()
checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
throwError . errorMessage $ DuplicateTypeArgument dup
where
firstDup :: Maybe String
firstDup = listToMaybe $ args \\ nub args
checkTypeClassInstance ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
Type ->
m ()
checkTypeClassInstance _ (TypeVar _) = return ()
checkTypeClassInstance _ (TypeConstructor ctor) = do
env <- getEnv
when (ctor `M.member` typeSynonyms env) . throwError . errorMessage $ TypeSynonymInstance
return ()
checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
checkTypeClassInstance _ ty = throwError . errorMessage $ InvalidInstanceHead ty
-- |
-- Check that type synonyms are fully-applied in a type
--
checkTypeSynonyms ::
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
Type ->
m ()
checkTypeSynonyms = void . replaceAllTypeSynonyms
-- |
-- Type check all declarations in a module
--
-- At this point, many declarations will have been desugared, but it is still necessary to
--
-- * Kind-check all types and add them to the @Environment@
--
-- * Type-check all values and add them to the @Environment@
--
-- * Bring type class instances into scope
--
-- * Process module imports
--
typeCheckAll :: forall m.
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
ModuleName ->
[DeclarationRef] ->
[Declaration] ->
m [Declaration]
typeCheckAll moduleName _ ds = traverse go ds <* traverse_ checkOrphanFixities ds
where
go :: Declaration -> m Declaration
go (DataDeclaration dtype name args dctors) = do
warnAndRethrow (addHint (ErrorInTypeConstructor name)) $ do
when (dtype == Newtype) $ checkNewtype dctors
checkDuplicateTypeArguments $ map fst args
ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
let args' = args `withKinds` ctorKind
addDataType moduleName dtype name args' dctors ctorKind
return $ DataDeclaration dtype name args dctors
where
checkNewtype :: [(ProperName, [Type])] -> m ()
checkNewtype [(_, [_])] = return ()
checkNewtype [(_, _)] = throwError . errorMessage $ InvalidNewtype name
checkNewtype _ = throwError . errorMessage $ InvalidNewtype name
go (d@(DataBindingGroupDeclaration tys)) = do
warnAndRethrow (addHint ErrorInDataBindingGroup) $ do
let syns = mapMaybe toTypeSynonym tys
let dataDecls = mapMaybe toDataDecl tys
(syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(_, name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
for_ (zip dataDecls data_ks) $ \((dtype, name, args, dctors), ctorKind) -> do
checkDuplicateTypeArguments $ map fst args
let args' = args `withKinds` ctorKind
addDataType moduleName dtype name args' dctors ctorKind
for_ (zip syns syn_ks) $ \((name, args, ty), kind) -> do
checkDuplicateTypeArguments $ map fst args
let args' = args `withKinds` kind
addTypeSynonym moduleName name args' ty kind
return d
where
toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
toTypeSynonym (PositionedDeclaration _ _ d') = toTypeSynonym d'
toTypeSynonym _ = Nothing
toDataDecl (DataDeclaration dtype nm args dctors) = Just (dtype, nm, args, dctors)
toDataDecl (PositionedDeclaration _ _ d') = toDataDecl d'
toDataDecl _ = Nothing
go (TypeSynonymDeclaration name args ty) = do
warnAndRethrow (addHint (ErrorInTypeSynonym name)) $ do
checkDuplicateTypeArguments $ map fst args
kind <- kindsOf False moduleName name args [ty]
let args' = args `withKinds` kind
addTypeSynonym moduleName name args' ty kind
return $ TypeSynonymDeclaration name args ty
go (TypeDeclaration{}) = internalError "Type declarations should have been removed"
go (ValueDeclaration name nameKind [] (Right val)) =
warnAndRethrow (addHint (ErrorInValueDeclaration name)) $ do
valueIsNotDefined moduleName name
[(_, (val', ty))] <- typesOf moduleName [(name, val)]
addValue moduleName name ty nameKind
return $ ValueDeclaration name nameKind [] $ Right val'
go (ValueDeclaration{}) = internalError "Binders were not desugared"
go (BindingGroupDeclaration vals) =
warnAndRethrow (addHint (ErrorInBindingGroup (map (\(ident, _, _) -> ident) vals))) $ do
for_ (map (\(ident, _, _) -> ident) vals) $ \name ->
valueIsNotDefined moduleName name
tys <- typesOf moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
vals' <- forM [ (name, val, nameKind, ty)
| (name, nameKind, _) <- vals
, (name', (val, ty)) <- tys
, name == name'
] $ \(name, val, nameKind, ty) -> do
addValue moduleName name ty nameKind
return (name, nameKind, val)
return $ BindingGroupDeclaration vals'
go (d@(ExternDataDeclaration name kind)) = do
env <- getEnv
putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
return d
go (d@(ExternDeclaration name ty)) = do
warnAndRethrow (addHint (ErrorInForeignImport name)) $ do
env <- getEnv
kind <- kindOf ty
guardWith (errorMessage (ExpectedType ty kind)) $ kind == Star
case M.lookup (moduleName, name) (names env) of
Just _ -> throwError . errorMessage $ RedefinedIdent name
Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, External, Defined) (names env) })
return d
go (d@(FixityDeclaration{})) = return d
go (d@(ImportDeclaration{})) = return d
go (d@(TypeClassDeclaration pn args implies tys)) = do
addTypeClass moduleName pn args implies tys
return d
go (d@(TypeInstanceDeclaration dictName deps className tys body)) = rethrow (addHint (ErrorInInstance className tys)) $ do
traverse_ (checkTypeClassInstance moduleName) tys
forM_ deps $ traverse_ (checkTypeClassInstance moduleName) . snd
checkOrphanInstance dictName className tys
_ <- traverseTypeInstanceBody checkInstanceMembers body
let dict = TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) [] className tys (Just deps)
addTypeClassDictionaries (Just moduleName) . M.singleton className $ M.singleton (tcdName dict) dict
return d
go (PositionedDeclaration pos com d) =
warnAndRethrowWithPosition pos $ PositionedDeclaration pos com <$> go d
checkOrphanFixities :: Declaration -> m ()
checkOrphanFixities (FixityDeclaration _ name) = do
env <- getEnv
guardWith (errorMessage (OrphanFixityDeclaration name)) $ M.member (moduleName, Op name) $ names env
checkOrphanFixities (PositionedDeclaration pos _ d) =
warnAndRethrowWithPosition pos $ checkOrphanFixities d
checkOrphanFixities _ = return ()
checkInstanceMembers :: [Declaration] -> m [Declaration]
checkInstanceMembers instDecls = do
let idents = sort . map head . group . map memberName $ instDecls
for_ (firstDuplicate idents) $ \ident ->
throwError . errorMessage $ DuplicateValueDeclaration ident
return instDecls
where
memberName :: Declaration -> Ident
memberName (ValueDeclaration ident _ _ _) = ident
memberName (PositionedDeclaration _ _ d) = memberName d
memberName _ = internalError "checkInstanceMembers: Invalid declaration in type instance definition"
firstDuplicate :: (Eq a) => [a] -> Maybe a
firstDuplicate (x : xs@(y : _))
| x == y = Just x
| otherwise = firstDuplicate xs
firstDuplicate _ = Nothing
checkOrphanInstance :: Ident -> Qualified ProperName -> [Type] -> m ()
checkOrphanInstance dictName className@(Qualified (Just mn') _) tys'
| moduleName == mn' || any checkType tys' = return ()
| otherwise = throwError . errorMessage $ OrphanInstance dictName className tys'
where
checkType :: Type -> Bool
checkType (TypeVar _) = False
checkType (TypeConstructor (Qualified (Just mn'') _)) = moduleName == mn''
checkType (TypeConstructor (Qualified Nothing _)) = internalError "Unqualified type name in checkOrphanInstance"
checkType (TypeApp t1 _) = checkType t1
checkType _ = internalError "Invalid type in instance in checkOrphanInstance"
checkOrphanInstance _ _ _ = internalError "Unqualified class name in checkOrphanInstance"
-- |
-- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
-- extracted from the kind of the type constructor itself.
--
withKinds :: [(String, Maybe Kind)] -> Kind -> [(String, Maybe Kind)]
withKinds [] _ = []
withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
withKinds _ _ = internalError "Invalid arguments to peelKinds"
-- |
-- Type check an entire module and ensure all types and classes defined within the module that are
-- required by exported members are also exported.
--
typeCheckModule :: forall m.
(Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
Module ->
m Module
typeCheckModule (Module _ _ _ _ Nothing) = internalError "exports should have been elaborated"
typeCheckModule (Module ss coms mn decls (Just exps)) = warnAndRethrow (addHint (ErrorInModule mn)) $ do
modify (\s -> s { checkCurrentModule = Just mn })
decls' <- typeCheckAll mn exps decls
for_ exps $ \e -> do
checkTypesAreExported e
checkClassMembersAreExported e
checkClassesAreExported e
return $ Module ss coms mn decls' (Just exps)
where
checkMemberExport :: (Type -> [DeclarationRef]) -> DeclarationRef -> m ()
checkMemberExport extract dr@(TypeRef name dctors) = do
env <- getEnv
case M.lookup (Qualified (Just mn) name) (typeSynonyms env) of
Nothing -> return ()
Just (_, ty) -> checkExport dr extract ty
case dctors of
Nothing -> return ()
Just dctors' -> for_ dctors' $ \dctor ->
case M.lookup (Qualified (Just mn) dctor) (dataConstructors env) of
Nothing -> return ()
Just (_, _, ty, _) -> checkExport dr extract ty
return ()
checkMemberExport extract dr@(ValueRef name) = do
ty <- lookupVariable mn (Qualified (Just mn) name)
checkExport dr extract ty
checkMemberExport _ _ = return ()
checkExport :: DeclarationRef -> (Type -> [DeclarationRef]) -> Type -> m ()
checkExport dr extract ty = case filter (not . exported) (extract ty) of
[] -> return ()
hidden -> throwError . errorMessage $ TransitiveExportError dr hidden
where
exported e = any (exports e) exps
exports (TypeRef pn1 _) (TypeRef pn2 _) = pn1 == pn2
exports (ValueRef id1) (ValueRef id2) = id1 == id2
exports (TypeClassRef pn1) (TypeClassRef pn2) = pn1 == pn2
exports (PositionedDeclarationRef _ _ r1) r2 = exports r1 r2
exports r1 (PositionedDeclarationRef _ _ r2) = exports r1 r2
exports _ _ = False
-- Check that all the type constructors defined in the current module that appear in member types
-- have also been exported from the module
checkTypesAreExported :: DeclarationRef -> m ()
checkTypesAreExported = checkMemberExport findTcons
where
findTcons :: Type -> [DeclarationRef]
findTcons = everythingOnTypes (++) go
where
go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [TypeRef name (internalError "Data constructors unused in checkTypesAreExported")]
go _ = []
-- Check that all the classes defined in the current module that appear in member types have also
-- been exported from the module
checkClassesAreExported :: DeclarationRef -> m ()
checkClassesAreExported = checkMemberExport findClasses
where
findClasses :: Type -> [DeclarationRef]
findClasses = everythingOnTypes (++) go
where
go (ConstrainedType cs _) = mapMaybe (fmap TypeClassRef . extractCurrentModuleClass . fst) cs
go _ = []
extractCurrentModuleClass :: Qualified ProperName -> Maybe ProperName
extractCurrentModuleClass (Qualified (Just mn') name) | mn == mn' = Just name
extractCurrentModuleClass _ = Nothing
checkClassMembersAreExported :: DeclarationRef -> m ()
checkClassMembersAreExported dr@(TypeClassRef name) = do
let members = ValueRef `map` head (mapMaybe findClassMembers decls)
let missingMembers = members \\ exps
unless (null missingMembers) $ throwError . errorMessage $ TransitiveExportError dr members
where
findClassMembers :: Declaration -> Maybe [Ident]
findClassMembers (TypeClassDeclaration name' _ _ ds) | name == name' = Just $ map extractMemberName ds
findClassMembers (PositionedDeclaration _ _ d) = findClassMembers d
findClassMembers _ = Nothing
extractMemberName :: Declaration -> Ident
extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
extractMemberName (TypeDeclaration memberName _) = memberName
extractMemberName _ = internalError "Unexpected declaration in typeclass member list"
checkClassMembersAreExported _ = return ()
| michaelficarra/purescript | src/Language/PureScript/TypeChecker.hs | mit | 18,866 | 16 | 21 | 3,750 | 6,045 | 3,088 | 2,957 | 344 | 34 |
{-# htermination (sequence_Nil :: (List (List a)) -> (List Tup0)) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup0 = Tup0 ;
foldr :: (b -> a -> a) -> a -> (List b) -> a;
foldr f z Nil = z;
foldr f z (Cons x xs) = f x (foldr f z xs);
gtGt0 q vv = q;
psPs :: (List a) -> (List a) -> (List a);
psPs Nil ys = ys;
psPs (Cons x xs) ys = Cons x (psPs xs ys);
gtGtEsNil :: (List b) -> (b -> (List c)) -> (List c)
gtGtEsNil (Cons x xs) f = psPs (f x) (gtGtEsNil xs f);
gtGtEsNil Nil f = Nil;
gtGtNil :: (List b) -> (List c) -> (List c)
gtGtNil p q = gtGtEsNil p (gtGt0 q);
returnNil :: b -> List b
returnNil x = Cons x Nil;
sequence_Nil :: (List (List b)) -> (List Tup0)
sequence_Nil = foldr gtGtNil (returnNil Tup0);
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/sequence__2.hs | mit | 808 | 0 | 10 | 214 | 425 | 224 | 201 | 20 | 1 |
import Data.List
import Data.Monoid
import Options.Applicative
data Opts = Opts
{ _files :: [String]
, _quiet :: Bool
, _fast :: Speed
}
data Speed = Slow | Fast
options :: Parser Opts
options = Opts <$> filename <*> quiet <*> fast
where
filename :: Parser [String]
filename = many $ argument str $
metavar "filename..."
<> help "Input files"
fast :: Parser Speed
fast = flag Slow Fast $
long "cheetah"
<> help "Perform task quickly."
quiet :: Parser Bool
quiet = switch $
long "quiet"
<> help "Whether to shut up."
greet :: Opts -> IO ()
greet (Opts files quiet fast) = do
putStrLn "reading these files:"
mapM_ print files
case fast of
Fast -> putStrLn "quickly"
Slow -> putStrLn "slowly"
case quiet of
True -> putStrLn "quietly"
False -> putStrLn "loudly"
opts :: ParserInfo Opts
opts = info (helper <*> options) fullDesc
main :: IO ()
main = execParser opts >>= greet
| riwsky/wiwinwlh | src/optparse_applicative.hs | mit | 985 | 6 | 10 | 270 | 326 | 161 | 165 | 36 | 3 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.PositionCallback (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.PositionCallback
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.PositionCallback
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/PositionCallback.hs | mit | 361 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
biggestInt, smallestInt :: Int
biggestInt = maxBound
smallestInt = minBound
sumtorial :: Integer -> Integer
sumtorial 0 = 0
sumtorial n = n + sumtorial (n-1)
hailstone :: Integer -> Integer
hailstone n
| n `mod` 2 == 0 = n `div` 2
| otherwise = 3*n + 1
foo :: Integer -> Integer
foo 0 = 16
foo 1
| "Haskell" > "C++" = 3
| otherwise = 4
foo n
| n < 0 = 0
| n `mod` 17 == 2 = -43
| otherwise = n + 3
isEven :: Integer -> Bool
isEven n
| n `mod` 2 == 0 = True
| otherwise = False
p :: (Int, Char)
p = (3, 'x')
sumPair :: (Int,Int) -> Int
sumPair (x, y) = x + y
f :: Int -> Int -> Int -> Int
f x y z = x + y + z
ex17 = f 3 17 8 :: Int
nums, range, range2, range3, range20, range7 :: [Integer]
nums = [1,2,3,19]
range = [1..100]
range2 = [2,6..100]
range3 = [3,8..20]
range20 = [20, 19..1]
range7 = [7,9..100]
hello1 :: [Char]
hello1 = ['h','e','l','l','o']
hello2 :: String
hello2 = "hello"
helloSame = hello1 == hello2
hailstoneSeq :: Integer -> [Integer]
hailstoneSeq 1 = [1]
hailstoneSeq n = n : hailstoneSeq (hailstone n)
intListLength :: [Integer] -> Integer
intListLength [] = 0
intListLength (x:xs) = 1 + intListLength xs
sumEveryTwo :: [Integer] -> [Integer]
sumEveryTwo [] = []
sumEveryTwo (x:[]) = [x]
sumEveryTwo (x:(y:zs)) = (x + y) : sumEveryTwo zs
hailstoneLen :: Integer -> Integer
hailstoneLen n = intListLength (hailstoneSeq n) -1
| mauriciofierrom/cis194-homework | homework01/int.hs | mit | 1,435 | 8 | 9 | 360 | 718 | 390 | 328 | 54 | 1 |
module Data.UTC.Class.IsDate.Test where
import Test.QuickCheck
import Test.Framework (testGroup)
import Test.Framework (Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Data.UTC
test :: Test
test
= testGroup "Data.UTC.Class.IsDate"
$ [ testGroup "addYears"
[ testProperty "addYears 1 '2000-02-28'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 2 >>= setDay 28 >>= addYears 1
in conjoin
[ (year `fmap` d) === Just 2001
, (month `fmap` d) === Just 2
, (day `fmap` d) === Just 28
]
, testProperty "addYears 1 '2000-02-29'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 2 >>= setDay 29 >>= addYears 1
in conjoin
[ (year `fmap` d) === Just 2001
, (month `fmap` d) === Just 2
, (day `fmap` d) === Just 28
]
, testProperty "addYears 4 '2000-02-29'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 2 >>= setDay 29 >>= addYears 4
in conjoin
[ (year `fmap` d) === Just 2004
, (month `fmap` d) === Just 2
, (day `fmap` d) === Just 29
]
, testProperty "addYears (-4) '2000-02-29'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 2 >>= setDay 29 >>= addYears (-4)
in conjoin
[ (year `fmap` d) === Just 1996
, (month `fmap` d) === Just 2
, (day `fmap` d) === Just 29
]
]
, testGroup "addMonths"
[ testProperty "addMonths 1 '2000-01-31'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 1 >>= setDay 31 >>= addMonths 1
in conjoin
[ (year `fmap` d) === Just 2000
, (month `fmap` d) === Just 2
, (day `fmap` d) === Just 29
]
, testProperty "addMonths 2 '2000-01-31'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 1 >>= setDay 31 >>= addMonths 2
in conjoin
[ (year `fmap` d) === Just 2000
, (month `fmap` d) === Just 3
, (day `fmap` d) === Just 31
]
, testProperty "addMonths 3 '2000-01-31'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 1 >>= setDay 31 >>= addMonths 3
in conjoin
[ (year `fmap` d) === Just 2000
, (month `fmap` d) === Just 4
, (day `fmap` d) === Just 30
]
, testProperty "addMonths 1 '2001-01-31'"
$ let d = setYear 2001 (epoch :: Date) >>= setMonth 1 >>= setDay 31 >>= addMonths 1
in conjoin
[ (year `fmap` d) === Just 2001
, (month `fmap` d) === Just 2
, (day `fmap` d) === Just 28
]
, testProperty "addMonths (-47) '2000-01-31'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 1 >>= setDay 31 >>= addMonths (-47)
in conjoin
[ (year `fmap` d) === Just 1996
, (month `fmap` d) === Just 2
, (day `fmap` d) === Just 29
]
]
, testGroup "addDays"
[ testProperty "addDays 366 '2000-01-01'"
$ let d = setYear 2000 (epoch :: Date) >>= setMonth 1 >>= setDay 1 >>= addDays 366
in conjoin
[ (year `fmap` d) === Just 2001
, (month `fmap` d) === Just 1
, (day `fmap` d) === Just 1
]
]
]
| lpeterse/haskell-utc | Data/UTC/Class/IsDate/Test.hs | mit | 3,436 | 0 | 18 | 1,305 | 1,232 | 650 | 582 | 72 | 1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.SpeechSynthesisEvent
(getCharIndex, getElapsedTime, getName, SpeechSynthesisEvent(..),
gTypeSpeechSynthesisEvent)
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/SpeechSynthesisEvent.charIndex Mozilla SpeechSynthesisEvent.charIndex documentation>
getCharIndex :: (MonadDOM m) => SpeechSynthesisEvent -> m Word
getCharIndex self
= liftDOM (round <$> ((self ^. js "charIndex") >>= valToNumber))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisEvent.elapsedTime Mozilla SpeechSynthesisEvent.elapsedTime documentation>
getElapsedTime :: (MonadDOM m) => SpeechSynthesisEvent -> m Float
getElapsedTime self
= liftDOM
(realToFrac <$> ((self ^. js "elapsedTime") >>= valToNumber))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisEvent.name Mozilla SpeechSynthesisEvent.name documentation>
getName ::
(MonadDOM m, FromJSString result) =>
SpeechSynthesisEvent -> m result
getName self = liftDOM ((self ^. js "name") >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/SpeechSynthesisEvent.hs | mit | 1,980 | 0 | 12 | 241 | 471 | 291 | 180 | 30 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Flag.Debugger (Debugger(..)) where
import Data.Data (Data)
data Debugger = UNSET | SET | ALL deriving (Show, Eq, Read, Ord, Bounded, Data)
| xnuk/another-aheui-interpreter | src/Flag/Debugger.hs | mit | 184 | 0 | 6 | 28 | 66 | 39 | 27 | 4 | 0 |
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
module PISA where
import Data.List (intercalate)
import Control.Arrow
import AST (TypeName, MethodName)
type Label = String
newtype Register = Reg Integer
deriving (Eq)
{-- Generic PISA Definitions --}
data GInstr i = ADD Register Register
| ADDI Register i
| ANDX Register Register Register
| ANDIX Register Register i
| NORX Register Register Register
| NEG Register
| ORX Register Register Register
| ORIX Register Register i
| RL Register i
| RLV Register Register
| RR Register i
| RRV Register Register
| SLLX Register Register i
| SLLVX Register Register Register
| SRAX Register Register i
| SRAVX Register Register Register
| SRLX Register Register i
| SRLVX Register Register Register
| SUB Register Register
| XOR Register Register
| XORI Register i
| BEQ Register Register Label
| BGEZ Register Label
| BGTZ Register Label
| BLEZ Register Label
| BLTZ Register Label
| BNE Register Register Label
| BRA Label
| EXCH Register Register
| SWAPBR Register
| RBRA Label
| START
| FINISH
| DATA i
| SUBI Register i --Pseudo
deriving (Eq)
newtype GProg i = GProg [(Maybe Label, GInstr i)]
{-- Macro PISA Definitions --}
data Macro = Immediate Integer
| AddressMacro Label
| SizeMacro TypeName
| OffsetMacro TypeName MethodName
| ProgramSize
| FreeListsSize
| StackOffset
| InitialMemoryBlockSize
| ReferenceCounterIndex
| ArrayElementOffset
deriving (Show, Eq)
type MInstruction = GInstr Macro
type MProgram = GProg Macro
invertInstructions :: [(Maybe Label, MInstruction)] -> [(Maybe Label, MInstruction)]
invertInstructions = reverse . map (second invertInstruction . first (fmap (++ "_i")))
where invertInstruction (ADD r1 r2) = SUB r1 r2
invertInstruction (SUB r1 r2) = ADD r1 r2
invertInstruction (ADDI r i) = SUBI r i
invertInstruction (SUBI r i) = ADDI r i
invertInstruction (RL r i) = RR r i
invertInstruction (RLV r1 r2) = RRV r1 r2
invertInstruction (RR r i) = RL r i
invertInstruction (RRV r1 r2) = RLV r1 r2
invertInstruction (BEQ r1 r2 l) = BEQ r1 r2 $ l ++ "_i"
invertInstruction (BGEZ r l) = BGEZ r $ l ++ "_i"
invertInstruction (BGTZ r l) = BGTZ r $ l ++ "_i"
invertInstruction (BLEZ r l) = BLEZ r $ l ++ "_i"
invertInstruction (BLTZ r l) = BLTZ r $ l ++ "_i"
invertInstruction (BNE r1 r2 l) = BNE r1 r2 $ l ++ "_i"
invertInstruction (BRA l) = BRA $ l ++ "_i"
invertInstruction (RBRA l) = RBRA $ l ++ "_i"
invertInstruction inst = inst
{-- Output PISA Definitions --}
type Instruction = GInstr Integer
type Program = GProg Integer
instance Show Register where
show (Reg r) = "$" ++ show r
instance Show Instruction where
show (ADD r1 r2) = unwords ["ADD ", show r1, show r2]
show (ADDI r i) = unwords ["ADDI ", show r, show i]
show (ANDX r1 r2 r3) = unwords ["ANDX ", show r1, show r2, show r3]
show (ANDIX r1 r2 i) = unwords ["ANDIX ", show r1, show r2, show i]
show (NORX r1 r2 r3) = unwords ["NORX ", show r1, show r2, show r3]
show (NEG r) = unwords ["NEG ", show r]
show (ORX r1 r2 r3) = unwords ["ORX ", show r1, show r2, show r3]
show (ORIX r1 r2 i) = unwords ["ORIX ", show r1, show r2, show i]
show (RL r i) = unwords ["RL ", show r, show i]
show (RLV r1 r2) = unwords ["RLV ", show r1, show r2]
show (RR r i) = unwords ["RR ", show r, show i]
show (RRV r1 r2) = unwords ["RRV ", show r1, show r2]
show (SLLX r1 r2 i) = unwords ["SLLX ", show r1, show r2, show i]
show (SLLVX r1 r2 r3) = unwords ["SLLVX ", show r1, show r2, show r3]
show (SRAX r1 r2 i) = unwords ["SRAX ", show r1, show r2, show i]
show (SRAVX r1 r2 r3) = unwords ["SRAVX ", show r1, show r2, show r3]
show (SRLX r1 r2 i) = unwords ["SRLX ", show r1, show r2, show i]
show (SRLVX r1 r2 r3) = unwords ["SRLVX ", show r1, show r2, show r3]
show (SUB r1 r2) = unwords ["SUB ", show r1, show r2]
show (XOR r1 r2) = unwords ["XOR ", show r1, show r2]
show (XORI r i) = unwords ["XORI ", show r, show i]
show (BEQ r1 r2 l) = unwords ["BEQ ", show r1, show r2, l]
show (BGEZ r l) = unwords ["BGEZ ", show r, l]
show (BGTZ r l) = unwords ["BGTZ ", show r, l]
show (BLEZ r l) = unwords ["BLEZ ", show r, l]
show (BLTZ r l) = unwords ["BLTZ ", show r, l]
show (BNE r1 r2 l) = unwords ["BNE ", show r1, show r2, l]
show (BRA l) = unwords ["BRA ", l]
show (EXCH r1 r2) = unwords ["EXCH ", show r1, show r2]
show (SWAPBR r) = unwords ["SWAPBR", show r]
show (RBRA l) = unwords ["RBRA ", l]
show START = "START "
show FINISH = "FINISH"
show (DATA i) = unwords ["DATA ", show i]
show (SUBI r i) = unwords ["ADDI ", show r, show $ -i] --Expand pseudo
showProgram :: Program -> String
showProgram (GProg p) = ";; pendulum pal file\n" ++ intercalate "\n" (map showLine p)
where showLine (Nothing, i) = spaces 25 ++ show i
showLine (Just l, i) = l ++ ":" ++ spaces (24 - length l) ++ show i
spaces :: (Int -> String)
spaces n = [1..n] >> " "
writeProgram :: String -> Program -> IO ()
writeProgram output p = writeFile output $ showProgram p | cservenka/ROOPLPPC | src/PISA.hs | mit | 5,866 | 0 | 12 | 1,932 | 2,293 | 1,184 | 1,109 | 125 | 17 |
-- File : musicmind.hs
-- Author : Hengfeng Li
-- Purpose : a MusicMind game
module Musicmind
(initialGuess,
nextGuess,
GameState
) where
import qualified Data.Set as Set
import Data.List
-- The GameState maintain the list of possible answers
-- in which each element is a Set type.
type GameState = [Set.Set [Char]]
-- Generate all 1330 possible answers in the first stage
-- by using the List Conprehension to select three element
-- from a collection of all pitches.
allChord :: GameState
allChord = Set.toList $ Set.fromList [ Set.fromList [a,b,c] |
a <- allPitches,
b <- [x | x <- allPitches, x /= a],
c <- [x | x <- allPitches, x /= a, x /= b]]
where allPitches = [ x:[y] | x <- "ABCDEFG", y <- "123"]
-- Generate a list which select one element from each patterns.
firstGroups :: [Set.Set String]
firstGroups = map snd $ nubBy (\x y -> (fst x) == (fst y)) allTuples
where allTuples = map getPattern allChord
-- Compute the pattern to reduce the 1330 possible answers
-- when deciding the first guess. As we known, there are
-- 6 patterns at the first stage.
getPattern :: Set.Set String -> ([Int], Set.Set String)
getPattern x = (map (length . nub) $ transpose $ Set.toList x, x)
-- Compute the first guess which one will lead to the
-- maximum number of possible answers leaving.
firstGuess :: GameState -> ([String],Int)
firstGuess gs
= foldr (\x acc ->
let num = maxSameOutput $ sameOutputs (Set.toList x) (delete x allChord)
in
if num < snd acc then ((Set.toList x),num) else acc
) ([""],length allChord) gs
-- Initialize the first guess and game state.
initialGuess :: ([String], GameState)
initialGuess = (guess, initialGameState)
where guess = fst $ firstGuess firstGroups
initialGameState = delete (Set.fromList guess) allChord
-- Delete all the inconsistent possible answers in game state.
delInconsistent :: ([String],GameState)->(Int,Int,Int) -> GameState
delInconsistent (prev, gamestate) answer
= filter (\x -> response prev (Set.toList x) == answer) gamestate
-- Generate the next guess according to the previous guess, game state
-- and answer.
nextGuess :: ([String],GameState)->(Int,Int,Int)->([String],GameState)
nextGuess (a, xs) answer = (x, zs)
where ys = delInconsistent (a,xs) answer
x = fst $ maxLeavingGuess ys
zs = delete (Set.fromList x) ys
-- Get the guess that the maximum number of
-- possible answers will leave.
maxLeavingGuess :: GameState -> ([String],Int)
maxLeavingGuess gs
| length gs == 1 = (Set.toList $ head gs, 0)
| otherwise = foldr (\x acc ->
let num = maxSameOutput $ sameOutputs (Set.toList x) (delete x gs)
in
if num < snd acc then ((Set.toList x),num) else acc
) ([""],length allChord) gs
-- Get the maximum number of the same outputs.
maxSameOutput :: [Int] -> Int
maxSameOutput = foldr (\x acc -> if x > acc then x else acc) 0
-- Compute the number of possible answers which has
-- the same output answer in the specific guess.
sameOutputs :: [String] -> GameState -> [Int]
sameOutputs guess gs = map length $ group $ sort $ map (response guess . Set.toList) gs
-- Compute the answer between target and guess.
response :: [String] -> [String] -> (Int,Int,Int)
response target guess = (mPitches,mNotes,mOctave)
where targetSet = Set.fromList target
guessSet = Set.fromList guess
intersection = Set.intersection targetSet guessSet
mPitches = Set.size intersection
diffTarget = Set.difference targetSet intersection
diffGuess = Set.difference guessSet intersection
targetNotes = nub $ map head $ Set.toList diffTarget
guessNotes = nub $ map head $ Set.toList diffGuess
mNotes = foldr (\x acc ->
if elem x guessNotes
then acc + 1 else acc) 0 targetNotes
targetOctaves = sort $ map tail $ Set.toList diffTarget
guessOctaves = sort $ map tail $ Set.toList diffGuess
mOctave = computeOctaves targetOctaves guessOctaves
-- Compute how many octaves are same.
computeOctaves :: [String] -> [String] -> Int
computeOctaves _ [] = 0
computeOctaves [] _ = 0
computeOctaves (x:xs) ys
| elem x ys = 1 + computeOctaves xs (delete x ys)
| otherwise = computeOctaves xs ys
| HengfengLi/Declarative-Programming | proj1/Musicmind.hs | mit | 4,423 | 0 | 17 | 1,073 | 1,320 | 715 | 605 | 69 | 2 |
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
module Hanoi.Semantik where
-- $Id$
import Hanoi.Type
import Hanoi.Move
import Hanoi.Restriction
import Condition
import Autolib.FiniteMap
import Autolib.Reporter
import Autolib.ToDoc
import qualified Challenger as C
import Inter.Types
import Data.Typeable
data Hanoi = Hanoi deriving ( Eq, Ord, Show, Read, Typeable )
instance OrderScore Hanoi where
scoringOrder _ = Increasing
instance C.Partial Hanoi HI [ Zug ] where
describe p i =
vcat [ text "Türme von Hanoi. Finden Sie eine Zugfolge von"
, nest 4 $ toDoc ( start i )
, text "nach"
, nest 4 $ toDoc ( ziel i )
, explain $ restriction i
]
initial p i = [ (A, B) ]
total p i b = do
hof <- moves ( restriction i ) ( start i ) b
inform $ vcat [ text "Sie erreichen diese Situation:"
, nest 4 $ toDoc hof
]
assert ( hof == ziel i ) $ text "Aufgabe gelöst?"
return ()
make :: Make
make = direct Hanoi $
let ts = take 3 [ A .. ]
leer = listToFM $ do t <- ts ; return ( t, [] )
ss = [ 1 .. 5 ]
in HI { start = addToFM leer A ss
, ziel = addToFM leer B ss
, restriction = Neighbours
}
| Erdwolf/autotool-bonn | src/Hanoi/Semantik.hs | gpl-2.0 | 1,276 | 9 | 15 | 381 | 431 | 225 | 206 | 37 | 1 |
module FormalLanguage.GrammarProduct.Op.Common where
import qualified Data.Set as S
import Control.Lens hiding (outside)
import Data.Set (Set)
import FormalLanguage.CFG.Grammar
import ADPfusion.Core.Term.Epsilon (LocalGlobal(..))
-- | Collect all terminal symbols from a set of rules.
--
-- TODO move to FormalGrammars library
--
-- TODO i guess, this collects multidim stuff for now!!!
collectTerminals :: S.Set Rule -> S.Set Symbol
collectTerminals = error "collectTerminals" -- S.fromList . filter isSymbT . concatMap _rhs . S.toList
-- | Collect all non-terminal symbols from a set of rules.
--
-- TODO move to FormalGrammars library
collectNonTerminals :: Set Rule -> Set Symbol -- S.Set Rule -> S.Set Symb
collectNonTerminals = error "collectNonTerminals" -- S.fromList . _ . view (folded.rhs) -- S.fromList . filter isSymbN . concatMap (\r -> r^.lhs : r^.rhs) . S.toList
-- |
--
-- TODO not needed anymore ?!
collectEpsilons :: S.Set Rule -> S.Set SynTermEps -- TN
collectEpsilons = error "collectEpsilons"
{-
collectEpsilons = S.fromList
. filter (\case E -> True ; z -> False)
. concatMap (view symb)
. concatMap _rhs
. S.toList
-}
-- | Generate a multidim epsilon symbol of the same length as the given
-- symbol.
genEps :: Symbol -> Symbol -- Symb -> [TN]
genEps s = Symbol $ replicate (length $ s^.getSymbolList) $ Epsilon Global -- replicate (length $ s^.symb) E
-- | Generate a multidim @Deletion@ symbol of the same length as the given
-- symbol.
genDel :: Symbol -> Symbol -- Symb -> [TN]
genDel s = Symbol $ replicate (length $ s^.getSymbolList) Deletion -- replicate (length $ s^.symb) E
-- | Checks if two grammars are compatible.
--
-- TODO different inside/outside status might not be a big problem! years
-- later: let's see if that holds true!
opCompatible :: Grammar -> Grammar -> Either String ()
opCompatible l r
| dim l /= dim r = Left "Grammars have different dimensions"
-- | l^.outside /= r^.outside = Left "Grammars have incompatible inside/outside status"
| otherwise = Right ()
| choener/GrammarProducts | FormalLanguage/GrammarProduct/Op/Common.hs | gpl-3.0 | 2,126 | 0 | 10 | 441 | 307 | 174 | 133 | 20 | 1 |
{- |
Module : Postmaster.Main
Copyright : (c) 2004-2008 by Peter Simons
License : GPL2
Maintainer : [email protected]
Stability : provisional
Portability : Haskell 2-pre
Postmaster's IO driver and general initialization functions.
-}
module Postmaster.Main where
import Prelude hiding ( catch )
import Data.Maybe
import Control.Concurrent.MVar
import Control.Monad.RWS hiding ( local )
import Control.Monad.State
import System.IO
import System.Posix.Signals
import Network ( PortID(..) )
import Network.Socket
import Network.BSD ( getHostName )
import ADNS
import Foreign
import Postmaster.Base
import Postmaster.FSM
import Postmaster.FSM.DNSResolver ( setDNSResolver )
import Postmaster.FSM.EventHandler ( setEventHandler )
import Postmaster.FSM.PeerAddr ( setPeerAddr )
import Postmaster.FSM.SessionState ( setSessionState )
import Postmaster.IO
import Text.ParserCombinators.Parsec.Rfc2821
import System.Posix.Syslog
-- * Speaking ESMTP
-- |This function ties it all together to build a
-- 'BlockHandler' for "System.IO.Driver".
smtpdHandler :: WriteHandle -> GlobalEnv -> BlockHandler SmtpdState
smtpdHandler hOut theEnv buf = runSmtpd (smtpd buf >>= handler) theEnv
where
handler :: ([SmtpReply], Buffer) -> Smtpd Buffer
handler (rs, buf') = do
safeWrite (hPutStr hOut (concatMap show rs) >> hFlush hOut)
when (any isShutdown rs) (fail "shutdown")
return buf'
-- |The unified interface to dialog and data section. This
-- function relies on the fact that pipelining ends with
-- @DATA@ commands: dialog and payload must /not/ come in a
-- single buffer. See
-- <http://www.faqs.org/rfcs/rfc2920.html> section 3.1.
smtpd :: Buffer -> Smtpd ([SmtpReply], Buffer)
smtpd buf@(Buf _ _ 0) = return ([], buf)
smtpd buf@(Buf _ ptr n) = do
sst <- getSessionState
if (sst == HaveData)
then do (r, buf') <- feed buf
return (maybeToList r, buf')
else do xs <- liftIO (peekArray (fromIntegral n) ptr)
let xs' = map (toEnum . fromEnum) xs
ls' = splitList "\r\n" xs'
ls = reverse . tail $ reverse ls'
rest = head $ reverse ls'
i = length xs - length rest
rs <- mapM handleDialog ls
buf' <- liftIO $ flush (fromIntegral i) buf
return (rs, buf')
handleDialog :: String -> Smtpd SmtpReply
handleDialog line = do
sst <- getSessionState
let (e, sst') = runState (smtpdFSM (fixCRLF line)) sst
r <- trigger e
case (e, isSuccess r) of
(_, True) -> setSessionState sst'
(StartData, False) -> trigger ResetState >> setSessionState HaveHelo
_ -> return ()
return r
-- * Running 'Smtpd' Computations
-- |Run the given 'Smtpd' computation and write the logging
-- output via the given 'Logger'. Use 'withGlobalEnv' to
-- create the global environment and 'emptyEnv' to
-- initialize the 'SmtpdState'.
runSmtpd' :: Logger -> Smtpd a -> GlobalEnv -> SmtpdState
-> IO (a, SmtpdState)
runSmtpd' logger f = runStateT . withLogger logger f
-- |Convenience wrapper for 'runSmtpd'' with 'Logger'
-- hard-coded to 'syslogger'.
runSmtpd :: Smtpd a -> GlobalEnv -> SmtpdState
-> IO (a, SmtpdState)
runSmtpd = runSmtpd' syslogger
-- |Run the given computation with an initialized global
-- environment for 'Smtpd'. The environment is destroyed
-- when this function returns.
withGlobalEnv :: HostName -- ^ 'myHeloName'
-> Resolver
-> EventT
-> (GlobalEnv -> IO a)
-> IO a
withGlobalEnv myHelo dns eventT f = do
let eventH = eventT (mkEvent myHelo "/tmp/test-spool")
initEnv = do setDNSResolver dns
setEventHandler eventH
newMVar (execState initEnv emptyEnv) >>= f
-- * ESMTP Network Daemon
smtpdServer :: Capacity -> GlobalEnv -> SocketHandler
smtpdServer cap theEnv =
handleLazy ReadWriteMode $ \(h, Just sa) -> do
hSetBuffering h (BlockBuffering (Just (fromIntegral cap)))
let st = execState (setPeerAddr sa) emptyEnv
smtpdMain cap theEnv h h st >> return ()
smtpdMain :: Capacity
-> GlobalEnv
-> ReadHandle
-> WriteHandle
-> SmtpdState
-> IO SmtpdState
smtpdMain cap theEnv hIn hOut initST = do
let greet = do r <- trigger Greeting
safeReply hOut r >> safeFlush hOut
to <- getReadTimeout
sid <- mySessionID
return (r, to, sid)
((r, to, sid), st) <- runSmtpd greet theEnv initST
st' <- case r of
Reply (Code Success _ _) _ -> do
let getTO = evalState (getVarDef (mkVar "ReadTimeout") to)
yellIO = syslogger . LogMsg sid st
hMain = smtpdHandler hOut theEnv
errH e st' = yellIO (CaughtException e) >> return st'
runLoopNB getTO errH hIn cap hMain st
_ -> return st
let bye = do sst <- getSessionState
when (sst /= HaveQuit)
(trigger Shutdown >> return ())
fmap snd (runSmtpd bye theEnv st')
main' :: Capacity -> PortID -> EventT -> IO ()
main' cap port eventT = do
_ <- installHandler sigPIPE Ignore Nothing
_ <- installHandler sigCHLD (Catch (return ())) Nothing
whoami <- getHostName
withSocketsDo $
withSyslog "postmaster" [PID, PERROR] MAIL $
initResolver [NoErrPrint,NoServerWarn] $ \dns ->
withGlobalEnv whoami dns eventT $
listener port . smtpdServer cap
main :: IO ()
main = main' 1024 (PortNumber 2525) id
-- ** Logging
type Logger = LogMsg -> IO ()
-- |Bind the logging back-end to demote 'Smtpd' to an
-- ordinary 'StateT' computation.
withLogger :: Logger -> Smtpd a -> GlobalEnv -> StateT SmtpdState IO a
withLogger logger f theEnv = do
(a, st, w) <- get >>= liftIO . runRWST f theEnv
liftIO $ mapM_ logger w
put st
return a
-- |Our default logging back-end.
syslogger :: Logger
syslogger (LogMsg sid _ e) = syslog Info $
showString "SID " . shows sid . (':':) . (' ':) $ show e
| richardfontana/postmaster | Postmaster/Main.hs | gpl-3.0 | 6,056 | 0 | 20 | 1,553 | 1,718 | 869 | 849 | 124 | 3 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Exception
import System.Environment
import Data.List
import Args
import Formats
import Utils
import DeriveDispatcher
import Run.Test
import Run.Gen
import Run.Exec
import Run.Shrink
import Run.List
import Run.Serve
import Test.QuickFuzz.Global
-- |Print unsupported file format error message
unsupported :: String -> IO ()
unsupported fmt = do
qf <- getProgName
error $ "file format '" ++ fmt ++ "' is not supported.\n" ++
"See '" ++ qf ++ " list' to print the available formats."
-- |Template Haskell dispatcher derivations
devDispatcher 'Test 'runTest
devDispatcher 'Gen 'runGen
devDispatcher 'Exec 'runExec
devDispatcher 'Shrink 'runShrink
devDispatcher 'Serve 'runServe
-- |Subcommands dispatcher
quickfuzz :: QFCommand -> IO ()
quickfuzz cmd@(Test {}) = dispatchTest cmd
quickfuzz cmd@(Gen {}) = dispatchGen cmd
quickfuzz cmd@(Exec {}) = dispatchExec cmd
quickfuzz cmd@(Shrink {}) = dispatchShrink cmd
quickfuzz cmd@(Serve {}) = dispatchServe cmd
quickfuzz List = runList
-- |Pretty print error messages
printException :: SomeException -> IO ()
printException e = do
restoreTerm
qf <- getProgName
putStrLn $ qf ++ ": " ++ show e
main :: IO ()
main = handle printException $ do
initFreqs
command <- parseCommand
cleanTerm
runApp command (\cmd -> sanitize cmd >>= quickfuzz)
restoreTerm
| elopez/QuickFuzz | app/Main.hs | gpl-3.0 | 1,430 | 0 | 12 | 269 | 416 | 216 | 200 | 45 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE PackageImports #-}
import "r0z" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, setPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
#ifndef mingw32_HOST_OS
import System.Posix.Signals (installHandler, sigINT, Handler(Catch))
#endif
main :: IO ()
main = do
#ifndef mingw32_HOST_OS
_ <- installHandler sigINT (Catch $ return ()) Nothing
#endif
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings (setPort port defaultSettings) app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| DasAsozialeNetzwerk/r0z | devel.hs | gpl-3.0 | 887 | 0 | 12 | 134 | 238 | 131 | 107 | 24 | 2 |
Subsets and Splits