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 UndecidableInstances #-}
-- | @mp4a@ Audio sample entry according to ISO 14496-14
module Data.ByteString.Mp4.Boxes.AudioSpecificConfig where
import Data.ByteString.IsoBaseFileFormat.ReExports
import Data.ByteString.Mp4.Boxes.DecoderSpecificInfo
-- * Decoder Configuration for ISO 14496-3 (Audio)
-- | A audio config using 'AudioConfigAacMinimal' for AAC-LC.
type AudioConfigAacLc freq channels =
AudioConfigAacMinimal 'AacLc DefaultGASpecificConfig freq channels
-- | A audio config using 'AudioConfigSbrExplicitHierachical' for HE-AAC (v1) in
-- dual rate mode.
type AudioConfigHeAac freq channels =
AudioConfigSbrExplicitHierachical
'AacLc DefaultGASpecificConfig freq channels freq
-- | A minimalistic audio config without sync and error protection
data AudioConfigAacMinimal
:: AudioObjectTypeId
-> Extends AudioSubConfig
-> Extends (EnumOf SamplingFreqTable)
-> Extends (EnumOf ChannelConfigTable)
-> Extends (DecoderSpecificInfo 'AudioIso14496_3 'AudioStream)
type instance
From (AudioConfigAacMinimal
aoId
subCfg
freq
channels) =
('MkDecoderSpecificInfo
(AudioConfigCommon aoId freq channels (BitRecordOfAudioSubConfig subCfg)))
-- | A audio config with SBR signalled explicit and hierachical
data AudioConfigSbrExplicitHierachical
:: AudioObjectTypeId
-> Extends AudioSubConfig
-> Extends (EnumOf SamplingFreqTable)
-> Extends (EnumOf ChannelConfigTable)
-> Extends (EnumOf SamplingFreqTable) -- extension SamplingFrequency
-> Extends (DecoderSpecificInfo 'AudioIso14496_3 'AudioStream)
type instance
From
(AudioConfigSbrExplicitHierachical aoId subCfg freq channels
extFreq)
=
'MkDecoderSpecificInfo
(AudioConfigCommon 'Sbr freq channels
(BitRecordOfEnum extFreq :+:
AudioObjectTypeRec aoId :+: BitRecordOfAudioSubConfig subCfg))
-- | Common header for audio specific config
type AudioConfigCommon aoId samplingFrequencyIndex channels rest =
AudioObjectTypeRec aoId
:+: BitRecordOfEnum samplingFrequencyIndex
:+: BitRecordOfEnum channels
:+: rest
-- ** Audio Object Type
data AudioObjectTypeId =
AacMain -- ^ ISO 14496-4 subpart 4
| AacLc -- ^ ISO 14496-4 subpart 4
| AacSsr -- ^ ISO 14496-4 subpart 4
| AacLtp -- ^ ISO 14496-4 subpart 4
| Sbr -- ^ ISO 14496-4 subpart 4
| AacScalable -- ^ ISO 14496-4 subpart 4
| TwinVq -- ^ ISO 14496-4 subpart 4
| Celp -- ^ ISO 14496-4 subpart 3
| Hvxc -- ^ ISO 14496-4 subpart 2
| AoReserved1
| AoReserved2
| Ttsi -- ^ ISO 14496-4 subpart 6
| MainSunthetic -- ^ ISO 14496-4 subpart 5
| WavetableSynthesis -- ^ ISO 14496-4 subpart 5
| GeneralMidi -- ^ ISO 14496-4 subpart 5
| AlgorithmicSynthesisAndAudioFx -- ^ ISO 14496-4 subpart 5
| ErAacLc -- ^ ISO 14496-4 subpart 4
| AoReserved3
| ErAacLtp -- ^ ISO 14496-4 subpart 4
| ErAacScalable -- ^ ISO 14496-4 subpart 4
| ErTwinVq -- ^ ISO 14496-4 subpart 4
| ErBsac -- ^ ISO 14496-4 subpart 4
| ErAacLd -- ^ ISO 14496-4 subpart 4
| ErCelp -- ^ ISO 14496-4 subpart 3
| ErHvxc -- ^ ISO 14496-4 subpart 2
| ErHiln -- ^ ISO 14496-4 subpart 7
| ErParametric -- ^ ISO 14496-4 subpart 2 or 7
| Ssc -- ^ ISO 14496-4 subpart 8
| AoReserved4
| AoReserved5
| AoCustom
| AoLayer1 -- ^ ISO 14496-4 subpart 9
| AoLayer2 -- ^ ISO 14496-4 subpart 9
| AoLayer3 -- ^ ISO 14496-4 subpart 9
| AoDst -- ^ ISO 14496-4 subpart 10
| AotInvalid
type instance FromEnum AudioObjectTypeId 'AotInvalid = 0
type instance FromEnum AudioObjectTypeId 'AacMain = 1
type instance FromEnum AudioObjectTypeId 'AacLc = 2
type instance FromEnum AudioObjectTypeId 'AacSsr = 3
type instance FromEnum AudioObjectTypeId 'AacLtp = 4
type instance FromEnum AudioObjectTypeId 'Sbr = 5
type instance FromEnum AudioObjectTypeId 'AacScalable = 6
type instance FromEnum AudioObjectTypeId 'TwinVq = 7
type instance FromEnum AudioObjectTypeId 'Celp = 8
type instance FromEnum AudioObjectTypeId 'Hvxc = 9
type instance FromEnum AudioObjectTypeId 'AoReserved1 = 10
type instance FromEnum AudioObjectTypeId 'AoReserved2 = 11
type instance FromEnum AudioObjectTypeId 'Ttsi = 12
type instance FromEnum AudioObjectTypeId 'MainSunthetic = 13
type instance FromEnum AudioObjectTypeId 'WavetableSynthesis = 14
type instance FromEnum AudioObjectTypeId 'GeneralMidi = 15
type instance FromEnum AudioObjectTypeId 'AlgorithmicSynthesisAndAudioFx = 16
type instance FromEnum AudioObjectTypeId 'ErAacLc = 17
type instance FromEnum AudioObjectTypeId 'AoReserved3 = 18
type instance FromEnum AudioObjectTypeId 'ErAacLtp = 19
type instance FromEnum AudioObjectTypeId 'ErAacScalable = 20
type instance FromEnum AudioObjectTypeId 'ErTwinVq = 21
type instance FromEnum AudioObjectTypeId 'ErBsac = 22
type instance FromEnum AudioObjectTypeId 'ErAacLd = 23
type instance FromEnum AudioObjectTypeId 'ErCelp = 24
type instance FromEnum AudioObjectTypeId 'ErHvxc = 25
type instance FromEnum AudioObjectTypeId 'ErHiln = 26
type instance FromEnum AudioObjectTypeId 'ErParametric = 27
type instance FromEnum AudioObjectTypeId 'Ssc = 28
type instance FromEnum AudioObjectTypeId 'AoReserved4 = 29
type instance FromEnum AudioObjectTypeId 'AoReserved5 = 30
type instance FromEnum AudioObjectTypeId 'AoCustom = 31
type instance FromEnum AudioObjectTypeId 'AoLayer1 = 32
type instance FromEnum AudioObjectTypeId 'AoLayer2 = 33
type instance FromEnum AudioObjectTypeId 'AoLayer3 = 34
type instance FromEnum AudioObjectTypeId 'AoDst = 35
type AudioObjectTypeRec n =
AudioObjectTypeField1 (FromEnum AudioObjectTypeId n)
.+: AudioObjectTypeField2 (FromEnum AudioObjectTypeId n)
type family AudioObjectTypeField1 (n :: Nat)
:: Extends (BitRecordField ('MkFieldBits :: BitField (B 5) Nat 5)) where
AudioObjectTypeField1 n =
If (n <=? 30) (Field 5 := n) (Field 5 := 31)
type family AudioObjectTypeField2 (n :: Nat) :: BitRecord where
AudioObjectTypeField2 n =
If (n <=? 30) 'EmptyBitRecord ('BitRecordMember (Field 6 := (n - 31)))
-- *** Sampling Frequency
type SamplingFreq = ExtEnum SamplingFreqTable 4 'SFCustom (Field 24)
data SamplingFreqTable =
SF96000
| SF88200
| SF64000
| SF48000
| SF44100
| SF32000
| SF24000
| SF22050
| SF16000
| SF12000
| SF11025
| SF8000
| SF7350
| SFReserved1
| SFReserved2
| SFCustom
type instance FromEnum SamplingFreqTable 'SF96000 = 0
type instance FromEnum SamplingFreqTable 'SF88200 = 1
type instance FromEnum SamplingFreqTable 'SF64000 = 2
type instance FromEnum SamplingFreqTable 'SF48000 = 3
type instance FromEnum SamplingFreqTable 'SF44100 = 4
type instance FromEnum SamplingFreqTable 'SF32000 = 5
type instance FromEnum SamplingFreqTable 'SF24000 = 6
type instance FromEnum SamplingFreqTable 'SF22050 = 7
type instance FromEnum SamplingFreqTable 'SF16000 = 8
type instance FromEnum SamplingFreqTable 'SF12000 = 9
type instance FromEnum SamplingFreqTable 'SF11025 = 0xa
type instance FromEnum SamplingFreqTable 'SF8000 = 0xb
type instance FromEnum SamplingFreqTable 'SF7350 = 0xc
type instance FromEnum SamplingFreqTable 'SFReserved1 = 0xd
type instance FromEnum SamplingFreqTable 'SFReserved2 = 0xe
type instance FromEnum SamplingFreqTable 'SFCustom = 0xf
sampleRateToNumber :: Num a => SamplingFreqTable -> a
sampleRateToNumber SF96000 = 96000
sampleRateToNumber SF88200 = 88200
sampleRateToNumber SF64000 = 64000
sampleRateToNumber SF48000 = 48000
sampleRateToNumber SF44100 = 44100
sampleRateToNumber SF32000 = 32000
sampleRateToNumber SF24000 = 24000
sampleRateToNumber SF22050 = 22050
sampleRateToNumber SF16000 = 16000
sampleRateToNumber SF12000 = 12000
sampleRateToNumber SF11025 = 11025
sampleRateToNumber SF8000 = 8000
sampleRateToNumber SF7350 = 7350
sampleRateToNumber _ = 0
sampleRateToEnum :: SamplingFreqTable -> EnumValue SamplingFreqTable
sampleRateToEnum SF96000 = MkEnumValue (Proxy @'SF96000)
sampleRateToEnum SF88200 = MkEnumValue (Proxy @'SF88200)
sampleRateToEnum SF64000 = MkEnumValue (Proxy @'SF64000)
sampleRateToEnum SF48000 = MkEnumValue (Proxy @'SF48000)
sampleRateToEnum SF44100 = MkEnumValue (Proxy @'SF44100)
sampleRateToEnum SF32000 = MkEnumValue (Proxy @'SF32000)
sampleRateToEnum SF24000 = MkEnumValue (Proxy @'SF24000)
sampleRateToEnum SF22050 = MkEnumValue (Proxy @'SF22050)
sampleRateToEnum SF16000 = MkEnumValue (Proxy @'SF16000)
sampleRateToEnum SF12000 = MkEnumValue (Proxy @'SF12000)
sampleRateToEnum SF11025 = MkEnumValue (Proxy @'SF11025)
sampleRateToEnum SF8000 = MkEnumValue (Proxy @'SF8000)
sampleRateToEnum SF7350 = MkEnumValue (Proxy @'SF7350)
sampleRateToEnum SFReserved1 = MkEnumValue (Proxy @'SFReserved1)
sampleRateToEnum SFReserved2 = MkEnumValue (Proxy @'SFReserved2)
sampleRateToEnum SFCustom = MkEnumValue (Proxy @'SFCustom)
-- *** Channel Config (Mono, Stereo, 7-1 Surround, ...)
type ChannelConfig = FixedEnum ChannelConfigTable 4
data ChannelConfigTable =
GasChannelConfig
| SingleChannel
| ChannelPair
| SinglePair
| SinglePairSingle
| SinglePairPair
| SinglePairPairLfe
| SinglePairPairPairLfe
type instance FromEnum ChannelConfigTable 'GasChannelConfig = 0
type instance FromEnum ChannelConfigTable 'SingleChannel = 1
type instance FromEnum ChannelConfigTable 'ChannelPair = 2
type instance FromEnum ChannelConfigTable 'SinglePair = 3
type instance FromEnum ChannelConfigTable 'SinglePairSingle = 4
type instance FromEnum ChannelConfigTable 'SinglePairPair = 5
type instance FromEnum ChannelConfigTable 'SinglePairPairLfe = 6
type instance FromEnum ChannelConfigTable 'SinglePairPairPairLfe = 7
channelConfigToNumber :: Num a => ChannelConfigTable -> a
channelConfigToNumber GasChannelConfig = 0
channelConfigToNumber SingleChannel = 1
channelConfigToNumber ChannelPair = 2
channelConfigToNumber SinglePair = 3
channelConfigToNumber SinglePairSingle = 4
channelConfigToNumber SinglePairPair = 5
channelConfigToNumber SinglePairPairLfe = 6
channelConfigToNumber SinglePairPairPairLfe = 7
channelConfigToEnum :: ChannelConfigTable -> EnumValue ChannelConfigTable
channelConfigToEnum GasChannelConfig = MkEnumValue (Proxy @'GasChannelConfig)
channelConfigToEnum SingleChannel = MkEnumValue (Proxy @'SingleChannel)
channelConfigToEnum ChannelPair = MkEnumValue (Proxy @'ChannelPair)
channelConfigToEnum SinglePair = MkEnumValue (Proxy @'SinglePair)
channelConfigToEnum SinglePairSingle = MkEnumValue (Proxy @'SinglePairSingle)
channelConfigToEnum SinglePairPair = MkEnumValue (Proxy @'SinglePairPair)
channelConfigToEnum SinglePairPairLfe = MkEnumValue (Proxy @'SinglePairPairLfe)
channelConfigToEnum SinglePairPairPairLfe = MkEnumValue (Proxy @'SinglePairPairPairLfe)
-- ** More Specific audio decoder config
data AudioSubConfig :: Type
type family BitRecordOfAudioSubConfig (x :: Extends AudioSubConfig) :: BitRecord
data GASpecificConfig
(frameLenFlag :: Extends (FieldValue "frameLenFlag" Bool))
(coreCoderDelay :: Maybe (Extends (FieldValue "coreCoderDelay" Nat)))
(extension :: Extends GASExtension)
:: Extends AudioSubConfig
type DefaultGASpecificConfig =
GASpecificConfig (StaticFieldValue "frameLenFlag" 'False) 'Nothing MkGASExtension
type instance From (GASpecificConfig fl cd ext)
= TypeError ('Text "AudioSubConfig is abstract!")
type instance
BitRecordOfAudioSubConfig (GASpecificConfig fl cd ext) =
( Flag :~ fl
.+: FlagJust cd
.+: Field 14 :+? cd
:+: BitRecordOfGASExtension ext
)
-- | TODO implment that GAS extensions
data GASExtension
data MkGASExtension :: Extends GASExtension
type BitRecordOfGASExtension (x :: Extends GASExtension) =
'BitRecordMember ("has-gas-extension" @: Flag := 'False)
| sheyll/isobmff-builder | src/Data/ByteString/Mp4/Boxes/AudioSpecificConfig.hs | bsd-3-clause | 13,298 | 1 | 13 | 3,477 | 2,607 | 1,430 | 1,177 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Text.XML.ToJSON.Builder
( -- * Element type and operations
Element(..)
, emptyElement
, addChild'
, addValue'
, addAttr'
, addAttrs'
-- * Stack type and operations
, Stack
, popStack
, closeStack
-- * Builder type and operations
, Builder
, runBuilder
, beginElement
, endElement
, modifyTopElement
, addChild
, addValue
, addAttr
, addAttrs
) where
import Data.Text (Text)
import Control.Monad.Trans.State
-- | represent a XML element.
data Element = Element
{ elAttrs :: [(Text, Text)] -- ^ tag attributes.
, elValues :: [Text] -- ^ text values.
, elChildren :: [(Text, Element)] -- ^ child elements.
} deriving (Show)
emptyElement :: Element
emptyElement = Element [] [] []
reverseBack :: Element -> Element
reverseBack (Element as vs cs) = Element as (reverse vs) (reverse cs)
-- | add a child element to an element in reverse order, reversed back in `popStack'.
addChild' :: (Text, Element) -> Element -> Element
addChild' item o = o { elChildren = item : elChildren o }
-- | add a text value to an element in reverse order, reversed back in `popStack'.
addValue' :: Text -> Element -> Element
addValue' v o = o { elValues = v : elValues o }
-- | add an attribute to an element
addAttr' :: (Text, Text) -> Element -> Element
addAttr' attr o = o { elAttrs = attr : elAttrs o }
-- | add multiple attributes to an element
addAttrs' :: [(Text, Text)] -> Element -> Element
addAttrs' as o = o { elAttrs = as ++ elAttrs o }
-- | xml element stack with recent opened element at the top.
type Stack = [(Text, Element)]
-- | close current tag.
popStack :: Stack -> Stack
popStack ((k,v) : (name,elm) : tl) = (name, addChild' (k,reverseBack v) elm) : tl
popStack _ = error "popStack: can't pop root elmect."
-- | close all unclosed tags and return the root element.
closeStack :: Stack -> Element
closeStack [] = error "closeStack: empty stack."
closeStack [(_, elm)] = reverseBack elm
closeStack st = closeStack (popStack st)
-- | `Builder' is a `State' monad to transform a `Stack'.
type Builder = State Stack ()
-- | exec the state monad and close the result stack.
runBuilder :: Builder -> Element
runBuilder b = closeStack $ execState b [("", emptyElement)]
-- | open element
beginElement :: Text -> Builder
beginElement name =
modify ( (name, emptyElement) : )
-- | close element
endElement :: Builder
endElement =
modify popStack
-- | util to modify top element.
modifyTopElement :: (Element -> Element) -> Builder
modifyTopElement f =
modify $ \st ->
case st of
((k, v) : tl) -> (k, f v) : tl
_ -> fail "modifyTopElement: impossible: empty stack."
-- | add value to top element.
addValue :: Text -> Builder
addValue = modifyTopElement . addValue'
-- | add attribute to top element.
addAttr :: (Text, Text) -> Builder
addAttr = modifyTopElement . addAttr'
-- | add multiple attributes to top element.
addAttrs :: [(Text, Text)] -> Builder
addAttrs = modifyTopElement . addAttrs'
-- | add child element to top element.
addChild :: (Text, Element) -> Builder
addChild = modifyTopElement . addChild'
| yihuang/xml2json | Text/XML/ToJSON/Builder.hs | bsd-3-clause | 3,219 | 0 | 12 | 711 | 817 | 472 | 345 | 71 | 2 |
#!/usr/bin/env runhaskell
import Distribution.Simple
import Distribution.PackageDescription
import Distribution.Version
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Program
import Distribution.Verbosity
import Data.Char (isSpace)
import Data.List (dropWhile,reverse)
import Control.Monad
main = defaultMainWithHooks simpleUserHooks {
hookedPrograms = [pgconfigProgram],
confHook = \pkg flags -> do
lbi <- confHook simpleUserHooks pkg flags
bi <- psqlBuildInfo lbi
return lbi {
localPkgDescr = updatePackageDescription
(Just bi, [("runtests", bi)]) (localPkgDescr lbi)
}
}
pgconfigProgram = (simpleProgram "pgconfig") {
programFindLocation = \verbosity -> do
pgconfig <- findProgramLocation verbosity "pgconfig"
pg_config <- findProgramLocation verbosity "pg_config"
return (pgconfig `mplus` pg_config)
}
psqlBuildInfo :: LocalBuildInfo -> IO BuildInfo
psqlBuildInfo lbi = do
(pgconfigProg, _) <- requireProgram verbosity
pgconfigProgram (withPrograms lbi)
let pgconfig = rawSystemProgramStdout verbosity pgconfigProg
incDir <- pgconfig ["--includedir"]
libDir <- pgconfig ["--libdir"]
return emptyBuildInfo {
extraLibDirs = [strip libDir],
includeDirs = [strip incDir]
}
where
verbosity = normal -- honestly, this is a hack
strip x = dropWhile isSpace $ reverse $ dropWhile isSpace $ reverse x
| tnarg/haskell-libpq | Setup.hs | bsd-3-clause | 1,460 | 0 | 17 | 294 | 379 | 198 | 181 | 34 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Monad (forM_)
import Data.Monoid (mconcat)
import Development.Shake
import Development.Shake.FilePath
import System.Console.GetOpt
import qualified System.Info (os, arch)
import System.IO
import Config
import Dirs
import GhcDist
import HaddockMaster
import OS
import Package
import Paths
import PlatformDB
import Releases
import SourceTarball
import Types
import Target
import Website
data Flags = Info | Prefix String | Full
deriving Eq
flags :: [OptDescr (Either a Flags)]
flags = [ Option ['i'] ["info"] (NoArg $ Right Info)
"Show info on what gets included in this HP release"
, Option [] ["prefix"] (ReqArg (Right . Prefix) "DIR")
"Set installation prefix (only for Posix builds)"
, Option ['f'] ["full"] (NoArg $ Right Full)
"Do a full (rather than minimal) build of the platform."
]
main :: IO ()
main = hSetEncoding stdout utf8 >> shakeArgsWith opts flags main'
where
main' flgs args =
if Info `elem` flgs
then info
else case args of
(tarfile:stackexe:buildType) -> return $ Just $ do
allRules tarfile stackexe flgs
want $ if null buildType then ["build-all"] else buildType
_ -> usage
info = do
putStrLn $ "This hptool is built to construct " ++ hpFullName ++ "\n\
\ for the " ++
System.Info.os ++ " " ++ System.Info.arch ++ " platform.\n\
\The HP constructed will contain the following:\n\n"
++ unlines (whatIsIncluded hpRelease)
return Nothing
usage = do
putStrLn "usage: hptool --info\n\
\ hptool [opts] <ghc-bindist.tar.bz> <stack executable> [target...]\n\
\ where target is one of:\n\
\ build-all -- build everything (default)\n\
\ build-source -- build the source tar ball\n\
\ build-target -- build the target tree\n\
\ build-package-<pkg> -- build the package (name or name-ver)\n\
\ build-local -- build the local GHC environment\n\
\ build-website -- build the website\n"
return Nothing
allRules tarfile stackexe flgs = do
buildConfig <- addConfigOracle hpRelease tarfile stackexe (prefixSetting flgs) (Full `elem` flgs)
ghcDistRules
packageRules
targetRules buildConfig
haddockMasterRules buildConfig
sourceTarballRules srcTarFile
buildRules hpRelease srcTarFile buildConfig
websiteRules "website"
prefixSetting = mconcat . reverse . map ps
where
ps (Prefix p) = Just p
ps _ = Nothing
opts = shakeOptions
hpRelease = hp_8_0_0
hpFullName = show $ relVersion hpRelease
srcTarFile = productDir </> hpFullName <.> "tar.gz"
whatIsIncluded :: Release -> [String]
whatIsIncluded rel = ("-- Minimal Platform:":minimalIncludes) ++ ("-- Full Platform:":fullIncludes) where
minimalIncludes = map (concat . includeToString) $ relMinimalIncludes rel
fullIncludes = map (concat . includeToString) $ relIncludes rel where
includeToString (IncGHC, p) = "GHC: " : [show p]
includeToString (IncGHCLib, p) = "GHCLib: " : [show p]
includeToString (IncLib, p) = "LIB: " : [show p]
includeToString (IncTool, p) = "TOOL: " : [show p]
includeToString (IncGHCTool, p) = "TOOL: " : [show p]
includeToString (IncIfWindows it, p) =
"IfWindows: " : includeToString (it,p)
includeToString (IncIfNotWindows it, p) =
"IfNotWindows: " : includeToString (it,p)
buildRules :: Release -> FilePath -> BuildConfig -> Rules()
buildRules hpRelease srcTarFile bc = do
"build-source" ~> need [srcTarFile]
"build-target" ~> need [targetDir]
"build-product" ~> need [osProduct]
"build-local" ~> need [dir ghcLocalDir]
"build-website" ~> need [dir websiteDir]
forM_ (platformPackages True hpRelease) $ \pkg -> do
let full = "build-package-" ++ show pkg
let short = "build-package-" ++ pkgName pkg
short ~> need [full]
full ~> need [dir $ packageBuildDir pkg]
"build-all" ~> do -- separate need call so built in order
need ["build-source"]
need ["build-product"]
osRules hpRelease bc
where
OS{..} = osFromConfig bc
| gbaz/haskell-platform | hptool/src/Main.hs | bsd-3-clause | 4,630 | 0 | 16 | 1,421 | 1,103 | 567 | 536 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Create new a new project directory populated with a basic working
-- project.
module Stack.New
( new
, NewOpts(..)
, TemplateName
, templatesHelp
) where
import Stack.Prelude
import Control.Monad.Trans.Writer.Strict
import Data.Aeson as A
import qualified Data.ByteString.Base64 as B64
import Data.ByteString.Builder (lazyByteString)
import qualified Data.ByteString.Lazy as LB
import Data.Conduit
import Data.List
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy.Encoding as TLE
import Data.Time.Calendar
import Data.Time.Clock
import Network.HTTP.StackClient (VerifiedDownloadException (..), Request, HttpException,
getResponseBody, httpLbs, mkDownloadRequest, parseRequest, parseUrlThrow,
setForceDownload, setGithubHeaders, setRequestCheckStatus, verifiedDownloadWithProgress)
import Path
import Path.IO
import Stack.Constants
import Stack.Constants.Config
import Stack.Types.Config
import Stack.Types.TemplateName
import qualified RIO.HashMap as HM
import RIO.Process
import qualified Text.Mustache as Mustache
import qualified Text.Mustache.Render as Mustache
import Text.ProjectTemplate
--------------------------------------------------------------------------------
-- Main project creation
-- | Options for creating a new project.
data NewOpts = NewOpts
{ newOptsProjectName :: PackageName
-- ^ Name of the project to create.
, newOptsCreateBare :: Bool
-- ^ Whether to create the project without a directory.
, newOptsTemplate :: Maybe TemplateName
-- ^ Name of the template to use.
, newOptsNonceParams :: Map Text Text
-- ^ Nonce parameters specified just for this invocation.
}
-- | Create a new project with the given options.
new :: HasConfig env => NewOpts -> Bool -> RIO env (Path Abs Dir)
new opts forceOverwrite = do
when (newOptsProjectName opts `elem` wiredInPackages) $
throwM $ Can'tUseWiredInName (newOptsProjectName opts)
pwd <- getCurrentDir
absDir <- if bare then return pwd
else do relDir <- parseRelDir (packageNameString project)
liftM (pwd </>) (return relDir)
exists <- doesDirExist absDir
configTemplate <- view $ configL.to configDefaultTemplate
let template = fromMaybe defaultTemplateName $ asum [ cliOptionTemplate
, configTemplate
]
if exists && not bare
then throwM (AlreadyExists absDir)
else do
templateText <- loadTemplate template (logUsing absDir template)
files <-
applyTemplate
project
template
(newOptsNonceParams opts)
absDir
templateText
when (not forceOverwrite && bare) $ checkForOverwrite (M.keys files)
writeTemplateFiles files
runTemplateInits absDir
return absDir
where
cliOptionTemplate = newOptsTemplate opts
project = newOptsProjectName opts
bare = newOptsCreateBare opts
logUsing absDir template templateFrom =
let loading = case templateFrom of
LocalTemp -> "Loading local"
RemoteTemp -> "Downloading"
in
logInfo
(loading <> " template \"" <> display (templateName template) <>
"\" to create project \"" <>
fromString (packageNameString project) <>
"\" in " <>
if bare then "the current directory"
else fromString (toFilePath (dirname absDir)) <>
" ...")
data TemplateFrom = LocalTemp | RemoteTemp
-- | Download and read in a template's text content.
loadTemplate
:: forall env. HasConfig env
=> TemplateName
-> (TemplateFrom -> RIO env ())
-> RIO env Text
loadTemplate name logIt = do
templateDir <- view $ configL.to templatesDir
case templatePath name of
AbsPath absFile -> logIt LocalTemp >> loadLocalFile absFile eitherByteStringToText
UrlPath s -> do
let settings = asIsFromUrl s
downloadFromUrl settings templateDir
RelPath rawParam relFile ->
catch
(do f <- loadLocalFile relFile eitherByteStringToText
logIt LocalTemp
return f)
(\(e :: NewException) -> do
case relSettings rawParam of
Just settings -> do
req <- parseRequest (tplDownloadUrl settings)
let extract = tplExtract settings
downloadTemplate req extract (templateDir </> relFile)
Nothing -> throwM e
)
RepoPath rtp -> do
let settings = settingsFromRepoTemplatePath rtp
downloadFromUrl settings templateDir
where
loadLocalFile :: Path b File -> (ByteString -> Either String Text) -> RIO env Text
loadLocalFile path extract = do
logDebug ("Opening local template: \"" <> fromString (toFilePath path)
<> "\"")
exists <- doesFileExist path
if exists
then do
bs <- readFileBinary (toFilePath path) --readFileUtf8 (toFilePath path)
case extract bs of
Left err -> do
logWarn $ "Template extraction error: " <> display (T.pack err)
throwM (FailedToLoadTemplate name (toFilePath path))
Right template ->
pure template
else throwM (FailedToLoadTemplate name (toFilePath path))
relSettings :: String -> Maybe TemplateDownloadSettings
relSettings req = do
rtp <- parseRepoPathWithService defaultRepoService (T.pack req)
pure (settingsFromRepoTemplatePath rtp)
downloadFromUrl :: TemplateDownloadSettings -> Path Abs Dir -> RIO env Text
downloadFromUrl settings templateDir = do
let url = tplDownloadUrl settings
req <- parseRequest url
let rel = fromMaybe backupUrlRelPath (parseRelFile url)
downloadTemplate req (tplExtract settings) (templateDir </> rel)
downloadTemplate :: Request -> (ByteString -> Either String Text) -> Path Abs File -> RIO env Text
downloadTemplate req extract path = do
let dReq = setForceDownload True $ mkDownloadRequest (setRequestCheckStatus req)
logIt RemoteTemp
catch
(void $ do
verifiedDownloadWithProgress dReq path (T.pack $ toFilePath path) Nothing
)
(useCachedVersionOrThrow path)
loadLocalFile path extract
useCachedVersionOrThrow :: Path Abs File -> VerifiedDownloadException -> RIO env ()
useCachedVersionOrThrow path exception = do
exists <- doesFileExist path
if exists
then do logWarn "Tried to download the template but an error was found."
logWarn "Using cached local version. It may not be the most recent version though."
else throwM (FailedToDownloadTemplate name exception)
data TemplateDownloadSettings = TemplateDownloadSettings
{ tplDownloadUrl :: String
, tplExtract :: ByteString -> Either String Text
}
eitherByteStringToText :: ByteString -> Either String Text
eitherByteStringToText = mapLeft show . decodeUtf8'
asIsFromUrl :: String -> TemplateDownloadSettings
asIsFromUrl url = TemplateDownloadSettings
{ tplDownloadUrl = url
, tplExtract = eitherByteStringToText
}
-- | Construct a URL for downloading from a repo.
settingsFromRepoTemplatePath :: RepoTemplatePath -> TemplateDownloadSettings
settingsFromRepoTemplatePath (RepoTemplatePath Github user name) =
-- T.concat ["https://raw.githubusercontent.com", "/", user, "/stack-templates/master/", name]
TemplateDownloadSettings
{ tplDownloadUrl = concat ["https://api.github.com/repos/", T.unpack user, "/stack-templates/contents/", T.unpack name]
, tplExtract = \bs -> do
decodedJson <- eitherDecode (LB.fromStrict bs)
case decodedJson of
Object o | Just (String content) <- HM.lookup "content" o -> do
let noNewlines = T.filter (/= '\n')
bsContent <- B64.decode $ T.encodeUtf8 (noNewlines content)
mapLeft show $ decodeUtf8' bsContent
_ ->
fail "Couldn't parse GitHub response as a JSON object with a \"content\" field"
}
settingsFromRepoTemplatePath (RepoTemplatePath Gitlab user name) =
asIsFromUrl $ concat ["https://gitlab.com", "/", T.unpack user, "/stack-templates/raw/master/", T.unpack name]
settingsFromRepoTemplatePath (RepoTemplatePath Bitbucket user name) =
asIsFromUrl $ concat ["https://bitbucket.org", "/", T.unpack user, "/stack-templates/raw/master/", T.unpack name]
-- | Apply and unpack a template into a directory.
applyTemplate
:: HasConfig env
=> PackageName
-> TemplateName
-> Map Text Text
-> Path Abs Dir
-> Text
-> RIO env (Map (Path Abs File) LB.ByteString)
applyTemplate project template nonceParams dir templateText = do
config <- view configL
currentYear <- do
now <- liftIO getCurrentTime
let (year, _, _) = toGregorian (utctDay now)
return $ T.pack . show $ year
let context = M.unions [nonceParams, nameParams, configParams, yearParam]
where
nameAsVarId = T.replace "-" "_" $ T.pack $ packageNameString project
nameAsModule = T.filter (/= ' ') $ T.toTitle $ T.replace "-" " " $ T.pack $ packageNameString project
nameParams = M.fromList [ ("name", T.pack $ packageNameString project)
, ("name-as-varid", nameAsVarId)
, ("name-as-module", nameAsModule) ]
configParams = configTemplateParams config
yearParam = M.singleton "year" currentYear
files :: Map FilePath LB.ByteString <-
catch (execWriterT $ runConduit $
yield (T.encodeUtf8 templateText) .|
unpackTemplate receiveMem id
)
(\(e :: ProjectTemplateException) ->
throwM (InvalidTemplate template (show e)))
when (M.null files) $
throwM (InvalidTemplate template "Template does not contain any files")
let isPkgSpec f = ".cabal" `isSuffixOf` f || f == "package.yaml"
unless (any isPkgSpec . M.keys $ files) $
throwM (InvalidTemplate template "Template does not contain a .cabal \
\or package.yaml file")
-- Apply Mustache templating to a single file within the project
-- template.
let applyMustache bytes
-- Workaround for performance problems with mustache and
-- large files, applies to Yesod templates with large
-- bootstrap CSS files. See
-- https://github.com/commercialhaskell/stack/issues/4133.
| LB.length bytes < 50000
, Right text <- TLE.decodeUtf8' bytes = do
let etemplateCompiled = Mustache.compileTemplate (T.unpack (templateName template)) $ TL.toStrict text
templateCompiled <- case etemplateCompiled of
Left e -> throwM $ InvalidTemplate template (show e)
Right t -> return t
let (substitutionErrors, applied) = Mustache.checkedSubstitute templateCompiled context
missingKeys = S.fromList $ concatMap onlyMissingKeys substitutionErrors
unless (S.null missingKeys)
(logInfo ("\n" <> displayShow (MissingParameters project template missingKeys (configUserConfigPath config)) <> "\n"))
pure $ LB.fromStrict $ encodeUtf8 applied
-- Too large or too binary
| otherwise = pure bytes
liftM
M.fromList
(mapM
(\(fpOrig,bytes) ->
do -- Apply the mustache template to the filenames
-- as well, so that we can have file names
-- depend on the project name.
fp <- applyMustache $ TLE.encodeUtf8 $ TL.pack fpOrig
path <- parseRelFile $ TL.unpack $ TLE.decodeUtf8 fp
bytes' <- applyMustache bytes
return (dir </> path, bytes'))
(M.toList files))
where
onlyMissingKeys (Mustache.VariableNotFound ks) = map T.unpack ks
onlyMissingKeys _ = []
-- | Check if we're going to overwrite any existing files.
checkForOverwrite :: (MonadIO m, MonadThrow m) => [Path Abs File] -> m ()
checkForOverwrite files = do
overwrites <- filterM doesFileExist files
unless (null overwrites) $ throwM (AttemptedOverwrites overwrites)
-- | Write files to the new project directory.
writeTemplateFiles
:: MonadIO m
=> Map (Path Abs File) LB.ByteString -> m ()
writeTemplateFiles files =
liftIO $
forM_
(M.toList files)
(\(fp,bytes) ->
do ensureDir (parent fp)
writeBinaryFileAtomic fp $ lazyByteString bytes)
-- | Run any initialization functions, such as Git.
runTemplateInits
:: HasConfig env
=> Path Abs Dir
-> RIO env ()
runTemplateInits dir = do
config <- view configL
case configScmInit config of
Nothing -> return ()
Just Git ->
withWorkingDir (toFilePath dir) $
catchAny (proc "git" ["init"] runProcess_)
(\_ -> logInfo "git init failed to run, ignoring ...")
-- | Display help for the templates command.
templatesHelp :: HasLogFunc env => RIO env ()
templatesHelp = do
let url = defaultTemplatesHelpUrl
req <- liftM setGithubHeaders (parseUrlThrow url)
resp <- httpLbs req `catch` (throwM . FailedToDownloadTemplatesHelp)
case decodeUtf8' $ LB.toStrict $ getResponseBody resp of
Left err -> throwM $ BadTemplatesHelpEncoding url err
Right txt -> logInfo $ display txt
--------------------------------------------------------------------------------
-- Defaults
-- | The default service to use to download templates.
defaultRepoService :: RepoService
defaultRepoService = Github
-- | Default web URL to get the `stack templates` help output.
defaultTemplatesHelpUrl :: String
defaultTemplatesHelpUrl =
"https://raw.githubusercontent.com/commercialhaskell/stack-templates/master/STACK_HELP.md"
--------------------------------------------------------------------------------
-- Exceptions
-- | Exception that might occur when making a new project.
data NewException
= FailedToLoadTemplate !TemplateName
!FilePath
| FailedToDownloadTemplate !TemplateName
!VerifiedDownloadException
| AlreadyExists !(Path Abs Dir)
| MissingParameters !PackageName !TemplateName !(Set String) !(Path Abs File)
| InvalidTemplate !TemplateName !String
| AttemptedOverwrites [Path Abs File]
| FailedToDownloadTemplatesHelp !HttpException
| BadTemplatesHelpEncoding
!String -- URL it's downloaded from
!UnicodeException
| Can'tUseWiredInName !PackageName
deriving (Typeable)
instance Exception NewException
instance Show NewException where
show (FailedToLoadTemplate name path) =
"Failed to load download template " <> T.unpack (templateName name) <>
" from " <>
path
show (FailedToDownloadTemplate name (DownloadHttpError httpError)) =
"There was an unexpected HTTP error while downloading template " <>
T.unpack (templateName name) <> ": " <> show httpError
show (FailedToDownloadTemplate name _) =
"Failed to download template " <> T.unpack (templateName name) <>
": unknown reason"
show (AlreadyExists path) =
"Directory " <> toFilePath path <> " already exists. Aborting."
show (MissingParameters name template missingKeys userConfigPath) =
intercalate
"\n"
[ "The following parameters were needed by the template but not provided: " <>
intercalate ", " (S.toList missingKeys)
, "You can provide them in " <>
toFilePath userConfigPath <>
", like this:"
, "templates:"
, " params:"
, intercalate
"\n"
(map
(\key ->
" " <> key <> ": value")
(S.toList missingKeys))
, "Or you can pass each one as parameters like this:"
, "stack new " <> packageNameString name <> " " <>
T.unpack (templateName template) <>
" " <>
unwords
(map
(\key ->
"-p \"" <> key <> ":value\"")
(S.toList missingKeys))]
show (InvalidTemplate name why) =
"The template \"" <> T.unpack (templateName name) <>
"\" is invalid and could not be used. " <>
"The error was: " <> why
show (AttemptedOverwrites fps) =
"The template would create the following files, but they already exist:\n" <>
unlines (map ((" " ++) . toFilePath) fps) <>
"Use --force to ignore this, and overwite these files."
show (FailedToDownloadTemplatesHelp ex) =
"Failed to download `stack templates` help. The HTTP error was: " <> show ex
show (BadTemplatesHelpEncoding url err) =
"UTF-8 decoding error on template info from\n " <> url <> "\n\n" <> show err
show (Can'tUseWiredInName name) =
"The name \"" <> packageNameString name <> "\" is used by GHC wired-in packages, and so shouldn't be used as a package name"
| juhp/stack | src/Stack/New.hs | bsd-3-clause | 18,535 | 0 | 23 | 5,621 | 3,996 | 1,996 | 2,000 | 378 | 8 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS -fno-warn-unused-do-bind -fno-warn-type-defaults #-}
-- | Calendar.
module Ircbrowse.View.Calendar
(calendar
,channel
,channelNav)
where
import Ircbrowse.Types.Import
import Ircbrowse.View
import Ircbrowse.View.Template
import Data.Function
import Data.List.Split
import qualified Data.Text as T
import Data.Time.Calendar.OrdinalDate
startYear :: Integer
startYear = 2001
channel :: Channel -> Html
channel channel = do
template "channel" (T.pack ("#" ++ showChan channel)) (return ()) $ do
channelNav channel
container $
row $ span12 $ p "Choose from the menu!"
footer
calendar :: Day -> Day -> Channel -> Html
calendar firstDay today channel =
template "calendar" (T.pack ("#" ++ showChan channel)) (return ()) $ do
channelNav channel
container $ do
forM_ (years firstDay today) $ \year ->
case year of
((yearsample:_):_) -> do
row $
span12 $
h2 $ toHtml (showYear yearsample)
forM_ (chunksOf 4 year) $ \months ->
row $ do
forM_ months $ \days ->
span3 $
case days of
[] -> return ()
(monthsample:_) -> do
h3 $ toHtml (showMonth monthsample)
table $
forM_ (chunksOf 7 days) $ \days ->
tr $
forM_ days $ \day ->
td $
a ! href (toValue ("/day/" ++ showChan channel ++ "/" ++ showDate day)) $
toHtml (showDayOfMonth day)
_ -> return ()
footer
years :: Day -> Day -> [[[Day]]]
years firstDay today =
reverse (map (groupBy (on (==) showMonth))
(groupBy (on (==) showYear)
(takeWhile (<= today)
(dropWhile (<firstDay)
[fromOrdinalDate startYear 01 ..]))))
showYear :: FormatTime t => t -> String
showYear = formatTime defaultTimeLocale "%Y"
showMonth :: FormatTime t => t -> String
showMonth = formatTime defaultTimeLocale "%B"
showDayOfMonth :: FormatTime t => t -> String
showDayOfMonth = formatTime defaultTimeLocale "%e"
showDate :: FormatTime t => t -> String
showDate = formatTime defaultTimeLocale "%Y/%m/%d"
| chrisdone/ircbrowse | src/Ircbrowse/View/Calendar.hs | bsd-3-clause | 2,663 | 0 | 44 | 1,028 | 724 | 372 | 352 | 67 | 3 |
-- | This module provides the type function symbols and variables.
module Tct.Trs.Data.Symbol
( Fun(..)
, AFun(..)
, F
, fun
, V
, var
, mainFunction
)
where
import qualified Data.ByteString.Char8 as BS
import qualified Tct.Core.Common.Pretty as PP
import qualified Tct.Core.Common.Xml as Xml
-- | Abstract function interface.
class Fun f where
markFun :: f -> f
compoundFun :: Int -> f
isMarkedFun :: f -> Bool
isCompoundFun :: f -> Bool
--- * instance -------------------------------------------------------------------------------------------------------
-- | Annotated function symbol.
data AFun f
= TrsFun f
| DpFun f
| ComFun Int
deriving (Eq, Ord, Show, Read)
newtype F = F (AFun BS.ByteString)
deriving (Eq, Ord, Show, Read)
fun :: String -> F
fun = F . TrsFun . BS.pack
mainFunction :: F
mainFunction = fun "main"
newtype V = V BS.ByteString
deriving (Eq, Ord)
instance Show V where
show (V x) = show x
var :: String -> V
var = V . BS.pack
instance Read V where
readsPrec _ str =
let str' = filter (/= '"') str
x = BS.pack $ if take 2 str' == "V " then drop 2 str' else str'
in [(V x, [])]
instance Fun F where
markFun (F (TrsFun f)) = F (DpFun f)
markFun _ = error "Tct.Trs.Data.Problem.markFun: not a trs symbol"
compoundFun = F . ComFun
isMarkedFun (F (DpFun _)) = True
isMarkedFun _ = False
isCompoundFun (F (ComFun _)) = True
isCompoundFun _ = False
--- * proofdata ------------------------------------------------------------------------------------------------------
instance PP.Pretty V where
pretty (V v) = PP.text (BS.unpack v)
instance Xml.Xml V where
toXml (V v) = Xml.elt "var" [Xml.text (BS.unpack v)]
toCeTA = Xml.toXml
-- instance PP.Pretty BS.ByteString where
-- pretty = PP.text . BS.unpack
-- instance Xml.Xml BS.ByteString where
-- toXml = Xml.text . BS.unpack
-- toCeTA = Xml.text . BS.unpack
instance PP.Pretty F where
pretty (F (TrsFun f)) = PP.text (BS.unpack f)
pretty (F (DpFun f)) = PP.text (BS.unpack f) PP.<> PP.char '#'
pretty (F (ComFun i)) = PP.pretty "c_" PP.<> PP.int i
instance Xml.Xml F where
toXml (F (TrsFun f)) = Xml.elt "name" [Xml.text $ BS.unpack f]
toXml (F (DpFun f)) =
Xml.elt "sharp" [Xml.elt "name" [Xml.text $ BS.unpack f]]
toXml (F (ComFun f)) = Xml.elt "name" [Xml.text $ 'c' : show f]
toCeTA = Xml.toXml
| ComputationWithBoundedResources/tct-trs | src/Tct/Trs/Data/Symbol.hs | bsd-3-clause | 2,456 | 0 | 13 | 567 | 864 | 459 | 405 | 61 | 1 |
-- | Utility functions on strings
module Servant.ChinesePod.Util.String (
explode
, dropBOM
, trim
, lowercase
) where
import Data.Char
-- | Split a string at the specified delimeter
explode :: Char -> String -> [String]
explode needle = go
where
go :: String -> [String]
go haystack = case break (== needle) haystack of
(xs, "") -> [xs]
(xs, _needle':haystack') -> xs : go haystack'
-- | Drop unicode BOM character if present
dropBOM :: String -> String
dropBOM ('\65279':str) = str
dropBOM str = str
-- | Trim whitespace
trim :: String -> String
trim = rtrim . ltrim
where
ltrim, rtrim :: String -> String
ltrim = dropWhile isSpace
rtrim = reverse . ltrim . reverse
-- | Map every character to lowercase
lowercase :: String -> String
lowercase = map toLower
| edsko/ChinesePodAPI | src/Servant/ChinesePod/Util/String.hs | bsd-3-clause | 866 | 0 | 11 | 241 | 230 | 131 | 99 | 22 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE OverloadedStrings #-}
module Snap.Internal.Parsing where
------------------------------------------------------------------------------
import Blaze.ByteString.Builder
import Control.Applicative
import Control.Arrow (first, second)
import Control.Monad
import Data.Bits
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.ByteString.Internal (c2w, w2c)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import Data.Char hiding (isDigit, isSpace)
import Data.Int
import Data.List (intersperse)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import Data.Word
import GHC.Exts
import GHC.Word (Word8 (..))
import Prelude hiding (head, take, takeWhile)
------------------------------------------------------------------------------
import Snap.Internal.Parsing.FastSet (FastSet)
import qualified Snap.Internal.Parsing.FastSet as FS
------------------------------------------------------------------------------
{-# INLINE fullyParse #-}
fullyParse :: ByteString -> Parser a -> Either String a
fullyParse s p =
case r' of
(Fail _ _ e) -> Left e
(Partial _) -> Left "parse failed"
(Done _ x) -> Right x
where
r = parse p s
r' = feed r ""
------------------------------------------------------------------------------
parseNum :: Parser Int64
parseNum = decimal
------------------------------------------------------------------------------
-- | Parsers for different tokens in an HTTP request.
sp, digit, letter :: Parser Char
sp = char ' '
digit = satisfy isDigit
letter = satisfy isAlpha
------------------------------------------------------------------------------
untilEOL :: Parser ByteString
untilEOL = takeWhile notend
where
notend c = not $ c == '\r' || c == '\n'
------------------------------------------------------------------------------
crlf :: Parser ByteString
crlf = string "\r\n"
------------------------------------------------------------------------------
generateFS :: (Word8 -> Bool) -> FastSet
generateFS f = FS.fromList $ filter f [0..255]
------------------------------------------------------------------------------
-- | Parser for zero or more spaces.
spaces :: Parser [Char]
spaces = many sp
------------------------------------------------------------------------------
pSpaces :: Parser ByteString
pSpaces = takeWhile isSpace
------------------------------------------------------------------------------
fieldChars :: Parser ByteString
fieldChars = takeWhile isFieldChar
where
isFieldChar = flip FS.memberChar fieldCharSet
------------------------------------------------------------------------------
fieldCharSet :: FastSet
fieldCharSet = generateFS f
where
f d = let c = (toEnum $ fromEnum d)
in (isDigit c) || (isAlpha c) || c == '-' || c == '_'
------------------------------------------------------------------------------
-- | Parser for request headers.
pHeaders :: Parser [(ByteString, ByteString)]
pHeaders = many header
where
--------------------------------------------------------------------------
header = {-# SCC "pHeaders/header" #-}
liftA2 (,)
fieldName
(char ':' *> spaces *> contents)
--------------------------------------------------------------------------
fieldName = {-# SCC "pHeaders/fieldName" #-}
liftA2 S.cons letter fieldChars
--------------------------------------------------------------------------
contents = {-# SCC "pHeaders/contents" #-}
liftA2 S.append
(untilEOL <* crlf)
(continuation <|> pure S.empty)
--------------------------------------------------------------------------
isLeadingWS w = {-# SCC "pHeaders/isLeadingWS" #-}
w == ' ' || w == '\t'
--------------------------------------------------------------------------
leadingWhiteSpace = {-# SCC "pHeaders/leadingWhiteSpace" #-}
takeWhile1 isLeadingWS
--------------------------------------------------------------------------
continuation = {-# SCC "pHeaders/continuation" #-}
liftA2 S.cons
(leadingWhiteSpace *> pure ' ')
contents
------------------------------------------------------------------------------
-- unhelpfully, the spec mentions "old-style" cookies that don't have quotes
-- around the value. wonderful.
pWord :: Parser ByteString
pWord = pQuotedString <|> (takeWhile (/= ';'))
------------------------------------------------------------------------------
pQuotedString :: Parser ByteString
pQuotedString = q *> quotedText <* q
where
quotedText = (S.concat . reverse) <$> f []
f soFar = do
t <- takeWhile qdtext
let soFar' = t:soFar
-- RFC says that backslash only escapes for <">
choice [ string "\\\"" *> f ("\"" : soFar')
, pure soFar' ]
q = char '\"'
qdtext = matchAll [ isRFCText, (/= '\"'), (/= '\\') ]
------------------------------------------------------------------------------
{-# INLINE isRFCText #-}
isRFCText :: Char -> Bool
isRFCText = not . isControl
------------------------------------------------------------------------------
{-# INLINE matchAll #-}
matchAll :: [ Char -> Bool ] -> Char -> Bool
matchAll x c = and $ map ($ c) x
------------------------------------------------------------------------------
pAvPairs :: Parser [(ByteString, ByteString)]
pAvPairs = do
a <- pAvPair
b <- many (pSpaces *> char ';' *> pSpaces *> pAvPair)
return $! a:b
------------------------------------------------------------------------------
{-# INLINE pAvPair #-}
pAvPair :: Parser (ByteString, ByteString)
pAvPair = do
key <- pToken <* pSpaces
val <- liftM trim (option "" $ char '=' *> pSpaces *> pWord)
return $! (key, val)
------------------------------------------------------------------------------
pParameter :: Parser (ByteString, ByteString)
pParameter = do
key <- pToken <* pSpaces
val <- liftM trim (char '=' *> pSpaces *> pWord)
return $! (trim key, val)
------------------------------------------------------------------------------
{-# INLINE trim #-}
trim :: ByteString -> ByteString
trim = snd . S.span isSpace . fst . S.spanEnd isSpace
------------------------------------------------------------------------------
pValueWithParameters :: Parser (ByteString, [(CI ByteString, ByteString)])
pValueWithParameters = do
value <- liftM trim (pSpaces *> takeWhile (/= ';'))
params <- many pParam
return (value, map (first CI.mk) params)
where
pParam = pSpaces *> char ';' *> pSpaces *> pParameter
------------------------------------------------------------------------------
pContentTypeWithParameters :: Parser ( ByteString
, [(CI ByteString, ByteString)] )
pContentTypeWithParameters = do
value <- liftM trim (pSpaces *> takeWhile (not . isSep))
params <- many (pSpaces *> satisfy isSep *> pSpaces *> pParameter)
return $! (value, map (first CI.mk) params)
where
isSep c = c == ';' || c == ','
------------------------------------------------------------------------------
{-# INLINE pToken #-}
pToken :: Parser ByteString
pToken = takeWhile isToken
------------------------------------------------------------------------------
{-# INLINE isToken #-}
isToken :: Char -> Bool
isToken c = FS.memberChar c tokenTable
------------------------------------------------------------------------------
tokenTable :: FastSet
tokenTable = generateFS (f . toEnum . fromEnum)
where
f = matchAll [ isAscii
, not . isControl
, not . isSpace
, not . flip elem [ '(', ')', '<', '>', '@', ',', ';'
, ':', '\\', '\"', '/', '[', ']'
, '?', '=', '{', '}' ]
]
------------------
-- Url encoding --
------------------
------------------------------------------------------------------------------
{-# INLINE parseToCompletion #-}
parseToCompletion :: Parser a -> ByteString -> Maybe a
parseToCompletion p s = toResult $ finish r
where
r = parse p s
toResult (Done _ c) = Just c
toResult _ = Nothing
------------------------------------------------------------------------------
type DList a = [a] -> [a]
pUrlEscaped :: Parser ByteString
pUrlEscaped = do
sq <- nextChunk id
return $! S.concat $ sq []
where
--------------------------------------------------------------------------
nextChunk :: DList ByteString -> Parser (DList ByteString)
nextChunk !s = (endOfInput *> pure s) <|> do
c <- anyChar
case c of
'+' -> plusSpace s
'%' -> percentEncoded s
_ -> unEncoded c s
--------------------------------------------------------------------------
percentEncoded :: DList ByteString -> Parser (DList ByteString)
percentEncoded !l = do
hx <- take 2
when (S.length hx /= 2 || (not $ S.all isHexDigit hx)) $
fail "bad hex in url"
let code = w2c ((unsafeFromHex hx) :: Word8)
nextChunk $ l . ((S.singleton code) :)
--------------------------------------------------------------------------
unEncoded :: Char -> DList ByteString -> Parser (DList ByteString)
unEncoded !c !l' = do
let l = l' . ((S.singleton c) :)
bs <- takeTill (flip elem ['%', '+'])
if S.null bs
then nextChunk l
else nextChunk $ l . (bs :)
--------------------------------------------------------------------------
plusSpace :: DList ByteString -> Parser (DList ByteString)
plusSpace l = nextChunk (l . ((S.singleton ' ') :))
------------------------------------------------------------------------------
-- "...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'(),"
-- [not including the quotes - ed], and reserved characters used for their
-- reserved purposes may be used unencoded within a URL."
------------------------------------------------------------------------------
-- | Decodes an URL-escaped string (see
-- <http://tools.ietf.org/html/rfc2396.html#section-2.4>)
urlDecode :: ByteString -> Maybe ByteString
urlDecode = parseToCompletion pUrlEscaped
{-# INLINE urlDecode #-}
------------------------------------------------------------------------------
-- | URL-escapes a string (see
-- <http://tools.ietf.org/html/rfc2396.html#section-2.4>)
urlEncode :: ByteString -> ByteString
urlEncode = toByteString . urlEncodeBuilder
{-# INLINE urlEncode #-}
------------------------------------------------------------------------------
-- | URL-escapes a string (see
-- <http://tools.ietf.org/html/rfc2396.html#section-2.4>) into a 'Builder'.
urlEncodeBuilder :: ByteString -> Builder
urlEncodeBuilder = go mempty
where
go !b !s = maybe b' esc (S.uncons y)
where
(x,y) = S.span (flip FS.memberChar urlEncodeTable) s
b' = b `mappend` fromByteString x
esc (c,r) = let b'' = if c == ' '
then b' `mappend` fromWord8 (c2w '+')
else b' `mappend` hexd c
in go b'' r
------------------------------------------------------------------------------
urlEncodeTable :: FastSet
urlEncodeTable = generateFS f
where
f c = any ($ (w2c c)) [\x -> isAscii x && isAlphaNum x,
flip elem [ '$', '_', '-', '.', '!'
, '*' , '\'', '(', ')', ',' ] ]
------------------------------------------------------------------------------
hexd :: Char -> Builder
hexd c0 = fromWord8 (c2w '%') `mappend` fromWord8 hi `mappend` fromWord8 low
where
!c = c2w c0
toDigit = c2w . intToDigit
!low = toDigit $ fromEnum $ c .&. 0xf
!hi = toDigit $ (c .&. 0xf0) `shiftr` 4
shiftr (W8# a#) (I# b#) = I# (word2Int# (uncheckedShiftRL# a# b#))
------------------------------------------------------------------------------
finish :: Result a -> Result a
finish (Partial f) = flip feed "" $ f ""
finish x = x
---------------------------------------
-- application/x-www-form-urlencoded --
---------------------------------------
------------------------------------------------------------------------------
-- | Parses a string encoded in @application/x-www-form-urlencoded@ format.
parseUrlEncoded :: ByteString -> Map ByteString [ByteString]
parseUrlEncoded s = foldr ins Map.empty decoded
where
--------------------------------------------------------------------------
ins (!k,v) !m = Map.insertWith' (++) k [v] m
--------------------------------------------------------------------------
parts :: [(ByteString,ByteString)]
parts = map breakApart $
S.splitWith (\c -> c == '&' || c == ';') s
--------------------------------------------------------------------------
breakApart = (second (S.drop 1)) . S.break (== '=')
--------------------------------------------------------------------------
urldecode = parseToCompletion pUrlEscaped
--------------------------------------------------------------------------
decodeOne (a,b) = do
!a' <- urldecode a
!b' <- urldecode b
return $! (a',b')
--------------------------------------------------------------------------
decoded = go id parts
where
go !dl [] = dl []
go !dl (x:xs) = maybe (go dl xs)
(\p -> go (dl . (p:)) xs)
(decodeOne x)
------------------------------------------------------------------------------
buildUrlEncoded :: Map ByteString [ByteString] -> Builder
buildUrlEncoded m = mconcat builders
where
builders = intersperse (fromWord8 $ c2w '&') $
concatMap encodeVS $ Map.toList m
encodeVS (k,vs) = map (encodeOne k) vs
encodeOne k v = mconcat [ urlEncodeBuilder k
, fromWord8 $ c2w '='
, urlEncodeBuilder v ]
------------------------------------------------------------------------------
printUrlEncoded :: Map ByteString [ByteString] -> ByteString
printUrlEncoded = toByteString . buildUrlEncoded
-----------------------
-- utility functions --
-----------------------
------------------------------------------------------------------------------
strictize :: L.ByteString -> ByteString
strictize = S.concat . L.toChunks
------------------------------------------------------------------------------
unsafeFromHex :: (Enum a, Num a, Bits a) => ByteString -> a
unsafeFromHex = S.foldl' f 0
where
sl = unsafeShiftL
f !cnt !i = sl cnt 4 .|. nybble i
nybble c | c >= '0' && c <= '9' = toEnum $! fromEnum c - fromEnum '0'
| c >= 'a' && c <= 'f' = toEnum $! 10 + fromEnum c - fromEnum 'a'
| c >= 'A' && c <= 'F' = toEnum $! 10 + fromEnum c - fromEnum 'A'
| otherwise = error $ "bad hex digit: " ++ show c
{-# INLINE unsafeFromHex #-}
------------------------------------------------------------------------------
unsafeFromInt :: (Enum a, Num a, Bits a) => ByteString -> a
unsafeFromInt = S.foldl' f 0
where
f !cnt !i = cnt * 10 + toEnum (digitToInt i)
{-# INLINE unsafeFromInt #-}
| jonpetterbergman/wai-snap | src/Snap/Internal/Parsing.hs | bsd-3-clause | 16,493 | 0 | 17 | 4,045 | 3,537 | 1,880 | 1,657 | 253 | 4 |
myEnumFromTo :: Integer -> Integer -> [Integer]
myEnumFromTo m n | m > n = []
myEnumFromTo m n = m : myEnumFromTo (m + 1) n
| YoshikuniJujo/funpaala | samples/16_return_list/enum.hs | bsd-3-clause | 124 | 0 | 8 | 27 | 65 | 32 | 33 | 3 | 1 |
module CLaSH.QuickCheck.Instances.Signal () where
import Test.QuickCheck
import CLaSH.Prelude
import CLaSH.Prelude.Explicit
instance Arbitrary a => Arbitrary (Signal' clk a) where
arbitrary = fromList <$> infiniteList
--TODO: what does it mean to shrink an infinite stream
--shrink x = [] : (fmap fromList $ shrink $ CLaSH.Prelude.sample x)
| Ericson2314/clash-prelude-quickcheck | src/CLaSH/QuickCheck/Instances/Signal.hs | bsd-3-clause | 353 | 0 | 7 | 58 | 61 | 36 | 25 | 6 | 0 |
-- | <http://programmingpraxis.com/2015/09/11/finding-the-median/ Finding the median>
--
-- The median of an array is the value in the middle if the array
-- was sorted; if the array has an odd number of items n, the median
-- is the (n+1)/2’th largest item in the array (which is also the
-- (n+1)/2’th smallest item in the array), and if the array has an
-- even number of items n, the median is the arithmetic average of the
-- n/2’th smallest item in the array and the n/2’th largest item in
-- the array. For instance, the median of the array [2,4,5,7,3,6,1] is
-- 4 and the median of the array [5,2,1,6,3,4] is 3.5.
--
-- Your task is to write a program that takes an array of 8-bit
-- integers (possibly but not necessarily in sort) and finds the
-- median value in the array; you should find an algorithm that takes
-- linear time and constant space. When you are finished, you are
-- welcome to read or run a suggested solution, or to post your own
-- solution or discuss the exercise in the comments below.
--
-- Note: I didn't have to use any of the unsafe functions below.
-- The safe versions are the default, but I wanted to show that
-- you can write C in Haskell if you want.
--
-- Also, all the implementations are sequential, not parallel.
{-# LANGUAGE BangPatterns #-}
module VectorExample where
import qualified Data.Word as Word
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as M
import qualified Data.Vector.Algorithms.Radix as Radix
-- | Assume 8-bit unsigned integer.
type Value = Word.Word8
-- | What to return as median when there is one.
type MedianValue = Double
-- | This is an obvious implementation, basically the specification.
-- The use of radix sort makes this linear in time, but a copy of
-- the original array is required.
inefficientSpaceMedian :: V.Vector Value -> Maybe MedianValue
inefficientSpaceMedian values
| V.null values = Nothing
| odd len = Just (fromIntegral (atSorted midIndex))
| otherwise = Just (averageValue (atSorted midIndex)
(atSorted (succ midIndex)))
where
len = V.length values
midIndex = pred (succ len `div` 2)
-- Make a local mutable copy to sort.
atSorted = V.unsafeIndex (V.modify Radix.sort values)
-- | Average of two values.
averageValue :: Value -> Value -> MedianValue
averageValue a b = (fromIntegral a + fromIntegral b) / 2
-- | Number of occurrences of an 8-bit unsigned value.
-- We assume no overflow beyond 'Int' range.
type CountOfValue = Int
-- | Create a table of counts for each possible value, since we know
-- the number of values is small and finite.
constantSpaceMedian :: V.Vector Value -> Maybe MedianValue
constantSpaceMedian values
| V.null values = Nothing
| odd len = Just (findMid 0 (numToCount - countOf 0))
| otherwise = Just (findMid2 0 (numToCount - countOf 0))
where
len = V.length values
-- How many sorted elements to count off, to reach first median value.
numToCount = succ len `div` 2
-- Make efficient table of counts for each possible value.
countOf = V.unsafeIndex (makeCountsMutably values)
findMid !i !numRemaining
| numRemaining <= 0 = fromIntegral i
| otherwise = findMid (succ i) (numRemaining - countOf (succ i))
findMid2 !i !numRemaining =
case numRemaining `compare` 0 of
LT -> fromIntegral i -- median is duplicated, don't need average
GT -> findMid2 (succ i) (numRemaining - countOf (succ i))
EQ -> midAverage (succ i) (countOf (succ i))
where
midAverage j 0 = midAverage (succ j) (countOf (succ j))
midAverage j _ = averageValue (fromIntegral i) (fromIntegral j)
-- | Use local mutation for efficiency in creating a table of counts,
-- looping through to update it, and freezing the result to return.
makeCountsMutably
:: V.Vector Value -- ^ values seen
-> V.Vector CountOfValue -- ^ value => count
makeCountsMutably values = V.create $ do
counts <- M.replicate numPossibleValues 0
V.forM_ values $
M.unsafeModify counts succ . fromIntegral
return counts
-- | 256, in our case.
numPossibleValues :: Int
numPossibleValues = fromIntegral (maxBound :: Value) + 1
-- | Make table of counts without using 'MVector'.
makeCountsPurely
:: V.Vector Value
-> V.Vector CountOfValue
makeCountsPurely =
V.unsafeAccumulate (+) (V.replicate numPossibleValues 0)
. V.map (\v -> (fromIntegral v, 1))
| FranklinChen/twenty-four-days2015-of-hackage | src/VectorExample.hs | bsd-3-clause | 4,467 | 0 | 16 | 925 | 825 | 435 | 390 | 54 | 4 |
{-# LANGUAGE ScopedTypeVariables, BangPatterns, GADTs, FlexibleContexts,
FlexibleInstances, TypeFamilies, EmptyDataDecls #-}
-- | Module for definitions of detector level physical objects
module HEP.Parser.LHCOAnalysis.PhysObj (
-- * Individual Physical Object
-- | Types for reconstructed physical objects
Photon, Electron, Muon, Tau, Jet, BJet, MET,
-- * Collective Object
ObjTag(..), PhyObj(..), MomObj(..), ChargedObj(..),
MultiTrkObj(..), EachObj(..), Lepton12Obj(..),
JetBJetObj(..),
-- * Object Properties
TauProng(..),
ECharge(..),
FourMomentum,
fst3,
snd3,
trd3,
fourmomfrometaphipt,
fourmomfrometaphiptm_new,
pxpyFromPhiPT,
etatocosth,
ntrktoecharge,
ntrktotauprong,
ptcompare,
ptordering,
headsafe,
first_positive,
first_negative,
prettyprint,
prettyprintevent,
isElectron,
isMuon,
-- * Event
PhyEvent,
PhyEventClassified(..),
zeroevent,
sortPhyEventC,
numofobj,
leptonlst,
jetOrBJetLst,
etaphipt,
etaphiptm
) where
import Data.Function
import Data.Binary
import Data.List (sortBy)
data Photon
data Electron
data Muon
data Tau
data Jet
data BJet
data MET
-- | GADT type for reconstructed physical objects
data ObjTag a where
Photon :: ObjTag Photon
Electron :: ObjTag Electron
Muon :: ObjTag Muon
Tau :: ObjTag Tau
Jet :: ObjTag Jet
BJet :: ObjTag BJet
MET :: ObjTag MET
data TauProng = Prong1 | Prong3
data ECharge = CPlus | CMinus
-- | FourMomentum is a type synonym of (E,px,py,pz)
type FourMomentum = (Double,Double,Double,Double)
fst3 :: (a,b,c) -> a
fst3 (a,_,_) = a
snd3 :: (a,b,c) -> b
snd3 (_,a,_) = a
trd3 :: (a,b,c) -> c
trd3 (_,_,a) = a
fourmomfrometaphipt :: (Double,Double,Double) -> FourMomentum
fourmomfrometaphipt !etaphipt = (p0, p1, p2, p3 )
where eta' = fst3 etaphipt
phi' = snd3 etaphipt
pt' = trd3 etaphipt
costh = etatocosth eta'
sinth = sqrt (1 - costh*costh)
p1 = pt' * cos phi'
p2 = pt' * sin phi'
p3 = pt' * costh / sinth
p0 = pt' / sinth
etatocosth :: Double -> Double
etatocosth !et = ( exp (2.0 * et) - 1 ) / (exp (2.0 * et) + 1 )
ntrktoecharge :: Double -> ECharge
ntrktoecharge ntrk = if ntrk > 0 then CPlus else CMinus
ntrktotauprong :: Double -> TauProng
ntrktotauprong ntrk = let absntrk = abs ntrk
in if absntrk > 0.9 && absntrk < 1.1
then Prong1
else Prong3
data PhyObj a where
ObjPhoton :: { etaphiptphoton :: !(Double, Double, Double)
} -> PhyObj Photon
ObjElectron :: { etaphiptelectron :: !(Double, Double, Double)
, chargeelectron :: !ECharge
} -> PhyObj Electron
ObjMuon :: { etaphiptmuon :: !(Double, Double, Double)
, chargemuon :: !ECharge
} -> PhyObj Muon
ObjTau :: { etaphipttau :: !(Double, Double, Double)
, chargetau :: !ECharge
, prongtau :: !TauProng
} -> PhyObj Tau
ObjJet :: { etaphiptjet :: !(Double, Double, Double)
, mjet :: !Double
, numtrkjet :: !Int
} -> PhyObj Jet
ObjBJet :: { etaphiptbjet :: !(Double, Double, Double)
, mbjet :: !Double
, numtrkbjet :: !Int
} -> PhyObj BJet
ObjMET :: { phiptmet :: !(Double,Double)
} -> PhyObj MET
class MomObj a where
fourmom :: a -> FourMomentum
eta :: a -> Double
phi :: a -> Double
pt :: a -> Double
mass :: a -> Double
ptcompare :: MomObj a => a -> a -> Ordering
ptcompare x y = compare (pt x) (pt y)
class ChargedObj a where
charge :: a -> Int
headsafe :: [a] -> Maybe a
headsafe [] = Nothing
headsafe (x:_) = Just x
first_positive :: (ChargedObj a) => [a] -> Maybe a
first_positive lst = headsafe $ dropWhile (\x->(charge x < 0)) lst
first_negative :: (ChargedObj a) => [a] -> Maybe a
first_negative lst = headsafe $ dropWhile (\x->(charge x > 0)) lst
class MultiTrkObj a where
numoftrk :: a -> Int
-- | Heterotic container for all the PhyObj
data EachObj where
EO :: (Show (PhyObj a), Binary (PhyObj a)) => PhyObj a -> EachObj
-- | Heterotic container for 1st and 2nd gen charged leptons.
data Lepton12Obj where
LO_Elec :: PhyObj Electron -> Lepton12Obj
LO_Muon :: PhyObj Muon -> Lepton12Obj
isElectron :: Lepton12Obj -> Bool
isElectron (LO_Elec _) = True
isElectron (LO_Muon _) = False
isMuon :: Lepton12Obj -> Bool
isMuon = not . isElectron
-- | Heterotic container for jet and bjet.
data JetBJetObj where
JO_Jet :: PhyObj Jet -> JetBJetObj
JO_BJet :: PhyObj BJet -> JetBJetObj
instance ChargedObj Lepton12Obj where
charge (LO_Elec e) = charge e
charge (LO_Muon m) = charge m
instance MomObj Lepton12Obj where
fourmom (LO_Elec e) = fourmom e
fourmom (LO_Muon m) = fourmom m
eta (LO_Elec e) = eta e
eta (LO_Muon m) = eta m
phi (LO_Elec e) = phi e
phi (LO_Muon m) = phi m
pt (LO_Elec e) = pt e
pt (LO_Muon m) = pt m
instance MomObj JetBJetObj where
fourmom (JO_Jet j) = fourmom j
fourmom (JO_BJet b) = fourmom b
eta (JO_Jet j) = eta j
eta (JO_BJet b) = eta b
phi (JO_Jet j) = phi j
phi (JO_BJet b) = phi b
pt (JO_Jet j) = pt j
pt (JO_BJet b) = pt b
pxpyFromPhiPT :: (Double,Double) -> (Double,Double)
pxpyFromPhiPT (phi',pt') = (pt' * cos phi' , pt' * sin phi' )
leptonlst :: PhyEventClassified -> [(Int,Lepton12Obj)]
leptonlst p = let el = map (\(x,y)->(x,LO_Elec y)) (electronlst p)
ml = map (\(x,y)->(x,LO_Muon y)) (muonlst p)
in ptordering (ml ++ el)
jetOrBJetLst :: PhyEventClassified -> [(Int,JetBJetObj)]
jetOrBJetLst p = let jl = map (\(x,y)->(x,JO_Jet y)) (jetlst p)
bl = map (\(x,y)->(x,JO_BJet y)) (bjetlst p)
in ptordering (jl ++ bl)
ptordering :: (MomObj a) => [(Int,a)] -> [(Int,a)]
ptordering lst = sortBy ((flip ptcompare) `on` snd) lst
type PhyEvent = [(Int,EachObj)]
data PhyEventClassified = PhyEventClassified
{ eventid :: !Int,
photonlst :: ![(Int,(PhyObj Photon))],
electronlst :: ![(Int,(PhyObj Electron))],
muonlst :: ![(Int,(PhyObj Muon))],
taulst :: ![(Int,(PhyObj Tau))],
jetlst :: ![(Int,(PhyObj Jet))],
bjetlst :: ![(Int,(PhyObj BJet))],
met :: !(PhyObj MET) }
zeroevent :: PhyEventClassified
zeroevent = PhyEventClassified (-1) [] [] [] [] [] [] (ObjMET (0,0))
-- | sort PhysEventClassfied with PT ordering
sortPhyEventC :: PhyEventClassified -> PhyEventClassified
sortPhyEventC p = let eid = eventid p
phl = photonlst p
ell = electronlst p
mul = muonlst p
tal = taulst p
jel = jetlst p
bjl = bjetlst p
met'= met p
phl' = sortBy ((flip ptcompare) `on` snd) phl
ell' = sortBy ((flip ptcompare) `on` snd) ell
mul' = sortBy ((flip ptcompare) `on` snd) mul
tal' = sortBy ((flip ptcompare) `on` snd) tal
jel' = sortBy ((flip ptcompare) `on` snd) jel
bjl' = sortBy ((flip ptcompare) `on` snd) bjl
in PhyEventClassified eid phl' ell' mul' tal' jel' bjl' met'
-- | num of object in one event
numofobj :: ObjTag a -> PhyEventClassified -> Int
numofobj Photon p = Prelude.length (photonlst p)
numofobj Electron p = Prelude.length (electronlst p)
numofobj Muon p = Prelude.length (muonlst p)
numofobj Tau p = Prelude.length (taulst p)
numofobj Jet p = Prelude.length (jetlst p)
numofobj BJet p = Prelude.length (bjetlst p)
numofobj MET _ = 1
-- From here on, I am defining the instances.
instance Binary (TauProng) where
put (Prong1) = putWord8 1
put (Prong3) = putWord8 3
get = do tag <- getWord8
return $ case tag of
1 -> Prong1
3 -> Prong3
_ -> error "not a TauProng"
instance Binary (ECharge) where
put (CPlus) = putWord8 1
put (CMinus) = putWord8 (-1)
get = do tag <- getWord8
tag `seq` return $ case tag of
1 -> CPlus
-1 -> CMinus
_ -> error "not a ECharge"
instance Binary (PhyObj Photon) where
put (ObjPhoton x) = putWord8 100 >> put x
get = do getWord8
x <- get
x `seq` return (ObjPhoton x)
instance Binary (PhyObj Electron) where
put (ObjElectron x y) = putWord8 101 >> put x >> put y
get = do {-# SCC "Electron8" #-} getWord8
x <- {-# SCC "Electronx" #-} get
y <- {-# SCC "Electrony" #-} get
x `seq` y `seq` return (ObjElectron x y)
instance Binary (PhyObj Muon) where
put (ObjMuon x y) = putWord8 102 >> put x >> put y
get = do getWord8
x <- get
y <- get
x `seq` y `seq` return (ObjMuon x y)
instance Binary (PhyObj Tau) where
put (ObjTau x y z) = putWord8 103 >> put x >> put y >> put z
get = do getWord8
x <- get
y <- get
z <- get
x `seq` y `seq` z `seq` return (ObjTau x y z)
instance Binary (PhyObj Jet) where
put (ObjJet x y z) = putWord8 104 >> put x >> put y >> put z
get = do getWord8
x <- get
y <- get
z <- get
x `seq` y `seq` z `seq` return (ObjJet x y z)
instance Binary (PhyObj BJet) where
put (ObjBJet x y z) = putWord8 105 >> put x >> put y >> put z
get = do getWord8
x <- get
y <- get
z <- get
x `seq` y `seq` z `seq` return (ObjBJet x y z)
instance Binary (PhyObj MET) where
put (ObjMET x) = putWord8 106 >> put x
get = do getWord8
x <- get
x `seq` return (ObjMET x)
prettyprint :: PhyObj a -> String
prettyprint (ObjPhoton x) = "photon:" ++ show x
prettyprint (ObjElectron x _) = "electron:" ++ show x
prettyprint (ObjMuon x _) = "muon:" ++ show x
prettyprint (ObjTau x _ _) = "tau:" ++ show x
prettyprint (ObjJet x _ _) = "jet:" ++ show x
prettyprint (ObjBJet x _ _) = "bjet:" ++ show x
prettyprint (ObjMET x) = "met:"++ show x
prettyprintevent :: PhyEventClassified -> String
prettyprintevent p = "event " ++ show (eventid p) ++ "\n"
++ printeach (photonlst p) ++ "\n"
++ printeach (electronlst p) ++ "\n"
++ printeach (muonlst p) ++ "\n"
++ printeach (taulst p) ++ "\n"
++ printeach (jetlst p) ++ "\n"
++ printeach (bjetlst p) ++ "\n"
++ prettyprint (met p) ++ "\n"
where printeach :: forall a. [(Int, PhyObj a)] -> String
printeach = concatMap (\(x,y)->("(" ++ show x ++ "," ++ prettyprint y ++ ")"))
instance Show (PhyObj Photon) where
show _ = "(photon)"
instance Show (PhyObj Electron) where
show _ = "(electron)"
instance Show (PhyObj Muon) where
show _ = "(muon)"
instance Show (PhyObj Tau) where
show _ = "(tau)"
instance Show (PhyObj Jet) where
show _ = "(jet)"
instance Show (PhyObj BJet) where
show _ = "(bjet)"
instance Show (PhyObj MET) where
show _ = "(met)"
instance Binary EachObj where
put (EO x) = put x
-- get = getWord8 >> \tag -> get >>= \(x :: (Show (PhyObj a), Binary (PhyObj
{-- get = getWord8 >>= \tag ->
case tag of
100 -> get >>= \(x :: PhyObj Photon) ->
return $ EO x
101 -> get >>= \(x :: PhyObj Electron) ->
return $ EO x
102 -> get >>= \(x :: PhyObj Muon) ->
return $ EO x
103 -> get >>= \(x :: PhyObj Tau) ->
return $ EO x
104 -> get >>= \(x :: PhyObj Jet) ->
return $ EO x
105 -> get >>= \(x :: PhyObj BJet) ->
return $ EO x
106 -> get >>= \(x :: PhyObj MET) ->
return $ EO x --}
get = do tag <- getWord8
case tag of
100 -> do (x :: PhyObj Photon) <- get
return $ EO x
101 -> do (x :: PhyObj Electron) <- get
return $ EO x
102 -> do (x :: PhyObj Muon) <- get
return $ EO x
103 -> do (x :: PhyObj Tau) <- get
return $ EO x
104 -> do (x :: PhyObj Jet) <- get
return $ EO x
105 -> do (x :: PhyObj BJet) <- get
return $ EO x
106 -> do (x :: PhyObj MET) <- get
return $ EO x
_ -> error "strange object"
instance Show EachObj where
show (EO x) = show x
instance Binary PhyEventClassified where
put x = putWord8 300 >> put (eventid x)
>> put (photonlst x)
>> put (electronlst x)
>> put (muonlst x)
>> put (taulst x )
>> put (jetlst x)
>> put (bjetlst x)
>> put (met x)
get = do getWord8
xid <- get
x0 <- get
x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return $ PhyEventClassified xid x0 x1 x2 x3 x4 x5 x6
instance Show PhyEventClassified where
show (PhyEventClassified xid x0 x1 x2 x3 x4 x5 x6) =
"id :" ++ show xid ++ ":" ++
show x0 ++ show x1 ++ show x2 ++ show x3 ++ show x4 ++ show x5 ++ show x6
-- Charged Object
instance ChargedObj (PhyObj Electron) where
charge x = case chargeelectron x of
CPlus -> 1
CMinus -> -1
instance ChargedObj (PhyObj Muon) where
charge x = case chargemuon x of
CPlus -> 1
CMinus -> -1
instance ChargedObj (PhyObj Tau) where
charge x = case chargetau x of
CPlus -> 1
CMinus -> -1
instance MultiTrkObj (PhyObj Tau) where
numoftrk x = case (prongtau x) of
Prong1 -> 1
Prong3 -> 3
instance MultiTrkObj (PhyObj Jet) where
numoftrk = numtrkjet
instance MultiTrkObj (PhyObj BJet) where
numoftrk = numtrkbjet
instance MomObj (PhyObj Photon) where
fourmom = fourmomfrometaphipt . etaphiptphoton
eta = fst3 . etaphiptphoton
phi = snd3 . etaphiptphoton
pt = trd3 . etaphiptphoton
mass = const 0.0
instance MomObj (PhyObj Electron) where
fourmom = fourmomfrometaphipt . etaphiptelectron
eta = fst3 . etaphiptelectron
phi = snd3 . etaphiptelectron
pt = trd3 . etaphiptelectron
mass = const 0.0
instance MomObj (PhyObj Muon) where
fourmom = fourmomfrometaphipt . etaphiptmuon
eta = fst3 . etaphiptmuon
phi = snd3 . etaphiptmuon
pt = trd3 . etaphiptmuon
mass = const 0.0
instance MomObj (PhyObj Tau) where
fourmom = fourmomfrometaphipt . etaphipttau
eta = fst3 . etaphipttau
phi = snd3 . etaphipttau
pt = trd3 . etaphipttau
mass = const 0.0
instance MomObj (PhyObj Jet) where
fourmom j = fourmomfrometaphiptm (mjet j) (etaphiptjet j)
eta = fst3 . etaphiptjet
phi = snd3 . etaphiptjet
pt = trd3 . etaphiptjet
mass = mjet
instance MomObj (PhyObj BJet) where
fourmom bj = fourmomfrometaphiptm (mbjet bj) (etaphiptbjet bj)
eta = fst3 . etaphiptbjet
phi = snd3 . etaphiptbjet
pt = trd3 . etaphiptbjet
mass = mbjet
etaphipt :: (MomObj a) => a -> (Double,Double,Double)
etaphipt p = (eta p, phi p, pt p)
etaphiptm :: (MomObj a) => a -> (Double,Double,Double,Double)
etaphiptm p = (eta p, phi p, pt p, mass p)
fourmomfrometaphiptm !ma (eta',phi',pt') = (p0, p1, p2, p3 )
where costh = etatocosth eta'
sinth = sqrt (1 - costh*costh)
p1 = pt' * cos phi'
p2 = pt' * sin phi'
p3 = pt' * costh / sinth
p0 = sqrt (p1^2 + p2^2 + p3^2 + ma^2)
fourmomfrometaphiptm_new (eta',phi',pt',ma) = fourmomfrometaphiptm ma (eta',phi',pt')
| wavewave/LHCOAnalysis-type | src/HEP/Parser/LHCOAnalysis/PhysObj.hs | bsd-3-clause | 16,628 | 2 | 23 | 5,792 | 5,665 | 2,961 | 2,704 | -1 | -1 |
-- | TAG a stack project based on snapshot versions
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Stack.Tag where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import qualified Control.Exception as E
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Traversable as T
import Control.Monad.Reader
import Data.Maybe
import Data.Text (Text)
import System.Directory
import System.Process
import System.Exit
import Control.Concurrent.Async.Pool
data StackTagOpts
= StackTagOpts
{
-- | Location of the stack.yaml to generate
-- tags for
optsStackYaml :: !(Maybe FilePath)
-- | Verbose output
, optsVerbose :: !Bool
-- | Flag to ignore any cached tags and re-run the tagger
, noCache :: !Bool
-- TODO flags
-- set tag command, hasktags, hothasktags, etc
-- , tagCommand :: !Tagger
-- Set format etags/ctags
-- , tagFormat :: !TagFmt
-- Only tag dependencies explicitly mentioned in
-- the cabal file.
-- , noTransitive :: !Bool
} deriving Show
data Tagger = Hasktags
| HotHasktags
| OtherTagger Text
deriving Show
data TagFmt = CTag
| ETag
| OtherFmt Text
deriving Show
type TagOutput = FilePath
type SourceDir = FilePath
data TagCmd = TagCmd Tagger TagFmt TagOutput SourceDir deriving Show
newtype StackTag a = StackTag {
runStackTag :: ReaderT StackTagOpts IO a
} deriving (
Functor
, Applicative
, Monad
, MonadReader StackTagOpts
, MonadIO
)
defStackOpts :: StackTagOpts
defStackOpts = StackTagOpts Nothing False True
stackTag :: StackTagOpts -> IO ()
stackTag = runReaderT (runStackTag app)
where
app = do chkStackCompatible
chkHaskTags
chkIsStack
sources <- stkPaths
depSources <- stkDepSources
tagSources sources depSources
--------------------------------------------------------------------------
--------------------------------------------------------------------------
io :: MonadIO m => IO a -> m a
io = liftIO
p :: (MonadIO m) => String -> m ()
p = io . putStrLn
-- | Run a command using the `stack' command-line tool
-- with a list of arguments
runStk :: [String] -> IO (ExitCode, String, String)
runStk args
= readProcessWithExitCode "stack" args []
chkIsStack :: StackTag ()
chkIsStack = do
StackTagOpts {optsStackYaml=stackYaml} <- ask
sYaml <- io $ doesFileExist "stack.yaml"
case stackYaml of
Nothing -> unless sYaml $ error "stack.yaml not found or specified!"
_ -> return ()
chkHaskTags :: StackTag ()
chkHaskTags = do
ht <- io $ findExecutable "hasktags"
case ht of
Just p -> return ()
Nothing -> error "You must have hasktags installed. Run 'stack install hasktags'."
--- | Check whether the current version of stack
-- is compatible by trying to run `stack list-depenencies --help`.
chkStackCompatible :: StackTag ()
chkStackCompatible = do
(exitc,out,_) <- io $ runStk ["list-dependencies", "--help"]
case exitc of
ExitSuccess -> return ()
ExitFailure _e ->
p (show exitc) >> error "You need stack version 0.1.2.2 or higher installed and in your PATH to use stack-tag"
-- | Get a list of relavant directories from stack using
-- the @stack path@ command
stkPaths :: StackTag [(Text,[Text])]
stkPaths = do
(_,ps,_) <- io $ runStk ["path"]
return (parsePaths ps)
where
parsePaths = map parsePath . T.lines . T.pack
parsePath ps = let (k,vs) = T.breakOn ":" ps
in (k, splitAndStrip vs)
splitAndStrip = filter (not . T.null) . map T.strip . T.splitOn ":"
-- | Get a list of dependencies using:
-- @stack --list-dependencies --separator=-@
stkDepSources :: StackTag [String]
stkDepSources = do
(_exitc,ls,_) <- io $ runStk ["list-dependencies", "--separator=-"]
return $ lines ls
--------------------------------------------------------------------------
--------------------------------------------------------------------------
tagSources :: [(Text,[Text])] -> [FilePath] -> StackTag ()
tagSources srcs depsrcs = do
let srcDir = lookup "project-root" srcs
let tagroot = T.unpack . fromMaybe "." . listToMaybe . fromMaybe [] $ srcDir
-- alternative pooled
depTagFiles <- parTag srcs depsrcs
-- map a tag command over all provided sources
let cmd = TagCmd Hasktags ETag "stack.tags" tagroot
p $ "Running Tagger => " ++ show cmd
thisProj <- io $ runTagger cmd
p "Merging TAGS"
taggedSrcs <- T.traverse (io . readFile) (catMaybes (thisProj : depTagFiles))
let xs = concat $ fmap lines taggedSrcs
ys = if False then (Set.toList . Set.fromList) xs else xs
io $ writeFile "TAGS" $ unlines ys
parTag :: [(Text, [Text])] -> [FilePath] -> StackTag [Maybe FilePath]
parTag srcs depsrcs = do
StackTagOpts {noCache=nocache} <- ask
-- control the number of jobs by using capabilities Currently,
-- capabilities creates a few too many threads which saturates the
-- CPU and network connection. For now, it's manually set to 3 until
-- a better threading story is figured out.
--
-- io $ mapCapabilityPool (tagDependency nocache srcs) depsrcs
io $ mapPool 3 (tagDependency nocache srcs) depsrcs
-- | Tag a single dependency
tagDependency :: Bool -> [(Text, [Text])] -> FilePath -> IO (Maybe FilePath)
tagDependency nocache stkpaths dep = do
let msg = "No 'snapshot-install-root' found, aborting."
fatal = error ("Fatal error tagging " ++ dep ++ ". " ++ msg)
(snapRoot:_) = fromMaybe fatal (lookup "snapshot-install-root" stkpaths)
dir = T.unpack snapRoot ++ "/packages" ++ "/" ++ dep
tagFile = dir ++ "/TAGS"
-- HACK as of Aug 5 2015, `stack unpack` can only download sources
-- into the current directory. Therefore, we move the source to
-- the correct snapshot location. This could/should be fixed in
-- the stack source (especially since --haddock has similar
-- behavior). A quick solution to avoid this might be to run the
-- entire function in the target directory
readProcess "rm" ["--preserve-root", "-rf", dep] []
exists <- doesDirectoryExist dir
tagged <- doesFileExist tagFile
if exists
then p $ "Cached version of " ++ dep ++ " found"
else p $ "No cached version of " ++ dep ++ " found"
unless exists $ void $ do
createDirectoryIfMissing True dir
p $ "Unpacking " ++ dep
(ec,stout,_) <- runStk ["unpack", dep]
case ec of
ExitFailure _ -> void $ p stout
ExitSuccess -> void $ do
p $ "Moving " ++ dep ++ " to snapshot location " ++ dir
readProcess "mv" [dep,dir] []
if tagged && nocache
then return (Just tagFile)
else do p $ "Tagging " ++ dep
runTagger (TagCmd Hasktags ETag tagFile dir)
`E.catch` handleError
where
handleError (E.SomeException err) = p (show err) >> return Nothing
runTagger :: MonadIO m => TagCmd -> m (Maybe TagOutput)
runTagger (TagCmd t fmt to fp)
= do (ec,stout,_) <- io $ readProcessWithExitCode
(tagExe t)
[tagFmt fmt, "-R", "--ignore-close-implementation", "--output", to, fp]
[]
case ec of
ExitFailure _ -> p stout >> return Nothing
ExitSuccess -> return (Just to)
tagExe :: Tagger -> String
tagExe Hasktags = "hasktags"
tagExe _ = error "Tag command not supported. Feel free to create an issue at https://github.com/creichert/stack-tag"
tagFmt :: TagFmt -> String
tagFmt ETag = "--etags"
tagFmt _ = error "Tag format not supported. Feel free to create an issue at https://github.com/creichert/stack-tag"
| CodyReichert/stack-tag | src/Stack/Tag.hs | bsd-3-clause | 7,990 | 0 | 19 | 2,022 | 1,880 | 980 | 900 | 156 | 4 |
module TestFramework (
assert_, assertEqual_, assertEqual2_, assertNotNull_, assertNull_,
assertSeqEqual_,
assertLambdabot_,
tests, random, io80,
HU.Test(..), runTestTT
) where
import Data.Char
import IO ( stderr )
import Data.List ( (\\) )
import Language.Haskell.TH
import qualified Test.HUnit as HU
import System.Random hiding (random)
import Test.QuickCheck
import Lambdabot.Process
import System.Directory
import qualified Control.OldException as E
type Location = (String, Int)
showLoc :: Location -> String
showLoc (f,n) = f ++ ":" ++ show n
assert_ :: Location -> Bool -> HU.Assertion
assert_ loc False = HU.assertFailure ("assert failed at " ++ showLoc loc)
assert_ loc True = return ()
-- lb
assertLambdabot_ :: Location -> String -> String -> HU.Assertion
assertLambdabot_ loc src expected = do
actual <- echo src
if expected /= actual
then HU.assertFailure (msg actual)
else return ()
where msg a = "assertEqual failed at " ++ showLoc loc ++
"\n expected: " ++ show expected ++ "\n but got: " ++ show a
assertEqual_ :: (Eq a, Show a) => Location -> a -> a -> HU.Assertion
assertEqual_ loc expected actual =
if expected /= actual
then HU.assertFailure msg
else return ()
where msg = "assertEqual failed at " ++ showLoc loc ++
"\n expected: " ++ show expected ++ "\n but got: " ++ show actual
assertEqual2_ :: Eq a => Location -> a -> a -> HU.Assertion
assertEqual2_ loc expected actual =
if expected /= actual
then HU.assertFailure ("assertEqual2' failed at " ++ showLoc loc)
else return ()
assertSeqEqual_ :: (Eq a, Show a) => Location -> [a] -> [a] -> HU.Assertion
assertSeqEqual_ loc expected actual =
let ne = length expected
na = length actual
in case () of
_| ne /= na ->
HU.assertFailure ("assertSeqEqual failed at " ++ showLoc loc
++ "\n expected length: " ++ show ne
++ "\n actual length: " ++ show na)
| not (unorderedEq expected actual) ->
HU.assertFailure ("assertSeqEqual failed at " ++ showLoc loc
++ "\n expected: " ++ show expected
++ "\n actual: " ++ show actual)
| otherwise -> return ()
where unorderedEq l1 l2 =
null (l1 \\ l2) && null (l2 \\ l1)
assertNotNull_ :: Location -> [a] -> HU.Assertion
assertNotNull_ loc [] = HU.assertFailure ("assertNotNull failed at " ++ showLoc loc)
assertNotNull_ _ (_:_) = return ()
assertNull_ :: Location -> [a] -> HU.Assertion
assertNull_ loc (_:_) = HU.assertFailure ("assertNull failed at " ++ showLoc loc)
assertNull_ loc [] = return ()
tests :: String -> Q [Dec] -> Q [Dec]
tests name decs =
do decs' <- decs
let ts = collectTests decs'
e <- [| HU.TestLabel name (HU.TestList $(listE (map mkExp ts))) |]
let lete = LetE decs' e
suiteDec = ValD (VarP (mkName name)) (NormalB lete) []
resDecs = [suiteDec]
--runIO $ putStrLn (pprint resDecs)
return resDecs
where
collectTests :: [Dec] -> [Name]
collectTests [] = []
collectTests (ValD (VarP name) _ _ : rest)
| isTestName (nameBase name) = name : collectTests rest
collectTests (_ : rest) = collectTests rest
isTestName ('t':'e':'s':'t':_) = True
isTestName _ = False
mkExp :: Name -> Q Exp
mkExp name =
let s = nameBase name
in [| HU.TestLabel s (HU.TestCase $(varE name)) |]
-- We use our own test runner, because HUnit print test paths a bit unreadable:
-- If a test list contains a named tests, then HUnit prints `i:n' where i
-- is the index of the named tests and n is the name.
{-
`runTestText` executes a test, processing each report line according
to the given reporting scheme. The reporting scheme's state is
threaded through calls to the reporting scheme's function and finally
returned, along with final count values.
-}
runTestText :: HU.PutText st -> HU.Test -> IO (HU.Counts, st)
runTestText (HU.PutText put us) t = do
put allTestsStr True us
(counts, us') <- HU.performTest reportStart reportError reportFailure us t
us'' <- put (HU.showCounts counts) True us'
return (counts, us'')
where
allTestsStr = unlines ("All tests:" :
map (\p -> " " ++ showPath p) (HU.testCasePaths t))
reportStart ss us = put (HU.showCounts (HU.counts ss)) False us
reportError = reportProblem "Error:" "Error in: "
reportFailure = reportProblem "Failure:" "Failure in: "
reportProblem p0 p1 msg ss us = put line True us
where line = "### " ++ kind ++ path' ++ '\n' : msg
kind = if null path' then p0 else p1
path' = showPath (HU.path ss)
{-
`showPath` converts a test case path to a string, separating adjacent
elements by ':'. An element of the path is quoted (as with `show`)
when there is potential ambiguity.
-}
showPath :: HU.Path -> String
showPath [] = ""
showPath nodes = foldr1 f (map showNode (filterNodes (reverse nodes)))
where f a b = a ++ ":" ++ b
showNode (HU.ListItem n) = show n
showNode (HU.Label label) = safe label (show label)
safe s ss = if ':' `elem` s || "\"" ++ s ++ "\"" /= ss then ss else s
filterNodes (HU.ListItem _ : l@(HU.Label _) : rest) =
l : filterNodes rest
filterNodes [] = []
filterNodes (x:rest) = x : filterNodes rest
{-
`runTestTT` provides the "standard" text-based test controller.
Reporting is made to standard error, and progress reports are
included. For possible programmatic use, the final counts are
returned. The "TT" in the name suggests "Text-based reporting to the
Terminal".
-}
runTestTT :: HU.Test -> IO HU.Counts
runTestTT t = do (counts, 0) <- runTestText (HU.putTextToHandle stderr True) t
return counts
lambdabot = "./lambdabot"
lambdabotHome = ".."
-- run the lambdabot
echo :: String -> IO String
echo cmd = E.handle (\e -> return (show e)) $ do
p <- getCurrentDirectory
setCurrentDirectory lambdabotHome
let s = cmd ++ "\n"
v <- eval lambdabot s clean
setCurrentDirectory p
return v
where
clean s = let f = drop 11 . reverse
in case f (f s) of
[] -> []
x -> init x
eval :: FilePath -> String -> (String -> String) -> IO String
eval binary src scrub = do
(out,_,_) <- popen binary [] (Just src)
return ( scrub out )
random :: Arbitrary a => IO a
random = do
g <- getStdGen
return $ generate 1000 g (arbitrary :: Arbitrary a => Gen a)
io80 :: IO String -> IO String
io80 f = take 80 `fmap` f
instance Arbitrary Char where
-- filters ctrl chars, and chops lines too remember!
arbitrary = elements $ ['a'..'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9']
coarbitrary c = variant (ord c `rem` 4)
| zeekay/lambdabot | testsuite/TestFramework.hs | mit | 6,964 | 0 | 18 | 1,881 | 2,179 | 1,105 | 1,074 | -1 | -1 |
module Database.Persist.Sql.Types
( module Database.Persist.Sql.Types
, SqlBackend, SqlReadBackend (..), SqlWriteBackend (..)
, Statement (..), LogFunc, InsertSqlResult (..)
, readToUnknown, readToWrite, writeToUnknown
, SqlBackendCanRead, SqlBackendCanWrite, SqlReadT, SqlWriteT, IsSqlBackend
, OverflowNatural(..)
, ConnectionPoolConfig(..)
) where
import Control.Exception (Exception(..))
import Control.Monad.Logger (NoLoggingT)
import Control.Monad.Trans.Reader (ReaderT(..))
import Control.Monad.Trans.Resource (ResourceT)
import Data.Pool (Pool)
import Data.Text (Text)
import Data.Time (NominalDiffTime)
import Database.Persist.Sql.Types.Internal
import Database.Persist.Types
data Column = Column
{ cName :: !FieldNameDB
, cNull :: !Bool
, cSqlType :: !SqlType
, cDefault :: !(Maybe Text)
, cGenerated :: !(Maybe Text)
, cDefaultConstraintName :: !(Maybe ConstraintNameDB)
, cMaxLen :: !(Maybe Integer)
, cReference :: !(Maybe ColumnReference)
}
deriving (Eq, Ord, Show)
-- | This value specifies how a field references another table.
--
-- @since 2.11.0.0
data ColumnReference = ColumnReference
{ crTableName :: !EntityNameDB
-- ^ The table name that the
--
-- @since 2.11.0.0
, crConstraintName :: !ConstraintNameDB
-- ^ The name of the foreign key constraint.
--
-- @since 2.11.0.0
, crFieldCascade :: !FieldCascade
-- ^ Whether or not updates/deletions to the referenced table cascade
-- to this table.
--
-- @since 2.11.0.0
}
deriving (Eq, Ord, Show)
data PersistentSqlException = StatementAlreadyFinalized Text
| Couldn'tGetSQLConnection
deriving Show
instance Exception PersistentSqlException
type SqlPersistT = ReaderT SqlBackend
type SqlPersistM = SqlPersistT (NoLoggingT (ResourceT IO))
type ConnectionPool = Pool SqlBackend
-- | Values to configure a pool of database connections. See "Data.Pool" for details.
--
-- @since 2.11.0.0
data ConnectionPoolConfig = ConnectionPoolConfig
{ connectionPoolConfigStripes :: Int -- ^ How many stripes to divide the pool into. See "Data.Pool" for details. Default: 1.
, connectionPoolConfigIdleTimeout :: NominalDiffTime -- ^ How long connections can remain idle before being disposed of, in seconds. Default: 600
, connectionPoolConfigSize :: Int -- ^ How many connections should be held in the connection pool. Default: 10
}
deriving (Show)
-- TODO: Bad defaults for SQLite maybe?
-- | Initializes a ConnectionPoolConfig with default values. See the documentation of 'ConnectionPoolConfig' for each field's default value.
--
-- @since 2.11.0.0
defaultConnectionPoolConfig :: ConnectionPoolConfig
defaultConnectionPoolConfig = ConnectionPoolConfig 1 600 10
-- $rawSql
--
-- Although it covers most of the useful cases, @persistent@'s
-- API may not be enough for some of your tasks. May be you need
-- some complex @JOIN@ query, or a database-specific command
-- needs to be issued.
--
-- To issue raw SQL queries, use 'rawSql'. It does all the hard work of
-- automatically parsing the rows of the result. It may return:
--
-- * An 'Entity', that which 'selectList' returns.
-- All of your entity's fields are
-- automatically parsed.
--
-- * A @'Single' a@, which is a single, raw column of type @a@.
-- You may use a Haskell type (such as in your entity
-- definitions), for example @Single Text@ or @Single Int@,
-- or you may get the raw column value with @Single
-- 'PersistValue'@.
--
-- * A tuple combining any of these (including other tuples).
-- Using tuples allows you to return many entities in one
-- query.
--
-- The only difference between issuing SQL queries with 'rawSql'
-- and using other means is that we have an /entity selection/
-- /placeholder/, the double question mark @??@. It /must/ be
-- used whenever you want to @SELECT@ an 'Entity' from your
-- query. Here's a sample SQL query @sampleStmt@ that may be
-- issued:
--
-- @
-- SELECT ??, ??
-- FROM \"Person\", \"Likes\", \"Object\"
-- WHERE \"Person\".id = \"Likes\".\"personId\"
-- AND \"Object\".id = \"Likes\".\"objectId\"
-- AND \"Person\".name LIKE ?
-- @
--
-- To use that query, you could say
--
-- @
-- do results <- 'rawSql' sampleStmt [\"%Luke%\"]
-- forM_ results $
-- \\( Entity personKey person
-- , Entity objectKey object
-- ) -> do ...
-- @
--
-- Note that 'rawSql' knows how to replace the double question
-- marks @??@ because of the type of the @results@.
-- | A single column (see 'rawSql'). Any 'PersistField' may be
-- used here, including 'PersistValue' (which does not do any
-- processing).
newtype Single a = Single {unSingle :: a}
deriving (Eq, Ord, Show, Read)
| yesodweb/persistent | persistent/Database/Persist/Sql/Types.hs | mit | 4,814 | 0 | 11 | 963 | 564 | 371 | 193 | 70 | 1 |
module Lamdu.Infer.Unify
( unify
) where
import Lamdu.Calc.Type (Type)
import Lamdu.Infer.Internal.Monad (Infer)
import qualified Lamdu.Infer.Internal.Monad as M
import qualified Lamdu.Infer.Internal.Subst as Subst
import Lamdu.Infer.Internal.Unify (unifyUnsafe)
{-# INLINE unify #-}
unify :: Type -> Type -> Infer ()
unify x y =
do
s <- M.getSubst
unifyUnsafe (Subst.apply s x) (Subst.apply s y)
| Peaker/Algorithm-W-Step-By-Step | src/Lamdu/Infer/Unify.hs | gpl-3.0 | 457 | 0 | 10 | 112 | 133 | 79 | 54 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Webbench.Client
(
ClientDone(..),
ClientConfig,
ClientAsync,
ClientOK,
ClientCount
) where
import Control.Exception ( SomeException, handle )
import Control.Concurrent ( forkIO )
import Control.Concurrent.Async ( async, Async )
import qualified Network.Wreq as Wreq
import Data.Pool
import Data.Time.Click ( UTCTime )
import qualified Data.Text as Text
import Data.Text.Encoding ( decodeUTF8 )
import Network.HTTP.Client (
newtype ClientOK = ClientOK ()
data ClientDone = ClientDone
{
clientStartTime :: UTCTime,
clientEndTime :: UTCTime,
clientResult :: Either SomeException Wreq.Status
}
type ClientAsync = Async ClientDone
data ClientConfig = ClientConfig
{
apiCall :: String -> IO (Wreq.Response Bytestring) -- Given an endpoint path, return the Response
}
type ClientCount = Int
setupClients :: ClientCount -> IO ClientConfig
setupClients count = do
return ClientConfig
{
apiCall = call
}
where
host = "localhost" --TODO Read this from an environment variable
port = 3000 --TODO Read this from an environment variable
prefix = "http://" ++ host ++ ":" ++ (show port)
opts = Wreq.defaults & Wreq.manager .~ Left (
defaultManagerSettings {
}
)
call endpoint = Wreq.getWith opts $ prefix ++ endpoint
cleanupClients :: ClientConfig -> IO ()
cleanupClients = undefined
startClient :: IO ClientAsync
startClient = undefined
| Sapiens-OpenSource/webbench | client/src/Webbench/Client.hs | bsd-2-clause | 1,640 | 11 | 8 | 468 | 255 | 173 | 82 | -1 | -1 |
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--short-names" @-}
{-@ LIQUID "--diff" @-}
module KMP (search) where
import Language.Haskell.Liquid.Prelude (liquidError, liquidAssert)
import Data.IORef
import Control.Applicative ((<$>))
import qualified Data.Map as M
import Prelude hiding (map)
{-@ type Upto N = {v:Nat | v < N} @-}
---------------------------------------------------------------------------
{-@ search :: pat:String -> str:String -> IO (Maybe (Upto (len str))) @-}
---------------------------------------------------------------------------
search :: String -> String -> IO (Maybe Int)
search pat str = do
p <- ofListIO pat
s <- ofListIO str
kmpSearch p s
---------------------------------------------------------------------------
-- | Do the Search --------------------------------------------------------
---------------------------------------------------------------------------
kmpSearch p@(IOA m _) s@(IOA n _) = do
t <- kmpTable p
find p s t 0 0
find p@(IOA m _) s@(IOA n _) t = go
where
go i j
| i >= n = return $ Nothing
| j >= m = return $ Just (i - m)
| otherwise = do si <- getIO s i
pj <- getIO p j
tj <- getIO t j
case () of
_ | si == pj -> go (i+1) (j+1)
| j == 0 -> go (i+1) j
| otherwise -> go i tj
---------------------------------------------------------------------------
-- | Make Table -----------------------------------------------------------
---------------------------------------------------------------------------
-- BUG WHAT's going on?
{-@ bob :: Nat -> IO () @-}
bob n = do
t <- newIO (n + 1) (\_ -> 0)
setIO t 0 100
r <- getIO t 0
liquidAssert (r == 100) $ return ()
kmpTable p@(IOA m _) = do
t <- newIO m (\_ -> 0)
fill p t 1 0
return t
fill p t@(IOA m _) = go
where
go i j
| i < m - 1 = do
pi <- getIO p (id i)
pj <- getIO p j
case () of
_ | pi == pj -> do
let i' = i + 1
let j' = j + 1
setIO t i' j'
go i' j'
| j == 0 -> do
let i' = i + 1
setIO t i' 0
go i' j
| otherwise -> do
j' <- getIO t j
go i j'
| otherwise = return t
-------------------------------------------------------------------------------
-- | An Imperative Array ------------------------------------------------------
-------------------------------------------------------------------------------
data IOArr a = IOA { size :: Int
, pntr :: IORef (Arr a)
}
{-@ data IOArr a <p :: Int -> a -> Prop>
= IOA { size :: Nat
, pntr :: IORef ({v:Arr<p> a | alen v = size})
}
@-}
{-@ newIO :: forall <p :: Int -> a -> Prop>.
n:Nat -> (i:Upto n -> a<p i>) -> IO ({v: IOArr<p> a | size v = n})
@-}
newIO n f = IOA n <$> newIORef (new n f)
{-@ getIO :: forall <p :: Int -> a -> Prop>.
a:IOArr<p> a -> i:Upto (size a) -> IO (a<p i>)
@-}
getIO a@(IOA sz p) i
= do arr <- readIORef p
return $ (arr ! i)
{-@ setIO :: forall <p :: Int -> a -> Prop>.
a:IOArr<p> a -> i:Upto (size a) -> a<p i> -> IO ()
@-}
setIO a@(IOA sz p) i v
= do arr <- readIORef p
let arr' = set arr i v
writeIORef p arr'
{-@ ofListIO :: xs:[a] -> IO ({v:IOArr a | size v = len xs}) @-}
ofListIO xs = newIO n f
where
n = length xs
m = M.fromList $ zip [0..] xs
f i = (M.!) m i
{-@ mapIO :: (a -> b) -> a:IOArr a -> IO ({v:IOArr b | size v = size a}) @-}
mapIO f (IOA n p)
= do a <- readIORef p
IOA n <$> newIORef (map f a)
-------------------------------------------------------------------------------
-- | A Pure Array -------------------------------------------------------------
-------------------------------------------------------------------------------
data Arr a = A { alen :: Int
, aval :: Int -> a
}
{-@ data Arr a <p :: Int -> a -> Prop>
= A { alen :: Nat
, aval :: i:Upto alen -> a<p i>
}
@-}
{-@ new :: forall <p :: Int -> a -> Prop>.
n:Nat -> (i:Upto n -> a<p i>) -> {v: Arr<p> a | alen v = n}
@-}
new n v = A { alen = n
, aval = \i -> if (0 <= i && i < n)
then v i
else liquidError "Out of Bounds!"
}
{-@ (!) :: forall <p :: Int -> a -> Prop>.
a:Arr<p> a -> i:Upto (alen a) -> a<p i>
@-}
(A _ f) ! i = f i
{-@ set :: forall <p :: Int -> a -> Prop>.
a:Arr<p> a -> i:Upto (alen a) -> a<p i> -> {v:Arr<p> a | alen v = alen a}
@-}
set a@(A _ f) i v = a { aval = \j -> if (i == j) then v else f j }
{-@ ofList :: xs:[a] -> {v:Arr a | alen v = len xs} @-}
ofList xs = new n f
where
n = length xs
m = M.fromList $ zip [0..] xs
f i = (M.!) m i
{-@ map :: (a -> b) -> a:Arr a -> {v:Arr b | alen v = alen a} @-}
map f a@(A n z) = A n (f . z)
| Kyly/liquidhaskell | tests/todo/kmpMonad.hs | bsd-3-clause | 5,263 | 0 | 19 | 1,806 | 1,310 | 659 | 651 | 83 | 2 |
{-# LANGUAGE TemplateHaskell, CPP, MultiParamTypeClasses #-}
-- | Offline mode / RC file / -e support module. Handles spooling lists
-- of commands (from readline, files, or the command line) into the vchat
-- layer.
module Plugin.OfflineRC (theModule) where
import Plugin
import System.IO( hPutStrLn, hFlush, stdout )
import LMain( received )
import IRCBase
import Control.Monad.Reader( asks )
import Control.Monad.State( get, gets, put )
import Control.Concurrent( forkIO )
import Control.Concurrent.MVar( readMVar )
import Lambdabot.Error( finallyError )
import Control.OldException ( evaluate )
import Config
#ifdef mingw32_HOST_OS
-- Work around the lack of readline on windows
readline :: String -> IO (Maybe String)
readline p = do
putStr p
hFlush stdout
liftM Just getLine
addHistory :: String -> IO ()
addHistory _ = return ()
#else
import System.Console.Readline( readline, addHistory )
#endif
$(plugin "OfflineRC")
-- We need to track the number of active sourcings so that we can
-- unregister the server (-> allow the bot to quit) when it is not
-- being used.
type OfflineRC = ModuleT Integer LB
instance Module OfflineRCModule Integer where
modulePrivs _ = ["offline", "rc"]
moduleHelp _ "offline" = "offline. Start a repl"
moduleHelp _ "rc" = "rc name. Read a file of commands (asynchonously). FIXME: better name."
moduleInit _ = do act <- bindModule0 onInit
lift $ liftLB forkIO $ do mv <- asks ircInitDoneMVar
io $ readMVar mv
act
return ()
moduleDefState _ = return 0
process_ _ "offline" _ = do act <- bindModule0 $ finallyError replLoop unlockRC
lockRC
lift $ liftLB forkIO act
return []
process_ _ "rc" fn = do txt <- io $ readFile fn
io $ evaluate $ foldr seq () txt
act <- bindModule0 $ finallyError (mapM_ feed $ lines txt) unlockRC
lockRC
lift $ liftLB forkIO act
return []
onInit :: ModuleT Integer LB ()
onInit = do st <- get
put (st { ircOnStartupCmds = [] })
let cmds = ircOnStartupCmds st
lockRC >> finallyError (mapM_ feed cmds) unlockRC
feed :: String -> ModuleT Integer LB ()
feed msg = let msg' = case msg of '>':xs -> cmdPrefix ++ "run " ++ xs
'!':xs -> xs
_ -> cmdPrefix ++ dropWhile (== ' ') msg
in lift . (>> return ()) . liftLB (timeout (15 * 1000 * 1000)) . received $
IrcMessage { msgServer = "offlinerc"
, msgLBName = "offline"
, msgPrefix = "null!n=user@null"
, msgCommand = "PRIVMSG"
, msgParams = ["offline", ":" ++ msg' ] }
where cmdPrefix = head (commandPrefixes config)
handleMsg :: IrcMessage -> LB ()
handleMsg msg = liftIO $ do
let str = case (tail . msgParams) msg of
[] -> []
(x:_) -> tail x
hPutStrLn stdout str
hFlush stdout
replLoop :: OfflineRC ()
replLoop = do line <- io $ readline "lambdabot> "
s' <- case line of Nothing -> fail "<eof>"
Just x -> return $ dropWhile isSpace x
when (not $ null s') (do io (addHistory s')
feed s')
continue <- gets ircStayConnected
when continue replLoop
lockRC :: OfflineRC ()
lockRC = do add <- bindModule0 $ addServer "offlinerc" handleMsg
withMS $ \ cur writ -> do when (cur == 0) $ add
writ (cur + 1)
unlockRC :: OfflineRC ()
unlockRC = withMS $ \ cur writ -> do when (cur == 1) $ remServer "offlinerc"
writ (cur - 1)
| dmalikov/lambdabot | Plugin/OfflineRC.hs | mit | 4,213 | 0 | 15 | 1,642 | 1,100 | 545 | 555 | 74 | 3 |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN"
"http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="en-GB">
<title>Passive Scan Rules - Alpha | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
| 0xkasun/security-tools | src/org/zaproxy/zap/extension/pscanrulesAlpha/resources/help/helpset.hs | apache-2.0 | 1,000 | 82 | 68 | 175 | 430 | 219 | 211 | -1 | -1 |
module Moo (plusOne) where
{-@ assert plusOne :: x:Int -> {v:Int| v > x } @-}
plusOne :: Int -> Int
plusOne x = x + 1
| ssaavedra/liquidhaskell | tests/tmp/Moo.hs | bsd-3-clause | 119 | 0 | 5 | 28 | 31 | 18 | 13 | 3 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module T12538 where
data Tagged t a = Tagged a
type family Tag a where
Tag (Tagged t a) = Tagged t a
Tag a = Tagged Int a
class (r ~ Tag a) => TagImpl a r | a -> r where
tag :: a -> r
instance {-# OVERLAPPING #-} (r ~ Tag (Tagged t a)) => TagImpl (Tagged t a) r where
tag = id
#ifdef WRONG
instance {-# OVERLAPPING #-} (r ~ Tagged t a, r ~ Tag a) => TagImpl a r where
#else
instance {-# OVERLAPPING #-} (r ~ Tagged Int a, r ~ Tag a) => TagImpl a r where
#endif
tag = Tagged @Int
data family DF x
data instance DF (Tagged t a) = DF (Tagged t a)
class ToDF a b | a -> b where
df :: a -> b
instance (TagImpl a a', b ~ DF a') => ToDF a b where
df = DF . tag
main :: IO ()
main = pure ()
| ezyang/ghc | testsuite/tests/indexed-types/should_compile/T12538.hs | bsd-3-clause | 946 | 0 | 10 | 221 | 322 | 174 | 148 | 26 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Blaze.ByteString.Builder (Builder, fromByteString)
import Blaze.ByteString.Builder.Char8 (fromShow)
import Data.Monoid (mappend)
import Network.Wai.Handler.Warp (run)
import Data.Enumerator (enumList, ($$), run_)
bigtable :: [Builder]
bigtable =
fromByteString "<table>"
: foldr (:) [fromByteString "</table>"] (replicate 2 row)
where
row = fromByteString "<tr>"
`mappend` foldr go (fromByteString "</tr>") [1..2]
go i rest = fromByteString "<td>"
`mappend` fromShow i
`mappend` fromByteString "</td>"
`mappend` rest
main = run 3000 app
app _ = return $ ResponseEnumerator $ \f ->
run_ $ enumList 4 bigtable $$ f status200 [("Content-Type", "text/html")]
| jberryman/wai | warp/attic/bigtable-stream.hs | mit | 799 | 0 | 10 | 171 | 245 | 138 | 107 | 20 | 1 |
import Graphics.Gloss
import System.IO.Unsafe
import System.Environment
import Data.Char
-- | Main entry point to the application.
-- | module Main where
-- | The main entry point.
main = animate (InWindow "Sierpinski Triangles" (500, 650) (20, 20))
black (picture_sierpinski getDegree)
getDegree :: Int
getDegree = (digitToInt (head (head (unsafePerformIO (getArgs)))))
side :: Float
side = 100.0
-- Sierpinski Triangles
picture_sierpinski :: Int -> Float -> Picture
picture_sierpinski degree time
= sierpinski degree time (azure)
-- Base of triangles
base_tri :: Color -> Picture
base_tri color
= Color color
$ Polygon [
((-(side/2)),0),
((side/2),0),
(0,(-(((sqrt 3.0)/2)*side)))]
sierpinski :: Int -> Float -> Color -> Picture
sierpinski 0 time color = base_tri color
sierpinski n time color
= let inner
= Scale 0.5 0.5
$ sierpinski (n-1) time (mix color)
in Pictures
[base_tri color
, Rotate (180 * (sin (time/2))) $ Translate (-(side/2)) (-((((sqrt 3.0)/2)*side)/2)) $ inner
, Rotate (180 * (sin (time/2))) $ Translate ((side/2)) (-((((sqrt 3.0)/2)*side)/2)) $ inner
, Rotate (360 * (sin (time/2))) $ Translate (0) (((((sqrt 3.0)/2)*side)/2)) $ inner]
--
mix :: Color -> Color
mix c = mixColors 1 2 red c
| kylegodbey/haskellProject | src/sierpinski_ani.hs | mit | 1,349 | 10 | 21 | 323 | 611 | 331 | 280 | 33 | 1 |
import Data.List.Split
import Control.Arrow
data Point = Point Int Int
instance Show Point where
show (Point x y) = show x ++ " " ++ show y
symPoint :: Point -> Point -> Point
symPoint (Point px py) (Point qx qy) = Point (qx + (qx - px)) (qy + (qy - py))
solve :: String -> String
solve line = show res
where tokens = splitOn " " line
[px, py, qx, qy] = map read tokens
res = symPoint (Point px py) (Point qx qy)
main :: IO ()
main = do
_ <- getLine
interact $ lines >>> map solve >>> unlines | Dobiasd/HackerRank-solutions | Algorithms/Geometry/Find_Point/Main.hs | mit | 533 | 0 | 9 | 145 | 254 | 130 | 124 | 16 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Utils where
import Text.Printf
import Data.Text (Text)
import qualified Data.Text as T
-- Remove nth item from list
remove :: Int -> [a] -> [a]
remove n xs = let (ys,zs) = splitAt n xs in ys ++ (tail zs)
showT :: (Show a) => a -> Text
showT = T.pack . show
numberToEuropean :: Text -> Text
numberToEuropean = T.map switchDelimiters
where switchDelimiters ',' = '.'
switchDelimiters '.' = ','
switchDelimiters x = x
rawFormat :: Double -> Text
rawFormat = T.pack . printf "%.2f"
-- output utils
eurFormatVal :: Double -> Text
eurFormatVal = numberToEuropean . rawFormat
| michaelbeaumont/kirchhoff-generator | src/Utils.hs | mit | 642 | 0 | 9 | 135 | 207 | 114 | 93 | 18 | 3 |
import Data.List
import Primes
import Utils
truncateRight :: Integer -> [Integer]
truncateRight 0 = []
truncateRight n | n>0 = n : truncateRight (n `div` 10)
truncateLeft :: Integer -> [Integer]
truncateLeft n
| n>9 = n : truncateLeft ((read $ tail $ show n) :: Integer)
| otherwise = [n]
allTruncRightPrimes n = and $ map isPrime $ truncateRight n
allTruncLeftPrimes n = and $ map isPrime $ truncateLeft n
allTruncPrimes n = (allTruncRightPrimes n) && (allTruncLeftPrimes n)
candidates = filter (\n -> n>7 && doesNotContain [2,4,6,8,0,5] n) primeTable
doesNotContain :: [Integer] -> Integer -> Bool
doesNotContain l n = (length $ intersect l digits) == 0
where digits = numberToDigits n
validPrimes = drop 4 $ take 15 $ filter allTruncPrimes primeTable
answer = sum validPrimes
| arekfu/project_euler | p0037/p0037.hs | mit | 810 | 0 | 11 | 159 | 338 | 173 | 165 | 19 | 1 |
second xs = head (tail xs)
| calebgregory/fp101x | wk2/second.hs | mit | 27 | 0 | 7 | 6 | 18 | 8 | 10 | 1 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Maintainer : me@joelt.io
-- Stability : experimental
-- Portability : portable
--
-- A monad whose actions produce an output.
--
-- This module builds output strictly. For a lazy version, see
-- "Control.Monad.Writer.Concurrent.Lazy".
-----------------------------------------------------------------------------
module Control.Monad.Writer.Concurrent.Strict (
module Control.Monad.Writer,
-- *** The WriterC monad transformer
WriterC,
-- *** Running WriterC actions
runWriterC, execWriterC, mapWriterC,
-- *** Running concurrent operations on a single input
runWritersC, execWritersC,
-- *** Lifting other operations
liftCallCC, liftCatch
) where
import Control.Applicative
import Control.Arrow (first)
import Control.Concurrent.Lifted.Fork
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.Exception (throwIO)
import Control.Monad
import Control.Monad.Catch
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Reader
import Control.Monad.Writer
-- ---------------------------------------------------------------------------
-- | A concurrent monad transformer collecting output of type @w@.
--
-- This is very similar to @transformers@' 'WriterT', with the exception of
-- the 'MonadIO' constraint on every instance, which is necessary to
-- perform STM actions.
newtype WriterC w m a = WriterC
{ _runWriterC :: TVar w -> m (a, TVar w) }
instance MonadTrans (WriterC w) where
lift m = WriterC $ \w -> do
a <- m
return (a, w)
instance MonadIO m => MonadIO (WriterC w m) where
liftIO i = WriterC $ \w -> do
a <- liftIO i
return (a, w)
instance Functor m => Functor (WriterC w m) where
fmap f m = WriterC $ \w ->
fmap (first f) $ _runWriterC m w
instance (Functor m, Monad m) => Applicative (WriterC w m) where
pure = return
(<*>) = ap
instance (Functor m, MonadPlus m) => Alternative (WriterC w m) where
empty = mzero
(<|>) = mplus
instance Monad m => Monad (WriterC w m) where
return a = WriterC $ \w -> return (a, w)
m >>= k = WriterC $ \w -> do
(a, w') <- _runWriterC m w
_runWriterC (k a) w'
instance MonadPlus m => MonadPlus (WriterC w m) where
mzero = WriterC $ const mzero
m `mplus` n = WriterC $ \w -> _runWriterC m w `mplus` _runWriterC n w
instance MonadFix m => MonadFix (WriterC w m) where
mfix f = WriterC $ \w -> mfix $ \(a, _) -> _runWriterC (f a) w
instance (Monoid w, MonadReader r m) => MonadReader r (WriterC w m) where
ask = lift ask
local f m = WriterC $ \w -> local f $ _runWriterC m w
reader = lift . reader
instance (Monoid w, MonadIO m) => MonadWriter w (WriterC w m) where
writer (a, w) = WriterC $ \tw -> do
liftIO . atomically $ modifyTVar' tw (<> w)
return (a, tw)
listen m = WriterC $ \tw -> do
(a, tw') <- _runWriterC m tw
w <- liftIO $ readTVarIO tw'
return ((a, w), tw')
pass m = WriterC $ \tw -> do
((a, f), tw') <- _runWriterC m tw
liftIO . atomically $ modifyTVar' tw' f
return (a, tw')
instance (MonadIO m, MonadCatch m) => MonadCatch (WriterC w m) where
throwM = liftIO . throwIO
catch = liftCatch catch
mask a = WriterC $ \w -> mask $ \u -> _runWriterC (a $ q u) w where
q u (WriterC f) = WriterC (u . f)
uninterruptibleMask a =
WriterC $ \w -> uninterruptibleMask $ \u -> _runWriterC (a $ q u) w where
q u (WriterC f) = WriterC (u . f)
instance (Monoid w, MonadFork m) => MonadFork (WriterC w m) where
fork = liftFork fork
forkOn i = liftFork (forkOn i)
forkOS = liftFork forkOS
liftFork :: Monad m => (m () -> m a) -> WriterC w m () -> WriterC w m a
liftFork f (WriterC m) = WriterC $ \w -> do
tid <- f . voidM $ m w
return (tid, w)
where voidM = (>> return ())
-- | Unwrap a concurrent Writer monad computation as a function.
runWriterC :: MonadIO m
=> WriterC w m a -- ^ computation to execute
-> TVar w -- ^ output channel
-> m (a, w) -- ^ return value and collected output
runWriterC m tw = do
(a, w) <- _runWriterC m tw
w' <- liftIO $ readTVarIO w
return (a, w')
-- | Unwrap a concurrent Writer monad computation as a function, discarding
-- the return value.
--
-- * @'execWriterC' m w = 'liftM' 'snd' ('runWriterC' m w)@
execWriterC :: MonadIO m
=> WriterC w m a -- ^ computation to execute
-> TVar w -- ^ output channel
-> m w -- ^ collected output
execWriterC m tw = liftM snd $ runWriterC m tw
-- | Map both the return value and output of a computation using the given
-- function.
mapWriterC :: (m (a, TVar w) -> n (b, TVar w)) -> WriterC w m a -> WriterC w n b
mapWriterC f m = WriterC $ \w -> f (_runWriterC m w)
-- | Lift a @callCC@ operation to the new monad.
liftCallCC :: ((((a, TVar w) -> m (b, TVar w)) -> m (a, TVar w)) -> m (a, TVar w)) -> ((a -> WriterC w m b) -> WriterC w m a) -> WriterC w m a
liftCallCC callCC f = WriterC $ \w ->
callCC $ \c ->
_runWriterC (f (\a -> WriterC $ \_ -> c (a, w))) w
-- | Lift a @catchError@ operation to the new monad.
liftCatch :: (m (a, TVar w) -> (e -> m (a, TVar w)) -> m (a, TVar w)) -> WriterC w m a -> (e -> WriterC w m a) -> WriterC w m a
liftCatch catchError m h =
WriterC $ \w -> _runWriterC m w `catchError` \e -> _runWriterC (h e) w
-- | Run multiple Writer operations on the same value, returning the
-- resultant output and the value produced by each operation.
runWritersC :: (MonadFork m, Monoid w)
=> [WriterC w m a] -- ^ writer computations to execute
-> m ([a], w) -- ^ return values and output
runWritersC ms = do
output <- liftIO $ newTVarIO mempty
mvs <- mapM (const (liftIO newEmptyMVar)) ms
forM_ (zip mvs ms) $ \(mv, operation) -> fork $ do
(res, _) <- runWriterC operation output
liftIO $ putMVar mv res
items <- forM mvs (liftIO . takeMVar)
out <- liftIO $ readTVarIO output
return (items, out)
-- | Run multiple Writer operations on the same value, returning the
-- resultant output.
execWritersC :: (MonadFork m, Monoid w)
=> [WriterC w m a] -- ^ writer computations to execute
-> m w -- ^ output
execWritersC = liftM snd . runWritersC
| pikajude/concurrent-state | src/Control/Monad/Writer/Concurrent/Strict.hs | mit | 6,555 | 0 | 17 | 1,609 | 2,199 | 1,157 | 1,042 | 122 | 1 |
module Handler.Articles where
import Import
import qualified Database.Esqueleto as E
import qualified Data.Text as T
import qualified Data.Time.Format as Time
getArticlesR :: Handler Html
getArticlesR = do
articles <- runDB $
E.select
$ E.from $ \(article `E.InnerJoin` language) -> do
E.on $ article E.^. ArticleLang E.==. language E.^. LanguageId
E.orderBy [ E.desc (article E.^. ArticleCreated) ]
return (article, language)
defaultLayout $ do
setTitle $ toHtml $ T.pack "Articles"
$(widgetFile "articles")
| builtinnya/lambdar-website | Handler/Articles.hs | mit | 565 | 0 | 16 | 126 | 183 | 98 | 85 | 16 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Hackup.Action(Action(..),
Archive(..), baseName, targetDirectory, archiveItems, archiveItemsBaseDir, keepPrevious,
Command(..), workingDir, command, ignoreFailure,
planActions) where
import Control.Applicative
import Control.Lens hiding (Action)
import Data.Maybe (fromMaybe)
import Hackup.Config.Types
import Hackup.Selectors
data Archive = Archive { _baseName :: FilePath
, _targetDirectory :: FilePath
, _archiveItemsBaseDir :: FilePath
, _archiveItems :: [FileSelector]
, _keepPrevious :: Integer
} deriving (Eq, Show)
data Action = CommandAction Command
| ArchiveAction Archive
deriving (Show, Eq)
archiveAction :: FilePath -> Integer -> String -> Section -> Archive
archiveAction backupRoot defKeep name section =
Archive archName archDir (section ^. itemsBaseDir) (section ^. items) keepNum
where archDir = fromMaybe backupRoot $ section ^. archiveDir
archName = fromMaybe name $ section ^. archiveName
keepNum = fromMaybe defKeep $ section ^. keep
planSection :: FilePath -> Integer -> (String, Section) -> [Action]
planSection backupRoot defKeep (name, section) =
(CommandAction <$> (section ^. before)) ++
[ArchiveAction $ archiveAction backupRoot defKeep name section] ++
(CommandAction <$> (section ^. after))
planActions :: Config -> [[Action]]
planActions cfg =
planSection (cfg ^. backupRootDir) (cfg ^. defaultKeep) <$>
cfg ^@.. sections . itraversed
makeLenses ''Archive
| chwthewke/hackup | src/Hackup/Action.hs | mit | 1,771 | 0 | 10 | 523 | 440 | 250 | 190 | -1 | -1 |
{-# OPTIONS_HADDOCK show-extensions #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
{-|
Module : Numeric.Neural.Layer
Description : layer components
Copyright : (c) Lars Brünjes, 2016
License : MIT
Maintainer : brunjlar@gmail.com
Stability : experimental
Portability : portable
This modules defines special "layer" components and convenience functions for the creation of such layers.
-}
module Numeric.Neural.Layer
( Layer
, linearLayer
, layer
, tanhLayer
, tanhLayer'
, logisticLayer
, reLULayer
, softmax
, softmaxLayer
) where
import Control.Category
import Data.FixedSize
import Data.Proxy
import Data.Utils.Analytic
import Data.Utils.Random
import GHC.TypeLits
import GHC.TypeLits.Witnesses
import Numeric.Neural.Model
import Prelude hiding (id, (.))
-- | A @'Layer' i o@ is a component that maps a @'Vector'@ of length @i@ to a @'Vector'@ of length @o@.
--
type Layer i o = Component (Vector i) (Vector o)
linearLayer' :: forall i o s. Analytic s => ParamFun s (Matrix o (i + 1)) (Vector i s) (Vector o s)
linearLayer' = ParamFun $ \xs ws -> ws <%%> cons 1 xs
-- | Creates a /linear/ @'Layer'@, i.e. a layer that multiplies the input with a weight @'Matrix'@ and adds a bias to get the output.
--
-- Random initialization follows the recommendation from chapter 3 of the online book
-- <http://neuralnetworksanddeeplearning.com/ Neural Networks and Deep Learning> by Michael Nielsen.
linearLayer :: forall i o. (KnownNat i, KnownNat o) => Layer i o
linearLayer = withNatOp (%+) p (Proxy :: Proxy 1) Component
{ weights = pure 0
, compute = linearLayer'
, initR = sequenceA $ generate r
}
where
p = Proxy :: Proxy i
s = 1 / sqrt (fromIntegral $ natVal p)
r (_, 0) = boxMuller
r (_, _) = boxMuller' 0 s
-- | Creates a @'Layer'@ as a combination of a linear layer and a non-linear activation function.
--
layer :: (KnownNat i, KnownNat o) => Diff' -> Layer i o
layer f = cArr (diff f) . linearLayer
-- | This is a simple @'Layer'@, specialized to @'tanh'@-activation. Output values are all in the interval [-1,1].
--
tanhLayer :: (KnownNat i, KnownNat o) => Layer i o
tanhLayer = layer tanh
-- | This is a simple @'Layer'@, specialized to a modified @'tanh'@-activation, following the suggestion from
-- <http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf Efficient BackProp> by LeCun et al., where
-- output values are all in the interval [-1.7159,1.7159].
tanhLayer' :: (KnownNat i, KnownNat o) => Layer i o
tanhLayer' = layer $ \x -> 1.7159 * tanh (2 * x / 3)
-- | This is a simple @'Layer'@, specialized to the logistic function as activation. Output values are all in the interval [0,1].
--
logisticLayer :: (KnownNat i, KnownNat o) => Layer i o
logisticLayer = layer $ \x -> 1 / (1 + exp (- x))
-- | This is a simple @'Layer'@, specialized to the /rectified linear unit/ activation function.
-- Output values are all non-negative.
--
reLULayer :: (KnownNat i, KnownNat o) => Layer i o
reLULayer = layer $ \x -> max 0 x
-- | The @'softmax'@ function normalizes a vector, so that all entries are in [0,1] with sum 1.
-- This means the output entries can be interpreted as probabilities.
--
softmax :: (Floating a, Functor f, Foldable f) => f a -> f a
softmax xs = let xs' = exp <$> xs
s = sum xs'
in (/ s) <$> xs'
-- | A @'softmaxLayer'@ is a deterministic layer that performs a @'softmax'@
-- step.
softmaxLayer :: Layer i i
softmaxLayer = cArr $ Diff softmax
| brunjlar/neural | src/Numeric/Neural/Layer.hs | mit | 3,622 | 0 | 12 | 763 | 725 | 408 | 317 | 52 | 2 |
module Game where
import Graphics.Gloss.Interface.Pure.Game
import Graphics.Gloss.Data.Picture
import Data.List
import qualified Data.Map.Strict as M
import Types
import BrickMap
import Paddle
import Ball
import Collision
import Timer
import Instance
initGame :: Int -> Int -> Game
initGame w h =
let fw = fromIntegral w
fh = fromIntegral h
in Game
{ gTime = 0
, gDims = (fw, fh)
, gBricks = initBrickMap 11 5 25 64 20 fw fh
, gPaddle = initPaddle fw
, gBall = initBall fw fh
, gScore = 0
, gLives = 3
, gTimers = [ballTimer]
, gInsts = []
}
render :: Game -> Picture
render game =
let bricks = drawBricks $ gBricks game
paddle = drawPaddle $ gPaddle game
ball = drawBall $ gBall game
ui = renderUI game
insts = map (`iFunc` game) $ gInsts game
final = pictures $ [bricks, paddle, ball, ui] ++ insts
in translate (-400) (-300) final
renderUI :: Game -> Picture
renderUI game =
let (w, h) = gDims game
score = translate 32 (-16) $ scale 0.2 0.2 $ text $ "Score: " ++ show (gScore game)
balls = map (\x -> translate (fromIntegral x * 16) 0 $ circleSolid 4) [1..gLives game]
lives = translate (w - 96) 0 $ pictures balls
in translate 0 (h - 32) $ color (greyN 0.6) $ pictures [score, lives]
handleEvents :: Event -> Game -> Game
handleEvents (EventKey key state _ _) game =
let acc = case key of
Char c ->
case c of
'a' -> -0.5
'd' -> 0.5
_ -> 0
SpecialKey sk ->
case sk of
KeyLeft -> -0.5
KeyRight -> 0.5
_ -> 0
_ -> 0
fixAcc = case state of
Up -> -acc
_ -> acc
in game { gPaddle = addPaddleAccel fixAcc $ gPaddle game }
handleEvents _ game = game
update :: Time -> Game -> Game
update dt oldGame
| loseCond || winCond || gameOver =
let (w, h) = gDims oldGame
in oldGame
{ gBricks = if loseCond then gBricks oldGame else initBrickMap 11 5 25 64 20 w h
, gBall = initBall w h
, gScore = if gameOver then 0 else gScore oldGame
, gLives = if gameOver then 3 else gLives oldGame - if loseCond then 1 else 0
, gTimers = ballTimer : gTimers oldGame
}
| otherwise =
let (due, timers) = partition tTimeout $ map (updateTimer dt) $ gTimers oldGame
game = foldl (flip tFunc) oldGame due
paddleCol = checkPaddleCollision (gPaddle game) (gBall game)
bricksCol = checkBricksCollision (gBricks game) (gBall game)
in game
{ gTime = gTime game + dt
, gBricks = updateBricks (gBricks game) bricksCol
, gPaddle = updatePaddle (gPaddle game)
, gBall = updateBall (gBall game) $ collisionMerge paddleCol bricksCol
, gScore = case bricksCol of
NoCollision -> gScore game
_ -> gScore game + 5
, gTimers = timers
, gInsts = filter iTimeout $ map (updateInst dt) $ gInsts oldGame
}
where loseCond = (bY . gBall) oldGame < (pY . gPaddle) oldGame - 8
winCond = (M.size . bmBricks . gBricks) oldGame == 0
gameOver = gLives oldGame <= 0
| Chase-C/Breakout | src/Game.hs | mit | 3,616 | 0 | 16 | 1,429 | 1,169 | 613 | 556 | 89 | 8 |
module Main (
main
) where
import Test.HUnit
import Pangraph.GraphML.Parser
import Tuura.Fantasi.VHDL.Writer
import VHDLLiterals
main :: IO Counts
main = runTestTT $ TestList[case1, case2]
case1 :: Test
case1 = TestCase $ assertEqual "case1: Enviroment Writer N1"
enviroFile1 (writeEnvironment $ unsafeParse graphfileN1)
case2 :: Test
case2 = TestCase $ assertEqual "case2: Graph Writer N1"
vhdlGraph1 (writeGraph $ unsafeParse graphfileN1)
| tuura/fantasi | test/Main.hs | mit | 450 | 0 | 9 | 67 | 118 | 66 | 52 | 14 | 1 |
-- file: ch03/GlobalVariable.hs
itemName = "Weighted Companion Cube"
-- That variable is defined at the top level of a source file.
| supermitch/learn-haskell | real-world-haskell/ch03/GlobalVariable.hs | mit | 134 | 0 | 4 | 23 | 8 | 5 | 3 | 1 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeApplications #-}
-- | This is a tutorial on implementing custom effects.
--
-- == What is an effect?
--
-- An effect is made up of a few parts.
--
-- === External
--
-- This is the external interface of the effect that users of the effect use.
--
-- 1. __The DSL syntax__: the primitives that this effect enables.
--
-- 2. __DSL interpreter (aka handler)__: the function which interprets the DSL.
--
-- === Internal
--
-- In order to implement the above, the implementer has to, additionally, think
-- of:
--
-- 1. __Request messages__: the messages that are dispatched to the handler when
-- the DSL is used.
--
-- 2. __Interpreter logic__: how to respond to the requests.
--
-- == How do we implement an effect?
--
-- Each of the four parts above corresponds to something that's needed for
-- implementing the effect:
--
-- 1. __A datatype (/internal/)__: these define the /requests/ that the handler
-- receives.
--
-- 2. __Smart constructors (/external/)__: these define the /DSL syntax/ that
-- users of the effect will use.
--
-- 3. __A 'Control.Eff.Extend.Handle' instance (/internal/)__: this defines the
-- /interpreter logic/, i.e., how the handler responds to the requests.
--
-- 4. __A handler using the 'Control.Eff.Extend.Handle' instance (/external/)__:
-- this is the /handler/ that users of the effect invoke. We define this by:
--
-- * invoking 'Control.Eff.Extend.handle_relay'
-- * passing an argument which specifies how to embed pure values
-- * tying the recursive-knot using 'Data.Function.fix'
--
-- __TODO__: The above might benefit from some template-haskell to reduce
-- boilerplate.
--
-- == The effect design process
--
-- * As with all things, this starts with a name (say @t@). The name of the
-- effect is also the name we give the datatype.
--
-- * Having decided the name of the effect, we need to determine the DSL
-- syntax. The syntax names are shared both by the data constructors as well as
-- the smart constructors.
--
-- * We need to define the types for the DSL syntax. Since this is an effectful
-- DSL, each DSL component will have a type of the form:
--
-- * @Member t r => Eff r b@, or
-- * @Member t r => a0 -> Eff r b@.
-- * @Member t r => a0 -> a1 -> Eff r b@.
-- * ...
--
-- * Having decided the types, we have to think about the implementation.
--
-- Let's implement a DSL dealing with some basic arithmetic operations:
-- @addition, minimum@.
module Control.Eff.Extend.Tutorial where
import Control.Eff
import Control.Eff.Extend
import Data.Function (fix)
-- | 'Arith' DSL syntax for constant literals.
lit :: Member Arith r => Integer -> Eff r Integer
-- | 'Arith' DSL syntax to addition of two numbers.
add :: Member Arith r => Eff r Integer -> Eff r Integer -> Eff r Integer
-- | 'Arith' DSL syntax for minimum of two numbers.
min :: Member Arith r => Eff r Integer -> Eff r Integer -> Eff r Integer
-- | The request messages sent to the /handler/.
data Arith a where
-- | Introduce integer literals
Lit :: Integer -> Arith Integer
-- | Addition of two numbers. Per the signature the specific addition
-- operation is provided by the handler
Add :: Arith (Integer -> Integer -> Integer)
-- | Minimum of two numbers. Per the signature the specific minimum operation
-- is provided by the handler.
Min :: Arith (Integer -> Integer -> Integer)
-- | Send the @Lit@ request.
lit x = send (Lit x)
-- | Send the @Add@ request.
add x y = send Add <*> x <*> y
-- | Send the @Min@ request.
min x y = send Min <*> x <*> y
-- | The /handler/ logic.
instance Handle Arith r a (Eff r' Integer) where
handle h q = \case
Lit x -> pure x
Add -> k (+)
Min -> k Prelude.min
where k = qComp q h
-- | The handler
runArith :: Eff (Arith ': r) Integer -> Eff r Integer
runArith = fix (handle_relay pure)
| suhailshergill/extensible-effects | src/Control/Eff/Extend/Tutorial.hs | mit | 3,855 | 0 | 10 | 778 | 447 | 267 | 180 | -1 | -1 |
module Utilities where
isqrt :: Integer -> Integer
isqrt num = floor (sqrt (fromIntegral num))
isPrime :: Integer -> Bool
isPrime num
| num < 2 = False
| num == 2 = True
| even num = False
| otherwise = and (map (\n -> (num `mod` n) /= 0) [3, 5 .. lim])
where
lim = isqrt num + 1
isModZero :: Integer -> Integer -> Integer
isModZero x y
| y `mod` x == 0 = 0
| otherwise = y
sieve :: Integer -> Integer -> [Integer] -> [Integer]
sieve iter max [] = []
sieve iter max (x:xs)
| iter > max = filter (\n -> n /= 0) (x:xs)
| x == 0 = sieve (iter + 1) max xs
| otherwise = [x] ++ (sieve (iter+1) max (map (isModZero x) xs))
primesTo :: Integer -> [Integer]
primesTo bound
| bound < 2 = []
| otherwise = sieve 2 (isqrt bound) [2..bound] | KumarL/ProjectEuler | ProjectEuler/Utilities.hs | cc0-1.0 | 793 | 0 | 13 | 223 | 425 | 216 | 209 | 24 | 1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : $Header$
Description : Instance of class Logic for the Haskell logic
Copyright : (c) Christian Maeder, Sonja Groening, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable(Logic)
Here is the place where the classes 'Category', 'Syntax',
'StaticAnalysis', 'Sentences', and 'Logic' are instantiated for
Haskell.
Some method implementations for 'StaticAnalysis' and 'Sentences'
are still missing.
-}
module Haskell.Logic_Haskell
( Haskell(..)
, HaskellMorphism
, SYMB_ITEMS
, SYMB_MAP_ITEMS
, Haskell_Sublogics
, Symbol
, RawSymbol
) where
import Common.AS_Annotation
import Common.DefaultMorphism
import Haskell.TiPropATC()
import Haskell.HatParser
import Haskell.HatAna
import Common.Doc
import Common.DocUtils
import Common.Id
import Logic.Logic
-- a dummy datatype for the LogicGraph and for identifying the right
-- instances
data Haskell = Haskell deriving Show
instance Language Haskell where
description _ = unlines
[ "Haskell - a purely functional programming language"
, "featuring static typing, higher-order functions, polymorphism,"
, "type classes and monadic effects."
, "See http://www.haskell.org. This version is based on Programatica,"
, "see http://www.cse.ogi.edu/PacSoft/projects/programatica/" ]
type HaskellMorphism = DefaultMorphism Sign
-- abstract syntax, parsing (and printing)
type SYMB_ITEMS = ()
type SYMB_MAP_ITEMS = ()
instance Syntax Haskell HsDecls
SYMB_ITEMS SYMB_MAP_ITEMS
where
parse_basic_spec Haskell = Just hatParser
parse_symb_items Haskell = Nothing
parse_symb_map_items Haskell = Nothing
type Haskell_Sublogics = ()
type Symbol = ()
type RawSymbol = ()
instance GetRange (TiDecl PNT)
instance Sentences Haskell (TiDecl PNT) Sign HaskellMorphism Symbol where
map_sen Haskell _m s = return s
print_named Haskell sen =
pretty (sentence sen) <>
case senAttr sen of
[] -> empty
lab -> space <> text "{-" <+> text lab <+> text "-}"
instance StaticAnalysis Haskell HsDecls
(TiDecl PNT)
SYMB_ITEMS SYMB_MAP_ITEMS
Sign
HaskellMorphism
Symbol RawSymbol where
basic_analysis Haskell = Just hatAna
empty_signature Haskell = emptySign
signature_union Haskell s = return . addSign s
final_union Haskell = signature_union Haskell
is_subsig Haskell = isSubSign
subsig_inclusion Haskell = defaultInclusion
instance Logic Haskell Haskell_Sublogics
HsDecls (TiDecl PNT) SYMB_ITEMS SYMB_MAP_ITEMS
Sign
HaskellMorphism
Symbol RawSymbol ()
| nevrenato/Hets_Fork | Haskell/Logic_Haskell.hs | gpl-2.0 | 2,901 | 0 | 13 | 676 | 463 | 247 | 216 | 62 | 0 |
module Amath.Expr.ExprFuncs
( numop
, wmSize
, expSize
, expLength
, evalExpr
, matches
, applyPattern
, getVarBinding
, getVarBinding'
, getVars
, linearize
, subExpr
, isubExpr
, transformExpr
, substExpr
, substAll
, isPattern
, parseExp
, parsePM
, argChanged
, containsN
, simplifyExp
, parseDM
, dropZeroWeighted
) where
import Amath.Expr.LexExp
import Amath.Expr.ParExp
import Amath.Expr.AbsExp
import Amath.Expr.ErrM
import Amath.Expr.Digits as Dg
import Data.List
import qualified Data.Map as Map
import Control.Monad (liftM2)
{-
type ParseFun a = [Token] -> Err a
fromOK :: Err a -> a
fromOK (Ok e) = e
fromOK (Bad e) = error "fromOK: cannot be parsed."
isOk :: Err a -> Bool
isOk (Ok o) = True
isOK (Bad b) = False
isBad :: Err a -> Bool
isBad (Bad _) = True
isBad _ = False
-}
myLLexer = myLexer -- :: String -> [Token]
parseExp :: String -> Maybe Exp
parseExp str = case (pExp (myLLexer str)) of
Ok a -> Just a
Bad _ -> Nothing
parsePM :: String -> Pmemory
parsePM s = case (pPmemory (myLLexer s)) of
Ok a -> a
Bad _ -> Pmem []
{-
instance Show Exp where
show = showExp
showExp :: Exp -> String
showExp (EAdd e1 e2) = showExp e1 ++ "+" ++ showExp e2
showExp (ESub e1 e2) = showExp e1 ++ "-" ++ showExp' e2
showExp (EMul e1 e2) = showFactor e1 ++ "*" ++ showFactor e2
showExp (EDiv e1 e2) = showFactor e1 ++ "/" ++ showExp' e2
showExp (EInt n) = show n
showExp (EVar v) = show v
showExp (EEqual e1 e2) = showExp e1 ++ "=" ++ showExp e2
showExp (EExp e1 e2) = "(" ++ showExp e1 ++ "^" ++ showExp e2 ++ ")"
showExp (ENeg e) = "-(" ++ showExp e ++ ")"
showExp (EFunc (Ident n) e1) = n ++ "(" ++ showExp e1 ++ ")"
showExp (ERec i e) = "Rec:(" ++ show i ++ "," ++ showExp e ++ ")"
showExp (EF i) = "f(n-" ++ show i ++ ")"
showExp' (EInt n) = show n
showExp' (EVar v) = show v
showExp' e = "(" ++ showExp e ++ ")"
showExp' (EInt n) = show n
showExp' (EVar v) = show v
showExp' e = "(" ++ showExp e ++ ")"
showFactor :: Exp -> String
showFactor (EAdd e1 e2) = "(" ++ showExp e1 ++ "+" ++ showExp e2 ++ ")"
showFactor (ESub e1 e2) = "(" ++ showExp e1 ++ "-" ++ showExp e2 ++ ")"
showFactor exp = showExp exp
-}
numop :: Exp -> Int -- Number of binary operators in the expression
numop (EAdd exp1 exp2) = 1 + numop exp1 + numop exp2
numop (ESub exp1 exp2) = 1 + numop exp1 + numop exp2
numop (EMul exp1 exp2) = 1 + numop exp1 + numop exp2
numop (EDiv exp1 exp2) = 1 + numop exp1 + numop exp2
numop (EExp exp1 exp2) = 1 + numop exp1 + numop exp2
numop (EEqual exp1 exp2) = 1 + numop exp1 + numop exp2
numop (ENeg exp1) = 1 + numop exp1
numop (EFunc _ exp1) = numop exp1
numop _ = 0
expLength :: Exp -> Int -- length, including lengths of integers
expLength e = expSize' e 1 (\n -> length (show n)) (\x -> length x)
intsize :: Integer -> Int
intsize n = length $ filter (/=0) $ Dg.digitsRev 10 n
wmSize :: Exp -> Int
wmSize e = expSize' e 1 (fromIntegral . intsize) (\_ -> 1)
expSize :: Exp -> Int
expSize = wmSize
--expSize e = expSize' e 1 (\x -> 1) (\x -> 1)
expSize' :: Exp -> Int -> (Integer -> Int) -> (String -> Int) -> Int -- size of an expression
expSize' (EAdd exp1 exp2) op i v = op + expSize' exp1 op i v + expSize' exp2 op i v
expSize' (ESub exp1 exp2) op i v = op + expSize' exp1 op i v + expSize' exp2 op i v
expSize' (EMul exp1 exp2) op i v = op + expSize' exp1 op i v + expSize' exp2 op i v
expSize' (EDiv exp1 exp2) op i v = op + expSize' exp1 op i v + expSize' exp2 op i v
expSize' (EExp exp1 exp2) op i v = op + expSize' exp1 op i v + expSize' exp2 op i v
expSize' (EEqual exp1 exp2) op i v = op + expSize' exp1 op i v + expSize' exp2 op i v
--expSize' (EInt n) t = if t then length (show n) else 1
expSize' (ENeg exp1) op i v = 1 + expSize' exp1 op i v
expSize' (EInt n) op i v = i n
expSize' (EVar (Ident str)) op i v = v str
expSize' (EFunc (Ident "f") xs) op i v = 1
expSize' (EFunc (Ident f) xs) op i v = op + expSize' xs op i v
expSize' (EF n) op i v = 1 -- fromInteger n
expSize' (ERec _ n) op i v = expSize' n op i v
expSize' ENull op i v = 0
evalExpr = eval
eval :: Exp -> Maybe Integer -- evaluates an expression
eval (EAdd e1 e2) = liftM2 (+) (eval e1) (eval e2)
eval (ESub e1 e2) = liftM2 (-) (eval e1) (eval e2)
eval (EMul e1 e2) = liftM2 (*) (eval e1) (eval e2)
eval (EDiv e1 e2) = liftM2 div (eval e1) (eval e2)
eval (EExp e1 e2) = liftM2 (^) (eval e1) (eval e2)
eval (EInt n) = Just n
eval _ = Nothing
isPattern :: Exp -> Bool -- an expression is a pattern if it contains variables
isPattern (EInt n) = False
isPattern (ENeg e1) = isPattern e1
isPattern (ERec i e1) = isPattern e1
isPattern (EVar _) = True
isPattern ENull = False
isPattern (EAdd e1 e2) = isPattern e1 || isPattern e2
isPattern (ESub e1 e2) = isPattern e1 || isPattern e2
isPattern (EDiv e1 e2) = isPattern e1 || isPattern e2
isPattern (EMul e1 e2) = isPattern e1 || isPattern e2
isPattern (EExp e1 e2) = isPattern e1 || isPattern e2
isPattern (EFunc name arg) = isPattern arg
isPattern (EEqual e1 e2) = isPattern e1 || isPattern e2
transformExpr :: Exp -> [(Exp,Exp)] -> [Exp]
transformExpr exp [] = []
transformExpr exp xs = map (applyPattern' exp) (filter (matchExpr exp . fst) xs)
--transformExpr exp (x:xs) = if matches' exp (fst x)
-- then (applyPattern' exp x):(transformExpr exp xs)
-- else transformExpr exp xs
--transformExpr exp (x:xs) = (applyPattern exp x):(transformExpr exp xs)
-- rewrite an expression from a list of equivalent expressions (ltm)
rewriteExpr = expRewrite
exprewrite :: Exp -> [(Exp,Exp)] -> [Exp]
exprewrite exp [] = []
--exprewrite exp (x:xs) = if exp == fst x
exprewrite exp (x:xs) = if exp `matches` fst x
then (applyPattern exp x):(exprewrite exp xs)
else exprewrite exp xs
expRewrite :: Exp -> Map.Map Exp Exp -> [Exp]
--expRewrite exp [] = []
--exprewrite exp (x:xs) = if exp == fst x
expRewrite exp dmmap = case Map.lookup exp dmmap of
(Just x) -> [x]
Nothing -> []
matches :: Exp -> Exp -> Bool -- match a pattern to an expression
matches e1 e2 = if isPattern e2 then matches' e1 e2 else e1 == e2
matchExpr :: Exp -> Exp -> Bool
matchExpr e lhs = matches' e lhs && (clearBinding b == b)
where
b = nub $ binding e lhs []
binding e (EInt _ ) xs = xs
binding e (EVar id) xs = (id,e):xs
binding (ENeg e1) (ENeg e2) xs = binding e1 e2 xs ++ xs
binding (ERec i1 e1) (ERec i2 e2) xs = if i1 == i2 then binding e1 e2 xs ++ xs else xs
binding (EAdd e1 e2) (EAdd exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (ESub e1 e2) (ESub exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EMul e1 e2) (EMul exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EDiv e1 e2) (EDiv exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EExp e1 e2) (EExp exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EFunc n1 e1) (EFunc n2 exp1) xs =
if n1 == n2 then binding e1 exp1 xs ++ xs else xs
matches' :: Exp -> Exp -> Bool
matches' (EAdd e11 e12) (EAdd e21 e22) = matches' e11 e21 && matches' e12 e22
matches' (ESub e11 e12) (ESub e21 e22) = matches' e11 e21 && matches' e12 e22
matches' (EMul e11 e12) (EMul e21 e22) = matches' e11 e21 && matches' e12 e22
matches' (EDiv e11 e12) (EDiv e21 e22) = matches' e11 e21 && matches' e12 e22
matches' (EExp e11 e12) (EExp e21 e22) = matches' e11 e21 && matches' e12 e22
matches' (EFunc n1 e1) (EFunc n2 e2) = n1 == n2 && matches' e1 e2
matches' (ENeg e1) (ENeg e2) = matches' e1 e2
matches' (ERec i1 e1) (ERec i2 e2) = i1 == i2 && matches' e1 e2
matches' e1 (EVar id) = True
matches' e1 e2 = e1 == e2
applyPattern :: Exp -> (Exp,Exp) -> Exp
applyPattern e (lhs,rhs) =
if isPattern lhs && length binding > 0
then if isPattern rhs then apply'' rhs binding else rhs
else if (e == lhs) then rhs else e
where
binding = getVarBinding e lhs
--apply (EAdd e1 e2) ((EAdd exp1 exp2),rhs)
applyPattern' :: Exp -> (Exp,Exp) -> Exp
applyPattern' e (lhs,rhs) =
if length binding > 0
then apply'' rhs binding
else e
where
binding = getVarBinding e lhs
getVarBinding' :: Exp -> Exp -> [(Exp,Exp)]
getVarBinding' e lhs = map (\(x,y) -> (EVar x, y)) (getVarBinding e lhs)
getVarBinding :: Exp -> Exp -> [(Ident,Exp)]
getVarBinding e lhs = clearBinding . nub $ binding e lhs []
where
binding e (EInt _ ) xs = xs
binding e (EVar id) xs = (id,e):xs
binding (ENeg e1) (ENeg e2) xs = binding e1 e2 xs
binding (ERec i1 e1) (ERec i2 e2) xs = if i1 == i2 then binding e1 e2 xs ++ xs else xs
binding (EAdd e1 e2) (EAdd exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (ESub e1 e2) (ESub exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EMul e1 e2) (EMul exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EDiv e1 e2) (EDiv exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EExp e1 e2) (EExp exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EEqual e1 e2) (EEqual exp1 exp2) xs = binding e1 exp1 xs ++ binding e2 exp2 xs ++ xs
binding (EFunc n1 e1) (EFunc n2 e2) xs =
if n1 == n2 then binding e1 e2 xs ++ xs else xs
apply' :: Exp -> Exp -> Ident -> Exp
apply' e exp id =
case e of
(EVar id') -> if id == id' then exp else (EVar id')
(EInt n) -> (EInt n)
(ENeg e1) -> ENeg (apply' e1 exp id)
(EAdd e1 e2) -> EAdd (apply' e1 exp id) (apply' e2 exp id)
(ESub e1 e2) -> ESub (apply' e1 exp id) (apply' e2 exp id)
(EMul e1 e2) -> EMul (apply' e1 exp id) (apply' e2 exp id)
(EDiv e1 e2) -> EDiv (apply' e1 exp id) (apply' e2 exp id)
(EFunc n e1) -> EFunc n (apply' e1 exp id)
(EF n) -> EF n
apply'' :: Exp -> [(Ident,Exp)] -> Exp
apply'' e [] = e
apply'' e ((id,exp):xs) = apply'' e' xs
where
e' = apply' e exp id
getVars :: Exp -> [Ident]
getVars (EVar id) = [id]
getVars (EInt _ ) = []
getVars (EAdd e1 e2) = getVars e1 ++ getVars e2
getVars (ESub e1 e2) = getVars e1 ++ getVars e2
getVars (EMul e1 e2) = getVars e1 ++ getVars e2
getVars (EDiv e1 e2) = getVars e1 ++ getVars e2
first = fst $ head ltm
second = snd $ head ltm
bind :: [(Ident, Exp)]
bind = [(Ident "x",EInt 25),(Ident "y",EInt 25),(Ident "x",EInt 5),(Ident "y",EInt 6),(Ident "z",EInt 30)]
clearBinding :: [(Ident, Exp)] -> [(Ident, Exp)]
clearBinding xs = nubBy' (\(x,y) (p,q) -> x==p) xs
where
nubBy' eq [] = []
nubBy' eq (x:xs) = if (length nubbed == length (xs))
then x : nubbed
else nubbed
where
nubbed = nubBy' eq (filter (\ y -> not (eq x y)) xs)
-- Linearize an expression
linearize = lin
lin :: Exp -> Exp
lin e = case e of
(EAdd (EAdd a b) (ESub c d)) -> lin $ EAdd (lin a) (lin (EAdd b (ESub c d)))
(EAdd (EAdd a b) c) -> lin $ EAdd (lin a) (lin (EAdd b c))
(EMul (EMul a b) (EDiv c d)) -> lin $ EMul (lin a) (lin (EMul b (EDiv c d)))
(EMul (EMul a b) c) -> lin $ EMul (lin a) (lin (EMul b c))
(EAdd a b) -> EAdd (lin a) (lin b)
(ESub a b) -> ESub (lin a) (lin b)
(EDiv a b) -> EDiv (lin a) (lin b)
(EMul a b) -> EMul (lin a) (lin b)
(EFunc name exp) -> EFunc name (lin exp)
e -> e
-- indexed list of sub expressions
isubExpr :: Exp -> Bool -> [(Exp,Int)]
isubExpr e atomic = indexedList $ subExpr e atomic
indexedList :: Ord t => [t] -> [(t, Int)]
indexedList explst = concat $ map ((flip zip) [1..]) (group $ sort explst)
-- Subexpressions of an expression
-- Requies the input to be linearized before calling this function
subExpr = sub
sub :: Exp -- input expression, linearized
-> Bool -- whether atomic expressions are to be included
-> [Exp] -- list of all subexpressions
sub exp t = map lin $ case exp of
(EAdd a e@(EAdd b c)) -> sub a t ++ sub (EAdd a b) t ++ sub e t ++ [exp] ++ subAdd (EAdd a b) c
(EAdd a e@(ESub b c)) -> sub a t ++ sub (EAdd a b) t ++ sub e t ++ [exp]
(EAdd a b) -> sub a t ++ sub b t ++ [exp]
(EMul a e@(EMul b c)) -> sub a t ++ sub (EMul a b) t ++ sub e t ++ [exp] ++ subMul (EMul a b) c
(EMul a e@(EDiv b c)) -> sub a t ++ sub (EMul a b) t ++ sub e t ++ [exp]
(EMul a b) -> sub a t ++ sub b t ++ [exp]
(ESub (EAdd a b) c) -> sub a t ++ sub (EAdd a b) t ++ sub (ESub b c) t ++ [exp]
(ESub a b) -> sub a t ++ sub b t ++ [exp]
(EDiv (EMul a b) c) -> sub a t ++ sub (EMul a b) t ++ sub (EDiv b c) t ++ [exp]
(EDiv a b) -> sub a t ++ sub b t ++ [exp]
(EFunc name expr) -> sub expr t ++ [exp]
--(ENeg (EInt n)) -> if t then [exp] else []
--(ENeg (EVar v)) -> if t then [exp] else []
(ENeg a) -> sub a t ++ [exp]
(EInt n) -> if t then [exp] else []
(EVar v) -> if t then [exp] else []
(EF i) -> [exp]
subAdd :: Exp -> Exp -> [Exp]
subAdd e1 e2 = case e2 of
(EAdd a b) -> [EAdd e1 a] ++ subAdd (EAdd e1 a) b
_ -> []
subMul :: Exp -> Exp -> [Exp]
subMul e1 e2 = case e2 of
(EMul a b) -> [EMul e1 a] ++ subMul (EAdd e1 a) b
_ -> []
-- substitute all occurences of an expression with another in the given exp
-- return the original exp if no occurence found
substAll :: Exp -- exp in which to substitute
-> (Exp, Exp) -- replace all occurences of first with second
-> Exp -- return the new exp
substAll wm p@(fst,snd) = if wm == fst then snd else case wm of
(EAdd a b) -> EAdd (substAll a p) (substAll b p)
(ESub a b) -> ESub (substAll a p) (substAll b p)
(EMul a b) -> EMul (substAll a p) (substAll b p)
(EDiv a b) -> EDiv (substAll a p) (substAll b p)
(EExp a b) -> EExp (substAll a p) (substAll b p)
(EFunc n a) -> EFunc n (substAll a p)
(EEqual a b) -> EEqual (substAll a p) (substAll b p)
(ENeg a) -> ENeg (substAll a p)
(ERec i a) -> ERec i (substAll a p)
e -> if e == fst then snd else e
-- substitute an expression, return multiple expressions each with one substitution
substExpr :: Exp -- expression into which to substitute, linearized
-> (Exp, Exp) -- look for first expression, and replace with the second if found
-> [Exp] -- list of expressions with substitution
substExpr wm p = nub
. filter (/= wm)
. map lin $ substExpr' wm p
substExpr' :: Exp -> (Exp,Exp) -> [Exp]
substExpr' wm p@(fst,snd) = if wm == fst then [snd] else case wm of
(EAdd a (EAdd b c)) -> constructAdd a (EAdd b c) p ++ constructAdd (EAdd a b) c p
(EAdd a (ESub b c)) -> constructAdd a (ESub b c) p ++ constructSub (EAdd a b) c p
(EAdd a b) -> constructAdd a b p
(EMul a (EMul b c)) -> constructMul a (EMul b c) p ++ constructMul (EMul a b) c p
(EMul a (EDiv b c)) -> constructMul a (EDiv b c) p ++ constructDiv (EMul a b) c p
(EMul a b) -> constructMul a b p
(ESub (EAdd a b) c) -> constructAdd a (ESub b c) p ++ constructSub (EAdd a b) c p
(ESub a b) -> constructSub a b p
(EDiv (EMul a b) c) -> constructMul a (EDiv b c) p ++ constructDiv (EMul a b) c p
(EDiv a b) -> constructDiv a b p
(EFunc name arg) -> map (\x -> EFunc name x) (substExpr arg p)
(ENeg a) -> map (\x -> ENeg x) (substExpr a p)
e -> if e == fst then [snd] else [e]
constructAdd a b p = -- :: Exp -> Exp -> (Exp,Exp) -> [Exp]
let a' = substExpr a p
b' = substExpr b p
in map (\e -> EAdd e b) a' ++ map (\e -> EAdd a e) b'
constructSub a b p =
let a' = substExpr a p
b' = substExpr b p
in map (\e -> ESub e b) a' ++ map (\e -> ESub a e) b'
constructMul a b p = -- :: Exp -> Exp -> (Exp,Exp) -> [Exp]
let a' = substExpr a p
b' = substExpr b p
in map (\e -> EMul e b) a' ++ map (\e -> EMul a e) b'
constructDiv a b p = -- :: Exp -> Exp -> (Exp,Exp) -> [Exp]
let a' = substExpr a p
b' = substExpr b p
in map (\e -> EDiv e b) a' ++ map (\e -> EDiv a e) b'
subst :: Exp -> [(Exp,Int)] -> Exp -> Exp
subst e1 e2s e3 = fst $ subst' 1 e1 e2s e3
subst' :: Int -> Exp -> [(Exp,Int)] -> Exp -> (Exp,Int)
subst' occ expr1 expr2s e =
let (incr, found) = if fst (head expr2s) == e && (any (==occ) (map snd expr2s) || snd (head expr2s) == 0)
then (occ + 1, True)
else (if fst (head expr2s) == e then (occ + 1) else occ, False)
in if found
then (expr1, incr)
else case e of
EAdd a (EAdd b c) -> let (e1, i1) = subst' incr expr1 expr2s a
(e2, i2) = subst' i1 expr1 expr2s (EAdd b c)
in (EAdd e1 e2, i2)
EAdd a b -> let (e1, i1) = subst' incr expr1 expr2s a
(e2, i2) = subst' i1 expr1 expr2s b
in (EAdd e1 e2, i2)
ESub a b -> let (e1, i1) = subst' incr expr1 expr2s a
(e2, i2) = subst' i1 expr1 expr2s b
in (ESub e1 e2, i2)
EMul a (EMul b c) -> let (e1, i1) = subst' incr expr1 expr2s (EMul a b)
(e2, i2) = subst' i1 expr1 expr2s c
in (EMul e1 e2, i2)
EMul a b -> let (e1, i1) = subst' incr expr1 expr2s a
(e2, i2) = subst' i1 expr1 expr2s b
in (EMul e1 e2, i2)
EDiv a b -> let (e1, i1) = subst' incr expr1 expr2s a
(e2, i2) = subst' i1 expr1 expr2s b
in (EDiv e1 e2, i2)
_ -> (e, incr)
-- some example expressions for testing
ex :: Exp
ex = EMul (EMul (EInt 1) (EInt 10)) (EMul (EMul (EInt 2) (EInt 3)) (EDiv (EInt 5) (EInt 9)))
{-
ex2 = fromOK $ parseExp "(50+3)/2"
ex2' = fromOK $ parseExp "(50+3)-20"
ex3 = fromOK $ parseExp "(x+y)/z"
ex4 = fromOK $ parseExp "x/z+y/z"
-}
ltm :: [(Exp,Exp)]
ltm = [(EDiv (EVar (Ident "x")) (EVar (Ident "x")),EInt 1)]
-- check if the argument of any function is changed in the two expressions
argChanged :: Exp -> Exp -> Bool
argChanged (EFunc f1 e1) (EFunc f2 e2) = if f1 == f2 then e1 /= e2 else False
argChanged (EF n1) (EF n2) = n1 /= n2
argChanged (EEqual e1 e2) (EEqual n1 n2) = argChanged e1 n1 || argChanged e2 n2
argChanged (EAdd e1 e2) (EAdd n1 n2) = argChanged e1 n1 || argChanged e2 n2
argChanged (ESub e1 e2) (ESub n1 n2) = argChanged e1 n1 || argChanged e2 n2
argChanged (EMul e1 e2) (EMul n1 n2) = argChanged e1 n1 || argChanged e2 n2
argChanged (EDiv e1 e2) (EDiv n1 n2) = argChanged e1 n1 || argChanged e2 n2
argChanged (EExp e1 e2) (EExp n1 n2) = argChanged e1 n1 || argChanged e2 n2
argChanged (ERec n1 e1) (ERec n2 e2) = if n1 == n2 then argChanged e1 e2 else False
argChanged _ _ = False
containsN :: Exp -> Bool
containsN e = case e of
(EEqual a b) -> containsN a || containsN b
(EAdd a b) -> containsN a || containsN b
(EMul a b) -> containsN a || containsN b
(ESub a b) -> containsN a || containsN b
(EDiv a b) -> containsN a || containsN b
(EExp a b) -> containsN a || containsN b
(EFunc name expr) -> if name == (Ident "f") then False else containsN expr
(ENeg a) -> containsN a
(ERec _ a) -> containsN a
(EInt n) -> False
(EVar v) -> v == Ident "n"
(EF i) -> False
ENull -> False
-- simplify an expression by adding, subtracting, multiplying or
-- dividing any constants (integers)
simplifyExp = simplify
simplify :: Exp -> Exp
simplify (ENeg e) = ENeg (simplify e)
simplify (EFunc f e) = EFunc f (simplify e)
simplify (ERec i e) = ERec i (simplify e)
simplify (EAdd (EInt i1) (EInt i2)) = EInt (i1+i2)
simplify (EAdd (EInt i1) (EAdd (EInt i2) e1)) = simplify $ EAdd (EInt (i1+i2)) e1
simplify (EAdd (EAdd e1 (EInt i1)) (EInt i2)) = simplify $ EAdd e1 (EInt (i1+i2))
simplify (EAdd e1 e2) = EAdd (simplify e1) (simplify e2)
simplify (ESub (EInt i1) (EInt i2)) =
if (i1-i2 >= 0) then (EInt (i1-i2)) else (ENeg (EInt (i2-i1)))
simplify (ESub e1 e2) = ESub (simplify e1) (simplify e2)
simplify (EMul (EInt i1) (EInt i2)) = EInt (i1*i2)
simplify (EMul (EInt i1) (EMul (EInt i2) e1)) = simplify $ EMul (EInt (i1*i2)) e1
simplify (EMul (EMul e1 (EInt i1)) (EInt i2)) = simplify $ EMul e1 (EInt (i1*i2))
simplify (EMul e1 e2) = EMul (simplify e1) (simplify e2)
simplify (EDiv (EInt i1) (EInt 0)) = EDiv (EInt i1) (EInt 0)
simplify e@(EDiv (EInt i1) (EInt i2)) =
if (i1 `mod` i2 == 0) then EInt (i1 `div` i2) else e
simplify (EDiv e1 e2) = EDiv (simplify e1) (simplify e2)
simplify (EExp (EInt i1) (EInt i2)) = EInt (i1 ^ i2)
simplify (EExp e1 e2) = EExp (simplify e1) (simplify e2)
simplify (EEqual e1 e2) = EEqual (simplify e1) (simplify e2)
simplify e = e
-- parses the Ltm file, generating a list of equations.
-- an equation is a pair of expressions, i.e. left and right expression
parseDM :: String -> [(Exp,Exp)]
parseDM dmstr = [(e1,e2) | x@(Just (EEqual e1 e2)) <- temp]
where temp = map (parseExp) (lines dmstr)
dropZeroWeighted :: Pmemory -> [PRule]
dropZeroWeighted (Pmem xs) = filter check' xs
where
check' x@(Rule name value list) = value > 0
| arnizamani/SeqSolver | Amath/Expr/ExprFuncs.hs | gpl-2.0 | 21,913 | 2 | 17 | 6,491 | 9,613 | 4,862 | 4,751 | 384 | 17 |
-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)
-- Released under the GNU GPL, see LICENSE
module Graphics.Implicit.Export.Render.TesselateLoops (tesselateLoop) where
import Graphics.Implicit.Definitions
import Graphics.Implicit.Export.Render.Definitions
import Graphics.Implicit.Export.Util (centroid)
import Data.VectorSpace
import Data.Cross
tesselateLoop :: ℝ -> Obj3 -> [[ℝ3]] -> [TriSquare]
tesselateLoop _ _ [] = []
tesselateLoop _ _ [[a,b],[_,c],[_,_]] = return $ Tris [(a,b,c)]
{-
#____# #____#
| | | |
# # -> #____#
| | | |
#____# #____#
-}
tesselateLoop res obj [[_,_], as@(_:_:_:_),[_,_], bs@(_:_:_:_)] | length as == length bs =
concat $ map (tesselateLoop res obj) $
[[[a1,b1],[b1,b2],[b2,a2],[a2,a1]] | ((a1,b1),(a2,b2)) <- zip (init pairs) (tail pairs)]
where pairs = zip (reverse as) bs
tesselateLoop res obj [as@(_:_:_:_),[_,_], bs@(_:_:_:_), [_,_] ] | length as == length bs =
concat $ map (tesselateLoop res obj) $
[[[a1,b1],[b1,b2],[b2,a2],[a2,a1]] | ((a1,b1),(a2,b2)) <- zip (init pairs) (tail pairs)]
where pairs = zip (reverse as) bs
{-
#__#
| | -> if parallegram then quad
#__#
-}
tesselateLoop _ _ [[a,_],[b,_],[c,_],[d,_]] | centroid [a,c] == centroid [b,d] =
let
b1 = normalized $ a ^-^ b
b2 = normalized $ c ^-^ b
b3 = b1 `cross3` b2
in [Sq (b1,b2,b3) (a ⋅ b3) (a ⋅ b1, c ⋅ b1) (a ⋅ b2, c ⋅ b2) ]
{-
#__# #__#
| | -> | /|
#__# #/_#
-}
tesselateLoop res obj [[a,_],[b,_],[c,_],[d,_]] | obj (centroid [a,c]) < res/30 =
return $ Tris $ [(a,b,c),(a,c,d)]
-- Fallback case: make fans
tesselateLoop res obj pathSides = return $ Tris $
let
path' = concat $ map init pathSides
(early_tris,path) = shrinkLoop 0 path' res obj
in if null path
then early_tris
else let
mid@(_,_,_) = centroid path
midval = obj mid
preNormal = foldl1 (^+^) $
[ a `cross3` b | (a,b) <- zip path (tail path ++ [head path]) ]
preNormalNorm = magnitude preNormal
normal = preNormal ^/ preNormalNorm
deriv = (obj (mid ^+^ (normal ^* (res/100)) ) ^-^ midval)/res*100
mid' = mid ^-^ normal ^* (midval/deriv)
in if abs midval > res/50 && preNormalNorm > 0.5 && abs deriv > 0.5
&& abs (midval/deriv) < 2*res && 3*abs (obj mid') < abs midval
then early_tris ++ [(a,b,mid') | (a,b) <- zip path (tail path ++ [head path]) ]
else early_tris ++ [(a,b,mid) | (a,b) <- zip path (tail path ++ [head path]) ]
shrinkLoop :: Int -> [ℝ3] -> ℝ -> Obj3 -> ([Triangle], [ℝ3])
shrinkLoop _ path@[a,b,c] res obj =
if abs (obj $ centroid [a,b,c]) < res/50
then
( [(a,b,c)], [])
else
([], path)
shrinkLoop n path@(a:b:c:xs) res obj | n < length path =
if abs (obj (centroid [a,c])) < res/50
then
let (tris,remainder) = shrinkLoop 0 (a:c:xs) res obj
in ((a,b,c):tris, remainder)
else
shrinkLoop (n+1) (b:c:xs ++ [a]) res obj
shrinkLoop _ path _ _ = ([],path)
| silky/ImplicitCAD | Graphics/Implicit/Export/Render/TesselateLoops.hs | gpl-2.0 | 3,170 | 0 | 24 | 860 | 1,609 | 898 | 711 | 55 | 3 |
--
-- Copyright (c) 2013 Bonelli Nicola <bonelli@antifork.org>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
module CGrep.Lang (Lang(..), langMap, getFileLang, splitLangList,
dumpLangMap, dumpLangRevMap) where
import qualified Data.Map as Map
import System.FilePath(takeExtension, takeFileName)
import Control.Monad
import Control.Applicative
import Data.Maybe
import Options
import Util
data Lang = Awk | C | Cpp | Cabal | Csharp | Chapel | Coffee | Conf | Css | CMake | D | Erlang | Fsharp | Go | Haskell |
Html | Java | Javascript | Latex | Lua | Make | OCaml | ObjectiveC |
Perl | PHP | Python | Ruby | Scala | Tcl | Text | Shell | Verilog | VHDL | Vim
deriving (Read, Show, Eq, Ord, Bounded)
data FileType = Name String | Ext String
deriving (Eq, Ord)
instance Show FileType where
show (Name x) = x
show (Ext e) = "*." ++ e
type LangMapType = Map.Map Lang [FileType]
type LangRevMapType = Map.Map FileType Lang
langMap :: LangMapType
langMap = Map.fromList [
(Awk, [Ext "awk", Ext "mawk", Ext "gawk"]),
(C, [Ext "c", Ext "C"]),
(Cpp, [Ext "cpp", Ext "CPP", Ext "cxx", Ext "cc", Ext "cp", Ext "tcc", Ext "h", Ext "H", Ext "hpp", Ext "ipp", Ext "HPP", Ext "hxx", Ext "hh", Ext "hp"]),
(Cabal, [Ext "cabal"]),
(Csharp, [Ext "cs", Ext "CS"]),
(Coffee, [Ext "coffee"]),
(Conf, [Ext "conf", Ext "cfg", Ext "doxy"]),
(Chapel, [Ext "chpl"]),
(Css, [Ext "css"]),
(CMake, [Name "CMakeLists.txt", Ext "cmake"]),
(D, [Ext "d", Ext "D"]),
(Erlang, [Ext "erl", Ext "ERL",Ext "hrl", Ext "HRL"]),
(Fsharp, [Ext "fs", Ext "fsx", Ext "fsi"]),
(Go, [Ext "go"]),
(Haskell, [Ext "hs", Ext "lhs", Ext "hsc"]),
(Html, [Ext "htm", Ext "html"]),
(Java, [Ext "java"]),
(Javascript,[Ext "js"]),
(Latex, [Ext "latex", Ext "tex"]),
(Lua, [Ext "lua"]),
(Make, [Name "Makefile", Name "makefile", Name "GNUmakefile", Ext "mk", Ext "mak"]),
(OCaml , [Ext "ml", Ext "mli"]),
(ObjectiveC,[Ext "m", Ext "mi"]),
(Perl, [Ext "pl", Ext "pm", Ext "pm6", Ext "plx", Ext "perl"]),
(PHP, [Ext "php", Ext "php3", Ext "php4", Ext "php5",Ext "phtml"]),
(Python, [Ext "py", Ext "pyx", Ext "pxd", Ext "pxi", Ext "scons"]),
(Ruby, [Ext "rb", Ext "ruby"]),
(Scala, [Ext "scala"]),
(Tcl, [Ext "tcl", Ext "tk"]),
(Text, [Ext "txt", Ext "md", Name "README", Name "INSTALL"]),
(Shell, [Ext "sh", Ext "bash", Ext "csh", Ext "tcsh", Ext "ksh", Ext "zsh"]),
(Verilog, [Ext "v", Ext "vh", Ext "sv"]),
(VHDL, [Ext "vhd", Ext "vhdl"]),
(Vim, [Ext "vim"])
]
langRevMap :: LangRevMapType
langRevMap = Map.fromList $ concatMap (\(l, xs) -> map (\x -> (x,l)) xs ) $ Map.toList langMap
-- utility functions
lookupFileLang :: FilePath -> Maybe Lang
lookupFileLang f = Map.lookup (Name $ takeFileName f) langRevMap <|> Map.lookup (Ext (let name = takeExtension f in case name of ('.':xs) -> xs; _ -> name )) langRevMap
forcedLang :: Options -> Maybe Lang
forcedLang Options{ force_language = l }
| Nothing <- l = Nothing
| otherwise = Map.lookup (Ext $ fromJust l) langRevMap <|> Map.lookup (Name $ fromJust l) langRevMap
getFileLang :: Options -> FilePath -> Maybe Lang
getFileLang opts f = forcedLang opts <|> lookupFileLang f
dumpLangMap :: LangMapType -> IO ()
dumpLangMap m = forM_ (Map.toList m) $ \(l, ex) ->
putStrLn $ show l ++ [ ' ' | _ <- [length (show l)..12]] ++ "-> " ++ show ex
dumpLangRevMap :: LangRevMapType -> IO ()
dumpLangRevMap m = forM_ (Map.toList m) $ \(ext, l) ->
putStrLn $ show ext ++ [ ' ' | _ <- [length (show ext)..12 ]] ++ "-> " ++ show l
splitLangList :: [String] -> ([Lang], [Lang], [Lang])
splitLangList = foldl run ([],[],[])
where run :: ([Lang], [Lang], [Lang]) -> String -> ([Lang], [Lang], [Lang])
run (l1, l2, l3) l
| '+':xs <- l = (l1, prettyRead xs "Lang" : l2, l3)
| '-':xs <- l = (l1, l2, prettyRead xs "Lang" : l3)
| otherwise = (prettyRead l "Lang" : l1, l2, l3)
| beni55/cgrep | src/CGrep/Lang.hs | gpl-2.0 | 4,916 | 0 | 16 | 1,248 | 1,891 | 1,053 | 838 | 79 | 2 |
{-----------------------------------------------------------------
(c) 2008-2009 Markus Dittrich
This program is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public
License Version 3 as published by the Free Software Foundation.
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 Version 3 for more details.
You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
--------------------------------------------------------------------}
-- | main archy driver
module Main where
-- imports
import System.Console.Readline
-- local imports
import Parser
import CalculatorState
import HelpParser
import InfoRoutines
import Messages
import Prelude
import PrettyPrint
import TokenParser
-- | main
main :: IO ()
main = do
show_greeting
parse_it defaultCalcState
-- | main parse function
parse_it :: CalcState -> IO ()
parse_it state = do
-- prompt and get a line from stdin
input <- readline $ color_string Red "husky> "
case input of
Nothing -> parse_it state
Just "" -> parse_it state -- continue w/o parsing
Just "\\q" -> confirm_and_exit
>>= \ans -> case ans of -- quit after confirmation
True -> return () -- otherwise continue
False -> parse_it state
Just "\\v" -> list_variables state -- list all defined
>> parse_it state -- variables
Just "\\f" -> list_functions state -- list all defined
>> parse_it state -- functions
Just "\\t" -> show_time -- show current time
>> parse_it state
Just line -> do -- otherwise calculate
addHistory line
{- parse it as a potential help request if it succeeds we
parse the next command line, otherwise we channel it
into the calculator parser -}
case runParser help state "" line of
Right helpMsg -> putStr helpMsg
>> parse_it state
Left _ ->
-- parse it as a calculation or unit conversion
case runParser main_parser state "" line of
Left er -> print_error_message (show er) line
>> parse_it state
{- if the parser succeeds we do one of the following:
1) If the return value is a DblResult or UnitResult we
just print it
2) If the return value is a ErrResult we print the
the associated error string -}
Right (result, newState) ->
case result of
DblResult d -> husky_result $ (show d):[""]
UnitResult (v,u) -> husky_result $ (show v):[u]
ErrResult err -> (putStrLn $ "Error: " ++ err)
StrResult str -> husky_result $ str:[""]
>> parse_it newState
| markusle/husky | src/husky.hs | gpl-3.0 | 3,302 | 0 | 24 | 1,092 | 463 | 232 | 231 | 46 | 13 |
{-# LANGUAGE ScopedTypeVariables, RecordWildCards, Rank2Types, ExistentialQuantification #-}
-----------------------------------------------------------------------------
-- |
-- Module : HEP.Automation.EventChain.File
-- Copyright : (c) 2012,2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-- File operation
--
-----------------------------------------------------------------------------
module HEP.Automation.EventChain.File where
-- from other packages
import Data.Conduit
import Data.Conduit.Binary
import qualified Data.Conduit.List as CL
import Data.Conduit.Zlib
import qualified Data.Traversable as T
import System.IO
import Text.XML.Stream.Parse
-- from other hep-platform packages
import HEP.Parser.LHE.Conduit
import HEP.Parser.LHE.Type
-- from this package
import HEP.Automation.EventChain.Type.Process
-- | get parsed LHEvent from a ungzipped lhe file.
evtsHandle :: Bool -- ^ is zipped
-> Handle
-> Source IO LHEvent
evtsHandle p h
| p = sourceHandle h =$= ungzip =$= parseBytes def =$= parseEvent
| otherwise = sourceHandle h =$= parseBytes def =$= parseEvent
-- |
getLHEvents :: FilePath -> IO [LHEvent]
getLHEvents fn = do
h <- openFile fn ReadMode
evts <- evtsHandle True h $$ CL.consume
return evts
-- |
makeLHEProcessMap :: ProcessMap FilePath -> IO (ProcessMap [LHEvent])
makeLHEProcessMap = T.mapM getLHEvents
| wavewave/evchain | lib/HEP/Automation/EventChain/File.hs | gpl-3.0 | 1,589 | 0 | 9 | 341 | 265 | 153 | 112 | 25 | 1 |
{-|
A 'Transaction' represents a movement of some commodity(ies) between two
or more accounts. It consists of multiple account 'Posting's which balance
to zero, a date, and optional extras like description, cleared status, and
tags.
-}
module Hledger.Data.Transaction (
-- * Transaction
nullsourcepos,
nulltransaction,
txnTieKnot,
-- settxn,
-- * operations
showAccountName,
hasRealPostings,
realPostings,
virtualPostings,
balancedVirtualPostings,
transactionsPostings,
isTransactionBalanced,
-- nonzerobalanceerror,
-- * date operations
transactionDate2,
-- * arithmetic
transactionPostingBalances,
balanceTransaction,
-- * rendering
showTransaction,
showTransactionUnelided,
-- * misc.
tests_Hledger_Data_Transaction
)
where
import Data.List
import Data.Maybe
import Data.Time.Calendar
import Test.HUnit
import Text.Printf
import qualified Data.Map as Map
import Text.Parsec.Pos
import Hledger.Utils
import Hledger.Data.Types
import Hledger.Data.Dates
import Hledger.Data.Posting
import Hledger.Data.Amount
instance Show Transaction where show = showTransactionUnelided
instance Show ModifierTransaction where
show t = "= " ++ mtvalueexpr t ++ "\n" ++ unlines (map show (mtpostings t))
instance Show PeriodicTransaction where
show t = "~ " ++ ptperiodicexpr t ++ "\n" ++ unlines (map show (ptpostings t))
nullsourcepos :: SourcePos
nullsourcepos = initialPos ""
nulltransaction :: Transaction
nulltransaction = Transaction {
tsourcepos=nullsourcepos,
tdate=nulldate,
tdate2=Nothing,
tstatus=Uncleared,
tcode="",
tdescription="",
tcomment="",
ttags=[],
tpostings=[],
tpreceding_comment_lines=""
}
{-|
Show a journal transaction, formatted for the print command. ledger 2.x's
standard format looks like this:
@
yyyy/mm/dd[ *][ CODE] description......... [ ; comment...............]
account name 1..................... ...$amount1[ ; comment...............]
account name 2..................... ..$-amount1[ ; comment...............]
pcodewidth = no limit -- 10 -- mimicking ledger layout.
pdescwidth = no limit -- 20 -- I don't remember what these mean,
pacctwidth = 35 minimum, no maximum -- they were important at the time.
pamtwidth = 11
pcommentwidth = no limit -- 22
@
-}
showTransaction :: Transaction -> String
showTransaction = showTransaction' True
showTransactionUnelided :: Transaction -> String
showTransactionUnelided = showTransaction' False
tests_showTransactionUnelided = [
"showTransactionUnelided" ~: do
let t `gives` s = assertEqual "" s (showTransactionUnelided t)
nulltransaction `gives` "0000/01/01\n\n"
nulltransaction{
tdate=parsedate "2012/05/14",
tdate2=Just $ parsedate "2012/05/15",
tstatus=Uncleared,
tcode="code",
tdescription="desc",
tcomment="tcomment1\ntcomment2\n",
ttags=[("ttag1","val1")],
tpostings=[
nullposting{
pstatus=Cleared,
paccount="a",
pamount=Mixed [usd 1, hrs 2],
pcomment="\npcomment2\n",
ptype=RegularPosting,
ptags=[("ptag1","val1"),("ptag2","val2")]
}
]
}
`gives` unlines [
"2012/05/14=2012/05/15 (code) desc ; tcomment1",
" ; tcomment2",
" $1.00",
" * a 2.00h",
" ; pcomment2",
""
]
]
-- cf showPosting
showTransaction' :: Bool -> Transaction -> String
showTransaction' elide t =
unlines $ [descriptionline]
++ newlinecomments
++ (postingsAsLines elide t (tpostings t))
++ [""]
where
descriptionline = rstrip $ concat [date, status, code, desc, samelinecomment]
date = showdate (tdate t) ++ maybe "" showedate (tdate2 t)
showdate = printf "%-10s" . showDate
showedate = printf "=%s" . showdate
status | tstatus t == Cleared = " *"
| tstatus t == Pending = " !"
| otherwise = ""
code = if length (tcode t) > 0 then printf " (%s)" $ tcode t else ""
desc = if null d then "" else " " ++ d where d = tdescription t
(samelinecomment, newlinecomments) =
case renderCommentLines (tcomment t) of [] -> ("",[])
c:cs -> (c,cs)
-- Render a transaction or posting's comment as indented, semicolon-prefixed comment lines.
renderCommentLines :: String -> [String]
renderCommentLines s = case lines s of ("":ls) -> "":map commentprefix ls
ls -> map commentprefix ls
where
commentprefix = indent . ("; "++)
-- -- Render a transaction or posting's comment as semicolon-prefixed comment lines -
-- -- an inline (same-line) comment if it's a single line, otherwise multiple indented lines.
-- commentLines' :: String -> (String, [String])
-- commentLines' s
-- | null s = ("", [])
-- | length ls == 1 = (prefix $ head ls, [])
-- | otherwise = ("", (prefix $ head ls):(map prefix $ tail ls))
-- where
-- ls = lines s
-- prefix = indent . (";"++)
postingsAsLines :: Bool -> Transaction -> [Posting] -> [String]
postingsAsLines elide t ps
| elide && length ps > 1 && isTransactionBalanced Nothing t -- imprecise balanced check
= (concatMap (postingAsLines False ps) $ init ps) ++ postingAsLines True ps (last ps)
| otherwise = concatMap (postingAsLines False ps) ps
postingAsLines :: Bool -> [Posting] -> Posting -> [String]
postingAsLines elideamount ps p =
postinglines
++ newlinecomments
where
postinglines = map rstrip $ lines $ concatTopPadded [showacct p, " ", amount, samelinecomment]
amount = if elideamount then "" else showamt (pamount p)
(samelinecomment, newlinecomments) =
case renderCommentLines (pcomment p) of [] -> ("",[])
c:cs -> (c,cs)
showacct p =
indent $ showstatus p ++ printf (printf "%%-%ds" w) (showAccountName Nothing (ptype p) (paccount p))
where
showstatus p = if pstatus p == Cleared then "* " else ""
w = maximum $ map (length . paccount) ps
showamt =
padleft 12 . showMixedAmount
tests_postingAsLines = [
"postingAsLines" ~: do
let p `gives` ls = assertEqual "" ls (postingAsLines False [p] p)
posting `gives` [" 0"]
posting{
pstatus=Cleared,
paccount="a",
pamount=Mixed [usd 1, hrs 2],
pcomment="pcomment1\npcomment2\n tag3: val3 \n",
ptype=RegularPosting,
ptags=[("ptag1","val1"),("ptag2","val2")]
}
`gives` [
" $1.00",
" * a 2.00h ; pcomment1",
" ; pcomment2",
" ; tag3: val3 "
]
]
indent :: String -> String
indent = (" "++)
-- | Show an account name, clipped to the given width if any, and
-- appropriately bracketed/parenthesised for the given posting type.
showAccountName :: Maybe Int -> PostingType -> AccountName -> String
showAccountName w = fmt
where
fmt RegularPosting = take w'
fmt VirtualPosting = parenthesise . reverse . take (w'-2) . reverse
fmt BalancedVirtualPosting = bracket . reverse . take (w'-2) . reverse
w' = fromMaybe 999999 w
parenthesise s = "("++s++")"
bracket s = "["++s++"]"
hasRealPostings :: Transaction -> Bool
hasRealPostings = not . null . realPostings
realPostings :: Transaction -> [Posting]
realPostings = filter isReal . tpostings
virtualPostings :: Transaction -> [Posting]
virtualPostings = filter isVirtual . tpostings
balancedVirtualPostings :: Transaction -> [Posting]
balancedVirtualPostings = filter isBalancedVirtual . tpostings
transactionsPostings :: [Transaction] -> [Posting]
transactionsPostings = concat . map tpostings
-- | Get the sums of a transaction's real, virtual, and balanced virtual postings.
transactionPostingBalances :: Transaction -> (MixedAmount,MixedAmount,MixedAmount)
transactionPostingBalances t = (sumPostings $ realPostings t
,sumPostings $ virtualPostings t
,sumPostings $ balancedVirtualPostings t)
-- | Is this transaction balanced ? A balanced transaction's real
-- (non-virtual) postings sum to 0, and any balanced virtual postings
-- also sum to 0.
isTransactionBalanced :: Maybe (Map.Map Commodity AmountStyle) -> Transaction -> Bool
isTransactionBalanced styles t =
-- isReallyZeroMixedAmountCost rsum && isReallyZeroMixedAmountCost bvsum
isZeroMixedAmount rsum' && isZeroMixedAmount bvsum'
where
(rsum, _, bvsum) = transactionPostingBalances t
rsum' = canonicalise $ costOfMixedAmount rsum
bvsum' = canonicalise $ costOfMixedAmount bvsum
canonicalise = maybe id canonicaliseMixedAmount styles
-- | Ensure this transaction is balanced, possibly inferring a missing
-- amount or conversion price, or return an error message.
--
-- Balancing is affected by commodity display precisions, so those may
-- be provided.
--
-- We can infer a missing real amount when there are multiple real
-- postings and exactly one of them is amountless (likewise for
-- balanced virtual postings). Inferred amounts are converted to cost
-- basis when possible.
--
-- We can infer a conversion price when all real amounts are specified
-- and the sum of real postings' amounts is exactly two
-- non-explicitly-priced amounts in different commodities (likewise
-- for balanced virtual postings).
balanceTransaction :: Maybe (Map.Map Commodity AmountStyle) -> Transaction -> Either String Transaction
balanceTransaction styles t@Transaction{tpostings=ps}
| length rwithoutamounts > 1 || length bvwithoutamounts > 1
= Left $ printerr "could not balance this transaction (can't have more than one missing amount; remember to put 2 or more spaces before amounts)"
| not $ isTransactionBalanced styles t''' = Left $ printerr $ nonzerobalanceerror t'''
| otherwise = Right t''''
where
-- maybe infer missing amounts
(rwithamounts, rwithoutamounts) = partition hasAmount $ realPostings t
(bvwithamounts, bvwithoutamounts) = partition hasAmount $ balancedVirtualPostings t
ramounts = map pamount rwithamounts
bvamounts = map pamount bvwithamounts
t' = t{tpostings=map inferamount ps}
where
inferamount p | not (hasAmount p) && isReal p = p{pamount = costOfMixedAmount (- sum ramounts)}
| not (hasAmount p) && isBalancedVirtual p = p{pamount = costOfMixedAmount (- sum bvamounts)}
| otherwise = p
-- maybe infer conversion prices, for real postings
rmixedamountsinorder = map pamount $ realPostings t'
ramountsinorder = concatMap amounts rmixedamountsinorder
rcommoditiesinorder = map acommodity ramountsinorder
rsumamounts = amounts $ sum rmixedamountsinorder
-- assumption: the sum of mixed amounts is normalised (one simple amount per commodity)
t'' = if length rsumamounts == 2 && all ((==NoPrice).aprice) rsumamounts && t'==t
then t'{tpostings=map inferprice ps}
else t'
where
-- assumption: a posting's mixed amount contains one simple amount
inferprice p@Posting{pamount=Mixed [a@Amount{acommodity=c,aprice=NoPrice}], ptype=RegularPosting}
= p{pamount=Mixed [a{aprice=conversionprice c}]}
where
conversionprice c | c == unpricedcommodity
-- assign a balancing price. Use @@ for more exact output when possible.
-- invariant: prices should always be positive. Enforced with "abs"
= if length ramountsinunpricedcommodity == 1
then TotalPrice $ abs targetcommodityamount `withPrecision` maxprecision
else UnitPrice $ abs (targetcommodityamount `divideAmount` (aquantity unpricedamount)) `withPrecision` maxprecision
| otherwise = NoPrice
where
unpricedcommodity = head $ filter (`elem` (map acommodity rsumamounts)) rcommoditiesinorder
unpricedamount = head $ filter ((==unpricedcommodity).acommodity) rsumamounts
targetcommodityamount = head $ filter ((/=unpricedcommodity).acommodity) rsumamounts
ramountsinunpricedcommodity = filter ((==unpricedcommodity).acommodity) ramountsinorder
inferprice p = p
-- maybe infer prices for balanced virtual postings. Just duplicates the above for now.
bvmixedamountsinorder = map pamount $ balancedVirtualPostings t''
bvamountsinorder = concatMap amounts bvmixedamountsinorder
bvcommoditiesinorder = map acommodity bvamountsinorder
bvsumamounts = amounts $ sum bvmixedamountsinorder
t''' = if length bvsumamounts == 2 && all ((==NoPrice).aprice) bvsumamounts && t'==t -- XXX could check specifically for bv amount inferring
then t''{tpostings=map inferprice ps}
else t''
where
inferprice p@Posting{pamount=Mixed [a@Amount{acommodity=c,aprice=NoPrice}], ptype=BalancedVirtualPosting}
= p{pamount=Mixed [a{aprice=conversionprice c}]}
where
conversionprice c | c == unpricedcommodity
= if length bvamountsinunpricedcommodity == 1
then TotalPrice $ abs targetcommodityamount `withPrecision` maxprecision
else UnitPrice $ abs (targetcommodityamount `divideAmount` (aquantity unpricedamount)) `withPrecision` maxprecision
| otherwise = NoPrice
where
unpricedcommodity = head $ filter (`elem` (map acommodity bvsumamounts)) bvcommoditiesinorder
unpricedamount = head $ filter ((==unpricedcommodity).acommodity) bvsumamounts
targetcommodityamount = head $ filter ((/=unpricedcommodity).acommodity) bvsumamounts
bvamountsinunpricedcommodity = filter ((==unpricedcommodity).acommodity) bvamountsinorder
inferprice p = p
-- tie the knot so eg relatedPostings works right
t'''' = txnTieKnot t'''
printerr s = intercalate "\n" [s, showTransactionUnelided t]
nonzerobalanceerror :: Transaction -> String
nonzerobalanceerror t = printf "could not balance this transaction (%s%s%s)" rmsg sep bvmsg
where
(rsum, _, bvsum) = transactionPostingBalances t
rmsg | isReallyZeroMixedAmountCost rsum = ""
| otherwise = "real postings are off by " ++ showMixedAmount (costOfMixedAmount rsum)
bvmsg | isReallyZeroMixedAmountCost bvsum = ""
| otherwise = "balanced virtual postings are off by " ++ showMixedAmount (costOfMixedAmount bvsum)
sep = if not (null rmsg) && not (null bvmsg) then "; " else "" :: String
-- Get a transaction's secondary date, defaulting to the primary date.
transactionDate2 :: Transaction -> Day
transactionDate2 t = fromMaybe (tdate t) $ tdate2 t
-- | Ensure a transaction's postings refer back to it.
txnTieKnot :: Transaction -> Transaction
txnTieKnot t@Transaction{tpostings=ps} = t{tpostings=map (settxn t) ps}
-- | Set a posting's parent transaction.
settxn :: Transaction -> Posting -> Posting
settxn t p = p{ptransaction=Just t}
tests_Hledger_Data_Transaction = TestList $ concat [
tests_postingAsLines,
tests_showTransactionUnelided,
[
"showTransaction" ~: do
assertEqual "show a balanced transaction, eliding last amount"
(unlines
["2007/01/28 coopportunity"
," expenses:food:groceries $47.18"
," assets:checking"
,""
])
(let t = Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "coopportunity" "" []
[posting{paccount="expenses:food:groceries", pamount=Mixed [usd 47.18], ptransaction=Just t}
,posting{paccount="assets:checking", pamount=Mixed [usd (-47.18)], ptransaction=Just t}
] ""
in showTransaction t)
,"showTransaction" ~: do
assertEqual "show a balanced transaction, no eliding"
(unlines
["2007/01/28 coopportunity"
," expenses:food:groceries $47.18"
," assets:checking $-47.18"
,""
])
(let t = Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "coopportunity" "" []
[posting{paccount="expenses:food:groceries", pamount=Mixed [usd 47.18], ptransaction=Just t}
,posting{paccount="assets:checking", pamount=Mixed [usd (-47.18)], ptransaction=Just t}
] ""
in showTransactionUnelided t)
-- document some cases that arise in debug/testing:
,"showTransaction" ~: do
assertEqual "show an unbalanced transaction, should not elide"
(unlines
["2007/01/28 coopportunity"
," expenses:food:groceries $47.18"
," assets:checking $-47.19"
,""
])
(showTransaction
(txnTieKnot $ Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "coopportunity" "" []
[posting{paccount="expenses:food:groceries", pamount=Mixed [usd 47.18]}
,posting{paccount="assets:checking", pamount=Mixed [usd (-47.19)]}
] ""))
,"showTransaction" ~: do
assertEqual "show an unbalanced transaction with one posting, should not elide"
(unlines
["2007/01/28 coopportunity"
," expenses:food:groceries $47.18"
,""
])
(showTransaction
(txnTieKnot $ Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "coopportunity" "" []
[posting{paccount="expenses:food:groceries", pamount=Mixed [usd 47.18]}
] ""))
,"showTransaction" ~: do
assertEqual "show a transaction with one posting and a missing amount"
(unlines
["2007/01/28 coopportunity"
," expenses:food:groceries"
,""
])
(showTransaction
(txnTieKnot $ Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "coopportunity" "" []
[posting{paccount="expenses:food:groceries", pamount=missingmixedamt}
] ""))
,"showTransaction" ~: do
assertEqual "show a transaction with a priced commodityless amount"
(unlines
["2010/01/01 x"
," a 1 @ $2"
," b"
,""
])
(showTransaction
(txnTieKnot $ Transaction nullsourcepos (parsedate "2010/01/01") Nothing Uncleared "" "x" "" []
[posting{paccount="a", pamount=Mixed [num 1 `at` (usd 2 `withPrecision` 0)]}
,posting{paccount="b", pamount= missingmixedamt}
] ""))
,"balanceTransaction" ~: do
assertBool "detect unbalanced entry, sign error"
(isLeft $ balanceTransaction Nothing
(Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "test" "" []
[posting{paccount="a", pamount=Mixed [usd 1]}
,posting{paccount="b", pamount=Mixed [usd 1]}
] ""))
assertBool "detect unbalanced entry, multiple missing amounts"
(isLeft $ balanceTransaction Nothing
(Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "test" "" []
[posting{paccount="a", pamount=missingmixedamt}
,posting{paccount="b", pamount=missingmixedamt}
] ""))
let e = balanceTransaction Nothing (Transaction nullsourcepos (parsedate "2007/01/28") Nothing Uncleared "" "" "" []
[posting{paccount="a", pamount=Mixed [usd 1]}
,posting{paccount="b", pamount=missingmixedamt}
] "")
assertBool "balanceTransaction allows one missing amount" (isRight e)
assertEqual "balancing amount is inferred"
(Mixed [usd (-1)])
(case e of
Right e' -> (pamount $ last $ tpostings e')
Left _ -> error' "should not happen")
let e = balanceTransaction Nothing (Transaction nullsourcepos (parsedate "2011/01/01") Nothing Uncleared "" "" "" []
[posting{paccount="a", pamount=Mixed [usd 1.35]}
,posting{paccount="b", pamount=Mixed [eur (-1)]}
] "")
assertBool "balanceTransaction can infer conversion price" (isRight e)
assertEqual "balancing conversion price is inferred"
(Mixed [usd 1.35 @@ (eur 1 `withPrecision` maxprecision)])
(case e of
Right e' -> (pamount $ head $ tpostings e')
Left _ -> error' "should not happen")
assertBool "balanceTransaction balances based on cost if there are unit prices" (isRight $
balanceTransaction Nothing (Transaction nullsourcepos (parsedate "2011/01/01") Nothing Uncleared "" "" "" []
[posting{paccount="a", pamount=Mixed [usd 1 `at` eur 2]}
,posting{paccount="a", pamount=Mixed [usd (-2) `at` eur 1]}
] ""))
assertBool "balanceTransaction balances based on cost if there are total prices" (isRight $
balanceTransaction Nothing (Transaction nullsourcepos (parsedate "2011/01/01") Nothing Uncleared "" "" "" []
[posting{paccount="a", pamount=Mixed [usd 1 @@ eur 1]}
,posting{paccount="a", pamount=Mixed [usd (-2) @@ eur 1]}
] ""))
,"isTransactionBalanced" ~: do
let t = Transaction nullsourcepos (parsedate "2009/01/01") Nothing Uncleared "" "a" "" []
[posting{paccount="b", pamount=Mixed [usd 1.00], ptransaction=Just t}
,posting{paccount="c", pamount=Mixed [usd (-1.00)], ptransaction=Just t}
] ""
assertBool "detect balanced" (isTransactionBalanced Nothing t)
let t = Transaction nullsourcepos (parsedate "2009/01/01") Nothing Uncleared "" "a" "" []
[posting{paccount="b", pamount=Mixed [usd 1.00], ptransaction=Just t}
,posting{paccount="c", pamount=Mixed [usd (-1.01)], ptransaction=Just t}
] ""
assertBool "detect unbalanced" (not $ isTransactionBalanced Nothing t)
let t = Transaction nullsourcepos (parsedate "2009/01/01") Nothing Uncleared "" "a" "" []
[posting{paccount="b", pamount=Mixed [usd 1.00], ptransaction=Just t}
] ""
assertBool "detect unbalanced, one posting" (not $ isTransactionBalanced Nothing t)
let t = Transaction nullsourcepos (parsedate "2009/01/01") Nothing Uncleared "" "a" "" []
[posting{paccount="b", pamount=Mixed [usd 0], ptransaction=Just t}
] ""
assertBool "one zero posting is considered balanced for now" (isTransactionBalanced Nothing t)
let t = Transaction nullsourcepos (parsedate "2009/01/01") Nothing Uncleared "" "a" "" []
[posting{paccount="b", pamount=Mixed [usd 1.00], ptransaction=Just t}
,posting{paccount="c", pamount=Mixed [usd (-1.00)], ptransaction=Just t}
,posting{paccount="d", pamount=Mixed [usd 100], ptype=VirtualPosting, ptransaction=Just t}
] ""
assertBool "virtual postings don't need to balance" (isTransactionBalanced Nothing t)
let t = Transaction nullsourcepos (parsedate "2009/01/01") Nothing Uncleared "" "a" "" []
[posting{paccount="b", pamount=Mixed [usd 1.00], ptransaction=Just t}
,posting{paccount="c", pamount=Mixed [usd (-1.00)], ptransaction=Just t}
,posting{paccount="d", pamount=Mixed [usd 100], ptype=BalancedVirtualPosting, ptransaction=Just t}
] ""
assertBool "balanced virtual postings need to balance among themselves" (not $ isTransactionBalanced Nothing t)
let t = Transaction nullsourcepos (parsedate "2009/01/01") Nothing Uncleared "" "a" "" []
[posting{paccount="b", pamount=Mixed [usd 1.00], ptransaction=Just t}
,posting{paccount="c", pamount=Mixed [usd (-1.00)], ptransaction=Just t}
,posting{paccount="d", pamount=Mixed [usd 100], ptype=BalancedVirtualPosting, ptransaction=Just t}
,posting{paccount="3", pamount=Mixed [usd (-100)], ptype=BalancedVirtualPosting, ptransaction=Just t}
] ""
assertBool "balanced virtual postings need to balance among themselves (2)" (isTransactionBalanced Nothing t)
]]
| kmels/hledger | hledger-lib/Hledger/Data/Transaction.hs | gpl-3.0 | 25,354 | 2 | 26 | 7,091 | 5,981 | 3,214 | 2,767 | 389 | 7 |
{-
- Copyright (C) 2014 Alexander Berntsen <alexander@plaimi.net>
-
- This file is part of virtualtennis.
-
- Virtual Tennis 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.
-
- Virtual Tennis 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 Virtual Tennis. If not, see <http://www.gnu.org/licenses/>.
-} module Visible where
import Graphics.Gloss.Data.Picture (Picture)
-- | All objects in the 'World' that need to be drawn are 'Visible' objects.
class Visible a where
-- | 'render' makes a 'Picture' of a 'Visible'.
render :: a -> Picture
| alexander-b/master-fun | src/virtualtennis/Visible.hs | gpl-3.0 | 994 | 0 | 7 | 177 | 37 | 23 | 14 | 4 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module DoublePole where
import RungeKutta
import Control.Lens
data Config = Config { _maxTimeSteps :: Int
, _gravity :: Float
, _cartMass :: Float
, _poleLength1 :: Float
, _poleLength2 :: Float
, _poleMass1 :: Float
, _poleMass2 :: Float
, _deltaTime :: Float
, _angleThreshold :: Float
, _trackLength :: Float
, _maxAngVel :: Float
, _maxVelocity :: Float}
makeLenses ''Config
newtype State = State [Float]
getPos (State s) = head s
getVel (State s) = s !! 1
getTh1 (State s) = s !! 2
getAV1 (State s) = s !! 3
getTh2 (State s) = s !! 4
getAV2 (State s) = s !! 5
defaultConfig = Config { _maxTimeSteps = 10000
, _gravity = 9.8
, _cartMass = 100
, _poleLength1 = 1.0
, _poleLength2 = 0.5
, _poleMass1 = 4.0
, _poleMass2 = 8.0
, _deltaTime = 1/60
, _angleThreshold = pi/5.0
, _trackLength = 800
, _maxAngVel = 1.0
, _maxVelocity = 1.0}
initState :: Config -> State
initState c = State [0,0,0.01,0,0,0]
step :: Float -> Config -> Float -> State -> State
step dt config action (State st0) = State st1 where
st1 = rungeKutta (stepFunc config action) dt st0
stepFunc c a st = let (State st') = stepH c a (State st) in st'
stepH :: Config -> Float -> State -> State
stepH config action st = State st' where
g = config^.gravity
force = (action - 0.5) * (config^.cartMass + m1 + m2)
cosA1 = cos (getTh1 st)
sinA1 = sin (getTh1 st)
cosA2 = cos (getTh2 st)
sinA2 = sin (getTh2 st)
av1 = getAV1 st
av2 = getAV2 st
m1 = config^.poleMass1
m2 = config^.poleMass2
l1 = config^.poleLength1
l2 = config^.poleLength2
t1 = m1 * (g * sinA1 * cosA1 - l1 * av1 ^ 2 * sinA1)
t2 = m2 * (g * sinA2 * cosA2 - l2 * av2 ^ 2 * sinA2)
d1 = m1 + m2 + (config^.cartMass) - m1 * cosA1 ^ 2 - m2 * cosA2 ^ 2
ac = (force - t1 - t2) / d1
aac1 = (g * sinA1 - ac * cosA1) / l1
aac2 = (g * sinA2 - ac * cosA2) / l2
st' = [getVel st,ac,getAV1 st,aac1,getAV2 st,aac2]
--TODO: normalize inputs to 0-1
dpToInputs :: Config -> State -> [Float]
dpToInputs config st = [pos,vel,a1,a2,av1,av2] where
pos = getPos st / (config^.trackLength)
vel = getVel st / (config^.maxVelocity)
a1 = getTh1 st / (config^.angleThreshold)
av1 = getAV1 st / (config^.maxAngVel)
a2 = getTh2 st / (config^.angleThreshold)
av2 = getAV2 st / (config^.maxAngVel)
run :: ([Float] -> Float) -> Config -> State -> Float
run f config st = result where
inputs = dpToInputs config st
output = f inputs
result = undefined
| jrraymond/pendulum | src/DoublePole.hs | gpl-3.0 | 3,060 | 0 | 15 | 1,144 | 1,077 | 589 | 488 | 76 | 1 |
{-# OPTIONS -O2 -Wall #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.Store.Transaction
(Transaction, run, Property,
Store(..),
lookupBS, lookup,
insertBS, insert,
delete, deleteIRef,
readIRef, readIRefDef, writeIRef,
readGuid, writeGuid,
isEmpty,
irefExists,
newIRef, newKey,
fromIRef, fromIRefDef,
followBy,
anchorRef, anchorRefDef)
where
import Prelude hiding (lookup)
import Control.Applicative (Applicative)
import Control.Monad (liftM)
import Control.Monad.Trans.State (StateT, runStateT, get, gets, modify)
import Control.Monad.Trans.Reader (ReaderT, runReaderT, ask)
import Control.Monad.Trans.Class (MonadTrans(..))
import Data.Binary (Binary)
import Data.Binary.Utils (encodeS, decodeS)
import Data.Store.Rev.Change (Key, Value)
import Data.Store.IRef (IRef)
import qualified Data.Store.IRef as IRef
import Data.Store.Guid (Guid)
import qualified Data.Store.Property as Property
import Data.Monoid (mempty)
import Data.Maybe (isJust)
import Data.ByteString (ByteString)
import qualified Data.Map as Map
import Data.Map (Map)
type Property t m = Property.Property (Transaction t m)
type Changes = Map Key (Maybe Value)
-- 't' is a phantom-type tag meant to make sure you run Transactions
-- with the right store
data Store t m = Store {
storeNewKey :: m Key,
storeLookup :: Key -> m (Maybe Value),
storeAtomicWrite :: [(Key, Maybe Value)] -> m ()
}
-- Define transformer stack:
newtype Transaction t m a = Transaction {
unTransaction :: ReaderT (Store t m) (StateT Changes m) a
} deriving (Monad, Applicative, Functor)
liftReaderT :: ReaderT (Store t m) (StateT Changes m) a -> Transaction t m a
liftReaderT = Transaction
liftStateT :: Monad m => StateT Changes m a -> Transaction t m a
liftStateT = liftReaderT . lift
liftInner :: Monad m => m a -> Transaction t m a
liftInner = Transaction . lift . lift
isEmpty :: Monad m => Transaction t m Bool
isEmpty = liftStateT (gets Map.null)
lookupBS :: Monad m => Guid -> Transaction t m (Maybe Value)
lookupBS guid = do
changes <- liftStateT get
case Map.lookup guid changes of
Nothing -> do
store <- liftReaderT ask
liftInner $ storeLookup store guid
Just res -> return res
insertBS :: Monad m => Guid -> ByteString -> Transaction t m ()
insertBS key = liftStateT . modify . Map.insert key . Just
delete :: Monad m => Guid -> Transaction t m ()
delete key = liftStateT . modify . Map.insert key $ Nothing
lookup :: (Monad m, Binary a) => Guid -> Transaction t m (Maybe a)
lookup = (liftM . fmap) decodeS . lookupBS
insert :: (Monad m, Binary a) => Guid -> a -> Transaction t m ()
insert key = insertBS key . encodeS
writeGuid :: (Monad m, Binary a) => Guid -> a -> Transaction t m ()
writeGuid = insert
guidExists :: Monad m => Guid -> Transaction t m Bool
guidExists = liftM isJust . lookupBS
readGuidMb :: (Monad m, Binary a) => Transaction t m a -> Guid -> Transaction t m a
readGuidMb nothingCase guid =
maybe nothingCase return =<< lookup guid
readGuidDef :: (Monad m, Binary a) => a -> Guid -> Transaction t m a
readGuidDef = readGuidMb . return
readGuid :: (Monad m, Binary a) => Guid -> Transaction t m a
readGuid guid = readGuidMb failure guid
where
failure = fail $ show guid ++ " to inexistent object dereferenced"
deleteIRef :: Monad m => IRef a -> Transaction t m ()
deleteIRef = delete . IRef.guid
readIRefDef :: (Monad m, Binary a) => a -> IRef a -> Transaction t m a
readIRefDef def = readGuidDef def . IRef.guid
readIRef :: (Monad m, Binary a) => IRef a -> Transaction t m a
readIRef = readGuid . IRef.guid
irefExists :: (Monad m, Binary a) => IRef a -> Transaction t m Bool
irefExists = guidExists . IRef.guid
writeIRef :: (Monad m, Binary a) => IRef a -> a -> Transaction t m ()
writeIRef = writeGuid . IRef.guid
fromIRef :: (Monad m, Binary a) => IRef a -> Property t m a
fromIRef iref = Property.Property (readIRef iref) (writeIRef iref)
fromIRefDef :: (Monad m, Binary a) => IRef a -> a -> Property t m a
fromIRefDef iref def = Property.Property (readIRefDef def iref) (writeIRef iref)
newKey :: Monad m => Transaction t m Key
newKey = liftInner . storeNewKey =<< liftReaderT ask
newIRef :: (Monad m, Binary a) => a -> Transaction t m (IRef a)
newIRef val = do
newGuid <- newKey
insert newGuid val
return $ IRef.unsafeFromGuid newGuid
-- Dereference the *current* value of the IRef (Will not track new
-- values of IRef, by-value and not by-name)
followBy :: (Monad m, Binary a) =>
(b -> IRef a) ->
Property t m b ->
Transaction t m (Property t m a)
followBy conv = liftM (fromIRef . conv) . Property.get
anchorRef :: (Monad m, Binary a) => String -> Property t m a
anchorRef = fromIRef . IRef.anchor
anchorRefDef :: (Monad m, Binary a) => String -> a -> Property t m a
anchorRefDef name def = flip fromIRefDef def . IRef.anchor $ name
run :: Monad m => Store t m -> Transaction t m a -> m a
run store transaction = do
(res, changes) <- (`runStateT` mempty) . (`runReaderT` store) . unTransaction $ transaction
storeAtomicWrite store $ Map.toList changes
return res
| alonho/bottle | src/Data/Store/Transaction.hs | gpl-3.0 | 5,588 | 0 | 13 | 1,471 | 1,944 | 1,024 | 920 | 114 | 2 |
-- Proof objects, proof parser and theorem-prover for prop logic
-- THIS VERSION ENCODES NAMES AS INTEGERS, THUS ALLOWING MORE RAPID COMPARISON.
module PropLogicProofLib(
Proof(Axiom, AndIntro, AndElimL, AndElimR, ImpIntro, ImpElim,
OrIntroL, OrIntroR, OrElim, NotIntro, NotElim, TrueIntro, FalseElim),
form, proof,
infer, pp, inf
) where {
import PropLogicLib;
import Parse;
-- Concrete representation of proofs for an intuitionistic propositional logic.
-- Note that a Proof value is *not* necessarily a well-formed proof.
data Proof = Axiom Name -- Axiom names are encoded as integers
| AndIntro Proof Proof
| AndElimL Proof
| AndElimR Proof
| ImpIntro Name Form Proof -- Ditto
| ImpElim Proof Proof
| OrIntroL Proof Form
| OrIntroR Proof Form
| OrElim Proof (Name, Proof) (Name, Proof) -- Ditto
| NotIntro Name Form Proof -- Ditto
| NotElim Proof Proof
| TrueIntro
| FalseElim Proof Form;
-- Parser for IPL proofs
form :: Reads Form;
form = readsForm;
proof :: Reads Proof;
proof = axiomProof <> bracketedProof <>
andIntroProof <> andElimLProof <> andElimRProof <>
impIntroProof <> impElimProof <>
orIntroLProof <> orIntroRProof <> orElimProof <>
notIntroProof <> notElimProof <>
trueIntroProof <> falseElimProof;
axiomProof = spaced identifier ~> (Axiom . encode); -- Axiom name encoded as an Int
andIntroProof =
((keyword "AndIntro" >> proof) >> proof) ~>
\x -> let { proof1 = snd (fst x);
proof2 = snd x
} in AndIntro proof1 proof2;
andElimLProof =
(keyword "AndElimL" >> proof) ~>
\x -> let prf = snd x in AndElimL prf;
andElimRProof =
(keyword "AndElimR" >> proof) ~>
\x -> let prf = snd x in AndElimR prf;
impIntroProof =
(((((keyword "ImpIntro" >> name) >> colon) >> form) >> dot) >> proof) ~>
\x -> let { prf = snd x;
y = fst (fst x);
fm = snd y;
z = fst (fst y);
nm = snd z
} in ImpIntro nm fm prf;
impElimProof =
(keyword "ImpElim" >> proof) >> proof ~>
\x -> let { prf1 = snd (fst x);
prf2 = snd x
} in ImpElim prf1 prf2;
orIntroLProof =
(keyword "OrIntroL" >> proof) >> form ~>
\x -> let { prf = snd (fst x);
fm = snd x
} in OrIntroL prf fm;
orIntroRProof =
(keyword "OrIntroR" >> proof) >> form ~>
\x -> let { prf = snd (fst x);
fm = snd x
} in OrIntroR prf fm;
orElimProof =
((((((((((keyword "OrElim" >> proof) >> (keyword "of")) >>
(keyword "Left" )) >> name) >> (keyword "->")) >> proof) >>
(keyword "Right")) >> name) >> (keyword "->")) >> proof) ~>
\u -> case u of
((((((((((_, prf), _), _), nm1), _), prf1), _), nm2), _), prf2) ->
OrElim prf (nm1, prf1) (nm2, prf2);
notIntroProof =
(((((keyword "NotIntro" >> name) >> colon) >> form) >> dot) >> proof) ~>
\u -> case u of
(((((_, nm), _), fm), _), prf) ->
NotIntro nm fm prf;
notElimProof =
((keyword "NotElim" >> proof) >> proof) ~>
\u -> case u of
((_, prf1), prf2) ->
NotElim prf1 prf2;
trueIntroProof =
keyword "TrueIntro" ~>
\u -> TrueIntro;
falseElimProof =
((keyword "FalseElim" >> proof) >> form) ~>
\u -> case u of
((_, prf), fm) ->
FalseElim prf fm;
bracketedProof = bracketed proof;
colon = spaced (char ':');
dot = spaced (char '.');
name = spaced (identifier ~> encode); -- Names are encoded as Ints
keyword s = spaced (string s);
-- I N F E R E N C E -------------------------------------------------------
infer :: Proof -> Maybe Theorem;
infer = infer1 [];
infer1 :: [Hyp] -> Proof -> Either String Theorem;
infer1 hyps prf =
case prf of {
Axiom nm -> case lookupHyp hyps nm of {
Nothing -> Left ("Bad axiom name: " ++ showName nm);
Just fm -> Right (taut nm fm)
};
AndIntro prf1 prf2 -> case ((infer1 hyps prf1), (infer1 hyps prf2)) of {
((Left s), _) -> Left s;
(_, (Left s)) -> Left s;
((Right thm1),(Right thm2)) -> Right (andIntro thm1 thm2)
};
AndElimL prf -> case (infer1 hyps prf) of {
Left s -> Left s;
Right thm -> Right (andElimL thm)
};
AndElimR prf -> case (infer1 hyps prf) of {
Left s -> Left s;
Right thm -> Right (andElimR thm)
};
ImpIntro nm fm prf -> let {hyps' = (nm,fm): hyps;
eThm = infer1 hyps' prf
} in case eThm of {
Left s -> Left s;
Right thm -> Right (disch nm thm)
};
ImpElim prf1 prf2 -> let {eThm1 = infer1 hyps prf1;
eThm2 = infer1 hyps prf2
} in case (eThm1, eThm2) of {
(Right thm1, Right thm2) ->
Right (mp thm1 thm2)
};
OrIntroL prf fm -> let eThm = infer1 hyps prf
in case eThm of {
Left s -> Left s;
Right thm -> Right (orIntroL thm fm)
};
OrIntroR prf fm -> let eThm = infer1 hyps prf
in case eThm of {
Left s -> Left s;
Right thm -> Right (orIntroR thm fm)
};
OrElim prf (nm1, prf1) (nm2, prf2) ->
case infer1 hyps prf of {
Left s -> Left s;
Right thm ->
case projForm thm of {
Disj fmL fmR ->
let { eThm1 = infer1 ((nm1, fmL) : hyps) prf1;
eThm2 = infer1 ((nm2, fmR) : hyps) prf2
} in case (eThm1, eThm2) of {
(Left s, _) -> Left s;
(_, Left s) -> Left s;
(Right thm1, Right thm2) -> Right (orElim thm thm1 thm2)
};
fm -> Left ("Not a disjunction: " ++ show fm)
}
};
NotIntro nm fm prf -> let {hyps' = (nm, fm): hyps;
eThm = infer1 hyps' prf
} in case eThm of {
Left s -> Left s;
Right thm -> Right (notIntro nm thm)
};
NotElim prf1 prf2 -> let {eThm1 = infer1 hyps prf1;
eThm2 = infer1 hyps prf2
} in case (eThm1, eThm2) of {
(Left s, _) -> Left s;
(_, Left s) -> Left s;
(Right thm1, Right thm2) -> Right (notElim thm1 thm2)
};
TrueIntro -> Right trueIntro;
FalseElim prf fm -> let eThm = infer1 hyps prf
in case eThm of {
Left s -> Left s;
Right thm -> Right (falseElim thm fm)
}
};
lookupHyp :: [(Name, Form)] -> Name -> Maybe Form;
lookupHyp hyps nm =
case hyps of {
[] -> Nothing;
(nm', fm):hyps -> if nm == nm' then
Just fm
else
lookupHyp hyps nm
};
-- Convenient functions ---------------------------------------------------
-- Parse a proof (yields an error if unparsable)
pp :: String -> Proof;
pp = unique (exact proof);
-- Infer a theorem (with error if not possible)
inf :: Proof -> Theorem;
inf prf = case infer prf of {
Left s -> error s;
Right thm -> thm
}
}
| ckaestne/CIDE | CIDE_Language_Haskell/test/fromviral/PropLogicProofLib-encoded.hs | gpl-3.0 | 9,210 | 4 | 26 | 4,514 | 2,597 | 1,409 | 1,188 | -1 | -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.DoubleClickBidManager.Queries.Listqueries
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves stored queries.
--
-- /See:/ <https://developers.google.com/bid-manager/ DoubleClick Bid Manager API Reference> for @doubleclickbidmanager.queries.listqueries@.
module Network.Google.Resource.DoubleClickBidManager.Queries.Listqueries
(
-- * REST Resource
QueriesListqueriesResource
-- * Creating a Request
, queriesListqueries
, QueriesListqueries
-- * Request Lenses
, qlXgafv
, qlUploadProtocol
, qlAccessToken
, qlUploadType
, qlPageToken
, qlPageSize
, qlCallback
) where
import Network.Google.DoubleClickBids.Types
import Network.Google.Prelude
-- | A resource alias for @doubleclickbidmanager.queries.listqueries@ method which the
-- 'QueriesListqueries' request conforms to.
type QueriesListqueriesResource =
"doubleclickbidmanager" :>
"v1.1" :>
"queries" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListQueriesResponse
-- | Retrieves stored queries.
--
-- /See:/ 'queriesListqueries' smart constructor.
data QueriesListqueries =
QueriesListqueries'
{ _qlXgafv :: !(Maybe Xgafv)
, _qlUploadProtocol :: !(Maybe Text)
, _qlAccessToken :: !(Maybe Text)
, _qlUploadType :: !(Maybe Text)
, _qlPageToken :: !(Maybe Text)
, _qlPageSize :: !(Maybe (Textual Int32))
, _qlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'QueriesListqueries' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'qlXgafv'
--
-- * 'qlUploadProtocol'
--
-- * 'qlAccessToken'
--
-- * 'qlUploadType'
--
-- * 'qlPageToken'
--
-- * 'qlPageSize'
--
-- * 'qlCallback'
queriesListqueries
:: QueriesListqueries
queriesListqueries =
QueriesListqueries'
{ _qlXgafv = Nothing
, _qlUploadProtocol = Nothing
, _qlAccessToken = Nothing
, _qlUploadType = Nothing
, _qlPageToken = Nothing
, _qlPageSize = Nothing
, _qlCallback = Nothing
}
-- | V1 error format.
qlXgafv :: Lens' QueriesListqueries (Maybe Xgafv)
qlXgafv = lens _qlXgafv (\ s a -> s{_qlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
qlUploadProtocol :: Lens' QueriesListqueries (Maybe Text)
qlUploadProtocol
= lens _qlUploadProtocol
(\ s a -> s{_qlUploadProtocol = a})
-- | OAuth access token.
qlAccessToken :: Lens' QueriesListqueries (Maybe Text)
qlAccessToken
= lens _qlAccessToken
(\ s a -> s{_qlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
qlUploadType :: Lens' QueriesListqueries (Maybe Text)
qlUploadType
= lens _qlUploadType (\ s a -> s{_qlUploadType = a})
-- | Optional pagination token.
qlPageToken :: Lens' QueriesListqueries (Maybe Text)
qlPageToken
= lens _qlPageToken (\ s a -> s{_qlPageToken = a})
-- | Maximum number of results per page. Must be between 1 and 100. Defaults
-- to 100 if unspecified.
qlPageSize :: Lens' QueriesListqueries (Maybe Int32)
qlPageSize
= lens _qlPageSize (\ s a -> s{_qlPageSize = a}) .
mapping _Coerce
-- | JSONP
qlCallback :: Lens' QueriesListqueries (Maybe Text)
qlCallback
= lens _qlCallback (\ s a -> s{_qlCallback = a})
instance GoogleRequest QueriesListqueries where
type Rs QueriesListqueries = ListQueriesResponse
type Scopes QueriesListqueries =
'["https://www.googleapis.com/auth/doubleclickbidmanager"]
requestClient QueriesListqueries'{..}
= go _qlXgafv _qlUploadProtocol _qlAccessToken
_qlUploadType
_qlPageToken
_qlPageSize
_qlCallback
(Just AltJSON)
doubleClickBidsService
where go
= buildClient
(Proxy :: Proxy QueriesListqueriesResource)
mempty
| brendanhay/gogol | gogol-doubleclick-bids/gen/Network/Google/Resource/DoubleClickBidManager/Queries/Listqueries.hs | mpl-2.0 | 5,043 | 0 | 18 | 1,201 | 806 | 466 | 340 | 113 | 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.CloudTasks.Projects.Locations.Queues.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a queue. This command will delete the queue even if it has tasks
-- in it. Note: If you delete a queue, a queue with the same name can\'t be
-- created for 7 days. WARNING: Using this method may have unintended side
-- effects if you are using an App Engine \`queue.yaml\` or \`queue.xml\`
-- file to manage your queues. Read [Overview of Queue Management and
-- queue.yaml](https:\/\/cloud.google.com\/tasks\/docs\/queue-yaml) before
-- using this method.
--
-- /See:/ <https://cloud.google.com/tasks/ Cloud Tasks API Reference> for @cloudtasks.projects.locations.queues.delete@.
module Network.Google.Resource.CloudTasks.Projects.Locations.Queues.Delete
(
-- * REST Resource
ProjectsLocationsQueuesDeleteResource
-- * Creating a Request
, projectsLocationsQueuesDelete
, ProjectsLocationsQueuesDelete
-- * Request Lenses
, plqdXgafv
, plqdUploadProtocol
, plqdAccessToken
, plqdUploadType
, plqdName
, plqdCallback
) where
import Network.Google.CloudTasks.Types
import Network.Google.Prelude
-- | A resource alias for @cloudtasks.projects.locations.queues.delete@ method which the
-- 'ProjectsLocationsQueuesDelete' request conforms to.
type ProjectsLocationsQueuesDeleteResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a queue. This command will delete the queue even if it has tasks
-- in it. Note: If you delete a queue, a queue with the same name can\'t be
-- created for 7 days. WARNING: Using this method may have unintended side
-- effects if you are using an App Engine \`queue.yaml\` or \`queue.xml\`
-- file to manage your queues. Read [Overview of Queue Management and
-- queue.yaml](https:\/\/cloud.google.com\/tasks\/docs\/queue-yaml) before
-- using this method.
--
-- /See:/ 'projectsLocationsQueuesDelete' smart constructor.
data ProjectsLocationsQueuesDelete =
ProjectsLocationsQueuesDelete'
{ _plqdXgafv :: !(Maybe Xgafv)
, _plqdUploadProtocol :: !(Maybe Text)
, _plqdAccessToken :: !(Maybe Text)
, _plqdUploadType :: !(Maybe Text)
, _plqdName :: !Text
, _plqdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsQueuesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plqdXgafv'
--
-- * 'plqdUploadProtocol'
--
-- * 'plqdAccessToken'
--
-- * 'plqdUploadType'
--
-- * 'plqdName'
--
-- * 'plqdCallback'
projectsLocationsQueuesDelete
:: Text -- ^ 'plqdName'
-> ProjectsLocationsQueuesDelete
projectsLocationsQueuesDelete pPlqdName_ =
ProjectsLocationsQueuesDelete'
{ _plqdXgafv = Nothing
, _plqdUploadProtocol = Nothing
, _plqdAccessToken = Nothing
, _plqdUploadType = Nothing
, _plqdName = pPlqdName_
, _plqdCallback = Nothing
}
-- | V1 error format.
plqdXgafv :: Lens' ProjectsLocationsQueuesDelete (Maybe Xgafv)
plqdXgafv
= lens _plqdXgafv (\ s a -> s{_plqdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plqdUploadProtocol :: Lens' ProjectsLocationsQueuesDelete (Maybe Text)
plqdUploadProtocol
= lens _plqdUploadProtocol
(\ s a -> s{_plqdUploadProtocol = a})
-- | OAuth access token.
plqdAccessToken :: Lens' ProjectsLocationsQueuesDelete (Maybe Text)
plqdAccessToken
= lens _plqdAccessToken
(\ s a -> s{_plqdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plqdUploadType :: Lens' ProjectsLocationsQueuesDelete (Maybe Text)
plqdUploadType
= lens _plqdUploadType
(\ s a -> s{_plqdUploadType = a})
-- | Required. The queue name. For example:
-- \`projects\/PROJECT_ID\/locations\/LOCATION_ID\/queues\/QUEUE_ID\`
plqdName :: Lens' ProjectsLocationsQueuesDelete Text
plqdName = lens _plqdName (\ s a -> s{_plqdName = a})
-- | JSONP
plqdCallback :: Lens' ProjectsLocationsQueuesDelete (Maybe Text)
plqdCallback
= lens _plqdCallback (\ s a -> s{_plqdCallback = a})
instance GoogleRequest ProjectsLocationsQueuesDelete
where
type Rs ProjectsLocationsQueuesDelete = Empty
type Scopes ProjectsLocationsQueuesDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsQueuesDelete'{..}
= go _plqdName _plqdXgafv _plqdUploadProtocol
_plqdAccessToken
_plqdUploadType
_plqdCallback
(Just AltJSON)
cloudTasksService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsQueuesDeleteResource)
mempty
| brendanhay/gogol | gogol-cloudtasks/gen/Network/Google/Resource/CloudTasks/Projects/Locations/Queues/Delete.hs | mpl-2.0 | 5,771 | 0 | 15 | 1,200 | 709 | 420 | 289 | 102 | 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.OpsWorks.DescribeRdsDbInstances
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes Amazon RDS instances.
--
-- Required Permissions: To use this action, an IAM user must have a Show,
-- Deploy, or Manage permissions level for the stack, or an attached policy that
-- explicitly grants permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DescribeRdsDbInstances.html>
module Network.AWS.OpsWorks.DescribeRdsDbInstances
(
-- * Request
DescribeRdsDbInstances
-- ** Request constructor
, describeRdsDbInstances
-- ** Request lenses
, drdiRdsDbInstanceArns
, drdiStackId
-- * Response
, DescribeRdsDbInstancesResponse
-- ** Response constructor
, describeRdsDbInstancesResponse
-- ** Response lenses
, drdirRdsDbInstances
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
data DescribeRdsDbInstances = DescribeRdsDbInstances
{ _drdiRdsDbInstanceArns :: List "RdsDbInstanceArns" Text
, _drdiStackId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeRdsDbInstances' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drdiRdsDbInstanceArns' @::@ ['Text']
--
-- * 'drdiStackId' @::@ 'Text'
--
describeRdsDbInstances :: Text -- ^ 'drdiStackId'
-> DescribeRdsDbInstances
describeRdsDbInstances p1 = DescribeRdsDbInstances
{ _drdiStackId = p1
, _drdiRdsDbInstanceArns = mempty
}
-- | An array containing the ARNs of the instances to be described.
drdiRdsDbInstanceArns :: Lens' DescribeRdsDbInstances [Text]
drdiRdsDbInstanceArns =
lens _drdiRdsDbInstanceArns (\s a -> s { _drdiRdsDbInstanceArns = a })
. _List
-- | The stack ID that the instances are registered with. The operation returns
-- descriptions of all registered Amazon RDS instances.
drdiStackId :: Lens' DescribeRdsDbInstances Text
drdiStackId = lens _drdiStackId (\s a -> s { _drdiStackId = a })
newtype DescribeRdsDbInstancesResponse = DescribeRdsDbInstancesResponse
{ _drdirRdsDbInstances :: List "RdsDbInstances" RdsDbInstance
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeRdsDbInstancesResponse where
type Item DescribeRdsDbInstancesResponse = RdsDbInstance
fromList = DescribeRdsDbInstancesResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _drdirRdsDbInstances
-- | 'DescribeRdsDbInstancesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drdirRdsDbInstances' @::@ ['RdsDbInstance']
--
describeRdsDbInstancesResponse :: DescribeRdsDbInstancesResponse
describeRdsDbInstancesResponse = DescribeRdsDbInstancesResponse
{ _drdirRdsDbInstances = mempty
}
-- | An a array of 'RdsDbInstance' objects that describe the instances.
drdirRdsDbInstances :: Lens' DescribeRdsDbInstancesResponse [RdsDbInstance]
drdirRdsDbInstances =
lens _drdirRdsDbInstances (\s a -> s { _drdirRdsDbInstances = a })
. _List
instance ToPath DescribeRdsDbInstances where
toPath = const "/"
instance ToQuery DescribeRdsDbInstances where
toQuery = const mempty
instance ToHeaders DescribeRdsDbInstances
instance ToJSON DescribeRdsDbInstances where
toJSON DescribeRdsDbInstances{..} = object
[ "StackId" .= _drdiStackId
, "RdsDbInstanceArns" .= _drdiRdsDbInstanceArns
]
instance AWSRequest DescribeRdsDbInstances where
type Sv DescribeRdsDbInstances = OpsWorks
type Rs DescribeRdsDbInstances = DescribeRdsDbInstancesResponse
request = post "DescribeRdsDbInstances"
response = jsonResponse
instance FromJSON DescribeRdsDbInstancesResponse where
parseJSON = withObject "DescribeRdsDbInstancesResponse" $ \o -> DescribeRdsDbInstancesResponse
<$> o .:? "RdsDbInstances" .!= mempty
| dysinger/amazonka | amazonka-opsworks/gen/Network/AWS/OpsWorks/DescribeRdsDbInstances.hs | mpl-2.0 | 5,035 | 0 | 10 | 978 | 571 | 344 | 227 | 69 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- Module : System.Statgrab
-- Copyright : (c) 2013-2015 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
-- | Monadic context and data types for managing the underlying libstatgrab FFI calls
-- with transparent resource allocation and deallocation.
module System.Statgrab
(
-- * Running the @Stats@ Monad
Stats
, runStats
, async
-- * Retrieving Statistics
, snapshot
, snapshots
, Stat
, Struct
-- * Statistic Types
, Host (..)
, CPU (..)
, CPUPercent (..)
, Memory (..)
, Load (..)
, User (..)
, Swap (..)
, FileSystem (..)
, DiskIO (..)
, NetworkIO (..)
, NetworkInterface (..)
, Page (..)
, Process (..)
, ProcessCount (..)
-- * Enums
, HostState (..)
, CPUPercentSource (..)
, DeviceType (..)
, InterfaceMode (..)
, InterfaceStatus (..)
, ProcessState (..)
, ProcessSource (..)
-- * Re-exported
, Async
, wait
) where
import Control.Applicative
import Control.Concurrent.Async (Async, wait)
import qualified Control.Concurrent.Async as Async
import qualified Control.Exception as E
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Data.IORef
import GHC.Word
import System.Statgrab.Base
import System.Statgrab.Internal
newtype Stats a = Stats { unwrap :: ReaderT (IORef Word) IO a }
deriving (Applicative, Functor, Monad, MonadIO)
-- | Run the 'Stats' Monad, bracketing libstatgrab's sg_init and sg_shutdown
-- calls via reference counting to ensure reentrancy.
runStats :: MonadIO m => Stats a -> m a
runStats = liftIO
. E.bracket (sg_init 0 >> sg_drop_privileges >> newIORef 1) destroy
. runReaderT
. unwrap
-- | Run the 'Stats' Monad asynchronously. 'wait' from the async package can
-- be used to block and retrieve the result of the asynchronous computation.
async :: Stats a -> Stats (Async a)
async (Stats s) = Stats $ do
ref <- ask
liftIO $ do
atomicModifyIORef' ref $ \ n -> (succ n, ())
Async.async $ runReaderT s ref `E.finally` destroy ref
-- | Retrieve statistics from the underlying operating system, copying them to
-- the Haskell heap and freeing the related @Ptr a@.
--
-- The *_r variants of the libstatgrab functions are used and
-- the deallocation strategy is bracketed.
snapshot :: (Stat (Struct a), Copy a) => Stats a
snapshot = liftIO (E.bracket acquireN releaseN copy)
{-# INLINE snapshot #-}
-- | Retrieve a list of statistics from the underlying operating system.
--
-- /See:/ 'snapshot'.
snapshots :: (Stat (Struct a), Copy a) => Stats [a]
snapshots = liftIO (E.bracket acquireN releaseN copyBatch)
{-# INLINE snapshots #-}
destroy :: IORef Word -> IO ()
destroy ref = do
n <- atomicModifyIORef' ref $ \n -> (pred n, n)
when (n == 1) $
void sg_shutdown
| brendanhay/statgrab | src/System/Statgrab.hs | mpl-2.0 | 3,574 | 0 | 14 | 1,026 | 678 | 405 | 273 | 69 | 1 |
module AstroData2
( Species(..)
, parseSpecies
, showSpecies ) where
import Text.Parsec
import Debug.Trace ( traceShow )
data Species = D | G | H | Hp | He | Hep | Hepp | Hm | H2 | H2p
| R | S | H2xD | Cx | Cy | Cz | Mv
deriving (Show, Read, Eq, Ord)
parseSpecies :: String -> Species
parseSpecies = read . (replace '-' 'm') . (replace '+' 'p')
showSpecies :: Species -> String
showSpecies = (replace 'p' '+') . (replace 'm' '-') . show
replace x y = map (\e -> if e == x then y else e) | kvelicka/Fizz | AstroData_parser.hs | lgpl-2.1 | 514 | 0 | 9 | 132 | 217 | 126 | 91 | 14 | 2 |
{-
Copyright 2010-2012 Cognimeta Inc.
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 TemplateHaskell, TypeFamilies, GeneralizedNewtypeDeriving, ScopedTypeVariables, MagicHash, UnboxedTuples #-}
module Cgm.System.Endian (
Endian(..),
swapHalves,
ixBytes,
littleEndianIxBytes,
bigEndianIxBytes,
platformEndianness,
platformWordEndianness,
ByteSwapped,
swapBytes,
unswapBytes,
Endianness(..),
reverseEndianness
) where
import Data.Bits
import Data.Ix
import Control.Applicative
import Foreign.Marshal.Alloc
import Foreign.Ptr
import Foreign.Storable
import Cgm.Data.Tagged
import Cgm.Data.Word
import Cgm.Data.Array
import Cgm.Data.Len
import Cgm.Data.Structured
import Cgm.Control.InFunctor
import Cgm.Control.Combinators
class (Prim w, Bits w, Num w) => Endian w where
untypedSwapBytes :: w -> w
instance Endian Word8 where
{-# INLINE untypedSwapBytes #-}
untypedSwapBytes = id
instance Endian Word16 where
{-# INLINE untypedSwapBytes #-}
untypedSwapBytes = swapHalves
instance Endian Word32 where
{-# INLINE untypedSwapBytes #-}
untypedSwapBytes = swapMask 0xff00ff 8 . swapHalves
instance Endian Word64 where
{-# INLINE untypedSwapBytes #-}
untypedSwapBytes = swapMask 0xff00ff00ff00ff 8 . swapMask 0xffff0000ffff 16 . swapHalves
instance Endian Word where
{-# INLINE untypedSwapBytes #-}
untypedSwapBytes = onWordConvB (flip liftItI untypedSwapBytes) (flip liftItI untypedSwapBytes)
{-# INLINE swapHalves #-}
swapHalves :: forall w. FiniteBits w => w -> w
swapHalves w = w `shiftR` halfBitSize .|. w `shiftL` halfBitSize where
halfBitSize = finiteBitSize (undefined :: w) `div` 2
-- | Exchange bits in mask with bits at some specified relative position (the last bits must not be in the mask)
{-# INLINE swapMask #-}
swapMask :: Bits w => w -> Int -> w -> w
swapMask mask shift w = ((w `shiftR` shift) .&. mask) .|. ((w .&. mask) `shiftL` shift)
-- | Number with byte value n in the nth byte, in order of increasing significance (starting at 0)
byteNumbers :: forall w. Endian w => w
byteNumbers = foldr (.|.) 0 $ fmap (\n -> fromIntegral n `shiftL` (8 * fromIntegral n)) $ (at :: At w) increasingBytes
increasingBytes :: forall w. Prim w => Tagged w [Word8]
increasingBytes = Tagged $ range (0, fromIntegral (primSizeOf (undefined :: w)) - 1)
singletonArray :: Prim w => w -> PrimArray Free w
singletonArray w = runSTPrimArray (mkArray 1 >>= \a -> a <$ writeArray a 0 w)
-- Indexes each byte of a word
ixBytes :: forall w. Endian w => w -> [Word8]
ixBytes w = let a = unsafePrimArrayCast (singletonArray w) :: PrimArray Free Word8 in indexArray a . unsafeLen . fromIntegral <$> (at :: At w) increasingBytes
littleEndianIxBytes :: forall w. Prim w => Tagged w [Word8]
littleEndianIxBytes = increasingBytes
bigEndianIxBytes :: forall w. Prim w => Tagged w [Word8]
bigEndianIxBytes = reverse <$> increasingBytes
data Endianness = LittleEndian | BigEndian deriving (Eq, Show)
-- | Undefined when the platform is neither big nor little endian.
{-# SPECIALIZE platformEndianness :: Tagged Word32 Endianness #-}
{-# SPECIALIZE platformEndianness :: Tagged Word64 Endianness #-}
{-# SPECIALIZE platformEndianness :: Tagged Word Endianness #-}
platformEndianness :: forall w. Endian w => Tagged w Endianness
platformEndianness = do
let plat = ixBytes (byteNumbers :: w)
l <- littleEndianIxBytes
b <- bigEndianIxBytes
if plat == l then return LittleEndian else if plat == b then return BigEndian else undefined
platformWordEndianness :: Endianness
platformWordEndianness = (at :: At Word) platformEndianness
reverseEndianness LittleEndian = BigEndian
reverseEndianness BigEndian = LittleEndian
newtype ByteSwapped w = ByteSwapped w deriving (Show)
swapBytes :: Endian w => w -> ByteSwapped w
swapBytes = ByteSwapped . untypedSwapBytes
unswapBytes :: Endian w => ByteSwapped w -> w
unswapBytes (ByteSwapped w) = untypedSwapBytes w
-- Deriving Prim fails due to unpacked tuple in readByteArray# so...
instance Prim a => Prim (ByteSwapped a) where
sizeOf# (ByteSwapped a) = sizeOf# a
alignment# (ByteSwapped a) = alignment# a
indexByteArray# arr# i# = ByteSwapped (indexByteArray# arr# i#)
readByteArray# arr# i# s# = case readByteArray# arr# i# s# of
(# s1#, x# #) -> (# s1#, ByteSwapped x# #)
writeByteArray# arr# i# (ByteSwapped a) s# = writeByteArray# arr# i# a s#
setByteArray# arr# i# j# (ByteSwapped a) s# = setByteArray# arr# i# j# a s#
indexOffAddr# arr# i# = ByteSwapped (indexOffAddr# arr# i#)
readOffAddr# arr# i# s# = case readOffAddr# arr# i# s# of
(# s1#, x# #) -> (# s1#, ByteSwapped x# #)
writeOffAddr# arr# i# (ByteSwapped a) s# = writeOffAddr# arr# i# a s#
setOffAddr# arr# i# j# (ByteSwapped a) s# = setOffAddr# arr# i# j# a s#
deriveStructured ''Endianness | Cognimeta/cognimeta-utils | src/Cgm/System/Endian.hs | apache-2.0 | 5,413 | 0 | 13 | 1,024 | 1,328 | 705 | 623 | 96 | 3 |
{-
onemax.hs
Description: Computes the sum of the bits over a boolean vector
License: GPL-3
This code creates a random boolean vector and sums all of its bits.
The time elapsed between the start and getting the result of the sum
is measured.
-}
import Data.Sequence hiding (take)
import Data.Time
import Data.Foldable hiding (concat)
import Control.DeepSeq
import System.Random
-- | Sums the bits of a boolean vector
onemax :: Seq Bool -> Int
onemax v = Data.Foldable.foldl (\y -> (\x -> if x then y+1 else y)) 0 v
-- | Complete benchmark over a vector of a given size. It generates a random
-- vector, and counts the 1 bits in it.
benchmark :: Int -> IO ()
benchmark n = do
-- Random vector generation
gen <- newStdGen
let rbools = randoms gen :: [Bool]
let vector = fromList $ take n rbools
-- Timing
start <- getCurrentTime
-- Counting
let count = onemax vector
-- Stops measuring the time.
-- Here 'deepseq' is neccessary to prevent lazy evaluation from giving us
-- an incorrect measure.
stop <- (count `deepseq` getCurrentTime)
let diffTime = diffUTCTime stop start
-- Printing
putStrLn $ concat ["Haskell-Sequence, ", show n, ", ", show diffTime]
main :: IO ()
main = do
sequence_ $ Prelude.map benchmark ((2^) <$> [4..16])
return ()
| geneura-papers/2016-ea-languages-PPSN | haskell/onemax.hs | artistic-2.0 | 1,287 | 0 | 11 | 264 | 302 | 161 | 141 | 21 | 2 |
module Emulator.InterpreterSpec where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = return ()
| intolerable/GroupProject | test/Emulator/InterpreterSpec.hs | bsd-2-clause | 121 | 0 | 6 | 23 | 44 | 24 | 20 | 6 | 1 |
{-#LANGUAGE NoImplicitPrelude, DeriveGeneric, ForeignFunctionInterface#-}
module LibMu.MuApi (
MuVM(..),
MuCtx(..),
newContext,
idOf,
nameOf,
setTrapHandler,
execute,
ctxIdOf,
ctxNameOf,
closeContext,
loadBundle,
loadHail,
handleFromSInt8,
handleFromUInt8,
handleFromSInt16,
handleFromUInt16,
handleFromSInt32,
handleFromUInt32,
handleFromSInt64,
handleFromUInt64,
handleFromFloat,
handleFromDouble,
handleFromPtr,
handleFromFp,
handleToSint8,
handleToUint8,
handleToSint16,
handleToUint16,
handleToSint32,
handleToUint32,
handleToSint64,
handleToUint64,
handleToFloat,
handleToDouble,
handleToPtr,
handleToFp,
handleFromConst,
handleFromGlobal,
handleFromFunc,
handleFromExpose,
deleteValue,
refEq,
refUlt,
extractValue,
insertValue,
extractElement,
insertElement,
newFixed,
newHybrid,
refCast,
getIref,
getFieldIref,
getElemIref,
shiftIref,
getVarPartIref,
load,
store,
cmpxchg,
atomicrmw,
fence,
newStack,
newThread,
killStack,
newCursor,
newFrame,
copyCursor,
closeCursor,
curFunc,
curFuncVer,
curInst,
dumpKeepalives,
popFramesTo,
pushFrame,
tr64IsFp,
tr64IsInt,
tr64isRef,
tr64ToFp,
tr64ToInt,
tr64ToRef,
tr64ToTag,
tr64FromFp,
tr64FromInt,
tr64FromRef,
enableWatchpoint,
disableWatchpoint,
pin,
unpin,
expose,
unexpose,
muThreadExit,
muRebindPassValues,
muRebindThrowExc,
muNotAtomic,
muRelaxex,
muConsume,
muAcquire,
muRelease,
muAcqRel,
muSeqCst,
muXchg,
muAdd,
muSub,
muAnd,
muNAnd,
muOr,
muXOr,
muMax,
muMin,
muUMax,
muUMin,
muDefault,
Int8_t,
UInt8_t,
Int16_t,
UInt16_t,
Int32_t,
UInt32_t,
Int64_t,
UInt64_t,
CChar(..),
CUChar(..),
CShort(..),
CUShort(..),
CInt(..),
CUInt(..),
CLong(..),
CULong(..),
Ptr,
MuValue,
MuIntValue,
MuFloatValue,
MuDoubleValue,
MuRefValue,
MuIRefValue,
MuStructValue,
MuArrayValue,
MuVectorValue,
MuFuncRefValue,
MuThreadRefValue,
MuStackRefValue,
MuFCRefValue,
MuTagRef64Value,
MuUPtrValue,
MuUFPValue,
MuID,
Hs_MuID,
MuName,
Hs_MuName,
MuCPtr,
MuCFP,
MuTrapHandlerResult,
MuHowToResume,
MuValuesFreer,
MuTrapHandler,
MuMemOrd,
MuAtomicRMWOp,
MuCallConv
) where
import Prelude (IO, Integral(..))
import Foreign
import Foreign.C.String (CString)
import Foreign.C.Types
import GHC.Generics
import Foreign.CStorable
--Stdint.h typedefs
type Int8_t = CChar
type UInt8_t = CUChar
type Int16_t = CShort
type UInt16_t = CUShort
type Int32_t = CInt
type UInt32_t = CUInt
type Int64_t = CLong
type UInt64_t = CULong
type MuValue = Ptr () -- Any Mu value
type MuIntValue = Ptr () -- int<n>
type MuFloatValue = Ptr () -- float
type MuDoubleValue = Ptr () -- double
type MuRefValue = Ptr () -- ref<T>
type MuIRefValue = Ptr () -- iref<T>
type MuStructValue = Ptr () -- struct<...>
type MuArrayValue = Ptr () -- array<T l>
type MuVectorValue = Ptr () -- vector<T l>
type MuFuncRefValue = Ptr () -- funcref<sig>
type MuThreadRefValue = Ptr () -- threadref
type MuStackRefValue = Ptr () -- stackref
type MuFCRefValue = Ptr () -- framecursorref
type MuTagRef64Value = Ptr () -- tagref64
type MuUPtrValue = Ptr () -- uptr
type MuUFPValue = Ptr () -- ufuncptr
-- Identifiers and names of Mu
type MuID = CUInt
type Hs_MuID = Int32
type MuName = CString
type Hs_MuName = CString
-- Convenient types for the void* type and the void(*)() type in C
type MuCPtr = Ptr ()
type MuCFP = FunPtr (IO ())
-- Result of a trap handler
type MuTrapHandlerResult = CInt
-- Used by new_thread
type MuHowToResume = CInt
muThreadExit, muRebindPassValues, muRebindThrowExc :: (Integral a) => a
muThreadExit = 0x00
muRebindPassValues = 0x01
muRebindThrowExc = 0x02
-- Used by MuTrapHandler
type MuValuesFreer = FunPtr (Ptr MuValue -> MuCPtr -> IO ())
-- Signature of the trap handler
type MuTrapHandler = FunPtr (Ptr MuCtx -> MuThreadRefValue ->
MuStackRefValue -> CInt -> Ptr MuTrapHandlerResult ->
Ptr MuStackRefValue -> Ptr (Ptr MuValue) -> Ptr CInt ->
Ptr MuValuesFreer -> Ptr MuCPtr -> Ptr MuRefValue ->
MuCPtr -> IO ())
muNotAtomic, muRelaxex, muConsume, muAcquire, muRelease, muAcqRel, muSeqCst :: (Integral a) => a
muNotAtomic = 0x00
muRelaxex = 0x01
muConsume = 0x02
muAcquire = 0x03
muRelease = 0x04
muAcqRel = 0x05
muSeqCst = 0x06
muXchg, muAdd, muSub, muAnd, muNAnd, muOr, muXOr, muMax, muMin, muUMax, muUMin :: (Integral a) => a
muXchg = 0x00
muAdd = 0x01
muSub = 0x02
muAnd = 0x03
muNAnd = 0x04
muOr = 0x05
muXOr = 0x06
muMax = 0x07
muMin = 0x08
muUMax = 0x09
muUMin = 0x0A
muDefault :: (Integral a) => a
muDefault = 0x00
-- Memory orders
type MuMemOrd = CInt
type MuAtomicRMWOp = CInt
type MuCallConv = CInt
data MuVM = MuVM {
header :: Ptr (),
new_context :: FunPtr (Ptr MuVM -> IO (Ptr MuCtx)),
id_of :: FunPtr (Ptr MuVM -> MuName -> IO Hs_MuID),
name_of :: FunPtr (Ptr MuVM -> MuID -> IO MuName),
set_trap_handler :: FunPtr (Ptr MuVM -> MuTrapHandler -> MuCPtr -> IO ()),
mvmExecute :: FunPtr (Ptr MuVM -> IO ())
} deriving (Generic)
instance CStorable MuVM
instance Storable MuVM where
sizeOf = cSizeOf
alignment = cAlignment
poke = cPoke
peek = cPeek
foreign import ccall "dynamic" mkNewContext :: FunPtr (Ptr MuVM -> IO (Ptr MuCtx)) -> Ptr MuVM -> IO (Ptr MuCtx)
foreign import ccall "dynamic" mkIdOf :: FunPtr (Ptr MuVM -> MuName -> IO Hs_MuID) -> Ptr MuVM -> MuName -> IO Hs_MuID
foreign import ccall "dynamic" mkNameOf :: FunPtr (Ptr MuVM -> MuID -> IO Hs_MuName) -> Ptr MuVM -> MuID -> IO Hs_MuName
foreign import ccall "dynamic" mkSetTrapHandler :: FunPtr (Ptr MuVM -> MuTrapHandler -> MuCPtr -> IO ()) -> Ptr MuVM -> MuTrapHandler -> MuCPtr -> IO ()
foreign import ccall "dynamic" mkExecute :: FunPtr (Ptr MuVM -> IO ()) -> Ptr MuVM -> IO ()
newContext :: Ptr MuVM -> IO (Ptr MuCtx)
newContext mvm = call0 mkNewContext new_context mvm
idOf :: Ptr MuVM -> MuName -> IO Hs_MuID
idOf = call1 mkIdOf id_of
nameOf :: Ptr MuVM -> MuID -> IO Hs_MuName
nameOf = call1 mkNameOf name_of
setTrapHandler :: Ptr MuVM -> MuTrapHandler -> MuCPtr -> IO ()
setTrapHandler = call2 mkSetTrapHandler set_trap_handler
execute :: Ptr MuVM -> IO ()
execute = call0 mkExecute mvmExecute
data MuCtx = MuCtx {
ctx_header :: Ptr (), -- Refer to internal stuff
-- Convert between IDs and names
ctx_id_of :: FunPtr (Ptr MuCtx -> MuName -> IO Hs_MuID),
ctx_name_of :: FunPtr (Ptr MuCtx -> MuID -> IO Hs_MuName),
-- Close the current context, releasing all resources
close_context :: FunPtr (Ptr MuCtx -> IO ()),
-- Load bundles and HAIL scripts
load_bundle :: FunPtr (Ptr MuCtx -> CString -> CInt -> IO ()),
load_hail :: FunPtr (Ptr MuCtx -> CString -> CInt -> IO ()),
-- Convert from C values to Mu values
handle_from_sint8 :: FunPtr (Ptr MuCtx -> Int8_t -> CInt -> IO MuIntValue),
handle_from_uint8 :: FunPtr (Ptr MuCtx -> UInt8_t -> CInt -> IO MuIntValue),
handle_from_sint16 :: FunPtr (Ptr MuCtx -> Int16_t -> CInt -> IO MuIntValue),
handle_from_uint16 :: FunPtr (Ptr MuCtx -> UInt16_t -> CInt -> IO MuIntValue),
handle_from_sint32 :: FunPtr (Ptr MuCtx -> Int32_t -> CInt -> IO MuIntValue),
handle_from_uint32 :: FunPtr (Ptr MuCtx -> UInt32_t -> CInt -> IO MuIntValue),
handle_from_sint64 :: FunPtr (Ptr MuCtx -> Int64_t -> CInt -> IO MuIntValue),
handle_from_uint64 :: FunPtr (Ptr MuCtx -> UInt64_t -> CInt -> IO MuIntValue),
handle_from_float :: FunPtr (Ptr MuCtx -> CFloat -> IO MuFloatValue),
handle_from_double :: FunPtr (Ptr MuCtx -> CDouble -> IO MuDoubleValue),
handle_from_ptr :: FunPtr (Ptr MuCtx -> MuID -> MuCPtr -> IO MuUPtrValue),
handle_from_fp :: FunPtr (Ptr MuCtx -> MuID -> MuCFP -> IO MuUFPValue),
-- Convert from Mu values to C values
handle_to_sint8 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int8_t),
handle_to_uint8 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt8_t),
handle_to_sint16 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int16_t),
handle_to_uint16 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt16_t),
handle_to_sint32 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int32_t),
handle_to_uint32 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt32_t),
handle_to_sint64 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int64_t),
handle_to_uint64 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt64_t),
handle_to_float :: FunPtr (Ptr MuCtx -> MuFloatValue -> IO CFloat),
handle_to_double :: FunPtr (Ptr MuCtx -> MuDoubleValue -> IO CDouble),
handle_to_ptr :: FunPtr (Ptr MuCtx -> MuUPtrValue -> IO MuCPtr),
handle_to_fp :: FunPtr (Ptr MuCtx -> MuUFPValue -> IO MuCFP),
-- Make MuValue instances from Mu global SSA variables
handle_from_const :: FunPtr (Ptr MuCtx -> MuID -> IO MuValue),
handle_from_global :: FunPtr (Ptr MuCtx -> MuID -> IO MuIRefValue),
handle_from_func :: FunPtr (Ptr MuCtx -> MuID -> IO MuFuncRefValue),
handle_from_expose :: FunPtr (Ptr MuCtx -> MuID -> IO MuValue),
-- Delete the value held by the MuCtx, making it unusable, but freeing up
-- the resource.
delete_value :: FunPtr (Ptr MuCtx -> MuValue -> IO ()),
-- Compare reference or general reference types.
-- EQ. Available for ref, iref, funcref, threadref and stackref.
ref_eq :: FunPtr (Ptr MuCtx -> MuValue -> MuValue -> IO CInt),
-- ULT. Available for iref only.
ref_ult :: FunPtr (Ptr MuCtx -> MuIRefValue -> MuIRefValue -> IO CInt),
-- Manipulate Mu values of the struct<...> type
extract_value :: FunPtr (Ptr MuCtx -> MuStructValue -> CInt -> IO MuValue),
insert_value :: FunPtr (Ptr MuCtx -> MuStructValue -> CInt -> MuValue -> IO MuValue),
-- Manipulate Mu values of the array or vector type
-- str can be MuArrayValue or MuVectorValue
extract_element :: FunPtr (Ptr MuCtx -> MuValue -> MuIntValue -> IO MuValue),
insert_element :: FunPtr (Ptr MuCtx -> MuValue -> MuIntValue -> MuValue -> IO MuValue),
-- Heap allocation
new_fixed :: FunPtr (Ptr MuCtx -> MuID -> IO MuRefValue),
new_hybrid :: FunPtr (Ptr MuCtx -> MuID -> MuIntValue -> IO MuRefValue),
-- Change the T or sig in ref<T>, iref<T> or func<sig>
refcast :: FunPtr (Ptr MuCtx -> MuValue -> MuID -> IO MuValue),
-- Memory addressing
get_iref :: FunPtr (Ptr MuCtx -> MuRefValue -> IO MuIRefValue),
get_field_iref :: FunPtr (Ptr MuCtx -> MuIRefValue -> CInt -> IO MuIRefValue),
get_elem_iref :: FunPtr (Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue),
shift_iref :: FunPtr (Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue),
get_var_part_iref :: FunPtr (Ptr MuCtx -> MuIRefValue -> IO MuIRefValue),
-- Memory accessing
load' :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuIRefValue -> IO MuValue),
store' :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuIRefValue -> MuValue -> IO ()),
cmpxchg' :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuMemOrd -> CInt -> MuIRefValue -> MuValue -> MuValue -> Ptr CInt -> IO MuValue),
atomicrmw' :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuAtomicRMWOp -> MuIRefValue -> MuValue -> IO MuValue),
fence' :: FunPtr (Ptr MuCtx -> MuMemOrd -> IO ()),
-- Thread and stack creation and stack destruction
new_stack :: FunPtr (Ptr MuCtx -> MuFuncRefValue -> IO MuStackRefValue),
new_thread :: FunPtr (Ptr MuCtx -> MuStackRefValue -> MuHowToResume -> Ptr MuValue -> CInt -> MuRefValue -> IO MuThreadRefValue),
kill_stack :: FunPtr (Ptr MuCtx -> MuStackRefValue -> IO ()),
-- Frame cursor operations
new_cursor :: FunPtr (Ptr MuCtx -> MuStackRefValue -> IO MuFCRefValue),
new_frame :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO ()),
copy_cursor :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuFCRefValue),
close_cursor :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO ()),
-- Stack introspection
cur_func :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuID),
cur_func_ver :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuID),
cur_inst :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuID),
dump_keepalives :: FunPtr (Ptr MuCtx -> MuFCRefValue -> Ptr MuValue -> IO ()),
-- On-stack replacement
pop_frames_to :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO ()),
push_frame :: FunPtr (Ptr MuCtx -> MuStackRefValue -> MuFuncRefValue -> IO ()),
-- 64-bit tagged reference operations
tr64_is_fp :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO CInt),
tr64_is_int :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO CInt),
tr64_is_ref :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO CInt),
tr64_to_fp :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuDoubleValue),
tr64_to_int :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue),
tr64_to_ref :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuRefValue),
tr64_to_tag :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue),
tr64_from_fp :: FunPtr (Ptr MuCtx -> MuDoubleValue -> IO MuTagRef64Value),
tr64_from_int :: FunPtr (Ptr MuCtx -> MuIntValue -> IO MuTagRef64Value),
tr64_from_ref :: FunPtr (Ptr MuCtx -> MuRefValue -> MuIntValue -> IO MuTagRef64Value),
-- Watchpoint operations
enable_watchpoint :: FunPtr (Ptr MuCtx -> CInt -> IO ()),
disable_watchpoint :: FunPtr (Ptr MuCtx -> CInt -> IO ()),
-- Mu memory pinning, usually object pinning
pin' :: FunPtr (Ptr MuCtx -> MuValue -> IO MuUPtrValue), --loc is either MuRefValue or MuIRefValue
unpin' :: FunPtr (Ptr MuCtx -> MuValue -> IO ()), --loc is either MuRefValue or MuIRefValue
-- Expose Mu functions as native callable things, usually function pointers
expose' :: FunPtr (Ptr MuCtx -> MuFuncRefValue -> MuCallConv -> MuIntValue -> IO MuValue),
unexpose' :: FunPtr (Ptr MuCtx -> MuCallConv -> MuValue -> IO ())
} deriving (Generic)
instance CStorable MuCtx
instance Storable MuCtx where
sizeOf = cSizeOf
alignment = cAlignment
poke = cPoke
peek = cPeek
foreign import ccall "dynamic" mkCtxIdOf :: FunPtr (Ptr MuCtx -> MuName -> IO Hs_MuID) -> Ptr MuCtx -> MuName -> IO Hs_MuID
foreign import ccall "dynamic" mkCtxNameOf :: FunPtr (Ptr MuCtx -> MuID -> IO Hs_MuName) -> Ptr MuCtx -> MuID -> IO Hs_MuName
foreign import ccall "dynamic" mkCloseContext :: FunPtr (Ptr MuCtx -> IO ()) -> Ptr MuCtx -> IO ()
foreign import ccall "dynamic" mkLoadBundle :: FunPtr (Ptr MuCtx -> CString -> CInt -> IO ()) -> Ptr MuCtx -> CString -> CInt -> IO ()
foreign import ccall "dynamic" mkLoadHail :: FunPtr (Ptr MuCtx -> CString -> CInt -> IO ()) -> Ptr MuCtx -> CString -> CInt -> IO ()
foreign import ccall "dynamic" mkHandleFromSint8 :: FunPtr (Ptr MuCtx -> Int8_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> Int8_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromUint8 :: FunPtr (Ptr MuCtx -> UInt8_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> UInt8_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromSint16 :: FunPtr (Ptr MuCtx -> Int16_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> Int16_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromUint16 :: FunPtr (Ptr MuCtx -> UInt16_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> UInt16_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromSint32 :: FunPtr (Ptr MuCtx -> Int32_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> Int32_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromUint32 :: FunPtr (Ptr MuCtx -> UInt32_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> UInt32_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromSint64 :: FunPtr (Ptr MuCtx -> Int64_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> Int64_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromUint64 :: FunPtr (Ptr MuCtx -> UInt64_t -> CInt -> IO MuIntValue) -> Ptr MuCtx -> UInt64_t -> CInt -> IO MuIntValue
foreign import ccall "dynamic" mkHandleFromFloat :: FunPtr (Ptr MuCtx -> CFloat -> IO MuFloatValue) -> Ptr MuCtx -> CFloat -> IO MuFloatValue
foreign import ccall "dynamic" mkHandleFromDouble :: FunPtr (Ptr MuCtx -> CDouble -> IO MuDoubleValue) -> Ptr MuCtx -> CDouble -> IO MuDoubleValue
foreign import ccall "dynamic" mkHandleFromPtr :: FunPtr (Ptr MuCtx -> MuID -> MuCPtr -> IO MuUPtrValue) -> Ptr MuCtx -> MuID -> MuCPtr -> IO MuUPtrValue
foreign import ccall "dynamic" mkHandleFromFp :: FunPtr (Ptr MuCtx -> MuID -> MuCFP -> IO MuUFPValue) -> Ptr MuCtx -> MuID -> MuCFP -> IO MuUFPValue
foreign import ccall "dynamic" mkHandleToSint8 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int8_t) -> Ptr MuCtx -> MuIntValue -> IO Int8_t
foreign import ccall "dynamic" mkHandleToUint8 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt8_t) -> Ptr MuCtx -> MuIntValue -> IO UInt8_t
foreign import ccall "dynamic" mkHandleToSint16 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int16_t) -> Ptr MuCtx -> MuIntValue -> IO Int16_t
foreign import ccall "dynamic" mkHandleToUint16 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt16_t) -> Ptr MuCtx -> MuIntValue -> IO UInt16_t
foreign import ccall "dynamic" mkHandleToSint32 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int32_t) -> Ptr MuCtx -> MuIntValue -> IO Int32_t
foreign import ccall "dynamic" mkHandleToUint32 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt32_t) -> Ptr MuCtx -> MuIntValue -> IO UInt32_t
foreign import ccall "dynamic" mkHandleToSint64 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO Int64_t) -> Ptr MuCtx -> MuIntValue -> IO Int64_t
foreign import ccall "dynamic" mkHandleToUint64 :: FunPtr (Ptr MuCtx -> MuIntValue -> IO UInt64_t) -> Ptr MuCtx -> MuIntValue -> IO UInt64_t
foreign import ccall "dynamic" mkHandleToFloat :: FunPtr (Ptr MuCtx -> MuFloatValue -> IO CFloat) -> Ptr MuCtx -> MuFloatValue -> IO CFloat
foreign import ccall "dynamic" mkHandleToDouble :: FunPtr (Ptr MuCtx -> MuDoubleValue -> IO CDouble) -> Ptr MuCtx -> MuDoubleValue -> IO CDouble
foreign import ccall "dynamic" mkHandleToPtr :: FunPtr (Ptr MuCtx -> MuUPtrValue -> IO MuCPtr) -> Ptr MuCtx -> MuUPtrValue -> IO MuCPtr
foreign import ccall "dynamic" mkHandleToFp :: FunPtr (Ptr MuCtx -> MuUFPValue -> IO MuCFP) -> Ptr MuCtx -> MuUFPValue -> IO MuCFP
foreign import ccall "dynamic" mkHandleFromConst :: FunPtr (Ptr MuCtx -> MuID -> IO MuValue) -> Ptr MuCtx -> MuID -> IO MuValue
foreign import ccall "dynamic" mkHandleFromGlobal :: FunPtr (Ptr MuCtx -> MuID -> IO MuIRefValue) -> Ptr MuCtx -> MuID -> IO MuIRefValue
foreign import ccall "dynamic" mkHandleFromFunc :: FunPtr (Ptr MuCtx -> MuID -> IO MuFuncRefValue) -> Ptr MuCtx -> MuID -> IO MuFuncRefValue
foreign import ccall "dynamic" mkhandleFromExpose :: FunPtr (Ptr MuCtx -> MuID -> IO MuValue) -> Ptr MuCtx -> MuID -> IO MuValue
foreign import ccall "dynamic" mkDeleteValue :: FunPtr (Ptr MuCtx -> MuValue -> IO ()) -> Ptr MuCtx -> MuValue -> IO ()
foreign import ccall "dynamic" mkRefEq :: FunPtr (Ptr MuCtx -> MuValue -> MuValue -> IO CInt) -> Ptr MuCtx -> MuValue -> MuValue -> IO CInt
foreign import ccall "dynamic" mkRefUlt :: FunPtr (Ptr MuCtx -> MuIRefValue -> MuIRefValue -> IO CInt) -> Ptr MuCtx -> MuIRefValue -> MuIRefValue -> IO CInt
foreign import ccall "dynamic" mkExtractValue :: FunPtr (Ptr MuCtx -> MuStructValue -> CInt -> IO MuValue) -> Ptr MuCtx -> MuStructValue -> CInt -> IO MuValue
foreign import ccall "dynamic" mkInsertValue :: FunPtr (Ptr MuCtx -> MuStructValue -> CInt -> MuValue -> IO MuValue) -> Ptr MuCtx -> MuStructValue -> CInt -> MuValue -> IO MuValue
foreign import ccall "dynamic" mkExtractElement :: FunPtr (Ptr MuCtx -> MuValue -> MuIntValue -> IO MuValue) -> Ptr MuCtx -> MuValue -> MuIntValue -> IO MuValue
foreign import ccall "dynamic" mkInsertElement :: FunPtr (Ptr MuCtx -> MuValue -> MuIntValue -> MuValue -> IO MuValue) -> Ptr MuCtx -> MuValue -> MuIntValue -> MuValue -> IO MuValue
foreign import ccall "dynamic" mkNewFixed :: FunPtr (Ptr MuCtx -> MuID -> IO MuRefValue) -> Ptr MuCtx -> MuID -> IO MuRefValue
foreign import ccall "dynamic" mkNewHybrid :: FunPtr (Ptr MuCtx -> MuID -> MuIntValue -> IO MuRefValue) -> Ptr MuCtx -> MuID -> MuIntValue -> IO MuRefValue
foreign import ccall "dynamic" mkRefCast :: FunPtr (Ptr MuCtx -> MuValue -> MuID -> IO MuValue) -> Ptr MuCtx -> MuValue -> MuID -> IO MuValue
foreign import ccall "dynamic" mkGetIref :: FunPtr (Ptr MuCtx -> MuRefValue -> IO MuIRefValue) -> Ptr MuCtx -> MuRefValue -> IO MuIRefValue
foreign import ccall "dynamic" mkGetFieldIref :: FunPtr (Ptr MuCtx -> MuIRefValue -> CInt -> IO MuIRefValue) -> Ptr MuCtx -> MuIRefValue -> CInt -> IO MuIRefValue
foreign import ccall "dynamic" mkGetElemIref :: FunPtr (Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue) -> Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue
foreign import ccall "dynamic" mkShiftIref :: FunPtr (Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue) -> Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue
foreign import ccall "dynamic" mkGetVarPartIref :: FunPtr (Ptr MuCtx -> MuIRefValue -> IO MuIRefValue) -> Ptr MuCtx -> MuIRefValue -> IO MuIRefValue
foreign import ccall "dynamic" mkLoad :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuIRefValue -> IO MuValue) -> Ptr MuCtx -> MuMemOrd -> MuIRefValue -> IO MuValue
foreign import ccall "dynamic" mkStore :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuIRefValue -> MuValue -> IO ()) -> Ptr MuCtx -> MuMemOrd -> MuIRefValue -> MuValue -> IO ()
foreign import ccall "dynamic" mkCmpxchg :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuMemOrd -> CInt -> MuIRefValue -> MuValue -> MuValue -> Ptr CInt -> IO MuValue) -> Ptr MuCtx -> MuMemOrd -> MuMemOrd -> CInt -> MuIRefValue -> MuValue -> MuValue -> Ptr CInt -> IO MuValue
foreign import ccall "dynamic" mkAtomicrmw :: FunPtr (Ptr MuCtx -> MuMemOrd -> MuAtomicRMWOp -> MuIRefValue -> MuValue -> IO MuValue) -> Ptr MuCtx -> MuMemOrd -> MuAtomicRMWOp -> MuIRefValue -> MuValue -> IO MuValue
foreign import ccall "dynamic" mkFence :: FunPtr (Ptr MuCtx -> MuMemOrd -> IO ()) -> Ptr MuCtx -> MuMemOrd -> IO ()
foreign import ccall "dynamic" mkNewStack :: FunPtr (Ptr MuCtx -> MuFuncRefValue -> IO MuStackRefValue) -> Ptr MuCtx -> MuFuncRefValue -> IO MuStackRefValue
foreign import ccall "dynamic" mkNewThread :: FunPtr (Ptr MuCtx -> MuStackRefValue -> MuHowToResume -> Ptr MuValue -> CInt -> MuRefValue -> IO MuThreadRefValue) -> Ptr MuCtx -> MuStackRefValue -> MuHowToResume -> Ptr MuValue -> CInt -> MuRefValue -> IO MuThreadRefValue
foreign import ccall "dynamic" mkKillStack :: FunPtr (Ptr MuCtx -> MuStackRefValue -> IO ()) -> Ptr MuCtx -> MuStackRefValue -> IO ()
foreign import ccall "dynamic" mkNewCursor :: FunPtr (Ptr MuCtx -> MuStackRefValue -> IO MuFCRefValue) -> Ptr MuCtx -> MuStackRefValue -> IO MuFCRefValue
foreign import ccall "dynamic" mkNewFrame :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO ()) -> Ptr MuCtx -> MuFCRefValue -> IO ()
foreign import ccall "dynamic" mkCopyCursor :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuFCRefValue) -> Ptr MuCtx -> MuFCRefValue -> IO MuFCRefValue
foreign import ccall "dynamic" mkCloseCursor :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO ()) -> Ptr MuCtx -> MuFCRefValue -> IO ()
foreign import ccall "dynamic" mkCurFunc :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuID) -> Ptr MuCtx -> MuFCRefValue -> IO MuID
foreign import ccall "dynamic" mkCurFuncVer :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuID) -> Ptr MuCtx -> MuFCRefValue -> IO MuID
foreign import ccall "dynamic" mkCurInst :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO MuID) -> Ptr MuCtx -> MuFCRefValue -> IO MuID
foreign import ccall "dynamic" mkDumpKeepalives :: FunPtr (Ptr MuCtx -> MuFCRefValue -> Ptr MuValue -> IO ()) -> Ptr MuCtx -> MuFCRefValue -> Ptr MuValue -> IO ()
foreign import ccall "dynamic" mkPopFramesTo :: FunPtr (Ptr MuCtx -> MuFCRefValue -> IO ()) -> Ptr MuCtx -> MuFCRefValue -> IO ()
foreign import ccall "dynamic" mkPushFrame :: FunPtr (Ptr MuCtx -> MuStackRefValue -> MuFuncRefValue -> IO ()) -> Ptr MuCtx -> MuStackRefValue -> MuFuncRefValue -> IO ()
foreign import ccall "dynamic" mkTr64IsFp :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO CInt) -> Ptr MuCtx -> MuTagRef64Value -> IO CInt
foreign import ccall "dynamic" mkTr64IsInt :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO CInt) -> Ptr MuCtx -> MuTagRef64Value -> IO CInt
foreign import ccall "dynamic" mkTr64isRef :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO CInt) -> Ptr MuCtx -> MuTagRef64Value -> IO CInt
foreign import ccall "dynamic" mkTr64ToFp :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuDoubleValue) -> Ptr MuCtx -> MuTagRef64Value -> IO MuDoubleValue
foreign import ccall "dynamic" mkTr64ToInt :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue) -> Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue
foreign import ccall "dynamic" mkTr64ToRef :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuRefValue) -> Ptr MuCtx -> MuTagRef64Value -> IO MuRefValue
foreign import ccall "dynamic" mkTr64ToTag :: FunPtr (Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue) -> Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue
foreign import ccall "dynamic" mkTr64FromFp :: FunPtr (Ptr MuCtx -> MuDoubleValue -> IO MuTagRef64Value) -> Ptr MuCtx -> MuDoubleValue -> IO MuTagRef64Value
foreign import ccall "dynamic" mkTr64FromInt :: FunPtr (Ptr MuCtx -> MuIntValue -> IO MuTagRef64Value) -> Ptr MuCtx -> MuIntValue -> IO MuTagRef64Value
foreign import ccall "dynamic" mkTr64FromRef :: FunPtr (Ptr MuCtx -> MuRefValue -> MuIntValue -> IO MuTagRef64Value) -> Ptr MuCtx -> MuRefValue -> MuIntValue -> IO MuTagRef64Value
foreign import ccall "dynamic" mkEnableWatchpoint :: FunPtr (Ptr MuCtx -> CInt -> IO ()) -> Ptr MuCtx -> CInt -> IO ()
foreign import ccall "dynamic" mkDisableWatchpoint :: FunPtr (Ptr MuCtx -> CInt -> IO ()) -> Ptr MuCtx -> CInt -> IO ()
foreign import ccall "dynamic" mkPin :: FunPtr (Ptr MuCtx -> MuValue -> IO MuUPtrValue) -> Ptr MuCtx -> MuValue -> IO MuUPtrValue
foreign import ccall "dynamic" mkUnpin :: FunPtr (Ptr MuCtx -> MuValue -> IO ()) -> Ptr MuCtx -> MuValue -> IO ()
foreign import ccall "dynamic" mkExpose :: FunPtr (Ptr MuCtx -> MuFuncRefValue -> MuCallConv -> MuIntValue -> IO MuValue) -> Ptr MuCtx -> MuFuncRefValue -> MuCallConv -> MuIntValue -> IO MuValue
foreign import ccall "dynamic" mkUnexpose :: FunPtr (Ptr MuCtx -> MuCallConv -> MuValue -> IO ()) -> Ptr MuCtx -> MuCallConv -> MuValue -> IO ()
ctxIdOf :: Ptr MuCtx -> MuName -> IO Hs_MuID
ctxIdOf = call1 mkCtxIdOf ctx_id_of
ctxNameOf :: Ptr MuCtx -> MuID -> IO Hs_MuName
ctxNameOf = call1 mkCtxNameOf ctx_name_of
closeContext :: Ptr MuCtx -> IO ()
closeContext = call0 mkCloseContext close_context
loadBundle :: Ptr MuCtx -> CString -> CInt -> IO ()
loadBundle = call2 mkLoadBundle load_bundle
loadHail :: Ptr MuCtx -> CString -> CInt -> IO ()
loadHail = call2 mkLoadHail load_hail
handleFromSInt8 :: Ptr MuCtx -> Int8_t -> CInt -> IO MuIntValue
handleFromSInt8 = call2 mkHandleFromSint8 handle_from_sint8
handleFromUInt8 :: Ptr MuCtx -> UInt8_t -> CInt -> IO MuIntValue
handleFromUInt8 = call2 mkHandleFromUint8 handle_from_uint8
handleFromSInt16 :: Ptr MuCtx -> Int16_t -> CInt -> IO MuIntValue
handleFromSInt16 = call2 mkHandleFromSint16 handle_from_sint16
handleFromUInt16 :: Ptr MuCtx -> UInt16_t -> CInt -> IO MuIntValue
handleFromUInt16 = call2 mkHandleFromUint16 handle_from_uint16
handleFromSInt32 :: Ptr MuCtx -> Int32_t -> CInt -> IO MuIntValue
handleFromSInt32 = call2 mkHandleFromSint32 handle_from_sint32
handleFromUInt32 :: Ptr MuCtx -> UInt32_t -> CInt -> IO MuIntValue
handleFromUInt32 = call2 mkHandleFromUint32 handle_from_uint32
handleFromSInt64 :: Ptr MuCtx -> Int64_t -> CInt -> IO MuIntValue
handleFromSInt64 = call2 mkHandleFromSint64 handle_from_sint64
handleFromUInt64 :: Ptr MuCtx -> UInt64_t -> CInt -> IO MuIntValue
handleFromUInt64 = call2 mkHandleFromUint64 handle_from_uint64
handleFromFloat :: Ptr MuCtx -> CFloat -> IO MuFloatValue
handleFromFloat = call1 mkHandleFromFloat handle_from_float
handleFromDouble :: Ptr MuCtx -> CDouble -> IO MuDoubleValue
handleFromDouble = call1 mkHandleFromDouble handle_from_double
handleFromPtr :: Ptr MuCtx -> MuID -> MuCPtr -> IO MuUPtrValue
handleFromPtr = call2 mkHandleFromPtr handle_from_ptr
handleFromFp :: Ptr MuCtx -> MuID -> MuCFP -> IO MuUFPValue
handleFromFp = call2 mkHandleFromFp handle_from_fp
handleToSint8 :: Ptr MuCtx -> MuIntValue -> IO Int8_t
handleToSint8 = call1 mkHandleToSint8 handle_to_sint8
handleToUint8 ::Ptr MuCtx -> MuIntValue -> IO UInt8_t
handleToUint8 = call1 mkHandleToUint8 handle_to_uint8
handleToSint16 :: Ptr MuCtx -> MuIntValue -> IO Int16_t
handleToSint16 = call1 mkHandleToSint16 handle_to_sint16
handleToUint16 :: Ptr MuCtx -> MuIntValue -> IO UInt16_t
handleToUint16 = call1 mkHandleToUint16 handle_to_uint16
handleToSint32 :: Ptr MuCtx -> MuIntValue -> IO Int32_t
handleToSint32 = call1 mkHandleToSint32 handle_to_sint32
handleToUint32 :: Ptr MuCtx -> MuIntValue -> IO UInt32_t
handleToUint32 = call1 mkHandleToUint32 handle_to_uint32
handleToSint64 :: Ptr MuCtx -> MuIntValue -> IO Int64_t
handleToSint64 = call1 mkHandleToSint64 handle_to_sint64
handleToUint64 :: Ptr MuCtx -> MuIntValue -> IO UInt64_t
handleToUint64 = call1 mkHandleToUint64 handle_to_uint64
handleToFloat :: Ptr MuCtx -> MuFloatValue -> IO CFloat
handleToFloat = call1 mkHandleToFloat handle_to_float
handleToDouble :: Ptr MuCtx -> MuDoubleValue -> IO CDouble
handleToDouble = call1 mkHandleToDouble handle_to_double
handleToPtr :: Ptr MuCtx -> MuUPtrValue -> IO MuCPtr
handleToPtr = call1 mkHandleToPtr handle_to_ptr
handleToFp :: Ptr MuCtx -> MuUFPValue -> IO MuCFP
handleToFp = call1 mkHandleToFp handle_to_fp
handleFromConst :: Ptr MuCtx -> MuID -> IO MuValue
handleFromConst = call1 mkHandleFromConst handle_from_const
handleFromGlobal :: Ptr MuCtx -> MuID -> IO MuIRefValue
handleFromGlobal = call1 mkHandleFromGlobal handle_from_global
handleFromFunc :: Ptr MuCtx -> MuID -> IO MuFuncRefValue
handleFromFunc = call1 mkHandleFromFunc handle_from_func
handleFromExpose :: Ptr MuCtx -> MuID -> IO MuValue
handleFromExpose = call1 mkhandleFromExpose handle_from_expose
deleteValue :: Ptr MuCtx -> MuValue -> IO ()
deleteValue = call1 mkDeleteValue delete_value
refEq :: Ptr MuCtx -> MuValue -> MuValue -> IO CInt
refEq = call2 mkRefEq ref_eq
refUlt :: Ptr MuCtx -> MuIRefValue -> MuIRefValue -> IO CInt
refUlt = call2 mkRefUlt ref_ult
extractValue :: Ptr MuCtx -> MuStructValue -> CInt -> IO MuValue
extractValue = call2 mkExtractValue extract_value
insertValue :: Ptr MuCtx -> MuStructValue -> CInt -> MuValue -> IO MuValue
insertValue = call3 mkInsertValue insert_value
extractElement :: Ptr MuCtx -> MuValue -> MuIntValue -> IO MuValue
extractElement = call2 mkExtractElement extract_element
insertElement :: Ptr MuCtx -> MuValue -> MuIntValue -> MuValue -> IO MuValue
insertElement = call3 mkInsertElement insert_element
newFixed :: Ptr MuCtx -> MuID -> IO MuRefValue
newFixed = call1 mkNewFixed new_fixed
newHybrid :: Ptr MuCtx -> MuID -> MuIntValue -> IO MuRefValue
newHybrid = call2 mkNewHybrid new_hybrid
refCast :: Ptr MuCtx -> MuValue -> MuID -> IO MuValue
refCast = call2 mkRefCast refcast
getIref :: Ptr MuCtx -> MuRefValue -> IO MuIRefValue
getIref = call1 mkGetIref get_iref
getFieldIref :: Ptr MuCtx -> MuIRefValue -> CInt -> IO MuIRefValue
getFieldIref = call2 mkGetFieldIref get_field_iref
getElemIref :: Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue
getElemIref = call2 mkGetElemIref get_elem_iref
shiftIref :: Ptr MuCtx -> MuIRefValue -> MuIntValue -> IO MuIRefValue
shiftIref = call2 mkShiftIref shift_iref
getVarPartIref :: Ptr MuCtx -> MuIRefValue -> IO MuIRefValue
getVarPartIref = call1 mkGetVarPartIref get_var_part_iref
load :: Ptr MuCtx -> MuMemOrd -> MuIRefValue -> IO MuValue
load = call2 mkLoad load'
store :: Ptr MuCtx -> MuMemOrd -> MuIRefValue -> MuValue -> IO ()
store = call3 mkStore store'
cmpxchg :: Ptr MuCtx -> MuMemOrd -> MuMemOrd -> CInt -> MuIRefValue -> MuValue -> MuValue -> Ptr CInt -> IO MuValue
cmpxchg = call7 mkCmpxchg cmpxchg'
atomicrmw :: Ptr MuCtx -> MuMemOrd -> MuAtomicRMWOp -> MuIRefValue -> MuValue -> IO MuValue
atomicrmw = call4 mkAtomicrmw atomicrmw'
fence :: Ptr MuCtx -> MuMemOrd -> IO ()
fence = call1 mkFence fence'
newStack :: Ptr MuCtx -> MuFuncRefValue -> IO MuStackRefValue
newStack = call1 mkNewStack new_stack
newThread :: Ptr MuCtx -> MuStackRefValue -> MuHowToResume -> Ptr MuValue -> CInt -> MuRefValue -> IO MuThreadRefValue
newThread = call5 mkNewThread new_thread
killStack :: Ptr MuCtx -> MuStackRefValue -> IO ()
killStack = call1 mkKillStack kill_stack
newCursor :: Ptr MuCtx -> MuStackRefValue -> IO MuFCRefValue
newCursor = call1 mkNewCursor new_cursor
newFrame :: Ptr MuCtx -> MuFCRefValue -> IO ()
newFrame = call1 mkNewFrame new_frame
copyCursor :: Ptr MuCtx -> MuFCRefValue -> IO MuFCRefValue
copyCursor = call1 mkCopyCursor copy_cursor
closeCursor :: Ptr MuCtx -> MuFCRefValue -> IO ()
closeCursor = call1 mkCloseCursor close_cursor
curFunc :: Ptr MuCtx -> MuFCRefValue -> IO MuID
curFunc = call1 mkCurFunc cur_func
curFuncVer :: Ptr MuCtx -> MuFCRefValue -> IO MuID
curFuncVer = call1 mkCurFuncVer cur_func_ver
curInst :: Ptr MuCtx -> MuFCRefValue -> IO MuID
curInst = call1 mkCurInst cur_inst
dumpKeepalives :: Ptr MuCtx -> MuFCRefValue -> Ptr MuValue -> IO ()
dumpKeepalives = call2 mkDumpKeepalives dump_keepalives
popFramesTo :: Ptr MuCtx -> MuFCRefValue -> IO ()
popFramesTo = call1 mkPopFramesTo pop_frames_to
pushFrame :: Ptr MuCtx -> MuStackRefValue -> MuFuncRefValue -> IO ()
pushFrame = call2 mkPushFrame push_frame
tr64IsFp :: Ptr MuCtx -> MuTagRef64Value -> IO CInt
tr64IsFp = call1 mkTr64IsFp tr64_is_fp
tr64IsInt :: Ptr MuCtx -> MuTagRef64Value -> IO CInt
tr64IsInt = call1 mkTr64IsInt tr64_is_int
tr64isRef :: Ptr MuCtx -> MuTagRef64Value -> IO CInt
tr64isRef = call1 mkTr64isRef tr64_is_ref
tr64ToFp :: Ptr MuCtx -> MuTagRef64Value -> IO MuDoubleValue
tr64ToFp = call1 mkTr64ToFp tr64_to_fp
tr64ToInt :: Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue
tr64ToInt = call1 mkTr64ToInt tr64_to_int
tr64ToRef :: Ptr MuCtx -> MuTagRef64Value -> IO MuRefValue
tr64ToRef = call1 mkTr64ToRef tr64_to_ref
tr64ToTag :: Ptr MuCtx -> MuTagRef64Value -> IO MuIntValue
tr64ToTag = call1 mkTr64ToTag tr64_to_tag
tr64FromFp :: Ptr MuCtx -> MuDoubleValue -> IO MuTagRef64Value
tr64FromFp = call1 mkTr64FromFp tr64_from_fp
tr64FromInt :: Ptr MuCtx -> MuIntValue -> IO MuTagRef64Value
tr64FromInt = call1 mkTr64FromInt tr64_from_int
tr64FromRef :: Ptr MuCtx -> MuRefValue -> MuIntValue -> IO MuTagRef64Value
tr64FromRef = call2 mkTr64FromRef tr64_from_ref
enableWatchpoint :: Ptr MuCtx -> CInt -> IO ()
enableWatchpoint = call1 mkEnableWatchpoint enable_watchpoint
disableWatchpoint :: Ptr MuCtx -> CInt -> IO ()
disableWatchpoint = call1 mkDisableWatchpoint disable_watchpoint
pin :: Ptr MuCtx -> MuValue -> IO MuUPtrValue
pin = call1 mkPin pin'
unpin :: Ptr MuCtx -> MuValue -> IO ()
unpin = call1 mkUnpin unpin'
expose :: Ptr MuCtx -> MuFuncRefValue -> MuCallConv -> MuIntValue -> IO MuValue
expose = call3 mkExpose expose'
unexpose :: Ptr MuCtx -> MuCallConv -> MuValue -> IO ()
unexpose = call2 mkUnexpose unexpose'
call0 :: (Storable a) => (FunPtr (Ptr a -> IO b) -> (Ptr a -> IO b)) -> (a -> FunPtr (Ptr a -> IO b)) -> Ptr a -> IO b
call0 mkFn fn ctx = do
ctxVal <- peek ctx
mkFn (fn ctxVal) ctx
call1 :: (Storable a) => (FunPtr (Ptr a -> b -> IO c) -> (Ptr a -> b -> IO c)) -> (a -> FunPtr (Ptr a -> b -> IO c)) -> Ptr a -> b -> IO c
call1 mkFn fn ctx arg = do
ctxVal <- peek ctx
mkFn (fn ctxVal) ctx arg
call2 :: (Storable a) => (FunPtr (Ptr a -> b -> c -> IO d) -> (Ptr a -> b -> c -> IO d)) -> (a -> FunPtr (Ptr a -> b -> c -> IO d)) -> Ptr a -> b -> c -> IO d
call2 mkFn fn ctx arg arg2 = do
ctxVal <- peek ctx
mkFn (fn ctxVal) ctx arg arg2
call3 :: (Storable a) => (FunPtr (Ptr a -> b -> c -> d -> IO e) -> (Ptr a -> b -> c -> d -> IO e)) -> (a -> FunPtr (Ptr a -> b -> c -> d -> IO e)) -> Ptr a -> b -> c -> d -> IO e
call3 mkFn fn ctx arg arg2 arg3 = do
ctxVal <- peek ctx
mkFn (fn ctxVal) ctx arg arg2 arg3
call4 :: (Storable a) => (FunPtr (Ptr a -> b -> c -> d -> e -> IO f) -> (Ptr a -> b -> c -> d -> e -> IO f)) -> (a -> FunPtr (Ptr a -> b -> c -> d -> e -> IO f)) -> Ptr a -> b -> c -> d -> e -> IO f
call4 mkFn fn ctx arg arg2 arg3 arg4 = do
ctxVal <- peek ctx
mkFn (fn ctxVal) ctx arg arg2 arg3 arg4
call5 :: (Storable a) => (FunPtr (Ptr a -> b -> c -> d -> e -> f -> IO g) -> (Ptr a -> b -> c -> d -> e -> f -> IO g)) -> (a -> FunPtr (Ptr a -> b -> c -> d -> e -> f -> IO g)) -> Ptr a -> b -> c -> d -> e -> f -> IO g
call5 mkFn fn ctx arg arg2 arg3 arg4 arg5 = do
ctxVal <- peek ctx
mkFn (fn ctxVal) ctx arg arg2 arg3 arg4 arg5
call7 :: (Storable a) => (FunPtr (Ptr a -> b -> c -> d -> e -> f -> g -> h -> IO i) -> (Ptr a -> b -> c -> d -> e -> f -> g -> h -> IO i)) -> (a -> FunPtr (Ptr a -> b -> c -> d -> e -> f -> g -> h -> IO i)) -> Ptr a -> b -> c -> d -> e -> f -> g -> h -> IO i
call7 mkFn fn ctx arg arg2 arg3 arg4 arg5 arg6 arg7 = do
ctxVal <- peek ctx
mkFn (fn ctxVal) ctx arg arg2 arg3 arg4 arg5 arg6 arg7
| andrew-m-h/libmu-HS | src/LibMu/MuApi.hs | bsd-3-clause | 37,039 | 0 | 20 | 6,829 | 12,766 | 6,406 | 6,360 | 626 | 1 |
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is distributed under the terms of a BSD license,
-- found in the LICENSE file. An additional grant of patent rights can
-- be found in the PATENTS file.
-- | Everything needed to define data sources and to invoke the
-- engine. This module should not be imported by user code.
module Haxl.Core
( module Haxl.Core.Monad
, module Haxl.Core.Types
, module Haxl.Core.Exception
, module Haxl.Core.StateStore
, module Haxl.Core.Show1
) where
import Haxl.Core.Monad hiding (unsafeLiftIO {- Ask nicely to get this! -})
import Haxl.Core.Types
import Haxl.Core.Exception
import Haxl.Core.Show1 (Show1(..))
import Haxl.Core.StateStore
| kantp/Haxl | Haxl/Core.hs | bsd-3-clause | 723 | 0 | 6 | 120 | 97 | 69 | 28 | 11 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Models.Favorite where
import Data.Text (Text)
import Database.Persist.TH (mkMigrate, mkPersist, persistLowerCase, share,
sqlSettings)
import Models.Article
import Models.User
share [mkPersist sqlSettings, mkMigrate "migrateFavorite"] [persistLowerCase|
Favorite json sql=favorits
userId UserId
articleId ArticleId
Primary userId articleId
UniqueFavorite userId articleId
|]
| rpereira/servant-blog | src/Models/Favorite.hs | bsd-3-clause | 971 | 0 | 7 | 277 | 85 | 56 | 29 | 19 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.TextureSwizzle
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/texture_swizzle.txt ARB_texture_swizzle> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.TextureSwizzle (
-- * Enums
gl_TEXTURE_SWIZZLE_A,
gl_TEXTURE_SWIZZLE_B,
gl_TEXTURE_SWIZZLE_G,
gl_TEXTURE_SWIZZLE_R,
gl_TEXTURE_SWIZZLE_RGBA
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/TextureSwizzle.hs | bsd-3-clause | 756 | 0 | 4 | 90 | 49 | 39 | 10 | 7 | 0 |
{-# LANGUAGE NamedFieldPuns, OverloadedStrings #-}
module MusicPad.Utils where
import Rika.Scene
import Rika.Engine
import Prelude ()
import Rika.Env hiding (encode)
import Rika.Component.Script.Helper
import qualified Prelude as P
import Rika.Data.Tensor
import MusicPad.Type
import Text.JSON.Generic
import Control.Monad
import Rika.Component.Script.Shell
import Rika.Engine.Loader
import MusicPad.Type.Music
import MPS.Extra
safe_ls :: String -> IO [String]
safe_ls x = ls x ^ reject (starts_with ".")
read_pitch_class :: String -> PitchClass
read_pitch_class = camel_case > P.read
read_pitch :: String -> Pitch
read_pitch x =
let octave = x.select (belongs_to ['0'..'9']) .P.read
pitch_class = x.reject (belongs_to ['0'..'9']) .read_pitch_class
in
(pitch_class, octave) | nfjinjing/level5 | src/MusicPad/Utils.hs | bsd-3-clause | 793 | 2 | 12 | 110 | 234 | 134 | 100 | 25 | 1 |
-- |
-- Module: Language.KURE.Combinators
-- Copyright: (c) 2006-2008 Andy Gill
-- License: BSD3
--
-- Maintainer: Andy Gill <andygill@ku.edu>
-- Stability: unstable
-- Portability: ghc
--
-- This module contains various combinators that use 'Translate' and 'Rewrite'. The convension is that
-- 'Translate' based combinators end with @T@, and 'Rewrite' based combinators end with @R@. Of course,
-- because 'Rewrite' is a type synomim of 'Translate', the 'Rewrite' functions also operate with on 'Translate',
-- and the 'Translate' functions operate with 'Rewrite'.
module Language.KURE.Combinators
( -- * The 'Translate' combinators
(<+)
, (>->)
, failT
, readerT
, readEnvT
, mapEnvT
, writeEnvT
, pureT
, constT
, concatT
, -- * The 'Rewrite' combinators
(.+)
, (!->)
, tryR
, changedR
, repeatR
, acceptR
, idR
, failR
, -- * The Prelude combinators
tuple2R
, listR
, maybeR
, tuple2U
, listU
, maybeU
, -- * Generic failure, over both 'Monad's and 'Translate's.
(?)
, Failable(..)
) where
import Language.KURE.RewriteMonad
import Language.KURE.Translate
import Language.KURE.Rewrite
import Data.Monoid
import Control.Monad
infixl 3 <+, >->, .+, !->
infixr 3 ?
-- Note: We use < for catching fail, . for catching id.
--------------------------------------------------------------------------------
-- The Translate combinators.
-- | like a catch, '<+' does the first translate , and if it fails, then does the second translate.
(<+) :: (Monoid dec, Monad m) => Translate m dec a b -> Translate m dec a b -> Translate m dec a b
(<+) rr1 rr2 = transparently $ translate $ \ e -> apply rr1 e `catchM` (\ _ -> apply rr2 e)
-- | like a @;@ If the first translate succeeds, then do to the second translate after the first translate.
(>->) :: (Monoid dec, Monad m) => Translate m dec a b -> Translate m dec b c -> Translate m dec a c
(>->) rr1 rr2 = transparently $ translate $ \ e -> chainM (apply rr1 e) ( \ _i e2 -> apply rr2 e2)
-- | failing translation.
failT :: (Monad m, Monoid dec) => String -> Translate m dec a b
failT msg = translate $ \ _ -> failM msg
-- | look at the argument for the translation before choosing which translation to perform.
readerT :: (Monoid dec, Monad m) => (a -> Translate m dec a b) -> Translate m dec a b
readerT fn = transparently $ translate $ \ expA -> apply (fn expA) expA
-- | look at the @dec@ before choosing which translation to do.
readEnvT :: (Monad m, Monoid dec) => (dec -> Translate m dec a b) -> Translate m dec a b
readEnvT f = transparently $ translate $ \ e ->
do dec <- readEnvM
apply (f dec) e
-- | add to the context 'dec', which is propogated using a writer monad.
writeEnvT :: (Monad m, Monoid dec) => dec -> Rewrite m dec a
writeEnvT dec = translate $ \ e -> do writeEnvM dec ; return e
-- | change the @dec@'s for a scoped translation.
mapEnvT :: (Monoid dec,Monad m) => (dec -> dec) -> Translate m dec a r -> Translate m dec a r
mapEnvT f_env rr = transparently $ translate $ \ e -> mapEnvM f_env (apply rr e)
-- | 'pureT' promotes a function into an unfailable, non-identity 'Translate'.
pureT :: (Monad m,Monoid dec) => (a -> b) -> Translate m dec a b
pureT f = translate $ \ a -> return (f a)
-- | 'constT' always translates into an unfailable 'Translate' that returns the first argument.
constT :: (Monad m,Monoid dec) => b -> Translate m dec a b
constT = pureT . const
-- | 'concatT' composes a list of 'Translate' into a single 'Translate' which 'mconcat's its result.
concatT :: (Monad m,Monoid dec,Monoid r) => [Translate m dec a r] -> Translate m dec a r
concatT ts = translate $ \ e -> do
rs <- sequence [ apply t e | t <- ts ]
return (mconcat rs)
--------------------------------------------------------------------------------
-- The 'Rewrite' combinators.
-- | if the first rewrite is an identity, then do the second rewrite.
(.+) :: (Monoid dec, Monad m) => Rewrite m dec a -> Rewrite m dec a -> Rewrite m dec a
(.+) a b = a `countTrans` (\ i -> if i == 0 then b else idR)
-- | if the first rewrite was /not/ an identity, then also do the second rewrite.
(!->) :: (Monoid dec, Monad m) => Rewrite m dec a -> Rewrite m dec a -> Rewrite m dec a
(!->) a b = a `countTrans` (\ i -> if i == 0 then idR else b)
-- | catch a failing 'Rewrite', making it into an identity.
tryR :: (Monoid dec, Monad m) => Rewrite m dec a -> Rewrite m dec a
tryR s = s <+ idR
-- | if this is an identity rewrite, make it fail. To succeed, something must have changed.
changedR :: (Monoid dec,Monad m) => Rewrite m dec a -> Rewrite m dec a
changedR rr = rr .+ failR "unchanged"
-- | repeat a rewrite until it fails, then return the result before the failure.
repeatR :: (Monoid dec, Monad m) => Rewrite m dec a -> Rewrite m dec a
repeatR s = tryR (s >-> repeatR s)
-- | look at the argument to a rewrite, and choose to be either a failure of trivial success.
acceptR :: (Monoid dec, Monad m) => (a -> Bool) -> Rewrite m dec a
acceptR fn = transparently $ translate $ \ expA ->
if fn expA
then return expA
else fail "accept failed"
-- | identity rewrite.
idR :: (Monad m, Monoid dec) => Rewrite m dec exp
idR = transparently $ rewrite $ \ e -> return e
-- | failing rewrite.
failR :: (Monad m, Monoid dec) => String -> Rewrite m dec a
failR = failT
--------------------------------------------------------------------------------
-- Prelude structures
tuple2R :: (Monoid dec, Monad m) => Rewrite m dec a -> Rewrite m dec b -> Rewrite m dec (a,b)
tuple2R rra rrb = transparently $ rewrite $ \ (a,b) -> liftM2 (,) (apply rra a) (apply rrb b)
listR :: (Monoid dec, Monad m) => Rewrite m dec a -> Rewrite m dec [a]
listR rr = transparently $ rewrite $ mapM (apply rr)
maybeR :: (Monoid dec, Monad m) => Rewrite m dec a -> Rewrite m dec (Maybe a)
maybeR rr = transparently $ rewrite $ \ e -> case e of
Just e' -> liftM Just (apply rr e')
Nothing -> return $ Nothing
tuple2U :: (Monoid dec, Monad m, Monoid r) => Translate m dec a r -> Translate m dec b r -> Translate m dec (a,b) r
tuple2U rra rrb = translate $ \ (a,b) -> liftM2 mappend (apply rra a) (apply rrb b)
listU :: (Monoid dec, Monad m, Monoid r) => Translate m dec a r -> Translate m dec [a] r
listU rr = translate $ liftM mconcat . mapM (apply rr)
maybeU :: (Monoid dec, Monad m, Monoid r) => Translate m dec a r -> Translate m dec (Maybe a) r
maybeU rr = translate $ \ e -> case e of
Just e' -> apply rr e'
Nothing -> return $ mempty
--------------------------------------------------------------------------------
-- | Failable structure.
class Failable f where
failure :: String -> f a
instance (Monad m, Monoid dec) => Failable (Translate m dec a) where
failure msg = failT msg
instance (Monad m, Monoid dec) => Failable (RewriteM m dec) where
failure msg = fail msg
-- | Guarded translate or monadic action.
(?) :: (Failable f) => Bool -> f a -> f a
(?) False _rr = failure "(False ?)"
(?) True rr = rr
--------------------------------------------------------------------------------
-- internal to this module.
countTrans :: (Monoid dec, Monad m) => Rewrite m dec a -> (Int -> Rewrite m dec a) -> Rewrite m dec a
countTrans rr fn = transparently $ translate $ \ e ->
chainM (apply rr e)
(\ i e' -> apply (fn i) e')
| andygill/kure | Language/KURE/Combinators.hs | bsd-3-clause | 7,385 | 22 | 13 | 1,616 | 2,369 | 1,257 | 1,112 | 107 | 2 |
{-# LANGUAGE TemplateHaskell, NoMonomorphismRestriction, MultiParamTypeClasses, TypeFamilies #-}
module Main where
import Language.KURE
import Language.KURE.Boilerplate
import Data.Monoid
import Data.List
import Debug.Trace
import Control.Monad
import Exp
import Id
data MyGeneric = ExpG Exp
$(kureYourBoilerplate ''MyGeneric ''Id ''())
instance Term Exp where
type Generic Exp = MyGeneric
inject = ExpG
select (ExpG e) = return e
instance Term MyGeneric where
type Generic MyGeneric = MyGeneric -- MyGeneric is its own Generic root.
inject = id
select e = return e
type R e = Rewrite Id () e
type T e1 e2 = Translate Id () e1 e2
main = do
let es1 = [e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11]
sequence_ [ print e | e <- es1]
let frees :: Exp -> Id [Name]
frees exp = do Right (fs,b) <- runTranslate freeExpT () exp
return $ nub fs
let e_frees = map (runId . frees) es1
sequence_ [ print e | e <- e_frees]
sequence [ print (e,function (substExp v ed) e) | v <- ["x","y","z"], ed <- es1, e <- es1 ]
sequence [ print (runId $ runTranslate betaRedR () e) | e <- es1 ]
let fn = extractR (topdownR (promoteR $ repeatR betaRedR))
sequence [ print (runId $ runTranslate fn () e) | e <- es1 ]
------------------------------------------------------------------------
function :: Translate Id () a b -> a -> b
function f a = runId $ do
Right (b,_) <- runTranslate f () a
return $ b
------------------------------------------------------------------------
freeExpT :: T Exp [Name]
freeExpT = lambda <+ var <+ crushU (promoteU freeExpT)
where
var = varG >-> translate (\ (Var v) -> return [v])
lambda = lamG >-> translate (\ (Lam n e) -> do
frees <- apply freeExpT e
return (nub frees \\ [n]))
freeExp :: Exp -> [Name]
freeExp = function freeExpT
newName :: Name -> [Name] -> Name
newName suggest frees =
head [ nm | nm <- suggest : suggests
, nm `notElem` frees
]
where suggests = [ suggest ++ "_" ++ show n | n <- [1..]]
-- Only works for lambdas, fails for all others
shallowAlpha :: [Name] -> R Exp
shallowAlpha frees' = lamG >->
rewrite (\ (Lam n e) -> do
frees <- apply freeExpT e
let n' = newName n (frees ++ frees')
e' <- apply (substExp n (Var n')) e
return $ Lam n' e')
substExp :: Name -> Exp -> R Exp
substExp v s = rule1 <+ rule2 <+ rule3 <+ rule4 <+ rule5 <+ rule6
where
-- From Lambda Calc Textbook, the 6 rules.
rule1 = rewrite $ withVar $ \ n -> n == v ? return s
rule2 = varP $ \ n -> n /= v ? idR
rule3 = lamP $ \ n e -> n == v ? idR
rule4 = lamP $ \ n e -> (n `notElem` freeExp s || v `notElem` freeExp e)
? allR (promoteR $ substExp v s)
rule5 = lamP $ \ n e -> (n `elem` freeExp s && v `elem` freeExp e)
? (shallowAlpha (freeExp s) >-> substExp v s)
rule6 = appG >-> allR (promoteR $ substExp v s)
-------------
betaRedR :: R Exp
betaRedR = rewrite $ \ e ->
case e of
(App (Lam v e1) e2) -> apply (substExp v e2) e1
_ -> fail "betaRed"
debugR :: (Show e) => String -> R e
debugR msg = translate $ \ e -> transparently $ trace (msg ++ " : " ++ show e) (return e)
listR :: R e -> R [e]
listR rr = rewrite $ \ es -> transparently $ do mapM (apply rr) es
tuple2R :: R e1 -> R e2 -> R (e1,e2)
tuple2R rr1 rr2 = rewrite $ \ (e1,e2) -> transparently $ do liftM2 (,) (apply rr1 e1) (apply rr2 e2)
--allR' :: (R (Generic e)) -> R [e]
--allR' = extractR
| andygill/kure-your-boilerplate | test/Test2.hs | bsd-3-clause | 3,729 | 5 | 18 | 1,118 | 1,463 | 757 | 706 | 79 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
module Schema.AQuery where
import Data.List.NonEmpty (NonEmpty ((:|)))
import Database.DSH
data Trade = Trade
{ t_amount :: Double
, t_price :: Double
, t_tid :: Integer
, t_timestamp :: Integer
, t_tradeDate :: Day
}
deriveDSH ''Trade
deriveTA ''Trade
generateTableSelectors ''Trade
data Portfolio = Portfolio
{ po_pid :: Integer
, po_tid :: Integer
, po_tradedSince :: Integer
}
deriveDSH ''Portfolio
deriveTA ''Portfolio
generateTableSelectors ''Portfolio
trades :: Q [Trade]
trades = table "trades"
("amount" :|
[ "price"
, "tid"
, "ts"
, "tradeDate"])
(TableHints (pure $ Key ("tid" :| ["ts"])) NonEmpty)
portfolios :: Q [Portfolio]
portfolios = table "portfolio"
("po_pid" :| ["po_tid", "po_tradedSince"])
(TableHints (pure $ Key (pure "po_pid")) NonEmpty)
data Packet = Packet
{ p_dest :: Integer
, p_len :: Integer
, p_pid :: Integer
, p_src :: Integer
, p_ts :: Integer
}
deriveDSH ''Packet
deriveTA ''Packet
generateTableSelectors ''Packet
packets :: Q [Packet]
packets = table "packets"
("dst" :|
[ "len"
, "pid"
, "src"
, "ts"
])
(TableHints (pure $ Key (pure "pid")) NonEmpty)
| ulricha/dsh-example-queries | Schema/AQuery.hs | bsd-3-clause | 1,659 | 0 | 13 | 588 | 406 | 225 | 181 | 53 | 1 |
module Parsing.Fta
( parseFta
) where
import Data.ByteString (ByteString)
import Data.Maybe (isJust)
import Text.Parsec hiding (State)
import Text.Parsec.ByteString
import Data.Set (Set)
import qualified Data.Set as Set
import Text.Parsec.Char
import Text.Parsec.Number
import Types.Fta
-- |Returns a FTA parsed from a string. Possible failure is represented by the 'm' type.
parseFta :: (Monad m) => ByteString -> m Fta
parseFta fileContent =
case runParser file () "" fileContent of
Left error -> fail $ show error
Right fta -> return fta
file :: Parser Fta
file = do
string "Ops"
skipSpacesAndNewlines
symbolList <- symbolList
skipMany1 endOfLine
(states, finalStates, transitions) <- automaton
returnFta states finalStates transitions symbolList
returnFta :: Set State -> Set State -> Set Transition -> RankedAlphabet -> Parser Fta
returnFta states finalStates transitions rankedAlphabet =
case makeFta states finalStates transitions rankedAlphabet of
Just fta -> return fta
_ -> fail "Invalid FTA"
symbolList :: Parser RankedAlphabet
symbolList =
sepEndByToSet symbolDecl (oneOf " \n")
symbolDecl :: Parser (Symbol, Rank)
symbolDecl = do
symbol <- Parsing.Fta.symbol
spaces
char ':'
skipMany space
rank <- decimal
return (symbol, rank)
automaton :: Parser (Set String, Set String, Set Transition)
automaton = do
string "Automaton "
many1 alphaNum
skipSpacesAndNewlines
string "States"
states <- stateList
skipSpacesAndNewlines
string "Final States"
finalStates <- stateList
skipSpacesAndNewlines
string "Transitions"
skipSpacesAndNewlines
transitions <- transitionList
return (states, finalStates, transitions)
stateList :: Parser (Set String)
stateList = do
isSpace <- optionMaybe (char ' ')
if isJust isSpace
then sepEndByToSet state (char ' ')
else endOfLine >> sepEndByToSet state endOfLine
state :: Parser String
state =
many1 alphaNum
transitionList :: Parser (Set Transition)
transitionList =
sepEndByToSet transition endOfLine
transition :: Parser Transition
transition = do
symbol <- Parsing.Fta.symbol
inputStates <- transitionStateList
string " -> "
finalState <- state
return (Types.Fta.Transition symbol inputStates finalState)
transitionStateList :: Parser (Set String)
transitionStateList =
option Set.empty (brackets (sepEndByToSet state (char ',')))
symbol :: Parser Symbol
symbol =
many1 alphaNum
sepEndByToSet :: (Ord a, Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m (Set a)
sepEndByToSet value separator =
fmap Set.fromList (value `sepEndBy` separator)
skipSpacesAndNewlines :: Parser ()
skipSpacesAndNewlines =
skipMany (oneOf " \n")
brackets =
between (char '(') (char ')')
| jakubriha/automata | src/Parsing/Fta.hs | bsd-3-clause | 2,764 | 0 | 11 | 501 | 866 | 425 | 441 | 88 | 2 |
-- | Check parse tables for conflicts and resolve them.
module Data.Parser.Grempa.Parser.Conflict
( Conflict
, conflicts
, showConflict
) where
import qualified Control.Arrow as A
import Data.Function
import Data.List
import Data.Parser.Grempa.Grammar.Token
import Data.Parser.Grempa.Parser.Table
type Conflict t = (StateI, [[(Tok t, Action t)]])
-- | Check an action table to see if there are any conflicts.
-- If there is a conflict, try to resolve it.
conflicts :: Ord t
=> ActionTable t
-- ^ Input table with potential conflicts
-> (ActionTable t, [Conflict t])
-- ^ Corrected action table, and its conflicts
conflicts tab = (tab', cs)
where
cs = filter (not . null . snd)
[(st, filter ((>=2) . length)
$ groupBy ((==) `on` fst)
$ nub
$ sort acts)
| (st, (acts, _)) <- tab]
tab' = map (A.second (A.first (nub . sort))) tab
-- | Show a conflict in a readable way
showConflict :: Show t => Conflict t -> String
showConflict (st, confs)
= "Warning: Conflicts in action table (state " ++ show st
++ "), between " ++ intercalate " and " (map go confs)
where
go cs = "[" ++ intercalate "," (map go' cs) ++ "]"
go' (t, a) = "On token " ++ tokToString t ++ " " ++ showAction a
showAction (Shift s) = "shift state " ++ show s
showAction (Reduce r p _ _) = "reduce (rule " ++ show r ++ ", production " ++ show p ++ ")"
showAction Accept = "accept"
showAction (Error {}) = "error"
| ollef/Grempa | Data/Parser/Grempa/Parser/Conflict.hs | bsd-3-clause | 1,575 | 0 | 16 | 451 | 477 | 262 | 215 | 31 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.String
import Data.Text.Lazy (Text)
import Data.Monoid ((<>))
import Web.Scotty.Trans
import Web.Beam
import Web.Beam.Types
import Web.Beam.Plugins.Auth
import Web.Beam.Plugins.Session
import Web.Beam.Utils.Cookie
-- | Use the RAM auth and session backend. Later we could swap this out
-- for a DB backend w/o having to change our application code.
import MemoryBackend
type MyApp b = BeamApplication AppState b
-- | Our Application datatype must hold thread safe resources for our plugins.
data AppState = AppState { authContainer :: AuthContainer
, sessContainer :: SessionContainer }
-- | Allow plugins to know where their resources are.
instance AuthApp AppState where
getAuthContainer = authContainer
instance SessionApp AppState where
getSessionContainer = sessContainer
main :: IO ()
main = do
-- Initialize plugin resources and settings. Plugins can add settings and
-- additional functions (e.g. routes and middleware) that will run before
-- your application.
(initState, appConfig) <- runBeamInit $ do
authMem <- initAuthMemory
sessMem <- initSessionMemory
return $ AppState authMem sessMem
runBeamApp appConfig initState app
app :: MyApp ()
app = do
get "/" $ do
c <- getCurrentUser
html $ "<html><body>" <> (fromString $ show c) <> "</body></html>"
get "/register" $ do
register "bob" "123"
redirect "/"
get "/login" $ do
c <- login "bob" "123"
html $ "<html><body>" <> (fromString $ show c) <> "</body></html>"
get "/logout" $ do
logout
redirect "/" | hansonkd/BeamFramework | examples/Main.hs | bsd-3-clause | 1,678 | 0 | 14 | 374 | 355 | 187 | 168 | 40 | 1 |
module AWS.RDS.Types.OptionGroup
( OptionGroup(..)
, Option(..)
) where
import AWS.Lib.FromText (Text)
import AWS.RDS.Types.DBInstance
( VpcSecurityGroupMembership
, DBSecurityGroupMembership
)
data OptionGroup = OptionGroup
{ optionGroupAllowsVpcAndNonVpcInstanceMemberships :: Bool
, optionGroupMajorEngineVersion :: Text
, optionGroupName :: Text
, optionGroupVpcId :: Maybe Text
, optionGroupEngineName :: Text
, optionGroupDescription :: Text
, optionGroupOption :: [Option]
}
deriving (Show, Eq)
data Option = Option
{ optionPort :: Int
, optionName :: Text
, optionDescription :: Text
, optionVpcSecurityGroupMemberships :: [VpcSecurityGroupMembership]
, optionDBSecurityGroupMemberships :: [DBSecurityGroupMembership]
}
deriving (Show, Eq)
| IanConnolly/aws-sdk-fork | AWS/RDS/Types/OptionGroup.hs | bsd-3-clause | 835 | 0 | 9 | 170 | 174 | 111 | 63 | 23 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Mandelbrot.NikolaV4.Implementation where
import qualified Prelude as P
import Prelude hiding (iterate, map, zipWith)
import Data.Array.Nikola.Backend.CUDA
import Data.Array.Nikola.Combinators
import Data.Array.Nikola.Eval
import Data.Array.Nikola.Repr.HintIrregular
import Data.Int
import Data.Word
type R = Double
type RGBA = Word32
type Complex = (Exp R, Exp R)
type Bitmap r = Array r DIM2 (Exp RGBA)
type MBitmap r = MArray r DIM2 (Exp RGBA)
type ComplexPlane r = Array r DIM2 Complex
type MComplexPlane r = MArray r DIM2 Complex
type StepPlane r = Array r DIM2 (Complex, Exp Int32)
type MStepPlane r = MArray r DIM2 (Complex, Exp Int32)
magnitude :: Complex -> Exp R
magnitude (x,y) = x*x + y*y
instance Num Complex where
(x,y) + (x',y') = (x+x' ,y+y')
(x,y) - (x',y') = (x-x', y-y')
(x,y) * (x',y') = (x*x'-y*y', x*y'+y*x')
negate (x,y) = (negate x, negate y)
abs z = (magnitude z, 0)
signum (0,0) = 0
signum z@(x,y) = (x/r, y/r) where r = magnitude z
fromInteger n = (fromInteger n, 0)
stepN :: Exp Int32 -> ComplexPlane G -> MStepPlane G -> P ()
stepN n cs mzs = do
zs <- unsafeFreezeMArray mzs
loadP (hintIrregular (zipWith stepPoint cs zs)) mzs
where
stepPoint :: Complex -> (Complex, Exp Int32) -> (Complex, Exp Int32)
stepPoint c (z,i) = iterateWhile n go (z,i)
where
go :: (Complex, Exp Int32) -> (Exp Bool, (Complex, Exp Int32))
go (z,i) =
if magnitude z' >* 4.0
then (lift False, (z, i))
else (lift True, (z', i+1))
where
z' = next c z
next :: Complex -> Complex -> Complex
next c z = c + (z * z)
genPlane :: Exp R
-> Exp R
-> Exp R
-> Exp R
-> Exp Int32
-> Exp Int32
-> MComplexPlane G
-> P ()
genPlane lowx lowy highx highy viewx viewy mcs =
flip loadP mcs $
fromFunction (Z:.viewy:.viewx) $ \(Z:.y:.x) ->
(lowx + (fromInt x*xsize)/fromInt viewx, lowy + (fromInt y*ysize)/fromInt viewy)
where
xsize, ysize :: Exp R
xsize = highx - lowx
ysize = highy - lowy
mkinit :: ComplexPlane G -> MStepPlane G -> P ()
mkinit cs mzs = loadP (map f cs) mzs
where
f :: Complex -> (Complex, Exp Int32)
f z = (z,0)
prettyRGBA :: Exp Int32 -> (Complex, Exp Int32) -> Exp RGBA
{-# INLINE prettyRGBA #-}
prettyRGBA limit (_, s) = r + g + b + a
where
t = fromInt $ ((limit - s) * 255) `quot` limit
r = (t `mod` 128 + 64) * 0x1000000
g = (t * 2 `mod` 128 + 64) * 0x10000
b = (t * 3 `mod` 256 ) * 0x100
a = 0xFF
prettyMandelbrot :: Exp Int32 -> StepPlane G -> MBitmap G -> P ()
prettyMandelbrot limit zs mbmap =
loadP (map (prettyRGBA limit) zs) mbmap
mandelbrot :: Exp R
-> Exp R
-> Exp R
-> Exp R
-> Exp Int32
-> Exp Int32
-> Exp Int32
-> MComplexPlane G
-> MStepPlane G
-> P ()
mandelbrot lowx lowy highx highy viewx viewy depth mcs mzs = do
genPlane lowx lowy highx highy viewx viewy mcs
cs <- unsafeFreezeMArray mcs
mkinit cs mzs
stepN depth cs mzs
| mainland/nikola | examples/mandelbrot/Mandelbrot/NikolaV4/Implementation.hs | bsd-3-clause | 3,337 | 0 | 15 | 976 | 1,439 | 766 | 673 | 92 | 2 |
------------------------------------------------------------------------------
-- |
-- Module : Data.Param.TFVec
-- Copyright : (c) 2009 Christiaan Baaij
-- Licence : BSD-style (see the file LICENCE)
--
-- Maintainer : christiaan.baaij@gmail.com
-- Stability : experimental
-- Portability : non-portable
--
-- 'TFVec': Fixed sized vectors. Vectors with numerically parameterized size,
-- using type-level numerals from 'tfp' library
--
------------------------------------------------------------------------------
module Data.Param.TFVec
( TFVec
, empty
, (+>)
, singleton
, vectorTH
, unsafeVector
, readTFVec
, length
, lengthT
, fromVector
, null
, (!)
, replace
, head
, last
, init
, tail
, take
, drop
, select
, (<+)
, (++)
, map
, zipWith
, foldl
, foldr
, zip
, unzip
, shiftl
, shiftr
, rotl
, rotr
, concat
, reverse
, iterate
, iteraten
, generate
, generaten
, copy
, copyn
, split
) where
import Types
import Types.Data.Num
import Types.Data.Num.Decimal.Literals.TH
import Data.RangedWord
import Data.Generics (Data)
import Data.Typeable
import qualified Prelude as P
import Prelude hiding (
null, length, head, tail, last, init, take, drop, (++), map, foldl, foldr,
zipWith, zip, unzip, concat, reverse, iterate )
import qualified Data.Foldable as DF (Foldable, foldr)
import qualified Data.Traversable as DT (Traversable(traverse))
import Language.Haskell.TH hiding (Pred)
import Language.Haskell.TH.Syntax (Lift(..))
newtype (NaturalT s) => TFVec s a = TFVec {unTFVec :: [a]}
deriving (Eq, Typeable)
deriving instance (NaturalT s, Typeable s, Data s, Typeable a, Data a) => Data (TFVec s a)
-- ==========================
-- = Constructing functions =
-- ==========================
empty :: TFVec D0 a
empty = TFVec []
(+>) :: a -> TFVec s a -> TFVec (Succ s) a
x +> (TFVec xs) = TFVec (x:xs)
infix 5 +>
singleton :: a -> TFVec D1 a
singleton x = x +> empty
-- FIXME: Not the most elegant solution... but it works for now in clash
vectorTH :: (Lift a) => [a] -> ExpQ
-- vectorTH xs = sigE [| (TFVec xs) |] (decTFVecT (toInteger (P.length xs)) xs)
vectorTH [] = [| empty |]
vectorTH [x] = [| singleton x |]
vectorTH (x:xs) = [| x +> $(vectorTH xs) |]
unsafeVector :: NaturalT s => s -> [a] -> TFVec s a
unsafeVector l xs
| fromIntegerT l /= P.length xs =
error (show 'unsafeVector P.++ ": dynamic/static lenght mismatch")
| otherwise = TFVec xs
readTFVec :: (Read a, NaturalT s) => String -> TFVec s a
readTFVec = read
-- =======================
-- = Observing functions =
-- =======================
length :: forall s a . NaturalT s => TFVec s a -> Int
length _ = fromIntegerT (undefined :: s)
lengthT :: NaturalT s => TFVec s a -> s
lengthT = undefined
fromVector :: NaturalT s => TFVec s a -> [a]
fromVector (TFVec xs) = xs
null :: TFVec D0 a -> Bool
null _ = True
(!) :: ( PositiveT s
, NaturalT u
, (s :>: u) ~ True) => TFVec s a -> RangedWord u -> a
(TFVec xs) ! i = xs !! (fromInteger (toInteger i))
-- ==========================
-- = Transforming functions =
-- ==========================
replace :: (PositiveT s, NaturalT u, (s :>: u) ~ True) =>
TFVec s a -> RangedWord u -> a -> TFVec s a
replace (TFVec xs) i y = TFVec $ replace' xs (toInteger i) y
where replace' [] _ _ = []
replace' (_:xs) 0 y = (y:xs)
replace' (x:xs) n y = x : (replace' xs (n-1) y)
head :: PositiveT s => TFVec s a -> a
head = P.head . unTFVec
tail :: PositiveT s => TFVec s a -> TFVec (Pred s) a
tail = liftV P.tail
last :: PositiveT s => TFVec s a -> a
last = P.last . unTFVec
init :: PositiveT s => TFVec s a -> TFVec (Pred s) a
init = liftV P.init
take :: NaturalT i => i -> TFVec s a -> TFVec (Min s i) a
take i = liftV $ P.take (fromIntegerT i)
drop :: NaturalT i => i -> TFVec s a -> TFVec (s :-: (Min s i)) a
drop i = liftV $ P.drop (fromIntegerT i)
select :: (NaturalT f, NaturalT s, NaturalT n, (f :<: i) ~ True,
(((s :*: n) :+: f) :<=: i) ~ True) =>
f -> s -> n -> TFVec i a -> TFVec n a
select f s n = liftV (select' f' s' n')
where (f', s', n') = (fromIntegerT f, fromIntegerT s, fromIntegerT n)
select' f s n = ((selectFirst0 s n).(P.drop f))
selectFirst0 :: Int -> Int -> [a] -> [a]
selectFirst0 s n l@(x:_)
| n > 0 = x : selectFirst0 s (n-1) (P.drop s l)
| otherwise = []
selectFirst0 _ 0 [] = []
(<+) :: TFVec s a -> a -> TFVec (Succ s) a
(<+) (TFVec xs) x = TFVec (xs P.++ [x])
(++) :: TFVec s a -> TFVec s2 a -> TFVec (s :+: s2) a
(++) = liftV2 (P.++)
infixl 5 <+
infixr 5 ++
map :: (a -> b) -> TFVec s a -> TFVec s b
map f = liftV (P.map f)
zipWith :: (a -> b -> c) -> TFVec s a -> TFVec s b -> TFVec s c
zipWith f = liftV2 (P.zipWith f)
foldl :: (a -> b -> a) -> a -> TFVec s b -> a
foldl f e = (P.foldl f e) . unTFVec
foldr :: (b -> a -> a) -> a -> TFVec s b -> a
foldr f e = (P.foldr f e) . unTFVec
zip :: TFVec s a -> TFVec s b -> TFVec s (a, b)
zip = liftV2 P.zip
unzip :: TFVec s (a, b) -> (TFVec s a, TFVec s b)
unzip (TFVec xs) = let (a,b) = P.unzip xs in (TFVec a, TFVec b)
shiftl :: (PositiveT s, NaturalT n, n ~ Pred s, s ~ Succ n) =>
TFVec s a -> a -> TFVec s a
shiftl xs x = x +> init xs
shiftr :: (PositiveT s, NaturalT n, n ~ Pred s, s ~ Succ n) =>
TFVec s a -> a -> TFVec s a
shiftr xs x = tail xs <+ x
rotl :: forall s a . NaturalT s => TFVec s a -> TFVec s a
rotl = liftV rotl'
where vlen = fromIntegerT (undefined :: s)
rotl' [] = []
rotl' xs = let (i,[l]) = splitAt (vlen - 1) xs
in l : i
rotr :: NaturalT s => TFVec s a -> TFVec s a
rotr = liftV rotr'
where
rotr' [] = []
rotr' (x:xs) = xs P.++ [x]
concat :: TFVec s1 (TFVec s2 a) -> TFVec (s1 :*: s2) a
concat = liftV (P.foldr ((P.++).unTFVec) [])
reverse :: TFVec s a -> TFVec s a
reverse = liftV P.reverse
iterate :: NaturalT s => (a -> a) -> a -> TFVec s a
iterate = iteraten (undefined :: s)
iteraten :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
iteraten s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.iterate f x)
generate :: NaturalT s => (a -> a) -> a -> TFVec s a
generate = generaten (undefined :: s)
generaten :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
generaten s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.tail $ P.iterate f x)
copy :: NaturalT s => a -> TFVec s a
copy x = copyn (undefined :: s) x
copyn :: NaturalT s => s -> a -> TFVec s a
copyn s x = iteraten s id x
split :: ( NaturalT s
-- , IsEven s ~ True
) => TFVec s a -> (TFVec (Div2 s) a, TFVec (Div2 s) a)
split (TFVec xs) = (TFVec (P.take vlen xs), TFVec (P.drop vlen xs))
where
vlen = round ((fromIntegral (P.length xs)) / 2)
-- =============
-- = Instances =
-- =============
instance Show a => Show (TFVec s a) where
showsPrec _ = showV.unTFVec
where showV [] = showString "<>"
showV (x:xs) = showChar '<' . shows x . showl xs
where showl [] = showChar '>'
showl (x:xs) = showChar ',' . shows x .
showl xs
instance (Read a, NaturalT nT) => Read (TFVec nT a) where
readsPrec _ str
| all fitsLength possibilities = P.map toReadS possibilities
| otherwise = error (fName P.++ ": string/dynamic length mismatch")
where
fName = "Data.Param.TFVec.read"
expectedL = fromIntegerT (undefined :: nT)
possibilities = readTFVecList str
fitsLength (_, l, _) = l == expectedL
toReadS (xs, _, rest) = (TFVec xs, rest)
instance NaturalT s => DF.Foldable (TFVec s) where
foldr = foldr
instance NaturalT s => Functor (TFVec s) where
fmap = map
instance NaturalT s => DT.Traversable (TFVec s) where
traverse f = (fmap TFVec).(DT.traverse f).unTFVec
instance (Lift a, NaturalT nT) => Lift (TFVec nT a) where
lift (TFVec xs) = [| unsafeTFVecCoerse
$(decLiteralV (fromIntegerT (undefined :: nT)))
(TFVec xs) |]
-- ======================
-- = Internal Functions =
-- ======================
liftV :: ([a] -> [b]) -> TFVec nT a -> TFVec nT' b
liftV f = TFVec . f . unTFVec
liftV2 :: ([a] -> [b] -> [c]) -> TFVec s a -> TFVec s2 b -> TFVec s3 c
liftV2 f a b = TFVec (f (unTFVec a) (unTFVec b))
splitAtM :: Int -> [a] -> Maybe ([a],[a])
splitAtM n xs = splitAtM' n [] xs
where splitAtM' 0 xs ys = Just (xs, ys)
splitAtM' n xs (y:ys) | n > 0 = do
(ls, rs) <- splitAtM' (n-1) xs ys
return (y:ls,rs)
splitAtM' _ _ _ = Nothing
unsafeTFVecCoerse :: nT' -> TFVec nT a -> TFVec nT' a
unsafeTFVecCoerse _ (TFVec v) = (TFVec v)
readTFVecList :: Read a => String -> [([a], Int, String)]
readTFVecList = readParen' False (\r -> [pr | ("<",s) <- lexTFVec r,
pr <- readl s])
where
readl s = [([],0,t) | (">",t) <- lexTFVec s] P.++
[(x:xs,1+n,u) | (x,t) <- reads s,
(xs, n, u) <- readl' t]
readl' s = [([],0,t) | (">",t) <- lexTFVec s] P.++
[(x:xs,1+n,v) | (",",t) <- lex s,
(x,u) <- reads t,
(xs,n,v) <- readl' u]
readParen' b g = if b then mandatory else optional
where optional r = g r P.++ mandatory r
mandatory r = [(x,n,u) | ("(",s) <- lexTFVec r,
(x,n,t) <- optional s,
(")",u) <- lexTFVec t]
-- Custom lexer for FSVecs, we cannot use lex directly because it considers
-- sequences of < and > as unique lexemes, and that breaks nested FSVecs, e.g.
-- <<1,2><3,4>>
lexTFVec :: ReadS String
lexTFVec ('>':rest) = [(">",rest)]
lexTFVec ('<':rest) = [("<",rest)]
lexTFVec str = lex str
| christiaanb/tfvec | Data/Param/TFVec.hs | bsd-3-clause | 10,103 | 2 | 14 | 2,948 | 4,342 | 2,291 | 2,051 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, ScopedTypeVariables, MagicHash #-}
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.List
-- Copyright : (c) The University of Glasgow 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The List data type and its operations
--
-----------------------------------------------------------------------------
module GHC.List (
-- [] (..), -- built-in syntax; can't be used in export list
map, (++), filter, concat,
head, last, tail, init, uncons, null, length, (!!),
foldl, foldl', foldl1, foldl1', scanl, scanl1, scanl', foldr, foldr1,
scanr, scanr1, iterate, repeat, replicate, cycle,
take, drop, sum, product, maximum, minimum, splitAt, takeWhile, dropWhile,
span, break, reverse, and, or,
any, all, elem, notElem, lookup,
concatMap,
zip, zip3, zipWith, zipWith3, unzip, unzip3,
errorEmptyList,
) where
import Data.Maybe
import GHC.Base
import GHC.Num (Num(..))
import GHC.Integer (Integer)
infixl 9 !!
infix 4 `elem`, `notElem`
--------------------------------------------------------------
-- List-manipulation functions
--------------------------------------------------------------
-- | Extract the first element of a list, which must be non-empty.
head :: [a] -> a
head (x:_) = x
head [] = badHead
{-# NOINLINE [1] head #-}
badHead :: a
badHead = errorEmptyList "head"
-- This rule is useful in cases like
-- head [y | (x,y) <- ps, x==t]
{-# RULES
"head/build" forall (g::forall b.(a->b->b)->b->b) .
head (build g) = g (\x _ -> x) badHead
"head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) .
head (augment g xs) = g (\x _ -> x) (head xs)
#-}
-- | Decompose a list into its head and tail. If the list is empty,
-- returns 'Nothing'. If the list is non-empty, returns @'Just' (x, xs)@,
-- where @x@ is the head of the list and @xs@ its tail.
--
-- /Since: 4.8.0.0/
uncons :: [a] -> Maybe (a, [a])
uncons [] = Nothing
uncons (x:xs) = Just (x, xs)
-- | Extract the elements after the head of a list, which must be non-empty.
tail :: [a] -> [a]
tail (_:xs) = xs
tail [] = errorEmptyList "tail"
-- | Extract the last element of a list, which must be finite and non-empty.
last :: [a] -> a
#ifdef USE_REPORT_PRELUDE
last [x] = x
last (_:xs) = last xs
last [] = errorEmptyList "last"
#else
-- use foldl to allow fusion
last = foldl (\_ x -> x) (errorEmptyList "last")
#endif
-- | Return all the elements of a list except the last one.
-- The list must be non-empty.
init :: [a] -> [a]
#ifdef USE_REPORT_PRELUDE
init [x] = []
init (x:xs) = x : init xs
init [] = errorEmptyList "init"
#else
-- eliminate repeated cases
init [] = errorEmptyList "init"
init (x:xs) = init' x xs
where init' _ [] = []
init' y (z:zs) = y : init' z zs
#endif
-- | Test whether a list is empty.
null :: [a] -> Bool
null [] = True
null (_:_) = False
-- | /O(n)/. 'length' returns the length of a finite list as an 'Int'.
-- It is an instance of the more general 'Data.List.genericLength',
-- the result type of which may be any kind of number.
{-# NOINLINE [1] length #-}
length :: [a] -> Int
length xs = lenAcc xs 0
lenAcc :: [a] -> Int -> Int
lenAcc [] n = n
lenAcc (_:ys) n = lenAcc ys (n+1)
{-# RULES
"length" [~1] forall xs . length xs = foldr lengthFB idLength xs 0
"lengthList" [1] foldr lengthFB idLength = lenAcc
#-}
-- The lambda form turns out to be necessary to make this inline
-- when we need it to and give good performance.
{-# INLINE [0] lengthFB #-}
lengthFB :: x -> (Int -> Int) -> Int -> Int
lengthFB _ r = \ !a -> r (a + 1)
{-# INLINE [0] idLength #-}
idLength :: Int -> Int
idLength = id
-- | 'filter', applied to a predicate and a list, returns the list of
-- those elements that satisfy the predicate; i.e.,
--
-- > filter p xs = [ x | x <- xs, p x]
{-# NOINLINE [1] filter #-}
filter :: (a -> Bool) -> [a] -> [a]
filter _pred [] = []
filter pred (x:xs)
| pred x = x : filter pred xs
| otherwise = filter pred xs
{-# NOINLINE [0] filterFB #-}
filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b
filterFB c p x r | p x = x `c` r
| otherwise = r
{-# RULES
"filter" [~1] forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
"filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
"filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
#-}
-- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
-- filterFB (filterFB c p) q a b
-- = if q a then filterFB c p a b else b
-- = if q a then (if p a then c a b else b) else b
-- = if q a && p a then c a b else b
-- = filterFB c (\x -> q x && p x) a b
-- I originally wrote (\x -> p x && q x), which is wrong, and actually
-- gave rise to a live bug report. SLPJ.
-- | 'foldl', applied to a binary operator, a starting value (typically
-- the left-identity of the operator), and a list, reduces the list
-- using the binary operator, from left to right:
--
-- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
--
-- The list must be finite.
-- We write foldl as a non-recursive thing, so that it
-- can be inlined, and then (often) strictness-analysed,
-- and hence the classic space leak on foldl (+) 0 xs
foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b
{-# INLINE foldl #-}
foldl k z0 xs =
foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> fn (k z v))) (id :: b -> b) xs z0
-- See Note [Left folds via right fold]
{-
Note [Left folds via right fold]
Implementing foldl et. al. via foldr is only a good idea if the compiler can
optimize the resulting code (eta-expand the recursive "go"). See #7994.
We hope that one of the two measure kick in:
* Call Arity (-fcall-arity, enabled by default) eta-expands it if it can see
all calls and determine that the arity is large.
* The oneShot annotation gives a hint to the regular arity analysis that
it may assume that the lambda is called at most once.
See [One-shot lambdas] in CoreArity and especially [Eta expanding thunks]
in CoreArity.
The oneShot annotations used in this module are correct, as we only use them in
argumets to foldr, where we know how the arguments are called.
-}
-- ----------------------------------------------------------------------------
-- | A strict version of 'foldl'.
foldl' :: forall a b . (b -> a -> b) -> b -> [a] -> b
{-# INLINE foldl' #-}
foldl' k z0 xs =
foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> z `seq` fn (k z v))) (id :: b -> b) xs z0
-- See Note [Left folds via right fold]
-- | 'foldl1' is a variant of 'foldl' that has no starting value argument,
-- and thus must be applied to non-empty lists.
foldl1 :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs) = foldl f x xs
foldl1 _ [] = errorEmptyList "foldl1"
-- | A strict version of 'foldl1'
foldl1' :: (a -> a -> a) -> [a] -> a
foldl1' f (x:xs) = foldl' f x xs
foldl1' _ [] = errorEmptyList "foldl1'"
-- -----------------------------------------------------------------------------
-- List sum and product
-- | The 'sum' function computes the sum of a finite list of numbers.
sum :: (Num a) => [a] -> a
{-# INLINE sum #-}
sum = foldl (+) 0
-- | The 'product' function computes the product of a finite list of numbers.
product :: (Num a) => [a] -> a
{-# INLINE product #-}
product = foldl (*) 1
-- | 'scanl' is similar to 'foldl', but returns a list of successive
-- reduced values from the left:
--
-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--
-- Note that
--
-- > last (scanl f z xs) == foldl f z xs.
-- This peculiar arrangement is necessary to prevent scanl being rewritten in
-- its own right-hand side.
{-# NOINLINE [1] scanl #-}
scanl :: (b -> a -> b) -> b -> [a] -> [b]
scanl = scanlGo
where
scanlGo :: (b -> a -> b) -> b -> [a] -> [b]
scanlGo f q ls = q : (case ls of
[] -> []
x:xs -> scanlGo f (f q x) xs)
-- Note [scanl rewrite rules]
{-# RULES
"scanl" [~1] forall f a bs . scanl f a bs =
build (\c n -> a `c` foldr (scanlFB f c) (constScanl n) bs a)
"scanlList" [1] forall f (a::a) bs .
foldr (scanlFB f (:)) (constScanl []) bs a = tail (scanl f a bs)
#-}
{-# INLINE [0] scanlFB #-}
scanlFB :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c
scanlFB f c = \b g -> oneShot (\x -> let b' = f x b in b' `c` g b')
-- See Note [Left folds via right fold]
{-# INLINE [0] constScanl #-}
constScanl :: a -> b -> a
constScanl = const
-- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
--
-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
scanl1 :: (a -> a -> a) -> [a] -> [a]
scanl1 f (x:xs) = scanl f x xs
scanl1 _ [] = []
-- | A strictly accumulating version of 'scanl'
{-# NOINLINE [1] scanl' #-}
scanl' :: (b -> a -> b) -> b -> [a] -> [b]
-- This peculiar form is needed to prevent scanl' from being rewritten
-- in its own right hand side.
scanl' = scanlGo'
where
scanlGo' :: (b -> a -> b) -> b -> [a] -> [b]
scanlGo' f !q ls = q : (case ls of
[] -> []
x:xs -> scanlGo' f (f q x) xs)
-- Note [scanl rewrite rules]
{-# RULES
"scanl'" [~1] forall f a bs . scanl' f a bs =
build (\c n -> a `c` foldr (scanlFB' f c) (flipSeqScanl' n) bs a)
"scanlList'" [1] forall f a bs .
foldr (scanlFB' f (:)) (flipSeqScanl' []) bs a = tail (scanl' f a bs)
#-}
{-# INLINE [0] scanlFB' #-}
scanlFB' :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c
scanlFB' f c = \b g -> oneShot (\x -> let !b' = f x b in b' `c` g b')
-- See Note [Left folds via right fold]
{-# INLINE [0] flipSeqScanl' #-}
flipSeqScanl' :: a -> b -> a
flipSeqScanl' a !_b = a
{-
Note [scanl rewrite rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~
In most cases, when we rewrite a form to one that can fuse, we try to rewrite it
back to the original form if it does not fuse. For scanl, we do something a
little different. In particular, we rewrite
scanl f a bs
to
build (\c n -> a `c` foldr (scanlFB f c) (constScanl n) bs a)
When build is inlined, this becomes
a : foldr (scanlFB f (:)) (constScanl []) bs a
To rewrite this form back to scanl, we would need a rule that looked like
forall f a bs. a : foldr (scanlFB f (:)) (constScanl []) bs a = scanl f a bs
The problem with this rule is that it has (:) at its head. This would have the
effect of changing the way the inliner looks at (:), not only here but
everywhere. In most cases, this makes no difference, but in some cases it
causes it to come to a different decision about whether to inline something.
Based on nofib benchmarks, this is bad for performance. Therefore, we instead
match on everything past the :, which is just the tail of scanl.
-}
-- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
-- above functions.
-- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
-- and thus must be applied to non-empty lists.
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 _ [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
foldr1 _ [] = errorEmptyList "foldr1"
-- | 'scanr' is the right-to-left dual of 'scanl'.
-- Note that
--
-- > head (scanr f z xs) == foldr f z xs.
{-# NOINLINE [1] scanr #-}
scanr :: (a -> b -> b) -> b -> [a] -> [b]
scanr _ q0 [] = [q0]
scanr f q0 (x:xs) = f x q : qs
where qs@(q:_) = scanr f q0 xs
{-# INLINE [0] strictUncurryScanr #-}
strictUncurryScanr :: (a -> b -> c) -> (a, b) -> c
strictUncurryScanr f pair = case pair of
(x, y) -> f x y
{-# INLINE [0] scanrFB #-}
scanrFB :: (a -> b -> b) -> (b -> c -> c) -> a -> (b, c) -> (b, c)
scanrFB f c = \x (r, est) -> (f x r, r `c` est)
{-# RULES
"scanr" [~1] forall f q0 ls . scanr f q0 ls =
build (\c n -> strictUncurryScanr c (foldr (scanrFB f c) (q0,n) ls))
"scanrList" [1] forall f q0 ls .
strictUncurryScanr (:) (foldr (scanrFB f (:)) (q0,[]) ls) =
scanr f q0 ls
#-}
-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
scanr1 :: (a -> a -> a) -> [a] -> [a]
scanr1 _ [] = []
scanr1 _ [x] = [x]
scanr1 f (x:xs) = f x q : qs
where qs@(q:_) = scanr1 f xs
-- | 'maximum' returns the maximum value from a list,
-- which must be non-empty, finite, and of an ordered type.
-- It is a special case of 'Data.List.maximumBy', which allows the
-- programmer to supply their own comparison function.
maximum :: (Ord a) => [a] -> a
{-# INLINE [1] maximum #-}
maximum [] = errorEmptyList "maximum"
maximum xs = foldl1 max xs
{-# RULES
"maximumInt" maximum = (strictMaximum :: [Int] -> Int);
"maximumInteger" maximum = (strictMaximum :: [Integer] -> Integer)
#-}
-- We can't make the overloaded version of maximum strict without
-- changing its semantics (max might not be strict), but we can for
-- the version specialised to 'Int'.
strictMaximum :: (Ord a) => [a] -> a
strictMaximum [] = errorEmptyList "maximum"
strictMaximum xs = foldl1' max xs
-- | 'minimum' returns the minimum value from a list,
-- which must be non-empty, finite, and of an ordered type.
-- It is a special case of 'Data.List.minimumBy', which allows the
-- programmer to supply their own comparison function.
minimum :: (Ord a) => [a] -> a
{-# INLINE [1] minimum #-}
minimum [] = errorEmptyList "minimum"
minimum xs = foldl1 min xs
{-# RULES
"minimumInt" minimum = (strictMinimum :: [Int] -> Int);
"minimumInteger" minimum = (strictMinimum :: [Integer] -> Integer)
#-}
strictMinimum :: (Ord a) => [a] -> a
strictMinimum [] = errorEmptyList "minimum"
strictMinimum xs = foldl1' min xs
-- | 'iterate' @f x@ returns an infinite list of repeated applications
-- of @f@ to @x@:
--
-- > iterate f x == [x, f x, f (f x), ...]
{-# NOINLINE [1] iterate #-}
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
{-# NOINLINE [0] iterateFB #-}
iterateFB :: (a -> b -> b) -> (a -> a) -> a -> b
iterateFB c f x0 = go x0
where go x = x `c` go (f x)
{-# RULES
"iterate" [~1] forall f x. iterate f x = build (\c _n -> iterateFB c f x)
"iterateFB" [1] iterateFB (:) = iterate
#-}
-- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.
repeat :: a -> [a]
{-# INLINE [0] repeat #-}
-- The pragma just gives the rules more chance to fire
repeat x = xs where xs = x : xs
{-# INLINE [0] repeatFB #-} -- ditto
repeatFB :: (a -> b -> b) -> a -> b
repeatFB c x = xs where xs = x `c` xs
{-# RULES
"repeat" [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
"repeatFB" [1] repeatFB (:) = repeat
#-}
-- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of
-- every element.
-- It is an instance of the more general 'Data.List.genericReplicate',
-- in which @n@ may be of any integral type.
{-# INLINE replicate #-}
replicate :: Int -> a -> [a]
replicate n x = take n (repeat x)
-- | 'cycle' ties a finite list into a circular one, or equivalently,
-- the infinite repetition of the original list. It is the identity
-- on infinite lists.
cycle :: [a] -> [a]
cycle [] = errorEmptyList "cycle"
cycle xs = xs' where xs' = xs ++ xs'
-- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the
-- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@:
--
-- > takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
-- > takeWhile (< 9) [1,2,3] == [1,2,3]
-- > takeWhile (< 0) [1,2,3] == []
--
{-# NOINLINE [1] takeWhile #-}
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile _ [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
{-# INLINE [0] takeWhileFB #-}
takeWhileFB :: (a -> Bool) -> (a -> b -> b) -> b -> a -> b -> b
takeWhileFB p c n = \x r -> if p x then x `c` r else n
-- The takeWhileFB rule is similar to the filterFB rule. It works like this:
-- takeWhileFB q (takeWhileFB p c n) n =
-- \x r -> if q x then (takeWhileFB p c n) x r else n =
-- \x r -> if q x then (\x' r' -> if p x' then x' `c` r' else n) x r else n =
-- \x r -> if q x then (if p x then x `c` r else n) else n =
-- \x r -> if q x && p x then x `c` r else n =
-- takeWhileFB (\x -> q x && p x) c n
{-# RULES
"takeWhile" [~1] forall p xs. takeWhile p xs =
build (\c n -> foldr (takeWhileFB p c n) n xs)
"takeWhileList" [1] forall p. foldr (takeWhileFB p (:) []) [] = takeWhile p
"takeWhileFB" forall c n p q. takeWhileFB q (takeWhileFB p c n) n =
takeWhileFB (\x -> q x && p x) c n
#-}
-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@:
--
-- > dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
-- > dropWhile (< 9) [1,2,3] == []
-- > dropWhile (< 0) [1,2,3] == [1,2,3]
--
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile _ [] = []
dropWhile p xs@(x:xs')
| p x = dropWhile p xs'
| otherwise = xs
-- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@
-- of length @n@, or @xs@ itself if @n > 'length' xs@:
--
-- > take 5 "Hello World!" == "Hello"
-- > take 3 [1,2,3,4,5] == [1,2,3]
-- > take 3 [1,2] == [1,2]
-- > take 3 [] == []
-- > take (-1) [1,2] == []
-- > take 0 [1,2] == []
--
-- It is an instance of the more general 'Data.List.genericTake',
-- in which @n@ may be of any integral type.
take :: Int -> [a] -> [a]
#ifdef USE_REPORT_PRELUDE
take n _ | n <= 0 = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
#else
{- We always want to inline this to take advantage of a known length argument
sign. Note, however, that it's important for the RULES to grab take, rather
than trying to INLINE take immediately and then letting the RULES grab
unsafeTake. Presumably the latter approach doesn't grab it early enough; it led
to an allocation regression in nofib/fft2. -}
{-# INLINE [1] take #-}
take n xs | 0 < n = unsafeTake n xs
| otherwise = []
-- A version of take that takes the whole list if it's given an argument less
-- than 1.
{-# NOINLINE [1] unsafeTake #-}
unsafeTake :: Int -> [a] -> [a]
unsafeTake !_ [] = []
unsafeTake 1 (x: _) = [x]
unsafeTake m (x:xs) = x : unsafeTake (m - 1) xs
{-# RULES
"take" [~1] forall n xs . take n xs =
build (\c nil -> if 0 < n
then foldr (takeFB c nil) (flipSeqTake nil) xs n
else nil)
"unsafeTakeList" [1] forall n xs . foldr (takeFB (:) []) (flipSeqTake []) xs n
= unsafeTake n xs
#-}
{-# INLINE [0] flipSeqTake #-}
-- Just flip seq, specialized to Int, but not inlined too early.
-- It's important to force the numeric argument here, even though
-- it's not used. Otherwise, take n [] doesn't force n. This is
-- bad for strictness analysis and unboxing, and leads to increased
-- allocation in T7257.
flipSeqTake :: a -> Int -> a
flipSeqTake x !_n = x
{-# INLINE [0] takeFB #-}
takeFB :: (a -> b -> b) -> b -> a -> (Int -> b) -> Int -> b
-- The \m accounts for the fact that takeFB is used in a higher-order
-- way by takeFoldr, so it's better to inline. A good example is
-- take n (repeat x)
-- for which we get excellent code... but only if we inline takeFB
-- when given four arguments
takeFB c n x xs
= \ m -> case m of
1 -> x `c` n
_ -> x `c` xs (m - 1)
#endif
-- | 'drop' @n xs@ returns the suffix of @xs@
-- after the first @n@ elements, or @[]@ if @n > 'length' xs@:
--
-- > drop 6 "Hello World!" == "World!"
-- > drop 3 [1,2,3,4,5] == [4,5]
-- > drop 3 [1,2] == []
-- > drop 3 [] == []
-- > drop (-1) [1,2] == [1,2]
-- > drop 0 [1,2] == [1,2]
--
-- It is an instance of the more general 'Data.List.genericDrop',
-- in which @n@ may be of any integral type.
drop :: Int -> [a] -> [a]
#ifdef USE_REPORT_PRELUDE
drop n xs | n <= 0 = xs
drop _ [] = []
drop n (_:xs) = drop (n-1) xs
#else /* hack away */
{-# INLINE drop #-}
drop n ls
| n <= 0 = ls
| otherwise = unsafeDrop n ls
where
-- A version of drop that drops the whole list if given an argument
-- less than 1
unsafeDrop :: Int -> [a] -> [a]
unsafeDrop !_ [] = []
unsafeDrop 1 (_:xs) = xs
unsafeDrop m (_:xs) = unsafeDrop (m - 1) xs
#endif
-- | 'splitAt' @n xs@ returns a tuple where first element is @xs@ prefix of
-- length @n@ and second element is the remainder of the list:
--
-- > splitAt 6 "Hello World!" == ("Hello ","World!")
-- > splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
-- > splitAt 1 [1,2,3] == ([1],[2,3])
-- > splitAt 3 [1,2,3] == ([1,2,3],[])
-- > splitAt 4 [1,2,3] == ([1,2,3],[])
-- > splitAt 0 [1,2,3] == ([],[1,2,3])
-- > splitAt (-1) [1,2,3] == ([],[1,2,3])
--
-- It is equivalent to @('take' n xs, 'drop' n xs)@ when @n@ is not @_|_@
-- (@splitAt _|_ xs = _|_@).
-- 'splitAt' is an instance of the more general 'Data.List.genericSplitAt',
-- in which @n@ may be of any integral type.
splitAt :: Int -> [a] -> ([a],[a])
#ifdef USE_REPORT_PRELUDE
splitAt n xs = (take n xs, drop n xs)
#else
splitAt n ls
| n <= 0 = ([], ls)
| otherwise = splitAt' n ls
where
splitAt' :: Int -> [a] -> ([a], [a])
splitAt' _ [] = ([], [])
splitAt' 1 (x:xs) = ([x], xs)
splitAt' m (x:xs) = (x:xs', xs'')
where
(xs', xs'') = splitAt' (m - 1) xs
#endif /* USE_REPORT_PRELUDE */
-- | 'span', applied to a predicate @p@ and a list @xs@, returns a tuple where
-- first element is longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@ and second element is the remainder of the list:
--
-- > span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
-- > span (< 9) [1,2,3] == ([1,2,3],[])
-- > span (< 0) [1,2,3] == ([],[1,2,3])
--
-- 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
span :: (a -> Bool) -> [a] -> ([a],[a])
span _ xs@[] = (xs, xs)
span p xs@(x:xs')
| p x = let (ys,zs) = span p xs' in (x:ys,zs)
| otherwise = ([],xs)
-- | 'break', applied to a predicate @p@ and a list @xs@, returns a tuple where
-- first element is longest prefix (possibly empty) of @xs@ of elements that
-- /do not satisfy/ @p@ and second element is the remainder of the list:
--
-- > break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
-- > break (< 9) [1,2,3] == ([],[1,2,3])
-- > break (> 9) [1,2,3] == ([1,2,3],[])
--
-- 'break' @p@ is equivalent to @'span' ('not' . p)@.
break :: (a -> Bool) -> [a] -> ([a],[a])
#ifdef USE_REPORT_PRELUDE
break p = span (not . p)
#else
-- HBC version (stolen)
break _ xs@[] = (xs, xs)
break p xs@(x:xs')
| p x = ([],xs)
| otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
#endif
-- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.
-- @xs@ must be finite.
reverse :: [a] -> [a]
#ifdef USE_REPORT_PRELUDE
reverse = foldl (flip (:)) []
#else
reverse l = rev l []
where
rev [] a = a
rev (x:xs) a = rev xs (x:a)
#endif
-- | 'and' returns the conjunction of a Boolean list. For the result to be
-- 'True', the list must be finite; 'False', however, results from a 'False'
-- value at a finite index of a finite or infinite list.
and :: [Bool] -> Bool
#ifdef USE_REPORT_PRELUDE
and = foldr (&&) True
#else
and [] = True
and (x:xs) = x && and xs
{-# NOINLINE [1] and #-}
{-# RULES
"and/build" forall (g::forall b.(Bool->b->b)->b->b) .
and (build g) = g (&&) True
#-}
#endif
-- | 'or' returns the disjunction of a Boolean list. For the result to be
-- 'False', the list must be finite; 'True', however, results from a 'True'
-- value at a finite index of a finite or infinite list.
or :: [Bool] -> Bool
#ifdef USE_REPORT_PRELUDE
or = foldr (||) False
#else
or [] = False
or (x:xs) = x || or xs
{-# NOINLINE [1] or #-}
{-# RULES
"or/build" forall (g::forall b.(Bool->b->b)->b->b) .
or (build g) = g (||) False
#-}
#endif
-- | Applied to a predicate and a list, 'any' determines if any element
-- of the list satisfies the predicate. For the result to be
-- 'False', the list must be finite; 'True', however, results from a 'True'
-- value for the predicate applied to an element at a finite index of a finite or infinite list.
any :: (a -> Bool) -> [a] -> Bool
#ifdef USE_REPORT_PRELUDE
any p = or . map p
#else
any _ [] = False
any p (x:xs) = p x || any p xs
{-# NOINLINE [1] any #-}
{-# RULES
"any/build" forall p (g::forall b.(a->b->b)->b->b) .
any p (build g) = g ((||) . p) False
#-}
#endif
-- | Applied to a predicate and a list, 'all' determines if all elements
-- of the list satisfy the predicate. For the result to be
-- 'True', the list must be finite; 'False', however, results from a 'False'
-- value for the predicate applied to an element at a finite index of a finite or infinite list.
all :: (a -> Bool) -> [a] -> Bool
#ifdef USE_REPORT_PRELUDE
all p = and . map p
#else
all _ [] = True
all p (x:xs) = p x && all p xs
{-# NOINLINE [1] all #-}
{-# RULES
"all/build" forall p (g::forall b.(a->b->b)->b->b) .
all p (build g) = g ((&&) . p) True
#-}
#endif
-- | 'elem' is the list membership predicate, usually written in infix form,
-- e.g., @x \`elem\` xs@. For the result to be
-- 'False', the list must be finite; 'True', however, results from an element
-- equal to @x@ found at a finite index of a finite or infinite list.
elem :: (Eq a) => a -> [a] -> Bool
#ifdef USE_REPORT_PRELUDE
elem x = any (== x)
#else
elem _ [] = False
elem x (y:ys) = x==y || elem x ys
{-# NOINLINE [1] elem #-}
{-# RULES
"elem/build" forall x (g :: forall b . Eq a => (a -> b -> b) -> b -> b)
. elem x (build g) = g (\ y r -> (x == y) || r) False
#-}
#endif
-- | 'notElem' is the negation of 'elem'.
notElem :: (Eq a) => a -> [a] -> Bool
#ifdef USE_REPORT_PRELUDE
notElem x = all (/= x)
#else
notElem _ [] = True
notElem x (y:ys)= x /= y && notElem x ys
{-# NOINLINE [1] notElem #-}
{-# RULES
"notElem/build" forall x (g :: forall b . Eq a => (a -> b -> b) -> b -> b)
. notElem x (build g) = g (\ y r -> (x /= y) && r) True
#-}
#endif
-- | 'lookup' @key assocs@ looks up a key in an association list.
lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
lookup _key [] = Nothing
lookup key ((x,y):xys)
| key == x = Just y
| otherwise = lookup key xys
-- | Map a function over a list and concatenate the results.
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = foldr ((++) . f) []
{-# NOINLINE [1] concatMap #-}
{-# RULES
"concatMap" forall f xs . concatMap f xs =
build (\c n -> foldr (\x b -> foldr c b (f x)) n xs)
#-}
-- | Concatenate a list of lists.
concat :: [[a]] -> [a]
concat = foldr (++) []
{-# NOINLINE [1] concat #-}
{-# RULES
"concat" forall xs. concat xs =
build (\c n -> foldr (\x y -> foldr c y x) n xs)
-- We don't bother to turn non-fusible applications of concat back into concat
#-}
-- | List index (subscript) operator, starting from 0.
-- It is an instance of the more general 'Data.List.genericIndex',
-- which takes an index of any integral type.
(!!) :: [a] -> Int -> a
#ifdef USE_REPORT_PRELUDE
xs !! n | n < 0 = error "Prelude.!!: negative index"
[] !! _ = error "Prelude.!!: index too large"
(x:_) !! 0 = x
(_:xs) !! n = xs !! (n-1)
#else
-- We don't really want the errors to inline with (!!).
-- We may want to fuss around a bit with NOINLINE, and
-- if so we should be careful not to trip up known-bottom
-- optimizations.
tooLarge :: Int -> a
tooLarge _ = error (prel_list_str ++ "!!: index too large")
negIndex :: a
negIndex = error $ prel_list_str ++ "!!: negative index"
{-# INLINABLE (!!) #-}
xs !! n
| n < 0 = negIndex
| otherwise = foldr (\x r k -> case k of
0 -> x
_ -> r (k-1)) tooLarge xs n
#endif
--------------------------------------------------------------
-- The zip family
--------------------------------------------------------------
foldr2 :: (a -> b -> c -> c) -> c -> [a] -> [b] -> c
foldr2 k z = go
where
go [] !_ys = z -- see #9495 for the !
go _xs [] = z
go (x:xs) (y:ys) = k x y (go xs ys)
{-# INLINE [0] foldr2 #-}
foldr2_left :: (a -> b -> c -> d) -> d -> a -> ([b] -> c) -> [b] -> d
foldr2_left _k z _x _r [] = z
foldr2_left k _z x r (y:ys) = k x y (r ys)
foldr2_right :: (a -> b -> c -> d) -> d -> b -> ([a] -> c) -> [a] -> d
foldr2_right _k z _y _r [] = z
foldr2_right k _z y r (x:xs) = k x y (r xs)
-- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
-- foldr2 k z xs ys = foldr (foldr2_right k z) (\_ -> z) ys xs
{-# RULES
"foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
"foldr2/right" forall k z xs (g::forall b.(a->b->b)->b->b) .
foldr2 k z xs (build g) = g (foldr2_right k z) (\_ -> z) xs
#-}
-- Zips for larger tuples are in the List module.
----------------------------------------------
-- | 'zip' takes two lists and returns a list of corresponding pairs.
-- If one input list is short, excess elements of the longer list are
-- discarded.
--
-- NOTE: GHC's implementation of @zip@ deviates slightly from the
-- standard. In particular, Haskell 98 and Haskell 2010 require that
-- @zip [x1,x2,...,xn] (y1:y2:...:yn:_|_) = [(x1,y1),(x2,y2),...,(xn,yn)]@
-- In GHC, however,
-- @zip [x1,x2,...,xn] (y1:y2:...:yn:_|_) = (x1,y1):(x2,y2):...:(xn,yn):_|_@
-- That is, you cannot use termination of the left list to avoid hitting
-- bottom in the right list.
-- This deviation is necessary to make fusion with 'build' in the right
-- list preserve semantics.
{-# NOINLINE [1] zip #-}
zip :: [a] -> [b] -> [(a,b)]
zip [] !_bs = [] -- see #9495 for the !
zip _as [] = []
zip (a:as) (b:bs) = (a,b) : zip as bs
{-# INLINE [0] zipFB #-}
zipFB :: ((a, b) -> c -> d) -> a -> b -> c -> d
zipFB c = \x y r -> (x,y) `c` r
{-# RULES
"zip" [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
"zipList" [1] foldr2 (zipFB (:)) [] = zip
#-}
----------------------------------------------
-- | 'zip3' takes three lists and returns a list of triples, analogous to
-- 'zip'.
zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
-- Specification
-- zip3 = zipWith3 (,,)
zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
zip3 _ _ _ = []
-- The zipWith family generalises the zip family by zipping with the
-- function given as the first argument, instead of a tupling function.
----------------------------------------------
-- | 'zipWith' generalises 'zip' by zipping with the function given
-- as the first argument, instead of a tupling function.
-- For example, @'zipWith' (+)@ is applied to two lists to produce the
-- list of corresponding sums.
--
-- NOTE: GHC's implementation of @zipWith@ deviates slightly from the
-- standard. In particular, Haskell 98 and Haskell 2010 require that
-- @zipWith (,) [x1,x2,...,xn] (y1:y2:...:yn:_|_) = [(x1,y1),(x2,y2),...,(xn,yn)]@
-- In GHC, however,
-- @zipWith (,) [x1,x2,...,xn] (y1:y2:...:yn:_|_) = (x1,y1):(x2,y2):...:(xn,yn):_|_@
-- That is, you cannot use termination of the left list to avoid hitting
-- bottom in the right list.
-- This deviation is necessary to make fusion with 'build' in the right
-- list preserve semantics.
{-# NOINLINE [1] zipWith #-}
zipWith :: (a->b->c) -> [a]->[b]->[c]
zipWith _f [] !_bs = [] -- see #9495 for the !
zipWith _f _as [] = []
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
-- zipWithFB must have arity 2 since it gets two arguments in the "zipWith"
-- rule; it might not get inlined otherwise
{-# INLINE [0] zipWithFB #-}
zipWithFB :: (a -> b -> c) -> (d -> e -> a) -> d -> e -> b -> c
zipWithFB c f = \x y r -> (x `f` y) `c` r
{-# RULES
"zipWith" [~1] forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
"zipWithList" [1] forall f. foldr2 (zipWithFB (:) f) [] = zipWith f
#-}
-- | The 'zipWith3' function takes a function which combines three
-- elements, as well as three lists and returns a list of their point-wise
-- combination, analogous to 'zipWith'.
zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith3 z (a:as) (b:bs) (c:cs)
= z a b c : zipWith3 z as bs cs
zipWith3 _ _ _ _ = []
-- | 'unzip' transforms a list of pairs into a list of first components
-- and a list of second components.
unzip :: [(a,b)] -> ([a],[b])
{-# INLINE unzip #-}
unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
-- | The 'unzip3' function takes a list of triples and returns three
-- lists, analogous to 'unzip'.
unzip3 :: [(a,b,c)] -> ([a],[b],[c])
{-# INLINE unzip3 #-}
unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
([],[],[])
--------------------------------------------------------------
-- Error code
--------------------------------------------------------------
-- Common up near identical calls to `error' to reduce the number
-- constant strings created when compiled:
errorEmptyList :: String -> a
errorEmptyList fun =
error (prel_list_str ++ fun ++ ": empty list")
prel_list_str :: String
prel_list_str = "Prelude."
| jstolarek/ghc | libraries/base/GHC/List.hs | bsd-3-clause | 35,165 | 0 | 14 | 9,782 | 5,542 | 3,170 | 2,372 | 412 | 3 |
{-# LANGUAGE FunctionalDependencies, UndecidableInstances #-}
module Data.Array.Repa.Operators.Mapping
( -- * Generic maps
map, mapLTS, zipWithLTS
, zipWith
, (+^), (-^), (*^), (/^)
-- * Structured maps
, Structured(..))
where
import Data.Array.Repa.Shape
import Data.Array.Repa.Base
import Data.Array.Repa.Repr.ByteString
import Data.Array.Repa.Repr.Cursored
import Data.Array.Repa.Repr.Delayed
import Data.Array.Repa.Repr.ForeignPtr
import Data.Array.Repa.Repr.HintSmall
import Data.Array.Repa.Repr.HintInterleave
import Data.Array.Repa.Repr.Partitioned
import Data.Array.Repa.Repr.Unboxed
import Data.Array.Repa.Repr.Undefined
import Prelude hiding (map, zipWith)
import Foreign.Storable
import Data.Word
import Data.Array.Repa.Repr.LazyTreeSplitting
import qualified Data.Rope as RP
import Control.Monad.Par
mapLTS :: (Shape sh, Source L a) => (a -> b) -> Array L sh a -> Array L sh b
mapLTS f rope = fromRope (extent rope) (runPar $ RP.mapLTS f (toRope rope))
zipWithLTS :: (Shape sh, Source L a, Source L b) => (a -> b -> c) -> Array L sh a -> Array L sh b -> Array L sh c
zipWithLTS f rp1 rp2 = fromRope (extent rp1) $ runPar $ RP.zipWithLTS f (toRope rp1) (toRope rp2)
-- | Apply a worker function to each element of an array,
-- yielding a new array with the same extent.
--
map :: (Shape sh, Source r a)
=> (a -> b) -> Array r sh a -> Array D sh b
map f arr
= case delay arr of
ADelayed sh g -> ADelayed sh (f . g)
{-# INLINE [3] map #-}
-- ZipWith --------------------------------------------------------------------
-- | Combine two arrays, element-wise, with a binary operator.
-- If the extent of the two array arguments differ,
-- then the resulting array's extent is their intersection.
--
zipWith :: (Shape sh, Source r1 a, Source r2 b)
=> (a -> b -> c)
-> Array r1 sh a -> Array r2 sh b
-> Array D sh c
zipWith f arr1 arr2
= let get ix = f (arr1 `unsafeIndex` ix) (arr2 `unsafeIndex` ix)
{-# INLINE get #-}
in fromFunction
(intersectDim (extent arr1) (extent arr2))
get
{-# INLINE [2] zipWith #-}
(+^) = zipWith (+)
{-# INLINE (+^) #-}
(-^) = zipWith (-)
{-# INLINE (-^) #-}
(*^) = zipWith (*)
{-# INLINE (*^) #-}
(/^) = zipWith (/)
{-# INLINE (/^) #-}
-- Structured -------------------------------------------------------------------
-- | Structured versions of @map@ and @zipWith@ that preserve the representation
-- of cursored and partitioned arrays.
--
-- For cursored (@C@) arrays, the cursoring of the source array is preserved.
--
-- For partitioned (@P@) arrays, the worker function is fused with each array
-- partition separately, instead of treating the whole array as a single
-- bulk object.
--
-- Preserving the cursored and\/or paritioned representation of an array
-- is will make follow-on computation more efficient than if the array was
-- converted to a vanilla Delayed (@D@) array as with plain `map` and `zipWith`.
--
-- If the source array is not cursored or partitioned then `smap` and
-- `szipWith` are identical to the plain functions.
--
class Structured r1 a b where
-- | The target result representation.
type TR r1
-- | Structured @map@.
smap :: Shape sh
=> (a -> b)
-> Array r1 sh a
-> Array (TR r1) sh b
-- | Structured @zipWith@.
-- If you have a cursored or partitioned source array then use that as
-- the third argument (corresponding to @r1@ here)
szipWith
:: (Shape sh, Source r c)
=> (c -> a -> b)
-> Array r sh c
-> Array r1 sh a
-> Array (TR r1) sh b
-- ByteString -------------------------
instance Structured B Word8 b where
type TR B = D
smap = map
szipWith = zipWith
-- Cursored ---------------------------
instance Structured C a b where
type TR C = C
smap f (ACursored sh makec shiftc loadc)
= ACursored sh makec shiftc (f . loadc)
{-# INLINE [3] smap #-}
szipWith f arr1 (ACursored sh makec shiftc loadc)
= let makec' ix = (ix, makec ix)
{-# INLINE makec' #-}
shiftc' off (ix, cur) = (addDim off ix, shiftc off cur)
{-# INLINE shiftc' #-}
load' (ix, cur) = f (arr1 `unsafeIndex` ix) (loadc cur)
{-# INLINE load' #-}
in ACursored
(intersectDim (extent arr1) sh)
makec' shiftc' load'
{-# INLINE [2] szipWith #-}
-- Delayed ----------------------------
instance Structured D a b where
type TR D = D
smap = map
szipWith = zipWith
-- ForeignPtr -------------------------
instance Storable a => Structured F a b where
type TR F = D
smap = map
szipWith = zipWith
-- Partitioned ------------------------
instance (Structured r1 a b
, Structured r2 a b)
=> Structured (P r1 r2) a b where
type TR (P r1 r2) = P (TR r1) (TR r2)
smap f (APart sh range arr1 arr2)
= APart sh range (smap f arr1) (smap f arr2)
{-# INLINE [3] smap #-}
szipWith f arr1 (APart sh range arr21 arr22)
= APart sh range (szipWith f arr1 arr21)
(szipWith f arr1 arr22)
{-# INLINE [2] szipWith #-}
-- Small ------------------------------
instance Structured r1 a b
=> Structured (S r1) a b where
type TR (S r1) = S (TR r1)
smap f (ASmall arr1)
= ASmall (smap f arr1)
{-# INLINE [3] smap #-}
szipWith f arr1 (ASmall arr2)
= ASmall (szipWith f arr1 arr2)
{-# INLINE [3] szipWith #-}
-- Interleaved ------------------------
instance Structured r1 a b
=> Structured (I r1) a b where
type TR (I r1) = I (TR r1)
smap f (AInterleave arr1)
= AInterleave (smap f arr1)
{-# INLINE [3] smap #-}
szipWith f arr1 (AInterleave arr2)
= AInterleave (szipWith f arr1 arr2)
{-# INLINE [3] szipWith #-}
-- Unboxed ----------------------------
instance Unbox a => Structured U a b where
type TR U = D
smap = map
szipWith = zipWith
-- Undefined --------------------------
instance Structured X a b where
type TR X = X
smap _ (AUndefined sh) = AUndefined sh
szipWith _ _ (AUndefined sh) = AUndefined sh
| kairne/repa-lts | Data/Array/Repa/Operators/Mapping.hs | bsd-3-clause | 6,264 | 8 | 13 | 1,616 | 1,680 | 922 | 758 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Database.PostgreSQL.Simple.Streams.LargeObjects
-- Copyright : (c) 2013-2014 Leon P Smith
-- License : BSD3
--
-- Maintainer : leon@melding-monads.com
-- Stability : experimental
--
--
-- An io-stream based interface to importing and export large objects.
--
-- Note that these functions and the streams they create must be
-- used inside a single transaction, and it is up to you to manage
-- that transaction.
--
-- You may interleave the use of these streams with other commands
-- on the same connection.
--
-----------------------------------------------------------------------------
{-# LANGUAGE BangPatterns #-}
module Database.PostgreSQL.Simple.Streams.LargeObjects
( loImport
, loImportWithOid
, loExport
, loReadStream
, loWriteStream
) where
import Data.ByteString(ByteString)
import qualified Data.ByteString as BS
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as Streams
import qualified Database.PostgreSQL.Simple as DB
import qualified Database.PostgreSQL.Simple.LargeObjects as DB
bUFSIZE :: Int
bUFSIZE = 4096
loExport :: DB.Connection -> DB.Oid -> IO (InputStream ByteString)
loExport conn oid = do
lofd <- DB.loOpen conn oid DB.ReadMode
loReadStream conn lofd bUFSIZE
loImport :: DB.Connection -> IO (DB.Oid, OutputStream ByteString)
loImport conn = do
oid <- DB.loCreat conn
sOut <- loImportWithOid conn oid
return (oid, sOut)
loImportWithOid :: DB.Connection -> DB.Oid -> IO (OutputStream ByteString)
loImportWithOid conn oid = do
lofd <- DB.loOpen conn oid DB.WriteMode
loWriteStream conn lofd
-- | @'loReadStream' conn lofd bufferSize@ returns an 'InputStream' that
-- reads chunks of size @bufferSize@ from the large object descriptor.
--
-- This stream may only be used in the context of a single explicit
-- transaction block.
loReadStream :: DB.Connection -> DB.LoFd -> Int -> IO (InputStream ByteString)
loReadStream conn lofd bufSize = do
Streams.makeInputStream $ do
x <- DB.loRead conn lofd bufSize
return $! if BS.null x then Nothing else Just x
-- | @'loWriteStream' conn lofd@ returns an 'OutputStream' that
-- writes bytestrings to the large object descriptor.
loWriteStream :: DB.Connection -> DB.LoFd -> IO (OutputStream ByteString)
loWriteStream conn lofd = do
Streams.makeOutputStream $ maybe (return ()) write
where
write !bs = do
n <- DB.loWrite conn lofd bs
if BS.length bs < n
then write (BS.drop n bs)
else return ()
| lpsmith/postgresql-simple-streams | src/Database/PostgreSQL/Simple/Streams/LargeObjects.hs | bsd-3-clause | 2,685 | 0 | 13 | 534 | 532 | 288 | 244 | 41 | 2 |
module Test.Unification where
import Test.Tasty
import Test.Tasty.HUnit
import Types.Constant
import Types.EType
import Types.Expr
import Unification
unificationSpec :: TestTree
unificationSpec = testGroup "Type unification"
[ testCase "constants" $
let lit = literal (I 12)
in testInference lit (Right $ Forall [] (Ty "int"))
, testCase "identity" $
let a = TV 0
t = TyVar a
in testInference (lam "x" (var "x")) (Right $ Forall [a] (t :-> t))
, testCase "higher-order functions" $
let a = TyVar $ TV 0
b = TyVar $ TV 1
expr = lam "x" $ lam "y" $ call (var "y") (var "x")
ty = a :-> (a :-> b) :-> b
in testInference expr (Right $ Forall [TV 0, TV 1] ty)
, testCase "infinite types" $
let expr = lam "x" $ call (var "x") (var "x")
a = TV 0
b = TV 1
in testInference expr (Left (InfiniteType a (TyVar a :-> TyVar b)))
, testCase "unbound variables" $
testInference (var "x") (Left (Unbound "x"))
]
testInference :: Expr -> Either TypeError Scheme -> Assertion
testInference expr expected = typeOf expr @?= expected
| letsbreelhere/egg | test/Test/Unification.hs | bsd-3-clause | 1,550 | 0 | 17 | 720 | 464 | 230 | 234 | 31 | 1 |
{-# LANGUAGE TemplateHaskell, RecordWildCards, NamedFieldPuns, PatternGuards, FlexibleContexts #-}
module Data.TrieMap.Representation.TH.Representation (
Representation(..),
Case(..),
fstRepr,
sndRepr,
prodRepr,
sumRepr,
unifyProdRepr,
unifySumRepr,
checkEnumRepr,
unitRepr,
vectorizeRepr,
mapReprInput,
conify,
ordRepr,
outputRepr,
recursiveRepr,
keyRepr) where
import Control.Exception (assert)
import Control.Monad
import Control.Monad.ST
import Data.Word
import Data.Maybe
import qualified Data.Vector as V
import Data.Vector.Fusion.Stream (MStream)
import Language.Haskell.TH.Syntax
import Data.TrieMap.Modifiers
import Data.TrieMap.Representation.Class
import Data.TrieMap.Representation.TH.Utils
import Data.TrieMap.Representation.TH.ReprMonad
data Representation = Repr {reprType :: Type, cases :: [Case]} deriving (Show)
data Case = Case {input :: [Pat], output :: Exp} deriving (Show)
unitRepr :: Representation
unitRepr = Repr {reprType = TupleT 0, cases = [Case [] (TupE [])]}
vectorizeRepr :: Quasi m => Exp -> Representation -> m Representation
vectorizeRepr toVecE Repr{..} = do
xs <- qNewName "xs"
eToR <- qNewName "eToR"
let mapE f xs = VarE 'V.map `AppE` f `AppE` xs
let eToRDec = FunD eToR (map caseToClause cases)
return $ Repr {
reprType = ConT ''V.Vector `AppT` reprType,
cases = [Case {input = [VarP xs],
output = mapE (LetE [eToRDec] (VarE eToR)) (toVecE `AppE` VarE xs)}]}
fstRepr, sndRepr :: Representation -> Representation
fstRepr = mapReprOutput fstTy fstExp
sndRepr = mapReprOutput sndTy sndExp
prodCase :: Case -> Case -> Case
prodCase Case{input = input1, output = output1} Case{input = input2, output = output2}
= Case {input = input1 ++ input2, output = TupE [output1, output2]}
unifyProdCase :: Case -> Case -> Maybe Case
unifyProdCase Case{input = input1, output = output1} Case{input = input2, output = output2}
= do guard (input1 == input2)
return Case{input = input1, output = TupE [output1, output2]}
mapCaseInput :: ([Pat] -> Pat) -> Case -> Case
mapCaseInput f Case{..} = Case{input = [f input],..}
mapCaseOutput :: (Exp -> Exp) -> Case -> Case
mapCaseOutput f Case{..} = Case{output = f output,..}
prodRepr, sumRepr, unifySumRepr, unifyProdRepr :: Representation -> Representation -> Representation
prodRepr Repr{reprType = repr1, cases = cases1} Repr{reprType = repr2, cases = cases2}
= Repr {reprType = repr1 `tyProd` repr2, cases = liftM2 prodCase cases1 cases2}
sumRepr Repr{reprType = repr1, cases = cases1} Repr{reprType = repr2, cases = cases2}
= Repr {reprType = repr1 `tySum` repr2,
cases = map (mapCaseOutput leftExp) cases1 ++ map (mapCaseOutput rightExp) cases2}
unifySumRepr Repr{reprType = repr1, cases = cases1} Repr{reprType = repr2, cases = cases2}
= assert (repr1 == repr2) $ Repr {reprType = repr1, cases = cases1 ++ cases2}
unifyProdRepr Repr{reprType = repr1, cases = cases1} Repr{reprType = repr2, cases = cases2}
= Repr {reprType = repr1 `tyProd` repr2, cases = catMaybes (liftM2 unifyProdCase cases1 cases2)}
mapReprInput :: ([Pat] -> Pat) -> Representation -> Representation
mapReprInput f Repr{..} = Repr{cases = map (mapCaseInput f) cases, ..}
conify :: Name -> Representation -> Representation
conify con = mapReprInput (ConP con)
mapReprOutput :: (Type -> Type) -> (Exp -> Exp) -> Representation -> Representation
mapReprOutput tyOp outOp Repr{..} = Repr{reprType = tyOp reprType, cases = map (mapCaseOutput outOp) cases}
checkEnumRepr :: Representation -> Representation
checkEnumRepr Repr{..}
| isEnumTy reprType, length cases > 2
= Repr {reprType = ConT ''Word, cases = [Case{input, output = LitE (IntegerL i)} | (i, Case{..}) <- zip [0..] cases]}
checkEnumRepr repr = repr
ordRepr :: Quasi m => Type -> m Representation
ordRepr ty = do
x <- qNewName "ordK"
return Repr{reprType = ConT ''Ordered `AppT` ty,
cases = [Case {input = [VarP x], output = ConE 'Ord `AppE` VarE x}]}
caseToClause :: Case -> Clause
caseToClause Case{..} = Clause input (NormalB output) []
{-# INLINE toRepStreamImpl #-}
toRepStreamImpl :: (Repr a, Repr (Rep a)) => MStream (ST s) a -> ST s (RepStream (Rep a))
toRepStreamImpl = toRepStreamM . fmap toRep
outputRepr :: Cxt -> Type -> Representation -> ReprMonad Type
outputRepr cxt ty Repr{..} = do
forceDef <- forceDefaultListRep
let listReps = if forceDef then
[TySynInstD ''RepStream [ty] (ConT ''DRepStream `AppT` ty),
ValD (VarP 'toRepStreamM) (NormalB (VarE 'dToRepStreamM)) []]
else [TySynInstD ''RepStream [ty] (ConT ''RepStream `AppT` reprType),
ValD (VarP 'toRepStreamM) (NormalB (VarE 'toRepStreamImpl)) []]
outputInstance ty reprType
[InstanceD cxt (ConT ''Repr `AppT` ty)
([TySynInstD ''Rep [ty] reprType,
FunD 'toRep
(map caseToClause cases)] ++ listReps)]
return reprType
recursiveRepr :: Quasi m => Type -> Exp -> m Representation
recursiveRepr reprType toRepE = do
deep <- qNewName "deep"
return Repr{reprType, cases = [Case{input = [VarP deep], output = toRepE `AppE` VarE deep}]}
keyRepr :: Quasi m => Type -> m Representation
keyRepr ty = do
shallow <- qNewName "shallow"
let keyCon = ConE 'Key
return Repr{reprType = ConT ''Key `AppT` ty, cases = [Case{input = [VarP shallow], output = keyCon `AppE` VarE shallow}]} | lowasser/TrieMap | Data/TrieMap/Representation/TH/Representation.hs | bsd-3-clause | 5,274 | 28 | 17 | 877 | 2,099 | 1,153 | 946 | 113 | 2 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[RnSource]{Main pass of renamer}
-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module RnSource (
rnSrcDecls, addTcgDUs, findSplice
) where
#include "HsVersions.h"
import {-# SOURCE #-} RnExpr( rnLExpr )
import {-# SOURCE #-} RnSplice ( rnSpliceDecl, rnTopSpliceDecls )
import HsSyn
import FieldLabel
import RdrName
import RnTypes
import RnBinds
import RnEnv
import RnNames
import RnHsDoc ( rnHsDoc, rnMbLHsDoc )
import TcAnnotations ( annCtxt )
import TcRnMonad
import ForeignCall ( CCallTarget(..) )
import Module
import HscTypes ( Warnings(..), plusWarns )
import Class ( FunDep )
import PrelNames ( applicativeClassName, pureAName, thenAName
, monadClassName, returnMName, thenMName
, monadFailClassName, failMName, failMName_preMFP
, semigroupClassName, sappendName
, monoidClassName, mappendName
)
import Name
import NameSet
import NameEnv
import Avail
import Outputable
import Bag
import BasicTypes ( RuleName, pprRuleName )
import FastString
import SrcLoc
import DynFlags
import HscTypes ( HscEnv, hsc_dflags )
import ListSetOps ( findDupsEq, removeDups, equivClasses )
import Digraph ( SCC, flattenSCC, stronglyConnCompFromEdgedVertices )
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import Control.Arrow ( first )
import Data.List ( sortBy )
import Maybes( orElse, mapMaybe )
import qualified Data.Set as Set ( difference, fromList, toList, null )
#if __GLASGOW_HASKELL__ < 709
import Data.Traversable (traverse)
#endif
{-
@rnSourceDecl@ `renames' declarations.
It simultaneously performs dependency analysis and precedence parsing.
It also does the following error checks:
\begin{enumerate}
\item
Checks that tyvars are used properly. This includes checking
for undefined tyvars, and tyvars in contexts that are ambiguous.
(Some of this checking has now been moved to module @TcMonoType@,
since we don't have functional dependency information at this point.)
\item
Checks that all variable occurrences are defined.
\item
Checks the @(..)@ etc constraints in the export list.
\end{enumerate}
-}
-- Brings the binders of the group into scope in the appropriate places;
-- does NOT assume that anything is in scope already
rnSrcDecls :: HsGroup RdrName -> RnM (TcGblEnv, HsGroup Name)
-- Rename a top-level HsGroup; used for normal source files *and* hs-boot files
rnSrcDecls group@(HsGroup { hs_valds = val_decls,
hs_splcds = splice_decls,
hs_tyclds = tycl_decls,
hs_instds = inst_decls,
hs_derivds = deriv_decls,
hs_fixds = fix_decls,
hs_warnds = warn_decls,
hs_annds = ann_decls,
hs_fords = foreign_decls,
hs_defds = default_decls,
hs_ruleds = rule_decls,
hs_vects = vect_decls,
hs_docs = docs })
= do {
-- (A) Process the fixity declarations, creating a mapping from
-- FastStrings to FixItems.
-- Also checks for duplicates.
local_fix_env <- makeMiniFixityEnv fix_decls ;
-- (B) Bring top level binders (and their fixities) into scope,
-- *except* for the value bindings, which get done in step (D)
-- with collectHsIdBinders. However *do* include
--
-- * Class ops, data constructors, and record fields,
-- because they do not have value declarations.
-- Aso step (C) depends on datacons and record fields
--
-- * For hs-boot files, include the value signatures
-- Again, they have no value declarations
--
(tc_envs, tc_bndrs) <- getLocalNonValBinders local_fix_env group ;
setEnvs tc_envs $ do {
failIfErrsM ; -- No point in continuing if (say) we have duplicate declarations
-- (D1) Bring pattern synonyms into scope.
-- Need to do this before (D2) because rnTopBindsLHS
-- looks up those pattern synonyms (Trac #9889)
extendPatSynEnv val_decls local_fix_env $ \pat_syn_bndrs -> do {
-- (D2) Rename the left-hand sides of the value bindings.
-- This depends on everything from (B) being in scope,
-- and on (C) for resolving record wild cards.
-- It uses the fixity env from (A) to bind fixities for view patterns.
new_lhs <- rnTopBindsLHS local_fix_env val_decls ;
-- Bind the LHSes (and their fixities) in the global rdr environment
let { id_bndrs = collectHsIdBinders new_lhs } ; -- Excludes pattern-synonym binders
-- They are already in scope
traceRn (text "rnSrcDecls" <+> ppr id_bndrs) ;
tc_envs <- extendGlobalRdrEnvRn (map avail id_bndrs) local_fix_env ;
traceRn (text "D2" <+> ppr (tcg_rdr_env (fst tc_envs)));
setEnvs tc_envs $ do {
-- Now everything is in scope, as the remaining renaming assumes.
-- (E) Rename type and class decls
-- (note that value LHSes need to be in scope for default methods)
--
-- You might think that we could build proper def/use information
-- for type and class declarations, but they can be involved
-- in mutual recursion across modules, and we only do the SCC
-- analysis for them in the type checker.
-- So we content ourselves with gathering uses only; that
-- means we'll only report a declaration as unused if it isn't
-- mentioned at all. Ah well.
traceRn (text "Start rnTyClDecls") ;
(rn_tycl_decls, src_fvs1) <- rnTyClDecls tycl_decls ;
-- (F) Rename Value declarations right-hand sides
traceRn (text "Start rnmono") ;
let { val_bndr_set = mkNameSet id_bndrs `unionNameSet` mkNameSet pat_syn_bndrs } ;
is_boot <- tcIsHsBootOrSig ;
(rn_val_decls, bind_dus) <- if is_boot
-- For an hs-boot, use tc_bndrs (which collects how we're renamed
-- signatures), since val_bndr_set is empty (there are no x = ...
-- bindings in an hs-boot.)
then rnTopBindsBoot tc_bndrs new_lhs
else rnValBindsRHS (TopSigCtxt val_bndr_set) new_lhs ;
traceRn (text "finish rnmono" <+> ppr rn_val_decls) ;
-- (G) Rename Fixity and deprecations
-- Rename fixity declarations and error if we try to
-- fix something from another module (duplicates were checked in (A))
let { all_bndrs = tc_bndrs `unionNameSet` val_bndr_set } ;
rn_fix_decls <- rnSrcFixityDecls all_bndrs fix_decls ;
-- Rename deprec decls;
-- check for duplicates and ensure that deprecated things are defined locally
-- at the moment, we don't keep these around past renaming
rn_warns <- rnSrcWarnDecls all_bndrs warn_decls ;
-- (H) Rename Everything else
(rn_inst_decls, src_fvs2) <- rnList rnSrcInstDecl inst_decls ;
(rn_rule_decls, src_fvs3) <- setXOptM LangExt.ScopedTypeVariables $
rnList rnHsRuleDecls rule_decls ;
-- Inside RULES, scoped type variables are on
(rn_vect_decls, src_fvs4) <- rnList rnHsVectDecl vect_decls ;
(rn_foreign_decls, src_fvs5) <- rnList rnHsForeignDecl foreign_decls ;
(rn_ann_decls, src_fvs6) <- rnList rnAnnDecl ann_decls ;
(rn_default_decls, src_fvs7) <- rnList rnDefaultDecl default_decls ;
(rn_deriv_decls, src_fvs8) <- rnList rnSrcDerivDecl deriv_decls ;
(rn_splice_decls, src_fvs9) <- rnList rnSpliceDecl splice_decls ;
-- Haddock docs; no free vars
rn_docs <- mapM (wrapLocM rnDocDecl) docs ;
last_tcg_env <- getGblEnv ;
-- (I) Compute the results and return
let {rn_group = HsGroup { hs_valds = rn_val_decls,
hs_splcds = rn_splice_decls,
hs_tyclds = rn_tycl_decls,
hs_instds = rn_inst_decls,
hs_derivds = rn_deriv_decls,
hs_fixds = rn_fix_decls,
hs_warnds = [], -- warns are returned in the tcg_env
-- (see below) not in the HsGroup
hs_fords = rn_foreign_decls,
hs_annds = rn_ann_decls,
hs_defds = rn_default_decls,
hs_ruleds = rn_rule_decls,
hs_vects = rn_vect_decls,
hs_docs = rn_docs } ;
tcf_bndrs = hsTyClForeignBinders rn_tycl_decls rn_inst_decls rn_foreign_decls ;
other_def = (Just (mkNameSet tcf_bndrs), emptyNameSet) ;
other_fvs = plusFVs [src_fvs1, src_fvs2, src_fvs3, src_fvs4,
src_fvs5, src_fvs6, src_fvs7, src_fvs8,
src_fvs9] ;
-- It is tiresome to gather the binders from type and class decls
src_dus = [other_def] `plusDU` bind_dus `plusDU` usesOnly other_fvs ;
-- Instance decls may have occurrences of things bound in bind_dus
-- so we must put other_fvs last
final_tcg_env = let tcg_env' = (last_tcg_env `addTcgDUs` src_dus)
in -- we return the deprecs in the env, not in the HsGroup above
tcg_env' { tcg_warns = tcg_warns tcg_env' `plusWarns` rn_warns };
} ;
traceRn (text "last" <+> ppr (tcg_rdr_env final_tcg_env)) ;
traceRn (text "finish rnSrc" <+> ppr rn_group) ;
traceRn (text "finish Dus" <+> ppr src_dus ) ;
return (final_tcg_env, rn_group)
}}}}
addTcgDUs :: TcGblEnv -> DefUses -> TcGblEnv
-- This function could be defined lower down in the module hierarchy,
-- but there doesn't seem anywhere very logical to put it.
addTcgDUs tcg_env dus = tcg_env { tcg_dus = tcg_dus tcg_env `plusDU` dus }
rnList :: (a -> RnM (b, FreeVars)) -> [Located a] -> RnM ([Located b], FreeVars)
rnList f xs = mapFvRn (wrapLocFstM f) xs
{-
*********************************************************
* *
HsDoc stuff
* *
*********************************************************
-}
rnDocDecl :: DocDecl -> RnM DocDecl
rnDocDecl (DocCommentNext doc) = do
rn_doc <- rnHsDoc doc
return (DocCommentNext rn_doc)
rnDocDecl (DocCommentPrev doc) = do
rn_doc <- rnHsDoc doc
return (DocCommentPrev rn_doc)
rnDocDecl (DocCommentNamed str doc) = do
rn_doc <- rnHsDoc doc
return (DocCommentNamed str rn_doc)
rnDocDecl (DocGroup lev doc) = do
rn_doc <- rnHsDoc doc
return (DocGroup lev rn_doc)
{-
*********************************************************
* *
Source-code fixity declarations
* *
*********************************************************
-}
rnSrcFixityDecls :: NameSet -> [LFixitySig RdrName] -> RnM [LFixitySig Name]
-- Rename the fixity decls, so we can put
-- the renamed decls in the renamed syntax tree
-- Errors if the thing being fixed is not defined locally.
--
-- The returned FixitySigs are not actually used for anything,
-- except perhaps the GHCi API
rnSrcFixityDecls bndr_set fix_decls
= do fix_decls <- mapM rn_decl fix_decls
return (concat fix_decls)
where
sig_ctxt = TopSigCtxt bndr_set
rn_decl :: LFixitySig RdrName -> RnM [LFixitySig Name]
-- GHC extension: look up both the tycon and data con
-- for con-like things; hence returning a list
-- If neither are in scope, report an error; otherwise
-- return a fixity sig for each (slightly odd)
rn_decl (L loc (FixitySig fnames fixity))
= do names <- mapM lookup_one fnames
return [ L loc (FixitySig name fixity)
| name <- names ]
lookup_one :: Located RdrName -> RnM [Located Name]
lookup_one (L name_loc rdr_name)
= setSrcSpan name_loc $
-- this lookup will fail if the definition isn't local
do names <- lookupLocalTcNames sig_ctxt what rdr_name
return [ L name_loc name | (_, name) <- names ]
what = text "fixity signature"
{-
*********************************************************
* *
Source-code deprecations declarations
* *
*********************************************************
Check that the deprecated names are defined, are defined locally, and
that there are no duplicate deprecations.
It's only imported deprecations, dealt with in RnIfaces, that we
gather them together.
-}
-- checks that the deprecations are defined locally, and that there are no duplicates
rnSrcWarnDecls :: NameSet -> [LWarnDecls RdrName] -> RnM Warnings
rnSrcWarnDecls _ []
= return NoWarnings
rnSrcWarnDecls bndr_set decls'
= do { -- check for duplicates
; mapM_ (\ dups -> let (L loc rdr:lrdr':_) = dups
in addErrAt loc (dupWarnDecl lrdr' rdr))
warn_rdr_dups
; pairs_s <- mapM (addLocM rn_deprec) decls
; return (WarnSome ((concat pairs_s))) }
where
decls = concatMap (\(L _ d) -> wd_warnings d) decls'
sig_ctxt = TopSigCtxt bndr_set
rn_deprec (Warning rdr_names txt)
-- ensures that the names are defined locally
= do { names <- concatMapM (lookupLocalTcNames sig_ctxt what . unLoc)
rdr_names
; return [(rdrNameOcc rdr, txt) | (rdr, _) <- names] }
what = text "deprecation"
warn_rdr_dups = findDupRdrNames $ concatMap (\(L _ (Warning ns _)) -> ns)
decls
findDupRdrNames :: [Located RdrName] -> [[Located RdrName]]
findDupRdrNames = findDupsEq (\ x -> \ y -> rdrNameOcc (unLoc x) == rdrNameOcc (unLoc y))
-- look for duplicates among the OccNames;
-- we check that the names are defined above
-- invt: the lists returned by findDupsEq always have at least two elements
dupWarnDecl :: Located RdrName -> RdrName -> SDoc
-- Located RdrName -> DeprecDecl RdrName -> SDoc
dupWarnDecl (L loc _) rdr_name
= vcat [text "Multiple warning declarations for" <+> quotes (ppr rdr_name),
text "also at " <+> ppr loc]
{-
*********************************************************
* *
\subsection{Annotation declarations}
* *
*********************************************************
-}
rnAnnDecl :: AnnDecl RdrName -> RnM (AnnDecl Name, FreeVars)
rnAnnDecl ann@(HsAnnotation s provenance expr)
= addErrCtxt (annCtxt ann) $
do { (provenance', provenance_fvs) <- rnAnnProvenance provenance
; (expr', expr_fvs) <- setStage (Splice Untyped) $
rnLExpr expr
; return (HsAnnotation s provenance' expr',
provenance_fvs `plusFV` expr_fvs) }
rnAnnProvenance :: AnnProvenance RdrName -> RnM (AnnProvenance Name, FreeVars)
rnAnnProvenance provenance = do
provenance' <- traverse lookupTopBndrRn provenance
return (provenance', maybe emptyFVs unitFV (annProvenanceName_maybe provenance'))
{-
*********************************************************
* *
\subsection{Default declarations}
* *
*********************************************************
-}
rnDefaultDecl :: DefaultDecl RdrName -> RnM (DefaultDecl Name, FreeVars)
rnDefaultDecl (DefaultDecl tys)
= do { (tys', fvs) <- rnLHsTypes doc_str tys
; return (DefaultDecl tys', fvs) }
where
doc_str = DefaultDeclCtx
{-
*********************************************************
* *
\subsection{Foreign declarations}
* *
*********************************************************
-}
rnHsForeignDecl :: ForeignDecl RdrName -> RnM (ForeignDecl Name, FreeVars)
rnHsForeignDecl (ForeignImport { fd_name = name, fd_sig_ty = ty, fd_fi = spec })
= do { topEnv :: HscEnv <- getTopEnv
; name' <- lookupLocatedTopBndrRn name
; (ty', fvs) <- rnHsSigType (ForeignDeclCtx name) ty
-- Mark any PackageTarget style imports as coming from the current package
; let unitId = thisPackage $ hsc_dflags topEnv
spec' = patchForeignImport unitId spec
; return (ForeignImport { fd_name = name', fd_sig_ty = ty'
, fd_co = noForeignImportCoercionYet
, fd_fi = spec' }, fvs) }
rnHsForeignDecl (ForeignExport { fd_name = name, fd_sig_ty = ty, fd_fe = spec })
= do { name' <- lookupLocatedOccRn name
; (ty', fvs) <- rnHsSigType (ForeignDeclCtx name) ty
; return (ForeignExport { fd_name = name', fd_sig_ty = ty'
, fd_co = noForeignExportCoercionYet
, fd_fe = spec }
, fvs `addOneFV` unLoc name') }
-- NB: a foreign export is an *occurrence site* for name, so
-- we add it to the free-variable list. It might, for example,
-- be imported from another module
-- | For Windows DLLs we need to know what packages imported symbols are from
-- to generate correct calls. Imported symbols are tagged with the current
-- package, so if they get inlined across a package boundry we'll still
-- know where they're from.
--
patchForeignImport :: UnitId -> ForeignImport -> ForeignImport
patchForeignImport unitId (CImport cconv safety fs spec src)
= CImport cconv safety fs (patchCImportSpec unitId spec) src
patchCImportSpec :: UnitId -> CImportSpec -> CImportSpec
patchCImportSpec unitId spec
= case spec of
CFunction callTarget -> CFunction $ patchCCallTarget unitId callTarget
_ -> spec
patchCCallTarget :: UnitId -> CCallTarget -> CCallTarget
patchCCallTarget unitId callTarget =
case callTarget of
StaticTarget src label Nothing isFun
-> StaticTarget src label (Just unitId) isFun
_ -> callTarget
{-
*********************************************************
* *
\subsection{Instance declarations}
* *
*********************************************************
-}
rnSrcInstDecl :: InstDecl RdrName -> RnM (InstDecl Name, FreeVars)
rnSrcInstDecl (TyFamInstD { tfid_inst = tfi })
= do { (tfi', fvs) <- rnTyFamInstDecl Nothing tfi
; return (TyFamInstD { tfid_inst = tfi' }, fvs) }
rnSrcInstDecl (DataFamInstD { dfid_inst = dfi })
= do { (dfi', fvs) <- rnDataFamInstDecl Nothing dfi
; return (DataFamInstD { dfid_inst = dfi' }, fvs) }
rnSrcInstDecl (ClsInstD { cid_inst = cid })
= do { (cid', fvs) <- rnClsInstDecl cid
; return (ClsInstD { cid_inst = cid' }, fvs) }
-- | Warn about non-canonical typeclass instance declarations
--
-- A "non-canonical" instance definition can occur for instances of a
-- class which redundantly defines an operation its superclass
-- provides as well (c.f. `return`/`pure`). In such cases, a canonical
-- instance is one where the subclass inherits its method
-- implementation from its superclass instance (usually the subclass
-- has a default method implementation to that effect). Consequently,
-- a non-canonical instance occurs when this is not the case.
--
-- See also descriptions of 'checkCanonicalMonadInstances' and
-- 'checkCanonicalMonoidInstances'
checkCanonicalInstances :: Name -> LHsSigType Name -> LHsBinds Name -> RnM ()
checkCanonicalInstances cls poly_ty mbinds = do
whenWOptM Opt_WarnNonCanonicalMonadInstances
checkCanonicalMonadInstances
whenWOptM Opt_WarnNonCanonicalMonadFailInstances
checkCanonicalMonadFailInstances
whenWOptM Opt_WarnNonCanonicalMonoidInstances
checkCanonicalMonoidInstances
where
-- | Warn about unsound/non-canonical 'Applicative'/'Monad' instance
-- declarations. Specifically, the following conditions are verified:
--
-- In 'Monad' instances declarations:
--
-- * If 'return' is overridden it must be canonical (i.e. @return = pure@)
-- * If '(>>)' is overridden it must be canonical (i.e. @(>>) = (*>)@)
--
-- In 'Applicative' instance declarations:
--
-- * Warn if 'pure' is defined backwards (i.e. @pure = return@).
-- * Warn if '(*>)' is defined backwards (i.e. @(*>) = (>>)@).
--
checkCanonicalMonadInstances
| cls == applicativeClassName = do
forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $ do
case mbind of
FunBind { fun_id = L _ name, fun_matches = mg }
| name == pureAName, isAliasMG mg == Just returnMName
-> addWarnNonCanonicalMethod1
Opt_WarnNonCanonicalMonadInstances "pure" "return"
| name == thenAName, isAliasMG mg == Just thenMName
-> addWarnNonCanonicalMethod1
Opt_WarnNonCanonicalMonadInstances "(*>)" "(>>)"
_ -> return ()
| cls == monadClassName = do
forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $ do
case mbind of
FunBind { fun_id = L _ name, fun_matches = mg }
| name == returnMName, isAliasMG mg /= Just pureAName
-> addWarnNonCanonicalMethod2
Opt_WarnNonCanonicalMonadInstances "return" "pure"
| name == thenMName, isAliasMG mg /= Just thenAName
-> addWarnNonCanonicalMethod2
Opt_WarnNonCanonicalMonadInstances "(>>)" "(*>)"
_ -> return ()
| otherwise = return ()
-- | Warn about unsound/non-canonical 'Monad'/'MonadFail' instance
-- declarations. Specifically, the following conditions are verified:
--
-- In 'Monad' instances declarations:
--
-- * If 'fail' is overridden it must be canonical
-- (i.e. @fail = Control.Monad.Fail.fail@)
--
-- In 'MonadFail' instance declarations:
--
-- * Warn if 'fail' is defined backwards
-- (i.e. @fail = Control.Monad.fail@).
--
checkCanonicalMonadFailInstances
| cls == monadFailClassName = do
forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $ do
case mbind of
FunBind { fun_id = L _ name, fun_matches = mg }
| name == failMName, isAliasMG mg == Just failMName_preMFP
-> addWarnNonCanonicalMethod1
Opt_WarnNonCanonicalMonadFailInstances "fail"
"Control.Monad.fail"
_ -> return ()
| cls == monadClassName = do
forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $ do
case mbind of
FunBind { fun_id = L _ name, fun_matches = mg }
| name == failMName_preMFP, isAliasMG mg /= Just failMName
-> addWarnNonCanonicalMethod2
Opt_WarnNonCanonicalMonadFailInstances "fail"
"Control.Monad.Fail.fail"
_ -> return ()
| otherwise = return ()
-- | Check whether Monoid(mappend) is defined in terms of
-- Semigroup((<>)) (and not the other way round). Specifically,
-- the following conditions are verified:
--
-- In 'Monoid' instances declarations:
--
-- * If 'mappend' is overridden it must be canonical
-- (i.e. @mappend = (<>)@)
--
-- In 'Semigroup' instance declarations:
--
-- * Warn if '(<>)' is defined backwards (i.e. @(<>) = mappend@).
--
checkCanonicalMonoidInstances
| cls == semigroupClassName = do
forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $ do
case mbind of
FunBind { fun_id = L _ name, fun_matches = mg }
| name == sappendName, isAliasMG mg == Just mappendName
-> addWarnNonCanonicalMethod1
Opt_WarnNonCanonicalMonoidInstances "(<>)" "mappend"
_ -> return ()
| cls == monoidClassName = do
forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $ do
case mbind of
FunBind { fun_id = L _ name, fun_matches = mg }
| name == mappendName, isAliasMG mg /= Just sappendName
-> addWarnNonCanonicalMethod2NoDefault
Opt_WarnNonCanonicalMonoidInstances "mappend" "(<>)"
_ -> return ()
| otherwise = return ()
-- | test whether MatchGroup represents a trivial \"lhsName = rhsName\"
-- binding, and return @Just rhsName@ if this is the case
isAliasMG :: MatchGroup Name (LHsExpr Name) -> Maybe Name
isAliasMG MG {mg_alts = L _ [L _ (Match { m_pats = [], m_grhss = grhss })]}
| GRHSs [L _ (GRHS [] body)] lbinds <- grhss
, L _ EmptyLocalBinds <- lbinds
, L _ (HsVar (L _ rhsName)) <- body = Just rhsName
isAliasMG _ = Nothing
-- got "lhs = rhs" but expected something different
addWarnNonCanonicalMethod1 flag lhs rhs = do
addWarn (Reason flag) $ vcat
[ text "Noncanonical" <+>
quotes (text (lhs ++ " = " ++ rhs)) <+>
text "definition detected"
, instDeclCtxt1 poly_ty
, text "Move definition from" <+>
quotes (text rhs) <+>
text "to" <+> quotes (text lhs)
]
-- expected "lhs = rhs" but got something else
addWarnNonCanonicalMethod2 flag lhs rhs = do
addWarn (Reason flag) $ vcat
[ text "Noncanonical" <+>
quotes (text lhs) <+>
text "definition detected"
, instDeclCtxt1 poly_ty
, text "Either remove definition for" <+>
quotes (text lhs) <+> text "or define as" <+>
quotes (text (lhs ++ " = " ++ rhs))
]
-- like above, but method has no default impl
addWarnNonCanonicalMethod2NoDefault flag lhs rhs = do
addWarn (Reason flag) $ vcat
[ text "Noncanonical" <+>
quotes (text lhs) <+>
text "definition detected"
, instDeclCtxt1 poly_ty
, text "Define as" <+>
quotes (text (lhs ++ " = " ++ rhs))
]
-- stolen from TcInstDcls
instDeclCtxt1 :: LHsSigType Name -> SDoc
instDeclCtxt1 hs_inst_ty
= inst_decl_ctxt (ppr (getLHsInstDeclHead hs_inst_ty))
inst_decl_ctxt :: SDoc -> SDoc
inst_decl_ctxt doc = hang (text "in the instance declaration for")
2 (quotes doc <> text ".")
rnClsInstDecl :: ClsInstDecl RdrName -> RnM (ClsInstDecl Name, FreeVars)
rnClsInstDecl (ClsInstDecl { cid_poly_ty = inst_ty, cid_binds = mbinds
, cid_sigs = uprags, cid_tyfam_insts = ats
, cid_overlap_mode = oflag
, cid_datafam_insts = adts })
= do { (inst_ty', inst_fvs) <- rnLHsInstType (text "an instance declaration") inst_ty
; let (ktv_names, _, head_ty') = splitLHsInstDeclTy inst_ty'
; let cls = case hsTyGetAppHead_maybe head_ty' of
Nothing -> mkUnboundName (mkTcOccFS (fsLit "<class>"))
Just (L _ cls, _) -> cls
-- rnLHsInstType has added an error message
-- if hsTyGetAppHead_maybe fails
-- Rename the bindings
-- The typechecker (not the renamer) checks that all
-- the bindings are for the right class
-- (Slightly strangely) when scoped type variables are on, the
-- forall-d tyvars scope over the method bindings too
; (mbinds', uprags', meth_fvs) <- rnMethodBinds False cls ktv_names mbinds uprags
; checkCanonicalInstances cls inst_ty' mbinds'
-- Rename the associated types, and type signatures
-- Both need to have the instance type variables in scope
; traceRn (text "rnSrcInstDecl" <+> ppr inst_ty' $$ ppr ktv_names)
; ((ats', adts'), more_fvs)
<- extendTyVarEnvFVRn ktv_names $
do { (ats', at_fvs) <- rnATInstDecls rnTyFamInstDecl cls ktv_names ats
; (adts', adt_fvs) <- rnATInstDecls rnDataFamInstDecl cls ktv_names adts
; return ( (ats', adts'), at_fvs `plusFV` adt_fvs) }
; let all_fvs = meth_fvs `plusFV` more_fvs
`plusFV` inst_fvs
; return (ClsInstDecl { cid_poly_ty = inst_ty', cid_binds = mbinds'
, cid_sigs = uprags', cid_tyfam_insts = ats'
, cid_overlap_mode = oflag
, cid_datafam_insts = adts' },
all_fvs) }
-- We return the renamed associated data type declarations so
-- that they can be entered into the list of type declarations
-- for the binding group, but we also keep a copy in the instance.
-- The latter is needed for well-formedness checks in the type
-- checker (eg, to ensure that all ATs of the instance actually
-- receive a declaration).
-- NB: Even the copies in the instance declaration carry copies of
-- the instance context after renaming. This is a bit
-- strange, but should not matter (and it would be more work
-- to remove the context).
rnFamInstDecl :: HsDocContext
-> Maybe (Name, [Name])
-> Located RdrName
-> HsTyPats RdrName
-> rhs
-> (HsDocContext -> rhs -> RnM (rhs', FreeVars))
-> RnM (Located Name, HsTyPats Name, rhs', FreeVars)
rnFamInstDecl doc mb_cls tycon (HsIB { hsib_body = pats }) payload rnPayload
= do { tycon' <- lookupFamInstName (fmap fst mb_cls) tycon
; let loc = case pats of
[] -> pprPanic "rnFamInstDecl" (ppr tycon)
(L loc _ : []) -> loc
(L loc _ : ps) -> combineSrcSpans loc (getLoc (last ps))
; pat_kity_vars_with_dups <- extractHsTysRdrTyVarsDups pats
-- Use the "...Dups" form becuase it's needed
-- below to report unsed binder on the LHS
; var_names <- mapM (newTyVarNameRn mb_cls . L loc . unLoc) $
freeKiTyVarsAllVars $
rmDupsInRdrTyVars pat_kity_vars_with_dups
-- All the free vars of the family patterns
-- with a sensible binding location
; ((pats', payload'), fvs)
<- bindLocalNamesFV var_names $
do { (pats', pat_fvs) <- rnLHsTypes (FamPatCtx tycon) pats
; (payload', rhs_fvs) <- rnPayload doc payload
-- Report unused binders on the LHS
-- See Note [Unused type variables in family instances]
; let groups :: [[Located RdrName]]
groups = equivClasses cmpLocated $
freeKiTyVarsAllVars pat_kity_vars_with_dups
; tv_nms_dups <- mapM (lookupOccRn . unLoc) $
[ tv | (tv:_:_) <- groups ]
-- Add to the used variables any variables that
-- appear *more than once* on the LHS
-- e.g. F a Int a = Bool
; let tv_nms_used = extendNameSetList rhs_fvs tv_nms_dups
; warnUnusedTypePatterns var_names tv_nms_used
-- See Note [Renaming associated types]
; let bad_tvs = case mb_cls of
Nothing -> []
Just (_,cls_tkvs) -> filter is_bad cls_tkvs
var_name_set = mkNameSet var_names
is_bad cls_tkv = cls_tkv `elemNameSet` rhs_fvs
&& not (cls_tkv `elemNameSet` var_name_set)
; unless (null bad_tvs) (badAssocRhs bad_tvs)
; return ((pats', payload'), rhs_fvs `plusFV` pat_fvs) }
; let anon_wcs = concatMap collectAnonWildCards pats'
all_ibs = anon_wcs ++ var_names
-- all_ibs: include anonymous wildcards in the implicit
-- binders In a type pattern they behave just like any
-- other type variable except for being anoymous. See
-- Note [Wildcards in family instances]
all_fvs = fvs `addOneFV` unLoc tycon'
; return (tycon',
HsIB { hsib_body = pats'
, hsib_vars = all_ibs },
payload',
all_fvs) }
-- type instance => use, hence addOneFV
rnTyFamInstDecl :: Maybe (Name, [Name])
-> TyFamInstDecl RdrName
-> RnM (TyFamInstDecl Name, FreeVars)
rnTyFamInstDecl mb_cls (TyFamInstDecl { tfid_eqn = L loc eqn })
= do { (eqn', fvs) <- rnTyFamInstEqn mb_cls eqn
; return (TyFamInstDecl { tfid_eqn = L loc eqn'
, tfid_fvs = fvs }, fvs) }
rnTyFamInstEqn :: Maybe (Name, [Name])
-> TyFamInstEqn RdrName
-> RnM (TyFamInstEqn Name, FreeVars)
rnTyFamInstEqn mb_cls (TyFamEqn { tfe_tycon = tycon
, tfe_pats = pats
, tfe_rhs = rhs })
= do { (tycon', pats', rhs', fvs) <-
rnFamInstDecl (TySynCtx tycon) mb_cls tycon pats rhs rnTySyn
; return (TyFamEqn { tfe_tycon = tycon'
, tfe_pats = pats'
, tfe_rhs = rhs' }, fvs) }
rnTyFamDefltEqn :: Name
-> TyFamDefltEqn RdrName
-> RnM (TyFamDefltEqn Name, FreeVars)
rnTyFamDefltEqn cls (TyFamEqn { tfe_tycon = tycon
, tfe_pats = tyvars
, tfe_rhs = rhs })
= bindHsQTyVars ctx Nothing (Just cls) [] tyvars $ \ tyvars' _ ->
do { tycon' <- lookupFamInstName (Just cls) tycon
; (rhs', fvs) <- rnLHsType ctx rhs
; return (TyFamEqn { tfe_tycon = tycon'
, tfe_pats = tyvars'
, tfe_rhs = rhs' }, fvs) }
where
ctx = TyFamilyCtx tycon
rnDataFamInstDecl :: Maybe (Name, [Name])
-> DataFamInstDecl RdrName
-> RnM (DataFamInstDecl Name, FreeVars)
rnDataFamInstDecl mb_cls (DataFamInstDecl { dfid_tycon = tycon
, dfid_pats = pats
, dfid_defn = defn })
= do { (tycon', pats', (defn', _), fvs) <-
rnFamInstDecl (TyDataCtx tycon) mb_cls tycon pats defn rnDataDefn
; return (DataFamInstDecl { dfid_tycon = tycon'
, dfid_pats = pats'
, dfid_defn = defn'
, dfid_fvs = fvs }, fvs) }
-- Renaming of the associated types in instances.
-- Rename associated type family decl in class
rnATDecls :: Name -- Class
-> [LFamilyDecl RdrName]
-> RnM ([LFamilyDecl Name], FreeVars)
rnATDecls cls at_decls
= rnList (rnFamDecl (Just cls)) at_decls
rnATInstDecls :: (Maybe (Name, [Name]) -> -- The function that renames
decl RdrName -> -- an instance. rnTyFamInstDecl
RnM (decl Name, FreeVars)) -- or rnDataFamInstDecl
-> Name -- Class
-> [Name]
-> [Located (decl RdrName)]
-> RnM ([Located (decl Name)], FreeVars)
-- Used for data and type family defaults in a class decl
-- and the family instance declarations in an instance
--
-- NB: We allow duplicate associated-type decls;
-- See Note [Associated type instances] in TcInstDcls
rnATInstDecls rnFun cls tv_ns at_insts
= rnList (rnFun (Just (cls, tv_ns))) at_insts
-- See Note [Renaming associated types]
{- Note [Wildcards in family instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Wild cards can be used in type/data family instance declarations to indicate
that the name of a type variable doesn't matter. Each wild card will be
replaced with a new unique type variable. For instance:
type family F a b :: *
type instance F Int _ = Int
is the same as
type family F a b :: *
type instance F Int b = Int
This is implemented as follows: during renaming anonymous wild cards
'_' are given freshly generated names. These names are collected after
renaming (rnFamInstDecl) and used to make new type variables during
type checking (tc_fam_ty_pats). One should not confuse these wild
cards with the ones from partial type signatures. The latter generate
fresh meta-variables whereas the former generate fresh skolems.
Note [Unused type variables in family instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the flag -fwarn-unused-type-patterns is on, the compiler reports warnings
about unused type variables. (rnFamInstDecl) A type variable is considered
used
* when it is either occurs on the RHS of the family instance, or
e.g. type instance F a b = a -- a is used on the RHS
* it occurs multiple times in the patterns on the LHS
e.g. type instance F a a = Int -- a appears more than once on LHS
As usual, the warnings are not reported for for type variables with names
beginning with an underscore.
Extra-constraints wild cards are not supported in type/data family
instance declarations.
Relevant tickets: #3699, #10586, #10982 and #11451.
Note [Renaming associated types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Check that the RHS of the decl mentions only type variables
bound on the LHS. For example, this is not ok
class C a b where
type F a x :: *
instance C (p,q) r where
type F (p,q) x = (x, r) -- BAD: mentions 'r'
c.f. Trac #5515
The same thing applies to kind variables, of course (Trac #7938, #9574):
class Funct f where
type Codomain f :: *
instance Funct ('KProxy :: KProxy o) where
type Codomain 'KProxy = NatTr (Proxy :: o -> *)
Here 'o' is mentioned on the RHS of the Codomain function, but
not on the LHS.
All this applies only for *instance* declarations. In *class*
declarations there is no RHS to worry about, and the class variables
can all be in scope (Trac #5862):
class Category (x :: k -> k -> *) where
type Ob x :: k -> Constraint
id :: Ob x a => x a a
(.) :: (Ob x a, Ob x b, Ob x c) => x b c -> x a b -> x a c
Here 'k' is in scope in the kind signature, just like 'x'.
-}
{-
*********************************************************
* *
\subsection{Stand-alone deriving declarations}
* *
*********************************************************
-}
rnSrcDerivDecl :: DerivDecl RdrName -> RnM (DerivDecl Name, FreeVars)
rnSrcDerivDecl (DerivDecl ty overlap)
= do { standalone_deriv_ok <- xoptM LangExt.StandaloneDeriving
; unless standalone_deriv_ok (addErr standaloneDerivErr)
; (ty', fvs) <- rnLHsInstType (text "In a deriving declaration") ty
; return (DerivDecl ty' overlap, fvs) }
standaloneDerivErr :: SDoc
standaloneDerivErr
= hang (text "Illegal standalone deriving declaration")
2 (text "Use StandaloneDeriving to enable this extension")
{-
*********************************************************
* *
\subsection{Rules}
* *
*********************************************************
-}
rnHsRuleDecls :: RuleDecls RdrName -> RnM (RuleDecls Name, FreeVars)
rnHsRuleDecls (HsRules src rules)
= do { (rn_rules,fvs) <- rnList rnHsRuleDecl rules
; return (HsRules src rn_rules,fvs) }
rnHsRuleDecl :: RuleDecl RdrName -> RnM (RuleDecl Name, FreeVars)
rnHsRuleDecl (HsRule rule_name act vars lhs _fv_lhs rhs _fv_rhs)
= do { let rdr_names_w_loc = map get_var vars
; checkDupRdrNames rdr_names_w_loc
; checkShadowedRdrNames rdr_names_w_loc
; names <- newLocalBndrsRn rdr_names_w_loc
; bindHsRuleVars (snd $ unLoc rule_name) vars names $ \ vars' ->
do { (lhs', fv_lhs') <- rnLExpr lhs
; (rhs', fv_rhs') <- rnLExpr rhs
; checkValidRule (snd $ unLoc rule_name) names lhs' fv_lhs'
; return (HsRule rule_name act vars' lhs' fv_lhs' rhs' fv_rhs',
fv_lhs' `plusFV` fv_rhs') } }
where
get_var (L _ (RuleBndrSig v _)) = v
get_var (L _ (RuleBndr v)) = v
bindHsRuleVars :: RuleName -> [LRuleBndr RdrName] -> [Name]
-> ([LRuleBndr Name] -> RnM (a, FreeVars))
-> RnM (a, FreeVars)
bindHsRuleVars rule_name vars names thing_inside
= go vars names $ \ vars' ->
bindLocalNamesFV names (thing_inside vars')
where
doc = RuleCtx rule_name
go (L l (RuleBndr (L loc _)) : vars) (n : ns) thing_inside
= go vars ns $ \ vars' ->
thing_inside (L l (RuleBndr (L loc n)) : vars')
go (L l (RuleBndrSig (L loc _) bsig) : vars) (n : ns) thing_inside
= rnHsSigWcTypeScoped doc bsig $ \ bsig' ->
go vars ns $ \ vars' ->
thing_inside (L l (RuleBndrSig (L loc n) bsig') : vars')
go [] [] thing_inside = thing_inside []
go vars names _ = pprPanic "bindRuleVars" (ppr vars $$ ppr names)
{-
Note [Rule LHS validity checking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Check the shape of a transformation rule LHS. Currently we only allow
LHSs of the form @(f e1 .. en)@, where @f@ is not one of the
@forall@'d variables.
We used restrict the form of the 'ei' to prevent you writing rules
with LHSs with a complicated desugaring (and hence unlikely to match);
(e.g. a case expression is not allowed: too elaborate.)
But there are legitimate non-trivial args ei, like sections and
lambdas. So it seems simmpler not to check at all, and that is why
check_e is commented out.
-}
checkValidRule :: FastString -> [Name] -> LHsExpr Name -> NameSet -> RnM ()
checkValidRule rule_name ids lhs' fv_lhs'
= do { -- Check for the form of the LHS
case (validRuleLhs ids lhs') of
Nothing -> return ()
Just bad -> failWithTc (badRuleLhsErr rule_name lhs' bad)
-- Check that LHS vars are all bound
; let bad_vars = [var | var <- ids, not (var `elemNameSet` fv_lhs')]
; mapM_ (addErr . badRuleVar rule_name) bad_vars }
validRuleLhs :: [Name] -> LHsExpr Name -> Maybe (HsExpr Name)
-- Nothing => OK
-- Just e => Not ok, and e is the offending sub-expression
validRuleLhs foralls lhs
= checkl lhs
where
checkl (L _ e) = check e
check (OpApp e1 op _ e2) = checkl op `mplus` checkl_e e1 `mplus` checkl_e e2
check (HsApp e1 e2) = checkl e1 `mplus` checkl_e e2
check (HsAppType e _) = checkl e
check (HsVar (L _ v)) | v `notElem` foralls = Nothing
check other = Just other -- Failure
-- Check an argument
checkl_e (L _ _e) = Nothing -- Was (check_e e); see Note [Rule LHS validity checking]
{- Commented out; see Note [Rule LHS validity checking] above
check_e (HsVar v) = Nothing
check_e (HsPar e) = checkl_e e
check_e (HsLit e) = Nothing
check_e (HsOverLit e) = Nothing
check_e (OpApp e1 op _ e2) = checkl_e e1 `mplus` checkl_e op `mplus` checkl_e e2
check_e (HsApp e1 e2) = checkl_e e1 `mplus` checkl_e e2
check_e (NegApp e _) = checkl_e e
check_e (ExplicitList _ es) = checkl_es es
check_e other = Just other -- Fails
checkl_es es = foldr (mplus . checkl_e) Nothing es
-}
badRuleVar :: FastString -> Name -> SDoc
badRuleVar name var
= sep [text "Rule" <+> doubleQuotes (ftext name) <> colon,
text "Forall'd variable" <+> quotes (ppr var) <+>
text "does not appear on left hand side"]
badRuleLhsErr :: FastString -> LHsExpr Name -> HsExpr Name -> SDoc
badRuleLhsErr name lhs bad_e
= sep [text "Rule" <+> pprRuleName name <> colon,
nest 4 (vcat [err,
text "in left-hand side:" <+> ppr lhs])]
$$
text "LHS must be of form (f e1 .. en) where f is not forall'd"
where
err = case bad_e of
HsUnboundVar uv -> text "Not in scope:" <+> ppr uv
_ -> text "Illegal expression:" <+> ppr bad_e
{-
*********************************************************
* *
\subsection{Vectorisation declarations}
* *
*********************************************************
-}
rnHsVectDecl :: VectDecl RdrName -> RnM (VectDecl Name, FreeVars)
-- FIXME: For the moment, the right-hand side is restricted to be a variable as we cannot properly
-- typecheck a complex right-hand side without invoking 'vectType' from the vectoriser.
rnHsVectDecl (HsVect s var rhs@(L _ (HsVar _)))
= do { var' <- lookupLocatedOccRn var
; (rhs', fv_rhs) <- rnLExpr rhs
; return (HsVect s var' rhs', fv_rhs `addOneFV` unLoc var')
}
rnHsVectDecl (HsVect _ _var _rhs)
= failWith $ vcat
[ text "IMPLEMENTATION RESTRICTION: right-hand side of a VECTORISE pragma"
, text "must be an identifier"
]
rnHsVectDecl (HsNoVect s var)
= do { var' <- lookupLocatedTopBndrRn var -- only applies to local (not imported) names
; return (HsNoVect s var', unitFV (unLoc var'))
}
rnHsVectDecl (HsVectTypeIn s isScalar tycon Nothing)
= do { tycon' <- lookupLocatedOccRn tycon
; return (HsVectTypeIn s isScalar tycon' Nothing, unitFV (unLoc tycon'))
}
rnHsVectDecl (HsVectTypeIn s isScalar tycon (Just rhs_tycon))
= do { tycon' <- lookupLocatedOccRn tycon
; rhs_tycon' <- lookupLocatedOccRn rhs_tycon
; return ( HsVectTypeIn s isScalar tycon' (Just rhs_tycon')
, mkFVs [unLoc tycon', unLoc rhs_tycon'])
}
rnHsVectDecl (HsVectTypeOut _ _ _)
= panic "RnSource.rnHsVectDecl: Unexpected 'HsVectTypeOut'"
rnHsVectDecl (HsVectClassIn s cls)
= do { cls' <- lookupLocatedOccRn cls
; return (HsVectClassIn s cls', unitFV (unLoc cls'))
}
rnHsVectDecl (HsVectClassOut _)
= panic "RnSource.rnHsVectDecl: Unexpected 'HsVectClassOut'"
rnHsVectDecl (HsVectInstIn instTy)
= do { (instTy', fvs) <- rnLHsInstType (text "a VECTORISE pragma") instTy
; return (HsVectInstIn instTy', fvs)
}
rnHsVectDecl (HsVectInstOut _)
= panic "RnSource.rnHsVectDecl: Unexpected 'HsVectInstOut'"
{-
*********************************************************
* *
\subsection{Type, class and iface sig declarations}
* *
*********************************************************
@rnTyDecl@ uses the `global name function' to create a new type
declaration in which local names have been replaced by their original
names, reporting any unknown names.
Renaming type variables is a pain. Because they now contain uniques,
it is necessary to pass in an association list which maps a parsed
tyvar to its @Name@ representation.
In some cases (type signatures of values),
it is even necessary to go over the type first
in order to get the set of tyvars used by it, make an assoc list,
and then go over it again to rename the tyvars!
However, we can also do some scoping checks at the same time.
Note [Extra dependencies from .hs-boot files]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following case:
A.hs-boot
module A where
data A1
B.hs
module B where
import {-# SOURCE #-} A
type DisguisedA1 = A1
data B1 = B1 DisguisedA1
A.hs
module A where
import B
data A2 = A2 A1
data A1 = A1 B1
Here A1 is really recursive (via B1), but we won't see that easily when
doing dependency analysis when compiling A.hs
To handle this problem, we add a dependency
- from every local declaration
- to everything that comes from this module's .hs-boot file.
In this case, we'll ad and edges
- from A2 to A1 (but that edge is there already)
- from A1 to A1 (which is new)
Well, not quite *every* declaration. Imagine module A
above had another datatype declaration:
data A3 = A3 Int
Even though A3 has a dependency (on Int), all its dependencies are from things
that live on other packages. Since we don't have mutual dependencies across
packages, it is safe not to add the dependencies on the .hs-boot stuff to A2.
Hence function Name.thisPackageImport.
See also Note [Grouping of type and class declarations] in TcTyClsDecls.
-}
rnTyClDecls :: [TyClGroup RdrName]
-> RnM ([TyClGroup Name], FreeVars)
-- Rename the declarations and do depedency analysis on them
rnTyClDecls tycl_ds
= do { ds_w_fvs <- mapM (wrapLocFstM rnTyClDecl) (tyClGroupConcat tycl_ds)
; let decl_names = mkNameSet (map (tcdName . unLoc . fst) ds_w_fvs)
; role_annot_env <- rnRoleAnnots decl_names (concatMap group_roles tycl_ds)
; tcg_env <- getGblEnv
; let this_mod = tcg_mod tcg_env
boot_info = tcg_self_boot tcg_env
add_boot_deps :: [(LTyClDecl Name, FreeVars)] -> [(LTyClDecl Name, FreeVars)]
-- See Note [Extra dependencies from .hs-boot files]
add_boot_deps ds_w_fvs
= case boot_info of
SelfBoot { sb_tcs = tcs } | not (isEmptyNameSet tcs)
-> map (add_one tcs) ds_w_fvs
_ -> ds_w_fvs
add_one :: NameSet -> (LTyClDecl Name, FreeVars) -> (LTyClDecl Name, FreeVars)
add_one tcs pr@(decl,fvs)
| has_local_imports fvs = (decl, fvs `plusFV` tcs)
| otherwise = pr
has_local_imports fvs
= foldNameSet ((||) . nameIsHomePackageImport this_mod)
False fvs
ds_w_fvs' = add_boot_deps ds_w_fvs
sccs :: [SCC (LTyClDecl Name)]
sccs = depAnalTyClDecls ds_w_fvs'
all_fvs = foldr (plusFV . snd) emptyFVs ds_w_fvs'
raw_groups = map flattenSCC sccs
-- See Note [Role annotations in the renamer]
(groups, orphan_roles)
= foldr (\group (groups_acc, orphans_acc) ->
let names = map (tcdName . unLoc) group
roles = mapMaybe (lookupNameEnv orphans_acc) names
orphans' = delListFromNameEnv orphans_acc names
-- there doesn't seem to be an interface to
-- do the above more efficiently
in ( TyClGroup { group_tyclds = group
, group_roles = roles } : groups_acc
, orphans' )
)
([], role_annot_env)
raw_groups
; mapM_ orphanRoleAnnotErr (nameEnvElts orphan_roles)
; traceRn (text "rnTycl" <+> (ppr ds_w_fvs $$ ppr sccs))
; return (groups, all_fvs) }
rnTyClDecl :: TyClDecl RdrName
-> RnM (TyClDecl Name, FreeVars)
-- All flavours of type family declarations ("type family", "newtype family",
-- and "data family"), both top level and (for an associated type)
-- in a class decl
rnTyClDecl (FamDecl { tcdFam = decl })
= do { (decl', fvs) <- rnFamDecl Nothing decl
; return (FamDecl decl', fvs) }
rnTyClDecl (SynDecl { tcdLName = tycon, tcdTyVars = tyvars, tcdRhs = rhs })
= do { tycon' <- lookupLocatedTopBndrRn tycon
; kvs <- freeKiTyVarsKindVars <$> extractHsTyRdrTyVars rhs
; let doc = TySynCtx tycon
; traceRn (text "rntycl-ty" <+> ppr tycon <+> ppr kvs)
; ((tyvars', rhs'), fvs) <- bindHsQTyVars doc Nothing Nothing kvs tyvars $
\ tyvars' _ ->
do { (rhs', fvs) <- rnTySyn doc rhs
; return ((tyvars', rhs'), fvs) }
; return (SynDecl { tcdLName = tycon', tcdTyVars = tyvars'
, tcdRhs = rhs', tcdFVs = fvs }, fvs) }
-- "data", "newtype" declarations
-- both top level and (for an associated type) in an instance decl
rnTyClDecl (DataDecl { tcdLName = tycon, tcdTyVars = tyvars, tcdDataDefn = defn })
= do { tycon' <- lookupLocatedTopBndrRn tycon
; kvs <- extractDataDefnKindVars defn
; let doc = TyDataCtx tycon
; traceRn (text "rntycl-data" <+> ppr tycon <+> ppr kvs)
; ((tyvars', defn', no_kvs), fvs)
<- bindHsQTyVars doc Nothing Nothing kvs tyvars $ \ tyvars' dep_vars ->
do { ((defn', kind_sig_fvs), fvs) <- rnDataDefn doc defn
; let sig_tvs = filterNameSet isTyVarName kind_sig_fvs
unbound_sig_tvs = sig_tvs `minusNameSet` dep_vars
; return ((tyvars', defn', isEmptyNameSet unbound_sig_tvs), fvs) }
-- See Note [Complete user-supplied kind signatures] in HsDecls
; typeintype <- xoptM LangExt.TypeInType
; let cusk = hsTvbAllKinded tyvars' &&
(not typeintype || no_kvs)
; return (DataDecl { tcdLName = tycon', tcdTyVars = tyvars'
, tcdDataDefn = defn', tcdDataCusk = cusk
, tcdFVs = fvs }, fvs) }
rnTyClDecl (ClassDecl { tcdCtxt = context, tcdLName = lcls,
tcdTyVars = tyvars, tcdFDs = fds, tcdSigs = sigs,
tcdMeths = mbinds, tcdATs = ats, tcdATDefs = at_defs,
tcdDocs = docs})
= do { lcls' <- lookupLocatedTopBndrRn lcls
; let cls' = unLoc lcls'
kvs = [] -- No scoped kind vars except those in
-- kind signatures on the tyvars
-- Tyvars scope over superclass context and method signatures
; ((tyvars', context', fds', ats'), stuff_fvs)
<- bindHsQTyVars cls_doc Nothing Nothing kvs tyvars $ \ tyvars' _ -> do
-- Checks for distinct tyvars
{ (context', cxt_fvs) <- rnContext cls_doc context
; fds' <- rnFds fds
-- The fundeps have no free variables
; (ats', fv_ats) <- rnATDecls cls' ats
; let fvs = cxt_fvs `plusFV`
fv_ats
; return ((tyvars', context', fds', ats'), fvs) }
; (at_defs', fv_at_defs) <- rnList (rnTyFamDefltEqn cls') at_defs
-- No need to check for duplicate associated type decls
-- since that is done by RnNames.extendGlobalRdrEnvRn
-- Check the signatures
-- First process the class op sigs (op_sigs), then the fixity sigs (non_op_sigs).
; let sig_rdr_names_w_locs = [op | L _ (ClassOpSig False ops _) <- sigs
, op <- ops]
; checkDupRdrNames sig_rdr_names_w_locs
-- Typechecker is responsible for checking that we only
-- give default-method bindings for things in this class.
-- The renamer *could* check this for class decls, but can't
-- for instance decls.
-- The newLocals call is tiresome: given a generic class decl
-- class C a where
-- op :: a -> a
-- op {| x+y |} (Inl a) = ...
-- op {| x+y |} (Inr b) = ...
-- op {| a*b |} (a*b) = ...
-- we want to name both "x" tyvars with the same unique, so that they are
-- easy to group together in the typechecker.
; (mbinds', sigs', meth_fvs)
<- rnMethodBinds True cls' (hsAllLTyVarNames tyvars') mbinds sigs
-- No need to check for duplicate method signatures
-- since that is done by RnNames.extendGlobalRdrEnvRn
-- and the methods are already in scope
-- Haddock docs
; docs' <- mapM (wrapLocM rnDocDecl) docs
; let all_fvs = meth_fvs `plusFV` stuff_fvs `plusFV` fv_at_defs
; return (ClassDecl { tcdCtxt = context', tcdLName = lcls',
tcdTyVars = tyvars', tcdFDs = fds', tcdSigs = sigs',
tcdMeths = mbinds', tcdATs = ats', tcdATDefs = at_defs',
tcdDocs = docs', tcdFVs = all_fvs },
all_fvs ) }
where
cls_doc = ClassDeclCtx lcls
-- "type" and "type instance" declarations
rnTySyn :: HsDocContext -> LHsType RdrName -> RnM (LHsType Name, FreeVars)
rnTySyn doc rhs = rnLHsType doc rhs
-- | Renames role annotations, returning them as the values in a NameEnv
-- and checks for duplicate role annotations.
-- It is quite convenient to do both of these in the same place.
-- See also Note [Role annotations in the renamer]
rnRoleAnnots :: NameSet -- ^ of the decls in this group
-> [LRoleAnnotDecl RdrName]
-> RnM (NameEnv (LRoleAnnotDecl Name))
rnRoleAnnots decl_names role_annots
= do { -- check for duplicates *before* renaming, to avoid lumping
-- together all the unboundNames
let (no_dups, dup_annots) = removeDups role_annots_cmp role_annots
role_annots_cmp (L _ annot1) (L _ annot2)
= roleAnnotDeclName annot1 `compare` roleAnnotDeclName annot2
; mapM_ dupRoleAnnotErr dup_annots
; role_annots' <- mapM (wrapLocM rn_role_annot1) no_dups
-- some of the role annots will be unbound; we don't wish
-- to include these
; return $ mkNameEnv [ (name, ra)
| ra <- role_annots'
, let name = roleAnnotDeclName (unLoc ra)
, not (isUnboundName name) ] }
where
rn_role_annot1 (RoleAnnotDecl tycon roles)
= do { -- the name is an *occurrence*, but look it up only in the
-- decls defined in this group (see #10263)
tycon' <- lookupSigCtxtOccRn (RoleAnnotCtxt decl_names)
(text "role annotation")
tycon
; return $ RoleAnnotDecl tycon' roles }
dupRoleAnnotErr :: [LRoleAnnotDecl RdrName] -> RnM ()
dupRoleAnnotErr [] = panic "dupRoleAnnotErr"
dupRoleAnnotErr list
= addErrAt loc $
hang (text "Duplicate role annotations for" <+>
quotes (ppr $ roleAnnotDeclName first_decl) <> colon)
2 (vcat $ map pp_role_annot sorted_list)
where
sorted_list = sortBy cmp_annot list
(L loc first_decl : _) = sorted_list
pp_role_annot (L loc decl) = hang (ppr decl)
4 (text "-- written at" <+> ppr loc)
cmp_annot (L loc1 _) (L loc2 _) = loc1 `compare` loc2
orphanRoleAnnotErr :: LRoleAnnotDecl Name -> RnM ()
orphanRoleAnnotErr (L loc decl)
= addErrAt loc $
hang (text "Role annotation for a type previously declared:")
2 (ppr decl) $$
parens (text "The role annotation must be given where" <+>
quotes (ppr $ roleAnnotDeclName decl) <+>
text "is declared.")
rnDataDefn :: HsDocContext -> HsDataDefn RdrName
-> RnM ((HsDataDefn Name, NameSet), FreeVars)
-- the NameSet includes all Names free in the kind signature
-- See Note [Complete user-supplied kind signatures]
rnDataDefn doc (HsDataDefn { dd_ND = new_or_data, dd_cType = cType
, dd_ctxt = context, dd_cons = condecls
, dd_kindSig = m_sig, dd_derivs = derivs })
= do { checkTc (h98_style || null (unLoc context))
(badGadtStupidTheta doc)
; (m_sig', sig_fvs) <- case m_sig of
Just sig -> first Just <$> rnLHsKind doc sig
Nothing -> return (Nothing, emptyFVs)
; (context', fvs1) <- rnContext doc context
; (derivs', fvs3) <- rn_derivs derivs
-- For the constructor declarations, drop the LocalRdrEnv
-- in the GADT case, where the type variables in the declaration
-- do not scope over the constructor signatures
-- data T a where { T1 :: forall b. b-> b }
; let { zap_lcl_env | h98_style = \ thing -> thing
| otherwise = setLocalRdrEnv emptyLocalRdrEnv }
; (condecls', con_fvs) <- zap_lcl_env $ rnConDecls condecls
-- No need to check for duplicate constructor decls
-- since that is done by RnNames.extendGlobalRdrEnvRn
; let all_fvs = fvs1 `plusFV` fvs3 `plusFV`
con_fvs `plusFV` sig_fvs
; return (( HsDataDefn { dd_ND = new_or_data, dd_cType = cType
, dd_ctxt = context', dd_kindSig = m_sig'
, dd_cons = condecls'
, dd_derivs = derivs' }
, sig_fvs )
, all_fvs )
}
where
h98_style = case condecls of -- Note [Stupid theta]
L _ (ConDeclGADT {}) : _ -> False
_ -> True
rn_derivs Nothing
= return (Nothing, emptyFVs)
rn_derivs (Just (L loc ds))
= do { (ds', fvs) <- mapFvRn (rnHsSigType doc) ds
; return (Just (L loc ds'), fvs) }
badGadtStupidTheta :: HsDocContext -> SDoc
badGadtStupidTheta _
= vcat [text "No context is allowed on a GADT-style data declaration",
text "(You can put a context on each contructor, though.)"]
rnFamDecl :: Maybe Name -- Just cls => this FamilyDecl is nested
-- inside an *class decl* for cls
-- used for associated types
-> FamilyDecl RdrName
-> RnM (FamilyDecl Name, FreeVars)
rnFamDecl mb_cls (FamilyDecl { fdLName = tycon, fdTyVars = tyvars
, fdInfo = info, fdResultSig = res_sig
, fdInjectivityAnn = injectivity })
= do { tycon' <- lookupLocatedTopBndrRn tycon
; kvs <- extractRdrKindSigVars res_sig
; ((tyvars', res_sig', injectivity'), fv1) <-
bindHsQTyVars doc Nothing mb_cls kvs tyvars $
\ tyvars'@(HsQTvs { hsq_implicit = rn_kvs }) _ ->
do { let rn_sig = rnFamResultSig doc rn_kvs
; (res_sig', fv_kind) <- wrapLocFstM rn_sig res_sig
; injectivity' <- traverse (rnInjectivityAnn tyvars' res_sig')
injectivity
; return ( (tyvars', res_sig', injectivity') , fv_kind ) }
; (info', fv2) <- rn_info info
; return (FamilyDecl { fdLName = tycon', fdTyVars = tyvars'
, fdInfo = info', fdResultSig = res_sig'
, fdInjectivityAnn = injectivity' }
, fv1 `plusFV` fv2) }
where
doc = TyFamilyCtx tycon
----------------------
rn_info (ClosedTypeFamily (Just eqns))
= do { (eqns', fvs) <- rnList (rnTyFamInstEqn Nothing) eqns
-- no class context,
; return (ClosedTypeFamily (Just eqns'), fvs) }
rn_info (ClosedTypeFamily Nothing)
= return (ClosedTypeFamily Nothing, emptyFVs)
rn_info OpenTypeFamily = return (OpenTypeFamily, emptyFVs)
rn_info DataFamily = return (DataFamily, emptyFVs)
rnFamResultSig :: HsDocContext
-> [Name] -- kind variables already in scope
-> FamilyResultSig RdrName
-> RnM (FamilyResultSig Name, FreeVars)
rnFamResultSig _ _ NoSig
= return (NoSig, emptyFVs)
rnFamResultSig doc _ (KindSig kind)
= do { (rndKind, ftvs) <- rnLHsKind doc kind
; return (KindSig rndKind, ftvs) }
rnFamResultSig doc kv_names (TyVarSig tvbndr)
= do { -- `TyVarSig` tells us that user named the result of a type family by
-- writing `= tyvar` or `= (tyvar :: kind)`. In such case we want to
-- be sure that the supplied result name is not identical to an
-- already in-scope type variable from an enclosing class.
--
-- Example of disallowed declaration:
-- class C a b where
-- type F b = a | a -> b
rdr_env <- getLocalRdrEnv
; let resName = hsLTyVarName tvbndr
; when (resName `elemLocalRdrEnv` rdr_env) $
addErrAt (getLoc tvbndr) $
(hsep [ text "Type variable", quotes (ppr resName) <> comma
, text "naming a type family result,"
] $$
text "shadows an already bound type variable")
; bindLHsTyVarBndr doc Nothing -- this might be a lie, but it's used for
-- scoping checks that are irrelevant here
(mkNameSet kv_names) emptyNameSet
-- use of emptyNameSet here avoids
-- redundant duplicate errors
tvbndr $ \ _ _ tvbndr' ->
return (TyVarSig tvbndr', unitFV (hsLTyVarName tvbndr')) }
-- Note [Renaming injectivity annotation]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- During renaming of injectivity annotation we have to make several checks to
-- make sure that it is well-formed. At the moment injectivity annotation
-- consists of a single injectivity condition, so the terms "injectivity
-- annotation" and "injectivity condition" might be used interchangeably. See
-- Note [Injectivity annotation] for a detailed discussion of currently allowed
-- injectivity annotations.
--
-- Checking LHS is simple because the only type variable allowed on the LHS of
-- injectivity condition is the variable naming the result in type family head.
-- Example of disallowed annotation:
--
-- type family Foo a b = r | b -> a
--
-- Verifying RHS of injectivity consists of checking that:
--
-- 1. only variables defined in type family head appear on the RHS (kind
-- variables are also allowed). Example of disallowed annotation:
--
-- type family Foo a = r | r -> b
--
-- 2. for associated types the result variable does not shadow any of type
-- class variables. Example of disallowed annotation:
--
-- class Foo a b where
-- type F a = b | b -> a
--
-- Breaking any of these assumptions results in an error.
-- | Rename injectivity annotation. Note that injectivity annotation is just the
-- part after the "|". Everything that appears before it is renamed in
-- rnFamDecl.
rnInjectivityAnn :: LHsQTyVars Name -- ^ Type variables declared in
-- type family head
-> LFamilyResultSig Name -- ^ Result signature
-> LInjectivityAnn RdrName -- ^ Injectivity annotation
-> RnM (LInjectivityAnn Name)
rnInjectivityAnn tvBndrs (L _ (TyVarSig resTv))
(L srcSpan (InjectivityAnn injFrom injTo))
= do
{ (injDecl'@(L _ (InjectivityAnn injFrom' injTo')), noRnErrors)
<- askNoErrs $
bindLocalNames [hsLTyVarName resTv] $
-- The return type variable scopes over the injectivity annotation
-- e.g. type family F a = (r::*) | r -> a
do { injFrom' <- rnLTyVar injFrom
; injTo' <- mapM rnLTyVar injTo
; return $ L srcSpan (InjectivityAnn injFrom' injTo') }
; let tvNames = Set.fromList $ hsAllLTyVarNames tvBndrs
resName = hsLTyVarName resTv
-- See Note [Renaming injectivity annotation]
lhsValid = EQ == (stableNameCmp resName (unLoc injFrom'))
rhsValid = Set.fromList (map unLoc injTo') `Set.difference` tvNames
-- if renaming of type variables ended with errors (eg. there were
-- not-in-scope variables) don't check the validity of injectivity
-- annotation. This gives better error messages.
; when (noRnErrors && not lhsValid) $
addErrAt (getLoc injFrom)
( vcat [ text $ "Incorrect type variable on the LHS of "
++ "injectivity condition"
, nest 5
( vcat [ text "Expected :" <+> ppr resName
, text "Actual :" <+> ppr injFrom ])])
; when (noRnErrors && not (Set.null rhsValid)) $
do { let errorVars = Set.toList rhsValid
; addErrAt srcSpan $ ( hsep
[ text "Unknown type variable" <> plural errorVars
, text "on the RHS of injectivity condition:"
, interpp'SP errorVars ] ) }
; return injDecl' }
-- We can only hit this case when the user writes injectivity annotation without
-- naming the result:
--
-- type family F a | result -> a
-- type family F a :: * | result -> a
--
-- So we rename injectivity annotation like we normally would except that
-- this time we expect "result" to be reported not in scope by rnLTyVar.
rnInjectivityAnn _ _ (L srcSpan (InjectivityAnn injFrom injTo)) =
setSrcSpan srcSpan $ do
(injDecl', _) <- askNoErrs $ do
injFrom' <- rnLTyVar injFrom
injTo' <- mapM rnLTyVar injTo
return $ L srcSpan (InjectivityAnn injFrom' injTo')
return $ injDecl'
{-
Note [Stupid theta]
~~~~~~~~~~~~~~~~~~~
Trac #3850 complains about a regression wrt 6.10 for
data Show a => T a
There is no reason not to allow the stupid theta if there are no data
constructors. It's still stupid, but does no harm, and I don't want
to cause programs to break unnecessarily (notably HList). So if there
are no data constructors we allow h98_style = True
-}
depAnalTyClDecls :: [(LTyClDecl Name, FreeVars)] -> [SCC (LTyClDecl Name)]
-- See Note [Dependency analysis of type and class decls]
depAnalTyClDecls ds_w_fvs
= stronglyConnCompFromEdgedVertices edges
where
edges = [ (d, tcdName (unLoc d), map get_parent (nameSetElems fvs))
| (d, fvs) <- ds_w_fvs ]
-- We also need to consider data constructor names since
-- they may appear in types because of promotion.
get_parent n = lookupNameEnv assoc_env n `orElse` n
assoc_env :: NameEnv Name -- Maps a data constructor back
-- to its parent type constructor
assoc_env = mkNameEnv $ concat assoc_env_list
assoc_env_list = do
(L _ d, _) <- ds_w_fvs
case d of
ClassDecl { tcdLName = L _ cls_name
, tcdATs = ats }
-> do L _ (FamilyDecl { fdLName = L _ fam_name }) <- ats
return [(fam_name, cls_name)]
DataDecl { tcdLName = L _ data_name
, tcdDataDefn = HsDataDefn { dd_cons = cons } }
-> do L _ dc <- cons
return $ zip (map unLoc $ getConNames dc) (repeat data_name)
_ -> []
{-
Note [Dependency analysis of type and class decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to do dependency analysis on type and class declarations
else we get bad error messages. Consider
data T f a = MkT f a
data S f a = MkS f (T f a)
This has a kind error, but the error message is better if you
check T first, (fixing its kind) and *then* S. If you do kind
inference together, you might get an error reported in S, which
is jolly confusing. See Trac #4875
Note [Role annotations in the renamer]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must ensure that a type's role annotation is put in the same group as the
proper type declaration. This is because role annotations are needed during
type-checking when creating the type's TyCon. So, rnRoleAnnots builds a
NameEnv (LRoleAnnotDecl Name) that maps a name to a role annotation for that
type, if any. Then, this map can be used to add the role annotations to the
groups after dependency analysis.
This process checks for duplicate role annotations, where we must be careful
to do the check *before* renaming to avoid calling all unbound names duplicates
of one another.
The renaming process, as usual, might identify and report errors for unbound
names. We exclude the annotations for unbound names in the annotation
environment to avoid spurious errors for orphaned annotations.
We then (in rnTyClDecls) do a check for orphan role annotations (role
annotations without an accompanying type decl). The check works by folding
over raw_groups (of type [[TyClDecl Name]]), selecting out the relevant
role declarations for each group, as well as diminishing the annotation
environment. After the fold is complete, anything left over in the name
environment must be an orphan, and errors are generated.
An earlier version of this algorithm short-cut the orphan check by renaming
only with names declared in this module. But, this check is insufficient in
the case of staged module compilation (Template Haskell, GHCi).
See #8485. With the new lookup process (which includes types declared in other
modules), we get better error messages, too.
*********************************************************
* *
\subsection{Support code for type/data declarations}
* *
*********************************************************
-}
---------------
badAssocRhs :: [Name] -> RnM ()
badAssocRhs ns
= addErr (hang (text "The RHS of an associated type declaration mentions"
<+> pprWithCommas (quotes . ppr) ns)
2 (text "All such variables must be bound on the LHS"))
-----------------
rnConDecls :: [LConDecl RdrName] -> RnM ([LConDecl Name], FreeVars)
rnConDecls = mapFvRn (wrapLocFstM rnConDecl)
rnConDecl :: ConDecl RdrName -> RnM (ConDecl Name, FreeVars)
rnConDecl decl@(ConDeclH98 { con_name = name, con_qvars = qtvs
, con_cxt = mcxt, con_details = details
, con_doc = mb_doc })
= do { _ <- addLocM checkConName name
; new_name <- lookupLocatedTopBndrRn name
; let doc = ConDeclCtx [new_name]
; mb_doc' <- rnMbLHsDoc mb_doc
; (kvs, qtvs') <- get_con_qtvs (hsConDeclArgTys details)
; bindHsQTyVars doc (Just $ inHsDocContext doc) Nothing kvs qtvs' $
\new_tyvars _ -> do
{ (new_context, fvs1) <- case mcxt of
Nothing -> return (Nothing,emptyFVs)
Just lcxt -> do { (lctx',fvs) <- rnContext doc lcxt
; return (Just lctx',fvs) }
; (new_details, fvs2) <- rnConDeclDetails (unLoc new_name) doc details
; let (new_details',fvs3) = (new_details,emptyFVs)
; traceRn (text "rnConDecl" <+> ppr name <+> vcat
[ text "free_kvs:" <+> ppr kvs
, text "qtvs:" <+> ppr qtvs
, text "qtvs':" <+> ppr qtvs' ])
; let all_fvs = fvs1 `plusFV` fvs2 `plusFV` fvs3
new_tyvars' = case qtvs of
Nothing -> Nothing
Just _ -> Just new_tyvars
; return (decl { con_name = new_name, con_qvars = new_tyvars'
, con_cxt = new_context, con_details = new_details'
, con_doc = mb_doc' },
all_fvs) }}
where
cxt = maybe [] unLoc mcxt
get_rdr_tvs tys = extractHsTysRdrTyVars (cxt ++ tys)
get_con_qtvs :: [LHsType RdrName]
-> RnM ([Located RdrName], LHsQTyVars RdrName)
get_con_qtvs arg_tys
| Just tvs <- qtvs -- data T = forall a. MkT (a -> a)
= do { free_vars <- get_rdr_tvs arg_tys
; return (freeKiTyVarsKindVars free_vars, tvs) }
| otherwise -- data T = MkT (a -> a)
= return ([], mkHsQTvs [])
rnConDecl decl@(ConDeclGADT { con_names = names, con_type = ty
, con_doc = mb_doc })
= do { mapM_ (addLocM checkConName) names
; new_names <- mapM lookupLocatedTopBndrRn names
; let doc = ConDeclCtx new_names
; mb_doc' <- rnMbLHsDoc mb_doc
; (ty', fvs) <- rnHsSigType doc ty
; traceRn (text "rnConDecl" <+> ppr names <+> vcat
[ text "fvs:" <+> ppr fvs ])
; return (decl { con_names = new_names, con_type = ty'
, con_doc = mb_doc' },
fvs) }
rnConDeclDetails
:: Name
-> HsDocContext
-> HsConDetails (LHsType RdrName) (Located [LConDeclField RdrName])
-> RnM (HsConDetails (LHsType Name) (Located [LConDeclField Name]), FreeVars)
rnConDeclDetails _ doc (PrefixCon tys)
= do { (new_tys, fvs) <- rnLHsTypes doc tys
; return (PrefixCon new_tys, fvs) }
rnConDeclDetails _ doc (InfixCon ty1 ty2)
= do { (new_ty1, fvs1) <- rnLHsType doc ty1
; (new_ty2, fvs2) <- rnLHsType doc ty2
; return (InfixCon new_ty1 new_ty2, fvs1 `plusFV` fvs2) }
rnConDeclDetails con doc (RecCon (L l fields))
= do { fls <- lookupConstructorFields con
; (new_fields, fvs) <- rnConDeclFields doc fls fields
-- No need to check for duplicate fields
-- since that is done by RnNames.extendGlobalRdrEnvRn
; return (RecCon (L l new_fields), fvs) }
-------------------------------------------------
-- | Brings pattern synonym names and also pattern synonym selectors
-- from record pattern synonyms into scope.
extendPatSynEnv :: HsValBinds RdrName -> MiniFixityEnv
-> ([Name] -> TcRnIf TcGblEnv TcLclEnv a) -> TcM a
extendPatSynEnv val_decls local_fix_env thing = do {
names_with_fls <- new_ps val_decls
; let pat_syn_bndrs =
concat [name: map flSelector fields | (name, fields) <- names_with_fls]
; let avails = map patSynAvail pat_syn_bndrs
; (gbl_env, lcl_env) <-
extendGlobalRdrEnvRn avails local_fix_env
; let field_env' = extendNameEnvList (tcg_field_env gbl_env) names_with_fls
final_gbl_env = gbl_env { tcg_field_env = field_env' }
; setEnvs (final_gbl_env, lcl_env) (thing pat_syn_bndrs) }
where
new_ps :: HsValBinds RdrName -> TcM [(Name, [FieldLabel])]
new_ps (ValBindsIn binds _) = foldrBagM new_ps' [] binds
new_ps _ = panic "new_ps"
new_ps' :: LHsBindLR RdrName RdrName
-> [(Name, [FieldLabel])]
-> TcM [(Name, [FieldLabel])]
new_ps' bind names
| L bind_loc (PatSynBind (PSB { psb_id = L _ n
, psb_args = RecordPatSyn as })) <- bind
= do
bnd_name <- newTopSrcBinder (L bind_loc n)
let rnames = map recordPatSynSelectorId as
mkFieldOcc :: Located RdrName -> LFieldOcc RdrName
mkFieldOcc (L l name) = L l (FieldOcc (L l name) PlaceHolder)
field_occs = map mkFieldOcc rnames
flds <- mapM (newRecordSelector False [bnd_name]) field_occs
return ((bnd_name, flds): names)
| L bind_loc (PatSynBind (PSB { psb_id = L _ n})) <- bind
= do
bnd_name <- newTopSrcBinder (L bind_loc n)
return ((bnd_name, []): names)
| otherwise
= return names
{-
*********************************************************
* *
\subsection{Support code to rename types}
* *
*********************************************************
-}
rnFds :: [Located (FunDep (Located RdrName))]
-> RnM [Located (FunDep (Located Name))]
rnFds fds
= mapM (wrapLocM rn_fds) fds
where
rn_fds (tys1, tys2)
= do { tys1' <- rnHsTyVars tys1
; tys2' <- rnHsTyVars tys2
; return (tys1', tys2') }
rnHsTyVars :: [Located RdrName] -> RnM [Located Name]
rnHsTyVars tvs = mapM rnHsTyVar tvs
rnHsTyVar :: Located RdrName -> RnM (Located Name)
rnHsTyVar (L l tyvar) = do
tyvar' <- lookupOccRn tyvar
return (L l tyvar')
{-
*********************************************************
* *
findSplice
* *
*********************************************************
This code marches down the declarations, looking for the first
Template Haskell splice. As it does so it
a) groups the declarations into a HsGroup
b) runs any top-level quasi-quotes
-}
findSplice :: [LHsDecl RdrName] -> RnM (HsGroup RdrName, Maybe (SpliceDecl RdrName, [LHsDecl RdrName]))
findSplice ds = addl emptyRdrGroup ds
addl :: HsGroup RdrName -> [LHsDecl RdrName]
-> RnM (HsGroup RdrName, Maybe (SpliceDecl RdrName, [LHsDecl RdrName]))
-- This stuff reverses the declarations (again) but it doesn't matter
addl gp [] = return (gp, Nothing)
addl gp (L l d : ds) = add gp l d ds
add :: HsGroup RdrName -> SrcSpan -> HsDecl RdrName -> [LHsDecl RdrName]
-> RnM (HsGroup RdrName, Maybe (SpliceDecl RdrName, [LHsDecl RdrName]))
-- #10047: Declaration QuasiQuoters are expanded immediately, without
-- causing a group split
add gp _ (SpliceD (SpliceDecl (L _ qq@HsQuasiQuote{}) _)) ds
= do { (ds', _) <- rnTopSpliceDecls qq
; addl gp (ds' ++ ds)
}
add gp loc (SpliceD splice@(SpliceDecl _ flag)) ds
= do { -- We've found a top-level splice. If it is an *implicit* one
-- (i.e. a naked top level expression)
case flag of
ExplicitSplice -> return ()
ImplicitSplice -> do { th_on <- xoptM LangExt.TemplateHaskell
; unless th_on $ setSrcSpan loc $
failWith badImplicitSplice }
; return (gp, Just (splice, ds)) }
where
badImplicitSplice = text "Parse error: naked expression at top level"
$$ text "Perhaps you intended to use TemplateHaskell"
-- Class declarations: pull out the fixity signatures to the top
add gp@(HsGroup {hs_tyclds = ts, hs_fixds = fs}) l (TyClD d) ds
| isClassDecl d
= let fsigs = [ L l f | L l (FixSig f) <- tcdSigs d ] in
addl (gp { hs_tyclds = add_tycld (L l d) ts, hs_fixds = fsigs ++ fs}) ds
| otherwise
= addl (gp { hs_tyclds = add_tycld (L l d) ts }) ds
-- Signatures: fixity sigs go a different place than all others
add gp@(HsGroup {hs_fixds = ts}) l (SigD (FixSig f)) ds
= addl (gp {hs_fixds = L l f : ts}) ds
add gp@(HsGroup {hs_valds = ts}) l (SigD d) ds
= addl (gp {hs_valds = add_sig (L l d) ts}) ds
-- Value declarations: use add_bind
add gp@(HsGroup {hs_valds = ts}) l (ValD d) ds
= addl (gp { hs_valds = add_bind (L l d) ts }) ds
-- Role annotations: added to the TyClGroup
add gp@(HsGroup {hs_tyclds = ts}) l (RoleAnnotD d) ds
= addl (gp { hs_tyclds = add_role_annot (L l d) ts }) ds
-- The rest are routine
add gp@(HsGroup {hs_instds = ts}) l (InstD d) ds
= addl (gp { hs_instds = L l d : ts }) ds
add gp@(HsGroup {hs_derivds = ts}) l (DerivD d) ds
= addl (gp { hs_derivds = L l d : ts }) ds
add gp@(HsGroup {hs_defds = ts}) l (DefD d) ds
= addl (gp { hs_defds = L l d : ts }) ds
add gp@(HsGroup {hs_fords = ts}) l (ForD d) ds
= addl (gp { hs_fords = L l d : ts }) ds
add gp@(HsGroup {hs_warnds = ts}) l (WarningD d) ds
= addl (gp { hs_warnds = L l d : ts }) ds
add gp@(HsGroup {hs_annds = ts}) l (AnnD d) ds
= addl (gp { hs_annds = L l d : ts }) ds
add gp@(HsGroup {hs_ruleds = ts}) l (RuleD d) ds
= addl (gp { hs_ruleds = L l d : ts }) ds
add gp@(HsGroup {hs_vects = ts}) l (VectD d) ds
= addl (gp { hs_vects = L l d : ts }) ds
add gp l (DocD d) ds
= addl (gp { hs_docs = (L l d) : (hs_docs gp) }) ds
add_tycld :: LTyClDecl a -> [TyClGroup a] -> [TyClGroup a]
add_tycld d [] = [TyClGroup { group_tyclds = [d], group_roles = [] }]
add_tycld d (ds@(TyClGroup { group_tyclds = tyclds }):dss)
= ds { group_tyclds = d : tyclds } : dss
add_role_annot :: LRoleAnnotDecl a -> [TyClGroup a] -> [TyClGroup a]
add_role_annot d [] = [TyClGroup { group_tyclds = [], group_roles = [d] }]
add_role_annot d (tycls@(TyClGroup { group_roles = roles }) : rest)
= tycls { group_roles = d : roles } : rest
add_bind :: LHsBind a -> HsValBinds a -> HsValBinds a
add_bind b (ValBindsIn bs sigs) = ValBindsIn (bs `snocBag` b) sigs
add_bind _ (ValBindsOut {}) = panic "RdrHsSyn:add_bind"
add_sig :: LSig a -> HsValBinds a -> HsValBinds a
add_sig s (ValBindsIn bs sigs) = ValBindsIn bs (s:sigs)
add_sig _ (ValBindsOut {}) = panic "RdrHsSyn:add_sig"
| GaloisInc/halvm-ghc | compiler/rename/RnSource.hs | bsd-3-clause | 85,704 | 1 | 25 | 26,931 | 16,954 | 8,938 | 8,016 | 1,056 | 8 |
{-# LANGUAGE TemplateHaskell #-}
module AWS.EC2.Types.Image
( AMIAttribute(..)
, AMIAttributeDescription(..)
, BlockDeviceMapping(..)
, BlockDeviceMappingParam(..)
, EbsBlockDevice(..)
, EbsSource(..)
, Image(..)
, ImageState(..)
, ImageType(..)
, LaunchPermission(..)
, LaunchPermissionItem(..)
, ProductCodeItem(..)
, RegisterImageRequest(..)
) where
import AWS.EC2.Types.Common
import AWS.EC2.Types.Volume (VolumeType)
import AWS.Lib.FromText
data AMIAttribute
= AMIDescription
| AMIKernel
| AMIRamdisk
| AMILaunchPermission
| AMIProductCodes
| AMIBlockDeviceMapping
deriving (Show, Read, Eq)
data AMIAttributeDescription = AMIAttributeDescription
{ amiAttributeDescriptionImageId :: Text
, amiAttributeDescriptionLaunchPermission :: [LaunchPermissionItem]
, amiAttributeDescriptionProductCodes :: [ProductCodeItem]
, amiAttributeDescriptionKernel :: Maybe Text
, amiAttributeDescriptionRamdisk :: Maybe Text
, amiAttributeDescriptionDescription :: Maybe Text
, amiAttributeDescriptionBlockDeviceMapping :: [BlockDeviceMapping]
}
deriving (Show, Read, Eq)
data BlockDeviceMapping = BlockDeviceMapping
{ blockDeviceMappingDeviceName :: Text
, blockDeviceMappingVirtualName :: Maybe Text
, blockDeviceMappingEbs :: Maybe EbsBlockDevice
}
deriving (Show, Read, Eq)
data BlockDeviceMappingParam
= BlockDeviceMappingParamEbs
{ blockDeviceMappingParamEbsDeviceName :: Text
, blockDeviceMappingParamEbsNoDevice :: Maybe Bool
, blockDeviceMappingParamEbsSource :: EbsSource
, blockDeviceMappingParamEbsDeleteOnTermination
:: Maybe Bool
, blockDeviceMappingParamEbsVolumeType :: Maybe VolumeType
}
| BlockDeviceMappingParamInstanceStore
{ blockDeviceMappingParamInstanceStoreDeviceName :: Text
, blockDeviceMappingParamInstanceStoreNoDevice
:: Maybe Bool
, blockDeviceMappingParamInstanceStoreVirtualName
:: Maybe Text
}
deriving (Show, Read, Eq)
data EbsBlockDevice = EbsBlockDevice
{ ebsSnapshotId :: Maybe Text
, ebsVolumeSize :: Maybe Int
, ebsDeleteOnTermination :: Bool
, ebsVolumeType :: VolumeType
}
deriving (Show, Read, Eq)
data EbsSource
= EbsSourceSnapshotId Text
| EbsSourceVolumeSize Int
deriving (Show, Read, Eq)
data Image = Image
{ imageId :: Text
, imageLocation :: Text
, imageImageState :: ImageState
, imageOwnerId :: Text
, imageIsPublic :: Bool
, imageProductCodes :: [ProductCode]
, imageArchitecture :: Text
, imageImageType :: ImageType
, imageKernelId :: Maybe Text
, imageRamdiskId :: Maybe Text
, imagePlatform :: Platform
, imageStateReason :: Maybe StateReason
, imageViridianEnabled :: Maybe Bool
, imageOwnerAlias :: Maybe Text
, imageName :: Maybe Text
, imageDescription :: Maybe Text
, imageBillingProducts :: [Text]
, imageRootDeviceType :: RootDeviceType
, imageRootDeviceName :: Maybe Text
, imageBlockDeviceMappings :: [BlockDeviceMapping]
, imageVirtualizationType :: VirtualizationType
, imageTagSet :: [ResourceTag]
, imageHypervisor :: Hypervisor
}
deriving (Show, Read, Eq)
data ImageState
= ImageStateAvailable
| ImageStatePending
| ImageStateFailed
deriving (Show, Read, Eq)
data ImageType
= ImageTypeMachine
| ImageTypeKernel
| ImageTypeRamDisk
deriving (Show, Read, Eq)
data LaunchPermission = LaunchPermission
{ launchPermissionAdd :: [LaunchPermissionItem]
, launchPermissionRemove :: [LaunchPermissionItem]
}
deriving (Show, Read, Eq)
data LaunchPermissionItem
= LaunchPermissionItemGroup Text
| LaunchPermissionItemUserId Text
deriving (Show, Read, Eq)
data ProductCodeItem = ProductCodeItem
{ productCodeItemProductCode :: Text
}
deriving (Show, Read, Eq)
data RegisterImageRequest = RegisterImageRequest
{ registerImageRequestName :: Text
, registerImageRequestImageLocation :: Maybe Text
, registerImageRequestDescription :: Maybe Text
, registerImageRequestArchitecture :: Maybe Text
, registerImageRequestKernelId :: Maybe Text
, registerImageRequestRamdiskId :: Maybe Text
, registerImageRequestRootDeviceName :: Maybe Text
, registerImageRequestBlockDeviceMappings
:: [BlockDeviceMappingParam]
}
deriving (Show, Read, Eq)
deriveFromText "ImageState" ["available", "pending", "failed"]
deriveFromText "ImageType" ["machine", "kernel", "ramdisk"]
| IanConnolly/aws-sdk-fork | AWS/EC2/Types/Image.hs | bsd-3-clause | 4,613 | 0 | 9 | 956 | 953 | 571 | 382 | 124 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent.STM.TQueue
import Control.Concurrent.STM.TVar
import Control.Monad.IO.Class
import Control.Monad.STM
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (fromStrict)
import qualified Data.Map.Strict as M
import Data.UUID
import Network.HTTP.Types.Status
import System.Environment
import Web.Scotty
type QueueMapVar = TVar (M.Map UUID (TQueue ByteString))
-- | 'getUUID' parses the uuid parameter - looking in capture, then in form
-- data, then in query parameters - and parses it, failing with HTTP 400
-- ("Bad Request") on parse failure.
getUUID :: (UUID -> ActionM ()) -> ActionM ()
getUUID cont = param "uuid" >>= maybe invalidUUIDfailure cont . fromASCIIBytes
where
invalidUUIDfailure = do
status badRequest400
text "Invalid UUID"
-- | 'getAction' takes the next value from a queue and returns it with HTTP 200
-- ("OK"), or if the queue is empty or non-existent, returns nothing with HTTP
-- 204 ("No Content").
getAction :: QueueMapVar -> ActionM ()
getAction queuesRef = getUUID $ \uuid -> do
res <- liftIO . atomically $ do
queues <- readTVar queuesRef
maybe (return Nothing) tryReadTQueue $ M.lookup uuid queues
maybe (status noContent204) (raw . fromStrict) res
-- | 'postAction' adds a value in the form field "value" to a queue, creating
-- the queue if necessary, and then returns HTTP 200 ("OK").
postAction :: QueueMapVar -> ActionM ()
postAction queuesRef = getUUID $ \uuid -> do
value <- param "value"
liftIO . atomically $ do
queues <- readTVar queuesRef
case M.lookup uuid queues of
Nothing -> do
-- we have to make the queue!
queue <- newTQueue
writeTQueue queue value
let newQueues = M.insert uuid queue queues
writeTVar queuesRef newQueues
Just queue -> writeTQueue queue value
-- | 'deleteAction' deletes a queue, if it exists, and returns HTTP 200 ("OK").
deleteAction :: QueueMapVar -> ActionM ()
deleteAction queuesRef = getUUID $ \uuid ->
liftIO . atomically $ modifyTVar' queuesRef $ M.delete uuid
main :: IO ()
main = do
args <- getArgs
let port = case args of
[] -> 9123
[n] -> read n
queuesRef <- newTVarIO M.empty
scotty port $ do
get "/:uuid" $ getAction queuesRef
post "/:uuid" $ postAction queuesRef
delete "/:uuid" $ deleteAction queuesRef
| Taneb/webqueues | Main.hs | bsd-3-clause | 2,418 | 0 | 21 | 500 | 596 | 298 | 298 | 51 | 2 |
infin :: Double -> Double -> Double
infin 0 v = v
infin n v = infin (n-1) (v + 1/n)
main =
let x = infin 1000000000 0
in
putStrLn (show x)
| dterei/Scraps | haskell/infin.hs | bsd-3-clause | 145 | 4 | 9 | 39 | 91 | 45 | 46 | 6 | 1 |
{-# LANGUAGE DeriveLift #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-- | Provides the git revision which this was compiled from.
--
-- Stack builds will have the `git` command available to run during
-- compilation.
--
-- Nix builds will inject the git revision into the executables after
-- compiling. If the git revision has changed but the sources have
-- not, then no haskell packages will be rebuilt, but the embedded git
-- revision will be updated.
module Pos.Util.CompileInfo
( CompileTimeInfo (..)
, HasCompileInfo
, compileInfo
, withCompileInfo
, gitRev
) where
import Universum
import Data.FileEmbed (dummySpaceWith)
import Data.Reflection (Given (..), give, given)
import qualified Data.Text as T
import Formatting (bprint, stext, (%))
import qualified Formatting.Buildable
import Pos.Util.CompileInfoGit
-- | Data about the system that we want to retrieve in compile time.
data CompileTimeInfo = CompileTimeInfo
{ ctiGitRevision :: Text
} deriving (Show)
instance Buildable CompileTimeInfo where
build CompileTimeInfo{..} =
bprint ("Compile time info: git revision '"%stext%"'") ctiGitRevision
type HasCompileInfo = Given CompileTimeInfo
compileInfo :: HasCompileInfo => CompileTimeInfo
compileInfo = given
withCompileInfo :: (HasCompileInfo => r) -> r
withCompileInfo = give (CompileTimeInfo gitRev)
gitRev :: Text
gitRev | gitRevEmbed /= zeroRev = gitRevEmbed
| T.null fromGit = zeroRev
| otherwise = fromGit
where
-- Git revision embedded after compilation using
-- Data.FileEmbed.injectWith. If nothing has been injected,
-- this will be filled with 0 characters.
gitRevEmbed :: Text
gitRevEmbed = decodeUtf8 $(dummySpaceWith "gitrev" 40)
-- Git revision found during compilation by running git. If
-- git could not be run, then this will be empty.
fromGit = T.strip (fromString $(gitRevFromGit))
zeroRev :: Text
zeroRev = "0000000000000000000000000000000000000000"
| input-output-hk/pos-haskell-prototype | util/src/Pos/Util/CompileInfo.hs | mit | 2,208 | 0 | 11 | 524 | 329 | 194 | 135 | -1 | -1 |
f y@(x:xs)
| x > 10 = let z = [] in (z)
| otherwise = []
| itchyny/vim-haskell-indent | test/guard/top_of_line.in.hs | mit | 57 | 1 | 10 | 17 | 55 | 27 | 28 | -1 | -1 |
-- | Migration support for JSONs with schemaVersion 2 to 3
-- Migration changes:
-- 1. Change "schemaVersion" to 3
--
-- 2. Replace "OO" with {"Object": <TAG>}
-- and "Infix" with {"Infix": [<TAG>, <TAG>]}
-- (presentation modes now mention the special tags)
module Lamdu.Data.Export.JSON.Migration.ToVersion3 (migrate) where
import qualified Control.Lens as Lens
import Control.Lens.Extended ((~~>))
import qualified Data.Aeson as Aeson
import qualified Data.HashMap.Strict as HashMap
import Data.List.Class (sortOn)
import qualified Data.Vector as Vector
import qualified Lamdu.Data.Export.JSON.Migration.Common as Migration
import Lamdu.Prelude
migrateEntity :: Migration.TagMap -> Aeson.Value -> Either Text Aeson.Value
migrateEntity tagMap (Aeson.Object obj) =
obj ^. Lens.at "defPresentationMode" >>= mkNewPresMode mTags
& fromMaybe (Right obj)
<&> Aeson.Object
where
mkNewPresMode Nothing _ =
obj
& Lens.at "defPresentationMode" ?~ Aeson.String "Verbose"
& Right & Just
mkNewPresMode (Just tags) (Aeson.String s) | s == "OO" =
obj
& Lens.at "defPresentationMode" ?~
Aeson.Object ("Object" ~~> Aeson.String (head tags))
& Right & Just
mkNewPresMode (Just tags) (Aeson.String s) | s == "Infix" =
obj
& Lens.at "defPresentationMode" ?~
Aeson.Object ("Infix" ~~> (take 2 tags <&> Aeson.String & Vector.fromList & Aeson.Array))
& Right & Just
mkNewPresMode _ _ = Nothing
mTags = mRecordType <&> HashMap.keys <&> sortOn tagOrder
tagOrder t = tagMap ^. Lens.at t
mRecordType =
obj ^. Lens.at "typ"
>>= mObject
>>= (^. Lens.at "schemeType")
>>= mObject
>>= (^. Lens.at "funcParam")
>>= mObject
>>= (^. Lens.at "record")
>>= mObject
-- TODO: something like this must exist
mObject (Aeson.Object x) = Just x
mObject _ = Nothing
migrateEntity _ _ = Left "Expecting object"
migrate :: Aeson.Value -> Either Text Aeson.Value
migrate =
Migration.migrateToVer 3 $
\vals ->
do
tagMap <- traverse Migration.collectTags vals <&> (^. traverse)
traverse (migrateEntity tagMap) vals
| lamdu/lamdu | src/Lamdu/Data/Export/JSON/Migration/ToVersion3.hs | gpl-3.0 | 2,377 | 0 | 18 | 684 | 610 | 323 | 287 | 50 | 5 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hu-HU">
<title>Active Scan Rules | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | msrader/zap-extensions | src/org/zaproxy/zap/extension/ascanrules/resources/help_hu_HU/helpset_hu_HU.hs | apache-2.0 | 979 | 80 | 66 | 161 | 417 | 211 | 206 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hu-HU">
<title>Token Generator | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/tokengen/src/main/javahelp/org/zaproxy/zap/extension/tokengen/resources/help_hu_HU/helpset_hu_HU.hs | apache-2.0 | 977 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
------------------------------------------------------------------------------
--- Knowledge-based Autonomic Heterogeneous Networks (KAHN)
--- @author Rajesh Krishnan, Cosocket LLC
--- @version September 2014
------------------------------------------------------------------------------
{-
Copyright (c) 2014, Cosocket LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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.
* Neither the name of Cosocket LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
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.
-}
{-# LANGUAGE DeriveGeneric #-}
module KAHN.SysInit where
import System.IO
import System.ZMQ4.Monadic
import System.Posix.IO (createPipe, fdToHandle)
import Control.Monad (when,forever)
import Control.Concurrent (forkIO)
import KAHN.BB (bb)
import KAHN.KBI (toKB, fromKB, cmdKB)
import KAHN.MIMI (mimi)
import KAHN.PKTPROC (pktproc)
import KAHN.Config (configOpts,Config(cfgKBInitStr),saveConfigFile)
makePipePair :: IO (Handle,Handle,Handle,Handle)
makePipePair = do
(f1,f2) <- createPipe
(f3,f4) <- createPipe
h1 <- fdToHandle f1
h2 <- fdToHandle f2
h3 <- fdToHandle f3
h4 <- fdToHandle f4
return(h1,h4,h3,h2)
initSystemFromKB :: IO (Handle,Handle,Handle,Handle,String)
initSystemFromKB = do
(pSIn,pSOut,cSIn,cSOut) <- makePipePair
(pAIn,pAOut,cAIn,cAOut) <- makePipePair
kbInitstr <- startComponents (kbi cSIn cSOut cAIn cAOut) -- use kbshort for testing
return (pSIn,pSOut,pAIn,pAOut,kbInitstr)
startComponents :: (Config -> IO ()) -> IO (String)
startComponents kbCurry = do
cfg <- configOpts
--saveConfigFile "/tmp/kahn.conf" cfg
forkIO $ kbCurry cfg
return (cfgKBInitStr cfg)
kbi :: Handle -> Handle -> Handle -> Handle -> Config -> IO ()
kbi sI sO aI aO cfg = runZMQ $ do
async (bb cfg)
async (toKB aO cfg)
async (fromKB aI cfg)
async (cmdKB sI sO cfg)
async (mimi cfg)
async (pktproc cfg)
return ()
kbe :: Config -> IO ()
kbe cfg = runZMQ $ do
async (bb cfg)
async (mimi cfg)
async (pktproc cfg)
return ()
kbshort :: Handle -> Handle -> Handle -> Handle -> Config -> IO ()
kbshort sI sO aI aO cfg = (forkIO $ echo aI aO) >> echo sI sO
stdecho :: IO ()
stdecho = echo stdin stdout
echo :: Handle -> Handle -> IO ()
echo i o = hGetLine i >>= hPutStrLn o >> hFlush o >> echo i o
| Cosocket-LLC/kahn | v2.0/src/KAHN/SysInit.hs | bsd-3-clause | 3,638 | 0 | 11 | 692 | 760 | 391 | 369 | 53 | 1 |
-- Copyright 2016 TensorFlow authors.
--
-- 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 OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ViewPatterns #-}
module TensorFlow.Examples.MNIST.Parse where
import Control.Monad (when, liftM)
import Data.Binary.Get (Get, runGet, getWord32be, getLazyByteString)
import Data.ByteString.Lazy (toStrict, readFile)
import Data.List.Split (chunksOf)
import Data.Monoid ((<>))
import Data.ProtoLens (Message, decodeMessageOrDie)
import Data.Text (Text)
import Data.Word (Word8, Word32)
import Prelude hiding (readFile)
import qualified Codec.Compression.GZip as GZip
import qualified Data.ByteString.Lazy as L
import qualified Data.Text as Text
import qualified Data.Vector as V
-- | Utilities specific to MNIST.
type MNIST = V.Vector Word8
-- | Produces a unicode rendering of the MNIST digit sample.
drawMNIST :: MNIST -> Text
drawMNIST = chunk . block
where
block :: V.Vector Word8 -> Text
block (V.splitAt 1 -> ([0], xs)) = " " <> block xs
block (V.splitAt 1 -> ([n], xs)) = c `Text.cons` block xs
where c = "\9617\9618\9619\9608" !! fromIntegral (n `div` 64)
block (V.splitAt 1 -> _) = ""
chunk :: Text -> Text
chunk "" = "\n"
chunk xs = Text.take 28 xs <> "\n" <> chunk (Text.drop 28 xs)
-- | Check's the file's endianess, throwing an error if it's not as expected.
checkEndian :: Get ()
checkEndian = do
magic <- getWord32be
when (magic `notElem` ([2049, 2051] :: [Word32])) $
fail "Expected big endian, but image file is little endian."
-- | Reads an MNIST file and returns a list of samples.
readMNISTSamples :: FilePath -> IO [MNIST]
readMNISTSamples path = do
raw <- GZip.decompress <$> readFile path
return $ runGet getMNIST raw
where
getMNIST :: Get [MNIST]
getMNIST = do
checkEndian
-- Parse header data.
cnt <- liftM fromIntegral getWord32be
rows <- liftM fromIntegral getWord32be
cols <- liftM fromIntegral getWord32be
-- Read all of the data, then split into samples.
pixels <- getLazyByteString $ fromIntegral $ cnt * rows * cols
return $ V.fromList <$> chunksOf (rows * cols) (L.unpack pixels)
-- | Reads a list of MNIST labels from a file and returns them.
readMNISTLabels :: FilePath -> IO [Word8]
readMNISTLabels path = do
raw <- GZip.decompress <$> readFile path
return $ runGet getLabels raw
where getLabels :: Get [Word8]
getLabels = do
checkEndian
-- Parse header data.
cnt <- liftM fromIntegral getWord32be
-- Read all of the labels.
L.unpack <$> getLazyByteString cnt
readMessageFromFileOrDie :: Message m => FilePath -> IO m
readMessageFromFileOrDie path = do
pb <- readFile path
return $ decodeMessageOrDie $ toStrict pb
-- TODO: Write a writeMessageFromFileOrDie and read/write non-lethal
-- versions.
| judah/tensorflow-haskell | tensorflow-mnist/src/TensorFlow/Examples/MNIST/Parse.hs | apache-2.0 | 3,526 | 0 | 13 | 752 | 773 | 425 | 348 | 60 | 4 |
--
-- Copyright (c) 2014 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Vm.Monitor
( VmMonitor
, VmEvent(..), Handler, HandlerID
, react
, stopReacting
, removeDefaultEvents
, submitVmEvent
, evalVmEvent
, newVmMonitor
, ensureXenvm
, getMonitorError
)
where
import Control.Concurrent
import Control.Concurrent.Chan
import Control.Concurrent.MVar
import Control.Monad
import Control.Monad.Trans
import Data.List
import Data.IORef
import System.IO
import Tools.XenStore
import Tools.Log
import Tools.Misc
import Tools.Text
import Vm.Types
import Vm.State (stateFromStr)
import Vm.Queries
import Vm.ConfigWriter
import qualified XenMgr.Connect.Xenvm as Xenvm
import qualified XenMgr.Connect.GuestRpcAgent as RpcAgent
import XenMgr.Rpc
import XenMgr.Errors
type RtcOffset = String
data VmEvent
= VmStateChange !VmState
| VmAcpiStateChange !AcpiState
| VmRtcChange !RtcOffset
| VmRpcAgentStart | VmRpcAgentStop
| VmPvAddonsNodeChange | VmPvAddonsUninstallNodeChange
| VmBsgDevNodeChange
| VmMeasurementFailure !FilePath !Integer !Integer
deriving (Eq,Show)
data VmMonitor
= VmMonitor { vmm_uuid :: Uuid
, vmm_submit :: VmEvent -> IO ()
, vmm_events :: IO [VmEvent]
, vmm_handlers :: MVar [(HandlerID, Handler)]
, vmm_lasterr :: IORef (Maybe XmError)
}
type HandlerID = Int
type Handler = HandlerID -> VmEvent -> Rpc ()
react :: VmMonitor -> Handler -> Rpc HandlerID
react m handle = liftIO $ modifyMVar (vmm_handlers m) install where
install hs =
return ( hs ++ [(handler_id, handle)]
, handler_id )
where
handler_id = maximum_ . map fst $ hs
maximum_ [] = 0
maximum_ xs = maximum xs
stopReacting :: VmMonitor -> HandlerID -> Rpc ()
stopReacting m hid = liftIO $ modifyMVar_ (vmm_handlers m) remove where
remove = return . filter ((/= hid) . fst)
evalVmEvent :: VmMonitor -> VmEvent -> Rpc ()
evalVmEvent m e = do
ctx <- rpcGetContext
liftIO $ withMVar (vmm_handlers m)
$ mapM_ (runHandler ctx e)
where
runHandler ctx e (hid,handle) = status (vmm_lasterr m) =<< rpc ctx (handle hid e)
status err_mv (Left ex) = warn (show ex) >> writeIORef err_mv (Just ex)
status _ _ = return ()
getMonitorError :: VmMonitor -> Rpc (Maybe XmError)
getMonitorError m = liftIO (readIORef $ vmm_lasterr m)
newVmMonitor :: Uuid -> Rpc VmMonitor
newVmMonitor uuid =
do evch <- liftIO newChan
let submit = \x -> liftIO (writeChan evch x)
events = liftIO (getChanContents evch)
handlers <- liftIO (newMVar [])
lasterr <- liftIO (newIORef Nothing)
let m = VmMonitor {
vmm_uuid = uuid
, vmm_submit = submit
, vmm_events = events
, vmm_handlers = handlers
, vmm_lasterr = lasterr
}
-- attach event insertion + event loop
insertDefaultEvents m
ctx <- rpcGetContext
liftIO . forkIO $ status =<< rpc ctx (evloop m)
return m
where
status (Left ex) = warn $ "ERROR in evloop for " ++ show uuid ++ ": " ++ (show ex)
status _ = return ()
submitVmEvent :: VmMonitor -> VmEvent -> Rpc ()
submitVmEvent m e = liftIO $ (vmm_submit m) e
insertDefaultEvents :: VmMonitor -> Rpc ()
insertDefaultEvents m = let uuid = vmm_uuid m in do
Xenvm.onNotify uuid "rtc" whenRtc
Xenvm.onNotify uuid "vm" whenVm
Xenvm.onNotify uuid "power-state" whenPowerState
RpcAgent.onAgentStarted uuid (submit VmRpcAgentStart)
RpcAgent.onAgentUninstalled uuid (submit VmRpcAgentStop)
-- xenstore watches installed on domain creation/shutdown
watches <- liftIO . sequence $ watchesForVm (vmm_submit m)
insertWatchEvents m watches
where
submit e = liftIO (vmm_submit m e)
whenRtc (offset:_) = submit (VmRtcChange offset)
whenRtc _ = return ()
whenVm ("state":state_str:_) =
let state = stateFromStr state_str in
submit (VmStateChange state)
whenVm _ = return ()
whenPowerState (state_str:_) =
case maybeRead state_str of
Just state -> submit (VmAcpiStateChange state)
_ -> return ()
whenPowerState _ = return ()
--Chain some calls to eventually invoke removeMatch
removeDefaultEvents :: Uuid -> Rpc ()
removeDefaultEvents uuid = do
Xenvm.onNotifyRemove uuid "rtc" whenRtc
Xenvm.onNotifyRemove uuid "vm" whenVm
Xenvm.onNotifyRemove uuid "power-state" whenPowerState
--Need to undo the onAgent stuff to remove match rules
RpcAgent.onAgentStartedRemove uuid (submit VmRpcAgentStart)
RpcAgent.onAgentUninstalledRemove uuid (submit VmRpcAgentStop)
where --do nothing here on these handlers
submit _ = return ()
whenRtc _ = return ()
whenVm _ = return ()
whenPowerState _ = return ()
-- add watches on vm creation (or if already running), prune watches on vm destroy
insertWatchEvents :: VmMonitor -> [VmWatch] -> Rpc ()
insertWatchEvents m watches = do
-- if the vm is already running, add watches
running <- isRunning uuid
when running $ addWatches uuid watches
react m add_rem_watches
return ()
where
uuid = vmm_uuid m
add_rem_watches _ (VmStateChange Created ) = addWatches uuid watches
add_rem_watches _ (VmStateChange Shutdown) = remWatches watches
add_rem_watches _ (VmStateChange Rebooted) = remWatches watches
add_rem_watches _ _ = return ()
evloop :: VmMonitor -> Rpc ()
evloop m = mapM_ process =<< liftIO (vmm_events m) where
process e = evalVmEvent m e
-- make sure xenvm instance is up
ensureXenvm :: VmMonitor -> VmConfig -> Rpc Bool
ensureXenvm m cfg =
do up <- Xenvm.isXenvmUp uuid
if (not up) then do
info $ "starting xenvm instance for " ++ show uuid
writeXenvmConfig cfg
Xenvm.forkXenvm uuid
return True
else
return False
where
uuid = vmm_uuid m
data VmWatch = VmWatch { watch_path :: String
, watch_action :: IO ()
, watch_active :: MVar Bool
, watch_quit :: MVar Bool
, watch_thread :: MVar ThreadId }
newVmWatch :: String -> IO () -> IO VmWatch
newVmWatch path f =
newMVar False >>= \quit ->
newMVar False >>= \active ->
newEmptyMVar >>= \thread ->
return $ VmWatch path f active quit thread
killVmWatch :: VmWatch -> IO ()
killVmWatch (VmWatch _ _ active quit threadID) =
do active' <- takeMVar active
when active' $ do
modifyMVar_ quit $ \_ -> return True
id <- takeMVar threadID
killThread id
putMVar active False
addWatches :: Uuid -> [VmWatch] -> Rpc ()
addWatches uuid ws =
do remWatches ws
whenDomainID_ uuid $ \domid ->
do let vm_path = "/local/domain/" ++ show domid
liftIO $ mapM_ (add vm_path) ws
where
add vm_path (VmWatch path pred active quit thread_id) =
forkIO $ do
myThreadId >>= \id -> putMVar thread_id id
modifyMVar_ active (\_ -> return True)
modifyMVar_ quit (\_ -> return False)
xsWaitFor (vm_path++path) (pred >> readMVar quit)
remWatches :: [VmWatch] -> Rpc ()
remWatches ws = liftIO $ mapM_ killVmWatch ws
watchesForVm :: (VmEvent -> IO ()) -> [IO VmWatch]
watchesForVm submit =
[ newVmWatch "/attr/PVAddons" (submit VmPvAddonsNodeChange)
, newVmWatch "/attr/PVAddonsUninstalled" (submit VmPvAddonsUninstallNodeChange)
, newVmWatch "/bsgdev" (submit VmBsgDevNodeChange)
]
| jean-edouard/manager | xenmgr/Vm/Monitor.hs | gpl-2.0 | 8,422 | 0 | 15 | 2,214 | 2,330 | 1,166 | 1,164 | 197 | 5 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fa-IR">
<title>OpenAPI Support Add-on</title>
<maps>
<homeID>openapi</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/openapi/src/main/javahelp/org/zaproxy/zap/extension/openapi/resources/help_fa_IR/helpset_fa_IR.hs | apache-2.0 | 971 | 77 | 67 | 157 | 413 | 209 | 204 | -1 | -1 |
{-# LANGUAGE CPP, StandaloneDeriving, GeneralizedNewtypeDeriving #-}
-- |
-- Types for referring to remote objects in Remote GHCi. For more
-- details, see Note [External GHCi pointers] in compiler/ghci/GHCi.hs
--
-- For details on Remote GHCi, see Note [Remote GHCi] in
-- compiler/ghci/GHCi.hs.
--
module GHCi.RemoteTypes
( RemotePtr(..), toRemotePtr, fromRemotePtr, castRemotePtr
, HValue(..)
, RemoteRef, mkRemoteRef, localRef, freeRemoteRef
, HValueRef, toHValueRef
, ForeignRef, mkForeignRef, withForeignRef
, ForeignHValue
, unsafeForeignRefToRemoteRef, finalizeForeignRef
) where
import Control.DeepSeq
import Data.Word
import Foreign hiding (newForeignPtr)
import Foreign.Concurrent
import Data.Binary
import Unsafe.Coerce
import GHC.Exts
import GHC.ForeignPtr
-- -----------------------------------------------------------------------------
-- RemotePtr
-- Static pointers only; don't use this for heap-resident pointers.
-- Instead use HValueRef. We will fix the remote pointer to be 64 bits. This
-- should cover 64 and 32bit systems, and permits the exchange of remote ptrs
-- between machines of different word size. For exmaple, when connecting to
-- an iserv instance on a different architecture with different word size via
-- -fexternal-interpreter.
newtype RemotePtr a = RemotePtr Word64
toRemotePtr :: Ptr a -> RemotePtr a
toRemotePtr p = RemotePtr (fromIntegral (ptrToWordPtr p))
fromRemotePtr :: RemotePtr a -> Ptr a
fromRemotePtr (RemotePtr p) = wordPtrToPtr (fromIntegral p)
castRemotePtr :: RemotePtr a -> RemotePtr b
castRemotePtr (RemotePtr a) = RemotePtr a
deriving instance Show (RemotePtr a)
deriving instance Binary (RemotePtr a)
deriving instance NFData (RemotePtr a)
-- -----------------------------------------------------------------------------
-- HValueRef
newtype HValue = HValue Any
instance Show HValue where
show _ = "<HValue>"
-- | A reference to a remote value. These are allocated and freed explicitly.
newtype RemoteRef a = RemoteRef (RemotePtr ())
deriving (Show, Binary)
-- We can discard type information if we want
toHValueRef :: RemoteRef a -> RemoteRef HValue
toHValueRef = unsafeCoerce
-- For convenience
type HValueRef = RemoteRef HValue
-- | Make a reference to a local value that we can send remotely.
-- This reference will keep the value that it refers to alive until
-- 'freeRemoteRef' is called.
mkRemoteRef :: a -> IO (RemoteRef a)
mkRemoteRef a = do
sp <- newStablePtr a
return $! RemoteRef (toRemotePtr (castStablePtrToPtr sp))
-- | Convert an HValueRef to an HValue. Should only be used if the HValue
-- originated in this process.
localRef :: RemoteRef a -> IO a
localRef (RemoteRef w) =
deRefStablePtr (castPtrToStablePtr (fromRemotePtr w))
-- | Release an HValueRef that originated in this process
freeRemoteRef :: RemoteRef a -> IO ()
freeRemoteRef (RemoteRef w) =
freeStablePtr (castPtrToStablePtr (fromRemotePtr w))
-- | An HValueRef with a finalizer
newtype ForeignRef a = ForeignRef (ForeignPtr ())
instance NFData (ForeignRef a) where
rnf x = x `seq` ()
type ForeignHValue = ForeignRef HValue
-- | Create a 'ForeignRef' from a 'RemoteRef'. The finalizer
-- should arrange to call 'freeHValueRef' on the 'HValueRef'. (since
-- this function needs to be called in the process that created the
-- 'HValueRef', it cannot be called directly from the finalizer).
mkForeignRef :: RemoteRef a -> IO () -> IO (ForeignRef a)
mkForeignRef (RemoteRef hvref) finalizer =
ForeignRef <$> newForeignPtr (fromRemotePtr hvref) finalizer
-- | Use a 'ForeignHValue'
withForeignRef :: ForeignRef a -> (RemoteRef a -> IO b) -> IO b
withForeignRef (ForeignRef fp) f =
withForeignPtr fp (f . RemoteRef . toRemotePtr)
unsafeForeignRefToRemoteRef :: ForeignRef a -> RemoteRef a
unsafeForeignRefToRemoteRef (ForeignRef fp) =
RemoteRef (toRemotePtr (unsafeForeignPtrToPtr fp))
finalizeForeignRef :: ForeignRef a -> IO ()
finalizeForeignRef (ForeignRef fp) = finalizeForeignPtr fp
| ezyang/ghc | libraries/ghci/GHCi/RemoteTypes.hs | bsd-3-clause | 3,990 | 0 | 12 | 621 | 791 | 425 | 366 | 60 | 1 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Config.Gnome
-- Copyright : (c) Spencer Janssen <spencerjanssen@gmail.com>
-- License : BSD
--
-- Maintainer : Spencer Janssen <spencerjanssen@gmail.com>
-- Stability : unstable
-- Portability : unportable
--
-- This module provides a config suitable for use with the GNOME desktop
-- environment.
module XMonad.Config.Gnome (
-- * Usage
-- $usage
gnomeConfig,
gnomeRun,
gnomeRegister
) where
import XMonad
import XMonad.Config.Desktop
import XMonad.Util.Run (safeSpawn)
import qualified Data.Map as M
import System.Environment (getEnvironment)
-- $usage
-- To use this module, start with the following @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad
-- > import XMonad.Config.Gnome
-- >
-- > main = xmonad gnomeConfig
--
-- For examples of how to further customize @gnomeConfig@ see "XMonad.Config.Desktop".
gnomeConfig = desktopConfig
{ terminal = "gnome-terminal"
, keys = gnomeKeys <+> keys desktopConfig
, startupHook = gnomeRegister >> startupHook desktopConfig }
gnomeKeys (XConfig {modMask = modm}) = M.fromList $
[ ((modm, xK_p), gnomeRun)
, ((modm .|. shiftMask, xK_q), spawn "gnome-session-save --kill") ]
-- | Launch the "Run Application" dialog. gnome-panel must be running for this
-- to work.
gnomeRun :: X ()
gnomeRun = withDisplay $ \dpy -> do
rw <- asks theRoot
gnome_panel <- getAtom "_GNOME_PANEL_ACTION"
panel_run <- getAtom "_GNOME_PANEL_ACTION_RUN_DIALOG"
io $ allocaXEvent $ \e -> do
setEventType e clientMessage
setClientMessageEvent e rw gnome_panel 32 panel_run 0
sendEvent dpy rw False structureNotifyMask e
sync dpy False
-- | Register xmonad with gnome. 'dbus-send' must be in the $PATH with which
-- xmonad is started.
--
-- This action reduces a delay on startup only only if you have configured
-- gnome-session>=2.26: to start xmonad with a command as such:
--
-- > gconftool-2 -s /desktop/gnome/session/required_components/windowmanager xmonad --type string
gnomeRegister :: MonadIO m => m ()
gnomeRegister = io $ do
x <- lookup "DESKTOP_AUTOSTART_ID" `fmap` getEnvironment
whenJust x $ \sessionId -> safeSpawn "dbus-send"
["--session"
,"--print-reply=string"
,"--dest=org.gnome.SessionManager"
,"/org/gnome/SessionManager"
,"org.gnome.SessionManager.RegisterClient"
,"string:xmonad"
,"string:"++sessionId]
| markus1189/xmonad-contrib-710 | XMonad/Config/Gnome.hs | bsd-3-clause | 2,616 | 0 | 13 | 538 | 394 | 227 | 167 | 38 | 1 |
{-# LANGUAGE RecordWildCards #-}
-- | This module provides the ability to create reapers: dedicated cleanup
-- threads. These threads will automatically spawn and die based on the
-- presence of a workload to process on.
module Control.Reaper (
-- * Settings
ReaperSettings
, defaultReaperSettings
-- * Accessors
, reaperAction
, reaperDelay
, reaperCons
, reaperNull
, reaperEmpty
-- * Type
, Reaper(..)
-- * Creation
, mkReaper
-- * Helper
, mkListAction
) where
import Control.AutoUpdate.Util (atomicModifyIORef')
import Control.Concurrent (forkIO, threadDelay)
import Control.Exception (mask_)
import Control.Monad (join, void)
import Data.IORef (IORef, newIORef, readIORef)
-- | Settings for creating a reaper. This type has two parameters:
-- @workload@ gives the entire workload, whereas @item@ gives an
-- individual piece of the queue. A common approach is to have @workload@
-- be a list of @item@s. This is encouraged by 'defaultReaperSettings' and
-- 'mkListAction'.
--
-- Since 0.1.1
data ReaperSettings workload item = ReaperSettings
{ reaperAction :: workload -> IO (workload -> workload)
-- ^ The action to perform on a workload. The result of this is a
-- \"workload modifying\" function. In the common case of using lists,
-- the result should be a difference list that prepends the remaining
-- workload to the temporary workload. For help with setting up such
-- an action, see 'mkListAction'.
--
-- Default: do nothing with the workload, and then prepend it to the
-- temporary workload. This is incredibly useless; you should
-- definitely override this default.
--
-- Since 0.1.1
, reaperDelay :: {-# UNPACK #-} !Int
-- ^ Number of microseconds to delay between calls of 'reaperAction'.
--
-- Default: 30 seconds.
--
-- Since 0.1.1
, reaperCons :: item -> workload -> workload
-- ^ Add an item onto a workload.
--
-- Default: list consing.
--
-- Since 0.1.1
, reaperNull :: workload -> Bool
-- ^ Check if a workload is empty, in which case the worker thread
-- will shut down.
--
-- Default: 'null'.
--
-- Since 0.1.1
, reaperEmpty :: workload
-- ^ An empty workload.
--
-- Default: empty list.
--
-- Since 0.1.1
}
-- | Default @ReaperSettings@ value, biased towards having a list of work
-- items.
--
-- Since 0.1.1
defaultReaperSettings :: ReaperSettings [item] item
defaultReaperSettings = ReaperSettings
{ reaperAction = \wl -> return (wl ++)
, reaperDelay = 30000000
, reaperCons = (:)
, reaperNull = null
, reaperEmpty = []
}
-- | A data structure to hold reaper APIs.
data Reaper workload item = Reaper {
-- | Adding an item to the workload
reaperAdd :: item -> IO ()
-- | Reading workload.
, reaperRead :: IO workload
-- | Stopping the reaper thread if exists.
-- The current workload is returned.
, reaperStop :: IO workload
}
-- | State of reaper.
data State workload = NoReaper -- ^ No reaper thread
| Workload workload -- ^ The current jobs
-- | Create a reaper addition function. This funciton can be used to add
-- new items to the workload. Spawning of reaper threads will be handled
-- for you automatically.
--
-- Since 0.1.1
mkReaper :: ReaperSettings workload item -> IO (Reaper workload item)
mkReaper settings@ReaperSettings{..} = do
stateRef <- newIORef NoReaper
return Reaper {
reaperAdd = update settings stateRef
, reaperRead = readRef stateRef
, reaperStop = stop stateRef
}
where
readRef stateRef = do
mx <- readIORef stateRef
case mx of
NoReaper -> return reaperEmpty
Workload wl -> return wl
stop stateRef = atomicModifyIORef' stateRef $ \mx ->
case mx of
NoReaper -> (NoReaper, reaperEmpty)
Workload x -> (Workload reaperEmpty, x)
update :: ReaperSettings workload item -> IORef (State workload) -> item
-> IO ()
update settings@ReaperSettings{..} stateRef item =
mask_ $ join $ atomicModifyIORef' stateRef cons
where
cons NoReaper = (Workload $ reaperCons item reaperEmpty
,spawn settings stateRef)
cons (Workload wl) = (Workload $ reaperCons item wl
,return ())
spawn :: ReaperSettings workload item -> IORef (State workload) -> IO ()
spawn settings stateRef = void . forkIO $ reaper settings stateRef
reaper :: ReaperSettings workload item -> IORef (State workload) -> IO ()
reaper settings@ReaperSettings{..} stateRef = do
threadDelay reaperDelay
-- Getting the current jobs. Push an empty job to the reference.
wl <- atomicModifyIORef' stateRef swapWithEmpty
-- Do the jobs. A function to merge the left jobs and
-- new jobs is returned.
merge <- reaperAction wl
-- Merging the left jobs and new jobs.
-- If there is no jobs, this thread finishes.
join $ atomicModifyIORef' stateRef (check merge)
where
swapWithEmpty NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (1)"
swapWithEmpty (Workload wl) = (Workload reaperEmpty, wl)
check _ NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (2)"
check merge (Workload wl)
-- If there is no job, reaper is terminated.
| reaperNull wl' = (NoReaper, return ())
-- If there are jobs, carry them out.
| otherwise = (Workload wl', reaper settings stateRef)
where
wl' = merge wl
-- | A helper function for creating 'reaperAction' functions. You would
-- provide this function with a function to process a single work item and
-- return either a new work item, or @Nothing@ if the work item is
-- expired.
--
-- Since 0.1.1
mkListAction :: (item -> IO (Maybe item'))
-> [item]
-> IO ([item'] -> [item'])
mkListAction f =
go id
where
go front [] = return front
go front (x:xs) = do
my <- f x
let front' =
case my of
Nothing -> front
Just y -> front . (y:)
go front' xs
| jberryman/wai | auto-update/Control/Reaper.hs | mit | 6,237 | 0 | 16 | 1,666 | 1,117 | 619 | 498 | 88 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
import Control.Applicative ((<$>), (<*>), empty)
import Data.Aeson
import GHC.Generics (Generic)
import Control.Monad (mzero)
import Data.Text (Text)
import Data.Scientific (Scientific)
import Data.ByteString.Lazy (ByteString)
data Adres = Adres { straat :: String
, huisnr :: Int
, stad :: String
, land :: String
} deriving (Show, Generic)
instance FromJSON Adres where
parseJSON (Object v) = Adres <$> v .: "street"
<*> v .: "no"
<*> v .: "city"
<*> v .: "country"
parseJSON _ = mzero
instance ToJSON Adres
data Person = Person { naam :: String
, leeftijd :: Int
, lustPizza :: Bool
, lotto :: [Int]
, woorden :: [String]
, adres :: [Adres]
, type_ :: Int
} deriving (Show)
instance FromJSON Person where
parseJSON (Object v) = Person <$> v .: "name"
<*> v .: "age"
<*> v .: "likespizza"
<*> v .: "lottonumbers"
<*> v .: "passphrase"
<*> v .: "addresses"
<*> v .: "type"
parseJSON _ = mzero
instance ToJSON Person where
toJSON (Person naam leeftijd lustPizza lotto woorden adres type_) =
object [ "name" .= naam
, "age" .= leeftijd
, "likespizza" .= lustPizza
, "lottonumbers" .= lotto
, "passphrase" .= woorden
, "addresses" .= adres
, "type" .= type_
]
-- Using {-# LANGUAGE DeriveGeneric #-} allows us to use
-- instance FromJSON Person
-- instance ToJSON Person
-- I haven't used it here because "type" is a haskell keyword.
--
-------------------- Being ------------------------
data Being = Human { name :: String
, age:: Int
} |
Animal { species :: String
, herbivor :: Bool
, age :: Int
} deriving Show
--instance FromJSON Being where
-- parseJSON (Object v) = Being
-------------------- Coordinates ------------------------
data Coord = Coord { x :: Double
, y :: Double
} deriving (Show)
instance FromJSON Coord where
parseJSON (Object v) = Coord <$>
v .: "x" <*>
v .: "y"
parseJSON _ = empty
instance ToJSON Coord where
toJSON (Coord xV yV) = object [ "x" .= xV,
"y" .= yV ]
-- toEncoding Coord{..} = pairs $
-- "x" .= x <>
-- "y" .= y
| iambernie/tryhaskell | aesonexamples/aesonex.hs | mit | 3,085 | 0 | 19 | 1,391 | 606 | 347 | 259 | 65 | 0 |
module Chess.BoardSpec where
import qualified Data.List.Safe as SL
import Data.Maybe (isNothing)
import Test.Hspec
import Test.QuickCheck
import Chess.Board
spec :: Spec
spec = do
describe "validPosition" $ do
it "returns True when given a valid position" $
all validPosition [(f, r) | f <- ['a'..'h'], r <- [1..8]] `shouldBe` True
it "returns False when given an invalid position" $ property $
\p@(f, r) -> ((f `notElem` ['a'..'h']) || (r `notElem` [1..8])) ==> not $ validPosition p
describe "fileIndex" $ do
it "returns correct index when given a valid file" $
[fileIndex f | f <- ['a'..'h']] `shouldBe` map Just [0..7]
it "returns Nothing when given an invalid file" $ property $
\f -> (f `notElem` ['a'..'h']) ==> isNothing $ fileIndex f
describe "rankIndex" $ do
it "returns correct index when given a valid rank" $
[rankIndex r | r <- [1..8]] `shouldBe` map Just [7, 6..0]
it "returns Nothing when given an invalid rank" $ property $
\r -> (r `notElem` [1..8]) ==> isNothing $ rankIndex r
describe "square" $
it "returns correct square for a given position" $
map (square board) (zip ['a'..'h'] [8,7..1]) `shouldBe` sqs
describe "rank" $ do
it "returns Nothing when given an invalid index" $ property $
\i -> (i `notElem` [1..8]) ==> isNothing $ rank board i
it "returns correct rank when given a valid index" $
[rank board r | r <- [1..8]] `shouldBe` map Just (reverse board)
describe "file" $ do
it "returns Nothing when given an invalid file" $ property $
\c -> (c `notElem` ['a'..'h']) ==> isNothing $ file board c
it "returns correct file when given a valid index" $
[file board f | f <- ['a'..'h']] `shouldBe` map Just (SL.transpose board)
sqs :: [Square]
sqs = [ Just $ Piece White King
, Just $ Piece White Queen
, Just $ Piece White Rook
, Just $ Piece White Bishop
, Just $ Piece Black Bishop
, Just $ Piece Black Rook
, Just $ Piece Black Queen
, Just $ Piece Black King
]
board :: Board
board = [ [sqs !! 0] ++ replicate 7 Nothing
, replicate 1 Nothing ++ [sqs !! 1] ++ replicate 6 Nothing
, replicate 2 Nothing ++ [sqs !! 2] ++ replicate 5 Nothing
, replicate 3 Nothing ++ [sqs !! 3] ++ replicate 4 Nothing
, replicate 4 Nothing ++ [sqs !! 4] ++ replicate 3 Nothing
, replicate 5 Nothing ++ [sqs !! 5] ++ replicate 2 Nothing
, replicate 6 Nothing ++ [sqs !! 6] ++ replicate 1 Nothing
, replicate 7 Nothing ++ [sqs !! 7]
]
| samgd/Chess | test/Chess/BoardSpec.hs | mit | 2,738 | 0 | 18 | 826 | 981 | 509 | 472 | 54 | 1 |
-- author: Benjamin Surma <benjamin.surma@gree.net>
{-# LANGUAGE DeriveGeneric #-}
module Main.Internals where
import Test.Sandbox hiding (sendTo)
import qualified Test.Sandbox (sendTo)
import Test.Sandbox.HUnit
import Test.Framework.Providers.Sandbox
import Control.Monad
import Data.List
import Data.Serialize
import GHC.Conc
import GHC.Generics (Generic)
import System.Directory
import System.FilePath
import System.Random
import Paths_flare_tests (getBinDir)
setup :: Sandbox ()
setup = setupWithPath Nothing
setupWithPath :: Maybe FilePath -> Sandbox ()
setupWithPath binDir = do
-- Register index server
rootDir <- liftIO getFlareRoot
let flareiBin = case (binDir, rootDir) of
(Just v, _) -> v </> "flarei"
(_, Just v) -> v </> "src" </> "flarei" </> "flarei"
(_, Nothing) -> "/usr" </> "local" </> "bin" </> "flarei"
dataDir <- getDataDir
flareiPort <- getPort "flarei"
register "flarei" flareiBin [ "--data-dir", dataDir
, "--server-name", "localhost"
, "--server-port", show flareiPort
, "--monitor-interval", "1"
, "--monitor-threshold", "2"
] def
-- Register daemons
let flaredBin = case (binDir, rootDir) of
(Just v, _) -> v </> "flared"
(_, Just v) -> v </> "src" </> "flared" </> "flared"
(_, Nothing) -> "/usr" </> "local" </> "bin" </> "flared"
setVariable "flared_bin" flaredBin
daemons <- setVariable "daemons" [ FlareDaemon 0 Master
, FlareDaemon 0 (Slave 0)
, FlareDaemon 0 (Slave 1)
, FlareDaemon 1 Master
, FlareDaemon 1 (Slave 0)
, FlareDaemon 1 (Slave 1)
, FlareDaemon 2 Master
, FlareDaemon 2 (Slave 0)
, FlareDaemon 2 (Slave 1) ]
mapM_ registerDaemon daemons
startAll
liftIO $ threadDelay 1000000
data FlareRole = Master
| Slave Int
deriving (Show, Generic)
instance Serialize FlareRole
data FlareDaemon = FlareDaemon {
fdPartition :: Int
, fdRole :: FlareRole }
deriving (Show, Generic)
instance Serialize FlareDaemon
fdId :: FlareDaemon -> String
fdId fd = case fdRole fd of
Master -> "Partition_" ++ show (fdPartition fd) ++ "_Master"
Slave i -> "Partition_" ++ show (fdPartition fd) ++ "_Slave_" ++ show i
registerDaemon :: FlareDaemon -> Sandbox ()
registerDaemon fd = do
dir <- getDataDir >>= (\d -> return $ d </> fdId fd)
liftIO $ createDirectory dir
bin <- getVariable "flared_bin" "flared"
flareiPort <- getPort "flarei"
port <- getPort (fdId fd)
void $ register (fdId fd) bin [ "--data-dir", dir
, "--index-server-name", "localhost"
, "--index-server-port", show flareiPort
, "--replication-type", "sync"
, "--server-name", "localhost"
, "--server-port", show port
] def { psWait = Nothing }
normalize :: String -> String
normalize = unlines . sort . lines
withTimeout :: Int -> Sandbox () -> Sandbox ()
withTimeout = withVariable "timeout"
sendTo :: String -> String -> Sandbox String
sendTo program input = do
timeout <- getVariable "timeout" 250
Test.Sandbox.sendTo program input timeout
sendToDaemon :: String -> Sandbox String
sendToDaemon input = do
daemons <- getVariable "daemons" [] :: Sandbox [FlareDaemon]
i <- liftIO randomIO :: Sandbox Int
let fd = daemons !! (i `mod` length daemons)
sendTo (fdId fd) input
assertSendTo :: String -> String -> String -> Sandbox ()
assertSendTo program input output =
assertEqual input output =<< sendTo program input
assertSendToDaemon :: String -> String -> Sandbox ()
assertSendToDaemon input output =
assertEqual input output =<< sendToDaemon input
getStat :: String -> FlareDaemon -> Sandbox String
getStat key fd = do
stats <- sendTo (fdId fd) "stats\r\n"
case find (key `isInfixOf`) $ lines stats of
Nothing -> throwError $ "STAT " ++ key ++ " not found."
Just stat -> return $ drop (length $ "STAT " ++ key ++ " ") stat
setupFlareDaemon :: FlareDaemon -> Sandbox ()
setupFlareDaemon fd = do
yieldProgress $ "Setting up " ++ fdId fd
port <- getPort (fdId fd)
let hpId = "localhost " ++ show port
case fdRole fd of
Master -> void $ assertSendTo "flarei" ("node role " ++ hpId ++ " master 1 " ++ show (fdPartition fd) ++ "\r\n") "OK\r\n"
Slave _ -> void $ assertSendTo "flarei" ("node role " ++ hpId ++ " slave 0 " ++ show (fdPartition fd) ++ "\r\n") "OK\r\n"
void $ assertSendTo "flarei" ("node state " ++ hpId ++ " active\r\n") "OK\r\n"
case fdRole fd of
Slave _ -> void $ assertSendTo "flarei" ("node role " ++ hpId ++ " slave 1 " ++ show (fdPartition fd) ++ "\r\n") "OK\r\n"
_ -> return ()
setupFlareCluster :: Sandbox ()
setupFlareCluster = withTimeout 1000 $ do
daemons <- getVariable "daemons" [] :: Sandbox [FlareDaemon]
mapM_ setupFlareDaemon daemons
yieldProgress "Wait 2s"
liftIO $ threadDelay 2000000
getFlareRoot :: IO (Maybe FilePath)
getFlareRoot = do
binDir <- getBinDir
cs <- getRootCandidates
cs' <- filterM isFlareRoot cs
case cs' of
c:_ -> return $ Just (c </> "flare")
_ -> return Nothing
getRootCandidates :: IO [FilePath]
getRootCandidates = do
bindir <- getBinDir
cwd <- getCurrentDirectory
return [ cwd
, takeDirectories 2 bindir
, takeDirectories 3 bindir
]
isFlareRoot :: FilePath -> IO Bool
isFlareRoot baseDir =
doesDirectoryExist $ baseDir </> "flare"
takeDirectories :: Int -> FilePath -> FilePath
takeDirectories n p =
if n <= 0 then p else iterate takeDirectory p !! (n - 1)
| gree/flare-tests | src/Main/Internals.hs | mit | 6,048 | 0 | 17 | 1,754 | 1,822 | 909 | 913 | 141 | 5 |
-- Example of an drawing graphics onto a canvas.
import Graphics.UI.Gtk
import Graphics.Rendering.Cairo
import Control.Monad.Trans ( liftIO )
import Graphics.UI.Gtk.Gdk.EventM
run :: Render () -> IO ()
run act = do
initGUI
dia <- dialogNew
dialogAddButton dia stockClose ResponseClose
contain <- dialogGetUpper dia
canvas <- drawingAreaNew
canvas `onSizeRequest` return (Requisition 250 250)
canvas `on` exposeEvent $ tryEvent $ updateCanvas canvas act
boxPackStartDefaults contain canvas
widgetShow canvas
dialogRun dia
widgetDestroy dia
-- Flush all commands that are waiting to be sent to the graphics server.
-- This ensures that the window is actually closed before ghci displays the
-- prompt again.
flush
where updateCanvas :: DrawingArea -> Render () -> EventM EExpose ()
updateCanvas canvas act = liftIO $ do
win <- widgetGetDrawWindow canvas
renderWithDrawable win act
setRed :: Render ()
setRed = do
setSourceRGB 1 0 0
setFat :: Render ()
setFat = do
setLineWidth 20
setLineCap LineCapRound
drawSquare :: Double -> Double -> Render ()
drawSquare width height = do
(x,y) <- getCurrentPoint
lineTo (x+width) y
lineTo (x+width) (y+height)
lineTo x (y+height)
closePath
stroke
drawHCirc :: Double -> Double -> Double -> Render ()
drawHCirc x y radius = do
arc x y radius 0 pi
stroke
drawStr :: String -> Render ()
drawStr txt = do
lay <- createLayout txt
showLayout lay
drawStr_ :: String -> Render ()
drawStr_ txt = do
lay <- liftIO $ do
ctxt <- cairoCreateContext Nothing
descr <- contextGetFontDescription ctxt
descr `fontDescriptionSetSize` 20
ctxt `contextSetFontDescription` descr
layoutText ctxt txt
showLayout lay | SwiftsNamesake/ElegantChess | Cairo.hs | mit | 1,756 | 0 | 12 | 375 | 555 | 263 | 292 | 54 | 1 |
module XorBool where
xorBool :: Bool -> Bool -> Bool
xorBool left right = (left || right) && (not (left && right))
xorPair :: (Bool, Bool) -> Bool
xorPair (x, y) = xorBool x y
xor :: [Bool] -> [Bool] -> [Bool]
xor xs ys = map xorPair (zip xs ys)
type Bits = [Bool]
intToBits' :: Int -> Bits
intToBits' 0 = [False]
intToBits' 1 = [True]
intToBits' n = if remainder == 0
then False : intToBits' nextVal
else True : intToBits' nextVal
where
remainder = n `mod` 2
nextVal = n `div` 2
maxBits :: Int
maxBits = length (intToBits' maxBound)
intToBits :: Int -> Bits
intToBits n = leadingFalses ++ reversedBits
where reversedBits = reverse (intToBits' n)
missingBits = maxBits - (length reversedBits)
leadingFalses = take missingBits (cycle [False])
charToBits :: Char -> Bits
charToBits char = intToBits (fromEnum char)
-- To understand this,
-- it’s helpful to realize that
-- binary 101 in decimal is 1*2^2 + 0*2^1 + 1*2^0.
-- Because the only two values are 1 or 0,
-- you take the sum of those nonzero powers.
-- indices thing works like this:
-- [9,8..0] = [9,8,7,6,5,4,3,2,1,0]
bitsToInt :: Bits -> Int
bitsToInt bits = sum (map (\x -> 2^(snd x)) trueLocations)
where size = length bits
indices = [size-1, size-2 .. 0]
trueLocations = filter (\x -> fst x == True) (zip bits indices)
bitsToChars :: Bits -> Char
bitsToChars bits = toEnum (bitsToInt bits)
myPad :: String
myPad = "MY_SUPER_KEY_YOU_WILL_NEVER_KNOW"
myPlainText :: String
myPlainText = "My plain text you will never decipher"
applyOTP' :: String -> String -> [Bits]
applyOTP' pad text = map (\pair -> (fst pair) `xor` (snd pair)) (zip padBits textBits)
where padBits = map charToBits pad
textBits = map charToBits text
-- If we apply this function to the function to short pad and long text
-- we'll get a shorten pad, which is very bad or should I say inacceptable.
applyOTP :: String -> String -> String
applyOTP pad text = map bitsToChars bitList
where bitList = applyOTP' pad text
-- Let's wrap everything in typeclass
class Cipher a where
encode :: a -> String -> String
decode :: a -> String -> String
-- OneTimePad cipher
data OneTimePad = OTP String
instance Cipher OneTimePad where
encode (OTP pad) text = applyOTP pad text
decode (OTP pad) text = applyOTP pad text
myOTP :: OneTimePad
myOTP = OTP (cycle [minBound .. maxBound])
-- Linear congruential generator
-- https://en.wikipedia.org/wiki/Linear_congruential_generator
prng :: Int -> Int -> Int -> Int -> Int
prng a b maxNumber seed = (a * seed + b) `mod` maxNumber
samplePRNG :: Int -> Int
samplePRNG = prng 1337 7 100
-- StreamCipher, using lcg algo
data StreamCipher = StreamCipher
-- instance Cipher StreamCipher where
-- encode StreamCipher text = applySSP text
-- decode StreamCipher text = applySSP text
streamInts :: [Int]
streamInts = map samplePRNG [0 .. maxBound]
applySSP' :: String -> [Bits]
applySSP' target = map (\pair -> (fst pair) `xor` (snd pair)) (zip pad text)
where pad = map intToBits streamInts
text = map charToBits target
applySSP :: String -> String
applySSP target = map bitsToChars bitList
where bitList = applySSP' target
| raventid/coursera_learning | haskell/will_kurt/15.11_xor_bool.hs | mit | 3,223 | 0 | 12 | 673 | 981 | 530 | 451 | 66 | 2 |
-- Car Depreciation
-- http://www.codewars.com/kata/55521d28f790f6d92d0001ab
module Codewars.Kata.CarValue where
import Text.Printf (printf)
car :: Float -> Integer -> String
car p n = printf "%.2f" (price p n :: Float)
where price p 0 = p
price p 1 = 0.8 * price p 0
price p 2 = 0.64 * price p 0
price p n = 0.9 * price p (n - 1)
| gafiatulin/codewars | src/Beta/CarValue.hs | mit | 371 | 0 | 10 | 104 | 134 | 70 | 64 | 8 | 4 |
module Rebase.Foreign
(
module Foreign
)
where
import Foreign
| nikita-volkov/rebase | library/Rebase/Foreign.hs | mit | 65 | 0 | 4 | 12 | 15 | 10 | 5 | 4 | 0 |
{-# htermination isPrefixOf :: [(Ratio Int)] -> [(Ratio Int)] -> Bool #-}
import List
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/List_isPrefixOf_9.hs | mit | 86 | 0 | 3 | 14 | 5 | 3 | 2 | 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.