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 OverloadedStrings,FlexibleInstances,UndecidableInstances,OverlappingInstances #-}
module HSL.Types where
import Data.Int (Int64)
import Data.List (intersperse)
import Data.Maybe (fromJust)
import qualified Data.Text as T
-- Type witnesses
t :: T.Text
t = undefined
i :: Int
i = undefined
f :: Float
f = undefined
-- Marshalling
class Datum a where
bs :: a -> T.Text
parse :: T.Text -> a
parse = undefined
parseMany :: [T.Text] -> a
parseMany = parse . head
instance Datum Int where
bs = T.pack . show
parse = read . T.unpack
instance Datum Float where
bs = T.pack . show
parse = read . T.unpack
instance Datum Int64 where
bs = T.pack . show
instance Datum Char where
bs = T.pack . show
parse = T.head
instance Datum String where
bs = T.pack
instance Datum T.Text where
bs = id
parse = id
instance (Datum a, Datum b) => Datum (a, b) where
bs (a, b) = T.concat $ intersperse "\t" [bs a, bs b]
parseMany [a, b] = (parse a, parse b)
instance (Datum a, Datum b, Datum c) => Datum (a, b, c) where
bs (a, b, c) = T.concat $ intersperse "\t" [bs a, bs b, bs c]
parseMany [a, b, c] = (parse a, parse b, parse c)
instance (Datum a, Datum b, Datum c, Datum d) => Datum (a, b, c, d) where
bs (a, b, c, d) = T.concat $ intersperse "\t" [bs a, bs b, bs c, bs d]
parseMany [a, b, c, d] = (parse a, parse b, parse c, parse d)
instance (Datum a, Datum b, Datum c, Datum d, Datum e) => Datum (a, b, c, d, e) where
bs (a, b, c, d, e) = T.concat $ intersperse "\t" [bs a, bs b, bs c, bs d, bs e]
parseMany [a, b, c, d, e] = (parse a, parse b, parse c, parse d, parse e)
class Renderable a where
render :: a -> [T.Text]
instance (Datum a) => Renderable a where
render = (:[]) . bs
instance (Datum a) => Renderable [a] where
render = map bs
instance (Datum a) => Renderable [[a]] where
render = map bs . concat
|
libscott/hawk
|
src/HSL/Types.hs
|
bsd-3-clause
| 1,966
| 0
| 9
| 520
| 926
| 507
| 419
| 54
| 1
|
module Synthesizer.MIDI.CausalIO.Process1 where
gateFromNoteOffs=
let dur = 1
in (d, 3
{-
AllNotesOff -> VoiceMsg.normalVelocity -} )
|
mpickering/ghc-exactprint
|
tests/examples/ghc710/Process1.hs
|
bsd-3-clause
| 163
| 0
| 8
| 46
| 31
| 19
| 12
| 4
| 1
|
-- Copyright (c) 2015-2020 Rudy Matela.
-- Distributed under the 3-Clause BSD licence (see the file LICENSE).
import Test
import System.Exit (exitFailure)
import Data.List (elemIndices,sort)
-- import Test.LeanCheck -- already exported by Test
import Test.LeanCheck.Utils
import Data.List (isPrefixOf)
import Data.Function (on)
main :: IO ()
main = do
max <- getMaxTestsFromArgs 200
case elemIndices False (tests max) of
[] -> putStrLn "Tests passed!"
is -> do putStrLn ("Failed tests:" ++ show is)
exitFailure
tests :: Int -> [Bool]
tests n =
[ True
, holds n $ (not . not) === id
, fails n $ abs === (* (-1)) -:> int
, holds n $ (+) ==== (\x y -> sum [x,y]) -:> int
, fails n $ (+) ==== (*) -:> int
, holds n $ const True &&& const True -:> bool
, fails n $ const False &&& const True -:> int
, holds n $ const False ||| const True -:> int
, fails n $ const False ||| const False -:> int
, holds n $ isCommutative (+) -:> int
, holds n $ isCommutative (*) -:> int
, holds n $ isCommutative (++) -:> [()]
, holds n $ isCommutative (&&)
, holds n $ isCommutative (||)
, fails n $ isCommutative (-) -:> int
, fails n $ isCommutative (++) -:> [bool]
, fails n $ isCommutative (==>)
, holds n $ isAssociative (+) -:> int
, holds n $ isAssociative (*) -:> int
, holds n $ isAssociative (++) -:> [int]
, holds n $ isAssociative (&&)
, holds n $ isAssociative (||)
, fails n $ isAssociative (-) -:> int
, fails n $ isAssociative (==>)
, holds n $ (*) `isDistributiveOver` (+) -:> int
, fails n $ (+) `isDistributiveOver` (*) -:> int
, holds n $ (*) `isLeftDistributiveOver` (+) -:> int
, fails n $ (+) `isLeftDistributiveOver` (*) -:> int
, holds n $ (*) `isRightDistributiveOver` (+) -:> int
, fails n $ (+) `isRightDistributiveOver` (*) -:> int
, holds n $ isSymmetric (==) -:> int
, holds n $ isSymmetric (/=) -:> int
, fails n $ isSymmetric (<=) -:> int
, holds n $ isReflexive (==) -:> int
, holds n $ isIrreflexive (/=) -:> int
, holds n $ (<) `isFlipped` (>) -:> int
, holds n $ (<=) `isFlipped` (>=) -:> int
, fails n $ (<) `isFlipped` (>=) -:> int
, fails n $ (<=) `isFlipped` (>) -:> int
, holds n $ isTransitive (==) -:> bool
, holds n $ isTransitive (<) -:> bool
, holds n $ isTransitive (<=) -:> bool
, fails n $ isTransitive (/=) -:> bool
, holds n $ isTransitive (==) -:> int
, holds n $ isTransitive (<) -:> int
, holds n $ isTransitive (<=) -:> int
, fails n $ isTransitive (/=) -:> int
, holds n $ isAsymmetric (<) -:> int
, holds n $ isAntisymmetric (<=) -:> int
, fails n $ isAsymmetric (<=) -:> int
, holds n $ isAsymmetric (>) -:> int
, holds n $ isAntisymmetric (>=) -:> int
, fails n $ isAsymmetric (>=) -:> int
, holds n $ isEquivalence (==) -:> int
, holds n $ isEquivalence ((==) `on` fst) -:> (int,int)
, holds n $ isEquivalence ((==) `on` length) -:> [int]
, holds n $ isTotalOrder (<=) -:> int
, holds n $ isStrictTotalOrder (<) -:> int
, fails n $ isTotalOrder (<) -:> int
, fails n $ isStrictTotalOrder (<=) -:> int
, holds n $ isTotalOrder (>=) -:> int
, holds n $ isStrictTotalOrder (>) -:> int
, fails n $ isTotalOrder (>) -:> int
, fails n $ isStrictTotalOrder (>=) -:> int
, holds n $ isPartialOrder isPrefixOf -:> [int]
, fails n $ isTotalOrder isPrefixOf -:> [int]
, holds n $ isComparison compare -:> int
, holds n $ isComparison compare -:> bool
, holds n $ isComparison compare -:> ()
, holds n $ okEqOrd -:> ()
, holds n $ okEqOrd -:> int
, holds n $ okEqOrd -:> char
, holds n $ okEqOrd -:> bool
, holds m $ okEqOrd -:> [()]
, holds n $ okEqOrd -:> [int]
, holds n $ okEqOrd -:> [bool]
, holds n $ okEqOrd -:> float -- fails if NaN is included in enumeration
, holds n $ okEqOrd -:> double -- fails if NaN is included in enumeration
, holds n $ okEqOrd -:> rational
, holds n $ okEqOrd -:> nat
, holds n $ okEqOrd -:> natural
, holds n $ okNum -:> int
, holds n $ okNum -:> integer
-- NOTE: the following two fail on Hugs due to a bug on Hugs.
--, holds n $ \x y z -> none isInfinite [x,y,z] ==> okNum x y (z -: float)
--, holds n $ \x y z -> none isInfinite [x,y,z] ==> okNum x y (z -: double)
, holds n $ okNum -:> rational
, holds n $ okNumNonNegative -:> nat
, holds n $ okNumNonNegative -:> natural
, holds n $ (\x y -> x < y ==> x - y == 0) -:> nat
, holds n $ (\x y -> x < y ==> x - y == 0) -:> natural
, holds n $ isIdempotent id -:> int
, holds n $ isIdempotent abs -:> int
, holds n $ isIdempotent sort -:> [bool]
, fails n $ isIdempotent not
, holds n $ isIdentity id -:> int
, holds n $ isIdentity (+0) -:> int
, holds m $ isIdentity sort -:> [()]
, holds n $ isIdentity (not . not)
, fails n $ isIdentity not
, holds n $ isNeverIdentity not
, fails n $ isNeverIdentity abs -:> int
, fails n $ isNeverIdentity negate -:> int
]
where
m = 200
--none :: (a -> Bool) -> [a] -> Bool
--none p = not . or . map p
|
rudymatela/llcheck
|
test/operators.hs
|
bsd-3-clause
| 5,112
| 0
| 15
| 1,340
| 2,117
| 1,127
| 990
| -1
| -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.RDS.ResetDBParameterGroup
-- 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.
-- | Modifies the parameters of a DB parameter group to the engine/system default
-- value. To reset specific parameters submit a list of the following: 'ParameterName' and 'ApplyMethod'. To reset the entire DB parameter group, specify the 'DBParameterGroup' name and 'ResetAllParameters' parameters. When resetting the entire group,
-- dynamic parameters are updated immediately and static parameters are set to 'pending-reboot' to take effect on the next DB instance restart or 'RebootDBInstance' request.
--
-- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_ResetDBParameterGroup.html>
module Network.AWS.RDS.ResetDBParameterGroup
(
-- * Request
ResetDBParameterGroup
-- ** Request constructor
, resetDBParameterGroup
-- ** Request lenses
, rdbpgDBParameterGroupName
, rdbpgParameters
, rdbpgResetAllParameters
-- * Response
, ResetDBParameterGroupResponse
-- ** Response constructor
, resetDBParameterGroupResponse
-- ** Response lenses
, rdbpgrDBParameterGroupName
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.RDS.Types
import qualified GHC.Exts
data ResetDBParameterGroup = ResetDBParameterGroup
{ _rdbpgDBParameterGroupName :: Text
, _rdbpgParameters :: List "member" Parameter
, _rdbpgResetAllParameters :: Maybe Bool
} deriving (Eq, Read, Show)
-- | 'ResetDBParameterGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rdbpgDBParameterGroupName' @::@ 'Text'
--
-- * 'rdbpgParameters' @::@ ['Parameter']
--
-- * 'rdbpgResetAllParameters' @::@ 'Maybe' 'Bool'
--
resetDBParameterGroup :: Text -- ^ 'rdbpgDBParameterGroupName'
-> ResetDBParameterGroup
resetDBParameterGroup p1 = ResetDBParameterGroup
{ _rdbpgDBParameterGroupName = p1
, _rdbpgResetAllParameters = Nothing
, _rdbpgParameters = mempty
}
-- | The name of the DB parameter group.
--
-- Constraints:
--
-- Must be 1 to 255 alphanumeric characters First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens
--
rdbpgDBParameterGroupName :: Lens' ResetDBParameterGroup Text
rdbpgDBParameterGroupName =
lens _rdbpgDBParameterGroupName
(\s a -> s { _rdbpgDBParameterGroupName = a })
-- | An array of parameter names, values, and the apply method for the parameter
-- update. At least one parameter name, value, and apply method must be
-- supplied; subsequent arguments are optional. A maximum of 20 parameters may
-- be modified in a single request.
--
-- MySQL
--
-- Valid Values (for Apply method): 'immediate' | 'pending-reboot'
--
-- You can use the immediate value with dynamic parameters only. You can use
-- the 'pending-reboot' value for both dynamic and static parameters, and changes
-- are applied when DB instance reboots.
--
-- Oracle
--
-- Valid Values (for Apply method): 'pending-reboot'
rdbpgParameters :: Lens' ResetDBParameterGroup [Parameter]
rdbpgParameters = lens _rdbpgParameters (\s a -> s { _rdbpgParameters = a }) . _List
-- | Specifies whether ('true') or not ('false') to reset all parameters in the DB
-- parameter group to default values.
--
-- Default: 'true'
rdbpgResetAllParameters :: Lens' ResetDBParameterGroup (Maybe Bool)
rdbpgResetAllParameters =
lens _rdbpgResetAllParameters (\s a -> s { _rdbpgResetAllParameters = a })
newtype ResetDBParameterGroupResponse = ResetDBParameterGroupResponse
{ _rdbpgrDBParameterGroupName :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'ResetDBParameterGroupResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rdbpgrDBParameterGroupName' @::@ 'Maybe' 'Text'
--
resetDBParameterGroupResponse :: ResetDBParameterGroupResponse
resetDBParameterGroupResponse = ResetDBParameterGroupResponse
{ _rdbpgrDBParameterGroupName = Nothing
}
-- | The name of the DB parameter group.
rdbpgrDBParameterGroupName :: Lens' ResetDBParameterGroupResponse (Maybe Text)
rdbpgrDBParameterGroupName =
lens _rdbpgrDBParameterGroupName
(\s a -> s { _rdbpgrDBParameterGroupName = a })
instance ToPath ResetDBParameterGroup where
toPath = const "/"
instance ToQuery ResetDBParameterGroup where
toQuery ResetDBParameterGroup{..} = mconcat
[ "DBParameterGroupName" =? _rdbpgDBParameterGroupName
, "Parameters" =? _rdbpgParameters
, "ResetAllParameters" =? _rdbpgResetAllParameters
]
instance ToHeaders ResetDBParameterGroup
instance AWSRequest ResetDBParameterGroup where
type Sv ResetDBParameterGroup = RDS
type Rs ResetDBParameterGroup = ResetDBParameterGroupResponse
request = post "ResetDBParameterGroup"
response = xmlResponse
instance FromXML ResetDBParameterGroupResponse where
parseXML = withElement "ResetDBParameterGroupResult" $ \x -> ResetDBParameterGroupResponse
<$> x .@? "DBParameterGroupName"
|
romanb/amazonka
|
amazonka-rds/gen/Network/AWS/RDS/ResetDBParameterGroup.hs
|
mpl-2.0
| 6,021
| 0
| 10
| 1,150
| 592
| 367
| 225
| 70
| 1
|
module Plugin3 where
import API
resource = plugin {
valueOf = reverse
}
|
abuiles/turbinado-blog
|
tmp/dependencies/hs-plugins-1.3.1/testsuite/multi/3plugins/Plugin3.hs
|
bsd-3-clause
| 82
| 0
| 6
| 23
| 20
| 13
| 7
| 4
| 1
|
module SkipWhereTypes where
main = print t
where
t :: Bool
t = True
|
fpco/fay
|
tests/SkipWhereTypes.hs
|
bsd-3-clause
| 79
| 0
| 6
| 25
| 24
| 14
| 10
| 4
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Main (main) where
import ClassyPrelude.Conduit
import Shelly (shellyNoDir, run_)
import Shared
main :: IO ()
main = shellyNoDir $ do
forM_ branches $ \branch -> do
run_ "git" ["checkout", branch]
unless (branch == master) $ run_ "git" ["merge", master]
run_ "git" ["diff", "--exit-code"]
run_ "git" ["checkout", "master"]
|
creichert/yesod-scaffold
|
merge.hs
|
mit
| 433
| 0
| 15
| 90
| 134
| 72
| 62
| 13
| 1
|
{-# LANGUAGE CPP, GADTs #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, (b) the type signatures, and
-- (c) the #if blah_TARGET_ARCH} things, the
-- structure should not be too overwhelming.
module PPC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import CodeGen.Platform
import PPC.Instr
import PPC.Cond
import PPC.Regs
import CPrim
import NCGMonad
import Instruction
import PIC
import Size
import RegClass
import Reg
import TargetReg
import Platform
-- Our intermediate code:
import BlockId
import PprCmm ( pprExpr )
import Cmm
import CmmUtils
import CmmSwitch
import CLabel
import Hoopl
-- The rest:
import OrdList
import Outputable
import Unique
import DynFlags
import Control.Monad ( mapAndUnzipM, when )
import Data.Bits
import Data.Word
import BasicTypes
import FastString
import Util
-- -----------------------------------------------------------------------------
-- Top-level of the instruction selector
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal (pre-order?) yields the insns in the correct
-- order.
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
picBaseMb <- getPicBaseMaybeNat
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
case picBaseMb of
Just picBase -> initializePicBase_ppc ArchPPC os picBase tops
Nothing -> return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
basicBlockCodeGen
:: Block CmmNode C C
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode size reg src
| target32Bit (targetPlatform dflags) &&
isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode size reg src
where ty = cmmRegType dflags reg
size = cmmTypeSize ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode size addr src
| target32Bit (targetPlatform dflags) &&
isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode size addr src
where ty = cmmExprType dflags src
size = cmmTypeSize ty
CmmUnsafeForeignCall target result_regs args
-> genCCall target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false -> do b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg } -> genJump arg
_ ->
panic "stmtToInstrs: statement should have been cps'd away"
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Size Reg InstrBlock
| Any Size (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Size -> Register
swizzleRegisterRep (Fixed _ reg code) size = Fixed size reg code
swizzleRegisterRep (Any _ codefn) size = Any size codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> CmmReg -> Reg
getRegisterReg _ (CmmLocal (LocalReg u pk))
= RegVirtual $ mkVirtualReg u (cmmTypeSize pk)
getRegisterReg platform (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr
mangleIndexTree dflags (CmmRegOff reg off)
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
mangleIndexTree _ _
= panic "PPC.CodeGen.mangleIndexTree: no match"
-- -----------------------------------------------------------------------------
-- Code gen for 64-bit arithmetic on 32-bit platforms
{-
Simple support for generating 64-bit code (ie, 64 bit values and 64
bit assignments) on 32-bit platforms. Unlike the main code generator
we merely shoot for generating working code as simply as possible, and
pay little attention to code quality. Specifically, there is no
attempt to deal cleverly with the fixed-vs-floating register
distinction; all values are generated into (pairs of) floating
registers, even if this would mean some redundant reg-reg moves as a
result. Only one of the VRegUniques is returned, since it will be
of the VRegUniqueLo form, and the upper-half VReg can be determined
by applying getHiVRegFromLo to it.
-}
data ChildCode64 -- a.k.a "Register64"
= ChildCode64
InstrBlock -- code
Reg -- the lower 32-bit temporary which contains the
-- result; use getHiVRegFromLo to find the other
-- VRegUnique. Rules of this simplified insn
-- selection game are therefore that the returned
-- Reg may be modified
-- | The dual to getAnyReg: compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock)
getI64Amodes addrTree = do
Amode hi_addr addr_code <- getAmode addrTree
case addrOffset hi_addr 4 of
Just lo_addr -> return (hi_addr, lo_addr, addr_code)
Nothing -> do (hi_ptr, code) <- getSomeReg addrTree
return (AddrRegImm hi_ptr (ImmInt 0),
AddrRegImm hi_ptr (ImmInt 4),
code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Big-endian store
mov_hi = ST II32 rhi hi_addr
mov_lo = ST II32 rlo lo_addr
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MR r_dst_lo r_src_lo
mov_hi = MR r_dst_hi r_src_hi
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(powerpc): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LD II32 rhi hi_addr
mov_lo = LD II32 rlo lo_addr
return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
half0 = fromIntegral (fromIntegral i :: Word16)
half1 = fromIntegral (fromIntegral (i `shiftR` 16) :: Word16)
half2 = fromIntegral (fromIntegral (i `shiftR` 32) :: Word16)
half3 = fromIntegral (fromIntegral (i `shiftR` 48) :: Word16)
code = toOL [
LIS rlo (ImmInt half1),
OR rlo rlo (RIImm $ ImmInt half0),
LIS rhi (ImmInt half3),
OR rhi rhi (RIImm $ ImmInt half2)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ ADDC rlo r1lo r2lo,
ADDE rhi r1hi r2hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Sub _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ SUBFC rlo r2lo r1lo,
SUBFE rhi r2hi r1hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv W32 W64) [expr]) = do
(expr_reg,expr_code) <- getSomeReg expr
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LI rhi (ImmInt 0)
mov_lo = MR rlo expr_reg
return $ ChildCode64 (expr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 expr
= pprPanic "iselExpr64(powerpc)" (pprExpr expr)
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
getRegister' dflags e
getRegister' :: DynFlags -> CmmExpr -> NatM Register
getRegister' _ (CmmReg (CmmGlobal PicBaseReg))
= do
reg <- getPicBaseNat archWordSize
return (Fixed archWordSize reg nilOL)
getRegister' dflags (CmmReg reg)
= return (Fixed (cmmTypeSize (cmmRegType dflags reg))
(getRegisterReg (targetPlatform dflags) reg) nilOL)
getRegister' dflags tree@(CmmRegOff _ _)
= getRegister' dflags (mangleIndexTree dflags tree)
-- for 32-bit architectuers, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmLoad mem pk)
| not (isWord64 pk)
= do
let platform = targetPlatform dflags
Amode addr addr_code <- getAmode mem
let code dst = ASSERT((targetClassOfReg platform dst == RcDouble) == isFloatType pk)
addr_code `snocOL` LD size dst addr
return (Any size code)
where size = cmmTypeSize pk
-- catch simple cases of zero- or sign-extended load
getRegister' _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode mem
return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr))
-- Note: there is no Load Byte Arithmetic instruction, so no signed case here
getRegister' _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode mem
return (Any II32 (\dst -> addr_code `snocOL` LD II16 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode mem
return (Any II32 (\dst -> addr_code `snocOL` LA II16 dst addr))
getRegister' dflags (CmmMachOp mop [x]) -- unary MachOps
= case mop of
MO_Not rep -> triv_ucode_int rep NOT
MO_F_Neg w -> triv_ucode_float w FNEG
MO_S_Neg w -> triv_ucode_int w NEG
MO_FF_Conv W64 W32 -> trivialUCode FF32 FRSP x
MO_FF_Conv W32 W64 -> conversionNop FF64 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_SS_Conv from to
| from == to -> conversionNop (intSize to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_SS_Conv W32 to -> conversionNop (intSize to) x
MO_SS_Conv W16 W8 -> conversionNop II8 x
MO_SS_Conv W8 to -> triv_ucode_int to (EXTS II8)
MO_SS_Conv W16 to -> triv_ucode_int to (EXTS II16)
MO_UU_Conv from to
| from == to -> conversionNop (intSize to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_UU_Conv W32 to -> conversionNop (intSize to) x
MO_UU_Conv W16 W8 -> conversionNop II8 x
MO_UU_Conv W8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 W32))
MO_UU_Conv W16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 W32))
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_ucode_int width instr = trivialUCode (intSize width) instr x
triv_ucode_float width instr = trivialUCode (floatSize width) instr x
conversionNop new_size expr
= do e_code <- getRegister' dflags expr
return (swizzleRegisterRep e_code new_size)
getRegister' _ (CmmMachOp mop [x, y]) -- dyadic PrimOps
= case mop of
MO_F_Eq _ -> condFltReg EQQ x y
MO_F_Ne _ -> condFltReg NE x y
MO_F_Gt _ -> condFltReg GTT x y
MO_F_Ge _ -> condFltReg GE x y
MO_F_Lt _ -> condFltReg LTT x y
MO_F_Le _ -> condFltReg LE x y
MO_Eq rep -> condIntReg EQQ (extendUExpr rep x) (extendUExpr rep y)
MO_Ne rep -> condIntReg NE (extendUExpr rep x) (extendUExpr rep y)
MO_S_Gt rep -> condIntReg GTT (extendSExpr rep x) (extendSExpr rep y)
MO_S_Ge rep -> condIntReg GE (extendSExpr rep x) (extendSExpr rep y)
MO_S_Lt rep -> condIntReg LTT (extendSExpr rep x) (extendSExpr rep y)
MO_S_Le rep -> condIntReg LE (extendSExpr rep x) (extendSExpr rep y)
MO_U_Gt rep -> condIntReg GU (extendUExpr rep x) (extendUExpr rep y)
MO_U_Ge rep -> condIntReg GEU (extendUExpr rep x) (extendUExpr rep y)
MO_U_Lt rep -> condIntReg LU (extendUExpr rep x) (extendUExpr rep y)
MO_U_Le rep -> condIntReg LEU (extendUExpr rep x) (extendUExpr rep y)
MO_F_Add w -> triv_float w FADD
MO_F_Sub w -> triv_float w FSUB
MO_F_Mul w -> triv_float w FMUL
MO_F_Quot w -> triv_float w FDIV
-- optimize addition with 32-bit immediate
-- (needed for PIC)
MO_Add W32 ->
case y of
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate W32 True (-imm)
-> trivialCode W32 True ADD x (CmmLit $ CmmInt imm immrep)
CmmLit lit
-> do
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
code dst = srcCode `appOL` toOL [
ADDIS dst src (HA imm),
ADD dst dst (RIImm (LO imm))
]
return (Any II32 code)
_ -> trivialCode W32 True ADD x y
MO_Add rep -> trivialCode rep True ADD x y
MO_Sub rep ->
case y of -- subfi ('substract from' with immediate) doesn't exist
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm)
-> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep)
_ -> trivialCodeNoImm' (intSize rep) SUBF y x
MO_Mul rep -> trivialCode rep True MULLW x y
MO_S_MulMayOflo W32 -> trivialCodeNoImm' II32 MULLW_MayOflo x y
MO_S_MulMayOflo _ -> panic "S_MulMayOflo (rep /= II32): not implemented"
MO_U_MulMayOflo _ -> panic "U_MulMayOflo: not implemented"
MO_S_Quot rep -> trivialCodeNoImm' (intSize rep) DIVW (extendSExpr rep x) (extendSExpr rep y)
MO_U_Quot rep -> trivialCodeNoImm' (intSize rep) DIVWU (extendUExpr rep x) (extendUExpr rep y)
MO_S_Rem rep -> remainderCode rep DIVW (extendSExpr rep x) (extendSExpr rep y)
MO_U_Rem rep -> remainderCode rep DIVWU (extendUExpr rep x) (extendUExpr rep y)
MO_And rep -> trivialCode rep False AND x y
MO_Or rep -> trivialCode rep False OR x y
MO_Xor rep -> trivialCode rep False XOR x y
MO_Shl rep -> trivialCode rep False SLW x y
MO_S_Shr rep -> trivialCode rep False SRAW (extendSExpr rep x) y
MO_U_Shr rep -> trivialCode rep False SRW (extendUExpr rep x) y
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_float :: Width -> (Size -> Reg -> Reg -> Reg -> Instr) -> NatM Register
triv_float width instr = trivialCodeNoImm (floatSize width) instr x y
getRegister' _ (CmmLit (CmmInt i rep))
| Just imm <- makeImmediate rep True i
= let
code dst = unitOL (LI dst imm)
in
return (Any (intSize rep) code)
getRegister' _ (CmmLit (CmmFloat f frep)) = do
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode dynRef
let size = floatSize frep
code dst =
LDATA ReadOnlyData (Statics lbl
[CmmStaticLit (CmmFloat f frep)])
`consOL` (addr_code `snocOL` LD size dst addr)
return (Any size code)
getRegister' dflags (CmmLit lit)
= let rep = cmmLitType dflags lit
imm = litToImm lit
code dst = toOL [
LIS dst (HA imm),
ADD dst dst (RIImm (LO imm))
]
in return (Any (cmmTypeSize rep) code)
getRegister' _ other = pprPanic "getRegister(ppc)" (pprExpr other)
-- extend?Rep: wrap integer expression of type rep
-- in a conversion to II32
extendSExpr :: Width -> CmmExpr -> CmmExpr
extendSExpr W32 x = x
extendSExpr rep x = CmmMachOp (MO_SS_Conv rep W32) [x]
extendUExpr :: Width -> CmmExpr -> CmmExpr
extendUExpr W32 x = x
extendUExpr rep x = CmmMachOp (MO_UU_Conv rep W32) [x]
-- -----------------------------------------------------------------------------
-- The 'Amode' type: Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
getAmode :: CmmExpr -> NatM Amode
getAmode tree@(CmmRegOff _ _) = do dflags <- getDynFlags
getAmode (mangleIndexTree dflags tree)
getAmode (CmmMachOp (MO_Sub W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True (-i)
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode (CmmMachOp (MO_Add W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True i
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
-- optimize addition with 32-bit immediate
-- (needed for PIC)
getAmode (CmmMachOp (MO_Add W32) [x, CmmLit lit])
= do
tmp <- getNewRegNat II32
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
code = srcCode `snocOL` ADDIS tmp src (HA imm)
return (Amode (AddrRegImm tmp (LO imm)) code)
getAmode (CmmLit lit)
= do
tmp <- getNewRegNat II32
let imm = litToImm lit
code = unitOL (LIS tmp (HA imm))
return (Amode (AddrRegImm tmp (LO imm)) code)
getAmode (CmmMachOp (MO_Add W32) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmode other
= do
(reg, code) <- getSomeReg other
let
off = ImmInt 0
return (Amode (AddrRegImm reg off) code)
-- The 'CondCode' type: Condition codes passed up the tree.
data CondCode
= CondCode Bool Cond InstrBlock
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- almost the same as everywhere else - but we need to
-- extend small integers to 32 bit first
getCondCode (CmmMachOp mop [x, y])
= case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq rep -> condIntCode EQQ (extendUExpr rep x) (extendUExpr rep y)
MO_Ne rep -> condIntCode NE (extendUExpr rep x) (extendUExpr rep y)
MO_S_Gt rep -> condIntCode GTT (extendSExpr rep x) (extendSExpr rep y)
MO_S_Ge rep -> condIntCode GE (extendSExpr rep x) (extendSExpr rep y)
MO_S_Lt rep -> condIntCode LTT (extendSExpr rep x) (extendSExpr rep y)
MO_S_Le rep -> condIntCode LE (extendSExpr rep x) (extendSExpr rep y)
MO_U_Gt rep -> condIntCode GU (extendUExpr rep x) (extendUExpr rep y)
MO_U_Ge rep -> condIntCode GEU (extendUExpr rep x) (extendUExpr rep y)
MO_U_Lt rep -> condIntCode LU (extendUExpr rep x) (extendUExpr rep y)
MO_U_Le rep -> condIntCode LEU (extendUExpr rep x) (extendUExpr rep y)
_ -> pprPanic "getCondCode(powerpc)" (pprMachOp mop)
getCondCode _ = panic "getCondCode(2)(powerpc)"
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- ###FIXME: I16 and I8!
condIntCode cond x (CmmLit (CmmInt y rep))
| Just src2 <- makeImmediate rep (not $ condUnsigned cond) y
= do
(src1, code) <- getSomeReg x
let
code' = code `snocOL`
(if condUnsigned cond then CMPL else CMP) II32 src1 (RIImm src2)
return (CondCode False cond code')
condIntCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
code' = code1 `appOL` code2 `snocOL`
(if condUnsigned cond then CMPL else CMP) II32 src1 (RIReg src2)
return (CondCode False cond code')
condFltCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
code' = code1 `appOL` code2 `snocOL` FCMP src1 src2
code'' = case cond of -- twiddle CR to handle unordered case
GE -> code' `snocOL` CRNOR ltbit eqbit gtbit
LE -> code' `snocOL` CRNOR gtbit eqbit ltbit
_ -> code'
where
ltbit = 0 ; eqbit = 2 ; gtbit = 1
return (CondCode True cond code'')
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_IntCode pk addr src = do
(srcReg, code) <- getSomeReg src
Amode dstAddr addr_code <- getAmode addr
return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src
= do
dflags <- getDynFlags
let dst = getRegisterReg (targetPlatform dflags) reg
r <- getRegister src
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` MR dst freg
-- Easy, isn't it?
assignMem_FltCode = assignMem_IntCode
assignReg_FltCode = assignReg_IntCode
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (unitOL $ JMP lbl)
genJump tree
= do
(target,code) <- getSomeReg tree
return (code `snocOL` MTCTR target `snocOL` BCTR [] Nothing)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump id bool = do
CondCode _ cond code <- getCondCode bool
return (code `snocOL` BCC cond id)
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
genCCall :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall target dest_regs argsAndHints
= do dflags <- getDynFlags
let platform = targetPlatform dflags
case platformOS platform of
OSLinux -> genCCall' dflags GCPLinux target dest_regs argsAndHints
OSDarwin -> genCCall' dflags GCPDarwin target dest_regs argsAndHints
_ -> panic "PPC.CodeGen.genCCall: not defined for this os"
data GenCCallPlatform = GCPLinux | GCPDarwin
genCCall'
:: DynFlags
-> GenCCallPlatform
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
{-
The PowerPC calling convention for Darwin/Mac OS X
is described in Apple's document
"Inside Mac OS X - Mach-O Runtime Architecture".
PowerPC Linux uses the System V Release 4 Calling Convention
for PowerPC. It is described in the
"System V Application Binary Interface PowerPC Processor Supplement".
Both conventions are similar:
Parameters may be passed in general-purpose registers starting at r3, in
floating point registers starting at f1, or on the stack.
But there are substantial differences:
* The number of registers used for parameter passing and the exact set of
nonvolatile registers differs (see MachRegs.hs).
* On Darwin, stack space is always reserved for parameters, even if they are
passed in registers. The called routine may choose to save parameters from
registers to the corresponding space on the stack.
* On Darwin, a corresponding amount of GPRs is skipped when a floating point
parameter is passed in an FPR.
* SysV insists on either passing I64 arguments on the stack, or in two GPRs,
starting with an odd-numbered GPR. It may skip a GPR to achieve this.
Darwin just treats an I64 like two separate II32s (high word first).
* I64 and FF64 arguments are 8-byte aligned on the stack for SysV, but only
4-byte aligned like everything else on Darwin.
* The SysV spec claims that FF32 is represented as FF64 on the stack. GCC on
PowerPC Linux does not agree, so neither do we.
According to both conventions, The parameter area should be part of the
caller's stack frame, allocated in the caller's prologue code (large enough
to hold the parameter lists for all called routines). The NCG already
uses the stack for register spilling, leaving 64 bytes free at the top.
If we need a larger parameter area than that, we just allocate a new stack
frame just before ccalling.
-}
genCCall' _ _ (PrimTarget MO_WriteBarrier) _ _
= return $ unitOL LWSYNC
genCCall' _ _ (PrimTarget MO_Touch) _ _
= return $ nilOL
genCCall' _ _ (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall' dflags gcp target dest_regs args0
= ASSERT(not $ any (`elem` [II16]) $ map cmmTypeSize argReps)
-- we rely on argument promotion in the codeGen
do
(finalStack,passArgumentsCode,usedRegs) <- passArguments
(zip args argReps)
allArgRegs
(allFPArgRegs platform)
initialStackOffset
(toOL []) []
(labelOrExpr, reduceToFF32) <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do
uses_pic_base_implicitly
return (Left lbl, False)
ForeignTarget expr _ -> do
uses_pic_base_implicitly
return (Right expr, False)
PrimTarget mop -> outOfLineMachOp mop
let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode
codeAfter = move_sp_up finalStack `appOL` moveResult reduceToFF32
case labelOrExpr of
Left lbl -> do
return ( codeBefore
`snocOL` BL lbl usedRegs
`appOL` codeAfter)
Right dyn -> do
(dynReg, dynCode) <- getSomeReg dyn
return ( dynCode
`snocOL` MTCTR dynReg
`appOL` codeBefore
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
where
platform = targetPlatform dflags
uses_pic_base_implicitly = do
-- See Note [implicit register in PPC PIC code]
-- on why we claim to use PIC register here
when (gopt Opt_PIC dflags) $ do
_ <- getPicBaseNat archWordSize
return ()
initialStackOffset = case gcp of
GCPDarwin -> 24
GCPLinux -> 8
-- size of linkage area + size of arguments, in bytes
stackDelta finalStack = case gcp of
GCPDarwin ->
roundTo 16 $ (24 +) $ max 32 $ sum $
map (widthInBytes . typeWidth) argReps
GCPLinux -> roundTo 16 finalStack
-- need to remove alignment information
args | PrimTarget mop <- target,
(mop == MO_Memcpy ||
mop == MO_Memset ||
mop == MO_Memmove)
= init args0
| otherwise
= args0
argReps = map (cmmExprType dflags) args0
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
move_sp_down finalStack
| delta > 64 =
toOL [STU II32 sp (AddrRegImm sp (ImmInt (-delta))),
DELTA (-delta)]
| otherwise = nilOL
where delta = stackDelta finalStack
move_sp_up finalStack
| delta > 64 =
toOL [ADD sp sp (RIImm (ImmInt delta)),
DELTA 0]
| otherwise = nilOL
where delta = stackDelta finalStack
passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed)
passArguments ((arg,arg_ty):args) gprs fprs stackOffset
accumCode accumUsed | isWord64 arg_ty =
do
ChildCode64 code vr_lo <- iselExpr64 arg
let vr_hi = getHiVRegFromLo vr_lo
case gcp of
GCPDarwin ->
do let storeWord vr (gpr:_) _ = MR gpr vr
storeWord vr [] offset
= ST II32 vr (AddrRegImm sp (ImmInt offset))
passArguments args
(drop 2 gprs)
fprs
(stackOffset+8)
(accumCode `appOL` code
`snocOL` storeWord vr_hi gprs stackOffset
`snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
((take 2 gprs) ++ accumUsed)
GCPLinux ->
do let stackOffset' = roundTo 8 stackOffset
stackCode = accumCode `appOL` code
`snocOL` ST II32 vr_hi (AddrRegImm sp (ImmInt stackOffset'))
`snocOL` ST II32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4)))
regCode hireg loreg =
accumCode `appOL` code
`snocOL` MR hireg vr_hi
`snocOL` MR loreg vr_lo
case gprs of
hireg : loreg : regs | even (length gprs) ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_skipped : hireg : loreg : regs ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_ -> -- only one or no regs left
passArguments args [] fprs (stackOffset'+8)
stackCode accumUsed
passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed
| reg : _ <- regs = do
register <- getRegister arg
let code = case register of
Fixed _ freg fcode -> fcode `snocOL` MR reg freg
Any _ acode -> acode reg
stackOffsetRes = case gcp of
-- The Darwin ABI requires that we reserve
-- stack slots for register parameters
GCPDarwin -> stackOffset + stackBytes
-- ... the SysV ABI doesn't.
GCPLinux -> stackOffset
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
stackOffsetRes
(accumCode `appOL` code)
(reg : accumUsed)
| otherwise = do
(vr, code) <- getSomeReg arg
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
(stackOffset' + stackBytes)
(accumCode `appOL` code `snocOL` ST (cmmTypeSize rep) vr stackSlot)
accumUsed
where
stackOffset' = case gcp of
GCPDarwin ->
-- stackOffset is at least 4-byte aligned
-- The Darwin ABI is happy with that.
stackOffset
GCPLinux
-- ... the SysV ABI requires 8-byte
-- alignment for doubles.
| isFloatType rep && typeWidth rep == W64 ->
roundTo 8 stackOffset
| otherwise ->
stackOffset
stackSlot = AddrRegImm sp (ImmInt stackOffset')
(nGprs, nFprs, stackBytes, regs)
= case gcp of
GCPDarwin ->
case cmmTypeSize rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- The Darwin ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
FF32 -> (1, 1, 4, fprs)
FF64 -> (2, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPLinux ->
case cmmTypeSize rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- ... the SysV ABI doesn't.
FF32 -> (0, 1, 4, fprs)
FF64 -> (0, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
moveResult reduceToFF32 =
case dest_regs of
[] -> nilOL
[dest]
| reduceToFF32 && isFloat32 rep -> unitOL (FRSP r_dest f1)
| isFloat32 rep || isFloat64 rep -> unitOL (MR r_dest f1)
| isWord64 rep -> toOL [MR (getHiVRegFromLo r_dest) r3,
MR r_dest r4]
| otherwise -> unitOL (MR r_dest r3)
where rep = cmmRegType dflags (CmmLocal dest)
r_dest = getRegisterReg platform (CmmLocal dest)
_ -> panic "genCCall' moveResult: Bad dest_regs"
outOfLineMachOp mop =
do
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference $
mkForeignLabel functionName Nothing ForeignLabelInThisPackage IsFunction
let mopLabelOrExpr = case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return (mopLabelOrExpr, reduce)
where
(functionName, reduce) = case mop of
MO_F32_Exp -> (fsLit "exp", True)
MO_F32_Log -> (fsLit "log", True)
MO_F32_Sqrt -> (fsLit "sqrt", True)
MO_F32_Sin -> (fsLit "sin", True)
MO_F32_Cos -> (fsLit "cos", True)
MO_F32_Tan -> (fsLit "tan", True)
MO_F32_Asin -> (fsLit "asin", True)
MO_F32_Acos -> (fsLit "acos", True)
MO_F32_Atan -> (fsLit "atan", True)
MO_F32_Sinh -> (fsLit "sinh", True)
MO_F32_Cosh -> (fsLit "cosh", True)
MO_F32_Tanh -> (fsLit "tanh", True)
MO_F32_Pwr -> (fsLit "pow", True)
MO_F64_Exp -> (fsLit "exp", False)
MO_F64_Log -> (fsLit "log", False)
MO_F64_Sqrt -> (fsLit "sqrt", False)
MO_F64_Sin -> (fsLit "sin", False)
MO_F64_Cos -> (fsLit "cos", False)
MO_F64_Tan -> (fsLit "tan", False)
MO_F64_Asin -> (fsLit "asin", False)
MO_F64_Acos -> (fsLit "acos", False)
MO_F64_Atan -> (fsLit "atan", False)
MO_F64_Sinh -> (fsLit "sinh", False)
MO_F64_Cosh -> (fsLit "cosh", False)
MO_F64_Tanh -> (fsLit "tanh", False)
MO_F64_Pwr -> (fsLit "pow", False)
MO_UF_Conv w -> (fsLit $ word2FloatLabel w, False)
MO_Memcpy -> (fsLit "memcpy", False)
MO_Memset -> (fsLit "memset", False)
MO_Memmove -> (fsLit "memmove", False)
MO_BSwap w -> (fsLit $ bSwapLabel w, False)
MO_PopCnt w -> (fsLit $ popCntLabel w, False)
MO_Clz w -> (fsLit $ clzLabel w, False)
MO_Ctz w -> (fsLit $ ctzLabel w, False)
MO_AtomicRMW w amop -> (fsLit $ atomicRMWLabel w amop, False)
MO_Cmpxchg w -> (fsLit $ cmpxchgLabel w, False)
MO_AtomicRead w -> (fsLit $ atomicReadLabel w, False)
MO_AtomicWrite w -> (fsLit $ atomicWriteLabel w, False)
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| gopt Opt_PIC dflags
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
tmp <- getNewRegNat II32
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let code = e_code `appOL` t_code `appOL` toOL [
SLW tmp reg (RIImm (ImmInt 2)),
LD II32 tmp (AddrRegReg tableReg tmp),
ADD tmp tmp (RIReg tableReg),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
| otherwise
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
tmp <- getNewRegNat II32
lbl <- getNewLabelNat
let code = e_code `appOL` toOL [
SLW tmp reg (RIImm (ImmInt 2)),
ADDIS tmp tmp (HA (ImmCLbl lbl)),
LD II32 tmp (AddrRegImm tmp (LO (ImmCLbl lbl))),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (BCTR ids (Just lbl)) =
let jumpTable
| gopt Opt_PIC dflags = map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
where jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
where blockLabel = mkAsmTempLabel (getUnique blockid)
in Just (CmmData ReadOnlyData (Statics lbl jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condReg :: NatM CondCode -> NatM Register
condReg getCond = do
CondCode _ cond cond_code <- getCond
let
{- code dst = cond_code `appOL` toOL [
BCC cond lbl1,
LI dst (ImmInt 0),
BCC ALWAYS lbl2,
NEWBLOCK lbl1,
LI dst (ImmInt 1),
BCC ALWAYS lbl2,
NEWBLOCK lbl2
]-}
code dst = cond_code
`appOL` negate_code
`appOL` toOL [
MFCR dst,
RLWINM dst dst (bit + 1) 31 31
]
negate_code | do_negate = unitOL (CRNOR bit bit bit)
| otherwise = nilOL
(bit, do_negate) = case cond of
LTT -> (0, False)
LE -> (1, True)
EQQ -> (2, False)
GE -> (0, True)
GTT -> (1, False)
NE -> (2, True)
LU -> (0, False)
LEU -> (1, True)
GEU -> (0, True)
GU -> (1, False)
_ -> panic "PPC.CodeGen.codeReg: no match"
return (Any II32 code)
condIntReg cond x y = condReg (condIntCode cond x y)
condFltReg cond x y = condReg (condFltCode cond x y)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
Wolfgang's PowerPC version of The Rules:
A slightly modified version of The Rules to take advantage of the fact
that PowerPC instructions work on all registers and don't implicitly
clobber any fixed registers.
* The only expression for which getRegister returns Fixed is (CmmReg reg).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
It may *not* modify global registers, unless the global
register happens to be the destination register.
It may not clobber any other registers. In fact, only ccalls clobber any
fixed registers.
Also, it may not modify the counter register (used by genCCall).
Corollary: If a getRegister for a subexpression returns Fixed, you need
not move it to a fresh temporary before evaluating the next subexpression.
The Fixed register won't be modified.
Therefore, we don't need a counterpart for the x86's getStableReg on PPC.
* SDM's First Rule is valid for PowerPC, too: subexpressions can depend on
the value of the destination register.
-}
trivialCode
:: Width
-> Bool
-> (Reg -> Reg -> RI -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
trivialCode rep signed instr x (CmmLit (CmmInt y _))
| Just imm <- makeImmediate rep signed y
= do
(src1, code1) <- getSomeReg x
let code dst = code1 `snocOL` instr dst src1 (RIImm imm)
return (Any (intSize rep) code)
trivialCode rep _ instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2)
return (Any (intSize rep) code)
trivialCodeNoImm' :: Size -> (Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm' size instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2
return (Any size code)
trivialCodeNoImm :: Size -> (Size -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm size instr x y = trivialCodeNoImm' size (instr size) x y
trivialUCode
:: Size
-> (Reg -> Reg -> Instr)
-> CmmExpr
-> NatM Register
trivialUCode rep instr x = do
(src, code) <- getSomeReg x
let code' dst = code `snocOL` instr dst src
return (Any rep code')
-- There is no "remainder" instruction on the PPC, so we have to do
-- it the hard way.
-- The "div" parameter is the division instruction to use (DIVW or DIVWU)
remainderCode :: Width -> (Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
remainderCode rep div x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `appOL` toOL [
div dst src1 src2,
MULLW dst dst (RIReg src2),
SUBF dst dst src1
]
return (Any (intSize rep) code)
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP fromRep toRep x = do
(src, code) <- getSomeReg x
lbl <- getNewLabelNat
itmp <- getNewRegNat II32
ftmp <- getNewRegNat FF64
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode dynRef
let
code' dst = code `appOL` maybe_exts `appOL` toOL [
LDATA ReadOnlyData $ Statics lbl
[CmmStaticLit (CmmInt 0x43300000 W32),
CmmStaticLit (CmmInt 0x80000000 W32)],
XORIS itmp src (ImmInt 0x8000),
ST II32 itmp (spRel dflags 3),
LIS itmp (ImmInt 0x4330),
ST II32 itmp (spRel dflags 2),
LD FF64 ftmp (spRel dflags 2)
] `appOL` addr_code `appOL` toOL [
LD FF64 dst addr,
FSUB FF64 dst ftmp dst
] `appOL` maybe_frsp dst
maybe_exts = case fromRep of
W8 -> unitOL $ EXTS II8 src src
W16 -> unitOL $ EXTS II16 src src
W32 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
maybe_frsp dst
= case toRep of
W32 -> unitOL $ FRSP dst dst
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
return (Any (floatSize toRep) code')
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int _ toRep x = do
dflags <- getDynFlags
-- the reps don't really matter: F*->FF64 and II32->I* are no-ops
(src, code) <- getSomeReg x
tmp <- getNewRegNat FF64
let
code' dst = code `appOL` toOL [
-- convert to int in FP reg
FCTIWZ tmp src,
-- store value (64bit) from FP to stack
ST FF64 tmp (spRel dflags 2),
-- read low word of value (high word is undefined)
LD II32 dst (spRel dflags 3)]
return (Any (intSize toRep) code')
-- Note [.LCTOC1 in PPC PIC code]
-- The .LCTOC1 label is defined to point 32768 bytes into the GOT table
-- to make the most of the PPC's 16-bit displacements.
-- As 16-bit signed offset is used (usually via addi/lwz instructions)
-- first element will have '-32768' offset against .LCTOC1.
-- Note [implicit register in PPC PIC code]
-- PPC generates calls by labels in assembly
-- in form of:
-- bl puts+32768@plt
-- in this form it's not seen directly (by GHC NCG)
-- that r30 (PicBaseReg) is used,
-- but r30 is a required part of PLT code setup:
-- puts+32768@plt:
-- lwz r11,-30484(r30) ; offset in .LCTOC1
-- mtctr r11
-- bctr
|
christiaanb/ghc
|
compiler/nativeGen/PPC/CodeGen.hs
|
bsd-3-clause
| 57,145
| 0
| 25
| 19,031
| 13,707
| 6,801
| 6,906
| -1
| -1
|
module GraphOps where
import qualified IntMap as M
import qualified IntSet as S
--import ListUtil(mapSnd)
--import Collect
---- Various functions on directed graphs (or relations if you wish)
-- A graph is represented as a finite map from nodes to set of nodes,
type Graph = M.IntMap NodeSet
-- and nodes are represented by numbers.
type Node = Int
type NodeSet = S.IntSet
--------------------------------------------------------------------------------
neighbours :: Graph -> Node -> NodeSet
neighbourlist :: Graph -> Node -> [Node]
reachable :: Graph -> Node -> NodeSet
transitiveClosure :: Graph -> Graph
nodes :: Graph -> [Node]
scc :: Graph -> [[Node]]
--------------------------------------------------------------------------------
-- The neighbours of a node:
neighbours g = M.lookupWithDefault g S.empty
neighbourlist g = S.toList . neighbours g
-- The set of reachable nodes from a given node in a graph:
reachable graph start = r S.empty [start]
where
r reached [] = reached
r reached (s:ss) =
if s `S.elem` reached
then r reached ss
else r (S.add s reached) (push (neighbourlist graph s) ss)
push [] ss = ss
push (x:xs) ss = push xs (x:ss)
-- The reflexitive, transitive closure of a graph (relation):
transitiveClosure graph =
M.fromList . map (\s->(s,reachable graph s)) . nodes $ graph
-- Reverse all the edges in a graph
--converse = neighbourtable . map swap . edgelist
-- Represenation changes:
--edgelist graph = [(from,to)|(from,tos)<-M.toList graph,to<-S.toList tos]
--neighbourtable = M.fromList . mapSnd S.fromList . collectByFst
-- List the nodes in a graph:
nodes = map fst . M.toList
-- Strongly Connected Components (equivalence classes):
scc graph = sc S.empty (nodes graph)
where
tg = transitiveClosure graph
sc visited [] = []
sc visited (n:ns) =
case n `S.elem` visited of
True -> sc visited ns
False -> if null scc0 then sc visited' ns else scc1:sc visited' ns
where
visited' = S.union visited (S.fromList scc1)
scc1 = n:scc0
scc0 = [n' | n' <- forward, n'/=n, n `S.elem` neighbours tg n']
forward = neighbourlist tg n
|
forste/haReFork
|
tools/base/parse2/LexerGen/GraphOps.hs
|
bsd-3-clause
| 2,210
| 11
| 13
| 485
| 494
| 283
| 211
| 36
| 4
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module T8165 where
import Data.Kind (Type)
-----------------------------------------------------------
class C a where
type T a
instance C Int where
type T Int = Bool
newtype NT = NT Int
deriving C
-----------------------------------------------------------
class D a where
type U a
instance D Int where
type U Int = Int
newtype E = MkE Int
deriving D
-----------------------------------------------------------
class C2 a b where
type F b c a :: Type
type G b (d :: Type -> Type) :: Type -> Type
instance C2 a y => C2 a (Either x y) where
type F (Either x y) c a = F y c a
type G (Either x y) d = G y d
newtype N a = MkN (Either Int a)
deriving (C2 x)
-----------------------------------------------------------
class HasRing a where
type Ring a
newtype L2Norm a = L2Norm a
deriving HasRing
newtype L1Norm a = L1Norm a
deriving HasRing
|
sdiehl/ghc
|
testsuite/tests/deriving/should_compile/T8165.hs
|
bsd-3-clause
| 1,082
| 0
| 8
| 226
| 289
| 167
| 122
| -1
| -1
|
module ParserNoBinaryLiterals1 where
f :: Int -> ()
f 0b0 = ()
f _ = ()
|
urbanslug/ghc
|
testsuite/tests/parser/should_fail/ParserNoBinaryLiterals1.hs
|
bsd-3-clause
| 75
| 0
| 6
| 19
| 35
| 19
| 16
| -1
| -1
|
module Ch22.Exercises where
import Control.Applicative
import Data.Maybe
import Utils ((|>))
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xs :: Maybe Integer
xs = zip x y |> lookup 3
ys :: Maybe Integer
ys = zip y z |> lookup 6
zs :: Maybe Integer
zs = zip x y |> lookup 4
z' :: Integer -> Maybe Integer
z' n = zip x z |> lookup n
x1 :: Maybe (Integer, Integer)
x1 = liftA2 (,) xs ys
x2 :: Maybe (Integer, Integer)
x2 = liftA2 (,) ys zs
x3 :: Integer -> (Maybe Integer, Maybe Integer)
x3 n = (z' n, z' n)
summed :: Num c => (c, c) -> c
summed (a, b) = a + b
bolt :: Integer -> Bool
bolt = liftA2 (&&) (>3) (<8)
seqA :: Integral a => a -> [Bool]
seqA m = sequenceA [(>3), (<8), even] m
s' :: Maybe Integer
s' = summed <$> ((,) <$> xs <*> ys)
main :: IO ()
main = do
print $ sequenceA [Just 3, Just 2, Just 1]
print $ sequenceA [x, y]
print $ sequenceA [xs, ys]
print $ s'
print $ fmap summed ((,) <$> xs <*> zs)
print $ bolt 7
print $ fmap bolt z
print $ seqA 7
-- solutions
print $ and . seqA $ 2
print $ seqA $ fromMaybe 0 s'
print $ bolt $ fromMaybe 0 ys
|
andrewMacmurray/haskell-book-solutions
|
src/ch22/Exercises.hs
|
mit
| 1,092
| 0
| 12
| 281
| 613
| 322
| 291
| 42
| 1
|
{-# LANGUAGE RankNTypes #-}
-- |
-- Module : Numeric.QuadraticIrrational.Internal.Lens
-- Description : A tiny implementation of some lens primitives
-- Copyright : © 2014 Johan Kiviniemi
-- License : MIT
-- Maintainer : Johan Kiviniemi <devel@johan.kiviniemi.name>
-- Stability : provisional
-- Portability : RankNTypes
--
-- A tiny implementation of some lens primitives. Please see
-- <http://hackage.haskell.org/package/lens> for proper documentation.
module Numeric.QuadraticIrrational.Internal.Lens
( Lens, Traversal, Lens', Traversal', Getting, Setting
, view, over, set
) where
import Control.Applicative (Const (Const), getConst)
import Data.Functor.Identity (Identity (Identity), runIdentity)
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t
type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s
type Traversal' s a = forall f. Applicative f => (a -> f a) -> s -> f s
type Getting r s a = (a -> Const r a) -> s -> Const r s
type Setting s t a b = (a -> Identity b) -> s -> Identity t
view :: Getting a s a -> s -> a
view l s = getConst (l Const s)
{-# INLINE view #-}
over :: Setting s t a b -> (a -> b) -> s -> t
over l f s = runIdentity (l (f `seq` Identity . f) s)
{-# INLINE over #-}
set :: Setting s t a b -> b -> s -> t
set l b s = over l (const b) s
{-# INLINE set #-}
|
ion1/quadratic-irrational
|
src/Numeric/QuadraticIrrational/Internal/Lens.hs
|
mit
| 1,437
| 0
| 10
| 329
| 481
| 273
| 208
| 21
| 1
|
module GUBS.Solver.Class (
SMTSolver (..)
, stack
, evalM
, F.BoolLit (..)
, F.Formula (..)
, F.Atom (..)
, SMTFormula
, SMTExpression
, assert
, F.smtTop
, F.smtBot
, F.smtBool
-- , F.smtNot
, F.smtOr
, F.smtAnd
, F.smtBigOr
, F.smtBigAnd
, F.smtAll
, F.smtAny
, smtEq
, smtGeq
) where
import Control.Monad ((>=>))
import Control.Monad.Trans (MonadIO, MonadTrans)
import Control.Monad.Trace
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import GUBS.Algebra hiding (neg)
import qualified GUBS.Expression as E
import qualified GUBS.Solver.Formula as F
import GUBS.Constraint (Constraint (..))
import qualified GUBS.Polynomial as Poly
type SMTExpression s = E.Expression (NLiteral s)
type SMTFormula s = F.Formula (BLiteral s) (SMTExpression s)
class (Monad (SolverM s), Ord (NLiteral s)) => SMTSolver s where
data SolverM s :: * -> *
data NLiteral s :: *
data BLiteral s :: *
freshBool :: SolverM s (BLiteral s)
freshNat :: SolverM s (NLiteral s)
push :: SolverM s ()
pop :: SolverM s ()
assertFormula :: SMTFormula s -> SolverM s ()
checkSat :: SolverM s Bool
getValue :: NLiteral s -> SolverM s Integer
assert :: SMTSolver s => SMTFormula s -> SolverM s ()
assert = letElim >=> assertFormula where
letElim F.Top = return F.Top
letElim F.Bot = return F.Bot
letElim l@F.Lit{} = return l
letElim a@F.Atom{} = return a
letElim (F.Or f1 f2) = F.Or <$> letElim f1 <*> letElim f2
letElim (F.And f1 f2) = F.And <$> letElim f1 <*> letElim f2
letElim (F.LetB e f) = do
e' <- letElim e
b <- freshBool
assertFormula (F.Iff (F.literal b) e')
letElim (f b)
-- isZero :: SMTSolver s => Expression (Literal s) -> Formula (Exp s)
-- isZero e = smtBigAnd [ smtBool (c == 0)
-- `smtOr` smtBigOr [ elit v `eqA` fromNatural 0 | (v,_) <- Poly.toPowers m]
-- | (c,m) <- Poly.toMonos e]
simpEq,simpGeq :: SMTSolver s => SMTExpression s -> SMTExpression s -> SMTFormula s
simpEq e1 e2 = e1 `F.eqA` e2
simpGeq e1 e2 = e1 `F.geqA` e2
-- simpEq e1 e2 | Poly.isZero e1 = isZero e2
-- | Poly.isZero e2 = isZero e1
-- | otherwise = toSolverExp e1 `Eq` toSolverExp e2
-- simpGeq e1 e2 | Poly.isZero e1 = isZero e2
-- | otherwise = toSolverExp e1 `Geq` toSolverExp e2
smtEq,smtGeq :: SMTSolver s => SMTExpression s -> SMTExpression s -> SMTFormula s
-- smtEq = simpEq
-- smtGeq = simpGeq
smtEq = smtFactorIEQ simpEq
smtGeq = smtFactorIEQ simpGeq
smtFactorIEQ :: SMTSolver s => (SMTExpression s -> SMTExpression s -> SMTFormula s)
-> SMTExpression s -> SMTExpression s -> SMTFormula s
smtFactorIEQ eq e1 e2 =
case Poly.factorise [e1,e2] of
Just ((_,m), [e1',e2']) -> F.smtBigOr ([ Poly.variable v `F.eqA` fromNatural 0 | v <- Poly.monoVariables m] ++ [e1' `eq` e2'])
_ -> e1 `eq` e2
stack :: SMTSolver s => SolverM s a -> SolverM s a
stack m = push *> m <* pop
evalM :: SMTSolver s => SMTExpression s -> SolverM s Integer
evalM = E.evalWithM getValue
|
mzini/gubs
|
src/GUBS/Solver/Class.hs
|
mit
| 3,068
| 0
| 15
| 736
| 1,028
| 554
| 474
| -1
| -1
|
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- License : MIT
-- Maintainer : Paweł Nowak <pawel834@gmail.com>
-- Portability : GHC only
-----------------------------------------------------------------------------
module Data.Total.Internal.SparseFold where
import Data.Proxy
import Data.Reflection
import Data.Semigroup
-- | `mpower x n` raises x to the power n taking advantage of associativity.
mpower :: Monoid m => m -> Integer -> m
mpower _ 0 = mempty
mpower x 1 = x
mpower x n = mpower x r `mappend` mpower (x `mappend` x) q
where (q, r) = quotRem n 2
-- | A semigroup used to quickly fold a sparse finite domain.
data SparseFold s m = SparseFold (Min Integer) m (Max Integer)
-- TODO: caching the powers would reduce complexity
-- from O(k * log (n/k)) to O(k + log n).
instance (Reifies s m, Monoid m) => Semigroup (SparseFold s m) where
SparseFold min x max <> SparseFold min' y max' =
SparseFold
(min <> min')
(x `mappend` mpower filler gapSize `mappend` y)
(max <> max')
where
gapSize = getMin min' - getMax max - 1
filler = reflect (Proxy :: Proxy s)
foldPoint :: Integer -> a -> Option (SparseFold s a)
foldPoint k v = Option $ Just $ SparseFold (Min k) v (Max k)
runSparseFold :: Monoid m => m
-> (forall s. Reifies s m => Proxy s -> Option (SparseFold s m))
-> m
runSparseFold d f = reify d $ \p -> extract (f p)
where extract (Option Nothing) = mempty
extract (Option (Just (SparseFold _ v _))) = v
|
pawel-n/total-maps
|
src/Data/Total/Internal/SparseFold.hs
|
mit
| 1,602
| 0
| 14
| 373
| 485
| 255
| 230
| 27
| 2
|
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module ViewModels.ShortUserViewModel where
import Data.Text
import Data.Data
data ShortUserViewModel = ShortUserViewModel {
displayName :: Maybe Text,
loginURL :: Text,
logoutURL :: Text
} deriving (Data, Typeable)
|
itsuart/fdc_archivist
|
src/ViewModels/ShortUserViewModel.hs
|
mit
| 279
| 0
| 9
| 40
| 58
| 35
| 23
| 9
| 0
|
module Main (main) where
import Control.Monad (forM_)
import Data.Monoid (Sum(..))
import System.Directory.PathWalk (pathWalkAccumulate)
import System.Environment (getArgs)
main :: IO ()
main = do
rawArgs <- getArgs
let args = if rawArgs == [] then ["."] else rawArgs
forM_ args $ \arg -> do
(Sum total) <- pathWalkAccumulate arg $ \root _dirs files -> do
putStrLn $ "files in " ++ root ++ ": " ++ show (length files)
return $ Sum (length files)
putStrLn $ "Total: " ++ show total
|
Xe/pathwalk
|
examples/accumulate/Main.hs
|
mit
| 535
| 0
| 19
| 134
| 204
| 106
| 98
| 14
| 2
|
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module Hydrogen.Prelude.System (
module Hydrogen.Prelude.IO
, module System.CPUTime
, module System.Directory
, module System.Environment
, module System.Exit
, module System.FilePath
, module System.Info
, module System.Process
, module System.Random
, findFilesRecursively
, findFilesRecursivelyWithContext
, escapeFileName
, unescapeFileName
) where
import Hydrogen.Prelude.IO
import "base" System.CPUTime
import "directory" System.Directory
import "base" System.Environment
import "base" System.Exit
import "filepath" System.FilePath
import "base" System.Info
import "process" System.Process
import "random" System.Random
import qualified Data.Set as Set
findFilesRecursively :: (FilePath -> IO Bool) -> FilePath -> IO [FilePath]
findFilesRecursively f dir =
map fst <$> findFilesRecursivelyWithContext (\c _ _ -> return c) f () dir
findFilesRecursivelyWithContext
:: forall c.
(c -> FilePath -> [FilePath] -> IO c) -- ^ update function for current context
-> (FilePath -> IO Bool) -- ^ predicate to filter files
-> c -- ^ current context
-> FilePath -> IO [(FilePath, c)]
findFilesRecursivelyWithContext updater predicate context dir = do
cwd <- getCurrentDirectory
snd <$> find Set.empty context (cwd </> dir)
where
find :: Set FilePath -> c -> FilePath -> IO (Set FilePath, [(FilePath, c)])
find visited context dir = canonicalizePath dir >>= find'
where
find' thisDirectory
| Set.member thisDirectory visited = return (Set.empty, [])
| otherwise = do
allFiles <- map (dir </>) <$> getDirectoryContents dir
theFiles <- filterFiles allFiles
theDirs <- filterM isDir allFiles
context' <- updater context dir theFiles
let visited' = Set.insert thisDirectory visited
f (visited, files) dir = do
(visited', files') <- find visited context' dir
return (visited', files' : files)
(visited'', files') <- foldM f (visited', []) theDirs
return (visited'', concat (zip theFiles (repeat context') : files'))
filterFiles = filterM (\x -> liftM2 (&&) (doesFileExist x) (predicate x))
isDir x = liftM2 (&&) (doesDirectoryExist x) (return (head (takeFileName x) /= '.'))
escapeFileName :: String -> String
escapeFileName s = case s of
('/' : xs)
-> '_' : escapeFileName xs
(x : xs)
| isSafeChar x -> x : escapeFileName xs
| ord x <= 255 -> '$' : printf "%02X" (ord x) ++ escapeFileName xs
| otherwise -> "$$" ++ printf "%04X" (ord x) ++ escapeFileName xs
[] -> []
where
isSafeChar x = isAscii x && isAlphaNum x || x `elem` ".-"
unescapeFileName :: String -> Maybe String
unescapeFileName s = case s of
('$' : '$' : a : b : c : d : xs)
-> (chr <$> hexnum (a : b : c : [d])) `cons` unescapeFileName xs
('$' : a : b : xs)
-> (chr <$> hexnum (a : [b])) `cons` unescapeFileName xs
('_' : xs)
-> pure '/' `cons` unescapeFileName xs
(x : xs)
-> pure x `cons` unescapeFileName xs
[] -> return []
where
cons = liftA2 (:)
hexnum = fmap fst . listToMaybe . readHex
|
hydrogen-tools/hydrogen-prelude
|
src/Hydrogen/Prelude/System.hs
|
mit
| 3,371
| 0
| 19
| 934
| 1,116
| 585
| 531
| -1
| -1
|
module Lab4 where
------------------------------------------------------------------------------------------------------------------------------
-- RECURSIVE FUNCTIONS
------------------------------------------------------------------------------------------------------------------------------
import Data.Char
-- ===================================
-- Ex. 0
-- ===================================
triangle :: Integer -> Integer
triangle 0 = 0
triangle n = n + triangle (n - 1)
-- ===================================
-- Ex. 1
-- ===================================
count :: Eq a => a -> [a] -> Int
count _ [] = 0
count a (x : xs)
| a == x = 1 + count a xs
| otherwise = count a xs
xs = [1,2,35,2,3,4,8,2,9,0,5,2,8,4,9,1,9,7,3,9,2,0,5,2,7,6,92,8,3,6,1,9,2,4,8,7,1,2,8,0,4,5,2,3,6,2,3,9,8,4,7,1,4,0,1,8,4,1,2,4,56,7,2,98,3,5,28,4,0,12,4,6,8,1,9,4,8,62,3,71,0,3,8,10,2,4,7,12,9,0,3,47,1,0,23,4,8,1,20,5,7,29,3,5,68,23,5,6,3,4,98,1,0,2,3,8,1]
ys = map (\x -> ((x + 1) * 3) ^ 3 - 7) xs
poem = [ "Three Types for the Lisp-kings under the parentheses,"
, "Seven for the Web-lords in their halls of XML,"
, "Nine for C Developers doomed to segfault,"
, "One for the Dark Lord on his dark throne"
, "In the Land of Haskell where the Monads lie."
, "One Type to rule them all, One Type to find them,"
, "One Type to bring them all and in the Lambda >>= them"
, "In the Land of Haskell where the Monads lie."
]
-- ===================================
-- Ex. 2
-- ===================================
euclid :: (Int, Int) -> Int
euclid (x, y)
| x == y = x
| x > y = euclid (x - y, y)
| x < y = euclid (x, y - x)
-- ===================================
-- Ex. 3
-- ===================================
funkyMap :: (a -> b) -> (a -> b) -> [a] -> [b]
--funkyMap f g xs = map(\ (i, j) -> if (even i) then f j else g j) $ zip [0..n] xs
-- where n = length xs - 1
funkyMap f g xs = h $ zip [0..n] xs
where n = length xs - 1
h = map(\ (i, j) -> if (even i) then f j else g j)
|
mitochon/hexercise
|
src/mooc/fp101/Lab4Template.hs
|
mit
| 2,045
| 0
| 13
| 396
| 785
| 473
| 312
| 29
| 2
|
{-# LANGUAGE TypeFamilies #-}
module Parser where
import Syntax
import Prelude hiding (error)
import Unbound.Generics.LocallyNameless
import Control.Monad (void)
import Control.Applicative (empty)
import Text.Megaparsec
import Text.Megaparsec.Text
import qualified Text.Megaparsec.Lexer as L
import Data.Scientific (toRealFloat)
import qualified Data.Text as T
type RawData t e = [Either (ParseError t e) Term]
parseProgram :: String -> T.Text -> Either (ParseError Char Dec) (RawData Char Dec)
parseProgram = runParser rawData
rawData :: Parser (RawData Char Dec)
rawData = between scn eof (sepEndBy e scn)
where e = withRecovery recover (Right <$> expr)
recover err = Left err <$ manyTill anyChar eol
rws :: [String] -- list of reserved words
rws = ["if", "then", "else", "true", "false", "in"]
identifier :: Parser String
identifier = (lexeme . try) (p >>= check)
where
p = (:) <$> letterChar <*> many alphaNumChar
check x = if x `elem` rws
then fail $ "keyword " ++ show x ++ " cannot be an identifier"
else return x
sc :: Parser ()
sc = L.space (void $ oneOf " \t") lineCmnt empty
scn :: Parser ()
scn = L.space (void spaceChar) lineCmnt empty
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
symbol :: String -> Parser String
symbol = L.symbol sc
parens :: Parser a -> Parser a
parens = between (symbol "(") (symbol ")")
lineCmnt :: Parser ()
lineCmnt = L.skipLineComment "#"
rword :: String -> Parser ()
rword w = string w *> notFollowedBy alphaNumChar *> sc
number :: Parser Term
number = do
n <- toRealFloat <$> lexeme L.number
return $ TmFloat n
floattimes :: Parser Term
floattimes = do
rword "floattimes"
n1 <- term
n2 <- term
return $ TmFloatTimes n1 n2
stringLit :: Parser Term
stringLit = do
void $ symbol "\""
str <- anyChar `manyTill` symbol "\""
return $ TmString str
successor :: Parser Term
successor = do
rword "succ"
n <- expr
return $ TmSucc n
predecessor :: Parser Term
predecessor = do
rword "pred"
n <- expr
return $ TmPred n
zero :: Parser Term
zero = rword "0" *> pure TmZero
iszero :: Parser Term
iszero = do
rword "iszero"
t <- expr
return $ TmIsZero t
true :: Parser Term
true = rword "true" *> pure TmTrue
false :: Parser Term
false = rword "false" *> pure TmFalse
var :: Parser Term
var = do
n <- identifier
return $ TmVar (string2Name n)
letRec :: Parser Term
letRec = do
rword "rec"
t1 <- expr
return $ TmFix t1
letIn :: Parser Term
letIn = do
rword "let"
n <- identifier
void $ symbol "="
boundExpr <- expr
rword "in"
body <- expr
return $ TmLet (bind (string2Name n, embed boundExpr) body)
lam :: Parser Term
lam = do
void $ symbol "λ" <|> symbol "\\"
(TmVar n) <- var
void $ symbol ":"
ty <- some validChars `sepBy` (symbol "->" <|> symbol "→")
void $ symbol "."
body <- expr
return $ TmAbs (bind (n, embed ty) body)
validChars :: Parser Char
validChars = alphaNumChar <|> oneOf "{:}"
ifThenElse :: Parser Term
ifThenElse = do
rword "if"
b <- expr
rword "then"
e1 <- expr
rword "else"
e2 <- expr
return $ TmIf b e1 e2
ascription :: Parser Term
ascription = do
rword "alias"
ty1 <- some validChars `sepBy` (symbol "->" <|> symbol "→") <* sc
rword "as"
ty2 <- some alphaNumChar <* sc
return $ TmAscription ty1 ty2
projection :: Parser Term
projection = do
t <- record
void $ symbol "."
p <- identifier
return $ TmProj t p
record :: Parser Term
record = do
void $ symbol "{"
fields <- dec `sepBy` symbol ","
void $ symbol "}"
return $ TmRecord fields
where dec = do
n <- identifier
void $ symbol "="
t <- expr
return (n, t)
error :: Parser Term
error = rword "error" *> pure TmError
term :: Parser Term
term = parens expr
<|> successor
<|> predecessor
<|> zero
<|> iszero
<|> ascription
<|> lam
<|> true
<|> false
<|> ifThenElse
<|> error
<|> stringLit
<|> number
<|> floattimes
<|> letRec
<|> letIn
<|> try projection
<|> record
<|> var
<?> "term"
expr :: Parser Term
expr = do
tms <- some term
return $ foldl1 TmApp tms
|
kellino/TypeSystems
|
fullSub/Parser.hs
|
mit
| 4,325
| 0
| 24
| 1,161
| 1,618
| 786
| 832
| -1
| -1
|
module RegExpOps where
import RegExp
import Data.List
{-+
"" =~ r <==> nullable r
-}
nullable r =
case r of
Zero -> False
One -> True
S _ -> False
r1 :& r2 -> nullable r1 && nullable r2
r1 :! r2 -> nullable r1 || nullable r2
r1 :-! r2 -> nullable r1 && not (nullable r2)
Many _ -> True
Some re -> nullable re
--nullR r = if nullable r then e else z
{-+
For all i in first r, there exists an is such that i:is =~ r
-}
first r =
case r of
Zero -> []
One -> []
S i -> [i]
r1 :& r2 -> first r1 `union` (if nullable r1 then first r2 else [])
r1 :! r2 -> first r1 `union` first r2
-- r1 :-! r2 -> first r1 \\ first r2 -- this is wrong!
r1 :-! _ -> first r1 -- `union` first r2
Many re -> first re
Some re -> first re
{-+
i:is =~ r <==> is =~ follow i r
-}
follow i r =
case r of
Zero -> Zero
One -> Zero
S i' -> if i'==i then One else Zero
r1 :& r2 -> follow i r1 & r2 ! (if nullable r1 then follow i r2 else Zero)
r1 :! r2 -> follow i r1 ! follow i r2
r1 :-! r2 -> follow i r1 -! follow i r2
Many re -> follow i re & Many re
Some re -> follow i re & Many re
factors r = (nullable r,[(i,r')|i<-sort (first r),let r'=follow i r,r'/=Zero])
factorsR (n,fs) = (if n then e else z) ! alts [S i & r|(i,r)<-fs]
{-+
Inspired by:
comp.compilers, comp.theory
http://compilers.iecc.com/comparch/article/93-10-022
The Equational Approach: (1) Regular Expressions -> DFA's.
markh@csd4.csd.uwm.edu (Mark)
Computing Services Division, University of Wisconsin - Milwaukee
Sat, 2 Oct 1993 17:47:13 GMT
-}
|
yav/haskell-lexer
|
generator/src/RegExpOps.hs
|
mit
| 1,612
| 0
| 11
| 447
| 577
| 287
| 290
| 35
| 10
|
import Distribution.Simple
import Distribution.Verbosity
import Distribution.Simple.Configure
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Utils
import Distribution.PackageDescription
import System.Environment
import System.Process
import System.Exit
import Control.Applicative
import Data.List (partition,stripPrefix,foldl')
import Data.Maybe (mapMaybe)
type RubyVersion = (Int, Int, Int)
data RubyInfo = RubyInfo { rbVersion :: RubyVersion
, rbInstallName :: String
, rbIncludes :: [String]
, rbLib :: String
, rbSoName :: String
, rbLibName :: String
} deriving (Eq, Show, Read)
evalRuby :: String -- expression to evaluate
-> IO (Maybe String) -- stdout, if successfull
evalRuby exp = do
(exitCode, out, err) <- readProcessWithExitCode "ruby" ["-e", exp] ""
return $ if exitCode == ExitSuccess
then Just out
else Nothing
getRubyInfo :: IO (Maybe RubyInfo)
getRubyInfo = do
version <- evalRuby "print '('+RUBY_VERSION.gsub('.', ',')+')'" >>= (return . fmap read)
installName <- evalRuby "print RbConfig::CONFIG['RUBY_INSTALL_NAME']"
headerDir <- evalRuby "print RbConfig::CONFIG['rubyhdrdir']"
archDir <- evalRuby "print RbConfig::CONFIG['rubyhdrdir'] + File::Separator + RbConfig::CONFIG['arch']"
libDir <- evalRuby "print RbConfig::CONFIG['libdir']"
soName <- evalRuby "print RbConfig::CONFIG['LIBRUBY_SO']"
libName <- evalRuby "print RbConfig::CONFIG['LIBRUBY_SO'].sub(/^lib/,'').sub(/\\.(so|dll|dylib)$/,'')"
return $ RubyInfo <$> version
<*> installName
<*> sequence [headerDir, archDir]
<*> libDir
<*> soName
<*> libName
defsFor :: RubyInfo -> [String]
defsFor info =
case rbVersion info of
(1, _, _) -> []
(2, 0, _) -> ["-DRUBY2"]
(2, _, _) -> ["-DRUBY2", "-DRUBY21"]
can'tFindRuby :: String
can'tFindRuby = unlines $ [ "Could not find the ruby library. Ensure that it is present on your system (on Debian/Ubuntu, make sure you installed the ruby1.8-dev package)."
, "If you know it to be installed, please install rupee in the following way (example for nix):"
, ""
, "$ cabal install rupee -p --configure-option=\"--rubyversion=19 --rubylib=ruby --rubyinc=/nix/store/v0w14mdpcy9c0qwvhqa7154qsv53ifqn-ruby-1.9.3-p484/include/ruby-1.9.1 --rubyinc=/nix/store/v0w14mdpcy9c0qwvhqa7154qsv53ifqn-ruby-1.9.3-p484/include/ruby-1.9.1/x86_64-linux' --extra-lib-dirs=$HOME/.nix-profile/lib/\""
, ""
, " --rubylib : Should be the name of the library passed to the linker (ruby for libruby.so)."
, " --rubyinc : There can be several instances of this flag. Should be the path of the various ruby header files."
, " --rubyversion : Mandatory for ruby 2.0 and 2.1, should have the values 20 or 21."
]
getBuildInfo :: LocalBuildInfo -> BuildInfo
getBuildInfo l = case library (localPkgDescr l) of
Just x -> libBuildInfo x
Nothing -> error "Could not find the buildinfo!"
setBuildInfo :: LocalBuildInfo -> BuildInfo -> LocalBuildInfo
setBuildInfo l b = l { localPkgDescr = lpd' }
where
lpd = localPkgDescr l
Just li = library lpd
li' = li { libBuildInfo = b }
lpd' = lpd { library = Just li' }
myConfHook :: LocalBuildInfo -> IO LocalBuildInfo
myConfHook h = do
mrubyInfo <- getRubyInfo
case mrubyInfo of
Just (info) ->
let buildinfos = getBuildInfo h
bi = buildinfos { extraLibs = rbLibName info : extraLibs buildinfos
, extraLibDirs = rbLib info : extraLibDirs buildinfos
, includeDirs = includeDirs buildinfos ++ rbIncludes info
, ccOptions = ccOptions buildinfos ++ defsFor info
}
in putStrLn ("Detected ruby: " ++ show info) >> return (setBuildInfo h bi)
_ -> warn normal can'tFindRuby >> return h
parseFlags :: [String] -> LocalBuildInfo -> IO LocalBuildInfo
parseFlags flags h = return $ setBuildInfo h $ foldl' parseFlags' bbi flags
where
bbi = getBuildInfo h
parseFlags' bi fl = case (stripPrefix "--rubylib=" fl, stripPrefix "--rubyinc=" fl, stripPrefix "--rubyversion=" fl) of
(Just l, _, _) -> bi { extraLibs = l : extraLibs bi }
(_, Just l, _) -> bi { includeDirs = l : includeDirs bi }
(_, _, Just "20") -> bi { ccOptions = "-DRUBY2" : ccOptions bi }
(_, _, Just "21") -> bi { ccOptions = "-DRUBY2" : "-DRUBY21" : ccOptions bi }
_ -> bi
main :: IO ()
main = do
args <- getArgs
let flags = mapMaybe (stripPrefix "--configure-option=") args
let hook = if null flags
then myConfHook
else parseFlags (concatMap words flags)
defaultMainWithHooks $ simpleUserHooks { confHook = (\a b -> configure a b >>= hook) }
|
cstrahan/rupee
|
Setup.hs
|
mit
| 5,530
| 0
| 17
| 1,813
| 1,155
| 607
| 548
| 96
| 5
|
{-# LANGUAGE OverloadedStrings #-}
module TwitterMarkov.TweetMarkov
(tweetsModel) where
import qualified Data.Text.Lazy as T
import TwitterMarkov.MarkovModel
import TwitterMarkov.Types
tweetsModel :: [Tweet] -> MarkovModel T.Text
tweetsModel tweets = foldMap (uncurry singletonModel) (tweets >>= tweetNGram 2)
tweetNGram :: Int -> Tweet -> [(T.Text, T.Text)]
tweetNGram n t = nGram n . T.words . text $ t
nGram :: Int -> [T.Text] -> [(T.Text, T.Text)]
nGram n (a:as) = let (l, r) = splitAt n (takeExactly (n*2) (a:as)) in
if not (null l || null r)
then (T.unwords l, T.unwords r) : nGram n as
else []
nGram _ [] = []
takeExactly :: Int -> [a] -> [a]
takeExactly n as = if length (take n as) == n
then take n as
else []
|
beala/twitter-markov
|
src/lib/TwitterMarkov/TweetMarkov.hs
|
mit
| 852
| 0
| 13
| 255
| 347
| 185
| 162
| 20
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Site where
import Control.Concurrent
import Control.Monad
import Control.Monad.Trans
import qualified Data.Acid.Advanced as A
import Data.ByteString (ByteString)
import qualified Data.Text as T
import Heist
import qualified Heist.Interpreted as I
import Snap.Snaplet
import Snap.Snaplet.AcidState
import Snap.Snaplet.Heist
import Snap.Util.FileServe
import System.Process
import Application
import Package
handleIndex :: AppHandler ()
handleIndex = do hackage <- query QueryHackage
packages <- query QueryPackages
renderWithSplices "home" (packageSplices hackage packages)
packageSplices :: Hackage -> [Package] -> Splices (SnapletISplice App)
packageSplices hackage packages = "packages" ## renderPackages hackage packages
renderPackages :: Hackage -> [Package] -> SnapletISplice App
renderPackages hackage = I.mapSplices $ I.runChildrenWith . packageSplice hackage
packageSplice :: Monad m => Hackage -> Package -> Splices (I.Splice m)
packageSplice hackage p@(Package pn pv) =
do "packageName" ## I.textSplice pn
"packageVersion" ## I.textSplice $ T.pack . showVersion $ pv
"hackageVersion" ## I.textSplice $ T.pack . showVersion $ hv
"packageStatus" ## I.textSplice . statusColor $ pv
where hv = hackageVersion hackage p
statusColor pv = if pv < hv
then "#f9bdbb"
else "#d0f8ce"
handleOutdatedpackages :: AppHandler ()
handleOutdatedpackages = do
hackage <- query QueryHackage
packages <- query QueryPackages
renderWithSplices "outdated"
(packageSplices hackage
(filter (\p -> hackageVersion hackage p > packageVersion p)
packages)
)
handleUpdateHackage :: AppHandler ()
handleUpdateHackage =
do createCheckpoint
a <- getAcidState
liftIO . void . forkIO . void $ cabalUpdate >> readHackage >>= A.scheduleUpdate a . UpdateHackage
where cabalUpdate = callCommand "cabal update -v0"
handleUpdatePackages :: AppHandler ()
handleUpdatePackages =
do createCheckpoint
a <- getAcidState
liftIO . void . forkIO . void $ readPackages >>= A.scheduleUpdate a . UpdatePackages
routes :: [ (ByteString, AppHandler ()) ]
routes = [ ("/", handleIndex)
, ("/updateHackage", handleUpdateHackage)
, ("/updatePackages", handleUpdatePackages)
, ("/outdated", handleOutdatedpackages)
, ("/static", serveDirectory "static")
]
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
a <- nestSnaplet "acid" acid $ acidInit initState
h <- nestSnaplet "" heist $ heistInit "templates"
addRoutes routes
return $ App a h
|
vikraman/gentoo-haskell-status
|
src/Site.hs
|
mit
| 2,997
| 0
| 15
| 837
| 750
| 386
| 364
| -1
| -1
|
module TypedBoolean where
import Control.Monad (liftM)
import Data.Foldable
import Prelude hiding (concat)
data Term = Var Symbol
| App Term Term
| Lambda Symbol Type Term
| Prim Primitive
data Primitive = BoolPrim Bool
| NandPrim
| ZeroPrim
| SuccPrim
data Type = Type :-> Type
| BoolType
| NatType
deriving Eq
type TypingContext = [(Symbol, Type)]
type Symbol = String
check :: TypingContext -> Term -> Either String Type
check _ (Prim (BoolPrim _)) = Right BoolType
check _ (Prim NandPrim) = Right (BoolType :-> (BoolType :-> BoolType))
check _ (Prim ZeroPrim) = Right NatType
check _ (Prim SuccPrim) = Right (NatType :-> NatType)
check context (Var x) = case lookup x context of
Just itsType -> Right itsType
Nothing -> Left ("Type of " ++ x ++ " not in scope")
check context (Lambda x argType term) = liftM (argType :->) (check ((x,argType):context) term)
check context (App t1 t2) = do
(t1Domain :-> t1Codomain) <- check context t1
t2Type <- check context t2
if t2Type == t1Domain
then Right t1Codomain
else Left (concat ["Expected an argument of type ", show t1Domain, ", but got a ", show t2Type, "."])
nand :: Bool -> Bool -> Bool
nand b1 b2 = not (b1 && b2)
instance Show Type where
show BoolType = "Bool"
show (t1@(_ :-> _) :-> t2) = concat ["(", show t1, ") -> ", show t2]
show (t1 :-> t2) = show t1 ++ " -> " ++ show t2
instance Show Primitive where
show (BoolPrim b) = show b
show NandPrim = "⊼"
instance Show Term where
show (Var s) = s
show (Prim p) = show p
show (Lambda x argType term) = concat ["λ", x, ":", show argType, ".", show term]
show (App l@(Lambda _ _ _) t) = concat ["(", show l, ") ", show t]
show (App t l@(Lambda _ _ _)) = concat [show t, " (", show l, ")"]
show (App t1 t2@(App _ _)) = concat [show t1, " (", show t2, ")"]
show (App t1 t2) = show t1 ++ " " ++ show t2
|
michaelblack/LambdaCalc
|
TypedBoolean.hs
|
mit
| 2,066
| 0
| 12
| 609
| 861
| 448
| 413
| 50
| 3
|
module Rebase.Control.Selective
(
module Control.Selective
)
where
import Control.Selective
|
nikita-volkov/rebase
|
library/Rebase/Control/Selective.hs
|
mit
| 95
| 0
| 5
| 12
| 20
| 13
| 7
| 4
| 0
|
module Fass.Printer where
import Control.Lens
import Data.List
import Fass.Types
prettyPrint :: [Entity] -> String
prettyPrint entities = intercalate "\n" $ toListOf (traverse._Just) $ map (printEntity 0) entities
printEntity :: Int -> Entity -> Maybe String
printEntity i (Rule key value) = padded i $ key ++ ": " ++ value ++ ";"
printEntity i (Comment content) = padded i $ "/*" ++ content ++ "*/"
printEntity i (Nested (Ruleset (Selector s) rules)) = padded i $ s ++ " {\n" ++ printedRules rules ++ " }\n"
where
printedRules :: [Entity] -> String
printedRules xs = intercalate "\n" $ toListOf (traverse._Just) $ map (printEntity (i + 2)) xs
printEntity _ _ = fail "Invalid input"
padded :: Int -> String -> Maybe String
padded i s = Just $ replicate i ' ' ++ s
|
darthdeus/fass
|
src/Fass/Printer.hs
|
mit
| 778
| 0
| 12
| 148
| 318
| 159
| 159
| 15
| 1
|
{-# LANGUAGE TemplateHaskell #-}
----------------------------------------------------------------------------------------------------
-- | This module provides a representation of Images that is avaiable for use within the rotatable
-- rectangle bin packing
module RectBinPacker.Image where
----------------------------------------------------------------------------------------------------
import Data.Char (isDigit)
----------------------------------------------------------------------------------------------------
import Control.Lens (view)
import Control.Lens.TH (makeLenses)
----------------------------------------------------------------------------------------------------
import RectBinPacker.BinRotatable (Orientation (..), Rotatable (..))
import RectBinPacker.Geometry (Dim (Dim), HasDim (..))
-- * Image Type
----------------------------------------------------------------------------------------------------
data Image = Image
{ _imageFile :: FilePath -- ^ File path of the image
, _imageDim :: Dim -- ^ Dimensions of the file
, _imageOrientation :: Orientation -- ^ Current orientation of the image
} deriving (Eq, Show)
-- ** Lenses
makeLenses ''Image
----------------------------------------------------------------------------------------------------
instance HasDim Image where
dim = imageDim
----------------------------------------------------------------------------------------------------
instance Rotatable Image where
rotate (Image fp d o) = Image fp (rotate d) (rotate o)
-- * Query
-- ** Orientation
----------------------------------------------------------------------------------------------------
-- | Rotates an image into portrait view. It does nothing if it already is.
orientTall :: Image -> Image
orientTall img
| view dimWidth img > view dimHeight img = rotate img
| otherwise = img
----------------------------------------------------------------------------------------------------
-- | Rotates an image into landscape view. It does nothing if it already is.
orientWide :: Image -> Image
orientWide img
| view dimWidth img < view dimHeight img = rotate img
| otherwise = img
----------------------------------------------------------------------------------------------------
-- | Rotates an image into it's original rotation
upright :: Image -> Image
upright img
| view imageOrientation img /= Upright = rotate img
| otherwise = img
-- * Read
----------------------------------------------------------------------------------------------------
-- | Reads images from a string in the following format:
--
-- @
-- image-name width height
-- image-name width height
-- ...
-- @
--
-- Reading will stop at the first invalid entry
readImages :: String -> [Image]
readImages = toImages . words
where
toImages (name:width:height:rest)
| all isDigit width && all isDigit height =
Image name (Dim (read width) (read height)) Upright : toImages rest
toImages _ = []
|
jochu/image-bin-packing
|
src/RectBinPacker/Image.hs
|
mit
| 3,106
| 0
| 13
| 523
| 469
| 258
| 211
| 35
| 2
|
{-| Generic data loader.
This module holds the common code for parsing the input data after it
has been loaded from external sources.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google 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., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.HTools.Loader
( mergeData
, clearDynU
, checkData
, assignIndices
, setMaster
, lookupNode
, lookupInstance
, lookupGroup
, eitherLive
, commonSuffix
, extractExTags
, updateExclTags
, RqType(..)
, Request(..)
, ClusterData(..)
, emptyCluster
) where
import Control.Monad
import Data.List
import qualified Data.Map as M
import Data.Maybe
import Text.Printf (printf)
import System.Time (ClockTime(..))
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Cluster as Cluster
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import Ganeti.HTools.Types
import Ganeti.Utils
import Ganeti.Types (EvacMode)
-- * Constants
-- | The exclusion tag prefix.
exTagsPrefix :: String
exTagsPrefix = "htools:iextags:"
-- * Types
{-| The iallocator request type.
This type denotes what request we got from Ganeti and also holds
request-specific fields.
-}
data RqType
= Allocate Instance.Instance Int -- ^ A new instance allocation
| Relocate Idx Int [Ndx] -- ^ Choose a new secondary node
| NodeEvacuate [Idx] EvacMode -- ^ node-evacuate mode
| ChangeGroup [Gdx] [Idx] -- ^ Multi-relocate mode
| MultiAllocate [(Instance.Instance, Int)] -- ^ Multi-allocate mode
deriving (Show)
-- | A complete request, as received from Ganeti.
data Request = Request RqType ClusterData
deriving (Show)
-- | The cluster state.
data ClusterData = ClusterData
{ cdGroups :: Group.List -- ^ The node group list
, cdNodes :: Node.List -- ^ The node list
, cdInstances :: Instance.List -- ^ The instance list
, cdTags :: [String] -- ^ The cluster tags
, cdIPolicy :: IPolicy -- ^ The cluster instance policy
} deriving (Show, Eq)
-- | An empty cluster.
emptyCluster :: ClusterData
emptyCluster = ClusterData Container.empty Container.empty Container.empty []
defIPolicy
-- * Functions
-- | Lookups a node into an assoc list.
lookupNode :: (Monad m) => NameAssoc -> String -> String -> m Ndx
lookupNode ktn inst node =
maybe (fail $ "Unknown node '" ++ node ++ "' for instance " ++ inst) return $
M.lookup node ktn
-- | Lookups an instance into an assoc list.
lookupInstance :: (Monad m) => NameAssoc -> String -> m Idx
lookupInstance kti inst =
maybe (fail $ "Unknown instance '" ++ inst ++ "'") return $ M.lookup inst kti
-- | Lookups a group into an assoc list.
lookupGroup :: (Monad m) => NameAssoc -> String -> String -> m Gdx
lookupGroup ktg nname gname =
maybe (fail $ "Unknown group '" ++ gname ++ "' for node " ++ nname) return $
M.lookup gname ktg
-- | Given a list of elements (and their names), assign indices to them.
assignIndices :: (Element a) =>
[(String, a)]
-> (NameAssoc, Container.Container a)
assignIndices name_element =
let (name_idx, idx_element) =
unzip . map (\ (idx, (k, v)) -> ((k, idx), (idx, setIdx v idx)))
. zip [0..] $ name_element
in (M.fromList name_idx, Container.fromList idx_element)
-- | Given am indexed node list, and the name of the master, mark it as such.
setMaster :: (Monad m) => NameAssoc -> Node.List -> String -> m Node.List
setMaster node_names node_idx master = do
kmaster <- maybe (fail $ "Master node " ++ master ++ " unknown") return $
M.lookup master node_names
let mnode = Container.find kmaster node_idx
return $ Container.add kmaster (Node.setMaster mnode True) node_idx
-- | For each instance, add its index to its primary and secondary nodes.
fixNodes :: Node.List
-> Instance.Instance
-> Node.List
fixNodes accu inst =
let pdx = Instance.pNode inst
sdx = Instance.sNode inst
pold = Container.find pdx accu
pnew = Node.setPri pold inst
ac2 = Container.add pdx pnew accu
in if sdx /= Node.noSecondary
then let sold = Container.find sdx accu
snew = Node.setSec sold inst
in Container.add sdx snew ac2
else ac2
-- | Set the node's policy to its group one. Note that this requires
-- the group to exist (should have been checked before), otherwise it
-- will abort with a runtime error.
setNodePolicy :: Group.List -> Node.Node -> Node.Node
setNodePolicy gl node =
let grp = Container.find (Node.group node) gl
gpol = Group.iPolicy grp
in Node.setPolicy gpol node
-- | Update instance with exclusion tags list.
updateExclTags :: [String] -> Instance.Instance -> Instance.Instance
updateExclTags tl inst =
let allTags = Instance.allTags inst
exclTags = filter (\tag -> any (`isPrefixOf` tag) tl) allTags
in inst { Instance.exclTags = exclTags }
-- | Update the movable attribute.
updateMovable :: [String] -- ^ Selected instances (if not empty)
-> [String] -- ^ Excluded instances
-> Instance.Instance -- ^ Target Instance
-> Instance.Instance -- ^ Target Instance with updated attribute
updateMovable selinsts exinsts inst =
if Instance.name inst `elem` exinsts ||
not (null selinsts || Instance.name inst `elem` selinsts)
then Instance.setMovable inst False
else inst
-- | Disables moves for instances with a split group.
disableSplitMoves :: Node.List -> Instance.Instance -> Instance.Instance
disableSplitMoves nl inst =
if not . isOk . Cluster.instanceGroup nl $ inst
then Instance.setMovable inst False
else inst
-- | Set the auto-repair policy for an instance.
setArPolicy :: [String] -- ^ Cluster tags
-> Group.List -- ^ List of node groups
-> Node.List -- ^ List of nodes
-> Instance.List -- ^ List of instances
-> ClockTime -- ^ Current timestamp, to evaluate ArSuspended
-> Instance.List -- ^ Updated list of instances
setArPolicy ctags gl nl il time =
let getArPolicy' = flip getArPolicy time
cpol = fromMaybe ArNotEnabled $ getArPolicy' ctags
gpols = Container.map (fromMaybe cpol . getArPolicy' . Group.allTags) gl
ipolfn = getArPolicy' . Instance.allTags
nlookup = flip Container.find nl . Instance.pNode
glookup = flip Container.find gpols . Node.group . nlookup
updateInstance inst = inst {
Instance.arPolicy = fromMaybe (glookup inst) $ ipolfn inst }
in
Container.map updateInstance il
-- | Get the auto-repair policy from a list of tags.
--
-- This examines the ganeti:watcher:autorepair and
-- ganeti:watcher:autorepair:suspend tags to determine the policy. If none of
-- these tags are present, Nothing (and not ArNotEnabled) is returned.
getArPolicy :: [String] -> ClockTime -> Maybe AutoRepairPolicy
getArPolicy tags time =
let enabled = mapMaybe (autoRepairTypeFromRaw <=<
chompPrefix C.autoRepairTagEnabled) tags
suspended = mapMaybe (chompPrefix C.autoRepairTagSuspended) tags
futureTs = filter (> time) . map (flip TOD 0) $
mapMaybe (tryRead "auto-repair suspend time") suspended
in
case () of
-- Note how we must return ArSuspended even if "enabled" is empty, so that
-- node groups or instances can suspend repairs that were enabled at an
-- upper scope (cluster or node group).
_ | "" `elem` suspended -> Just $ ArSuspended Forever
| not $ null futureTs -> Just . ArSuspended . Until . maximum $ futureTs
| not $ null enabled -> Just $ ArEnabled (minimum enabled)
| otherwise -> Nothing
-- | Compute the longest common suffix of a list of strings that
-- starts with a dot.
longestDomain :: [String] -> String
longestDomain [] = ""
longestDomain (x:xs) =
foldr (\ suffix accu -> if all (isSuffixOf suffix) xs
then suffix
else accu)
"" $ filter (isPrefixOf ".") (tails x)
-- | Extracts the exclusion tags from the cluster configuration.
extractExTags :: [String] -> [String]
extractExTags = filter (not . null) . mapMaybe (chompPrefix exTagsPrefix)
-- | Extracts the common suffix from node\/instance names.
commonSuffix :: Node.List -> Instance.List -> String
commonSuffix nl il =
let node_names = map Node.name $ Container.elems nl
inst_names = map Instance.name $ Container.elems il
in longestDomain (node_names ++ inst_names)
-- | Initializer function that loads the data from a node and instance
-- list and massages it into the correct format.
mergeData :: [(String, DynUtil)] -- ^ Instance utilisation data
-> [String] -- ^ Exclusion tags
-> [String] -- ^ Selected instances (if not empty)
-> [String] -- ^ Excluded instances
-> ClockTime -- ^ The current timestamp
-> ClusterData -- ^ Data from backends
-> Result ClusterData -- ^ Fixed cluster data
mergeData um extags selinsts exinsts time cdata@(ClusterData gl nl il ctags _) =
let il2 = setArPolicy ctags gl nl il time
il3 = foldl' (\im (name, n_util) ->
case Container.findByName im name of
Nothing -> im -- skipping unknown instance
Just inst ->
let new_i = inst { Instance.util = n_util }
in Container.add (Instance.idx inst) new_i im
) il2 um
allextags = extags ++ extractExTags ctags
inst_names = map Instance.name $ Container.elems il3
selinst_lkp = map (lookupName inst_names) selinsts
exinst_lkp = map (lookupName inst_names) exinsts
lkp_unknown = filter (not . goodLookupResult) (selinst_lkp ++ exinst_lkp)
selinst_names = map lrContent selinst_lkp
exinst_names = map lrContent exinst_lkp
node_names = map Node.name (Container.elems nl)
common_suffix = longestDomain (node_names ++ inst_names)
il4 = Container.map (computeAlias common_suffix .
updateExclTags allextags .
updateMovable selinst_names exinst_names) il3
nl2 = foldl' fixNodes nl (Container.elems il4)
nl3 = Container.map (setNodePolicy gl .
computeAlias common_suffix .
(`Node.buildPeers` il4)) nl2
il5 = Container.map (disableSplitMoves nl3) il4
in if' (null lkp_unknown)
(Ok cdata { cdNodes = nl3, cdInstances = il5 })
(Bad $ "Unknown instance(s): " ++ show(map lrContent lkp_unknown))
-- | In a cluster description, clear dynamic utilisation information.
clearDynU :: ClusterData -> Result ClusterData
clearDynU cdata@(ClusterData _ _ il _ _) =
let il2 = Container.map (\ inst -> inst {Instance.util = zeroUtil }) il
in Ok cdata { cdInstances = il2 }
-- | Checks the cluster data for consistency.
checkData :: Node.List -> Instance.List
-> ([String], Node.List)
checkData nl il =
Container.mapAccum
(\ msgs node ->
let nname = Node.name node
nilst = map (`Container.find` il) (Node.pList node)
dilst = filter Instance.instanceDown nilst
adj_mem = sum . map Instance.mem $ dilst
delta_mem = truncate (Node.tMem node)
- Node.nMem node
- Node.fMem node
- nodeImem node il
+ adj_mem
delta_dsk = truncate (Node.tDsk node)
- Node.fDsk node
- nodeIdsk node il
newn = Node.setFmem (Node.setXmem node delta_mem)
(Node.fMem node - adj_mem)
umsg1 =
if delta_mem > 512 || delta_dsk > 1024
then printf "node %s is missing %d MB ram \
\and %d GB disk"
nname delta_mem (delta_dsk `div` 1024):msgs
else msgs
in (umsg1, newn)
) [] nl
-- | Compute the amount of memory used by primary instances on a node.
nodeImem :: Node.Node -> Instance.List -> Int
nodeImem node il =
let rfind = flip Container.find il
il' = map rfind $ Node.pList node
oil' = filter Instance.notOffline il'
in sum . map Instance.mem $ oil'
-- | Compute the amount of disk used by instances on a node (either primary
-- or secondary).
nodeIdsk :: Node.Node -> Instance.List -> Int
nodeIdsk node il =
let rfind = flip Container.find il
in sum . map (Instance.dsk . rfind)
$ Node.pList node ++ Node.sList node
-- | Get live information or a default value
eitherLive :: (Monad m) => Bool -> a -> m a -> m a
eitherLive True _ live_data = live_data
eitherLive False def_data _ = return def_data
|
kawamuray/ganeti
|
src/Ganeti/HTools/Loader.hs
|
gpl-2.0
| 13,861
| 0
| 20
| 3,774
| 3,147
| 1,678
| 1,469
| 239
| 2
|
{-# LANGUAGE StandaloneDeriving #-}
module System.Watchque.Cli (
dumpWq,
dumpPkt,
argv2wqll,
str2wql,
str2wq,
str2evl,
ev2we
) where
import System.Watchque.Include
(Watch(..), WatchPacket(..), WatchArg(..), WatchEvent)
import System.INotify
(EventVariety(..))
import Text.Regex
(mkRegex)
import Data.List
(nub)
import qualified System.DevUtils.Base.Data.List as DUL
(split)
deriving instance Show EventVariety
dumpWq :: Watch -> String
dumpWq wq =
"Dumping watch:" ++
"\n\tsource: " ++ _source aw ++
"\n\tclass: " ++ _class aw ++
"\n\tqueue: " ++ _queue aw ++
"\n\tevents: " ++ _events aw ++
"\n\tfilter: " ++ (show (_filter aw)) ++
"\n\tmask: " ++ show (_mask wq) ++
"\n\trecursive: " ++
show (_rec wq) ++ "\n"
where
aw = _arg wq
dumpPkt :: WatchPacket -> String
dumpPkt pkt =
"Dumping pkt:" ++
"\n\tpath: " ++ _f pkt ++
"\n\tevent: " ++ show (_e pkt) ++
"\n\tdirectory: " ++ show (_d pkt) ++
"\n\n\t"++(dumpWq $ _w pkt) ++ "\n"
argv2wqll :: [String] -> [[Watch]]
argv2wqll ss = map str2wql ss
str2wql :: String -> [Watch]
str2wql s = map str2wq
(map
(\x -> WatchArg {
_class = h !! 0,
_queue = h !! 1,
_events = h !! 2,
_source = x,
_filter = if length h > 4 then Just (h !! 4) else Nothing,
_filterRe = if length h > 4 then Just (mkRegex (h !! 4)) else Nothing
}
)
t)
where
h = DUL.split ':' s
t = DUL.split ',' (h !! 3)
str2wq :: WatchArg -> Watch
str2wq wa = Watch {
_arg = wa,
_rec = not $ any (=='N') events,
_mask = str2evl events
}
where
events = _events wa
str2evl :: String -> [EventVariety]
str2evl [] = []
str2evl (s:ss) = nub $ ev ++ str2evl ss
where
ev = case s of
'a' -> [AllEvents,Create,MoveIn,Modify,Delete,DeleteSelf,MoveSelf,MoveOut,CloseWrite,CloseNoWrite,Attrib]
'c' -> [Create, MoveIn]
'u' -> [Modify, Attrib]
'd' -> [Delete, DeleteSelf, MoveOut]
'D' -> [Delete, DeleteSelf]
'r' -> [MoveSelf, MoveOut]
'C' -> [CloseWrite]
'A' -> [Attrib]
'M' -> [Modify]
'U' -> [Modify]
'I' -> [MoveIn]
'O' -> [MoveOut]
'Z' -> [Create]
_ -> []
ev2we :: EventVariety -> WatchEvent
ev2we ev = case ev of
Attrib -> ("MODIFY","ATTRIB")
Create -> ("CREATE","CREATE")
Delete -> ("DELETE","DELETE")
Access -> ("ACCESS","ACCESS")
Modify -> ("MODIFY","MODIFY")
MoveIn -> ("CREATE","MOVEIN")
MoveOut -> ("DELETE","MOVEOUT")
MoveSelf -> ("DELETE","MOVESELF")
Open -> ("OPEN","OPEN")
Close -> ("CLOSE","CLOSE")
CloseWrite -> ("CLOSE_WRITE","CLOSE")
CloseNoWrite -> ("CLOSE_NOWRITE","CLOSE")
_ -> ("UNKNOWN","UNKNOWN")
|
adarqui/Watchque
|
src/System/Watchque/Cli.hs
|
gpl-3.0
| 2,552
| 0
| 19
| 520
| 1,019
| 569
| 450
| 93
| 14
|
{-# LANGUAGE OverloadedLists #-}
module Kalkulu.Builtin.Logic (logicBuiltins) where
import Kalkulu.Builtin
import qualified Kalkulu.BuiltinSymbol as B
import qualified Data.Vector as V
logicBuiltins :: [(B.BuiltinSymbol, BuiltinDefinition)]
logicBuiltins = [
(B.True, true)
, (B.False, false)
, (B.And, and_)
-- , (B.Or, or_)
]
true :: BuiltinDefinition
true = defaultBuiltin { attributes = [Locked, Protected] }
false :: BuiltinDefinition
false = defaultBuiltin { attributes = [Locked, Protected] }
and_ :: BuiltinDefinition
and_ = defaultBuiltin {
attributes = [Flat, HoldAll, OneIdentity, Protected],
downcode = downcodeAnd
}
andArgs :: [Expression] -> Kernel (Maybe [Expression])
andArgs [] = return (Just [])
andArgs (h:t) = do
h_ev <- evaluate h
case h_ev of
SymbolB B.True -> andArgs t
SymbolB B.False -> return Nothing
_ -> andArgs t >>= return . (put h_ev)
where put _ Nothing = Nothing
put h (Just t) = Just (h:t)
downcodeAnd :: Expression -> Kernel Expression
downcodeAnd (Cmp _ args) = do
args' <- andArgs (V.toList args)
return $ case args' of
Nothing -> toExpression False
Just [] -> toExpression True
Just es -> CmpB B.And (V.fromList es)
|
vizietto/kalkulu
|
src/Kalkulu/Builtin/Logic.hs
|
gpl-3.0
| 1,241
| 0
| 14
| 262
| 443
| 240
| 203
| 35
| 4
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.CustomSearch.Types.Sum
-- 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)
--
module Network.Google.CustomSearch.Types.Sum where
import Network.Google.Prelude
-- | Returns images of a type, which can be one of: clipart, face, lineart,
-- news, and photo.
data CSEListImgType
= CliPart
-- ^ @clipart@
-- clipart
| Face
-- ^ @face@
-- face
| Lineart
-- ^ @lineart@
-- lineart
| News
-- ^ @news@
-- news
| Photo
-- ^ @photo@
-- photo
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListImgType
instance FromHttpApiData CSEListImgType where
parseQueryParam = \case
"clipart" -> Right CliPart
"face" -> Right Face
"lineart" -> Right Lineart
"news" -> Right News
"photo" -> Right Photo
x -> Left ("Unable to parse CSEListImgType from: " <> x)
instance ToHttpApiData CSEListImgType where
toQueryParam = \case
CliPart -> "clipart"
Face -> "face"
Lineart -> "lineart"
News -> "news"
Photo -> "photo"
instance FromJSON CSEListImgType where
parseJSON = parseJSONText "CSEListImgType"
instance ToJSON CSEListImgType where
toJSON = toJSONText
-- | Controls whether to include or exclude results from the site named in
-- the as_sitesearch parameter
data CSEListSiteSearchFilter
= E
-- ^ @e@
-- exclude
| I
-- ^ @i@
-- include
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListSiteSearchFilter
instance FromHttpApiData CSEListSiteSearchFilter where
parseQueryParam = \case
"e" -> Right E
"i" -> Right I
x -> Left ("Unable to parse CSEListSiteSearchFilter from: " <> x)
instance ToHttpApiData CSEListSiteSearchFilter where
toQueryParam = \case
E -> "e"
I -> "i"
instance FromJSON CSEListSiteSearchFilter where
parseJSON = parseJSONText "CSEListSiteSearchFilter"
instance ToJSON CSEListSiteSearchFilter where
toJSON = toJSONText
-- | Returns images of a specific dominant color: yellow, green, teal, blue,
-- purple, pink, white, gray, black and brown.
data CSEListImgDominantColor
= Black
-- ^ @black@
-- black
| Blue
-- ^ @blue@
-- blue
| Brown
-- ^ @brown@
-- brown
| Gray
-- ^ @gray@
-- gray
| Green
-- ^ @green@
-- green
| Pink
-- ^ @pink@
-- pink
| Purple
-- ^ @purple@
-- purple
| Teal
-- ^ @teal@
-- teal
| White
-- ^ @white@
-- white
| Yellow
-- ^ @yellow@
-- yellow
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListImgDominantColor
instance FromHttpApiData CSEListImgDominantColor where
parseQueryParam = \case
"black" -> Right Black
"blue" -> Right Blue
"brown" -> Right Brown
"gray" -> Right Gray
"green" -> Right Green
"pink" -> Right Pink
"purple" -> Right Purple
"teal" -> Right Teal
"white" -> Right White
"yellow" -> Right Yellow
x -> Left ("Unable to parse CSEListImgDominantColor from: " <> x)
instance ToHttpApiData CSEListImgDominantColor where
toQueryParam = \case
Black -> "black"
Blue -> "blue"
Brown -> "brown"
Gray -> "gray"
Green -> "green"
Pink -> "pink"
Purple -> "purple"
Teal -> "teal"
White -> "white"
Yellow -> "yellow"
instance FromJSON CSEListImgDominantColor where
parseJSON = parseJSONText "CSEListImgDominantColor"
instance ToJSON CSEListImgDominantColor where
toJSON = toJSONText
-- | Search safety level
data CSEListSafe
= High
-- ^ @high@
-- Enables highest level of safe search filtering.
| Medium
-- ^ @medium@
-- Enables moderate safe search filtering.
| Off
-- ^ @off@
-- Disables safe search filtering.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListSafe
instance FromHttpApiData CSEListSafe where
parseQueryParam = \case
"high" -> Right High
"medium" -> Right Medium
"off" -> Right Off
x -> Left ("Unable to parse CSEListSafe from: " <> x)
instance ToHttpApiData CSEListSafe where
toQueryParam = \case
High -> "high"
Medium -> "medium"
Off -> "off"
instance FromJSON CSEListSafe where
parseJSON = parseJSONText "CSEListSafe"
instance ToJSON CSEListSafe where
toJSON = toJSONText
-- | Returns black and white, grayscale, or color images: mono, gray, and
-- color.
data CSEListImgColorType
= CSELICTColor
-- ^ @color@
-- color
| CSELICTGray
-- ^ @gray@
-- gray
| CSELICTMono
-- ^ @mono@
-- mono
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListImgColorType
instance FromHttpApiData CSEListImgColorType where
parseQueryParam = \case
"color" -> Right CSELICTColor
"gray" -> Right CSELICTGray
"mono" -> Right CSELICTMono
x -> Left ("Unable to parse CSEListImgColorType from: " <> x)
instance ToHttpApiData CSEListImgColorType where
toQueryParam = \case
CSELICTColor -> "color"
CSELICTGray -> "gray"
CSELICTMono -> "mono"
instance FromJSON CSEListImgColorType where
parseJSON = parseJSONText "CSEListImgColorType"
instance ToJSON CSEListImgColorType where
toJSON = toJSONText
-- | Controls turning on or off the duplicate content filter.
data CSEListFilter
= CSELF0
-- ^ @0@
-- Turns off duplicate content filter.
| CSELF1
-- ^ @1@
-- Turns on duplicate content filter.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListFilter
instance FromHttpApiData CSEListFilter where
parseQueryParam = \case
"0" -> Right CSELF0
"1" -> Right CSELF1
x -> Left ("Unable to parse CSEListFilter from: " <> x)
instance ToHttpApiData CSEListFilter where
toQueryParam = \case
CSELF0 -> "0"
CSELF1 -> "1"
instance FromJSON CSEListFilter where
parseJSON = parseJSONText "CSEListFilter"
instance ToJSON CSEListFilter where
toJSON = toJSONText
-- | The language restriction for the search results
data CSEListLr
= LangAr
-- ^ @lang_ar@
-- Arabic
| LangBg
-- ^ @lang_bg@
-- Bulgarian
| LangCa
-- ^ @lang_ca@
-- Catalan
| LangCs
-- ^ @lang_cs@
-- Czech
| LangDa
-- ^ @lang_da@
-- Danish
| LangDe
-- ^ @lang_de@
-- German
| LangEl
-- ^ @lang_el@
-- Greek
| LangEn
-- ^ @lang_en@
-- English
| LangEs
-- ^ @lang_es@
-- Spanish
| LangEt
-- ^ @lang_et@
-- Estonian
| LangFi
-- ^ @lang_fi@
-- Finnish
| LangFr
-- ^ @lang_fr@
-- French
| LangHr
-- ^ @lang_hr@
-- Croatian
| LangHu
-- ^ @lang_hu@
-- Hungarian
| LangId
-- ^ @lang_id@
-- Indonesian
| LangIs
-- ^ @lang_is@
-- Icelandic
| LangIt
-- ^ @lang_it@
-- Italian
| LangIw
-- ^ @lang_iw@
-- Hebrew
| LangJa
-- ^ @lang_ja@
-- Japanese
| LangKo
-- ^ @lang_ko@
-- Korean
| LangLT
-- ^ @lang_lt@
-- Lithuanian
| LangLv
-- ^ @lang_lv@
-- Latvian
| LangNl
-- ^ @lang_nl@
-- Dutch
| LangNo
-- ^ @lang_no@
-- Norwegian
| LangPl
-- ^ @lang_pl@
-- Polish
| LangPt
-- ^ @lang_pt@
-- Portuguese
| LangRo
-- ^ @lang_ro@
-- Romanian
| LangRu
-- ^ @lang_ru@
-- Russian
| LangSk
-- ^ @lang_sk@
-- Slovak
| LangSl
-- ^ @lang_sl@
-- Slovenian
| LangSr
-- ^ @lang_sr@
-- Serbian
| LangSv
-- ^ @lang_sv@
-- Swedish
| LangTr
-- ^ @lang_tr@
-- Turkish
| LangZhCn
-- ^ @lang_zh-CN@
-- Chinese (Simplified)
| LangZhTw
-- ^ @lang_zh-TW@
-- Chinese (Traditional)
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListLr
instance FromHttpApiData CSEListLr where
parseQueryParam = \case
"lang_ar" -> Right LangAr
"lang_bg" -> Right LangBg
"lang_ca" -> Right LangCa
"lang_cs" -> Right LangCs
"lang_da" -> Right LangDa
"lang_de" -> Right LangDe
"lang_el" -> Right LangEl
"lang_en" -> Right LangEn
"lang_es" -> Right LangEs
"lang_et" -> Right LangEt
"lang_fi" -> Right LangFi
"lang_fr" -> Right LangFr
"lang_hr" -> Right LangHr
"lang_hu" -> Right LangHu
"lang_id" -> Right LangId
"lang_is" -> Right LangIs
"lang_it" -> Right LangIt
"lang_iw" -> Right LangIw
"lang_ja" -> Right LangJa
"lang_ko" -> Right LangKo
"lang_lt" -> Right LangLT
"lang_lv" -> Right LangLv
"lang_nl" -> Right LangNl
"lang_no" -> Right LangNo
"lang_pl" -> Right LangPl
"lang_pt" -> Right LangPt
"lang_ro" -> Right LangRo
"lang_ru" -> Right LangRu
"lang_sk" -> Right LangSk
"lang_sl" -> Right LangSl
"lang_sr" -> Right LangSr
"lang_sv" -> Right LangSv
"lang_tr" -> Right LangTr
"lang_zh-CN" -> Right LangZhCn
"lang_zh-TW" -> Right LangZhTw
x -> Left ("Unable to parse CSEListLr from: " <> x)
instance ToHttpApiData CSEListLr where
toQueryParam = \case
LangAr -> "lang_ar"
LangBg -> "lang_bg"
LangCa -> "lang_ca"
LangCs -> "lang_cs"
LangDa -> "lang_da"
LangDe -> "lang_de"
LangEl -> "lang_el"
LangEn -> "lang_en"
LangEs -> "lang_es"
LangEt -> "lang_et"
LangFi -> "lang_fi"
LangFr -> "lang_fr"
LangHr -> "lang_hr"
LangHu -> "lang_hu"
LangId -> "lang_id"
LangIs -> "lang_is"
LangIt -> "lang_it"
LangIw -> "lang_iw"
LangJa -> "lang_ja"
LangKo -> "lang_ko"
LangLT -> "lang_lt"
LangLv -> "lang_lv"
LangNl -> "lang_nl"
LangNo -> "lang_no"
LangPl -> "lang_pl"
LangPt -> "lang_pt"
LangRo -> "lang_ro"
LangRu -> "lang_ru"
LangSk -> "lang_sk"
LangSl -> "lang_sl"
LangSr -> "lang_sr"
LangSv -> "lang_sv"
LangTr -> "lang_tr"
LangZhCn -> "lang_zh-CN"
LangZhTw -> "lang_zh-TW"
instance FromJSON CSEListLr where
parseJSON = parseJSONText "CSEListLr"
instance ToJSON CSEListLr where
toJSON = toJSONText
-- | Specifies the search type: image.
data CSEListSearchType
= Image
-- ^ @image@
-- custom image search
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListSearchType
instance FromHttpApiData CSEListSearchType where
parseQueryParam = \case
"image" -> Right Image
x -> Left ("Unable to parse CSEListSearchType from: " <> x)
instance ToHttpApiData CSEListSearchType where
toQueryParam = \case
Image -> "image"
instance FromJSON CSEListSearchType where
parseJSON = parseJSONText "CSEListSearchType"
instance ToJSON CSEListSearchType where
toJSON = toJSONText
-- | Returns images of a specified size, where size can be one of: icon,
-- small, medium, large, xlarge, xxlarge, and huge.
data CSEListImgSize
= CSELISHuge
-- ^ @huge@
-- huge
| CSELISIcon
-- ^ @icon@
-- icon
| CSELISLarge
-- ^ @large@
-- large
| CSELISMedium
-- ^ @medium@
-- medium
| CSELISSmall
-- ^ @small@
-- small
| CSELISXlarge
-- ^ @xlarge@
-- xlarge
| CSELISXxlarge
-- ^ @xxlarge@
-- xxlarge
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CSEListImgSize
instance FromHttpApiData CSEListImgSize where
parseQueryParam = \case
"huge" -> Right CSELISHuge
"icon" -> Right CSELISIcon
"large" -> Right CSELISLarge
"medium" -> Right CSELISMedium
"small" -> Right CSELISSmall
"xlarge" -> Right CSELISXlarge
"xxlarge" -> Right CSELISXxlarge
x -> Left ("Unable to parse CSEListImgSize from: " <> x)
instance ToHttpApiData CSEListImgSize where
toQueryParam = \case
CSELISHuge -> "huge"
CSELISIcon -> "icon"
CSELISLarge -> "large"
CSELISMedium -> "medium"
CSELISSmall -> "small"
CSELISXlarge -> "xlarge"
CSELISXxlarge -> "xxlarge"
instance FromJSON CSEListImgSize where
parseJSON = parseJSONText "CSEListImgSize"
instance ToJSON CSEListImgSize where
toJSON = toJSONText
|
rueshyna/gogol
|
gogol-customsearch/gen/Network/Google/CustomSearch/Types/Sum.hs
|
mpl-2.0
| 13,473
| 0
| 11
| 4,200
| 2,492
| 1,345
| 1,147
| 320
| 0
|
{-# 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.FireStore.Projects.Databases.CollectionGroups.Fields.Get
-- 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)
--
-- Gets the metadata and configuration for a Field.
--
-- /See:/ <https://cloud.google.com/firestore Cloud Firestore API Reference> for @firestore.projects.databases.collectionGroups.fields.get@.
module Network.Google.Resource.FireStore.Projects.Databases.CollectionGroups.Fields.Get
(
-- * REST Resource
ProjectsDatabasesCollectionGroupsFieldsGetResource
-- * Creating a Request
, projectsDatabasesCollectionGroupsFieldsGet
, ProjectsDatabasesCollectionGroupsFieldsGet
-- * Request Lenses
, pdcgfgXgafv
, pdcgfgUploadProtocol
, pdcgfgAccessToken
, pdcgfgUploadType
, pdcgfgName
, pdcgfgCallback
) where
import Network.Google.FireStore.Types
import Network.Google.Prelude
-- | A resource alias for @firestore.projects.databases.collectionGroups.fields.get@ method which the
-- 'ProjectsDatabasesCollectionGroupsFieldsGet' request conforms to.
type ProjectsDatabasesCollectionGroupsFieldsGetResource
=
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GoogleFirestoreAdminV1Field
-- | Gets the metadata and configuration for a Field.
--
-- /See:/ 'projectsDatabasesCollectionGroupsFieldsGet' smart constructor.
data ProjectsDatabasesCollectionGroupsFieldsGet =
ProjectsDatabasesCollectionGroupsFieldsGet'
{ _pdcgfgXgafv :: !(Maybe Xgafv)
, _pdcgfgUploadProtocol :: !(Maybe Text)
, _pdcgfgAccessToken :: !(Maybe Text)
, _pdcgfgUploadType :: !(Maybe Text)
, _pdcgfgName :: !Text
, _pdcgfgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsDatabasesCollectionGroupsFieldsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pdcgfgXgafv'
--
-- * 'pdcgfgUploadProtocol'
--
-- * 'pdcgfgAccessToken'
--
-- * 'pdcgfgUploadType'
--
-- * 'pdcgfgName'
--
-- * 'pdcgfgCallback'
projectsDatabasesCollectionGroupsFieldsGet
:: Text -- ^ 'pdcgfgName'
-> ProjectsDatabasesCollectionGroupsFieldsGet
projectsDatabasesCollectionGroupsFieldsGet pPdcgfgName_ =
ProjectsDatabasesCollectionGroupsFieldsGet'
{ _pdcgfgXgafv = Nothing
, _pdcgfgUploadProtocol = Nothing
, _pdcgfgAccessToken = Nothing
, _pdcgfgUploadType = Nothing
, _pdcgfgName = pPdcgfgName_
, _pdcgfgCallback = Nothing
}
-- | V1 error format.
pdcgfgXgafv :: Lens' ProjectsDatabasesCollectionGroupsFieldsGet (Maybe Xgafv)
pdcgfgXgafv
= lens _pdcgfgXgafv (\ s a -> s{_pdcgfgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pdcgfgUploadProtocol :: Lens' ProjectsDatabasesCollectionGroupsFieldsGet (Maybe Text)
pdcgfgUploadProtocol
= lens _pdcgfgUploadProtocol
(\ s a -> s{_pdcgfgUploadProtocol = a})
-- | OAuth access token.
pdcgfgAccessToken :: Lens' ProjectsDatabasesCollectionGroupsFieldsGet (Maybe Text)
pdcgfgAccessToken
= lens _pdcgfgAccessToken
(\ s a -> s{_pdcgfgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pdcgfgUploadType :: Lens' ProjectsDatabasesCollectionGroupsFieldsGet (Maybe Text)
pdcgfgUploadType
= lens _pdcgfgUploadType
(\ s a -> s{_pdcgfgUploadType = a})
-- | Required. A name of the form
-- \`projects\/{project_id}\/databases\/{database_id}\/collectionGroups\/{collection_id}\/fields\/{field_id}\`
pdcgfgName :: Lens' ProjectsDatabasesCollectionGroupsFieldsGet Text
pdcgfgName
= lens _pdcgfgName (\ s a -> s{_pdcgfgName = a})
-- | JSONP
pdcgfgCallback :: Lens' ProjectsDatabasesCollectionGroupsFieldsGet (Maybe Text)
pdcgfgCallback
= lens _pdcgfgCallback
(\ s a -> s{_pdcgfgCallback = a})
instance GoogleRequest
ProjectsDatabasesCollectionGroupsFieldsGet
where
type Rs ProjectsDatabasesCollectionGroupsFieldsGet =
GoogleFirestoreAdminV1Field
type Scopes
ProjectsDatabasesCollectionGroupsFieldsGet
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/datastore"]
requestClient
ProjectsDatabasesCollectionGroupsFieldsGet'{..}
= go _pdcgfgName _pdcgfgXgafv _pdcgfgUploadProtocol
_pdcgfgAccessToken
_pdcgfgUploadType
_pdcgfgCallback
(Just AltJSON)
fireStoreService
where go
= buildClient
(Proxy ::
Proxy
ProjectsDatabasesCollectionGroupsFieldsGetResource)
mempty
|
brendanhay/gogol
|
gogol-firestore/gen/Network/Google/Resource/FireStore/Projects/Databases/CollectionGroups/Fields/Get.hs
|
mpl-2.0
| 5,677
| 0
| 15
| 1,205
| 701
| 411
| 290
| 111
| 1
|
module AlecAirport.A284918 (a284918) where
import Data.List (find, nub)
import Helpers.GridLabeling (pairs, onALine, onLine, everyPair)
a284918 n = map snd a284918_list !! (n - 1)
-- Lexicographically earliest sequence of positive integers such that no three distinct points (i, a(i)), (j, a(j)), (k, a(k)) form an isosceles triangle (including degenerate isosceles triangles).
a284918_list = (0,1) : recurse 1 where
recurse i = (i, nextTerm) : recurse (i + 1) where
nextTerm = head $ filter noIsosceles [1..] where
noIsosceles a_k = all (not . isoceles) $ everyPair $ take i a284918_list where
pk = (i, a_k)
isoceles (p0, p1)
| euclideanDistance p0 p1 == euclideanDistance p0 pk = True
| euclideanDistance p0 p1 == euclideanDistance p1 pk = True
| euclideanDistance p0 pk == euclideanDistance p1 pk = True
| otherwise = False
euclideanDistance (x_0, y_0) (x_1, y_1) = (x_0 - x_1)^2 + (y_0 - y_1)^2
|
peterokagey/haskellOEIS
|
src/AlecAirport/A284918.hs
|
apache-2.0
| 969
| 0
| 17
| 215
| 318
| 167
| 151
| 15
| 1
|
module Speed where
import Unit
import GPS
import Type
import CommandControl
type Speed = Double
-- | Default, unmodified speed in km/h
speedDefault :: Type -> Speed
speedDefault _ = 20
speedApplyCommandControl :: Speed -> CommandControlStatus -> Speed
speedApplyCommandControl s cnc = s * coeff
where
coeff = case cnc of
CommandControlGood -> 1
CommandControlAverage -> 0.8
CommandControlBad -> 0.6
CommandControlOffline -> 0.5
|
nbrk/ld
|
library/Speed.hs
|
bsd-2-clause
| 465
| 0
| 9
| 100
| 102
| 57
| 45
| 15
| 4
|
{-Joseph Eremondi UU# 4229924
Utrecht University, APA 2015
Project one: dataflow analysis
March 17, 2015 -}
module Optimize.Environment where
import AST.Annotation
import AST.Expression.General
import qualified AST.Pattern as Pattern
import qualified AST.Variable as Var
import qualified Data.Map as Map hiding ((!))
import Elm.Compiler.Module
import Optimize.Types
--import AST.Expression.Canonical as Canon
-- | Convert a raw string into a "local" variable
makeLocal :: String -> Var
makeLocal s = Var.Canonical (Var.Local) s
{-|
Given a name with the module path for a variable, and a variable with no module information,
add the proper module information to that variable
|-}
addContext :: Name -> Var -> Var
addContext (Name modList) (Var.Canonical Var.Local name) = Var.Canonical (Var.Module modList) name
addContext _ v = v
{-|
Useful for converting between Name, which is used in the Public Elm.Compiler interface,
and Var, which is used internally in the AST
|-}
nameToVar :: Name -> Var
nameToVar (Name lReversed) = case l of
[] -> error "Can't have a name with no name!"
[n] -> Var.Canonical Var.Local n
(n:reversedPath) -> Var.Canonical (Var.Module $ reverse reversedPath) n
where l = reverse lReversed
{-|
Given a pattern i.e. the left hand of a definition, or function argument,
return the list of variables defined by that pattern.
|-}
getPatternVars :: Pattern.CanonicalPattern -> [Var]
getPatternVars (Pattern.Data _ pats) = concatMap getPatternVars pats
getPatternVars (Pattern.Record strs) = map makeLocal strs --TODO check this case
getPatternVars (Pattern.Alias s p) = [makeLocal s] ++ (getPatternVars p) --TODO check this case
getPatternVars (Pattern.Var s) = [makeLocal s]
getPatternVars Pattern.Anything = []
getPatternVars (Pattern.Literal _) = []
{-|
Given a function which finds all variables defined in a definition,
A function mapping expressions to our target information type,
an initial expression, and an initial environment,
return an infinite list of environments.
This is used as the "context"-generating function, passing environments
down the AST, in our tree traversals for annotating ASTs.
|-}
extendEnv
:: (Ord l)
=> (d -> [Var])
-> (Expr a d Var -> l)
-> Expr a d Var
-> Env l
-> [Env l]
extendEnv getDefined getLabelFn expr env = case expr of
A _ann (Let defs _body) ->
repeat $ Map.union env $ Map.fromList $ [(v, label) | v <- concatMap getDefined defs]
A _ann (Lambda pat _fnBody) ->
repeat $ Map.union env $ Map.fromList $ [(v, label) | v <- getPatternVars pat]
_ -> repeat env
where label = getLabelFn expr
{-|
Given the expression for a module, generate the environment containing only
the top-level "global" definitions for that module.
|-}
--TODO do we need to use list fn from traversals?
globalEnv :: LabeledExpr -> Env Label
globalEnv expr =
let
(A (_,label,_) (Let defs _)) = expr
in foldr (\(GenericDef pat _ _) env ->
foldr (\v newEnv -> Map.insert v label newEnv) env (getPatternVars pat)) Map.empty defs
|
JoeyEremondi/utrecht-apa-p1
|
src/Optimize/Environment.hs
|
bsd-3-clause
| 3,116
| 0
| 14
| 620
| 751
| 395
| 356
| 46
| 3
|
import Trello.Data
key = OAuth {
oauthKey = "917e6c62f30b19fd332b5b93d582c43b"
,oauthToken = "temp"
}
|
vamega/haskell-trello
|
src/trello.hs
|
bsd-3-clause
| 111
| 0
| 6
| 22
| 25
| 15
| 10
| 4
| 1
|
import Control.Concurrent
import Control.Monad
import Data.ByteString.Lazy(ByteString, pack)
import qualified Data.ByteString.Lazy as BS
import Data.Word
import Hypervisor.Console
import Hypervisor.Debug
import Hypervisor.XenStore
import XenDevice.Disk
main :: IO ()
main = do
writeDebugConsole "Starting system!\n"
con <- initXenConsole
writeConsole con "Starting Disk device tests.\n"
xs <- initXenStore
writeDebugConsole "XenStore initialized!\n"
disks <- listDisks xs
threadDelay (1000000)
writeConsole con ("Found " ++ show (length disks) ++ " disks:\n")
forM_ disks $ \ d -> writeConsole con (" " ++ d ++ "\n")
writeConsole con "\n"
diskinfos <- zip disks `fmap` mapM (openDisk xs) disks
forM_ diskinfos $ \ (dname, d) -> do
writeConsole con ("Information about " ++ dname ++ ":\n")
writeConsole con (" # Sectors: " ++ show (diskSectors d) ++ "\n")
writeConsole con (" Sector size: " ++ show (diskSectorSize d) ++ "\n")
writeConsole con (" isReadOnly: " ++ show (isDiskReadOnly d) ++ "\n")
writeConsole con (" isDiskRemovable: " ++ show (isDiskRemovable d)++"\n")
writeConsole con (" diskSupportsBarrier: " ++
show (diskSupportsBarrier d) ++ "\n")
writeConsole con (" diskSupportsFlush: " ++
show (diskSupportsFlush d) ++ "\n")
writeConsole con (" diskSupportsDiscard: " ++
show (diskSupportsDiscard d) ++ "\n")
writeConsole con "\n"
case lookup "hdb" diskinfos of
Just disk ->
do writeConsole con "Verifying read-only disk 'hdb'\n"
checkROSectors con disk 0 0 (diskSectors disk)
Nothing ->
writeConsole con "Could not find read-only disk 'hdb'!\n"
case lookup "hda" diskinfos of
Just disk -> do
writeConsole con "Verifying read/write disk hda\n"
checkRWBlocks con disk
Nothing ->
writeConsole con "Could not find read/write disk 'hdb'!\n"
writeConsole con "Done!\n"
checkROSectors :: Console -> Disk -> Word -> Word8 -> Word -> IO ()
checkROSectors con disk cursec val endsec
| cursec == endsec =
writeConsole con (" --> Verified " ++ show endsec ++ " sectors.\n")
| otherwise = do
nextSec <- readDisk disk (diskSectorSize disk) cursec
let example = pack (replicate 512 val)
unless (example == nextSec) $ do
writeConsole con (" --> Verification FAILED at sector " ++
show cursec ++ "\n")
fail "Verification failed!"
checkROSectors con disk (cursec + 1) (val + 1) endsec
checkRWBlocks :: Console -> Disk -> IO ()
checkRWBlocks con disk = do
writeTest 0 0 (diskSectors disk)
writeDebugConsole "Completed write portion.\n"
diskWriteBarrier disk
writeDebugConsole "Executed write barrier.\n"
readTest 0 0 (diskSectors disk)
where
secsPerBlock = 8192 `div` diskSectorSize disk
--
writeTest x cur top
| cur == top =
writeConsole con (" --> Wrote " ++ show top ++ " sectors\n")
| otherwise = do
let example = pack (replicate 8192 x)
writeDisk disk example cur
writeTest (x + 1) (cur + secsPerBlock) top
--
readTest x cur top
| cur == top =
writeConsole con (" --> Verified " ++ show top ++ " sectors\n")
| otherwise = do
let example = pack (replicate 8192 x)
bstr <- readDisk disk 8192 cur
unless (example == bstr) $ do
writeConsole con (" --> Verification FAILED at sector " ++
show cur ++ "\n")
writeDebugConsole ("Start of example: " ++ show (BS.take 16 example) ++ "\n")
writeDebugConsole ("Start of block: " ++ show (BS.take 16 bstr) ++ "\n")
writeDebugConsole ("lengths: " ++ show (BS.length example) ++ " / " ++ show (BS.length bstr) ++ "\n")
writeDebugConsole ("Difference info: " ++ show (differenceInfo example bstr) ++ "\n")
fail "Verification failed!"
readTest (x + 1) (cur + secsPerBlock) top
differenceInfo :: ByteString -> ByteString -> (Int, String)
differenceInfo wrote read = go 0 wrote read
where
go x w r =
case (BS.uncons w, BS.uncons r) of
(Nothing, Nothing) -> (x, "PERFECT")
(Just _, Nothing) -> (x, "Read ended first.")
(Nothing, Just _) -> (x, "Wrote ended first.")
(Just (wv, w'), Just (rv, r'))
| wv /= rv -> (x, "Difference: " ++ show (BS.take 16 w) ++ " vs "
++ show (BS.take 16 r))
| otherwise -> go (x + 1) w' r'
|
GaloisInc/HaLVM
|
examples/XenDevice/VBDTest/VBDTest.hs
|
bsd-3-clause
| 4,505
| 0
| 22
| 1,191
| 1,503
| 716
| 787
| 101
| 4
|
module PerimeterOfSquaresInRectangle where
-- | Get the sum of perimeters of fibonacci squares (5 kyu)
-- | Link: https://biturl.io/FibRect
-- | My original solution (using only ord)
perimeter :: Integer -> Integer
perimeter n = 4 * sum (take (1 + fromInteger n) fibs)
where
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
|
Eugleo/Code-Wars
|
src/number-kata/PerimeterOfSquaresInRectangle.hs
|
bsd-3-clause
| 324
| 0
| 11
| 61
| 79
| 43
| 36
| 4
| 1
|
module Sharc.Instruments.ViolaMarteleBowing (violaMarteleBowing) where
import Sharc.Types
violaMarteleBowing :: Instr
violaMarteleBowing = Instr
"viola_martele"
"Viola (martele bowing)"
(Legend "McGill" "1" "10")
(Range
(InstrRange
(HarmonicFreq 1 (Pitch 130.81 36 "c3"))
(Pitch 130.81 36 "c3")
(Amplitude 9424.18 (HarmonicFreq 68 (Pitch 138.591 37 "c#3")) 0.16))
(InstrRange
(HarmonicFreq 47 (Pitch 10340.0 45 "a3"))
(Pitch 1046.5 72 "c6")
(Amplitude 554.36 (HarmonicFreq 1 (Pitch 554.365 61 "c#5")) 16816.0)))
[note0
,note1
,note2
,note3
,note4
,note5
,note6
,note7
,note8
,note9
,note10
,note11
,note12
,note13
,note14
,note15
,note16
,note17
,note18
,note19
,note20
,note21
,note22
,note23
,note24
,note25
,note26
,note27
,note28
,note29
,note30
,note31
,note32
,note33
,note34
,note35]
note0 :: Note
note0 = Note
(Pitch 130.813 36 "c3")
1
(Range
(NoteRange
(NoteRangeAmplitude 5494.14 42 0.2)
(NoteRangeHarmonicFreq 1 130.81))
(NoteRange
(NoteRangeAmplitude 261.62 2 5388.0)
(NoteRangeHarmonicFreq 76 9941.78)))
[Harmonic 1 1.991 18.18
,Harmonic 2 1.091 5388.0
,Harmonic 3 (-2.733) 4022.62
,Harmonic 4 0.739 2012.65
,Harmonic 5 (-0.752) 2248.8
,Harmonic 6 1.703 2028.85
,Harmonic 7 1.647 1084.12
,Harmonic 8 (-2.251) 54.3
,Harmonic 9 (-3.12) 546.42
,Harmonic 10 (-1.588) 105.09
,Harmonic 11 (-1.398) 617.17
,Harmonic 12 2.046 467.91
,Harmonic 13 (-0.147) 462.26
,Harmonic 14 2.053 150.35
,Harmonic 15 (-0.558) 40.31
,Harmonic 16 0.238 46.94
,Harmonic 17 1.712 24.61
,Harmonic 18 2.379 23.58
,Harmonic 19 (-0.83) 68.02
,Harmonic 20 (-2.493) 65.32
,Harmonic 21 (-1.163) 31.03
,Harmonic 22 1.33 18.85
,Harmonic 23 (-0.451) 29.38
,Harmonic 24 (-0.155) 26.17
,Harmonic 25 (-3.139) 3.75
,Harmonic 26 (-2.598) 32.93
,Harmonic 27 (-2.165) 52.67
,Harmonic 28 0.487 7.75
,Harmonic 29 (-0.841) 7.94
,Harmonic 30 1.59 8.77
,Harmonic 31 (-0.99) 5.79
,Harmonic 32 (-0.582) 9.12
,Harmonic 33 1.0e-3 3.03
,Harmonic 34 1.551 3.61
,Harmonic 35 2.682 3.1
,Harmonic 36 (-1.821) 2.07
,Harmonic 37 1.805 1.36
,Harmonic 38 2.993 0.59
,Harmonic 39 (-3.123) 3.04
,Harmonic 40 1.846 5.76
,Harmonic 41 1.817 0.25
,Harmonic 42 1.018 0.2
,Harmonic 43 (-1.52) 3.33
,Harmonic 44 1.457 4.66
,Harmonic 45 (-0.477) 1.72
,Harmonic 46 0.828 2.89
,Harmonic 47 0.416 1.09
,Harmonic 48 0.318 1.31
,Harmonic 49 2.64 1.08
,Harmonic 50 (-0.438) 1.54
,Harmonic 51 (-0.433) 2.17
,Harmonic 52 (-2.5) 0.49
,Harmonic 53 2.262 2.56
,Harmonic 54 2.578 0.36
,Harmonic 55 (-2.082) 2.69
,Harmonic 56 (-2.836) 2.92
,Harmonic 57 0.216 1.06
,Harmonic 58 (-2.787) 1.24
,Harmonic 59 2.962 0.9
,Harmonic 60 0.722 1.81
,Harmonic 61 0.146 0.91
,Harmonic 62 1.421 1.66
,Harmonic 63 0.76 0.58
,Harmonic 64 2.169 0.45
,Harmonic 65 3.11 0.33
,Harmonic 66 (-2.98) 1.02
,Harmonic 67 1.965 0.78
,Harmonic 68 2.681 0.54
,Harmonic 69 (-1.922) 0.73
,Harmonic 70 (-1.891) 1.0
,Harmonic 71 1.994 2.14
,Harmonic 72 (-1.95) 0.52
,Harmonic 73 (-2.709) 0.57
,Harmonic 74 3.129 0.43
,Harmonic 75 1.768 0.52
,Harmonic 76 2.775 0.38]
note1 :: Note
note1 = Note
(Pitch 138.591 37 "c#3")
2
(Range
(NoteRange
(NoteRangeAmplitude 9424.18 68 0.16)
(NoteRangeHarmonicFreq 1 138.59))
(NoteRange
(NoteRangeAmplitude 277.18 2 12051.0)
(NoteRangeHarmonicFreq 71 9839.96)))
[Harmonic 1 0.207 54.31
,Harmonic 2 (-2.032) 12051.0
,Harmonic 3 (-6.9e-2) 2749.24
,Harmonic 4 0.324 1534.66
,Harmonic 5 1.34 920.02
,Harmonic 6 (-1.81) 783.88
,Harmonic 7 (-2.734) 259.32
,Harmonic 8 (-0.709) 184.73
,Harmonic 9 1.361 281.74
,Harmonic 10 (-1.229) 420.67
,Harmonic 11 (-1.186) 125.14
,Harmonic 12 (-3.141) 163.28
,Harmonic 13 (-2.175) 324.22
,Harmonic 14 1.702 49.14
,Harmonic 15 2.523 88.3
,Harmonic 16 (-0.916) 8.27
,Harmonic 17 0.9 10.15
,Harmonic 18 1.507 53.97
,Harmonic 19 2.837 29.19
,Harmonic 20 0.113 61.69
,Harmonic 21 2.392 24.87
,Harmonic 22 (-1.937) 16.75
,Harmonic 23 1.426 46.07
,Harmonic 24 2.906 11.06
,Harmonic 25 1.574 47.65
,Harmonic 26 (-0.928) 23.43
,Harmonic 27 1.886 6.0
,Harmonic 28 0.31 8.31
,Harmonic 29 (-0.389) 8.49
,Harmonic 30 (-1.477) 9.28
,Harmonic 31 2.877 8.1
,Harmonic 32 (-1.147) 5.49
,Harmonic 33 1.661 2.02
,Harmonic 34 1.075 1.96
,Harmonic 35 2.523 10.4
,Harmonic 36 (-1.536) 5.18
,Harmonic 37 0.731 3.87
,Harmonic 38 (-2.988) 8.23
,Harmonic 39 2.564 3.11
,Harmonic 40 (-2.0) 6.2
,Harmonic 41 (-0.584) 2.9
,Harmonic 42 (-2.21) 1.28
,Harmonic 43 (-2.584) 4.26
,Harmonic 44 2.875 4.7
,Harmonic 45 (-0.132) 8.18
,Harmonic 46 1.799 0.42
,Harmonic 47 2.293 1.34
,Harmonic 48 (-2.068) 3.45
,Harmonic 49 (-1.727) 3.17
,Harmonic 50 (-0.459) 4.82
,Harmonic 51 (-1.0e-3) 2.98
,Harmonic 52 (-2.076) 2.6
,Harmonic 53 (-0.863) 3.72
,Harmonic 54 1.339 1.52
,Harmonic 55 0.936 4.51
,Harmonic 56 (-1.774) 2.49
,Harmonic 57 (-0.415) 1.52
,Harmonic 58 (-1.382) 0.63
,Harmonic 59 1.95 2.0
,Harmonic 60 2.006 1.19
,Harmonic 61 (-2.559) 3.3
,Harmonic 62 (-1.471) 1.1
,Harmonic 63 0.89 3.28
,Harmonic 64 1.316 0.83
,Harmonic 65 (-1.146) 2.31
,Harmonic 66 1.276 1.83
,Harmonic 67 (-2.578) 2.07
,Harmonic 68 (-0.399) 0.16
,Harmonic 69 2.183 1.02
,Harmonic 70 (-1.707) 1.52
,Harmonic 71 9.6e-2 0.57]
note2 :: Note
note2 = Note
(Pitch 146.832 38 "d3")
3
(Range
(NoteRange
(NoteRangeAmplitude 9690.91 66 0.2)
(NoteRangeHarmonicFreq 1 146.83))
(NoteRange
(NoteRangeAmplitude 293.66 2 7544.0)
(NoteRangeHarmonicFreq 68 9984.57)))
[Harmonic 1 (-3.1) 121.32
,Harmonic 2 0.764 7544.0
,Harmonic 3 1.325 4505.26
,Harmonic 4 2.976 1732.69
,Harmonic 5 2.269 2594.57
,Harmonic 6 (-1.832) 1589.54
,Harmonic 7 2.921 412.33
,Harmonic 8 (-1.726) 237.03
,Harmonic 9 (-2.925) 245.6
,Harmonic 10 (-2.369) 113.07
,Harmonic 11 2.331 432.45
,Harmonic 12 0.111 31.63
,Harmonic 13 0.946 728.16
,Harmonic 14 0.835 85.54
,Harmonic 15 1.323 55.43
,Harmonic 16 (-1.339) 27.18
,Harmonic 17 5.8e-2 127.44
,Harmonic 18 (-1.614) 76.62
,Harmonic 19 0.389 39.34
,Harmonic 20 1.255 24.22
,Harmonic 21 (-1.7e-2) 20.56
,Harmonic 22 2.267 12.94
,Harmonic 23 (-0.721) 31.79
,Harmonic 24 0.379 43.54
,Harmonic 25 (-2.434) 9.63
,Harmonic 26 (-0.835) 17.57
,Harmonic 27 (-3.101) 3.73
,Harmonic 28 (-3.116) 2.5
,Harmonic 29 (-0.773) 8.86
,Harmonic 30 (-1.307) 13.79
,Harmonic 31 (-3.048) 0.53
,Harmonic 32 0.393 0.55
,Harmonic 33 3.133 4.15
,Harmonic 34 3.137 3.53
,Harmonic 35 0.578 2.87
,Harmonic 36 3.037 0.46
,Harmonic 37 (-3.4e-2) 1.03
,Harmonic 38 3.111 4.98
,Harmonic 39 (-1.785) 3.72
,Harmonic 40 2.076 1.51
,Harmonic 41 2.492 1.37
,Harmonic 42 0.832 0.44
,Harmonic 43 (-2.489) 0.99
,Harmonic 44 (-1.683) 1.15
,Harmonic 45 (-2.124) 1.15
,Harmonic 46 (-1.581) 1.36
,Harmonic 47 (-0.612) 2.0
,Harmonic 48 (-1.951) 0.99
,Harmonic 49 1.614 3.49
,Harmonic 50 0.785 2.0
,Harmonic 51 (-1.111) 0.79
,Harmonic 52 (-3.128) 1.12
,Harmonic 53 (-2.678) 0.25
,Harmonic 54 (-2.589) 1.41
,Harmonic 55 1.595 1.51
,Harmonic 56 2.464 0.75
,Harmonic 57 (-2.556) 1.52
,Harmonic 58 (-3.088) 0.32
,Harmonic 59 (-0.557) 0.4
,Harmonic 60 1.585 0.79
,Harmonic 61 2.611 1.8
,Harmonic 62 2.958 1.68
,Harmonic 63 (-2.56) 0.57
,Harmonic 64 2.809 0.76
,Harmonic 65 2.5 1.27
,Harmonic 66 1.755 0.2
,Harmonic 67 (-2.616) 0.49
,Harmonic 68 1.71 1.12]
note3 :: Note
note3 = Note
(Pitch 155.563 39 "d#3")
4
(Range
(NoteRange
(NoteRangeAmplitude 8711.52 56 0.49)
(NoteRangeHarmonicFreq 1 155.56))
(NoteRange
(NoteRangeAmplitude 311.12 2 10698.0)
(NoteRangeHarmonicFreq 64 9956.03)))
[Harmonic 1 9.2e-2 51.67
,Harmonic 2 (-1.571) 10698.0
,Harmonic 3 (-1.947) 5444.77
,Harmonic 4 (-1.766) 3518.26
,Harmonic 5 (-2.25) 1421.87
,Harmonic 6 1.018 901.78
,Harmonic 7 (-1.22) 577.93
,Harmonic 8 2.751 1072.2
,Harmonic 9 (-5.2e-2) 1445.33
,Harmonic 10 0.269 207.17
,Harmonic 11 (-2.539) 464.42
,Harmonic 12 0.664 292.53
,Harmonic 13 (-2.589) 310.27
,Harmonic 14 2.188 91.47
,Harmonic 15 (-0.144) 30.91
,Harmonic 16 (-1.907) 59.56
,Harmonic 17 (-2.399) 58.74
,Harmonic 18 (-2.957) 149.09
,Harmonic 19 (-2.561) 21.64
,Harmonic 20 (-1.064) 31.48
,Harmonic 21 1.702 39.07
,Harmonic 22 (-0.637) 50.58
,Harmonic 23 (-2.935) 24.37
,Harmonic 24 2.053 7.64
,Harmonic 25 2.349 9.65
,Harmonic 26 2.379 21.1
,Harmonic 27 (-1.658) 16.54
,Harmonic 28 (-2.083) 10.03
,Harmonic 29 2.119 5.61
,Harmonic 30 (-1.395) 8.19
,Harmonic 31 1.658 10.03
,Harmonic 32 1.393 0.55
,Harmonic 33 (-1.985) 3.56
,Harmonic 34 1.001 4.07
,Harmonic 35 (-0.591) 1.16
,Harmonic 36 (-3.053) 4.5
,Harmonic 37 (-0.583) 1.29
,Harmonic 38 2.441 1.78
,Harmonic 39 (-0.125) 4.28
,Harmonic 40 1.467 5.01
,Harmonic 41 2.693 6.74
,Harmonic 42 (-2.851) 4.07
,Harmonic 43 (-1.426) 5.35
,Harmonic 44 (-2.344) 4.91
,Harmonic 45 0.226 3.63
,Harmonic 46 (-2.765) 4.31
,Harmonic 47 2.056 2.39
,Harmonic 48 (-2.809) 4.5
,Harmonic 49 (-1.068) 1.33
,Harmonic 50 (-0.603) 0.97
,Harmonic 51 (-1.53) 2.85
,Harmonic 52 (-2.741) 2.6
,Harmonic 53 0.35 4.37
,Harmonic 54 0.452 1.47
,Harmonic 55 (-1.632) 1.5
,Harmonic 56 (-1.454) 0.49
,Harmonic 57 (-0.832) 1.81
,Harmonic 58 (-1.816) 5.1
,Harmonic 59 (-9.6e-2) 3.96
,Harmonic 60 (-3.004) 4.67
,Harmonic 61 2.285 5.13
,Harmonic 62 (-2.314) 1.36
,Harmonic 63 1.376 0.79
,Harmonic 64 1.1 4.28]
note4 :: Note
note4 = Note
(Pitch 164.814 40 "e3")
5
(Range
(NoteRange
(NoteRangeAmplitude 5274.04 32 0.38)
(NoteRangeHarmonicFreq 1 164.81))
(NoteRange
(NoteRangeAmplitude 329.62 2 10714.0)
(NoteRangeHarmonicFreq 61 10053.65)))
[Harmonic 1 6.6e-2 121.32
,Harmonic 2 1.726 10714.0
,Harmonic 3 1.05 2066.81
,Harmonic 4 0.505 3856.25
,Harmonic 5 0.536 1150.52
,Harmonic 6 (-0.594) 436.22
,Harmonic 7 (-2.21) 758.07
,Harmonic 8 1.555 660.46
,Harmonic 9 (-1.189) 1536.23
,Harmonic 10 (-1.843) 455.69
,Harmonic 11 (-2.801) 45.35
,Harmonic 12 (-1.43) 27.26
,Harmonic 13 (-3.064) 23.44
,Harmonic 14 (-0.149) 82.36
,Harmonic 15 (-2.457) 32.12
,Harmonic 16 0.153 92.93
,Harmonic 17 (-2.989) 39.4
,Harmonic 18 (-0.645) 29.54
,Harmonic 19 1.566 29.44
,Harmonic 20 3.107 23.57
,Harmonic 21 2.24 25.05
,Harmonic 22 0.132 23.97
,Harmonic 23 0.837 6.01
,Harmonic 24 (-2.624) 4.22
,Harmonic 25 2.084 4.91
,Harmonic 26 (-0.416) 16.48
,Harmonic 27 (-2.544) 6.61
,Harmonic 28 (-1.827) 1.12
,Harmonic 29 1.764 1.85
,Harmonic 30 1.675 2.89
,Harmonic 31 1.89 2.56
,Harmonic 32 0.841 0.38
,Harmonic 33 2.379 1.99
,Harmonic 34 (-1.998) 2.69
,Harmonic 35 (-0.175) 2.49
,Harmonic 36 (-3.029) 3.52
,Harmonic 37 (-2.261) 0.88
,Harmonic 38 (-2.937) 1.41
,Harmonic 39 1.192 1.87
,Harmonic 40 1.887 1.32
,Harmonic 41 2.757 0.74
,Harmonic 42 (-2.688) 0.86
,Harmonic 43 2.345 0.81
,Harmonic 44 (-1.422) 0.59
,Harmonic 45 (-1.346) 0.47
,Harmonic 46 (-2.414) 1.73
,Harmonic 47 1.199 1.16
,Harmonic 48 2.548 3.1
,Harmonic 49 (-2.912) 1.1
,Harmonic 50 2.383 1.1
,Harmonic 51 (-2.958) 1.31
,Harmonic 52 1.279 0.59
,Harmonic 53 2.415 1.3
,Harmonic 54 2.304 0.67
,Harmonic 55 2.011 0.92
,Harmonic 56 (-1.936) 0.97
,Harmonic 57 1.859 1.06
,Harmonic 58 (-0.188) 0.85
,Harmonic 59 2.792 1.97
,Harmonic 60 (-3.094) 1.32
,Harmonic 61 (-2.818) 1.14]
note5 :: Note
note5 = Note
(Pitch 174.614 41 "f3")
6
(Range
(NoteRange
(NoteRangeAmplitude 8730.7 50 0.85)
(NoteRangeHarmonicFreq 1 174.61))
(NoteRange
(NoteRangeAmplitude 349.22 2 10049.0)
(NoteRangeHarmonicFreq 56 9778.38)))
[Harmonic 1 (-3.2e-2) 870.72
,Harmonic 2 0.69 10049.0
,Harmonic 3 2.366 6266.11
,Harmonic 4 (-2.761) 1492.99
,Harmonic 5 1.898 7665.59
,Harmonic 6 (-1.764) 418.24
,Harmonic 7 0.351 2435.89
,Harmonic 8 0.197 420.87
,Harmonic 9 (-3.098) 814.19
,Harmonic 10 (-0.336) 377.73
,Harmonic 11 2.074 323.58
,Harmonic 12 (-1.46) 1503.41
,Harmonic 13 1.627 166.97
,Harmonic 14 1.571 137.32
,Harmonic 15 (-2.254) 164.9
,Harmonic 16 (-2.728) 71.65
,Harmonic 17 1.648 207.49
,Harmonic 18 (-0.841) 137.69
,Harmonic 19 (-2.931) 161.39
,Harmonic 20 (-1.4e-2) 154.2
,Harmonic 21 0.365 35.75
,Harmonic 22 (-3.131) 38.72
,Harmonic 23 1.877 47.31
,Harmonic 24 (-2.197) 12.11
,Harmonic 25 (-2.962) 18.39
,Harmonic 26 2.47 14.34
,Harmonic 27 (-0.356) 4.71
,Harmonic 28 (-2.645) 20.63
,Harmonic 29 (-2.705) 7.52
,Harmonic 30 2.156 4.13
,Harmonic 31 1.744 8.01
,Harmonic 32 (-2.848) 3.92
,Harmonic 33 (-1.016) 3.46
,Harmonic 34 (-0.205) 4.89
,Harmonic 35 (-2.922) 5.17
,Harmonic 36 (-1.836) 2.82
,Harmonic 37 2.904 2.31
,Harmonic 38 (-3.047) 3.18
,Harmonic 39 (-1.344) 2.79
,Harmonic 40 1.222 3.56
,Harmonic 41 (-2.369) 5.54
,Harmonic 42 (-0.278) 1.28
,Harmonic 43 1.564 2.44
,Harmonic 44 2.67 1.93
,Harmonic 45 1.433 1.19
,Harmonic 46 2.311 2.17
,Harmonic 47 3.064 3.34
,Harmonic 48 (-1.376) 3.11
,Harmonic 49 (-2.288) 4.12
,Harmonic 50 (-3.106) 0.85
,Harmonic 51 1.067 3.67
,Harmonic 52 (-1.543) 1.59
,Harmonic 53 3.13 1.51
,Harmonic 54 (-3.011) 2.33
,Harmonic 55 (-1.949) 1.2
,Harmonic 56 2.58 1.46]
note6 :: Note
note6 = Note
(Pitch 184.997 42 "f#3")
7
(Range
(NoteRange
(NoteRangeAmplitude 6844.88 37 0.2)
(NoteRangeHarmonicFreq 1 184.99))
(NoteRange
(NoteRangeAmplitude 369.99 2 16602.0)
(NoteRangeHarmonicFreq 54 9989.83)))
[Harmonic 1 (-2.25) 686.23
,Harmonic 2 1.442 16602.0
,Harmonic 3 1.797 2104.48
,Harmonic 4 0.152 2756.8
,Harmonic 5 (-2.392) 1365.05
,Harmonic 6 (-1.029) 411.34
,Harmonic 7 1.812 934.2
,Harmonic 8 1.593 386.81
,Harmonic 9 1.15 1379.87
,Harmonic 10 7.0e-2 689.66
,Harmonic 11 1.016 455.85
,Harmonic 12 (-2.176) 256.01
,Harmonic 13 (-0.425) 159.3
,Harmonic 14 (-2.803) 87.71
,Harmonic 15 (-2.878) 245.19
,Harmonic 16 (-2.75) 123.98
,Harmonic 17 (-2.583) 44.28
,Harmonic 18 (-0.467) 68.15
,Harmonic 19 0.635 47.0
,Harmonic 20 (-2.191) 62.51
,Harmonic 21 (-3.05) 36.56
,Harmonic 22 0.529 18.54
,Harmonic 23 (-1.134) 21.51
,Harmonic 24 1.598 14.55
,Harmonic 25 (-2.961) 16.28
,Harmonic 26 1.334 17.53
,Harmonic 27 (-1.02) 7.33
,Harmonic 28 0.689 2.99
,Harmonic 29 1.677 2.84
,Harmonic 30 (-2.696) 1.43
,Harmonic 31 1.989 8.42
,Harmonic 32 2.015 7.92
,Harmonic 33 1.579 1.34
,Harmonic 34 (-2.703) 1.78
,Harmonic 35 (-0.571) 0.55
,Harmonic 36 3.008 1.78
,Harmonic 37 2.182 0.2
,Harmonic 38 2.181 1.13
,Harmonic 39 3.049 2.4
,Harmonic 40 0.886 2.0
,Harmonic 41 1.222 2.15
,Harmonic 42 (-2.633) 2.15
,Harmonic 43 (-1.409) 1.81
,Harmonic 44 (-2.212) 2.17
,Harmonic 45 (-2.487) 1.84
,Harmonic 46 (-3.049) 1.46
,Harmonic 47 (-2.059) 1.62
,Harmonic 48 (-2.395) 2.23
,Harmonic 49 1.388 0.54
,Harmonic 50 0.597 0.46
,Harmonic 51 (-3.107) 3.44
,Harmonic 52 (-2.014) 2.79
,Harmonic 53 (-2.823) 2.15
,Harmonic 54 (-3.124) 4.07]
note7 :: Note
note7 = Note
(Pitch 195.998 43 "g3")
8
(Range
(NoteRange
(NoteRangeAmplitude 7055.92 36 0.67)
(NoteRangeHarmonicFreq 1 195.99))
(NoteRange
(NoteRangeAmplitude 391.99 2 11293.0)
(NoteRangeHarmonicFreq 50 9799.9)))
[Harmonic 1 (-0.171) 1482.94
,Harmonic 2 2.078 11293.0
,Harmonic 3 0.726 6945.64
,Harmonic 4 1.266 667.12
,Harmonic 5 (-3.099) 1284.44
,Harmonic 6 (-2.307) 1239.93
,Harmonic 7 0.139 331.71
,Harmonic 8 0.223 1034.06
,Harmonic 9 0.138 977.97
,Harmonic 10 0.47 1254.38
,Harmonic 11 1.423 232.84
,Harmonic 12 (-0.697) 23.87
,Harmonic 13 2.647 170.33
,Harmonic 14 (-9.4e-2) 222.83
,Harmonic 15 2.91 173.94
,Harmonic 16 0.805 57.53
,Harmonic 17 2.222 182.57
,Harmonic 18 (-0.504) 197.3
,Harmonic 19 1.738 48.37
,Harmonic 20 (-0.227) 11.82
,Harmonic 21 2.927 4.45
,Harmonic 22 3.14 9.69
,Harmonic 23 (-0.958) 34.35
,Harmonic 24 2.236 9.85
,Harmonic 25 (-6.9e-2) 11.37
,Harmonic 26 (-1.263) 6.31
,Harmonic 27 (-0.108) 6.97
,Harmonic 28 1.482 3.74
,Harmonic 29 1.415 20.85
,Harmonic 30 (-0.15) 2.53
,Harmonic 31 (-3.105) 7.52
,Harmonic 32 (-1.181) 2.68
,Harmonic 33 1.652 4.1
,Harmonic 34 (-2.213) 4.18
,Harmonic 35 3.085 2.48
,Harmonic 36 (-0.492) 0.67
,Harmonic 37 (-2.877) 2.4
,Harmonic 38 (-1.651) 1.8
,Harmonic 39 (-0.333) 3.31
,Harmonic 40 (-0.957) 2.36
,Harmonic 41 (-2.052) 2.0
,Harmonic 42 (-0.362) 8.03
,Harmonic 43 (-0.89) 1.35
,Harmonic 44 0.12 3.18
,Harmonic 45 (-1.65) 3.78
,Harmonic 46 0.308 1.87
,Harmonic 47 2.96 3.35
,Harmonic 48 1.461 3.59
,Harmonic 49 (-1.111) 2.26
,Harmonic 50 (-1.074) 0.68]
note8 :: Note
note8 = Note
(Pitch 207.652 44 "g#3")
9
(Range
(NoteRange
(NoteRangeAmplitude 9967.29 48 0.88)
(NoteRangeHarmonicFreq 1 207.65))
(NoteRange
(NoteRangeAmplitude 415.3 2 4011.0)
(NoteRangeHarmonicFreq 48 9967.29)))
[Harmonic 1 (-1.808) 1155.25
,Harmonic 2 (-1.447) 4011.0
,Harmonic 3 (-2.667) 1383.5
,Harmonic 4 1.604 2200.03
,Harmonic 5 (-0.122) 1562.61
,Harmonic 6 (-2.989) 1680.68
,Harmonic 7 (-1.709) 651.98
,Harmonic 8 1.508 877.87
,Harmonic 9 (-2.041) 116.23
,Harmonic 10 (-2.05) 317.32
,Harmonic 11 1.188 89.37
,Harmonic 12 0.69 316.64
,Harmonic 13 1.071 183.37
,Harmonic 14 (-2.45) 192.8
,Harmonic 15 (-0.929) 51.44
,Harmonic 16 4.6e-2 49.48
,Harmonic 17 2.7e-2 66.05
,Harmonic 18 (-3.116) 8.95
,Harmonic 19 8.0e-2 20.64
,Harmonic 20 0.341 13.45
,Harmonic 21 (-2.62) 7.22
,Harmonic 22 1.165 3.81
,Harmonic 23 (-2.602) 13.99
,Harmonic 24 0.556 7.93
,Harmonic 25 1.424 9.03
,Harmonic 26 (-0.555) 4.93
,Harmonic 27 (-2.861) 3.75
,Harmonic 28 (-1.69) 2.37
,Harmonic 29 (-2.509) 3.14
,Harmonic 30 (-1.103) 5.41
,Harmonic 31 0.568 6.01
,Harmonic 32 0.825 4.35
,Harmonic 33 (-0.188) 10.69
,Harmonic 34 (-1.644) 4.68
,Harmonic 35 (-2.914) 5.27
,Harmonic 36 (-1.023) 2.41
,Harmonic 37 (-1.902) 5.77
,Harmonic 38 0.342 2.22
,Harmonic 39 0.395 5.09
,Harmonic 40 1.591 3.87
,Harmonic 41 (-2.635) 1.07
,Harmonic 42 2.844 3.05
,Harmonic 43 (-0.332) 4.32
,Harmonic 44 1.24 2.18
,Harmonic 45 1.827 1.81
,Harmonic 46 (-2.051) 3.96
,Harmonic 47 (-0.351) 4.44
,Harmonic 48 1.903 0.88]
note9 :: Note
note9 = Note
(Pitch 220.0 45 "a3")
10
(Range
(NoteRange
(NoteRangeAmplitude 8360.0 38 1.37)
(NoteRangeHarmonicFreq 1 220.0))
(NoteRange
(NoteRangeAmplitude 220.0 1 7650.84)
(NoteRangeHarmonicFreq 47 10340.0)))
[Harmonic 1 (-2.848) 7650.84
,Harmonic 2 0.209 3784.54
,Harmonic 3 (-2.414) 4512.15
,Harmonic 4 1.648 512.1
,Harmonic 5 (-2.269) 837.88
,Harmonic 6 (-2.992) 1134.46
,Harmonic 7 (-2.123) 3042.16
,Harmonic 8 2.651 681.78
,Harmonic 9 2.376 248.43
,Harmonic 10 2.463 217.39
,Harmonic 11 1.265 75.25
,Harmonic 12 2.842 148.02
,Harmonic 13 0.596 104.61
,Harmonic 14 0.511 38.0
,Harmonic 15 (-1.194) 77.62
,Harmonic 16 (-1.434) 52.82
,Harmonic 17 0.528 27.69
,Harmonic 18 2.958 63.4
,Harmonic 19 (-1.007) 27.13
,Harmonic 20 (-0.188) 31.06
,Harmonic 21 1.825 8.26
,Harmonic 22 (-2.942) 40.31
,Harmonic 23 (-0.352) 26.83
,Harmonic 24 1.173 21.83
,Harmonic 25 (-1.991) 27.53
,Harmonic 26 1.2 21.38
,Harmonic 27 (-2.821) 10.3
,Harmonic 28 0.378 8.78
,Harmonic 29 (-2.438) 21.66
,Harmonic 30 (-3.024) 5.96
,Harmonic 31 (-2.308) 2.66
,Harmonic 32 (-2.941) 4.72
,Harmonic 33 (-1.616) 13.33
,Harmonic 34 (-2.513) 2.5
,Harmonic 35 (-2.651) 5.24
,Harmonic 36 (-0.651) 6.96
,Harmonic 37 (-0.513) 12.69
,Harmonic 38 2.943 1.37
,Harmonic 39 (-2.55) 3.36
,Harmonic 40 1.059 3.37
,Harmonic 41 0.165 1.71
,Harmonic 42 (-3.141) 7.06
,Harmonic 43 (-1.941) 2.58
,Harmonic 44 (-2.838) 11.54
,Harmonic 45 (-1.531) 3.52
,Harmonic 46 (-1.187) 2.82
,Harmonic 47 1.405 2.89]
note10 :: Note
note10 = Note
(Pitch 246.942 47 "b3")
11
(Range
(NoteRange
(NoteRangeAmplitude 8889.91 36 2.19)
(NoteRangeHarmonicFreq 1 246.94))
(NoteRange
(NoteRangeAmplitude 987.76 4 9383.0)
(NoteRangeHarmonicFreq 40 9877.68)))
[Harmonic 1 0.485 3069.16
,Harmonic 2 2.908 1541.86
,Harmonic 3 1.438 2309.3
,Harmonic 4 (-1.685) 9383.0
,Harmonic 5 (-1.161) 1452.18
,Harmonic 6 (-0.301) 358.03
,Harmonic 7 2.966 3277.31
,Harmonic 8 (-2.143) 1220.58
,Harmonic 9 2.616 648.12
,Harmonic 10 (-0.528) 127.14
,Harmonic 11 2.961 287.87
,Harmonic 12 0.251 30.42
,Harmonic 13 (-1.489) 236.02
,Harmonic 14 (-1.211) 188.42
,Harmonic 15 3.005 136.25
,Harmonic 16 (-2.897) 35.03
,Harmonic 17 (-2.078) 28.65
,Harmonic 18 1.252 7.08
,Harmonic 19 0.732 12.73
,Harmonic 20 (-1.722) 22.8
,Harmonic 21 (-1.398) 23.39
,Harmonic 22 1.329 19.89
,Harmonic 23 (-2.232) 21.0
,Harmonic 24 1.916 3.6
,Harmonic 25 (-0.616) 22.29
,Harmonic 26 1.571 16.55
,Harmonic 27 (-1.867) 11.62
,Harmonic 28 (-0.697) 6.36
,Harmonic 29 (-0.186) 9.8
,Harmonic 30 0.134 3.74
,Harmonic 31 1.114 8.44
,Harmonic 32 1.145 18.93
,Harmonic 33 (-1.183) 19.25
,Harmonic 34 (-0.78) 10.9
,Harmonic 35 2.554 18.65
,Harmonic 36 2.952 2.19
,Harmonic 37 (-0.516) 6.21
,Harmonic 38 (-2.91) 3.2
,Harmonic 39 (-0.6) 5.25
,Harmonic 40 (-0.861) 2.94]
note11 :: Note
note11 = Note
(Pitch 261.626 48 "c4")
12
(Range
(NoteRange
(NoteRangeAmplitude 9941.78 38 1.77)
(NoteRangeHarmonicFreq 1 261.62))
(NoteRange
(NoteRangeAmplitude 523.25 2 8269.0)
(NoteRangeHarmonicFreq 38 9941.78)))
[Harmonic 1 (-0.754) 5999.76
,Harmonic 2 (-2.75) 8269.0
,Harmonic 3 (-3.111) 2231.76
,Harmonic 4 (-0.659) 3361.41
,Harmonic 5 (-0.796) 3761.62
,Harmonic 6 2.902 327.86
,Harmonic 7 1.504 474.88
,Harmonic 8 2.655 108.0
,Harmonic 9 (-3.06) 184.13
,Harmonic 10 (-0.96) 455.38
,Harmonic 11 (-1.577) 64.71
,Harmonic 12 (-2.087) 207.73
,Harmonic 13 (-1.735) 115.63
,Harmonic 14 (-0.415) 63.3
,Harmonic 15 (-2.844) 45.92
,Harmonic 16 (-0.1) 63.47
,Harmonic 17 (-2.789) 24.05
,Harmonic 18 (-0.227) 3.1
,Harmonic 19 (-2.352) 23.86
,Harmonic 20 0.632 4.49
,Harmonic 21 (-2.071) 11.74
,Harmonic 22 (-0.223) 7.94
,Harmonic 23 (-1.126) 2.9
,Harmonic 24 (-0.209) 8.67
,Harmonic 25 0.763 6.37
,Harmonic 26 1.481 14.5
,Harmonic 27 (-1.997) 2.87
,Harmonic 28 (-1.875) 2.93
,Harmonic 29 (-1.1) 8.94
,Harmonic 30 (-0.376) 5.77
,Harmonic 31 0.996 5.65
,Harmonic 32 (-3.042) 4.85
,Harmonic 33 (-1.516) 5.74
,Harmonic 34 1.979 2.17
,Harmonic 35 (-1.346) 2.7
,Harmonic 36 2.37 9.82
,Harmonic 37 1.256 2.37
,Harmonic 38 0.523 1.77]
note12 :: Note
note12 = Note
(Pitch 277.183 49 "c#4")
13
(Range
(NoteRange
(NoteRangeAmplitude 9978.58 36 0.55)
(NoteRangeHarmonicFreq 1 277.18))
(NoteRange
(NoteRangeAmplitude 554.36 2 7752.0)
(NoteRangeHarmonicFreq 36 9978.58)))
[Harmonic 1 0.634 5903.33
,Harmonic 2 1.664 7752.0
,Harmonic 3 (-0.504) 1237.75
,Harmonic 4 2.583 3513.76
,Harmonic 5 2.391 429.43
,Harmonic 6 (-0.139) 643.66
,Harmonic 7 (-2.356) 1103.68
,Harmonic 8 1.165 433.68
,Harmonic 9 1.174 266.11
,Harmonic 10 1.274 464.2
,Harmonic 11 (-2.267) 88.8
,Harmonic 12 (-1.194) 312.32
,Harmonic 13 (-1.796) 84.07
,Harmonic 14 0.853 10.43
,Harmonic 15 (-2.97) 8.3
,Harmonic 16 (-1.789) 24.85
,Harmonic 17 (-2.187) 17.62
,Harmonic 18 0.635 16.44
,Harmonic 19 2.0e-2 11.41
,Harmonic 20 (-0.583) 3.2
,Harmonic 21 1.816 5.08
,Harmonic 22 (-1.072) 8.47
,Harmonic 23 (-2.752) 3.89
,Harmonic 24 (-1.17) 1.85
,Harmonic 25 (-2.4) 12.0
,Harmonic 26 (-1.971) 3.02
,Harmonic 27 1.457 4.81
,Harmonic 28 2.53 5.08
,Harmonic 29 (-5.0e-2) 8.02
,Harmonic 30 (-0.624) 8.86
,Harmonic 31 1.698 3.88
,Harmonic 32 (-2.742) 1.79
,Harmonic 33 0.558 1.82
,Harmonic 34 0.276 0.58
,Harmonic 35 (-3.086) 2.08
,Harmonic 36 (-1.715) 0.55]
note13 :: Note
note13 = Note
(Pitch 293.665 50 "d4")
14
(Range
(NoteRange
(NoteRangeAmplitude 9397.28 32 1.83)
(NoteRangeHarmonicFreq 1 293.66))
(NoteRange
(NoteRangeAmplitude 587.33 2 10489.0)
(NoteRangeHarmonicFreq 34 9984.61)))
[Harmonic 1 (-1.167) 1083.53
,Harmonic 2 (-2.108) 10489.0
,Harmonic 3 (-1.851) 934.28
,Harmonic 4 (-0.238) 5587.91
,Harmonic 5 2.191 769.36
,Harmonic 6 0.993 559.8
,Harmonic 7 (-2.204) 2478.01
,Harmonic 8 (-2.062) 1188.8
,Harmonic 9 0.909 274.58
,Harmonic 10 (-2.497) 99.22
,Harmonic 11 1.32 208.28
,Harmonic 12 1.899 71.65
,Harmonic 13 1.923 86.81
,Harmonic 14 (-1.055) 66.84
,Harmonic 15 1.441 7.85
,Harmonic 16 3.011 115.2
,Harmonic 17 (-1.614) 31.2
,Harmonic 18 (-2.477) 86.78
,Harmonic 19 (-0.115) 16.44
,Harmonic 20 (-1.286) 11.17
,Harmonic 21 (-1.337) 8.79
,Harmonic 22 0.363 21.64
,Harmonic 23 (-2.563) 17.17
,Harmonic 24 (-0.776) 6.53
,Harmonic 25 0.455 11.95
,Harmonic 26 0.78 5.78
,Harmonic 27 0.25 3.7
,Harmonic 28 (-1.82) 2.3
,Harmonic 29 (-1.493) 8.28
,Harmonic 30 (-3.048) 3.55
,Harmonic 31 (-0.39) 16.39
,Harmonic 32 2.496 1.83
,Harmonic 33 (-2.353) 3.88
,Harmonic 34 (-1.074) 3.01]
note14 :: Note
note14 = Note
(Pitch 311.127 51 "d#4")
15
(Range
(NoteRange
(NoteRangeAmplitude 7778.17 25 7.19)
(NoteRangeHarmonicFreq 1 311.12))
(NoteRange
(NoteRangeAmplitude 622.25 2 7540.0)
(NoteRangeHarmonicFreq 32 9956.06)))
[Harmonic 1 1.827 3852.04
,Harmonic 2 1.123 7540.0
,Harmonic 3 (-1.521) 5308.43
,Harmonic 4 3.116 2501.75
,Harmonic 5 (-1.962) 3389.03
,Harmonic 6 (-1.718) 967.71
,Harmonic 7 2.054 1249.85
,Harmonic 8 (-1.294) 2336.2
,Harmonic 9 (-2.476) 2643.08
,Harmonic 10 (-0.289) 341.39
,Harmonic 11 (-2.165) 105.49
,Harmonic 12 (-2.366) 177.31
,Harmonic 13 2.332 128.97
,Harmonic 14 2.409 75.23
,Harmonic 15 2.065 91.37
,Harmonic 16 2.352 65.5
,Harmonic 17 1.284 28.5
,Harmonic 18 (-1.042) 18.48
,Harmonic 19 (-0.632) 9.26
,Harmonic 20 (-1.23) 27.38
,Harmonic 21 2.033 18.81
,Harmonic 22 2.201 14.67
,Harmonic 23 (-0.408) 58.88
,Harmonic 24 0.124 8.8
,Harmonic 25 1.581 7.19
,Harmonic 26 7.1e-2 38.77
,Harmonic 27 2.664 9.92
,Harmonic 28 2.538 15.63
,Harmonic 29 (-0.837) 19.63
,Harmonic 30 (-2.94) 13.14
,Harmonic 31 (-1.451) 7.46
,Harmonic 32 2.888 19.42]
note15 :: Note
note15 = Note
(Pitch 329.628 52 "e4")
16
(Range
(NoteRange
(NoteRangeAmplitude 9559.21 29 1.03)
(NoteRangeHarmonicFreq 1 329.62))
(NoteRange
(NoteRangeAmplitude 329.62 1 7074.0)
(NoteRangeHarmonicFreq 31 10218.46)))
[Harmonic 1 1.2 7074.0
,Harmonic 2 (-1.841) 2927.72
,Harmonic 3 1.424 4694.28
,Harmonic 4 1.352 1580.64
,Harmonic 5 2.575 1715.95
,Harmonic 6 (-2.02) 1880.26
,Harmonic 7 1.108 515.35
,Harmonic 8 (-2.085) 1018.23
,Harmonic 9 3.047 149.25
,Harmonic 10 0.318 115.96
,Harmonic 11 (-2.727) 121.55
,Harmonic 12 (-1.224) 49.42
,Harmonic 13 0.741 10.52
,Harmonic 14 (-0.585) 50.03
,Harmonic 15 (-2.005) 30.26
,Harmonic 16 (-1.015) 19.24
,Harmonic 17 1.169 24.23
,Harmonic 18 2.791 7.02
,Harmonic 19 2.294 7.76
,Harmonic 20 (-1.907) 10.63
,Harmonic 21 1.948 11.75
,Harmonic 22 0.982 4.64
,Harmonic 23 0.586 1.13
,Harmonic 24 2.736 10.75
,Harmonic 25 (-0.628) 5.19
,Harmonic 26 (-2.424) 7.77
,Harmonic 27 (-1.69) 2.6
,Harmonic 28 (-1.623) 9.87
,Harmonic 29 2.139 1.03
,Harmonic 30 (-1.428) 4.7
,Harmonic 31 (-2.294) 7.74]
note16 :: Note
note16 = Note
(Pitch 349.228 53 "f4")
17
(Range
(NoteRange
(NoteRangeAmplitude 9079.92 26 6.75)
(NoteRangeHarmonicFreq 1 349.22))
(NoteRange
(NoteRangeAmplitude 349.22 1 15999.0)
(NoteRangeHarmonicFreq 28 9778.38)))
[Harmonic 1 1.701 15999.0
,Harmonic 2 (-0.74) 15383.06
,Harmonic 3 1.687 9271.04
,Harmonic 4 (-2.254) 12348.67
,Harmonic 5 1.42 3856.67
,Harmonic 6 1.368 3708.36
,Harmonic 7 2.843 1593.97
,Harmonic 8 2.15 1959.62
,Harmonic 9 (-0.87) 92.9
,Harmonic 10 (-0.353) 294.35
,Harmonic 11 2.3 114.11
,Harmonic 12 3.041 55.85
,Harmonic 13 1.031 187.53
,Harmonic 14 (-1.468) 168.25
,Harmonic 15 (-2.053) 81.47
,Harmonic 16 0.73 131.76
,Harmonic 17 1.108 19.53
,Harmonic 18 0.529 156.3
,Harmonic 19 (-0.963) 55.15
,Harmonic 20 1.789 28.55
,Harmonic 21 0.98 79.42
,Harmonic 22 0.215 130.21
,Harmonic 23 (-0.862) 134.7
,Harmonic 24 (-0.816) 22.23
,Harmonic 25 (-1.114) 25.96
,Harmonic 26 1.989 6.75
,Harmonic 27 (-0.878) 13.64
,Harmonic 28 (-1.94) 21.47]
note17 :: Note
note17 = Note
(Pitch 369.994 54 "f#4")
18
(Range
(NoteRange
(NoteRangeAmplitude 7029.88 19 1.84)
(NoteRangeHarmonicFreq 1 369.99))
(NoteRange
(NoteRangeAmplitude 369.99 1 9652.0)
(NoteRangeHarmonicFreq 27 9989.83)))
[Harmonic 1 (-1.875) 9652.0
,Harmonic 2 (-1.243) 468.77
,Harmonic 3 (-1.363) 1886.37
,Harmonic 4 0.377 1327.92
,Harmonic 5 (-0.655) 776.93
,Harmonic 6 (-1.117) 271.05
,Harmonic 7 (-1.007) 454.77
,Harmonic 8 2.879 19.38
,Harmonic 9 (-1.43) 103.28
,Harmonic 10 (-2.589) 53.63
,Harmonic 11 0.818 133.17
,Harmonic 12 1.704 13.88
,Harmonic 13 (-1.225) 30.7
,Harmonic 14 2.36 17.61
,Harmonic 15 (-2.371) 17.71
,Harmonic 16 (-1.0e-2) 5.3
,Harmonic 17 1.554 4.86
,Harmonic 18 1.11 21.04
,Harmonic 19 (-1.866) 1.84
,Harmonic 20 0.624 6.16
,Harmonic 21 1.993 3.08
,Harmonic 22 (-2.958) 4.7
,Harmonic 23 1.72 3.13
,Harmonic 24 (-1.941) 2.09
,Harmonic 25 1.147 9.1
,Harmonic 26 0.91 2.0
,Harmonic 27 2.23 4.91]
note18 :: Note
note18 = Note
(Pitch 391.995 55 "g4")
19
(Range
(NoteRange
(NoteRangeAmplitude 8623.89 22 3.44)
(NoteRangeHarmonicFreq 1 391.99))
(NoteRange
(NoteRangeAmplitude 391.99 1 7371.0)
(NoteRangeHarmonicFreq 25 9799.87)))
[Harmonic 1 (-1.695) 7371.0
,Harmonic 2 0.464 2064.15
,Harmonic 3 (-2.85) 2148.6
,Harmonic 4 (-1.894) 1206.58
,Harmonic 5 (-1.841) 315.43
,Harmonic 6 (-1.291) 608.93
,Harmonic 7 2.532 67.47
,Harmonic 8 (-0.377) 29.03
,Harmonic 9 1.56 289.41
,Harmonic 10 0.506 127.84
,Harmonic 11 (-1.245) 104.12
,Harmonic 12 2.407 117.96
,Harmonic 13 1.21 24.71
,Harmonic 14 (-1.282) 30.01
,Harmonic 15 1.777 22.72
,Harmonic 16 2.58 16.5
,Harmonic 17 (-3.02) 40.01
,Harmonic 18 (-2.762) 30.03
,Harmonic 19 2.749 17.47
,Harmonic 20 (-1.937) 6.24
,Harmonic 21 2.536 10.52
,Harmonic 22 0.948 3.44
,Harmonic 23 0.453 9.61
,Harmonic 24 1.551 5.01
,Harmonic 25 1.968 3.46]
note19 :: Note
note19 = Note
(Pitch 415.305 56 "g#4")
20
(Range
(NoteRange
(NoteRangeAmplitude 9967.32 24 1.87)
(NoteRangeHarmonicFreq 1 415.3))
(NoteRange
(NoteRangeAmplitude 830.61 2 6264.0)
(NoteRangeHarmonicFreq 24 9967.32)))
[Harmonic 1 (-1.712) 4369.52
,Harmonic 2 (-0.766) 6264.0
,Harmonic 3 (-2.655) 4207.29
,Harmonic 4 (-0.921) 1300.24
,Harmonic 5 2.534 2693.5
,Harmonic 6 (-1.271) 1041.13
,Harmonic 7 1.079 678.66
,Harmonic 8 1.493 415.06
,Harmonic 9 (-1.32) 62.99
,Harmonic 10 (-1.889) 60.93
,Harmonic 11 (-0.82) 113.12
,Harmonic 12 3.096 35.49
,Harmonic 13 0.565 32.43
,Harmonic 14 2.117 2.02
,Harmonic 15 1.887 5.19
,Harmonic 16 (-1.786) 64.38
,Harmonic 17 1.817 5.27
,Harmonic 18 (-0.455) 23.4
,Harmonic 19 (-2.598) 4.26
,Harmonic 20 (-0.496) 2.82
,Harmonic 21 (-2.067) 7.72
,Harmonic 22 (-0.769) 13.52
,Harmonic 23 1.84 17.26
,Harmonic 24 2.709 1.87]
note20 :: Note
note20 = Note
(Pitch 440.0 57 "a4")
21
(Range
(NoteRange
(NoteRangeAmplitude 9240.0 21 2.46)
(NoteRangeHarmonicFreq 1 440.0))
(NoteRange
(NoteRangeAmplitude 440.0 1 10744.0)
(NoteRangeHarmonicFreq 23 10120.0)))
[Harmonic 1 (-5.7e-2) 10744.0
,Harmonic 2 (-1.752) 10272.82
,Harmonic 3 2.238 9267.26
,Harmonic 4 (-1.617) 3221.85
,Harmonic 5 0.578 1352.32
,Harmonic 6 3.05 3331.66
,Harmonic 7 (-0.868) 383.59
,Harmonic 8 (-0.203) 255.6
,Harmonic 9 0.2 413.16
,Harmonic 10 (-0.484) 295.04
,Harmonic 11 (-2.022) 175.06
,Harmonic 12 (-0.213) 196.56
,Harmonic 13 4.9e-2 37.75
,Harmonic 14 1.713 45.01
,Harmonic 15 1.798 58.47
,Harmonic 16 2.366 36.85
,Harmonic 17 0.6 82.09
,Harmonic 18 1.109 30.45
,Harmonic 19 1.191 50.24
,Harmonic 20 0.891 55.41
,Harmonic 21 (-0.537) 2.46
,Harmonic 22 0.596 56.24
,Harmonic 23 (-9.0e-2) 22.46]
note21 :: Note
note21 = Note
(Pitch 466.164 58 "a#4")
22
(Range
(NoteRange
(NoteRangeAmplitude 9323.27 20 23.75)
(NoteRangeHarmonicFreq 1 466.16))
(NoteRange
(NoteRangeAmplitude 932.32 2 9241.0)
(NoteRangeHarmonicFreq 21 9789.44)))
[Harmonic 1 2.151 1534.03
,Harmonic 2 0.502 9241.0
,Harmonic 3 2.061 7184.75
,Harmonic 4 0.458 1424.48
,Harmonic 5 (-3.047) 241.41
,Harmonic 6 2.324 2495.24
,Harmonic 7 0.415 558.7
,Harmonic 8 2.933 357.12
,Harmonic 9 (-1.08) 846.25
,Harmonic 10 2.658 374.78
,Harmonic 11 2.523 284.16
,Harmonic 12 1.434 84.72
,Harmonic 13 1.258 172.76
,Harmonic 14 7.9e-2 133.88
,Harmonic 15 (-0.854) 176.44
,Harmonic 16 (-1.891) 229.93
,Harmonic 17 (-2.556) 35.37
,Harmonic 18 2.373 63.49
,Harmonic 19 1.748 62.38
,Harmonic 20 (-2.348) 23.75
,Harmonic 21 (-1.042) 31.27]
note22 :: Note
note22 = Note
(Pitch 493.883 59 "b4")
23
(Range
(NoteRange
(NoteRangeAmplitude 9877.66 20 24.35)
(NoteRangeHarmonicFreq 1 493.88))
(NoteRange
(NoteRangeAmplitude 1975.53 4 8357.0)
(NoteRangeHarmonicFreq 20 9877.66)))
[Harmonic 1 2.234 1365.44
,Harmonic 2 2.222 1680.93
,Harmonic 3 1.089 7837.27
,Harmonic 4 0.83 8357.0
,Harmonic 5 1.248 2779.18
,Harmonic 6 1.124 956.93
,Harmonic 7 0.594 4236.85
,Harmonic 8 (-2.481) 43.88
,Harmonic 9 2.2 964.44
,Harmonic 10 2.181 69.54
,Harmonic 11 (-2.609) 90.6
,Harmonic 12 2.36 239.35
,Harmonic 13 (-1.743) 450.6
,Harmonic 14 1.527 407.8
,Harmonic 15 (-2.921) 68.16
,Harmonic 16 (-0.283) 85.02
,Harmonic 17 (-0.139) 202.1
,Harmonic 18 1.351 33.24
,Harmonic 19 2.908 102.65
,Harmonic 20 (-0.918) 24.35]
note23 :: Note
note23 = Note
(Pitch 523.251 60 "c5")
24
(Range
(NoteRange
(NoteRangeAmplitude 7325.51 14 10.36)
(NoteRangeHarmonicFreq 1 523.25))
(NoteRange
(NoteRangeAmplitude 1046.5 2 15601.0)
(NoteRangeHarmonicFreq 19 9941.76)))
[Harmonic 1 1.575 14071.69
,Harmonic 2 1.206 15601.0
,Harmonic 3 1.701 8674.56
,Harmonic 4 2.439 6823.59
,Harmonic 5 0.14 4979.3
,Harmonic 6 0.808 359.94
,Harmonic 7 (-0.997) 147.58
,Harmonic 8 (-2.398) 947.67
,Harmonic 9 (-3.046) 175.55
,Harmonic 10 0.754 104.11
,Harmonic 11 (-1.094) 52.05
,Harmonic 12 (-0.522) 37.13
,Harmonic 13 2.044 81.88
,Harmonic 14 (-1.935) 10.36
,Harmonic 15 (-2.811) 41.4
,Harmonic 16 2.77 41.81
,Harmonic 17 (-1.372) 54.64
,Harmonic 18 2.422 44.47
,Harmonic 19 (-0.679) 52.89]
note24 :: Note
note24 = Note
(Pitch 554.365 61 "c#5")
25
(Range
(NoteRange
(NoteRangeAmplitude 5543.65 10 60.95)
(NoteRangeHarmonicFreq 1 554.36))
(NoteRange
(NoteRangeAmplitude 554.36 1 16816.0)
(NoteRangeHarmonicFreq 18 9978.57)))
[Harmonic 1 1.654 16816.0
,Harmonic 2 (-2.884) 6095.37
,Harmonic 3 0.728 8475.37
,Harmonic 4 0.342 3434.01
,Harmonic 5 (-1.768) 2795.39
,Harmonic 6 2.704 981.22
,Harmonic 7 0.437 1372.09
,Harmonic 8 1.995 165.89
,Harmonic 9 2.446 159.92
,Harmonic 10 1.983 60.95
,Harmonic 11 (-1.954) 246.29
,Harmonic 12 2.405 122.07
,Harmonic 13 (-0.139) 134.55
,Harmonic 14 2.745 191.88
,Harmonic 15 (-0.521) 156.84
,Harmonic 16 (-0.59) 112.45
,Harmonic 17 (-1.3) 114.53
,Harmonic 18 (-2.314) 89.8]
note25 :: Note
note25 = Note
(Pitch 587.33 62 "d5")
26
(Range
(NoteRange
(NoteRangeAmplitude 9984.61 17 20.14)
(NoteRangeHarmonicFreq 1 587.33))
(NoteRange
(NoteRangeAmplitude 587.33 1 14024.0)
(NoteRangeHarmonicFreq 17 9984.61)))
[Harmonic 1 1.734 14024.0
,Harmonic 2 0.991 5695.93
,Harmonic 3 (-1.971) 4344.32
,Harmonic 4 (-8.9e-2) 888.89
,Harmonic 5 (-1.637) 489.74
,Harmonic 6 1.037 253.09
,Harmonic 7 1.915 444.65
,Harmonic 8 0.903 70.87
,Harmonic 9 (-1.006) 113.15
,Harmonic 10 (-0.668) 93.69
,Harmonic 11 1.769 75.6
,Harmonic 12 (-0.723) 58.8
,Harmonic 13 0.104 45.26
,Harmonic 14 2.892 51.97
,Harmonic 15 2.588 42.89
,Harmonic 16 1.194 70.0
,Harmonic 17 0.815 20.14]
note26 :: Note
note26 = Note
(Pitch 622.254 63 "d#5")
27
(Range
(NoteRange
(NoteRangeAmplitude 8711.55 14 8.19)
(NoteRangeHarmonicFreq 1 622.25))
(NoteRange
(NoteRangeAmplitude 622.25 1 16158.0)
(NoteRangeHarmonicFreq 16 9956.06)))
[Harmonic 1 1.626 16158.0
,Harmonic 2 0.872 8979.49
,Harmonic 3 2.008 1638.86
,Harmonic 4 (-1.747) 1055.06
,Harmonic 5 (-1.105) 543.2
,Harmonic 6 (-0.578) 214.0
,Harmonic 7 (-1.3) 84.73
,Harmonic 8 (-0.701) 33.49
,Harmonic 9 2.632 27.02
,Harmonic 10 (-0.649) 30.28
,Harmonic 11 0.905 114.3
,Harmonic 12 (-1.208) 25.71
,Harmonic 13 0.344 41.87
,Harmonic 14 2.271 8.19
,Harmonic 15 2.205 38.32
,Harmonic 16 2.169 16.72]
note27 :: Note
note27 = Note
(Pitch 659.255 64 "e5")
28
(Range
(NoteRange
(NoteRangeAmplitude 9229.57 14 12.72)
(NoteRangeHarmonicFreq 1 659.25))
(NoteRange
(NoteRangeAmplitude 659.25 1 13369.0)
(NoteRangeHarmonicFreq 15 9888.82)))
[Harmonic 1 (-1.323) 13369.0
,Harmonic 2 2.362 6498.9
,Harmonic 3 (-1.579) 4576.64
,Harmonic 4 (-2.262) 1962.15
,Harmonic 5 (-1.987) 1024.28
,Harmonic 6 (-2.137) 534.96
,Harmonic 7 2.862 164.19
,Harmonic 8 0.178 156.94
,Harmonic 9 (-0.213) 80.08
,Harmonic 10 5.6e-2 64.31
,Harmonic 11 0.252 34.03
,Harmonic 12 2.953 32.86
,Harmonic 13 (-1.328) 13.91
,Harmonic 14 2.554 12.72
,Harmonic 15 (-0.383) 36.9]
note28 :: Note
note28 = Note
(Pitch 698.456 65 "f5")
29
(Range
(NoteRange
(NoteRangeAmplitude 9778.38 14 17.64)
(NoteRangeHarmonicFreq 1 698.45))
(NoteRange
(NoteRangeAmplitude 698.45 1 16540.0)
(NoteRangeHarmonicFreq 14 9778.38)))
[Harmonic 1 (-2.841) 16540.0
,Harmonic 2 (-0.492) 12481.06
,Harmonic 3 (-0.773) 6167.16
,Harmonic 4 1.959 1549.97
,Harmonic 5 (-1.774) 1959.47
,Harmonic 6 (-0.235) 836.39
,Harmonic 7 1.028 409.67
,Harmonic 8 (-2.672) 234.65
,Harmonic 9 3.054 132.23
,Harmonic 10 6.9e-2 36.6
,Harmonic 11 (-0.501) 58.22
,Harmonic 12 1.722 72.06
,Harmonic 13 2.844 110.3
,Harmonic 14 (-2.902) 17.64]
note29 :: Note
note29 = Note
(Pitch 739.989 66 "f#5")
30
(Range
(NoteRange
(NoteRangeAmplitude 8879.86 12 13.94)
(NoteRangeHarmonicFreq 1 739.98))
(NoteRange
(NoteRangeAmplitude 739.98 1 10275.0)
(NoteRangeHarmonicFreq 13 9619.85)))
[Harmonic 1 1.821 10275.0
,Harmonic 2 1.04 2340.27
,Harmonic 3 0.493 2623.98
,Harmonic 4 1.726 1725.14
,Harmonic 5 1.701 347.92
,Harmonic 6 2.328 137.91
,Harmonic 7 3.114 69.22
,Harmonic 8 (-1.478) 116.1
,Harmonic 9 (-2.385) 297.17
,Harmonic 10 2.254 67.96
,Harmonic 11 1.135 71.09
,Harmonic 12 (-1.211) 13.94
,Harmonic 13 (-2.825) 39.83]
note30 :: Note
note30 = Note
(Pitch 783.991 67 "g5")
31
(Range
(NoteRange
(NoteRangeAmplitude 9407.89 12 8.43)
(NoteRangeHarmonicFreq 1 783.99))
(NoteRange
(NoteRangeAmplitude 783.99 1 8535.0)
(NoteRangeHarmonicFreq 12 9407.89)))
[Harmonic 1 1.826 8535.0
,Harmonic 2 0.569 4178.45
,Harmonic 3 (-2.906) 470.71
,Harmonic 4 0.603 154.66
,Harmonic 5 3.029 366.5
,Harmonic 6 (-2.159) 170.22
,Harmonic 7 (-0.125) 156.25
,Harmonic 8 1.666 33.33
,Harmonic 9 (-1.406) 39.75
,Harmonic 10 2.608 39.57
,Harmonic 11 3.032 9.44
,Harmonic 12 1.451 8.43]
note31 :: Note
note31 = Note
(Pitch 830.609 68 "g#5")
32
(Range
(NoteRange
(NoteRangeAmplitude 9136.69 11 38.39)
(NoteRangeHarmonicFreq 1 830.6))
(NoteRange
(NoteRangeAmplitude 1661.21 2 9620.0)
(NoteRangeHarmonicFreq 12 9967.3)))
[Harmonic 1 1.286 9044.96
,Harmonic 2 1.92 9620.0
,Harmonic 3 0.137 5254.54
,Harmonic 4 0.753 2224.84
,Harmonic 5 (-2.352) 515.7
,Harmonic 6 (-1.601) 90.12
,Harmonic 7 (-2.6e-2) 226.24
,Harmonic 8 (-2.789) 320.46
,Harmonic 9 (-1.726) 416.7
,Harmonic 10 (-1.281) 63.84
,Harmonic 11 (-2.083) 38.39
,Harmonic 12 1.532 69.35]
note32 :: Note
note32 = Note
(Pitch 880.0 69 "a5")
33
(Range
(NoteRange
(NoteRangeAmplitude 9680.0 11 0.66)
(NoteRangeHarmonicFreq 1 880.0))
(NoteRange
(NoteRangeAmplitude 880.0 1 647.0)
(NoteRangeHarmonicFreq 11 9680.0)))
[Harmonic 1 (-1.878) 647.0
,Harmonic 2 (-1.615) 202.42
,Harmonic 3 (-6.4e-2) 14.05
,Harmonic 4 3.017 11.54
,Harmonic 5 (-2.206) 15.27
,Harmonic 6 0.574 4.96
,Harmonic 7 1.726 1.13
,Harmonic 8 0.891 6.16
,Harmonic 9 1.1 1.15
,Harmonic 10 1.855 2.64
,Harmonic 11 (-1.738) 0.66]
note33 :: Note
note33 = Note
(Pitch 932.328 70 "a#5")
34
(Range
(NoteRange
(NoteRangeAmplitude 9323.27 10 41.88)
(NoteRangeHarmonicFreq 1 932.32))
(NoteRange
(NoteRangeAmplitude 932.32 1 16253.0)
(NoteRangeHarmonicFreq 10 9323.27)))
[Harmonic 1 (-1.483) 16253.0
,Harmonic 2 (-2.066) 7225.96
,Harmonic 3 2.156 1616.77
,Harmonic 4 (-1.425) 390.17
,Harmonic 5 (-0.551) 285.56
,Harmonic 6 3.043 47.89
,Harmonic 7 0.796 127.41
,Harmonic 8 2.026 68.71
,Harmonic 9 (-0.457) 45.16
,Harmonic 10 0.43 41.88]
note34 :: Note
note34 = Note
(Pitch 987.767 71 "b5")
35
(Range
(NoteRange
(NoteRangeAmplitude 9877.67 10 39.29)
(NoteRangeHarmonicFreq 1 987.76))
(NoteRange
(NoteRangeAmplitude 1975.53 2 9333.0)
(NoteRangeHarmonicFreq 10 9877.67)))
[Harmonic 1 0.937 8714.1
,Harmonic 2 1.674 9333.0
,Harmonic 3 2.601 338.15
,Harmonic 4 0.776 713.1
,Harmonic 5 1.694 100.74
,Harmonic 6 (-1.522) 184.14
,Harmonic 7 2.107 385.19
,Harmonic 8 (-0.253) 105.12
,Harmonic 9 2.523 40.23
,Harmonic 10 (-0.893) 39.29]
note35 :: Note
note35 = Note
(Pitch 1046.5 72 "c6")
36
(Range
(NoteRange
(NoteRangeAmplitude 9418.5 9 5.81)
(NoteRangeHarmonicFreq 1 1046.5))
(NoteRange
(NoteRangeAmplitude 1046.5 1 10201.0)
(NoteRangeHarmonicFreq 9 9418.5)))
[Harmonic 1 1.227 10201.0
,Harmonic 2 (-2.557) 2926.22
,Harmonic 3 0.927 645.13
,Harmonic 4 (-0.849) 203.52
,Harmonic 5 (-0.128) 22.41
,Harmonic 6 (-2.888) 28.78
,Harmonic 7 (-3.061) 60.72
,Harmonic 8 (-1.763) 12.44
,Harmonic 9 2.928 5.81]
|
anton-k/sharc-timbre
|
src/Sharc/Instruments/ViolaMarteleBowing.hs
|
bsd-3-clause
| 46,788
| 0
| 15
| 13,326
| 17,955
| 9,312
| 8,643
| 1,598
| 1
|
{-# LANGUAGE FlexibleInstances #-}
module Hcommand
( parseArgs
, Context
, ReadArg (readArg)
, getArg
, run
) where
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Spec
data Flag = Arg String | NoArg
data Context = Context { ctxSpec :: Spec.Spec
, ctxAnons :: [String]
, ctxFlags :: Map.Map String Flag
}
class ReadArg a where
readArg :: String -> a
instance ReadArg String where
readArg s = read $ show s :: String
run :: Spec.Spec -> [String] -> (Context -> IO ()) -> IO ()
run spec args action =
let ctx = parseArgs spec args
in
action ctx
parseArgs :: Spec.Spec -> [String] -> Context
parseArgs specs args =
let ctx = parseArgs' Context {ctxSpec=specs, ctxAnons=[], ctxFlags=Map.empty} args
in
ctx {ctxAnons=List.reverse $ ctxAnons ctx}
parseArgs' :: Context -> [String] -> Context
parseArgs' ctx [] = ctx
parseArgs' ctx [arg] =
let newAnons = arg : ctxAnons ctx
in
ctx {ctxAnons=newAnons}
parseArgs' ctx (arg1 : arg2 : rest) =
if "-" `List.isPrefixOf` arg1
then
let spec = Maybe.fromMaybe (error "invalid flag") (Map.lookup arg1 (Spec.flags $ ctxSpec ctx))
in
case spec of
Spec.Flag ->
let newFlags = Map.insert arg1 (Arg arg2) (ctxFlags ctx)
newCtx = ctx {ctxFlags=newFlags}
in parseArgs' newCtx rest
Spec.NoArg ->
let newFlags = Map.insert arg1 NoArg (ctxFlags ctx)
newCtx = ctx {ctxFlags=newFlags}
in
parseArgs' newCtx (arg2 : rest)
Spec.Anon -> error "invalid flag"
else
let newAnons = arg1 : ctxAnons ctx
newCtx = ctx {ctxAnons=newAnons}
in
parseArgs' newCtx (arg2 : rest)
getArg :: (ReadArg r) => String -> Context -> r
getArg arg ctx =
if "-" `List.isPrefixOf` arg
then
let val = Maybe.fromMaybe (error "No flag with this name") (Map.lookup arg (ctxFlags ctx))
in
case val of
NoArg -> readArg $ show True
Arg s -> readArg s
else
let i = Maybe.fromMaybe (error "No flag with this name") (Spec.anonIndex arg $ ctxSpec ctx)
in
readArg $ ctxAnons ctx !! i
|
jpanda109/Hcommand
|
src/Hcommand.hs
|
bsd-3-clause
| 2,253
| 0
| 17
| 642
| 796
| 419
| 377
| 60
| 4
|
module DES (BlockCipher(..), DES(..)) where
import Data.Char (ord, chr)
import Data.Bits (shiftL, shiftR, (.&.), (.|.), xor, Bits)
import Data.Tuple (swap)
import Crypto.Classes (BlockCipher(..))
import Data.Tagged (Tagged(..))
import Data.Serialize (Serialize(..), putWord32be, getByteString)
import Data.Word (Word32)
import qualified Data.ByteString as B
generateKeys key = f (join 9 (key, key)) 4
where f k len = map (getKey k) [0..(len-1)]
getKey k i = (shiftR k (10 - i)) .&. 0xFF
expand n = (shiftL (n .&. 0x30) 2) .|.
(shiftL (n .&. 0x4 ) 3) .|.
(shiftL (n .&. 0xC) 1) .|.
(shiftR (n .&. 0x8) 1) .|.
(n .&. 0x3)
-- split int n into len ints of bitlength k
splitList bitlength len n = map f [0..(len-1)]
where f i = n `shiftR` ((len - i - 1) * bitlength) .&. mask
mask = (1 `shiftL` bitlength) - 1
split k n = (left, right)
where left:right:_ = splitList k 2 n
-- concatenate a list of ints of bitlength k
joinList k = foldl (\a b -> (a `shiftL` k) .|. b) 0
join k (a, b) = joinList k [a, b]
-- 8 bits -> 6 bits
sBoxLookup n = join 3 (s1 !! (fromIntegral l), s2 !! (fromIntegral r))
where (l, r) = split 4 n
s1 = [5, 2, 1, 6, 3, 4, 7, 0, 1, 4, 6, 2, 0, 7, 5, 3]
s2 = [4, 0, 6, 5, 7, 1, 3, 2, 5, 3, 0, 7, 6, 2, 1, 4]
desRound (l, r) k_i = (r, newR)
where newR = xor l . sBoxLookup . xor k_i . expand $ r
-- encrypt 12 bit plaintex n with keys
desEncryptBlock keys n = join 6 $ foldl desRound (split 6 n) keys
desDecryptBlock keys n = join 6 $ swap $ foldl desRound (swap $ split 6 n) keys
joinTriple triple = [a,b]
where (a, b) = split 12 $ joinList 8 triple
desProcessBlock f plaintext = splitList 8 3 . joinList 12 $ (map f $ joinTriple plaintext)
desEncrypt k = desProcessBlock (desEncryptBlock (generateKeys k))
desDecrypt k = desProcessBlock (desDecryptBlock (reverse $ generateKeys k))
data DES = DES { rawKey :: Word32 } deriving Show
instance Serialize DES where
put k = do
putWord32be (rawKey k)
get = do
b <- getByteString 4
case buildKey b of
Nothing -> fail "Invalid key on 'get'"
Just k -> return k
instance BlockCipher DES where
blockSize = Tagged 24
keyLength = Tagged 9
encryptBlock (DES k) plaintext = B.pack . map fromIntegral $ desEncrypt k (map fromIntegral (B.unpack (plaintext)))
decryptBlock (DES k) ciphertext = B.pack . map fromIntegral . desDecrypt k . map fromIntegral . B.unpack $ ciphertext
buildKey k = Just $ DES $ head . map fromIntegral $ B.unpack k
|
cjlarose/haskell-des
|
DES.hs
|
bsd-3-clause
| 2,598
| 0
| 13
| 665
| 1,177
| 636
| 541
| 52
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -Wno-orphans #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-|
Module : AERN2.MP.WithCurrentPrec.Comparisons
Description : WithCurrentPrec order relations and operations
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
WithCurrentPrec order relations and operations
-}
module AERN2.MP.WithCurrentPrec.Comparisons
()
where
import MixedTypesNumPrelude
-- import qualified Prelude as P
-- import Text.Printf
-- import qualified Numeric.CollectErrors as CN
import AERN2.MP.Dyadic
import AERN2.MP.WithCurrentPrec.Type
instance
(HasEqAsymmetric t1 t2, p1 ~ p2)
=>
HasEqAsymmetric (WithCurrentPrec p1 t1) (WithCurrentPrec p2 t2)
where
type EqCompareType (WithCurrentPrec p1 t1) (WithCurrentPrec p2 t2) = EqCompareType t1 t2
equalTo = lift2P equalTo
notEqualTo = lift2P notEqualTo
instance
(HasOrderAsymmetric t1 t2, p1 ~ p2)
=>
HasOrderAsymmetric (WithCurrentPrec p1 t1) (WithCurrentPrec p2 t2)
where
type OrderCompareType (WithCurrentPrec p1 t1) (WithCurrentPrec p2 t2) = OrderCompareType t1 t2
greaterThan = lift2P greaterThan
lessThan = lift2P lessThan
geq = lift2P geq
leq = lift2P leq
instance
(CanAbs t)
=>
CanAbs (WithCurrentPrec p t)
where
type AbsType (WithCurrentPrec p t) = WithCurrentPrec p (AbsType t)
abs = lift1 abs
instance
(CanMinMaxAsymmetric t1 t2, p1 ~ p2)
=>
CanMinMaxAsymmetric (WithCurrentPrec p1 t1) (WithCurrentPrec p2 t2)
where
type MinMaxType (WithCurrentPrec p1 t1) (WithCurrentPrec p2 t2) = WithCurrentPrec p1 (MinMaxType t1 t2)
min = lift2 min
max = lift2 max
-- mixed type instances:
$(declForTypes
[[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |]]
(\ t -> [d|
-- min, max
instance
(CanMinMaxAsymmetric a $t)
=>
CanMinMaxAsymmetric (WithCurrentPrec p a) $t
where
type MinMaxType (WithCurrentPrec p a) $t = WithCurrentPrec p (MinMaxType a $t)
min = lift1T min
max = lift1T max
instance
(CanMinMaxAsymmetric a (CN $t))
=>
CanMinMaxAsymmetric (WithCurrentPrec p a) (CN $t)
where
type MinMaxType (WithCurrentPrec p a) (CN $t) = WithCurrentPrec p (MinMaxType a (CN $t))
min = lift1T min
max = lift1T max
instance
(CanMinMaxAsymmetric $t a)
=>
CanMinMaxAsymmetric $t (WithCurrentPrec p a)
where
type MinMaxType $t (WithCurrentPrec p a) = WithCurrentPrec p (MinMaxType $t a)
min = liftT1 min
max = liftT1 max
instance
(CanMinMaxAsymmetric (CN $t) a)
=>
CanMinMaxAsymmetric (CN $t) (WithCurrentPrec p a)
where
type MinMaxType (CN $t) (WithCurrentPrec p a) = WithCurrentPrec p (MinMaxType (CN $t) a)
min = liftT1 min
max = liftT1 max
-- equality
instance
(HasEqAsymmetric a $t)
=>
HasEqAsymmetric (WithCurrentPrec p a) $t
where
type EqCompareType (WithCurrentPrec p a) $t = EqCompareType a $t
equalTo = lift1TP (==)
notEqualTo = lift1TP (/=)
instance
(HasEqAsymmetric a (CN $t))
=>
HasEqAsymmetric (WithCurrentPrec p a) (CN $t)
where
type EqCompareType (WithCurrentPrec p a) (CN $t) = EqCompareType a (CN $t)
equalTo = lift1TP (==)
notEqualTo = lift1TP (/=)
instance
(HasEqAsymmetric $t a)
=>
HasEqAsymmetric $t (WithCurrentPrec p a)
where
type EqCompareType $t (WithCurrentPrec p a) = EqCompareType $t a
equalTo = liftT1P (==)
notEqualTo = liftT1P (/=)
instance
(HasEqAsymmetric (CN $t) a)
=>
HasEqAsymmetric (CN $t) (WithCurrentPrec p a)
where
type EqCompareType (CN $t) (WithCurrentPrec p a) = EqCompareType (CN $t) a
equalTo = liftT1P (==)
notEqualTo = liftT1P (/=)
-- order
instance
(HasOrderAsymmetric a $t)
=>
HasOrderAsymmetric (WithCurrentPrec p a) $t
where
type OrderCompareType (WithCurrentPrec p a) $t = OrderCompareType a $t
lessThan = lift1TP lessThan
greaterThan = lift1TP greaterThan
leq = lift1TP leq
geq = lift1TP geq
instance
(HasOrderAsymmetric a (CN $t))
=>
HasOrderAsymmetric (WithCurrentPrec p a) (CN $t)
where
type OrderCompareType (WithCurrentPrec p a) (CN $t) = OrderCompareType a (CN $t)
lessThan = lift1TP lessThan
greaterThan = lift1TP greaterThan
leq = lift1TP leq
geq = lift1TP geq
instance
(HasOrderAsymmetric $t a)
=>
HasOrderAsymmetric $t (WithCurrentPrec p a)
where
type OrderCompareType $t (WithCurrentPrec p a) = OrderCompareType $t a
lessThan = liftT1P lessThan
greaterThan = liftT1P greaterThan
leq = liftT1P leq
geq = liftT1P geq
instance
(HasOrderAsymmetric (CN $t) a)
=>
HasOrderAsymmetric (CN $t) (WithCurrentPrec p a)
where
type OrderCompareType (CN $t) (WithCurrentPrec p a) = OrderCompareType (CN $t) a
lessThan = liftT1P lessThan
greaterThan = liftT1P greaterThan
leq = liftT1P leq
geq = liftT1P geq
|]))
|
michalkonecny/aern2
|
aern2-mp/src/AERN2/MP/WithCurrentPrec/Comparisons.hs
|
bsd-3-clause
| 5,452
| 0
| 9
| 1,495
| 455
| 253
| 202
| -1
| -1
|
module AGL.SDL
( SurfImage
, fromSDLSurface
, renderSDL
) where
import Control.Lens
import Control.Monad (void)
import Data.Default (def)
import qualified Graphics.UI.SDL.Types as SDLT
import qualified Graphics.UI.SDL.Video as SDLV
import qualified Graphics.UI.SDL.Rect as SDLR
import AGL
import AGL.Internal.Transform
import AGL.Internal.Transform.DrawState
data SurfImage = SurfImage {
imSurface :: SDLT.Surface,
imW :: Double,
imH :: Double,
imPivot :: Pivot}
instance Image SurfImage where
imageH = imH
imageW = imW
imagePivot = imPivot
-- TODO add fromSDLSubSurface
fromSDLSurface s p = SurfImage {
imSurface = s,
imW = fromIntegral $ SDLT.surfaceGetWidth s,
imH = fromIntegral $ SDLT.surfaceGetHeight s,
imPivot = p}
-- | Draws the image to the SDL surface.
--
-- Blitting errors are ignored for now (are they even possible? With which SDL backends?)
--
drawSurfImage :: SDLT.Surface -> SurfImage -> DrawState -> TranslateDrawState -> IO ()
drawSurfImage target si ds translate =
let srcW = (SDLT.surfaceGetWidth . imSurface) si
srcH = (SDLT.surfaceGetHeight . imSurface) si
targetH = SDLT.surfaceGetHeight target
ds' = translatePivot translate si ds
aglBottomLeftX = ds'^.dsX
aglBottomLeftY = ds'^.dsY
sdlTopLeftX = round aglBottomLeftX
sdlTopLeftY = targetH - round aglBottomLeftY - srcH
drect = SDLR.Rect sdlTopLeftX sdlTopLeftY srcW srcH
srcSurf = imSurface si
alphaByte = floor . (255 *) . min 1.0 . max 0.0 . unAlpha
in do
SDLV.setAlpha srcSurf [SDLT.SrcAlpha] (ds^.dsAlpha.to alphaByte)
SDLV.blitSurface srcSurf Nothing target (Just drect)
return ()
-- | Draws the picture by pushing transforms through the standard AGL Transform
-- | and delegating execution to drawSurfImage.
drawSDL ds target pic = void $ execTransform ds pic (drawSurfImage target)
-- | Draws the picture and flips the screen surface.
renderSDL :: SDLT.Surface -> Picture SurfImage -> IO ()
renderSDL screen pic = drawSDL def screen pic >> SDLV.flip screen
|
robinp/agl
|
AGL/SDL.hs
|
bsd-3-clause
| 2,062
| 0
| 13
| 405
| 544
| 299
| 245
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Protocol
Description : Disco worker protocol implementation
Module handles receiving and sending Disco worker protocol messages.
More information: <http://disco.readthedocs.org/en/latest/howto/worker.html>
MSG format: \<name\> \‘SP\’ \<payload-len\> \‘SP\’ \<payload\> \‘\\n\’
\'SP\' - single space character
\<payload-len\> - is the length of the \<payload\> in bytes
\<payload\> is a JSON formatted term
-}
module Protocol(
exchange_msg, -- :: Worker_msg -> MaybeT IO Master_msg
send_worker, -- :: IO ()
recive, -- :: MaybeT IO Master_msg
Master_msg(..),
Worker_msg(..),
Task(..),
Input(..),
Output(..),
Task_input(..),
Replica(..),
Input_label(..),
Input_flag(..),
Input_status(..),
Worker_input_msg(..)
) where
import System.IO
import System.Posix.Process
import System.Timeout
import Data.Aeson
import qualified Data.Vector as V
import Data.Maybe
import Control.Applicative ((<$>), (<*>), empty)
import Control.Monad
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.Text as DT
-- | Protocol version
get_version :: String
get_version = "1.1"
get_timeout :: Int
get_timeout = 600 * 10^6 -- in microseconds (because of System.Timeout library)
-- | First message from worker to Disco
data Worker_info = Worker_info {
version :: String,
pid :: Int
} deriving (Show, Eq)
instance ToJSON Worker_info where
toJSON (Worker_info version pid) = object ["version" .= version, "pid" .= pid]
-- | Task information from Disco
data Task = Task {
taskid :: Int,
master :: String,
disco_port :: Int,
put_port :: Int,
ddfs_data :: String,
disco_data :: String,
stage :: String,
grouping :: String,
group :: (Int,String),
jobfile :: String,
jobname :: String,
host :: String
} deriving (Show, Eq)
instance FromJSON Task where
parseJSON (Object v) =
Task <$>
(v .: "taskid") <*>
(v .: "master") <*>
(v .: "disco_port") <*>
(v .: "put_port") <*>
(v .: "ddfs_data") <*>
(v .: "disco_data") <*>
(v .: "stage") <*>
(v .: "grouping") <*>
(v .: "group") <*>
(v .: "jobfile") <*>
(v .: "jobname") <*>
(v .: "host")
parseJSON _ = empty
data Replica = Replica {
replica_id :: Int,
replica_location :: String
} deriving (Show, Eq)
instance FromJSON Replica where
parseJSON (Array v) =
case (V.length v) of
2 -> let rid:rloc:_ = V.toList v in
Replica <$>
(parseJSON rid) <*>
(parseJSON rloc)
otherwise -> empty
parseJSON _ = empty
data Input_flag = More | Done deriving (Show, Eq) --kept in M_task_input
data Input_status = Ok | Busy | Failed deriving (Show, Eq)
instance FromJSON Input_flag where
parseJSON (String iflag) =
case parse_input_flag (DT.unpack iflag) of
Just fl -> return fl
Nothing -> empty
parseJSON _ = empty
parse_input_flag :: String -> Maybe Input_flag
parse_input_flag iflag =
case iflag of
"more" -> Just More
"done" -> Just Done
otherwise -> Nothing
parse_input_status :: String -> Maybe Input_status
parse_input_status istat =
case istat of
"ok" -> Just Ok
"busy" -> Just Busy
"failed" -> Just Failed
otherwise -> Nothing
instance FromJSON Input_status where
parseJSON (String istat) =
case parse_input_status (DT.unpack istat) of
Just st -> return st
Nothing -> empty
parseJSON _ = empty
instance FromJSON Input_label where
parseJSON (String ilabel) =
case ilabel of
"all" -> return All
_ -> empty
parseJSON ilabel = Label <$> parseJSON ilabel --TODO pattern ?
instance ToJSON Input_label where
toJSON All = String "all"
toJSON (Label x) = toJSON x
data Input_label = All | Label Int deriving (Show, Eq)
data Input = Input {
input_id :: Int,
status :: Input_status,
input_label :: Input_label,
replicas :: [Replica]
} deriving (Show, Eq)
instance FromJSON Input where
parseJSON (Array v) =
case (V.length v) of
4 ->
let iid:stat:lab:rep:_ = V.toList v in
Input <$>
(parseJSON iid) <*>
(parseJSON stat) <*>
(parseJSON lab) <*>
(parseJSON rep)
otherwise -> empty
parseJSON _ = empty
data Task_input = Task_input {
input_flag :: Input_flag,
inputs :: [Input]
} deriving (Show, Eq)
instance FromJSON Task_input where
parseJSON (Array v) =
case (V.length v) of
2 ->
let t_flag = V.head v
[ins] = (V.toList . V.tail) v in
Task_input <$>
parseJSON t_flag <*>
parseJSON ins
otherwise -> empty
parseJSON _ = empty
-- | Input message from Worker
data Worker_input_msg = Exclude [Int] | Include [Int] | Empty deriving (Show, Eq)
data Input_err = Input_err {
input_err_id :: Int,
rep_ids :: [Int]
} deriving (Show, Eq)
data Output_type = Disco | Part | Tag deriving (Show, Eq)
instance ToJSON Output_type where
toJSON Disco = String "disco"
toJSON Part = String "part"
toJSON Tag = String "tag"
-- | Output message from Worker
data Output = Output {
output_label :: Input_label,
output_location :: String,
output_size :: Integer
} deriving (Show, Eq)
-- | Messages from Worker to Disco
data Worker_msg
= W_worker
| W_task
| W_input Worker_input_msg
| W_input_err Input_err
| W_msg String
| W_output Output
| W_done
| W_error String
| W_fatal String
| W_ping deriving (Show, Eq)
-- | Messages from Disco to Worker
data Master_msg
= M_ok
| M_die
| M_task Task
| M_task_input Task_input
| M_retry [Replica]
| M_fail
| M_wait Int deriving (Show, Eq)
prep_init_worker :: IO BL.ByteString
prep_init_worker = getProcessID >>= json_w_info
where json_w_info pid = return $ encode Worker_info{version = get_version, pid = fromIntegral pid}
prep_input_msg :: Worker_input_msg -> BL.ByteString
prep_input_msg wim =
case wim of
Exclude xs -> encode (String "exclude", xs)
Include xs -> encode (String "include", xs)
Empty -> encode $ String ""
prep_input_err :: Input_err -> BL.ByteString
prep_input_err (Input_err ie_id xs) = encode (ie_id, xs)
prep_output :: Output -> BL.ByteString
prep_output (Output label location o_size) = encode (label, location, o_size)
prepare_msg :: Worker_msg -> (String, BL.ByteString)
prepare_msg wm =
case wm of
W_task -> ("TASK", encode $ String "")
W_input w_input_msg -> ("INPUT", prep_input_msg w_input_msg)
W_input_err input_err -> ("INPUT_ERR", prep_input_err input_err)
W_msg msg -> ("MSG", encode msg)
W_output output -> ("OUTPUT", prep_output output)
W_done -> ("DONE", encode $ String "")
W_error err_msg -> ("ERROR", encode err_msg)
W_fatal fatal_msg -> ("FATAL", encode fatal_msg)
W_ping -> ("PING", encode $ String "")
-- otherwise -> ("ERROR", encode $ String "Pattern matching fail, prepare_msg") --TODO
--separated because of impure getProcessPID in prepare init worker
-- | Sending initiall messge from Worker to Disco
send_worker :: IO ()
send_worker = prep_init_worker >>= send1
where send1 json_msg = hPutStrLn stderr $ unwords ["WORKER", show (BL.length json_msg), BL.unpack json_msg]
-- | General sending function from Worker to Disco
send :: Worker_msg -> IO ()
send wm = do
let (tag, json_msg) = prepare_msg wm
hPutStrLn stderr $ unwords [tag, show (BL.length json_msg), BL.unpack json_msg]
handle_timeout :: MaybeT IO String
handle_timeout = do
in_msg <- lift (timeout get_timeout getLine)
case in_msg of
Nothing -> mzero
Just s -> return s
recive :: MaybeT IO Master_msg
recive = do
in_msg <- handle_timeout
let [msg, payload_len, payload] = words in_msg
process_master_msg msg payload
-- | Synchronized message exchange
exchange_msg :: Worker_msg -> MaybeT IO Master_msg
exchange_msg wm = do
lift $ send wm
lift $ hFlush stderr
recive
process_master_msg :: MonadPlus m => String -> String -> m Master_msg
process_master_msg msg payload =
case msg of
"OK" -> return M_ok
"DIE" -> return M_die
"TASK" -> maybe mzero (return . M_task) ((decode . BL.pack) payload :: Maybe Task)
"FAIL" -> return M_fail
"RETRY" -> maybe mzero (return . M_retry) ((decode . BL.pack) payload :: Maybe [Replica])
"WAIT" -> return $ M_wait $ read payload
"INPUT" -> maybe mzero (return . M_task_input) ((decode . BL.pack) payload :: Maybe Task_input)
otherwise -> mzero
|
zuzia/haskell_worker
|
src/Protocol.hs
|
bsd-3-clause
| 9,038
| 2
| 19
| 2,404
| 2,597
| 1,395
| 1,202
| 244
| 9
|
{- | Defines a power algorithm to calculate powers based on an associative
binary operation effectively. -}
module Power (
power,
powerM
) where
import Control.Monad.Identity
import Test.QuickCheck
-- COMMENT OUTDATED: Arguments are now power f n x
{- | Efficient power algorithm.
> power x f n = x `f` x `f` x `f` ... (n times x)
Examples:
>>> power 2 (+) 3
6
>>> power 2 (*) 3
8
>>> power 2 (^) 3
16
The algorithm works by using the associativity of @f@, calculating each
term only once. For example @2*2*2*2@ can be calculated with two
multiplications by first calculating @2*2 = 4@, and then
@2*2*2*2 = (2*2)*(2*2) = 4*4 = 16@.
The calculation is tail recursive, and scales like log_2(n); for example
@n = 10^10@ requires @43@ applications of @f@. I haven't tested the
standard deviation on this, but the graph looked like @±5@ in the
@10^10@ region.
The inner working is as follows:
First, g is called. For @x <= 1@ it is the identity to work around
the negative exponent issue; for even n, it uses @x^(2n) == (x^2)^n@
and recurses.
For uneven exponents, it gives way to @h@, which is essentially the same
as @g@, but has another parameter to store the /rest value/ @r@:
@x^(2n+1) == (x^2)^n * x@. It then recurses, collecting all the rests
it encounters due to uneven exponents in the @r@ value.
Note that this is implemented using 'powerM' and the 'Identity' monad.
-}
power :: (Integral i) => (a -> a -> a) -> i -> a -> a
power f n = runIdentity . powerM (\a b -> Identity (f a b)) n
{-# INLINE power #-}
{- | Monadic version of 'power'.
This one was used to determine the number of applications of @f@ by
using the Sum monoid with the Writer monad, setting
@f a b = writer (a `f` b, Sum 1)@. The number of applications of @f@ is
then @getSum . snd . runWriter $ powerM 1 f n@.
-}
powerM :: (Integral i, Monad m) => (a -> a -> m a) -> i -> a -> m a
powerM f = g
where g n x
| n <= 0 = error "Negative exponent" -- Same as 1^(-1)
| n == 1 = return x
| even n = x `f` x >>= g (n `quot` 2)
| otherwise = x `f` x >>= h (pred n `quot` 2) x
h n r x
| n == 1 = x `f` r
| even n = x `f` x >>= h (n `quot` 2) r
| otherwise = do square <- x `f` x
rest <- r `f` x
h (pred n `quot` 2) rest square
{-# INLINE powerM #-}
-- QuickCheck part
main :: IO ()
main = runAll
runAll :: IO ()
runAll = do
let args = stdArgs { maxSuccess = 10000 }
quickCheckWith args prop_power
quickCheckWith args prop_mult
quickCheckWith args prop_concat
prop_power :: Property
prop_power = forAll arbitrary $ \(x, Positive n) ->
classify (x == (0 :: Integer)) "base 0" $
classify (x < 0) "negative base" $
classify (n > 10) "large exponent" $
(x :: Integer)^(n :: Integer) == power (*) n x
prop_mult :: Property
prop_mult = forAll arbitrary $ \(x, Positive n) ->
classify (x == 0) "n times 0" $
classify (x < 0) "negative factor" $
classify (n > 10 || abs x > 10) "large factor" $
(x :: Integer)*(n :: Integer) == power (+) n x
prop_concat :: Property
prop_concat = forAll arbitrary $ \(s, Positive n) ->
classify (null s) "empty list" $
power (++) (n :: Integer) (s :: [Int]) == concat (replicate (fromIntegral n) s)
|
quchen/HaskellEuler
|
src/Power.hs
|
bsd-3-clause
| 3,609
| 0
| 15
| 1,137
| 792
| 417
| 375
| 46
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Map as Map
import ANF.Pretty
import ANF.SCCP
import SSA.Pretty
import SSA.Syntax
import qualified SSA.ToANF as ToANF
------------------------------------------------------------------------
main :: IO ()
main = do
printAll ssaFac
printAll ssaSeven
------------------------------------------------------------------------
printAll :: Program String -> IO ()
printAll ssa = do
putStrLn "=== SSA ==="
printProgram ssa
putStrLn ""
let anf = ToANF.convert ssa
putStrLn "=== ANF ==="
printExpr anf
putStrLn ""
let anf' = sccp prims anf
putStrLn "=== ANF SCCP ==="
printExpr anf'
putStrLn ""
------------------------------------------------------------------------
prims :: PrimEnv String
prims = Map.fromList [
("mul", \[x, y] -> x * y)
, ("sub", \[x, y] -> x - y)
]
------------------------------------------------------------------------
ssaFac :: Program String
ssaFac =
Proc "fac" ["x"]
(BlockStart (Copy "r" (Const 1) $
Goto "L1")
`BlockLabel` ("L1", Phi "r0" (Map.fromList
[ (Start, Var "r")
, (Label "L1", Var "r1") ]) $
Phi "x0" (Map.fromList
[ (Start, Var "x")
, (Label "L1", Var "x1") ]) $
If (Var "x0")
(Call "r1" (Var "mul") [Var "r0", Var "x0"] $
Call "x1" (Var "sub") [Var "x0", Const 1] $
Goto "L1")
(RetCopy (Var "r0")))) $
Entry (RetCall (Var "fac") [Const 10])
------------------------------------------------------------------------
ssaSeven :: Program String
ssaSeven =
Proc "seven" ["x"]
(BlockStart (Goto "L1")
`BlockLabel` ("L1", Phi "x0" (Map.fromList
[ (Start, Const 1)
, (Label "L1", Var "x1") ]) $
Call "x1" (Var "sub") [Var "x0", Const 1] $
If (Var "x1")
(Goto "L1")
(RetCopy (Const 7)))) $
Entry (RetCall (Var "seven") [Const 10])
|
jystic/ssa-anf
|
src/Main.hs
|
bsd-3-clause
| 2,497
| 0
| 17
| 1,012
| 690
| 352
| 338
| 58
| 1
|
{-# LANGUAGE RankNTypes,
GADTs #-}
module Obsidian.GCDObsidian.Program
(Program(..)
,printProgram
,programThreads
,(*>*)
,targetArray
,targetPair
,Atomic(..)
,printAtomic
)where
import Data.Word
import Obsidian.GCDObsidian.Exp
import Obsidian.GCDObsidian.Types
import Obsidian.GCDObsidian.Globs
----------------------------------------------------------------------------
--
-- TODO: Data a and Exp a is the same. (look at this!)
data Program extra
= Skip
| forall a. Scalar a => Assign Name (Data Word32) (Data a)
-- Note: Writing of a scalar value into an array location.
| ForAll (Data Word32 -> (Program extra)) Word32
-- Could this be improved ?
| ForAllGlobal (Data Word32 -> (Program extra)) (Exp Word32)
-- DONE: I Think Allocate should not introduce nesting
| Allocate Name Word32 Type extra
-- potentially a sync is needed.
-- DONE: Analysis will check if it is REALLY needed
| Synchronize Bool
-- NOTE: Adding a synchronize statement here
-- the sync operation can now insert a Syncronizze as a guide
-- to the code generation
-- TODO: What will this mean when nested inside something ?
-- Again, to start with, I will ensure that none of my library function
-- introduces a Synchronize nested in anything.
| ProgramSeq (Program extra)
(Program extra)
| forall a. Scalar a => AtomicOp Name Name (Exp Word32) (Atomic (Data a))
-- took same as precedence as for ++ for *>*
infixr 5 *>*
(*>*) :: Program extra
-> Program extra
-> Program extra
(*>*) = ProgramSeq
programThreads :: Program extra -> Word32
programThreads Skip = 0
programThreads (Synchronize _) = 0
programThreads (Assign _ _ _) = 1
programThreads (ForAll f n) = n -- inner ForAlls are sequential
programThreads (Allocate _ _ _ _) = 0 -- programThreads p
-- programThreads (Cond b p ) = programThreads p
programThreads (p1 `ProgramSeq` p2) = max (programThreads p1) (programThreads p2)
programThreads (AtomicOp _ _ _ _) = 1
printProgram :: Show extra => Program extra -> String
printProgram Skip = ";"
printProgram (Synchronize b) = "Sync " ++ show b ++ "\n"
printProgram (Assign n t e) = n ++ "[" ++ show t ++ "]" ++ " = " ++ show e ++ ";\n"
printProgram (ForAll f n) = "par i " ++ show n ++ " {\n" ++ printProgram (f (variable "i")) ++ "\n}"
-- printProgram (Cond b p) = "cond {\n" ++ printProgram p ++ "\n}"
printProgram (Allocate name n t e) = name ++ " = malloc(" ++ show n ++ ")\n" ++
"[*** " ++ show e ++ " ***]\n"
printProgram (ProgramSeq p1 p2) = printProgram p1 ++ printProgram p2
-- Needs fresh name generations to be correct
printProgram (AtomicOp name n i e) = name ++ " = " ++ printAtomic e ++
"(" ++ n ++ "[" ++ show i ++ "])"
instance Show extra => Show (Program extra) where
show = printProgram
targetArray :: Scalar a => Name -> (Exp Word32,Exp a) -> Program ()
targetArray n (i,a) = Assign n i a
targetPair :: (Scalar a, Scalar b) => Name -> Name -> (Exp Word32,(Exp a,Exp b)) -> Program ()
targetPair n1 n2 (i,(a,b)) = Assign n1 i a *>*
Assign n2 i b
-- Atomic operations
data Atomic a where
AtomicInc :: Atomic (Data Int)
printAtomic AtomicInc = "atomicInc"
|
svenssonjoel/GCDObsidian
|
Obsidian/GCDObsidian/Program.hs
|
bsd-3-clause
| 3,448
| 0
| 11
| 924
| 928
| 492
| 436
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module Hop.Schwifty.Swift.M105.Parser (
parseSwift
) where
import Data.Text (Text)
import Data.Ratio
import Data.Maybe (fromJust)
import qualified Data.Text as T
import Text.Megaparsec
import Text.Megaparsec.Text
import Control.Lens
import Hop.Schwifty.Swift.M105.Types
-- Field Parsers
senderRef :: Parser SendersRef
senderRef = do
s <- count' 1 16 alphaNumChar <?> "[1,16] Char"
return $ SendersRef $ T.pack s
timeIndication :: Parser TimeIndication
timeIndication = do
_ <- char '/'
c <- count' 1 8 letterChar
_ <- char '/'
t <- count 4 numberChar
s <- char '-' <|> char '+'
o <- count 4 numberChar
return $ TimeIndication (T.pack c) (T.pack t) (T.pack [s]) (T.pack o)
bankOperationCode :: Parser BankOperationCode
bankOperationCode = try (string "CRED" >> return NormalCreditTransfer)
<|> try (string "CRTS" >> return TestMessage)
<|> try (string "SPAY" >> return SWIFTPay)
<|> try (string "SPRI" >> return Priority)
<|> try (string "SSTD" >> return Standard)
instructionCode :: Parser InstructionCode
instructionCode =
try (string "CORT" >> optional (char '/') >> optional (manyTill anyChar $ try newline)
>>= return . CorporateTrade . fmap T.pack)
<|> try (string "INTC" >> optional (char '/') >> optional (manyTill anyChar $ try newline)
>>= return . IntraCompanyPayment . fmap T.pack)
<|> try (string "REPA" >> optional (char '/') >> optional (manyTill anyChar $ try newline)
>>= return . RelatedPayment . fmap T.pack)
<|> try (string "SDVA" >> optional (char '/') >> optional (manyTill anyChar $ try newline)
>>= return . SameDayValue . fmap T.pack)
transactionTypeCode :: Parser TransactionTypeCode
transactionTypeCode = fmap (TransactionTypeCode . T.pack) $ count 3 alphaNumChar
valueParser :: Parser Value
valueParser = do
amtWhole <- some numberChar
_ <- char ','
amtPart <- some numberChar
return $ Value (read amtWhole :: Int)
((read amtPart :: Int) % (10 ^ length amtPart))
currencyParser :: Parser Text
currencyParser = fmap T.pack (count 3 alphaNumChar <?> "Currency as ISO 4217 (e.g. XXX)")
vDateCurSetl :: Parser VDateCurSetl
vDateCurSetl = do
dt <- count 6 numberChar <?> "Date in YYMMDD format"
cur <- currencyParser
val <- valueParser
return $ VDateCurSetl (Time dt) cur val
currencyInstructedAmt :: Parser CurrencyInstructedAmt
currencyInstructedAmt = do
cur <- currencyParser
val <- valueParser
return $ CurrencyInstructedAmt cur val
exchangeRate :: Parser ExchangeRate
exchangeRate = fmap ExchangeRate valueParser
idType :: Parser IdType
idType = try (string "ARNU" >> return AlienReg)
<|> try (string "CCPT" >> return Passport)
<|> try (string "CUST" >> return CustomerId)
<|> try (string "DRLC" >> return DriversLicence)
<|> try (string "EMPL" >> return Employer)
<|> try (string "NIDN" >> return NationalId)
<|> try (string "SOSE" >> return SocialSecurity)
<|> try (string "TXID" >> return TaxId)
partyId :: Parser PartyId
partyId = do
code <- idType
_ <- char '/'
countryCode <- count 2 letterChar
_ <- char '/'
identifier <- someTill anyChar newline
return $ PartyId code (T.pack countryCode) (T.pack identifier)
account :: Parser Account
account = do
_ <- char '/'
acct <- someTill anyChar newline
return $ Account $ T.pack acct
identifierCode :: Parser IdentifierCode
identifierCode = fmap (IdentifierCode . T.pack) $ space >> manyTill anyChar newline
field50FIdentifier :: Parser Field50FIdentifier
field50FIdentifier = try (fmap F50F_Account account)
<|> fmap F50F_PartyId partyId
field50FExtra :: Parser Field50FExtra
field50FExtra = try (space >> string "1/" >> manyTill anyChar newline >>= return . F50F_1_NameOrdCustomer . T.pack)
<|> try (space >> string "2/" >> manyTill anyChar newline >>= return . F50F_2_AddressLine . T.pack)
<|> try (space >> string "3/" >> manyTill anyChar newline >>= return . F50F_3_CountryAndTown . T.pack)
<|> try (space >> string "4/" >> manyTill anyChar newline >>= return . F50F_4_DateOfBirth . T.pack)
<|> try (space >> string "5/" >> manyTill anyChar newline >>= return . F50F_5_PlaceOfBirth . T.pack)
<|> try (space >> string "6/" >> manyTill anyChar newline >>= return . F50F_6_CustIdNum . T.pack)
<|> try (space >> string "7/" >> manyTill anyChar newline >>= return . F50F_7_NationalIdNum . T.pack)
<|> try (space >> string "8/" >> manyTill anyChar newline >>= return . F50F_8_AdditionalInfo . T.pack)
field50FExtras :: Parser [Field50FExtra]
field50FExtras = manyTill field50FExtra eof
invalidCustomerExtra :: Parser Text
invalidCustomerExtra = fmap T.pack $ space >> manyTill anyChar newline
invalidCustomerExtras :: Parser (Maybe [Text])
invalidCustomerExtras = optional $ someTill invalidCustomerExtra eof
orderingCustomerA :: Parser OrderingCustomer
orderingCustomerA = do
acct <- account
ident <- identifierCode
leftovers <- invalidCustomerExtras
return $ Field50A acct ident leftovers
orderingCustomerF :: Parser OrderingCustomer
orderingCustomerF = do
ident <- field50FIdentifier
x <- optional field50FExtras
leftovers <- invalidCustomerExtras
return $ Field50F ident x leftovers
orderingCustomerK :: Parser OrderingCustomer
orderingCustomerK = do
acct <- account
x <- optional field50FExtras
leftovers <- invalidCustomerExtras
return $ Field50K acct x leftovers
beneficiaryCustomer :: Parser BeneficiaryCustomer
beneficiaryCustomer = do
acct <- char '/' >> manyTill anyChar newline
dets <- maybe "" (T.intercalate "\n") <$> invalidCustomerExtras
return $ BeneficiaryCustomer (T.pack acct) dets
detailsOfCharges :: Parser DetailsOfCharges
detailsOfCharges = try (string "BEN" >> return Beneficiary)
<|> try (string "OUR" >> return OurCustomerCharged)
<|> try (string "SHA" >> return SharedCharges)
-- SWIFT Message Parser
parseCode :: Parser Code
parseCode = do
_ <- char ':' <?> "SWIFT Tag Opening \":\""
c <- count 3 anyChar
_ <- char ':' <?> "SWIFT Tag Closing \":\""
return $ Code $ T.pack c
parseBody :: Parser Text
parseBody = do
b <- try (someTill anyChar (try $ lookAhead parseCode)) <|> someTill anyChar eof
return $ T.pack b
parseToken :: Parser (Code, Text)
parseToken = do
c <- parseCode
b <- parseBody
return (c, b)
tokenize :: Parser [(Code,Text)]
tokenize = manyTill anyChar (try $ lookAhead parseCode) >> many parseToken
validateSWIFT :: MaybeSWIFT -> Either String SWIFT
validateSWIFT msg = case reqs of
[] -> Right finalSWIFT
xs -> Left $ "Required Fields Not Found: " ++ show xs
where
go s l = maybe [s] (const []) (view l msg)
reqs :: [String]
reqs = go "20 " msCode20
++ go "23B" msCode23B
++ go "32A" msCode32A
++ go "50a" msCode50a
++ go "59a" msCode59a
++ go "71A" msCode71A
finalSWIFT = SWIFT
(fromJust $ view msCode20 msg)
(view msCode13C msg)
(fromJust $ view msCode23B msg)
(view msCode23E msg)
(view msCode26T msg)
(fromJust $ view msCode32A msg)
(view msCode33B msg)
(view msCode36 msg)
(fromJust $ view msCode50a msg)
(view msCode51A msg)
(view msCode52A msg)
(view msCode53a msg)
(view msCode54A msg)
(view msCode55A msg)
(view msCode56A msg)
(view msCode57A msg)
(fromJust $ view msCode59a msg)
(view msCode70 msg)
(fromJust $ view msCode71A msg)
(view msCode71F msg)
(view msCode71G msg)
(view msCode72 msg)
(view msCode77B msg)
mapToMaybeSWIFT :: [(Code, Text)] -> ([String], MaybeSWIFT)
mapToMaybeSWIFT = foldl go mempty
where
go :: ([String], MaybeSWIFT) -> (Code, Text) -> ([String], MaybeSWIFT)
go (errs, ms) (c, t) = let (err, ms') = parseRest c t in (errs ++ err, ms `mappend` ms')
parseSwift :: Text -> Either String SWIFT
parseSwift s = case runParser tokenize "Swift Message" s of
Left err -> Left $ show err ++ "\n ## found in ## \n" ++ show s
Right v -> let (errs,m) = mapToMaybeSWIFT v
in case validateSWIFT m of
Left err -> Left $ err ++ "\n ## With Errors ##\n" ++ show errs
Right mv -> Right mv
parseBodyComment :: Parser String
parseBodyComment = manyTill anyChar (char ':') -- you want this ':' to capture as it delimits the end of a comma
restHelper :: (Monoid s) => Parsec Text b -> String -> Text -> ASetter' s (Maybe b) -> ([String], s)
restHelper p n t c = either (\x -> ([show x], mempty)) (\x -> ([], set c (Just x) mempty)) $ runParser (optional parseBodyComment >> p) n t
parseRest :: Code -> Text -> ([String], MaybeSWIFT)
parseRest (Code "20 ") t = restHelper senderRef "senderRef" t msCode20
parseRest (Code "13C") t = restHelper timeIndication "timeIndication" t msCode13C
parseRest (Code "23B") t = restHelper bankOperationCode "timeIndication" t msCode23B
parseRest (Code "23E") t = restHelper instructionCode "instructionCode" t msCode23E
parseRest (Code "26T") t = restHelper transactionTypeCode "transactionTypeCode" t msCode26T
parseRest (Code "32A") t = restHelper vDateCurSetl "vDateCurSetl" t msCode32A
parseRest (Code "33B") t = restHelper currencyInstructedAmt "currencyInstructedAmt" t msCode33B
parseRest (Code "36 ") t = restHelper exchangeRate "exchangeRate" t msCode36
parseRest (Code "50A") t = restHelper orderingCustomerA "orderingCustomer" t msCode50a
parseRest (Code "50F") t = restHelper orderingCustomerF "orderingCustomer" t msCode50a
parseRest (Code "50K") t = restHelper orderingCustomerK "orderingCustomer" t msCode50a
parseRest (Code "51A") _t = ([],mempty) -- restHelper undefined "undefined" t msCode51A
parseRest (Code "52A") _t = ([],mempty) -- restHelper undefined "undefined" t msCode52A
parseRest (Code "53A") _t = ([],mempty) -- restHelper undefined "undefined" t msCode53a
parseRest (Code "53B") _t = ([],mempty) -- restHelper undefined "undefined" t msCode53a
parseRest (Code "54A") _t = ([],mempty) -- restHelper undefined "undefined" t msCode54A
parseRest (Code "55A") _t = ([],mempty) -- restHelper undefined "undefined" t msCode55A
parseRest (Code "56A") _t = ([],mempty) -- restHelper undefined "undefined" t msCode56A
parseRest (Code "57A") _t = ([],mempty) -- restHelper undefined "undefined" t msCode57A
parseRest (Code "59 ") t = restHelper beneficiaryCustomer "beneficiaryCustomer" t msCode59a
parseRest (Code "59a") t = restHelper beneficiaryCustomer "beneficiaryCustomer" t msCode59a
parseRest (Code "70 ") _t = ([],mempty) -- restHelper undefined "undefined" t msCode70
parseRest (Code "71A") t = restHelper detailsOfCharges "detailsOfCharges" t msCode71A
parseRest (Code "71F") _t = ([],mempty) -- restHelper undefined "undefined" t msCode71F
parseRest (Code "71G") _t = ([],mempty) -- restHelper undefined "undefined" t msCode71G
parseRest (Code "72 ") _t = ([],mempty) -- restHelper undefined "undefined" t msCode72
parseRest (Code "77B") _t = ([],mempty) -- restHelper undefined "undefined" t msCode77B
parseRest (Code x) t = (["Unexepected Code: '" ++ show x ++ "' With Body: " ++ show t], mempty)
|
haroldcarr/juno
|
z-no-longer-used/src/Hop/Schwifty/Swift/M105/Parser.hs
|
bsd-3-clause
| 11,433
| 0
| 19
| 2,460
| 3,812
| 1,875
| 1,937
| 230
| 3
|
-- #hide
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.UI.GLUT.Constants
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/GLUT/LICENSE)
--
-- Maintainer : sven.panne@aedion.de
-- Stability : stable
-- Portability : portable
--
-- This purely internal module defines all numeric GLUT constants.
--
-----------------------------------------------------------------------------
module Graphics.UI.GLUT.Constants where
import Foreign.C.Types ( CInt, CUInt )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum )
-----------------------------------------------------------------------------
-- * Display mode bit masks
glut_RGB, glut_RGBA, glut_INDEX, glut_SINGLE, glut_DOUBLE, glut_ACCUM,
glut_ALPHA, glut_DEPTH, glut_STENCIL, glut_MULTISAMPLE, glut_STEREO,
glut_LUMINANCE, glut_AUX1, glut_AUX2, glut_AUX3, glut_AUX4 :: CUInt
glut_RGB = 0x0000
glut_RGBA = glut_RGB
glut_INDEX = 0x0001
glut_SINGLE = 0x0000
glut_DOUBLE = 0x0002
glut_ACCUM = 0x0004
glut_ALPHA = 0x0008
glut_DEPTH = 0x0010
glut_STENCIL = 0x0020
glut_MULTISAMPLE = 0x0080
glut_STEREO = 0x0100
glut_LUMINANCE = 0x0200
glut_AUX1 = 0x1000
glut_AUX2 = 0x2000
glut_AUX3 = 0x4000
glut_AUX4 = 0x8000
-----------------------------------------------------------------------------
-- * Mouse buttons
glut_LEFT_BUTTON, glut_MIDDLE_BUTTON, glut_RIGHT_BUTTON, glut_WHEEL_UP,
glut_WHEEL_DOWN :: CInt
glut_LEFT_BUTTON = 0
glut_MIDDLE_BUTTON = 1
glut_RIGHT_BUTTON = 2
glut_WHEEL_UP = 3
glut_WHEEL_DOWN = 4
-----------------------------------------------------------------------------
-- * Mouse button state
glut_DOWN, glut_UP :: CInt
glut_DOWN = 0
glut_UP = 1
-----------------------------------------------------------------------------
-- * Function keys
glut_KEY_F1, glut_KEY_F2, glut_KEY_F3, glut_KEY_F4, glut_KEY_F5, glut_KEY_F6,
glut_KEY_F7, glut_KEY_F8, glut_KEY_F9, glut_KEY_F10, glut_KEY_F11,
glut_KEY_F12 :: CInt
glut_KEY_F1 = 1
glut_KEY_F2 = 2
glut_KEY_F3 = 3
glut_KEY_F4 = 4
glut_KEY_F5 = 5
glut_KEY_F6 = 6
glut_KEY_F7 = 7
glut_KEY_F8 = 8
glut_KEY_F9 = 9
glut_KEY_F10 = 10
glut_KEY_F11 = 11
glut_KEY_F12 = 12
-----------------------------------------------------------------------------
-- * Directional Keys
glut_KEY_LEFT, glut_KEY_UP, glut_KEY_RIGHT, glut_KEY_DOWN, glut_KEY_PAGE_UP,
glut_KEY_PAGE_DOWN, glut_KEY_HOME, glut_KEY_END, glut_KEY_INSERT :: CInt
glut_KEY_LEFT = 100
glut_KEY_UP = 101
glut_KEY_RIGHT = 102
glut_KEY_DOWN = 103
glut_KEY_PAGE_UP = 104
glut_KEY_PAGE_DOWN = 105
glut_KEY_HOME = 106
glut_KEY_END = 107
glut_KEY_INSERT = 108
-----------------------------------------------------------------------------
-- * Entry\/exit state
glut_LEFT, glut_ENTERED :: CInt
glut_LEFT = 0
glut_ENTERED = 1
-----------------------------------------------------------------------------
-- * Menu usage state
glut_MENU_NOT_IN_USE, glut_MENU_IN_USE :: CInt
glut_MENU_NOT_IN_USE = 0
glut_MENU_IN_USE = 1
-----------------------------------------------------------------------------
-- * Visibility state
glut_NOT_VISIBLE, glut_VISIBLE :: CInt
glut_NOT_VISIBLE = 0
glut_VISIBLE = 1
-----------------------------------------------------------------------------
-- * Window status state
glut_HIDDEN, glut_FULLY_RETAINED, glut_PARTIALLY_RETAINED,
glut_FULLY_COVERED :: CInt
glut_HIDDEN = 0
glut_FULLY_RETAINED = 1
glut_PARTIALLY_RETAINED = 2
glut_FULLY_COVERED = 3
-----------------------------------------------------------------------------
-- * Color index component selection values
glut_RED, glut_GREEN, glut_BLUE :: CInt
glut_RED = 0
glut_GREEN = 1
glut_BLUE = 2
-----------------------------------------------------------------------------
-- * Layers in use
glut_NORMAL, glut_OVERLAY :: GLenum
glut_NORMAL = 0
glut_OVERLAY = 1
-----------------------------------------------------------------------------
-- * @glutGet@ parameters
glut_WINDOW_X, glut_WINDOW_Y, glut_WINDOW_WIDTH, glut_WINDOW_HEIGHT,
glut_WINDOW_BUFFER_SIZE, glut_WINDOW_STENCIL_SIZE, glut_WINDOW_DEPTH_SIZE,
glut_WINDOW_RED_SIZE, glut_WINDOW_GREEN_SIZE, glut_WINDOW_BLUE_SIZE,
glut_WINDOW_ALPHA_SIZE, glut_WINDOW_ACCUM_RED_SIZE,
glut_WINDOW_ACCUM_GREEN_SIZE, glut_WINDOW_ACCUM_BLUE_SIZE,
glut_WINDOW_ACCUM_ALPHA_SIZE, glut_WINDOW_DOUBLEBUFFER, glut_WINDOW_RGBA,
glut_WINDOW_PARENT, glut_WINDOW_NUM_CHILDREN, glut_WINDOW_COLORMAP_SIZE,
glut_WINDOW_NUM_SAMPLES, glut_WINDOW_STEREO, glut_WINDOW_CURSOR,
glut_SCREEN_WIDTH, glut_SCREEN_HEIGHT, glut_SCREEN_WIDTH_MM,
glut_SCREEN_HEIGHT_MM, glut_MENU_NUM_ITEMS, glut_DISPLAY_MODE_POSSIBLE,
glut_INIT_WINDOW_X, glut_INIT_WINDOW_Y, glut_INIT_WINDOW_WIDTH,
glut_INIT_WINDOW_HEIGHT, glut_INIT_DISPLAY_MODE, glut_ELAPSED_TIME,
glut_WINDOW_FORMAT_ID, glut_ACTION_ON_WINDOW_CLOSE, glut_WINDOW_BORDER_WIDTH,
glut_WINDOW_HEADER_HEIGHT, glut_VERSION, glut_RENDERING_CONTEXT,
glut_DIRECT_RENDERING :: GLenum
glut_WINDOW_X = 100
glut_WINDOW_Y = 101
glut_WINDOW_WIDTH = 102
glut_WINDOW_HEIGHT = 103
glut_WINDOW_BUFFER_SIZE = 104
glut_WINDOW_STENCIL_SIZE = 105
glut_WINDOW_DEPTH_SIZE = 106
glut_WINDOW_RED_SIZE = 107
glut_WINDOW_GREEN_SIZE = 108
glut_WINDOW_BLUE_SIZE = 109
glut_WINDOW_ALPHA_SIZE = 110
glut_WINDOW_ACCUM_RED_SIZE = 111
glut_WINDOW_ACCUM_GREEN_SIZE = 112
glut_WINDOW_ACCUM_BLUE_SIZE = 113
glut_WINDOW_ACCUM_ALPHA_SIZE = 114
glut_WINDOW_DOUBLEBUFFER = 115
glut_WINDOW_RGBA = 116
glut_WINDOW_PARENT = 117
glut_WINDOW_NUM_CHILDREN = 118
glut_WINDOW_COLORMAP_SIZE = 119
glut_WINDOW_NUM_SAMPLES = 120
glut_WINDOW_STEREO = 121
glut_WINDOW_CURSOR = 122
glut_SCREEN_WIDTH = 200
glut_SCREEN_HEIGHT = 201
glut_SCREEN_WIDTH_MM = 202
glut_SCREEN_HEIGHT_MM = 203
glut_MENU_NUM_ITEMS = 300
glut_DISPLAY_MODE_POSSIBLE = 400
glut_INIT_WINDOW_X = 500
glut_INIT_WINDOW_Y = 501
glut_INIT_WINDOW_WIDTH = 502
glut_INIT_WINDOW_HEIGHT = 503
glut_INIT_DISPLAY_MODE = 504
glut_ELAPSED_TIME = 700
glut_WINDOW_FORMAT_ID = 123
glut_ACTION_ON_WINDOW_CLOSE = 505
glut_WINDOW_BORDER_WIDTH = 506
glut_WINDOW_HEADER_HEIGHT = 507
glut_VERSION = 508
glut_RENDERING_CONTEXT = 509
glut_DIRECT_RENDERING = 510
-----------------------------------------------------------------------------
-- * @glutDeviceGet@ parameters
glut_HAS_KEYBOARD, glut_HAS_MOUSE, glut_HAS_SPACEBALL,
glut_HAS_DIAL_AND_BUTTON_BOX, glut_HAS_TABLET, glut_NUM_MOUSE_BUTTONS,
glut_NUM_SPACEBALL_BUTTONS, glut_NUM_BUTTON_BOX_BUTTONS, glut_NUM_DIALS,
glut_NUM_TABLET_BUTTONS, glut_DEVICE_IGNORE_KEY_REPEAT,
glut_DEVICE_KEY_REPEAT, glut_HAS_JOYSTICK, glut_OWNS_JOYSTICK,
glut_JOYSTICK_BUTTONS, glut_JOYSTICK_AXES, glut_JOYSTICK_POLL_RATE :: GLenum
glut_HAS_KEYBOARD = 600
glut_HAS_MOUSE = 601
glut_HAS_SPACEBALL = 602
glut_HAS_DIAL_AND_BUTTON_BOX = 603
glut_HAS_TABLET = 604
glut_NUM_MOUSE_BUTTONS = 605
glut_NUM_SPACEBALL_BUTTONS = 606
glut_NUM_BUTTON_BOX_BUTTONS = 607
glut_NUM_DIALS = 608
glut_NUM_TABLET_BUTTONS = 609
glut_DEVICE_IGNORE_KEY_REPEAT = 610
glut_DEVICE_KEY_REPEAT = 611
glut_HAS_JOYSTICK = 612
glut_OWNS_JOYSTICK = 613
glut_JOYSTICK_BUTTONS = 614
glut_JOYSTICK_AXES = 615
glut_JOYSTICK_POLL_RATE = 616
-----------------------------------------------------------------------------
-- * @glutLayerGet@ parameters
glut_OVERLAY_POSSIBLE, glut_LAYER_IN_USE, glut_HAS_OVERLAY,
glut_TRANSPARENT_INDEX, glut_NORMAL_DAMAGED, glut_OVERLAY_DAMAGED :: GLenum
glut_OVERLAY_POSSIBLE = 800
glut_LAYER_IN_USE = 801
glut_HAS_OVERLAY = 802
glut_TRANSPARENT_INDEX = 803
glut_NORMAL_DAMAGED = 804
glut_OVERLAY_DAMAGED = 805
-----------------------------------------------------------------------------
-- * @glutVideoResizeGet@ parameters
glut_VIDEO_RESIZE_POSSIBLE, glut_VIDEO_RESIZE_IN_USE,
glut_VIDEO_RESIZE_X_DELTA, glut_VIDEO_RESIZE_Y_DELTA,
glut_VIDEO_RESIZE_WIDTH_DELTA, glut_VIDEO_RESIZE_HEIGHT_DELTA,
glut_VIDEO_RESIZE_X, glut_VIDEO_RESIZE_Y, glut_VIDEO_RESIZE_WIDTH,
glut_VIDEO_RESIZE_HEIGHT :: CInt
glut_VIDEO_RESIZE_POSSIBLE = 900
glut_VIDEO_RESIZE_IN_USE = 901
glut_VIDEO_RESIZE_X_DELTA = 902
glut_VIDEO_RESIZE_Y_DELTA = 903
glut_VIDEO_RESIZE_WIDTH_DELTA = 904
glut_VIDEO_RESIZE_HEIGHT_DELTA = 905
glut_VIDEO_RESIZE_X = 906
glut_VIDEO_RESIZE_Y = 907
glut_VIDEO_RESIZE_WIDTH = 908
glut_VIDEO_RESIZE_HEIGHT = 909
-----------------------------------------------------------------------------
-- * @glutGetModifiers@ return mask
glut_ACTIVE_SHIFT, glut_ACTIVE_CTRL, glut_ACTIVE_ALT :: CInt
glut_ACTIVE_SHIFT = 0x01
glut_ACTIVE_CTRL = 0x02
glut_ACTIVE_ALT = 0x04
-----------------------------------------------------------------------------
-- * @glutSetCursor@ parameters
glut_CURSOR_RIGHT_ARROW, glut_CURSOR_LEFT_ARROW, glut_CURSOR_INFO,
glut_CURSOR_DESTROY, glut_CURSOR_HELP, glut_CURSOR_CYCLE,
glut_CURSOR_SPRAY, glut_CURSOR_WAIT, glut_CURSOR_TEXT,
glut_CURSOR_CROSSHAIR, glut_CURSOR_UP_DOWN, glut_CURSOR_LEFT_RIGHT,
glut_CURSOR_TOP_SIDE, glut_CURSOR_BOTTOM_SIDE, glut_CURSOR_LEFT_SIDE,
glut_CURSOR_RIGHT_SIDE, glut_CURSOR_TOP_LEFT_CORNER,
glut_CURSOR_TOP_RIGHT_CORNER, glut_CURSOR_BOTTOM_RIGHT_CORNER,
glut_CURSOR_BOTTOM_LEFT_CORNER, glut_CURSOR_INHERIT, glut_CURSOR_NONE,
glut_CURSOR_FULL_CROSSHAIR :: CInt
glut_CURSOR_RIGHT_ARROW = 0
glut_CURSOR_LEFT_ARROW = 1
glut_CURSOR_INFO = 2
glut_CURSOR_DESTROY = 3
glut_CURSOR_HELP = 4
glut_CURSOR_CYCLE = 5
glut_CURSOR_SPRAY = 6
glut_CURSOR_WAIT = 7
glut_CURSOR_TEXT = 8
glut_CURSOR_CROSSHAIR = 9
glut_CURSOR_UP_DOWN = 10
glut_CURSOR_LEFT_RIGHT = 11
glut_CURSOR_TOP_SIDE = 12
glut_CURSOR_BOTTOM_SIDE = 13
glut_CURSOR_LEFT_SIDE = 14
glut_CURSOR_RIGHT_SIDE = 15
glut_CURSOR_TOP_LEFT_CORNER = 16
glut_CURSOR_TOP_RIGHT_CORNER = 17
glut_CURSOR_BOTTOM_RIGHT_CORNER = 18
glut_CURSOR_BOTTOM_LEFT_CORNER = 19
glut_CURSOR_INHERIT = 100
glut_CURSOR_NONE = 101
glut_CURSOR_FULL_CROSSHAIR = 102
-----------------------------------------------------------------------------
-- * @glutSetKeyRepeat@ modes
glut_KEY_REPEAT_OFF, glut_KEY_REPEAT_ON, glut_KEY_REPEAT_DEFAULT :: CInt
glut_KEY_REPEAT_OFF = 0
glut_KEY_REPEAT_ON = 1
glut_KEY_REPEAT_DEFAULT = 2
-----------------------------------------------------------------------------
-- * Joystick button masks
glut_JOYSTICK_BUTTON_A, glut_JOYSTICK_BUTTON_B, glut_JOYSTICK_BUTTON_C,
glut_JOYSTICK_BUTTON_D :: CUInt
glut_JOYSTICK_BUTTON_A = 0x01
glut_JOYSTICK_BUTTON_B = 0x02
glut_JOYSTICK_BUTTON_C = 0x04
glut_JOYSTICK_BUTTON_D = 0x08
-----------------------------------------------------------------------------
-- @glutGameModeGet@ parameters
glut_GAME_MODE_ACTIVE, glut_GAME_MODE_POSSIBLE, glut_GAME_MODE_WIDTH,
glut_GAME_MODE_HEIGHT, glut_GAME_MODE_PIXEL_DEPTH,
glut_GAME_MODE_REFRESH_RATE, glut_GAME_MODE_DISPLAY_CHANGED :: GLenum
glut_GAME_MODE_ACTIVE = 0
glut_GAME_MODE_POSSIBLE = 1
glut_GAME_MODE_WIDTH = 2
glut_GAME_MODE_HEIGHT = 3
glut_GAME_MODE_PIXEL_DEPTH = 4
glut_GAME_MODE_REFRESH_RATE = 5
glut_GAME_MODE_DISPLAY_CHANGED = 6
-----------------------------------------------------------------------------
-- Direct/indirect rendering context options (has meaning only in unix/x11),
-- see glut_DIRECT_RENDERING (freeglut extension)
glut_FORCE_INDIRECT_CONTEXT, glut_ALLOW_DIRECT_CONTEXT,
glut_TRY_DIRECT_CONTEXT, glut_FORCE_DIRECT_CONTEXT :: CInt
glut_FORCE_INDIRECT_CONTEXT = 0
glut_ALLOW_DIRECT_CONTEXT = 1
glut_TRY_DIRECT_CONTEXT = 2
glut_FORCE_DIRECT_CONTEXT = 3
-----------------------------------------------------------------------------
-- Behaviour when the user clicks on an "x" to close a window, see
-- glut_ACTION_ON_WINDOW_CLOSE (freeglut extension)
glut_ACTION_EXIT, glut_ACTION_GLUTMAINLOOP_RETURNS,
glut_ACTION_CONTINUE_EXECUTION :: CInt
glut_ACTION_EXIT = 0
glut_ACTION_GLUTMAINLOOP_RETURNS = 1
glut_ACTION_CONTINUE_EXECUTION = 2
-----------------------------------------------------------------------------
-- Create a new rendering context when the user opens a new window? See
-- glut_RENDERING_CONTEXT (freeglut extension)
glut_CREATE_NEW_CONTEXT, glut_USE_CURRENT_CONTEXT :: CInt
glut_CREATE_NEW_CONTEXT = 0
glut_USE_CURRENT_CONTEXT = 1
|
FranklinChen/hugs98-plus-Sep2006
|
packages/GLUT/Graphics/UI/GLUT/Constants.hs
|
bsd-3-clause
| 15,595
| 0
| 5
| 4,742
| 1,448
| 1,025
| 423
| 253
| 1
|
module HeatExplicit where
import qualified Data.Matrix as M
import qualified Data.Vector as V
import Function
import Library
compute :: (Double, Function, Function, Function, Function) -> Either ComputeError Matrix
compute (sup_t, f, u_x_0, u_0_t, u_1_t) = M.fromVector (h_count + 1, tau_count + 1)
<$> V.fromList
<$> sequence [y i n | i <- [0..h_count], n <- [0..tau_count]]
where
h_count :: Int
h_count = truncate $ sqrt $ fromIntegral tau_count / 2.0 / sup_t -- τ ≤ 0.5h²
tau_count = 100
tau = sup_t / fromIntegral tau_count
h = 1.0 / fromIntegral h_count
arg :: Int -> Int -> Vector
arg i n = V.fromList [x i, t n]
x i = h * fromIntegral i
t n = tau * fromIntegral n
y :: Int -> Int -> Either ComputeError Double
y i n
| x i `closeTo` 0 = runFunction u_0_t (arg i n)
| x i `closeTo` 1 = runFunction u_1_t (arg i n)
| t n `closeTo` 0 = runFunction u_x_0 (arg i n)
| otherwise = do
y_i_1n <- y i (n-1)
f_i_1n <- runFunction f $ arg i (n-1)
y_i1_1n <- y (i+1) (n-1)
y_1i_1n <- y (i-1) (n-1)
return $ y_i_1n + tau*(f_i_1n + (y_i1_1n - 2 * y_i_1n + y_1i_1n)/h**2)
|
hrsrashid/nummet
|
lib/HeatExplicit.hs
|
bsd-3-clause
| 1,226
| 0
| 18
| 365
| 544
| 281
| 263
| 29
| 1
|
{-# LANGUAGE CPP #-}
module Main where
import qualified System.IO.Streams.Tests.Attoparsec.ByteString as AttoparsecByteString
import qualified System.IO.Streams.Tests.Attoparsec.Text as AttoparsecText
import qualified System.IO.Streams.Tests.Builder as Builder
import qualified System.IO.Streams.Tests.ByteString as ByteString
import qualified System.IO.Streams.Tests.Combinators as Combinators
import qualified System.IO.Streams.Tests.Concurrent as Concurrent
import qualified System.IO.Streams.Tests.Debug as Debug
import qualified System.IO.Streams.Tests.File as File
import qualified System.IO.Streams.Tests.Handle as Handle
import qualified System.IO.Streams.Tests.Internal as Internal
import qualified System.IO.Streams.Tests.List as List
#ifdef ENABLE_NETWORK
import qualified System.IO.Streams.Tests.Network as Network
#endif
import qualified System.IO.Streams.Tests.Process as Process
import qualified System.IO.Streams.Tests.Text as Text
import qualified System.IO.Streams.Tests.Vector as Vector
#ifdef ENABLE_ZLIB
import qualified System.IO.Streams.Tests.Zlib as Zlib
#endif
import Test.Framework (defaultMain, testGroup)
------------------------------------------------------------------------------
main :: IO ()
main = defaultMain tests
where
tests = [ testGroup "Tests.Attoparsec.ByteString" AttoparsecByteString.tests
, testGroup "Tests.Attoparsec.Text" AttoparsecText.tests
, testGroup "Tests.Builder" Builder.tests
, testGroup "Tests.ByteString" ByteString.tests
, testGroup "Tests.Debug" Debug.tests
, testGroup "Tests.Combinators" Combinators.tests
, testGroup "Tests.Concurrent" Concurrent.tests
, testGroup "Tests.File" File.tests
, testGroup "Tests.Handle" Handle.tests
, testGroup "Tests.Internal" Internal.tests
, testGroup "Tests.List" List.tests
#ifdef ENABLE_NETWORK
, testGroup "Tests.Network" Network.tests
#endif
, testGroup "Tests.Process" Process.tests
, testGroup "Tests.Text" Text.tests
, testGroup "Tests.Vector" Vector.tests
#ifdef ENABLE_ZLIB
, testGroup "Tests.Zlib" Zlib.tests
#endif
]
|
snapframework/io-streams
|
test/TestSuite.hs
|
bsd-3-clause
| 2,476
| 0
| 9
| 630
| 390
| 260
| 130
| 33
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Pivotal.Person ( Person(..) ) where
import GHC.Generics
import Data.Aeson
import Data.Aeson.Types
import Data.Char (toLower)
import qualified Data.Text as T
data Person = Person
{ userName :: T.Text
, userInitials :: T.Text
, userID :: Integer
} deriving (Generic,Show)
instance FromJSON Person
instance ToJSON Person where
toJSON =
genericToJSON
defaultOptions
{ fieldLabelModifier = drop 4 . map toLower
}
|
rob-b/pivotal
|
src/Pivotal/Person.hs
|
bsd-3-clause
| 560
| 0
| 10
| 146
| 134
| 79
| 55
| 19
| 0
|
{-# LANGUAGE NoImplicitPrelude, MagicHash, TypeOperators,
DataKinds, TypeFamilies, FlexibleContexts, MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : Java.IO
-- Copyright : (c) Jyothsna Srinivas 2017
--
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : jyothsnasrinivas17@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Bindings for Java Input/Output utilities
--
-----------------------------------------------------------------------------
module Java.IO where
import GHC.Base
import GHC.Int
import Java.Array
import Java.Primitive
import Java.NIO
import Java.Text
data {-# CLASS "java.io.File[]" #-}
FileArray = FileArray (Object# FileArray)
deriving Class
instance JArray File FileArray
-- Start java.io.Closeable
data {-# CLASS "java.io.Closeable" #-} Closeable = Closeable (Object# Closeable)
deriving Class
foreign import java unsafe "@interface" close :: (a <: Closeable) => Java a ()
-- End java.io.Closeable
-- Start java.io.Flushable
data {-# CLASS "java.io.Flushable" #-} Flushable = Flushable (Object# Flushable)
deriving Class
foreign import java unsafe "@interface" flush :: (a <: Flushable) => Java a ()
-- End java.io.Flushable
-- Start java.io.Readable
data {-# CLASS "java.lang.Readable" #-} Readable = Readable (Object# Readable)
deriving Class
foreign import java unsafe "@interface read" readBuffer :: (a <: Readable) => CharBuffer -> Java a Int
-- End java.lang.Readable
-- Start java.lang.Appendable
data {-# CLASS "java.lang.Appendable" #-} Appendable = Appendable (Object# Appendable)
deriving Class
foreign import java unsafe "@interface append" append :: (a <: Appendable) => JChar -> Java a Appendable
foreign import java unsafe "@interface append"
appendSequence :: (a <: Appendable, b <: CharSequence) => b -> Java a Appendable
foreign import java unsafe "@interface append"
appendSubSequence :: (a <: Appendable, b <: CharSequence) => b -> Int -> Int -> Java a Appendable
-- End java.lang.Appendable
-- Start java.io.Reader
data {-# CLASS "java.io.Reader" #-} Reader = Reader (Object# Reader)
deriving Class
type instance Inherits Reader = '[Object, Closeable, Readable]
foreign import java unsafe mark :: (a <: Reader) => Int -> Java a ()
foreign import java unsafe markSupported :: (a <: Reader) => Java a Bool
foreign import java unsafe "read" readReader :: (a <: Reader) => Java a Int
foreign import java unsafe "read" readArray :: (a <: Reader) => JCharArray -> Java a Int
foreign import java unsafe "read"
readSubArray :: (a <: Reader) => JCharArray -> Int -> Int -> Java a Int
foreign import java unsafe ready :: (a <: Reader) => Java a Bool
foreign import java unsafe reset :: (a <: Reader) => Java a ()
foreign import java unsafe skip :: (a <: Reader) => Int64 -> Java a Int64
-- end java.io.Reader
-- start java.io.Writer
data {-# CLASS "java.io.Writer" #-} Writer = Writer (Object# Writer)
deriving Class
type instance Inherits Writer = '[Object, Closeable, Flushable, Appendable]
foreign import java unsafe "write" writeArray :: (a <: Writer) => JCharArray -> Java a ()
foreign import java unsafe "write"
writeSubArray :: (a <: Writer) => JCharArray -> Int -> Int -> Java a ()
foreign import java unsafe "write" write :: (a <: Writer) => Int -> Java a ()
foreign import java unsafe "write" writeString :: (a <: Writer) => String -> Java a ()
foreign import java unsafe "write"
writeSubString :: (a <: Writer) => String -> Int -> Int -> Java a ()
-- End java.io.Writer
-- Start java.io.InputStream
data {-# CLASS "java.io.InputStream" #-} InputStream = InputStream (Object# InputStream)
deriving Class
type instance Inherits InputStream = '[Object, Closeable]
foreign import java unsafe available :: (a <: InputStream) => Java a Int
foreign import java unsafe "mark" markInputStream :: (a <: InputStream) => Int -> Java a Int
foreign import java unsafe "markSupported"
markSupportedInputStream :: (a <: InputStream) => Java a Bool
foreign import java unsafe "read" readInputStream :: (a <: InputStream) => Java a Int
foreign import java unsafe "read"
readArrayInputStream :: (a <: InputStream) => JByteArray -> Java a Int
foreign import java unsafe "read"
readSubArrayInputStream :: (a <: InputStream) => JByteArray -> Int -> Int -> Java a Int
foreign import java unsafe "reset" resetInputStream :: (a <: InputStream) => Java a ()
foreign import java unsafe "skip" skipInputStream :: (a <: InputStream) => Int64 -> Java a Int64
-- End java.io.InputStream
-- Start java.io.OutputStream
data {-# CLASS "java.io.OutputStream" #-} OutputStream = OutputStream (Object# OutputStream)
deriving Class
type instance Inherits OutputStream = '[Object, Closeable, Flushable]
foreign import java unsafe "write"
writeArrayOutputStream :: (a <: OutputStream) => JByteArray -> Java a ()
foreign import java unsafe "write"
writeSubArrayOutputStream :: (a <: OutputStream) => JByteArray -> Int -> Int -> Java a ()
foreign import java unsafe "write"
writeOutputStream :: (a <: OutputStream) => Int -> Java a ()
-- End java.io.OutputStream
-- Start java.io.BufferedInputStream
data {-# CLASS "java.io.BufferedInputStream" #-} BufferedInputStream = BufferedInputStream (Object# BufferedInputStream)
deriving Class
type instance Inherits BufferedInputStream = '[InputStream, Closeable]
-- End java.io.BufferedInputStream
-- Start java.io.BufferedOutputStream
data {-# CLASS "java.io.BufferedOutputStream" #-} BufferedOutputStream = BufferedOutputStream (Object# BufferedOutputStream)
deriving Class
type instance Inherits BufferedOutputStream = '[OutputStream, Closeable, Flushable]
-- End java.io.BufferedOutputStream
-- Start java.io.BufferedReader
data {-# CLASS "java.io.BufferedReader" #-} BufferedReader = BufferedReader (Object# BufferedReader)
deriving Class
type instance Inherits BufferedReader = '[Reader, Closeable]
-- End java.io.BufferedReader
-- Start java.io.BufferedWriter
data {-# CLASS "java.io.BufferedWriter" #-} BufferedWriter = BufferedWriter (Object# BufferedWriter)
deriving Class
type instance Inherits BufferedWriter = '[Writer, Closeable, Flushable]
foreign import java unsafe newLine :: (a <: BufferedWriter) => Java a ()
-- End java.io.BufferedWriter
-- Start java.io.StringReader
data {-# CLASS "java.io.StringReader" #-} StringReader = StringReader (Object# StringReader)
deriving Class
type instance Inherits StringReader = '[Reader, Closeable]
-- End java.io.StringReader
-- Start java.io.StringWriter
data {-# CLASS "java.io.StringWriter" #-} StringWriter = StringWriter (Object# StringWriter)
deriving Class
type instance Inherits StringWriter = '[Writer, Closeable, Flushable]
-- End java.io.StringWriter
-- Start java.io.CharArrayReader
data {-# CLASS "java.io.CharArrayReader" #-} CharArrayReader = CharArrayReader (Object# CharArrayReader)
deriving Class
type instance Inherits CharArrayReader = '[Reader, Closeable]
-- End java.io.CharArrayReader
-- Start java.io.CharArrayWriter
data {-# CLASS "java.io.CharArrayWriter" #-} CharArrayWriter = CharArrayWriter (Object# CharArrayWriter)
deriving Class
type instance Inherits CharArrayWriter = '[Writer, Closeable, Flushable]
-- End java.io.CharArrayWriter
-- Start java.io.DataInput
data {-# CLASS "java.io.DataInput" #-} DataInput = DataInput (Object# DataInput)
deriving Class
foreign import java unsafe "@interface" readBoolean :: (a <: DataInput) => Java a Bool
foreign import java unsafe "@interface" readByte :: (a <: DataInput) => Java a Byte
foreign import java unsafe "@interface" readChar :: (a <: DataInput) => Java a JChar
foreign import java unsafe "@interface" readDouble :: (a <: DataInput) => Java a Double
foreign import java unsafe "@interface" readFloat :: (a <: DataInput) => Java a Float
foreign import java unsafe "@interface" readFully :: (a <: DataInput) => JByteArray -> Java a ()
foreign import java unsafe "@interface readFully"
readFullySub :: (a <: DataInput) => JByteArray -> Int -> Int -> Java a ()
foreign import java unsafe "@interface" readInt :: (a <: DataInput) => Java a Int
foreign import java unsafe "@interface" readLine :: (a <: DataInput) => Java a String
foreign import java unsafe "@interface" readLong :: (a <: DataInput) => Java a Int64
foreign import java unsafe "@interface" readShort :: (a <: DataInput) => Java a Short
foreign import java unsafe "@interface" readUnsignedByte :: (a <: DataInput) => Java a Int
foreign import java unsafe "@interface" readUnsignedShort :: (a <: DataInput) => Java a Int
foreign import java unsafe "@interface" readUTF :: (a <: DataInput) => Java a String
foreign import java unsafe "@interface" skipBytes :: (a <: DataInput) => Int -> Java a Int
-- End java.io.DataInput
-- Start java.io.DataOutput
data {-# CLASS "java.io.DataOutput" #-} DataOutput = DataOutput (Object# DataOutput)
deriving Class
foreign import java unsafe "@interface write" writeArrayDO :: (a <: DataOutput) => JByteArray -> Java a ()
foreign import java unsafe "@interface write"
writeSubArrayDO :: (a <: DataOutput) => JByteArray -> Int -> Int -> Java a ()
foreign import java unsafe "@interface write" writeDO :: (a <: DataOutput) => Int -> Java a ()
foreign import java unsafe "@interface" writeBoolean :: (a <: DataOutput) => Bool -> Java a ()
foreign import java unsafe "@interface" writeByte :: (a <: DataOutput) => Int -> Java a ()
foreign import java unsafe "@interface" writeBytes :: (a <: DataOutput) => String -> Java a ()
foreign import java unsafe "@interface" writeChar :: (a <: DataOutput) => Int -> Java a ()
foreign import java unsafe "@interface" writeChars :: (a <: DataOutput) => String -> Java a ()
foreign import java unsafe "@interface" writeDouble :: (a <: DataOutput) => Double -> Java a ()
foreign import java unsafe "@interface" writeFloat :: (a <: DataOutput) => Float -> Java a ()
foreign import java unsafe "@interface" writeInt :: (a <: DataOutput) => Int -> Java a ()
foreign import java unsafe "@interface" writeLong :: (a <: DataOutput) => Int64 -> Java a ()
foreign import java unsafe "@interface" writeshort :: (a <: DataOutput) => Short -> Java a ()
foreign import java unsafe "@interface" writeUTF :: (a <: DataOutput) => String -> Java a ()
-- End java.io.DataOutput
-- Start java.io.FilterOutputStream
data {-# CLASS "java.io.FilterOutputStream" #-} FilterOutputStream = FilterOutputStream (Object# FilterOutputStream)
deriving Class
type instance Inherits FilterOutputStream = '[OutputStream, Closeable, Flushable]
-- End java.io.FilterOutputStream
-- Start java.io.PrintWriter
data {-# CLASS "java.io.PrintWriter" #-} PrintWriter = PrintWriter (Object# PrintWriter)
deriving Class
type instance Inherits PrintWriter = '[Writer, Closeable, Flushable, Appendable]
foreign import java unsafe checkError :: Java PrintWriter Bool
foreign import java unsafe clearError :: Java PrintWriter ()
foreign import java unsafe "format" formatLocale :: Locale -> String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe format :: String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe "print" printBool :: Bool -> Java PrintWriter ()
foreign import java unsafe "print" printChar :: Char -> Java PrintWriter ()
foreign import java unsafe "print" printCharArray :: JCharArray -> Java PrintWriter ()
foreign import java unsafe "print" printDouble :: Double -> Java PrintWriter ()
foreign import java unsafe "print" printFloat :: Float -> Java PrintWriter ()
foreign import java unsafe "print" printInt :: Int -> Java PrintWriter ()
foreign import java unsafe "print" printLong :: Int64 -> Java PrintWriter ()
foreign import java unsafe "print" printObject :: Object -> Java PrintWriter ()
foreign import java unsafe "print" printString :: String -> Java PrintWriter ()
foreign import java unsafe "printf"
printfLocale :: Locale -> String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe printf :: String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe println :: Java PrintWriter ()
foreign import java unsafe "println" printlnBool :: Bool -> Java PrintWriter ()
foreign import java unsafe "println" printlnChar :: Char -> Java PrintWriter ()
foreign import java unsafe "println" printlnCharArray :: JCharArray -> Java PrintWriter ()
foreign import java unsafe "println" printlnDouble :: Double -> Java PrintWriter ()
foreign import java unsafe "println" printlnFloat :: Float -> Java PrintWriter ()
foreign import java unsafe "println" printlnInt :: Int -> Java PrintWriter ()
foreign import java unsafe "println" printlnLong :: Int64 -> Java PrintWriter ()
foreign import java unsafe "println" printlnObject :: Object -> Java PrintWriter ()
foreign import java unsafe "println" printlnString :: String -> Java PrintWriter ()
foreign import java unsafe setError :: Java PrintWriter ()
-- End java.io.PrintWriter
-- Start java.io.PrintStream
data {-# CLASS "java.io.PrintStream" #-} PrintStream = PrintStream (Object# PrintStream)
deriving Class
type instance Inherits PrintStream = '[FilterOutputStream, Closeable, Flushable, Appendable]
foreign import java unsafe "checkError" checkErrorPStream :: Java PrintWriter Bool
foreign import java unsafe "clearError" clearErrorPStream :: Java PrintWriter ()
foreign import java unsafe "format" formatLocalePStream :: Locale -> String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe "format" formatPStream :: String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe "print" printBoolPStream :: Bool -> Java PrintWriter ()
foreign import java unsafe "print" printCharPStream :: Char -> Java PrintWriter ()
foreign import java unsafe "print" printCharArrayPStream :: JCharArray -> Java PrintWriter ()
foreign import java unsafe "print" printDoublePStream :: Double -> Java PrintWriter ()
foreign import java unsafe "print" printFloatPStream :: Float -> Java PrintWriter ()
foreign import java unsafe "print" printIntPStream :: Int -> Java PrintWriter ()
foreign import java unsafe "print" printLongPStream :: Int64 -> Java PrintWriter ()
foreign import java unsafe "print" printObjectPStream :: Object -> Java PrintWriter ()
foreign import java unsafe "print" printStringPStream :: String -> Java PrintWriter ()
foreign import java unsafe "printf"
printfLocalePStream :: Locale -> String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe "printf" printfPStream :: String -> JObjectArray -> Java PrintWriter ()
foreign import java unsafe "println" printlnPStream :: Java PrintWriter ()
foreign import java unsafe "println" printlnBoolPStream :: Bool -> Java PrintWriter ()
foreign import java unsafe "println" printlnCharPStream :: Char -> Java PrintWriter ()
foreign import java unsafe "println" printlnCharArrayPStream :: JCharArray -> Java PrintWriter ()
foreign import java unsafe "println" printlnDoublePStream :: Double -> Java PrintWriter ()
foreign import java unsafe "println" printlnFloatPStream :: Float -> Java PrintWriter ()
foreign import java unsafe "println" printlnIntPStream :: Int -> Java PrintWriter ()
foreign import java unsafe "println" printlnLongPStream :: Int64 -> Java PrintWriter ()
foreign import java unsafe "println" printlnObjectPStream :: Object -> Java PrintWriter ()
foreign import java unsafe "println" printlnStringPStream :: String -> Java PrintWriter ()
foreign import java unsafe "setError" setErrorPStream :: Java PrintWriter ()
-- End java.io.PrintStream
-- Start java.io.FilterInputStream
data {-# CLASS "java.io.FilterInputStream" #-}
FilterInputStream = FilterInputStream (Object# FilterInputStream)
deriving Class
type instance Inherits FilterInputStream = '[InputStream, Closeable]
-- End java.io.FilterInputStream
-- Start java.io.File
data {-# CLASS "java.io.File" #-}
File = File (Object# File)
deriving Class
type instance Inherits File = '[Object, (Comparable File)]
foreign import java unsafe canExecute :: Java File Bool
foreign import java unsafe canRead :: Java File Bool
foreign import java unsafe canWrite :: Java File Bool
foreign import java unsafe compareTo :: File -> Java File Int
foreign import java unsafe createNewFile :: Java File Bool
foreign import java unsafe delete :: Java File Bool
foreign import java unsafe deleteOnExit :: Java File ()
foreign import java unsafe exists :: Java File Bool
foreign import java unsafe getAbsoluteFile :: Java File File
foreign import java unsafe getAbsolutePath :: Java File String
foreign import java unsafe getCanonicalFile :: Java File File
foreign import java unsafe getCanonicalPath :: Java File String
foreign import java unsafe getFreeSpace :: Java File Int64
foreign import java unsafe getName :: Java File String
foreign import java unsafe getParent :: Java File String
foreign import java unsafe getParentFile :: Java File File
foreign import java unsafe getPath :: Java File String
foreign import java unsafe getTotalSpace :: Java File Int64
foreign import java unsafe getUsableSpace :: Java File Int64
foreign import java unsafe isAbsolute :: Java File Bool
foreign import java unsafe isDirectory :: Java File Bool
foreign import java unsafe isFile :: Java File Bool
foreign import java unsafe isHidden :: Java File Bool
foreign import java unsafe lastModified :: Java File Int64
foreign import java unsafe length :: Java File Int64
foreign import java unsafe list :: Java File JStringArray
foreign import java unsafe "list" listFilenameFilter :: FilenameFilter -> Java File JStringArray
foreign import java unsafe listFiles :: Java File FileArray
foreign import java unsafe "listFiles" listFilesFileFilter :: FileFilter -> Java File FileArray
foreign import java unsafe "listFiles" listFilesFilenameFilter :: FilenameFilter -> Java File FileArray
foreign import java unsafe mkdir :: Java File Bool
foreign import java unsafe mkdirs :: Java File Bool
foreign import java unsafe renameTo :: File -> Java File Bool
foreign import java unsafe setExecutable :: Bool -> Java File Bool
foreign import java unsafe "setExecutable" setExecutableOwner :: Bool -> Bool -> Java File Bool
foreign import java unsafe setLastModified :: Int64 -> Java File Bool
foreign import java unsafe setReadable :: Bool -> Java File Bool
foreign import java unsafe "setReadable" setReadableOwner :: Bool -> Bool -> Java File Bool
foreign import java unsafe setReadOnly :: Java File Bool
foreign import java unsafe setWritable :: Bool -> Java File Bool
foreign import java unsafe "setWritable" setWritableOwner :: Bool -> Bool -> Java File Bool
foreign import java unsafe toPath :: Java File Path
-- End java.io.File
-- Start java.io.FilenameFilter
data {-# CLASS "java.io.FilenameFilter" #-}
FilenameFilter = FilenameFilter (Object# FilenameFilter)
deriving Class
foreign import java unsafe "@interface"
accept :: (b <: FilenameFilter) => File -> String -> Java b Bool
-- End java.io.FilenameFilter
-- Start java.io.FileFilter
data {-# CLASS "java.io.FileFilter" #-}
FileFilter = FileFilter (Object# FileFilter)
deriving Class
foreign import java unsafe "@interface"
acceptFileFilter :: (b <: FileFilter) => File -> Java b Bool
-- End java.io.FileFilter
|
AlexeyRaga/eta
|
libraries/base/Java/IO.hs
|
bsd-3-clause
| 19,385
| 275
| 9
| 3,066
| 5,340
| 2,813
| 2,527
| -1
| -1
|
module Game where
import Action
import Blaze.ByteString.Builder.ByteString (fromLazyByteString)
import Channel
import Control.Concurrent (threadDelay, writeChan, Chan)
import Control.Monad.State
import Control.Wire
import Core
import Data.Aeson
import qualified Data.Maybe as Maybe
import Map
import qualified Network.Wai.EventSource as Wai.EventSource
import Player
import Prelude hiding ((.), id)
import World
import WorldView
oneSecond :: Int
oneSecond = 1000000
-- Responds to the requests with the current world state.
respond :: World -> [Request Message WorldView] -> IO ()
respond world = mapM_ respond'
where
respond' (Request (identifier, _) sender) = do
let player = Maybe.fromJust $ getPlayer identifier world
let worldView = newWorldView player world
sender `tell` worldView
-- Runs the main game loop.
run :: Channel Message WorldView -> Chan Wai.EventSource.ServerEvent -> IO ()
run messageChannel eventChannel = do
-- Load the tiled map.
tiledMap <- loadMapFile "static/test.tmx"
-- Create a world wire for the tiled map.
let wire = worldWire $ newWorld tiledMap
-- Run the loop.
loop wire $ counterSession 1
where
loop :: WorldWire -> Session IO -> IO ()
loop wire session = do
-- Get the pending messages.
requests <- drain messageChannel
let messages = map Channel.payload requests
-- Step the world wire with any pending messages.
(output, wire') <- stepWire wire 0 messages
case output of
-- TODO: handle the case where the world wire inhibits.
Left x -> putStrLn $ "Inhibited: " ++ show x
Right world -> do
-- Collide moving objects and calculate contacts.
-- TODO
-- Sleep for a second.
threadDelay oneSecond
-- Step the world wire with the tick message (and any contacts).
let playerIds = map playerId $ worldPlayers world
let messages' = zip playerIds $ repeat Tick
(output', wire'', session') <- stepSession wire' session messages'
case output' of
-- TODO: handle the case where the world wire inhibits.
Left x -> putStrLn $ "Inhibited: " ++ show x
Right world -> do
putStrLn $ "Produced: " ++ show world
respond world requests
_ <- liftIO $ writeChan eventChannel (Wai.EventSource.ServerEvent Nothing Nothing [fromLazyByteString $ encode world])
loop wire'' session'
|
nullobject/flatland-haskell
|
src/Game.hs
|
bsd-3-clause
| 2,626
| 0
| 26
| 768
| 594
| 304
| 290
| 48
| 3
|
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Data.Array.Nikola.Util.Random
-- Copyright : (c) The President and Fellows of Harvard College 2009-2010
-- Copyright : (c) Geoffrey Mainland 2012
-- License : BSD-style
--
-- Maintainer : Geoffrey Mainland <mainland@apeiron.net>
-- Stability : experimental
-- Portability : non-portable
module Data.Array.Nikola.Util.Random (
PureMTRandom(..),
randoms,
randomsRange
) where
import Data.Int
import qualified Data.Vector.Fusion.Stream as Stream
import qualified Data.Vector.Fusion.Stream.Monadic as S
import qualified Data.Vector.Fusion.Stream.Size as S
import qualified Data.Vector.Generic as G
import Data.Vector.Fusion.Util
import qualified System.Random.Mersenne.Pure64 as R
import GHC.Float
randoms :: forall v a . (G.Vector v a, PureMTRandom a)
=> Int
-> IO (v a)
randoms n = do
g <- R.newPureMT
return $ G.unstream (randomS g n)
where
randomS :: PureMTRandom a => R.PureMT -> Int -> Stream.Stream a
{-# INLINE [1] randomS #-}
randomS g n =
S.Stream (return . step) (n, g) (S.Exact (delay_inline max n 0))
where
{-# INLINE [0] step #-}
step (i,g) | i <= 0 = S.Done
| otherwise = g `seq` case random g of
(r, g') -> S.Yield r (i-1, g')
randomsRange :: forall v a . (Fractional a, G.Vector v a, PureMTRandom a)
=> Int
-> (a, a)
-> IO (v a)
randomsRange n (lo, hi) = do
g <- R.newPureMT
return $ G.unstream (randomS g n)
where
scale :: Int -> a
scale x = (1.0 - t) * lo + t * hi
where
t :: a
t = fromIntegral (abs x) / fromIntegral (maxBound :: Int)
randomS :: R.PureMT -> Int -> Stream.Stream a
{-# INLINE [1] randomS #-}
randomS g n = S.Stream (return . step) (n, g) (S.Exact (delay_inline max n 0))
where
{-# INLINE [0] step #-}
step (i,g) | i <= 0 = S.Done
| otherwise = g `seq` case random g of
(r, g') -> S.Yield (scale r) (i-1, g')
class PureMTRandom a where
random :: R.PureMT -> (a, R.PureMT)
instance PureMTRandom Int where
random = R.randomInt
instance PureMTRandom Int32 where
random g = let (i, g') = R.randomInt g
in
(fromIntegral i, g')
instance PureMTRandom Double where
random = R.randomDouble
instance PureMTRandom Float where
random g = let (f, g') = R.randomDouble g
in
(double2Float f, g')
|
mainland/nikola
|
src/Data/Array/Nikola/Util/Random.hs
|
bsd-3-clause
| 2,600
| 0
| 16
| 799
| 829
| 455
| 374
| 57
| 1
|
import Data.Maybe
import Text.Html
import Text.StringTemplate
main = renderNewsgroupIndex
renderNewsgroupIndex = do
newsgroupsFile <- readFile "templates/newsgroups.template.html"
headerFile <- readFile "templates/header.template.html"
let newsgroups = newSTMP newsgroupsFile :: StringTemplate String
let header = newSTMP headerFile :: StringTemplate String
let group = groupStringTemplates [("newsgroups", newsgroups),("header", header)]
--setEncoderGroup stringToHtmlString group
putStrLn $ toString $ fromJust $ getStringTemplate "newsgroups" group
|
clockfort/mobile-webnews
|
testTemplating.hs
|
bsd-3-clause
| 563
| 0
| 12
| 66
| 133
| 66
| 67
| 11
| 1
|
{-# LANGUAGE TemplateHaskell, PatternGuards #-}
module HsImport.HsImportSpec
( HsImportSpec(..)
, hsImportSpec
) where
import qualified Language.Haskell.Exts as HS
import qualified HsImport.Args as Args
import HsImport.Args (HsImportArgs)
import HsImport.Parse (parseFile)
import HsImport.SymbolImport (SymbolImport(..), Symbol(..))
import HsImport.ModuleImport
import HsImport.Types
import Data.List (find)
data HsImportSpec = HsImportSpec
{ sourceFile :: FilePath
, parsedSrcFile :: Module
, moduleImport :: ModuleImport
, symbolImport :: Maybe SymbolImport
, saveToFile :: Maybe FilePath
} deriving (Show)
hsImportSpec :: HsImportArgs -> IO (Either ErrorMessage HsImportSpec)
hsImportSpec args
| Just error <- checkArgs args = return $ Left error
| otherwise = do
result <- parseFile $ Args.inputSrcFile args
case result of
Right (ParseResult (HS.ParseOk hsModule) _) -> return $ Right $
HsImportSpec { sourceFile = Args.inputSrcFile args
, parsedSrcFile = hsModule
, moduleImport = module_
, symbolImport = symbolImport
, saveToFile = saveToFile
}
Right (ParseResult (HS.ParseFailed srcLoc error) _) -> return $ Left (show srcLoc ++ error)
Left error -> return $ Left error
where
module_ = ModuleImport { moduleName = Args.moduleName args
, qualified = not . null $ Args.qualifiedName args
, as = find (/= "") [Args.qualifiedName args, Args.as args]
}
constructor = if Args.hiding args then Hiding else Import
symbolImport =
case Args.symbolName args of
"" -> Nothing
name | Args.all args -> Just $ constructor $ AllOf name
| ws@(_:_) <- Args.with args -> Just $ constructor $ SomeOf name ws
| otherwise -> Just $ constructor $ Only name
saveToFile =
case Args.outputSrcFile args of
"" -> Nothing
fp -> Just fp
checkArgs args
| null . Args.inputSrcFile $ args
= Just "Missing source file!"
| null . Args.moduleName $ args
= Just "Missing module name!"
| (not . null $ qualifiedName) && (not . null $ asName)
= Just "Invalid usage of options '--qualifiedname' and '--as' at once!"
| otherwise
= Nothing
where
qualifiedName = Args.qualifiedName args
asName = Args.as args
|
dan-t/hsimport
|
lib/HsImport/HsImportSpec.hs
|
bsd-3-clause
| 2,717
| 0
| 16
| 953
| 706
| 368
| 338
| 58
| 6
|
import System.Plugins.Load
defaultModulePath :: String
defaultModulePath = "build3/DummyModule.o"
defaultFnName :: String
defaultFnName = "resource_dyn"
main :: IO ()
main = loop Nothing
loop :: Maybe Module -> IO ()
loop module' = do
putStrLn $ "module path to execute ("++defaultFnName++"), exit to stop, default: " ++ defaultModulePath
l <- getLine
case l of
"exit" -> return ()
"" -> loadWithPlugins defaultModulePath defaultFnName module'
otherwise -> loadWithPlugins l defaultFnName module'
loadWithPlugins :: FilePath -> String -> Maybe Module -> IO ()
loadWithPlugins modulePath fnName module' = do
case module' of
Nothing -> dynload modulePath [] [] fnName >>= handleLoad
(Just prevModule) -> reload prevModule fnName >>= handleLoad
where
handleLoad loadResult = do
case loadResult of
(LoadFailure msg) -> putStr "error: " >> print msg
(LoadSuccess module' fun) -> do
res <- return (fun (5 :: Int)) :: IO Int
print res
-- unload module'
loop $ Just module'
|
michaxm/dynamic-linking-exploration
|
app/PluginsExploration.hs
|
bsd-3-clause
| 1,050
| 0
| 18
| 231
| 326
| 157
| 169
| 27
| 3
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.Singletons.TH.Deriving.Show
-- Copyright : (C) 2017 Ryan Scott
-- License : BSD-style (see LICENSE)
-- Maintainer : Ryan Scott
-- Stability : experimental
-- Portability : non-portable
--
-- Implements deriving of Show instances
--
----------------------------------------------------------------------------
module Data.Singletons.TH.Deriving.Show (
mkShowInstance
, mkShowSingContext
) where
import Language.Haskell.TH.Syntax hiding (showName)
import Language.Haskell.TH.Desugar
import Data.Singletons.TH.Deriving.Infer
import Data.Singletons.TH.Deriving.Util
import Data.Singletons.TH.Names
import Data.Singletons.TH.Options
import Data.Singletons.TH.Syntax
import Data.Singletons.TH.Util
import Data.Maybe (fromMaybe)
import GHC.Lexeme (startsConSym, startsVarSym)
import GHC.Show (appPrec, appPrec1)
mkShowInstance :: OptionsMonad q => DerivDesc q
mkShowInstance mb_ctxt ty (DataDecl _ _ cons) = do
clauses <- mk_showsPrec cons
constraints <- inferConstraintsDef mb_ctxt (DConT showName) ty cons
return $ InstDecl { id_cxt = constraints
, id_name = showName
, id_arg_tys = [ty]
, id_sigs = mempty
, id_meths = [ (showsPrecName, UFunction clauses) ] }
mk_showsPrec :: OptionsMonad q => [DCon] -> q [DClause]
mk_showsPrec cons = do
p <- newUniqueName "p" -- The precedence argument (not always used)
if null cons
then do v <- newUniqueName "v"
pure [DClause [DWildP, DVarP v] (DCaseE (DVarE v) [])]
else mapM (mk_showsPrec_clause p) cons
mk_showsPrec_clause :: forall q. DsMonad q
=> Name -> DCon
-> q DClause
mk_showsPrec_clause p (DCon _ _ con_name con_fields _) = go con_fields
where
go :: DConFields -> q DClause
go con_fields' = do
case con_fields' of
-- No fields: print just the constructor name, with no parentheses
DNormalC _ [] -> return $
DClause [DWildP, DConP con_name [] []] $
DVarE showStringName `DAppE` dStringE (parenInfixConName con_name "")
-- Infix constructors have special Show treatment.
DNormalC True [_, _] -> do
argL <- newUniqueName "argL"
argR <- newUniqueName "argR"
fi <- fromMaybe defaultFixity <$> reifyFixityWithLocals con_name
let con_prec = case fi of Fixity prec _ -> prec
op_name = nameBase con_name
infixOpE = DAppE (DVarE showStringName) . dStringE $
if isInfixDataCon op_name
then " " ++ op_name ++ " "
-- Make sure to handle infix data constructors
-- like (Int `Foo` Int)
else " `" ++ op_name ++ "` "
return $ DClause [DVarP p, DConP con_name [] [DVarP argL, DVarP argR]] $
(DVarE showParenName `DAppE` (DVarE gtName `DAppE` DVarE p
`DAppE` dIntegerE con_prec))
`DAppE` (DVarE composeName
`DAppE` showsPrecE (con_prec + 1) argL
`DAppE` (DVarE composeName
`DAppE` infixOpE
`DAppE` showsPrecE (con_prec + 1) argR))
DNormalC _ tys -> do
args <- mapM (const $ newUniqueName "arg") tys
let show_args = map (showsPrecE appPrec1) args
composed_args = foldr1 (\v q -> DVarE composeName
`DAppE` v
`DAppE` (DVarE composeName
`DAppE` DVarE showSpaceName
`DAppE` q)) show_args
named_args = DVarE composeName
`DAppE` (DVarE showStringName
`DAppE` dStringE (parenInfixConName con_name " "))
`DAppE` composed_args
return $ DClause [DVarP p, DConP con_name [] $ map DVarP args] $
DVarE showParenName
`DAppE` (DVarE gtName `DAppE` DVarE p `DAppE` dIntegerE appPrec)
`DAppE` named_args
-- We show a record constructor with no fields the same way we'd show a
-- normal constructor with no fields.
DRecC [] -> go (DNormalC False [])
DRecC tys -> do
args <- mapM (const $ newUniqueName "arg") tys
let show_args =
concatMap (\((arg_name, _, _), arg) ->
let arg_nameBase = nameBase arg_name
infix_rec = showParen (isSym arg_nameBase)
(showString arg_nameBase) ""
in [ DVarE showStringName `DAppE` dStringE (infix_rec ++ " = ")
, showsPrecE 0 arg
, DVarE showCommaSpaceName
])
(zip tys args)
brace_comma_args = (DVarE showCharName `DAppE` dCharE '{')
: take (length show_args - 1) show_args
composed_args = foldr (\x y -> DVarE composeName `DAppE` x `DAppE` y)
(DVarE showCharName `DAppE` dCharE '}')
brace_comma_args
named_args = DVarE composeName
`DAppE` (DVarE showStringName
`DAppE` dStringE (parenInfixConName con_name " "))
`DAppE` composed_args
return $ DClause [DVarP p, DConP con_name [] $ map DVarP args] $
DVarE showParenName
`DAppE` (DVarE gtName `DAppE` DVarE p `DAppE` dIntegerE appPrec)
`DAppE` named_args
-- | Parenthesize an infix constructor name if it is being applied as a prefix
-- function (e.g., data Amp a = (:&) a a)
parenInfixConName :: Name -> ShowS
parenInfixConName conName =
let conNameBase = nameBase conName
in showParen (isInfixDataCon conNameBase) $ showString conNameBase
showsPrecE :: Int -> Name -> DExp
showsPrecE prec n = DVarE showsPrecName `DAppE` dIntegerE prec `DAppE` DVarE n
dCharE :: Char -> DExp
dCharE = DLitE . CharL
dStringE :: String -> DExp
dStringE = DLitE . StringL
dIntegerE :: Int -> DExp
dIntegerE = DLitE . IntegerL . fromIntegral
isSym :: String -> Bool
isSym "" = False
isSym (c : _) = startsVarSym c || startsConSym c
-- | Turn a context like @('Show' a, 'Show' b)@ into @('ShowSing' a, 'ShowSing' b)@.
-- This is necessary for standalone-derived 'Show' instances for singleton types.
mkShowSingContext :: DCxt -> DCxt
mkShowSingContext = map show_to_SingShow
where
show_to_SingShow :: DPred -> DPred
show_to_SingShow = modifyConNameDType $ \n ->
if n == showName
then showSingName
else n
|
goldfirere/singletons
|
singletons-th/src/Data/Singletons/TH/Deriving/Show.hs
|
bsd-3-clause
| 7,237
| 0
| 26
| 2,650
| 1,667
| 886
| 781
| -1
| -1
|
module Main (main) where
import System.Environment (getArgs)
import System.Exit
import System.IO
import TypedPerl.Inferance
import TypedPerl.Inferance.TypeContext
import TypedPerl.Parsec
import TypedPerl.Types
die :: String -> IO a
die message = do
hPutStrLn stderr message
exitFailure
main :: IO ()
main = do
path <- getArgs
if null path then die "Specify the file name" else return ()
source <- readFile . head $ path
ast <- either (die . show) return (parsePerl source)
(ty, ctx) <- either (die . show) return (inferTypeAndContext ast)
(putStrLn . showContext . context) ctx
putStrLn "----"
putStrLn (showPerlType ty)
return ()
|
hiratara/TypedPerl
|
src/typedperl.hs
|
bsd-3-clause
| 655
| 0
| 10
| 118
| 243
| 121
| 122
| 23
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module ChanWeb where
import Yesod
import ChanLib
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
/board/#String BoardR GET
|]
instance Yesod App
getHomeR = defaultLayout [whamlet|<a href=@{BoardR "g"}>View Parsed|]
getBoardR :: String -> Handler Html
getBoardR b = defaultLayout $ do
liftIO go >>= \x -> toWidget $ [hamlet|<p>#{x} |]
where go = do g <- getBoard $ "http://a.4cdn.org/" ++ b ++ "/catalog.json"
case g of
(Right board) -> return $ show board
(Left s) -> return s
run :: IO ()
run = warp 3000 App
|
spocot/haskell-chan
|
src/ChanWeb.hs
|
bsd-3-clause
| 785
| 0
| 13
| 220
| 187
| 101
| 86
| 21
| 2
|
{-# 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.IAM.GetRole
-- 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.
-- | Retrieves information about the specified role, including the role's path,
-- GUID, ARN, and the policy granting permission to assume the role. For more
-- information about ARNs, go to <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs ARNs>. For more information about roles, go to <http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html Working with Roles>.
--
-- The returned policy is URL-encoded according to RFC 3986. For more
-- information about RFC 3986, go to <http://www.faqs.org/rfcs/rfc3986.html http://www.faqs.org/rfcs/rfc3986.html>.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html>
module Network.AWS.IAM.GetRole
(
-- * Request
GetRole
-- ** Request constructor
, getRole
-- ** Request lenses
, grRoleName
-- * Response
, GetRoleResponse
-- ** Response constructor
, getRoleResponse
-- ** Response lenses
, grrRole
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
newtype GetRole = GetRole
{ _grRoleName :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'GetRole' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'grRoleName' @::@ 'Text'
--
getRole :: Text -- ^ 'grRoleName'
-> GetRole
getRole p1 = GetRole
{ _grRoleName = p1
}
-- | The name of the role to get information about.
grRoleName :: Lens' GetRole Text
grRoleName = lens _grRoleName (\s a -> s { _grRoleName = a })
newtype GetRoleResponse = GetRoleResponse
{ _grrRole :: Role
} deriving (Eq, Read, Show)
-- | 'GetRoleResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'grrRole' @::@ 'Role'
--
getRoleResponse :: Role -- ^ 'grrRole'
-> GetRoleResponse
getRoleResponse p1 = GetRoleResponse
{ _grrRole = p1
}
-- | Information about the role.
grrRole :: Lens' GetRoleResponse Role
grrRole = lens _grrRole (\s a -> s { _grrRole = a })
instance ToPath GetRole where
toPath = const "/"
instance ToQuery GetRole where
toQuery GetRole{..} = mconcat
[ "RoleName" =? _grRoleName
]
instance ToHeaders GetRole
instance AWSRequest GetRole where
type Sv GetRole = IAM
type Rs GetRole = GetRoleResponse
request = post "GetRole"
response = xmlResponse
instance FromXML GetRoleResponse where
parseXML = withElement "GetRoleResult" $ \x -> GetRoleResponse
<$> x .@ "Role"
|
kim/amazonka
|
amazonka-iam/gen/Network/AWS/IAM/GetRole.hs
|
mpl-2.0
| 3,585
| 0
| 9
| 802
| 426
| 263
| 163
| 54
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.RDS.RestoreDBInstanceToPointInTime
-- Copyright : (c) 2013-2015 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)
--
-- Restores a DB instance to an arbitrary point-in-time. Users can restore
-- to any point in time before the LatestRestorableTime for up to
-- BackupRetentionPeriod days. The target database is created with the most
-- of original configuration, but in a system chosen availability zone with
-- the default security group, the default subnet group, and the default DB
-- parameter group. By default, the new DB instance is created as a
-- single-AZ deployment except when the instance is a SQL Server instance
-- that has an option group that is associated with mirroring; in this
-- case, the instance becomes a mirrored deployment and not a single-AZ
-- deployment.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_RestoreDBInstanceToPointInTime.html AWS API Reference> for RestoreDBInstanceToPointInTime.
module Network.AWS.RDS.RestoreDBInstanceToPointInTime
(
-- * Creating a Request
restoreDBInstanceToPointInTime
, RestoreDBInstanceToPointInTime
-- * Request Lenses
, rditpitDBSecurityGroups
, rditpitUseLatestRestorableTime
, rditpitPubliclyAccessible
, rditpitAutoMinorVersionUpgrade
, rditpitDBSubnetGroupName
, rditpitRestoreTime
, rditpitIOPS
, rditpitDomain
, rditpitEngine
, rditpitTDECredentialPassword
, rditpitDBInstanceClass
, rditpitLicenseModel
, rditpitAvailabilityZone
, rditpitVPCSecurityGroupIds
, rditpitMultiAZ
, rditpitOptionGroupName
, rditpitCopyTagsToSnapshot
, rditpitTDECredentialARN
, rditpitTags
, rditpitPort
, rditpitStorageType
, rditpitDBName
, rditpitSourceDBInstanceIdentifier
, rditpitTargetDBInstanceIdentifier
-- * Destructuring the Response
, restoreDBInstanceToPointInTimeResponse
, RestoreDBInstanceToPointInTimeResponse
-- * Response Lenses
, rditpitrsDBInstance
, rditpitrsResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.RDS.Types
import Network.AWS.RDS.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- |
--
-- /See:/ 'restoreDBInstanceToPointInTime' smart constructor.
data RestoreDBInstanceToPointInTime = RestoreDBInstanceToPointInTime'
{ _rditpitDBSecurityGroups :: !(Maybe [Text])
, _rditpitUseLatestRestorableTime :: !(Maybe Bool)
, _rditpitPubliclyAccessible :: !(Maybe Bool)
, _rditpitAutoMinorVersionUpgrade :: !(Maybe Bool)
, _rditpitDBSubnetGroupName :: !(Maybe Text)
, _rditpitRestoreTime :: !(Maybe ISO8601)
, _rditpitIOPS :: !(Maybe Int)
, _rditpitDomain :: !(Maybe Text)
, _rditpitEngine :: !(Maybe Text)
, _rditpitTDECredentialPassword :: !(Maybe Text)
, _rditpitDBInstanceClass :: !(Maybe Text)
, _rditpitLicenseModel :: !(Maybe Text)
, _rditpitAvailabilityZone :: !(Maybe Text)
, _rditpitVPCSecurityGroupIds :: !(Maybe [Text])
, _rditpitMultiAZ :: !(Maybe Bool)
, _rditpitOptionGroupName :: !(Maybe Text)
, _rditpitCopyTagsToSnapshot :: !(Maybe Bool)
, _rditpitTDECredentialARN :: !(Maybe Text)
, _rditpitTags :: !(Maybe [Tag])
, _rditpitPort :: !(Maybe Int)
, _rditpitStorageType :: !(Maybe Text)
, _rditpitDBName :: !(Maybe Text)
, _rditpitSourceDBInstanceIdentifier :: !Text
, _rditpitTargetDBInstanceIdentifier :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RestoreDBInstanceToPointInTime' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rditpitDBSecurityGroups'
--
-- * 'rditpitUseLatestRestorableTime'
--
-- * 'rditpitPubliclyAccessible'
--
-- * 'rditpitAutoMinorVersionUpgrade'
--
-- * 'rditpitDBSubnetGroupName'
--
-- * 'rditpitRestoreTime'
--
-- * 'rditpitIOPS'
--
-- * 'rditpitDomain'
--
-- * 'rditpitEngine'
--
-- * 'rditpitTDECredentialPassword'
--
-- * 'rditpitDBInstanceClass'
--
-- * 'rditpitLicenseModel'
--
-- * 'rditpitAvailabilityZone'
--
-- * 'rditpitVPCSecurityGroupIds'
--
-- * 'rditpitMultiAZ'
--
-- * 'rditpitOptionGroupName'
--
-- * 'rditpitCopyTagsToSnapshot'
--
-- * 'rditpitTDECredentialARN'
--
-- * 'rditpitTags'
--
-- * 'rditpitPort'
--
-- * 'rditpitStorageType'
--
-- * 'rditpitDBName'
--
-- * 'rditpitSourceDBInstanceIdentifier'
--
-- * 'rditpitTargetDBInstanceIdentifier'
restoreDBInstanceToPointInTime
:: Text -- ^ 'rditpitSourceDBInstanceIdentifier'
-> Text -- ^ 'rditpitTargetDBInstanceIdentifier'
-> RestoreDBInstanceToPointInTime
restoreDBInstanceToPointInTime pSourceDBInstanceIdentifier_ pTargetDBInstanceIdentifier_ =
RestoreDBInstanceToPointInTime'
{ _rditpitDBSecurityGroups = Nothing
, _rditpitUseLatestRestorableTime = Nothing
, _rditpitPubliclyAccessible = Nothing
, _rditpitAutoMinorVersionUpgrade = Nothing
, _rditpitDBSubnetGroupName = Nothing
, _rditpitRestoreTime = Nothing
, _rditpitIOPS = Nothing
, _rditpitDomain = Nothing
, _rditpitEngine = Nothing
, _rditpitTDECredentialPassword = Nothing
, _rditpitDBInstanceClass = Nothing
, _rditpitLicenseModel = Nothing
, _rditpitAvailabilityZone = Nothing
, _rditpitVPCSecurityGroupIds = Nothing
, _rditpitMultiAZ = Nothing
, _rditpitOptionGroupName = Nothing
, _rditpitCopyTagsToSnapshot = Nothing
, _rditpitTDECredentialARN = Nothing
, _rditpitTags = Nothing
, _rditpitPort = Nothing
, _rditpitStorageType = Nothing
, _rditpitDBName = Nothing
, _rditpitSourceDBInstanceIdentifier = pSourceDBInstanceIdentifier_
, _rditpitTargetDBInstanceIdentifier = pTargetDBInstanceIdentifier_
}
-- | A list of DB security groups to associate with this DB instance.
--
-- Default: The default DB security group for the database engine.
rditpitDBSecurityGroups :: Lens' RestoreDBInstanceToPointInTime [Text]
rditpitDBSecurityGroups = lens _rditpitDBSecurityGroups (\ s a -> s{_rditpitDBSecurityGroups = a}) . _Default . _Coerce;
-- | Specifies whether ('true') or not ('false') the DB instance is restored
-- from the latest backup time.
--
-- Default: 'false'
--
-- Constraints: Cannot be specified if RestoreTime parameter is provided.
rditpitUseLatestRestorableTime :: Lens' RestoreDBInstanceToPointInTime (Maybe Bool)
rditpitUseLatestRestorableTime = lens _rditpitUseLatestRestorableTime (\ s a -> s{_rditpitUseLatestRestorableTime = a});
-- | Specifies the accessibility options for the DB instance. A value of true
-- specifies an Internet-facing instance with a publicly resolvable DNS
-- name, which resolves to a public IP address. A value of false specifies
-- an internal instance with a DNS name that resolves to a private IP
-- address.
--
-- Default: The default behavior varies depending on whether a VPC has been
-- requested or not. The following list shows the default behavior in each
-- case.
--
-- - __Default VPC:__true
-- - __VPC:__false
--
-- If no DB subnet group has been specified as part of the request and the
-- PubliclyAccessible value has not been set, the DB instance will be
-- publicly accessible. If a specific DB subnet group has been specified as
-- part of the request and the PubliclyAccessible value has not been set,
-- the DB instance will be private.
rditpitPubliclyAccessible :: Lens' RestoreDBInstanceToPointInTime (Maybe Bool)
rditpitPubliclyAccessible = lens _rditpitPubliclyAccessible (\ s a -> s{_rditpitPubliclyAccessible = a});
-- | Indicates that minor version upgrades will be applied automatically to
-- the DB instance during the maintenance window.
rditpitAutoMinorVersionUpgrade :: Lens' RestoreDBInstanceToPointInTime (Maybe Bool)
rditpitAutoMinorVersionUpgrade = lens _rditpitAutoMinorVersionUpgrade (\ s a -> s{_rditpitAutoMinorVersionUpgrade = a});
-- | The DB subnet group name to use for the new instance.
rditpitDBSubnetGroupName :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitDBSubnetGroupName = lens _rditpitDBSubnetGroupName (\ s a -> s{_rditpitDBSubnetGroupName = a});
-- | The date and time to restore from.
--
-- Valid Values: Value must be a time in Universal Coordinated Time (UTC)
-- format
--
-- Constraints:
--
-- - Must be before the latest restorable time for the DB instance
-- - Cannot be specified if UseLatestRestorableTime parameter is true
--
-- Example: '2009-09-07T23:45:00Z'
rditpitRestoreTime :: Lens' RestoreDBInstanceToPointInTime (Maybe UTCTime)
rditpitRestoreTime = lens _rditpitRestoreTime (\ s a -> s{_rditpitRestoreTime = a}) . mapping _Time;
-- | The amount of Provisioned IOPS (input\/output operations per second) to
-- be initially allocated for the DB instance.
--
-- Constraints: Must be an integer greater than 1000.
--
-- __SQL Server__
--
-- Setting the IOPS value for the SQL Server database engine is not
-- supported.
rditpitIOPS :: Lens' RestoreDBInstanceToPointInTime (Maybe Int)
rditpitIOPS = lens _rditpitIOPS (\ s a -> s{_rditpitIOPS = a});
-- | Specify the Active Directory Domain to restore the instance in.
rditpitDomain :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitDomain = lens _rditpitDomain (\ s a -> s{_rditpitDomain = a});
-- | The database engine to use for the new instance.
--
-- Default: The same as source
--
-- Constraint: Must be compatible with the engine of the source
--
-- Valid Values: 'MySQL' | 'oracle-se1' | 'oracle-se' | 'oracle-ee' |
-- 'sqlserver-ee' | 'sqlserver-se' | 'sqlserver-ex' | 'sqlserver-web' |
-- 'postgres'
rditpitEngine :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitEngine = lens _rditpitEngine (\ s a -> s{_rditpitEngine = a});
-- | The password for the given ARN from the Key Store in order to access the
-- device.
rditpitTDECredentialPassword :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitTDECredentialPassword = lens _rditpitTDECredentialPassword (\ s a -> s{_rditpitTDECredentialPassword = a});
-- | The compute and memory capacity of the Amazon RDS DB instance.
--
-- Valid Values:
-- 'db.t1.micro | db.m1.small | db.m1.medium | db.m1.large | db.m1.xlarge | db.m2.2xlarge | db.m2.4xlarge | db.m3.medium | db.m3.large | db.m3.xlarge | db.m3.2xlarge | db.r3.large | db.r3.xlarge | db.r3.2xlarge | db.r3.4xlarge | db.r3.8xlarge | db.t2.micro | db.t2.small | db.t2.medium'
--
-- Default: The same DBInstanceClass as the original DB instance.
rditpitDBInstanceClass :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitDBInstanceClass = lens _rditpitDBInstanceClass (\ s a -> s{_rditpitDBInstanceClass = a});
-- | License model information for the restored DB instance.
--
-- Default: Same as source.
--
-- Valid values: 'license-included' | 'bring-your-own-license' |
-- 'general-public-license'
rditpitLicenseModel :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitLicenseModel = lens _rditpitLicenseModel (\ s a -> s{_rditpitLicenseModel = a});
-- | The EC2 Availability Zone that the database instance will be created in.
--
-- Default: A random, system-chosen Availability Zone.
--
-- Constraint: You cannot specify the AvailabilityZone parameter if the
-- MultiAZ parameter is set to true.
--
-- Example: 'us-east-1a'
rditpitAvailabilityZone :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitAvailabilityZone = lens _rditpitAvailabilityZone (\ s a -> s{_rditpitAvailabilityZone = a});
-- | A list of EC2 VPC security groups to associate with this DB instance.
--
-- Default: The default EC2 VPC security group for the DB subnet group\'s
-- VPC.
rditpitVPCSecurityGroupIds :: Lens' RestoreDBInstanceToPointInTime [Text]
rditpitVPCSecurityGroupIds = lens _rditpitVPCSecurityGroupIds (\ s a -> s{_rditpitVPCSecurityGroupIds = a}) . _Default . _Coerce;
-- | Specifies if the DB instance is a Multi-AZ deployment.
--
-- Constraint: You cannot specify the AvailabilityZone parameter if the
-- MultiAZ parameter is set to 'true'.
rditpitMultiAZ :: Lens' RestoreDBInstanceToPointInTime (Maybe Bool)
rditpitMultiAZ = lens _rditpitMultiAZ (\ s a -> s{_rditpitMultiAZ = a});
-- | The name of the option group to be used for the restored DB instance.
--
-- Permanent options, such as the TDE option for Oracle Advanced Security
-- TDE, cannot be removed from an option group, and that option group
-- cannot be removed from a DB instance once it is associated with a DB
-- instance
rditpitOptionGroupName :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitOptionGroupName = lens _rditpitOptionGroupName (\ s a -> s{_rditpitOptionGroupName = a});
-- | This property is not currently implemented.
rditpitCopyTagsToSnapshot :: Lens' RestoreDBInstanceToPointInTime (Maybe Bool)
rditpitCopyTagsToSnapshot = lens _rditpitCopyTagsToSnapshot (\ s a -> s{_rditpitCopyTagsToSnapshot = a});
-- | The ARN from the Key Store with which to associate the instance for TDE
-- encryption.
rditpitTDECredentialARN :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitTDECredentialARN = lens _rditpitTDECredentialARN (\ s a -> s{_rditpitTDECredentialARN = a});
-- | Undocumented member.
rditpitTags :: Lens' RestoreDBInstanceToPointInTime [Tag]
rditpitTags = lens _rditpitTags (\ s a -> s{_rditpitTags = a}) . _Default . _Coerce;
-- | The port number on which the database accepts connections.
--
-- Constraints: Value must be '1150-65535'
--
-- Default: The same port as the original DB instance.
rditpitPort :: Lens' RestoreDBInstanceToPointInTime (Maybe Int)
rditpitPort = lens _rditpitPort (\ s a -> s{_rditpitPort = a});
-- | Specifies the storage type to be associated with the DB instance.
--
-- Valid values: 'standard | gp2 | io1'
--
-- If you specify 'io1', you must also include a value for the 'Iops'
-- parameter.
--
-- Default: 'io1' if the 'Iops' parameter is specified; otherwise
-- 'standard'
rditpitStorageType :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitStorageType = lens _rditpitStorageType (\ s a -> s{_rditpitStorageType = a});
-- | The database name for the restored DB instance.
--
-- This parameter is not used for the MySQL engine.
rditpitDBName :: Lens' RestoreDBInstanceToPointInTime (Maybe Text)
rditpitDBName = lens _rditpitDBName (\ s a -> s{_rditpitDBName = a});
-- | The identifier of the source DB instance from which to restore.
--
-- Constraints:
--
-- - Must be the identifier of an existing database instance
-- - Must contain from 1 to 63 alphanumeric characters or hyphens
-- - First character must be a letter
-- - Cannot end with a hyphen or contain two consecutive hyphens
rditpitSourceDBInstanceIdentifier :: Lens' RestoreDBInstanceToPointInTime Text
rditpitSourceDBInstanceIdentifier = lens _rditpitSourceDBInstanceIdentifier (\ s a -> s{_rditpitSourceDBInstanceIdentifier = a});
-- | The name of the new database instance to be created.
--
-- Constraints:
--
-- - Must contain from 1 to 63 alphanumeric characters or hyphens
-- - First character must be a letter
-- - Cannot end with a hyphen or contain two consecutive hyphens
rditpitTargetDBInstanceIdentifier :: Lens' RestoreDBInstanceToPointInTime Text
rditpitTargetDBInstanceIdentifier = lens _rditpitTargetDBInstanceIdentifier (\ s a -> s{_rditpitTargetDBInstanceIdentifier = a});
instance AWSRequest RestoreDBInstanceToPointInTime
where
type Rs RestoreDBInstanceToPointInTime =
RestoreDBInstanceToPointInTimeResponse
request = postQuery rDS
response
= receiveXMLWrapper
"RestoreDBInstanceToPointInTimeResult"
(\ s h x ->
RestoreDBInstanceToPointInTimeResponse' <$>
(x .@? "DBInstance") <*> (pure (fromEnum s)))
instance ToHeaders RestoreDBInstanceToPointInTime
where
toHeaders = const mempty
instance ToPath RestoreDBInstanceToPointInTime where
toPath = const "/"
instance ToQuery RestoreDBInstanceToPointInTime where
toQuery RestoreDBInstanceToPointInTime'{..}
= mconcat
["Action" =:
("RestoreDBInstanceToPointInTime" :: ByteString),
"Version" =: ("2014-10-31" :: ByteString),
"DBSecurityGroups" =:
toQuery
(toQueryList "DBSecurityGroupName" <$>
_rditpitDBSecurityGroups),
"UseLatestRestorableTime" =:
_rditpitUseLatestRestorableTime,
"PubliclyAccessible" =: _rditpitPubliclyAccessible,
"AutoMinorVersionUpgrade" =:
_rditpitAutoMinorVersionUpgrade,
"DBSubnetGroupName" =: _rditpitDBSubnetGroupName,
"RestoreTime" =: _rditpitRestoreTime,
"Iops" =: _rditpitIOPS, "Domain" =: _rditpitDomain,
"Engine" =: _rditpitEngine,
"TdeCredentialPassword" =:
_rditpitTDECredentialPassword,
"DBInstanceClass" =: _rditpitDBInstanceClass,
"LicenseModel" =: _rditpitLicenseModel,
"AvailabilityZone" =: _rditpitAvailabilityZone,
"VpcSecurityGroupIds" =:
toQuery
(toQueryList "VpcSecurityGroupId" <$>
_rditpitVPCSecurityGroupIds),
"MultiAZ" =: _rditpitMultiAZ,
"OptionGroupName" =: _rditpitOptionGroupName,
"CopyTagsToSnapshot" =: _rditpitCopyTagsToSnapshot,
"TdeCredentialArn" =: _rditpitTDECredentialARN,
"Tags" =:
toQuery (toQueryList "Tag" <$> _rditpitTags),
"Port" =: _rditpitPort,
"StorageType" =: _rditpitStorageType,
"DBName" =: _rditpitDBName,
"SourceDBInstanceIdentifier" =:
_rditpitSourceDBInstanceIdentifier,
"TargetDBInstanceIdentifier" =:
_rditpitTargetDBInstanceIdentifier]
-- | /See:/ 'restoreDBInstanceToPointInTimeResponse' smart constructor.
data RestoreDBInstanceToPointInTimeResponse = RestoreDBInstanceToPointInTimeResponse'
{ _rditpitrsDBInstance :: !(Maybe DBInstance)
, _rditpitrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RestoreDBInstanceToPointInTimeResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rditpitrsDBInstance'
--
-- * 'rditpitrsResponseStatus'
restoreDBInstanceToPointInTimeResponse
:: Int -- ^ 'rditpitrsResponseStatus'
-> RestoreDBInstanceToPointInTimeResponse
restoreDBInstanceToPointInTimeResponse pResponseStatus_ =
RestoreDBInstanceToPointInTimeResponse'
{ _rditpitrsDBInstance = Nothing
, _rditpitrsResponseStatus = pResponseStatus_
}
-- | Undocumented member.
rditpitrsDBInstance :: Lens' RestoreDBInstanceToPointInTimeResponse (Maybe DBInstance)
rditpitrsDBInstance = lens _rditpitrsDBInstance (\ s a -> s{_rditpitrsDBInstance = a});
-- | The response status code.
rditpitrsResponseStatus :: Lens' RestoreDBInstanceToPointInTimeResponse Int
rditpitrsResponseStatus = lens _rditpitrsResponseStatus (\ s a -> s{_rditpitrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-rds/gen/Network/AWS/RDS/RestoreDBInstanceToPointInTime.hs
|
mpl-2.0
| 20,054
| 0
| 13
| 3,889
| 2,504
| 1,516
| 988
| 271
| 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="hr-HR">
<title>Replacer | 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/replacer/src/main/javahelp/org/zaproxy/zap/extension/replacer/resources/help_hr_HR/helpset_hr_HR.hs
|
apache-2.0
| 970
| 80
| 66
| 159
| 413
| 209
| 204
| -1
| -1
|
{-# LANGUAGE TemplateHaskell #-}
module Main where
-- A simple word frequency counter using the task layer's mapreduce.
import Remote
import Control.Monad.Trans
import Control.Monad
import Debug.Trace
type Line = String
type Word = String
mrMapper :: [Line] -> TaskM [(Word, Int)]
mrMapper lines =
return (concatMap (\line -> map (\w -> (w,1)) (words line)) lines)
mrReducer :: (Word,[Int]) -> TaskM (Word,Int)
mrReducer (w,p) =
return (w,sum p)
$( remotable ['mrMapper, 'mrReducer] )
myMapReduce = MapReduce
{
mtMapper = mrMapper__closure,
mtReducer = mrReducer__closure,
mtChunkify = chunkify 5,
mtShuffle = shuffle
}
initialProcess "MASTER" =
do args <- getCfgArgs
case args of
[filename] ->
do file <- liftIO $ readFile filename
ans <- runTask $
do mapReduce myMapReduce (lines file)
say $ show ans
_ -> say "When starting MASTER, please also provide a filename on the command line"
initialProcess "WORKER" = receiveWait []
initialProcess _ = say "You need to start this program as either a MASTER or a WORKER. Set the appropiate value of cfgRole on the command line or in the config file."
main = remoteInit (Just "config") [Main.__remoteCallMetaData] initialProcess
|
jepst/CloudHaskell
|
examples/tests/Test-MapReduce.hs
|
bsd-3-clause
| 1,504
| 0
| 18
| 513
| 354
| 191
| 163
| 32
| 2
|
-----------------------------------------------------------------------------
--
-- Static flags
--
-- Static flags can only be set once, on the command-line. Inside GHC,
-- each static flag corresponds to a top-level value, usually of type Bool.
--
-- (c) The University of Glasgow 2005
--
-----------------------------------------------------------------------------
module StaticFlagParser (parseStaticFlags) where
#include "HsVersions.h"
import qualified StaticFlags as SF
import StaticFlags ( v_opt_C_ready, getWayFlags, tablesNextToCode, WayName(..)
, opt_SimplExcessPrecision )
import CmdLineParser
import Config
import SrcLoc
import Util
import Panic
import Control.Monad
import Data.Char
import Data.IORef
import Data.List
-----------------------------------------------------------------------------
-- Static flags
-- | Parses GHC's static flags from a list of command line arguments.
--
-- These flags are static in the sense that they can be set only once and they
-- are global, meaning that they affect every instance of GHC running;
-- multiple GHC threads will use the same flags.
--
-- This function must be called before any session is started, i.e., before
-- the first call to 'GHC.withGhc'.
--
-- Static flags are more of a hack and are static for more or less historical
-- reasons. In the long run, most static flags should eventually become
-- dynamic flags.
--
-- XXX: can we add an auto-generated list of static flags here?
--
parseStaticFlags :: [Located String] -> IO ([Located String], [Located String])
parseStaticFlags args = do
ready <- readIORef v_opt_C_ready
when ready $ ghcError (ProgramError "Too late for parseStaticFlags: call it before newSession")
(leftover, errs, warns1) <- processArgs static_flags args
when (not (null errs)) $ ghcError $ errorsToGhcException errs
-- deal with the way flags: the way (eg. prof) gives rise to
-- further flags, some of which might be static.
way_flags <- getWayFlags
let way_flags' = map (mkGeneralLocated "in way flags") way_flags
-- if we're unregisterised, add some more flags
let unreg_flags | cGhcUnregisterised == "YES" = unregFlags
| otherwise = []
(more_leftover, errs, warns2) <-
processArgs static_flags (unreg_flags ++ way_flags')
-- see sanity code in staticOpts
writeIORef v_opt_C_ready True
-- TABLES_NEXT_TO_CODE affects the info table layout.
-- Be careful to do this *after* all processArgs,
-- because evaluating tablesNextToCode involves looking at the global
-- static flags. Those pesky global variables...
let cg_flags | tablesNextToCode = map (mkGeneralLocated "in cg_flags")
["-optc-DTABLES_NEXT_TO_CODE"]
| otherwise = []
-- HACK: -fexcess-precision is both a static and a dynamic flag. If
-- the static flag parser has slurped it, we must return it as a
-- leftover too. ToDo: make -fexcess-precision dynamic only.
let excess_prec
| opt_SimplExcessPrecision = map (mkGeneralLocated "in excess_prec")
["-fexcess-precision"]
| otherwise = []
when (not (null errs)) $ ghcError $ errorsToGhcException errs
return (excess_prec ++ cg_flags ++ more_leftover ++ leftover,
warns1 ++ warns2)
static_flags :: [Flag IO]
-- All the static flags should appear in this list. It describes how each
-- static flag should be processed. Two main purposes:
-- (a) if a command-line flag doesn't appear in the list, GHC can complain
-- (b) a command-line flag may remove, or add, other flags; e.g. the "-fno-X" things
--
-- The common (PassFlag addOpt) action puts the static flag into the bunch of
-- things that are searched up by the top-level definitions like
-- opt_foo = lookUp (fsLit "-dfoo")
-- Note that ordering is important in the following list: any flag which
-- is a prefix flag (i.e. HasArg, Prefix, OptPrefix, AnySuffix) will override
-- flags further down the list with the same prefix.
static_flags = [
------- GHCi -------------------------------------------------------
Flag "ignore-dot-ghci" (PassFlag addOpt)
, Flag "read-dot-ghci" (NoArg (removeOpt "-ignore-dot-ghci"))
------- ways --------------------------------------------------------
, Flag "prof" (NoArg (addWay WayProf))
, Flag "eventlog" (NoArg (addWay WayEventLog))
, Flag "parallel" (NoArg (addWay WayPar))
, Flag "gransim" (NoArg (addWay WayGran))
, Flag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead"))
, Flag "debug" (NoArg (addWay WayDebug))
, Flag "ndp" (NoArg (addWay WayNDP))
, Flag "threaded" (NoArg (addWay WayThreaded))
, Flag "ticky" (PassFlag (\f -> do addOpt f; addWay WayDebug))
-- -ticky enables ticky-ticky code generation, and also implies -debug which
-- is required to get the RTS ticky support.
------ Debugging ----------------------------------------------------
, Flag "dppr-debug" (PassFlag addOpt)
, Flag "dppr-cols" (AnySuffix addOpt)
, Flag "dppr-user-length" (AnySuffix addOpt)
, Flag "dppr-case-as-let" (PassFlag addOpt)
, Flag "dsuppress-all" (PassFlag addOpt)
, Flag "dsuppress-uniques" (PassFlag addOpt)
, Flag "dsuppress-coercions" (PassFlag addOpt)
, Flag "dsuppress-module-prefixes" (PassFlag addOpt)
, Flag "dsuppress-type-applications" (PassFlag addOpt)
, Flag "dsuppress-idinfo" (PassFlag addOpt)
, Flag "dsuppress-var-kinds" (PassFlag addOpt)
, Flag "dsuppress-type-signatures" (PassFlag addOpt)
, Flag "dopt-fuel" (AnySuffix addOpt)
, Flag "dtrace-level" (AnySuffix addOpt)
, Flag "dno-debug-output" (PassFlag addOpt)
, Flag "dstub-dead-values" (PassFlag addOpt)
-- rest of the debugging flags are dynamic
----- Linker --------------------------------------------------------
, Flag "static" (PassFlag addOpt)
, Flag "dynamic" (NoArg (removeOpt "-static" >> addWay WayDyn))
-- ignored for compat w/ gcc:
, Flag "rdynamic" (NoArg (return ()))
----- RTS opts ------------------------------------------------------
, Flag "H" (HasArg (\s -> liftEwM (setHeapSize (fromIntegral (decodeSize s)))))
, Flag "Rghc-timing" (NoArg (liftEwM enableTimingStats))
------ Compiler flags -----------------------------------------------
-- -fPIC requires extra checking: only the NCG supports it.
-- See also DynFlags.parseDynamicFlags.
, Flag "fPIC" (PassFlag setPIC)
-- All other "-fno-<blah>" options cancel out "-f<blah>" on the hsc cmdline
, Flag "fno-"
(PrefixPred (\s -> isStaticFlag ("f"++s)) (\s -> removeOpt ("-f"++s)))
-- Pass all remaining "-f<blah>" options to hsc
, Flag "f" (AnySuffixPred isStaticFlag addOpt)
]
setPIC :: String -> StaticP ()
setPIC | cGhcWithNativeCodeGen == "YES" || cGhcUnregisterised == "YES"
= addOpt
| otherwise
= ghcError $ CmdLineError "-fPIC is not supported on this platform"
isStaticFlag :: String -> Bool
isStaticFlag f =
f `elem` [
"fscc-profiling",
"fdicts-strict",
"fspec-inline-join-points",
"firrefutable-tuples",
"fparallel",
"fgransim",
"fno-hi-version-check",
"dno-black-holing",
"fno-state-hack",
"fsimple-list-literals",
"fruntime-types",
"fno-pre-inlining",
"fno-opt-coercion",
"fexcess-precision",
"static",
"fhardwire-lib-paths",
"funregisterised",
"fcpr-off",
"ferror-spans",
"fPIC",
"fhpc"
]
|| any (`isPrefixOf` f) [
"fliberate-case-threshold",
"fmax-worker-args",
"fhistory-size",
"funfolding-creation-threshold",
"funfolding-dict-threshold",
"funfolding-use-threshold",
"funfolding-fun-discount",
"funfolding-keeness-factor"
]
unregFlags :: [Located String]
unregFlags = map (mkGeneralLocated "in unregFlags")
[ "-optc-DNO_REGS"
, "-optc-DUSE_MINIINTERPRETER"
, "-funregisterised" ]
-----------------------------------------------------------------------------
-- convert sizes like "3.5M" into integers
decodeSize :: String -> Integer
decodeSize str
| c == "" = truncate n
| c == "K" || c == "k" = truncate (n * 1000)
| c == "M" || c == "m" = truncate (n * 1000 * 1000)
| c == "G" || c == "g" = truncate (n * 1000 * 1000 * 1000)
| otherwise = ghcError (CmdLineError ("can't decode size: " ++ str))
where (m, c) = span pred str
n = readRational m
pred c = isDigit c || c == '.'
type StaticP = EwM IO
addOpt :: String -> StaticP ()
addOpt = liftEwM . SF.addOpt
addWay :: WayName -> StaticP ()
addWay = liftEwM . SF.addWay
removeOpt :: String -> StaticP ()
removeOpt = liftEwM . SF.removeOpt
-----------------------------------------------------------------------------
-- RTS Hooks
foreign import ccall unsafe "setHeapSize" setHeapSize :: Int -> IO ()
foreign import ccall unsafe "enableTimingStats" enableTimingStats :: IO ()
|
mcmaniac/ghc
|
compiler/main/StaticFlagParser.hs
|
bsd-3-clause
| 9,288
| 0
| 17
| 2,107
| 1,725
| 917
| 808
| 136
| 1
|
module System.Taffybar.Widget.Text.CPUMonitor (textCpuMonitorNew) where
import Control.Monad.IO.Class ( MonadIO )
import Text.Printf ( printf )
import qualified Text.StringTemplate as ST
import System.Taffybar.Information.CPU
import System.Taffybar.Widget.Generic.PollingLabel ( pollingLabelNew )
import qualified GI.Gtk
-- | Creates a simple textual CPU monitor. It updates once every polling
-- period (in seconds).
textCpuMonitorNew :: MonadIO m
=> String -- ^ Format. You can use variables: $total$, $user$, $system$
-> Double -- ^ Polling period (in seconds)
-> m GI.Gtk.Widget
textCpuMonitorNew fmt period = do
label <- pollingLabelNew period callback
GI.Gtk.toWidget label
where
callback = do
(userLoad, systemLoad, totalLoad) <- cpuLoad
let [userLoad', systemLoad', totalLoad'] = map (formatPercent.(*100)) [userLoad, systemLoad, totalLoad]
let template = ST.newSTMP fmt
let template' = ST.setManyAttrib [ ("user", userLoad'),
("system", systemLoad'),
("total", totalLoad') ] template
return $ ST.render template'
formatPercent :: Double -> String
formatPercent = printf "%.2f"
|
teleshoes/taffybar
|
src/System/Taffybar/Widget/Text/CPUMonitor.hs
|
bsd-3-clause
| 1,265
| 1
| 15
| 314
| 284
| 162
| 122
| 24
| 1
|
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module RegAlloc.Linear.FreeRegs (
FR(..),
maxSpillSlots
)
#include "HsVersions.h"
where
import Reg
import RegClass
import Panic
import Platform
-- -----------------------------------------------------------------------------
-- The free register set
-- This needs to be *efficient*
-- Here's an inefficient 'executable specification' of the FreeRegs data type:
--
-- type FreeRegs = [RegNo]
-- noFreeRegs = 0
-- releaseReg n f = if n `elem` f then f else (n : f)
-- initFreeRegs = allocatableRegs
-- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) f
-- allocateReg f r = filter (/= r) f
import qualified RegAlloc.Linear.PPC.FreeRegs as PPC
import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC
import qualified RegAlloc.Linear.X86.FreeRegs as X86
import qualified PPC.Instr
import qualified SPARC.Instr
import qualified X86.Instr
class Show freeRegs => FR freeRegs where
frAllocateReg :: RealReg -> freeRegs -> freeRegs
frGetFreeRegs :: RegClass -> freeRegs -> [RealReg]
frInitFreeRegs :: freeRegs
frReleaseReg :: RealReg -> freeRegs -> freeRegs
instance FR X86.FreeRegs where
frAllocateReg = X86.allocateReg
frGetFreeRegs = X86.getFreeRegs
frInitFreeRegs = X86.initFreeRegs
frReleaseReg = X86.releaseReg
instance FR PPC.FreeRegs where
frAllocateReg = PPC.allocateReg
frGetFreeRegs = PPC.getFreeRegs
frInitFreeRegs = PPC.initFreeRegs
frReleaseReg = PPC.releaseReg
instance FR SPARC.FreeRegs where
frAllocateReg = SPARC.allocateReg
frGetFreeRegs = SPARC.getFreeRegs
frInitFreeRegs = SPARC.initFreeRegs
frReleaseReg = SPARC.releaseReg
maxSpillSlots :: Platform -> Int
maxSpillSlots platform
= case platformArch platform of
ArchX86 -> X86.Instr.maxSpillSlots True -- 32bit
ArchX86_64 -> X86.Instr.maxSpillSlots False -- not 32bit
ArchPPC -> PPC.Instr.maxSpillSlots
ArchSPARC -> SPARC.Instr.maxSpillSlots
ArchARM _ _ -> panic "maxSpillSlots ArchARM"
ArchPPC_64 -> panic "maxSpillSlots ArchPPC_64"
ArchUnknown -> panic "maxSpillSlots ArchUnknown"
|
mcmaniac/ghc
|
compiler/nativeGen/RegAlloc/Linear/FreeRegs.hs
|
bsd-3-clause
| 2,528
| 0
| 9
| 535
| 374
| 221
| 153
| 44
| 7
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- | @since 4.7.0.0
module GHC.Profiling where
import GHC.Base
startProfTimer :: IO ()
startProfTimer = undefined
stopProfTimer :: IO ()
stopProfTimer = undefined
|
alexander-at-github/eta
|
libraries/base/GHC/Profiling.hs
|
bsd-3-clause
| 231
| 0
| 6
| 35
| 44
| 26
| 18
| 8
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Functions for the GHC package database.
module Stack.GhcPkg
(getGlobalDB
,findGhcPkgField
,createDatabase
,unregisterGhcPkgIds
,ghcPkgPathEnvVar
,mkGhcPackagePath)
where
import Stack.Prelude
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as BL
import Data.List
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Path (parent, (</>))
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import Stack.Constants
import Stack.Types.Config (GhcPkgExe (..))
import Stack.Types.GhcPkgId
import Stack.Types.Compiler
import System.FilePath (searchPathSeparator)
import RIO.Process
-- | Get the global package database
getGlobalDB
:: (HasProcessContext env, HasLogFunc env)
=> GhcPkgExe
-> RIO env (Path Abs Dir)
getGlobalDB pkgexe = do
logDebug "Getting global package database location"
-- This seems like a strange way to get the global package database
-- location, but I don't know of a better one
bs <- ghcPkg pkgexe [] ["list", "--global"] >>= either throwIO return
let fp = S8.unpack $ stripTrailingColon $ firstLine bs
liftIO $ resolveDir' fp
where
stripTrailingColon bs
| S8.null bs = bs
| S8.last bs == ':' = S8.init bs
| otherwise = bs
firstLine = S8.takeWhile (\c -> c /= '\r' && c /= '\n')
-- | Run the ghc-pkg executable
ghcPkg
:: (HasProcessContext env, HasLogFunc env)
=> GhcPkgExe
-> [Path Abs Dir]
-> [String]
-> RIO env (Either SomeException S8.ByteString)
ghcPkg pkgexe@(GhcPkgExe pkgPath) pkgDbs args = do
eres <- go
case eres of
Left _ -> do
mapM_ (createDatabase pkgexe) pkgDbs
go
Right _ -> return eres
where
pkg = toFilePath pkgPath
go = tryAny $ BL.toStrict . fst <$> proc pkg args' readProcess_
args' = packageDbFlags pkgDbs ++ args
-- | Create a package database in the given directory, if it doesn't exist.
createDatabase
:: (HasProcessContext env, HasLogFunc env)
=> GhcPkgExe
-> Path Abs Dir
-> RIO env ()
createDatabase (GhcPkgExe pkgPath) db = do
exists <- doesFileExist (db </> relFilePackageCache)
unless exists $ do
-- ghc-pkg requires that the database directory does not exist
-- yet. If the directory exists but the package.cache file
-- does, we're in a corrupted state. Check for that state.
dirExists <- doesDirExist db
args <- if dirExists
then do
logWarn $
"The package database located at " <>
fromString (toFilePath db) <>
" is corrupted (missing its package.cache file)."
logWarn "Proceeding with a recache"
return ["--package-db", toFilePath db, "recache"]
else do
-- Creating the parent doesn't seem necessary, as ghc-pkg
-- seems to be sufficiently smart. But I don't feel like
-- finding out it isn't the hard way
ensureDir (parent db)
return ["init", toFilePath db]
void $ proc (toFilePath pkgPath) args $ \pc ->
readProcess_ pc `onException`
logError ("Unable to create package database at " <> fromString (toFilePath db))
-- | Get the environment variable to use for the package DB paths.
ghcPkgPathEnvVar :: WhichCompiler -> Text
ghcPkgPathEnvVar Ghc = "GHC_PACKAGE_PATH"
-- | Get the necessary ghc-pkg flags for setting up the given package database
packageDbFlags :: [Path Abs Dir] -> [String]
packageDbFlags pkgDbs =
"--no-user-package-db"
: map (\x -> "--package-db=" ++ toFilePath x) pkgDbs
-- | Get the value of a field of the package.
findGhcPkgField
:: (HasProcessContext env, HasLogFunc env)
=> GhcPkgExe
-> [Path Abs Dir] -- ^ package databases
-> String -- ^ package identifier, or GhcPkgId
-> Text
-> RIO env (Maybe Text)
findGhcPkgField pkgexe pkgDbs name field = do
result <-
ghcPkg
pkgexe
pkgDbs
["field", "--simple-output", name, T.unpack field]
return $
case result of
Left{} -> Nothing
Right bs ->
fmap (stripCR . T.decodeUtf8) $ listToMaybe $ S8.lines bs
-- | unregister list of package ghcids, batching available from GHC 8.2.1,
-- see https://github.com/commercialhaskell/stack/issues/2662#issuecomment-460342402
-- using GHC package id where available (from GHC 7.9)
unregisterGhcPkgIds
:: (HasProcessContext env, HasLogFunc env)
=> GhcPkgExe
-> Path Abs Dir -- ^ package database
-> NonEmpty (Either PackageIdentifier GhcPkgId)
-> RIO env ()
unregisterGhcPkgIds pkgexe pkgDb epgids = do
eres <- ghcPkg pkgexe [pkgDb] args
case eres of
Left e -> logWarn $ displayShow e
Right _ -> return ()
where
(idents, gids) = partitionEithers $ toList epgids
args = "unregister" : "--user" : "--force" :
map packageIdentifierString idents ++
if null gids then [] else "--ipid" : map ghcPkgIdString gids
-- | Get the value for GHC_PACKAGE_PATH
mkGhcPackagePath :: Bool -> Path Abs Dir -> Path Abs Dir -> [Path Abs Dir] -> Path Abs Dir -> Text
mkGhcPackagePath locals localdb deps extras globaldb =
T.pack $ intercalate [searchPathSeparator] $ concat
[ [toFilePathNoTrailingSep localdb | locals]
, [toFilePathNoTrailingSep deps]
, [toFilePathNoTrailingSep db | db <- reverse extras]
, [toFilePathNoTrailingSep globaldb]
]
|
juhp/stack
|
src/Stack/GhcPkg.hs
|
bsd-3-clause
| 5,762
| 0
| 18
| 1,528
| 1,334
| 689
| 645
| 125
| 3
|
yes = readFile $ args !! 0
|
bitemyapp/apply-refact
|
tests/examples/Default23.hs
|
bsd-3-clause
| 26
| 0
| 6
| 6
| 14
| 7
| 7
| 1
| 1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Applicative ((<$>))
import Control.Concurrent (MVar, ThreadId, forkIOWithUnmask, killThread, newEmptyMVar, putMVar, takeMVar)
import Control.Exception (SomeException, bracketOnError, evaluate)
import qualified Control.Exception as E
import Data.ByteString.Builder (byteString, toLazyByteString)
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Network.Socket as N
import Snap.Core
import System.Environment (getArgs)
import qualified System.IO.Streams as Streams
------------------------------------------------------------------------------
import Snap.Internal.Http.Server.Session (httpAcceptLoop, snapToServerHandler)
import qualified Snap.Internal.Http.Server.Socket as Sock
import qualified Snap.Internal.Http.Server.Types as Types
------------------------------------------------------------------------------
-- | Returns the thread the server is running in as well as the port it is
-- listening on.
startTestSocketServer :: Int -> Snap a -> IO (ThreadId, MVar ())
startTestSocketServer portNum userHandler =
bracketOnError getSock cleanup forkServer
where
getSock = Sock.bindSocket "127.0.0.1" (fromIntegral portNum)
forkServer sock = do
port <- fromIntegral <$> N.socketPort sock
putStrLn $ "starting on " ++ show (port :: Int)
let scfg = emptyServerConfig
mv <- newEmptyMVar
tid <- forkIOWithUnmask $ \unmask -> do
putStrLn "server start"
(unmask $ httpAcceptLoop (snapToServerHandler userHandler)
scfg
(Sock.httpAcceptFunc sock))
`E.finally` putMVar mv ()
return (tid, mv)
cleanup = N.close
logAccess _ _ _ = return ()
_logError !e = L.putStrLn $ toLazyByteString e
onStart _ = return ()
onParse _ _ = return ()
onUserHandlerFinished _ _ _ = return ()
onDataFinished _ _ _ = return ()
onExceptionHook _ _ = return ()
onEscape _ = return ()
emptyServerConfig = Types.ServerConfig logAccess
_logError
onStart
onParse
onUserHandlerFinished
onDataFinished
onExceptionHook
onEscape
"localhost"
6
False
1
main :: IO ()
main = do
portNum <- (((read . head) <$> getArgs) >>= evaluate)
`E.catch` \(_::SomeException) -> return 3000
(tid, mv) <- startTestSocketServer portNum $ do
modifyResponse $ setContentLength 4 . setResponseBody output
takeMVar mv
killThread tid
where
output os = Streams.write (Just $ fromByteString "pong") os >> return os
|
k-bx/snap-server
|
pong/Main.hs
|
bsd-3-clause
| 3,517
| 0
| 20
| 1,372
| 698
| 378
| 320
| 64
| 1
|
module StoreTest
( tests
)
where
import Test.HUnit
import qualified Data.Map as Map
import Database.Schema.Migrations.Migration
import Database.Schema.Migrations.Store
tests :: [Test]
tests = validateSingleMigrationTests
++ validateMigrationMapTests
type ValidateSingleTestCase = ( MigrationMap
, Migration
, [MapValidationError]
)
type ValidateMigrationMapTestCase = ( MigrationMap
, [MapValidationError]
)
emptyMap :: MigrationMap
emptyMap = Map.fromList []
partialMap :: MigrationMap
partialMap = Map.fromList [ ("one", undefined)
, ("three", undefined)
]
fullMap :: MigrationMap
fullMap = Map.fromList [ ("one", undefined)
, ("two", undefined)
, ("three", undefined)
]
withDeps :: Migration
withDeps = Migration { mTimestamp = undefined
, mId = "with_deps"
, mDesc = Just "with dependencies"
, mApply = ""
, mRevert = Nothing
, mDeps = ["one", "two", "three"]
}
noDeps :: Migration
noDeps = Migration { mTimestamp = undefined
, mId = "no_deps"
, mDesc = Just "no dependencies"
, mApply = ""
, mRevert = Nothing
, mDeps = []
}
validateSingleTestCases :: [ValidateSingleTestCase]
validateSingleTestCases = [ (emptyMap, withDeps, [ DependencyReferenceError (mId withDeps) "one"
, DependencyReferenceError (mId withDeps) "two"
, DependencyReferenceError (mId withDeps) "three"
]
)
, (emptyMap, noDeps, [])
, (partialMap, withDeps, [DependencyReferenceError (mId withDeps) "two"])
, (fullMap, withDeps, [])
, (fullMap, noDeps, [])
]
validateSingleMigrationTests :: [Test]
validateSingleMigrationTests =
map mkValidateSingleTest validateSingleTestCases
where
mkValidateSingleTest (mmap, m, errs) =
errs ~=? validateSingleMigration mmap m
m1 :: Migration
m1 = noDeps { mId = "m1"
, mDeps = [] }
m2 :: Migration
m2 = noDeps { mId = "m2"
, mDeps = ["m1"] }
m3 :: Migration
m3 = noDeps { mId = "m3"
, mDeps = ["nonexistent"] }
m4 :: Migration
m4 = noDeps { mId = "m4"
, mDeps = ["one", "two"] }
map1 :: MigrationMap
map1 = Map.fromList [ ("m1", m1)
, ("m2", m2)
]
map2 :: MigrationMap
map2 = Map.fromList [ ("m3", m3)
]
map3 :: MigrationMap
map3 = Map.fromList [ ("m4", m4)
]
validateMapTestCases :: [ValidateMigrationMapTestCase]
validateMapTestCases = [ (emptyMap, [])
, (map1, [])
, (map2, [DependencyReferenceError (mId m3) "nonexistent"])
, (map3, [ DependencyReferenceError (mId m4) "one"
, DependencyReferenceError (mId m4) "two"])
]
validateMigrationMapTests :: [Test]
validateMigrationMapTests =
map mkValidateMapTest validateMapTestCases
where
mkValidateMapTest (mmap, errs) =
errs ~=? validateMigrationMap mmap
|
anton-dessiatov/dbmigrations
|
test/StoreTest.hs
|
bsd-3-clause
| 3,704
| 0
| 10
| 1,540
| 799
| 481
| 318
| 80
| 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="es-ES">
<title>Server-Sent Events Add-on</title>
<maps>
<homeID>sse.introduction</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>Índice</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Buscar</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/sse/src/main/javahelp/org/zaproxy/zap/extension/sse/resources/help_es_ES/helpset_es_ES.hs
|
apache-2.0
| 985
| 77
| 68
| 157
| 419
| 212
| 207
| -1
| -1
|
module WhereIn2 where
f = (case (x,y,z) of
(1,y,z) -> y + z
(x,y,z) -> z)
where
(x,y,z) = g 42
g x = (1,2,x)
|
kmate/HaRe
|
old/testing/simplifyExpr/WhereIn2.hs
|
bsd-3-clause
| 154
| 0
| 9
| 70
| 96
| 57
| 39
| 6
| 2
|
{-# LANGUAGE CPP, MagicHash, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Integer
-- Copyright : (c) Ian Lynagh 2007-2012
-- License : BSD3
--
-- Maintainer : igloo@earth.li
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- A simple definition of the 'Integer' type.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Integer (
Integer, mkInteger,
smallInteger, wordToInteger, integerToWord, integerToInt,
#if WORD_SIZE_IN_BITS < 64
integerToWord64, word64ToInteger,
integerToInt64, int64ToInteger,
#endif
plusInteger, minusInteger, timesInteger, negateInteger,
eqInteger, neqInteger, absInteger, signumInteger,
leInteger, gtInteger, ltInteger, geInteger, compareInteger,
eqInteger#, neqInteger#,
leInteger#, gtInteger#, ltInteger#, geInteger#,
divInteger, modInteger,
divModInteger, quotRemInteger, quotInteger, remInteger,
encodeFloatInteger, decodeFloatInteger, floatFromInteger,
encodeDoubleInteger, decodeDoubleInteger, doubleFromInteger,
-- gcdInteger, lcmInteger, -- XXX
andInteger, orInteger, xorInteger, complementInteger,
shiftLInteger, shiftRInteger, testBitInteger,
hashInteger,
) where
import GHC.Integer.Type
|
ezyang/ghc
|
libraries/integer-simple/GHC/Integer.hs
|
bsd-3-clause
| 1,384
| 0
| 4
| 213
| 180
| 126
| 54
| 19
| 0
|
module Child where
import Parent
child :: String
child = "child of " ++ parent
|
bennofs/ghc-server
|
tests/without-cabal/Child.hs
|
bsd-3-clause
| 81
| 0
| 5
| 17
| 21
| 13
| 8
| 4
| 1
|
{-# LANGUAGE BangPatterns #-}
-----------------------------------------------------------------------------
--
-- Fast write-buffered Handles
--
-- (c) The University of Glasgow 2005-2006
--
-- This is a simple abstraction over Handles that offers very fast write
-- buffering, but without the thread safety that Handles provide. It's used
-- to save time in Pretty.printDoc.
--
-----------------------------------------------------------------------------
module BufWrite (
BufHandle(..),
newBufHandle,
bPutChar,
bPutStr,
bPutFS,
bPutFZS,
bPutLitString,
bFlush,
) where
import FastString
import FastMutInt
import Control.Monad ( when )
import Data.ByteString (ByteString)
import qualified Data.ByteString.Unsafe as BS
import Data.Char ( ord )
import Foreign
import Foreign.C.String
import System.IO
-- -----------------------------------------------------------------------------
data BufHandle = BufHandle {-#UNPACK#-}!(Ptr Word8)
{-#UNPACK#-}!FastMutInt
Handle
newBufHandle :: Handle -> IO BufHandle
newBufHandle hdl = do
ptr <- mallocBytes buf_size
r <- newFastMutInt
writeFastMutInt r 0
return (BufHandle ptr r hdl)
buf_size :: Int
buf_size = 8192
bPutChar :: BufHandle -> Char -> IO ()
bPutChar b@(BufHandle buf r hdl) !c = do
i <- readFastMutInt r
if (i >= buf_size)
then do hPutBuf hdl buf buf_size
writeFastMutInt r 0
bPutChar b c
else do pokeElemOff buf i (fromIntegral (ord c) :: Word8)
writeFastMutInt r (i+1)
bPutStr :: BufHandle -> String -> IO ()
bPutStr (BufHandle buf r hdl) !str = do
i <- readFastMutInt r
loop str i
where loop "" !i = do writeFastMutInt r i; return ()
loop (c:cs) !i
| i >= buf_size = do
hPutBuf hdl buf buf_size
loop (c:cs) 0
| otherwise = do
pokeElemOff buf i (fromIntegral (ord c))
loop cs (i+1)
bPutFS :: BufHandle -> FastString -> IO ()
bPutFS b fs = bPutBS b $ fastStringToByteString fs
bPutFZS :: BufHandle -> FastZString -> IO ()
bPutFZS b fs = bPutBS b $ fastZStringToByteString fs
bPutBS :: BufHandle -> ByteString -> IO ()
bPutBS b bs = BS.unsafeUseAsCStringLen bs $ bPutCStringLen b
bPutCStringLen :: BufHandle -> CStringLen -> IO ()
bPutCStringLen b@(BufHandle buf r hdl) cstr@(ptr, len) = do
i <- readFastMutInt r
if (i + len) >= buf_size
then do hPutBuf hdl buf i
writeFastMutInt r 0
if (len >= buf_size)
then hPutBuf hdl ptr len
else bPutCStringLen b cstr
else do
copyBytes (buf `plusPtr` i) ptr len
writeFastMutInt r (i + len)
bPutLitString :: BufHandle -> LitString -> Int -> IO ()
bPutLitString b@(BufHandle buf r hdl) a len = a `seq` do
i <- readFastMutInt r
if (i+len) >= buf_size
then do hPutBuf hdl buf i
writeFastMutInt r 0
if (len >= buf_size)
then hPutBuf hdl a len
else bPutLitString b a len
else do
copyBytes (buf `plusPtr` i) a len
writeFastMutInt r (i+len)
bFlush :: BufHandle -> IO ()
bFlush (BufHandle buf r hdl) = do
i <- readFastMutInt r
when (i > 0) $ hPutBuf hdl buf i
free buf
return ()
|
sgillespie/ghc
|
compiler/utils/BufWrite.hs
|
bsd-3-clause
| 3,439
| 0
| 14
| 1,031
| 1,052
| 525
| 527
| 87
| 3
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
module Distribution.Solver.Types.ResolverPackage
( ResolverPackage(..)
, resolverPackageLibDeps
, resolverPackageExeDeps
) where
import Distribution.Solver.Types.InstSolverPackage
import Distribution.Solver.Types.SolverId
import Distribution.Solver.Types.SolverPackage
import qualified Distribution.Solver.Types.ComponentDeps as CD
import Distribution.Compat.Binary (Binary(..))
import Distribution.Compat.Graph (IsNode(..))
import Distribution.Package (Package(..), HasUnitId(..))
import Distribution.Simple.Utils (ordNub)
import GHC.Generics (Generic)
-- | The dependency resolver picks either pre-existing installed packages
-- or it picks source packages along with package configuration.
--
-- This is like the 'InstallPlan.PlanPackage' but with fewer cases.
--
data ResolverPackage loc = PreExisting InstSolverPackage
| Configured (SolverPackage loc)
deriving (Eq, Show, Generic)
instance Binary loc => Binary (ResolverPackage loc)
instance Package (ResolverPackage loc) where
packageId (PreExisting ipkg) = packageId ipkg
packageId (Configured spkg) = packageId spkg
resolverPackageLibDeps :: ResolverPackage loc -> CD.ComponentDeps [SolverId]
resolverPackageLibDeps (PreExisting ipkg) = instSolverPkgLibDeps ipkg
resolverPackageLibDeps (Configured spkg) = solverPkgLibDeps spkg
resolverPackageExeDeps :: ResolverPackage loc -> CD.ComponentDeps [SolverId]
resolverPackageExeDeps (PreExisting ipkg) = instSolverPkgExeDeps ipkg
resolverPackageExeDeps (Configured spkg) = solverPkgExeDeps spkg
instance IsNode (ResolverPackage loc) where
type Key (ResolverPackage loc) = SolverId
nodeKey (PreExisting ipkg) = PreExistingId (packageId ipkg) (installedUnitId ipkg)
nodeKey (Configured spkg) = PlannedId (packageId spkg)
-- Use dependencies for ALL components
nodeNeighbors pkg =
ordNub $ CD.flatDeps (resolverPackageLibDeps pkg) ++
CD.flatDeps (resolverPackageExeDeps pkg)
|
sopvop/cabal
|
cabal-install/Distribution/Solver/Types/ResolverPackage.hs
|
bsd-3-clause
| 2,028
| 0
| 10
| 290
| 467
| 257
| 210
| 35
| 1
|
-- Test selectors cannot be used ambiguously
{-# LANGUAGE DuplicateRecordFields #-}
data R = MkR { x :: Int, y :: Bool }
data S = MkS { x :: Int }
main = do print (x (MkS 42))
print (y (MkR 42 42))
|
ezyang/ghc
|
testsuite/tests/overloadedrecflds/should_fail/overloadedrecfldsfail02.hs
|
bsd-3-clause
| 211
| 0
| 11
| 57
| 82
| 44
| 38
| 5
| 1
|
{-# LANGUAGE Trustworthy #-}
module Main where
import SafeLang17_A -- trusted lib
import SafeLang17_B -- untrusted plugin
main = do
let r = res [(1::Int)]
putStrLn $ "Result: " ++ show r
putStrLn $ "Result: " ++ show function
|
ghc-android/ghc
|
testsuite/tests/safeHaskell/safeLanguage/SafeLang17.hs
|
bsd-3-clause
| 242
| 0
| 12
| 55
| 67
| 36
| 31
| 8
| 1
|
module Main where
import Control.Concurrent
main = do
t <- forkIO (return ())
threadCapability t >>= print
t <- forkOn 0 (return ())
threadCapability t >>= print
t <- forkOn 1 (return ())
threadCapability t >>= print
|
ghc-android/ghc
|
testsuite/tests/concurrent/should_run/conc071.hs
|
bsd-3-clause
| 231
| 0
| 11
| 51
| 102
| 47
| 55
| 9
| 1
|
{-# LANGUAGE DeriveTraversable #-}
module RegExp.AST
( RegF(..), RegExp(..), SetMode(..), RegFullF(..), RegExpFull(..),
empty, one, oneOf, noneOf, anyone, (|||), (>>>), rep, backref,
repExact, repAtLeast, repBetween,
grouping, foldRegExp, foldRegExpFull, simplify,
AcceptsEmpty(..)
) where
data SetMode = InSet | NotInSet
deriving (Read,Show,Eq,Ord)
data RegF e a r
= Empty
| OneOf SetMode [a]
| Rep r
| Alt e r r -- the Bool caches if accept empty
| Seq e r r -- ditto
deriving (Read,Show,Functor,Foldable,Traversable)
-- | This type adds additional support for backreferences to
-- a regular expression
data RegFullF a r
= RegF (RegF () a r)
| Group r
| BackRef Int
deriving (Read,Show,Functor,Foldable,Traversable)
class AcceptsEmpty t where
acceptsEmpty :: t -> Bool
instance AcceptsEmpty Bool where acceptsEmpty = id
instance AcceptsEmpty e => AcceptsEmpty (RegF e a r) where
acceptsEmpty r =
case r of
Empty -> True
OneOf {} -> False
Rep {} -> True
Alt b _ _ -> acceptsEmpty b
Seq b _ _ -> acceptsEmpty b
newtype RegExp a = RE (RegF Bool a (RegExp a))
deriving (Read,Show)
newtype RegExpFull a = REF (RegFullF a (RegExpFull a))
deriving (Read,Show)
instance Functor RegExpFull where
fmap f (REF r) = REF (mapRegFullF f r)
mapRegFullF :: Functor f => (a -> b) -> RegFullF a (f a) -> RegFullF b (f b)
mapRegFullF f r =
case r of
Group a -> Group (fmap f a)
BackRef i -> BackRef i
RegF a -> RegF (mapRegF f a)
instance Functor RegExp where
fmap f (RE r) = RE (mapRegF f r)
mapRegF :: Functor f => (a -> b) -> RegF e a (f a) -> RegF e b (f b)
mapRegF f r =
case r of
Empty -> Empty
OneOf m x -> OneOf m (map f x)
Rep p -> Rep (fmap f p)
Alt b p q -> Alt b (fmap f p) (fmap f q)
Seq b p q -> Seq b (fmap f p) (fmap f q)
foldRegExp :: (RegF Bool a r -> r) -> RegExp a -> r
foldRegExp f (RE x) = f (fmap (foldRegExp f) x)
foldRegExpFull :: (RegFullF a r -> r) -> RegExpFull a -> r
foldRegExpFull f (REF x) = f (fmap (foldRegExpFull f) x)
instance AcceptsEmpty (RegExp a) where
acceptsEmpty (RE e) = acceptsEmpty e
simple :: RegF () a (RegExpFull a) -> RegExpFull a
simple = REF . RegF
empty :: RegExpFull a
empty = simple Empty
one :: a -> RegExpFull a
one a = simple (OneOf InSet [a])
oneOf :: [a] -> RegExpFull a
oneOf xs = simple (OneOf InSet xs)
noneOf :: [a] -> RegExpFull a
noneOf xs = simple (OneOf NotInSet xs)
anyone :: RegExpFull a
anyone = noneOf []
(|||) :: RegExpFull a -> RegExpFull a -> RegExpFull a
r1 ||| r2 = simple (Alt () r1 r2)
(>>>) :: RegExpFull a -> RegExpFull a -> RegExpFull a
r1 >>> r2 = simple (Seq () r1 r2)
rep :: RegExpFull a -> RegExpFull a
rep r = simple (Rep r)
seqs :: [RegExpFull a] -> RegExpFull a
seqs [] = empty
seqs xs = foldr1 (>>>) xs
repExact :: Int -> RegExpFull a -> RegExpFull a
repExact n m = seqs (replicate n m)
repAtLeast :: Int -> RegExpFull a -> RegExpFull a
repAtLeast n m = seqs (replicate n m ++ [rep m])
repBetween :: Int -> Int -> RegExpFull a -> RegExpFull a
repBetween n1 n2 m | n1 == n2 = repExact n1 m
repBetween n1 n2 m = seqs (replicate n1 m ++ [repUpTo (n2-n1) m])
repUpTo :: Int -> RegExpFull a -> RegExpFull a
repUpTo 1 m = empty ||| m
repUpTo n m = empty ||| (m >>> repUpTo (n-1) m)
grouping :: RegExpFull a -> RegExpFull a
grouping r = REF (Group r)
backref :: Int -> RegExpFull a
backref i = REF (BackRef i)
simplify :: RegExpFull a -> Maybe (RegExp a)
simplify = foldRegExpFull $ \r ->
case r of
Group g -> g
BackRef{} -> Nothing
RegF s -> RE . cacheAcceptsEmpty <$> sequence s
cacheAcceptsEmpty :: AcceptsEmpty r => RegF z a r -> RegF Bool a r
cacheAcceptsEmpty r =
case r of
Empty -> Empty
OneOf m x -> OneOf m x
Rep p -> Rep p
Alt _ p q -> Alt (acceptsEmpty p || acceptsEmpty q) p q
Seq _ p q -> Seq (acceptsEmpty p && acceptsEmpty q) p q
|
glguy/5puzzle
|
src/RegExp/AST.hs
|
isc
| 4,047
| 0
| 11
| 1,077
| 1,859
| 938
| 921
| 109
| 5
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Oden.Substitution where
import Oden.Core.Expr
import Oden.Core.ProtocolImplementation
import Oden.Core.Typed
import Oden.Type.Polymorphic as Poly
import qualified Data.Map as Map
import qualified Data.Set as Set
newtype Subst = Subst (Map.Map TVar Type)
deriving (Eq, Ord, Show, Monoid)
-- | The empty substitution
emptySubst :: Subst
emptySubst = mempty
-- | Insert into a substitution
insert :: TVar -> Type -> Subst -> Subst
insert tvar type' (Subst s) = Subst (Map.insert tvar type' s)
-- | Compose substitutions
compose :: Subst -> Subst -> Subst
(Subst s1) `compose` (Subst s2) = Subst $ Map.map (apply (Subst s1)) s2 `Map.union` s1
-- | Union of substitutions
union :: Subst -> Subst -> Subst
(Subst s1) `union` (Subst s2) = Subst (s1 `Map.union` s2)
-- | Create a substitution from a list of vars and types.
fromList :: [(TVar, Type)] -> Subst
fromList = Subst . Map.fromList
-- | Create a singleton substitution.
singleton :: TVar -> Type -> Subst
singleton var type' = Subst $ Map.singleton var type'
class FTV a => Substitutable a where
apply :: Subst -> a -> a
instance Substitutable a => Substitutable [a] where
apply = fmap . apply
instance (Substitutable a, Ord a) => Substitutable (Set.Set a) where
apply = Set.map . apply
instance Substitutable Type where
apply s (TTuple si f s' r) = TTuple si (apply s f) (apply s s') (apply s r)
apply _ (TCon si n) = TCon si n
apply s (TApp si t1 t2) = TApp si (apply s t1) (apply s t2)
apply (Subst s) t@(TVar _ a) = Map.findWithDefault t a s
apply s (TNoArgFn si t) = TNoArgFn si (apply s t)
apply s (TFn si t1 t2) = TFn si (apply s t1) (apply s t2)
apply s (TForeignFn si variadic as r) = TForeignFn si variadic (map (apply s) as) (apply s r)
apply s (TSlice si t) = TSlice si (apply s t)
apply s (TRecord si r) = TRecord si (apply s r)
apply _ (REmpty si) = REmpty si
apply s (RExtension si l t r) = uniqueRow (RExtension si l (apply s t) (apply s r))
apply s (TNamed si n t) = TNamed si n (apply s t)
apply s (TConstrained cs t) = TConstrained (apply s cs) (apply s t)
instance Substitutable ProtocolConstraint where
apply s (ProtocolConstraint si protocolName' type') =
ProtocolConstraint si protocolName' (apply s type')
instance Substitutable Scheme where
apply (Subst s) (Forall si qs cs t) =
Forall si qs (apply s' cs) (apply s' t)
where s' = Subst $ foldr (Map.delete . getBindingVar) s qs
instance FTV TypedMethodReference where
ftv = \case
Unresolved{} -> Set.empty
Resolved _ _ impl -> ftv impl
instance Substitutable TypedMethodReference where
apply s = \case
Unresolved protocol method constraint ->
Unresolved protocol method (apply s constraint)
Resolved protocol method impl ->
Resolved protocol method (apply s impl)
instance FTV TypedMemberAccess where
ftv = \case
RecordFieldAccess expr _ -> ftv expr
PackageMemberAccess _ _ -> Set.empty
instance Substitutable TypedMemberAccess where
apply s = \case
RecordFieldAccess expr name -> RecordFieldAccess (apply s expr) name
PackageMemberAccess pkgAlias name -> PackageMemberAccess pkgAlias name
instance FTV CanonicalExpr where
ftv (sc, expr) = ftv sc `Set.union` ftv expr
instance Substitutable CanonicalExpr where
apply s (sc, expr) = (apply s sc, apply s expr)
instance FTV e => FTV (FieldInitializer e) where
ftv (FieldInitializer _ _ expr) = ftv expr
instance (Substitutable e) => Substitutable (FieldInitializer e) where
apply s (FieldInitializer si label expr) =
FieldInitializer si label (apply s expr)
instance FTV (Expr r Type m) where
ftv = ftv . typeOf
instance (Substitutable r, Substitutable m) => Substitutable (Expr r Type m) where
apply s = \case
Symbol si x t -> Symbol si x (apply s t)
Subscript si es i t -> Subscript si (apply s es) (apply s i) (apply s t)
Subslice si es (Range e1 e2) t -> Subslice si (apply s es) (Range (apply s e1) (apply s e2)) (apply s t)
Subslice si es (RangeTo e) t -> Subslice si (apply s es) (RangeTo (apply s e)) (apply s t)
Subslice si es (RangeFrom e) t -> Subslice si (apply s es) (RangeFrom (apply s e)) (apply s t)
Application si f p t -> Application si (apply s f) (apply s p) (apply s t)
NoArgApplication si f t -> NoArgApplication si (apply s f) (apply s t)
ForeignFnApplication si f p t -> ForeignFnApplication si (apply s f) (apply s p) (apply s t)
Fn si x b t -> Fn si x (apply s b) (apply s t)
NoArgFn si b t -> NoArgFn si (apply s b) (apply s t)
Let si x e b t -> Let si x (apply s e) (apply s b) (apply s t)
Literal si l t -> Literal si l (apply s t)
Tuple si fe se re t -> Tuple si (apply s fe) (apply s se) (apply s re) (apply s t)
If si c tb fb t -> If si (apply s c) (apply s tb) (apply s fb) (apply s t)
Slice si es t -> Slice si (apply s es) (apply s t)
Block si es t -> Block si (apply s es) (apply s t)
RecordInitializer si t fs -> RecordInitializer si (apply s t) (apply s fs)
MemberAccess si access t -> MemberAccess si (apply s access) (apply s t)
MethodReference si ref t -> MethodReference si (apply s ref) (apply s t)
Foreign si f t -> Foreign si f (apply s t)
instance Substitutable ProtocolMethod where
apply s (ProtocolMethod si name scheme) =
ProtocolMethod si name (apply s scheme)
instance Substitutable Protocol where
apply s (Protocol si name var methods) =
Protocol si name (apply s var) (apply s methods)
instance Substitutable (MethodImplementation TypedExpr) where
apply s (MethodImplementation si name method) =
MethodImplementation si name (apply s method)
instance Substitutable (ProtocolImplementation TypedExpr) where
apply s (ProtocolImplementation si name implHead methods) =
ProtocolImplementation si name (apply s implHead) (apply s methods)
|
oden-lang/oden
|
src/Oden/Substitution.hs
|
mit
| 6,479
| 0
| 13
| 1,784
| 2,623
| 1,304
| 1,319
| 115
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Language.PureScript.Publish.ErrorsWarnings
( PackageError(..)
, PackageWarning(..)
, UserError(..)
, InternalError(..)
, OtherError(..)
, RepositoryFieldError(..)
, JSONSource(..)
, printError
, renderError
, printWarnings
, renderWarnings
) where
import Prelude ()
import Prelude.Compat
import Data.Aeson.BetterErrors
import Data.Version
import Data.Maybe
import Data.Monoid
import Data.List (intersperse, intercalate)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Text as T
import Control.Exception (IOException)
import Web.Bower.PackageMeta (BowerError, PackageName, runPackageName)
import qualified Web.Bower.PackageMeta as Bower
import qualified Language.PureScript as P
import qualified Language.PureScript.Docs as D
import Language.PureScript.Publish.BoxesHelpers
-- | An error which meant that it was not possible to retrieve metadata for a
-- package.
data PackageError
= UserError UserError
| InternalError InternalError
| OtherError OtherError
deriving (Show)
data PackageWarning
= NoResolvedVersion PackageName
| UndeclaredDependency PackageName
| UnacceptableVersion (PackageName, String)
deriving (Show)
-- | An error that should be fixed by the user.
data UserError
= BowerJSONNotFound
| BowerExecutableNotFound [String] -- list of executable names tried
| CouldntParseBowerJSON (ParseError BowerError)
| BowerJSONNameMissing
| TagMustBeCheckedOut
| AmbiguousVersions [Version] -- Invariant: should contain at least two elements
| BadRepositoryField RepositoryFieldError
| MissingDependencies (NonEmpty PackageName)
| ParseAndDesugarError D.ParseDesugarError
| DirtyWorkingTree
deriving (Show)
data RepositoryFieldError
= RepositoryFieldMissing
| BadRepositoryType String
| NotOnGithub
deriving (Show)
-- | An error that probably indicates a bug in this module.
data InternalError
= JSONError JSONSource (ParseError BowerError)
deriving (Show)
data JSONSource
= FromFile FilePath
| FromBowerList
deriving (Show)
data OtherError
= ProcessFailed String [String] IOException
| IOExceptionThrown IOException
deriving (Show)
printError :: PackageError -> IO ()
printError = printToStderr . renderError
renderError :: PackageError -> Box
renderError err =
case err of
UserError e ->
vcat
[ para (
"There is a problem with your package, which meant that " ++
"it could not be published."
)
, para "Details:"
, indented (displayUserError e)
]
InternalError e ->
vcat
[ para "Internal error: this is probably a bug. Please report it:"
, indented (para "https://github.com/purescript/purescript/issues/new")
, spacer
, para "Details:"
, successivelyIndented (displayInternalError e)
]
OtherError e ->
vcat
[ para "An error occurred, and your package could not be published."
, para "Details:"
, indented (displayOtherError e)
]
displayUserError :: UserError -> Box
displayUserError e = case e of
BowerJSONNotFound ->
para (
"The bower.json file was not found. Please create one, or run " ++
"`pulp init`."
)
BowerExecutableNotFound names ->
para (concat
[ "The Bower executable was not found (tried: ", format names, "). Please"
, " ensure that bower is installed and on your PATH."
])
where
format = intercalate ", " . map show
CouldntParseBowerJSON err ->
vcat
[ successivelyIndented
[ "The bower.json file could not be parsed as JSON:"
, "aeson reported: " ++ show err
]
, para "Please ensure that your bower.json file is valid JSON."
]
BowerJSONNameMissing ->
vcat
[ successivelyIndented
[ "In bower.json:"
, "the \"name\" key was not found."
]
, para "Please give your package a name first."
]
TagMustBeCheckedOut ->
vcat
[ para (concat
[ "psc-publish requires a tagged version to be checked out in "
, "order to build documentation, and no suitable tag was found. "
, "Please check out a previously tagged version, or tag a new "
, "version."
])
, spacer
, para "Note: tagged versions must be in one of the following forms:"
, indented (para "* v{MAJOR}.{MINOR}.{PATCH} (example: \"v1.6.2\")")
, indented (para "* {MAJOR}.{MINOR}.{PATCH} (example: \"1.6.2\")")
, spacer
, para (concat
[ "If the version you are publishing is not yet tagged, you might want to use"
, "the --dry-run flag instead, which removes this requirement. Run"
, "psc-publish --help for more details."
])
]
AmbiguousVersions vs ->
vcat $
[ para (concat
[ "The currently checked out commit seems to have been tagged with "
, "more than 1 version, and I don't know which one should be used. "
, "Please either delete some of the tags, or create a new commit "
, "to tag the desired verson with."
])
, spacer
, para "Tags for the currently checked out commit:"
] ++ bulletedList showVersion vs
BadRepositoryField err ->
displayRepositoryError err
MissingDependencies pkgs ->
let singular = NonEmpty.length pkgs == 1
pl a b = if singular then b else a
do_ = pl "do" "does"
dependencies = pl "dependencies" "dependency"
them = pl "them" "it"
in vcat $
[ para (concat
[ "The following Bower ", dependencies, " ", do_, " not appear to be "
, "installed:"
])
] ++
bulletedList runPackageName (NonEmpty.toList pkgs)
++
[ spacer
, para (concat
[ "Please install ", them, " first, by running `bower install`."
])
]
ParseAndDesugarError (D.ParseError err) ->
vcat
[ para "Parse error:"
, indented (P.prettyPrintMultipleErrorsBox False err)
]
ParseAndDesugarError (D.SortModulesError err) ->
vcat
[ para "Error in sortModules:"
, indented (P.prettyPrintMultipleErrorsBox False err)
]
ParseAndDesugarError (D.DesugarError err) ->
vcat
[ para "Error while desugaring:"
, indented (P.prettyPrintMultipleErrorsBox False err)
]
DirtyWorkingTree ->
para (
"Your git working tree is dirty. Please commit, discard, or stash " ++
"your changes first."
)
displayRepositoryError :: RepositoryFieldError -> Box
displayRepositoryError err = case err of
RepositoryFieldMissing ->
vcat
[ para (concat
[ "The 'repository' field is not present in your bower.json file. "
, "Without this information, Pursuit would not be able to generate "
, "source links in your package's documentation. Please add one - like "
, "this, for example:"
])
, spacer
, indented (vcat
[ para "\"repository\": {"
, indented (para "\"type\": \"git\",")
, indented (para "\"url\": \"git://github.com/purescript/purescript-prelude.git\"")
, para "}"
]
)
]
BadRepositoryType ty ->
para (concat
[ "In your bower.json file, the repository type is currently listed as "
, "\"" ++ ty ++ "\". Currently, only git repositories are supported. "
, "Please publish your code in a git repository, and then update the "
, "repository type in your bower.json file to \"git\"."
])
NotOnGithub ->
vcat
[ para (concat
[ "The repository url in your bower.json file does not point to a "
, "GitHub repository. Currently, Pursuit does not support packages "
, "which are not hosted on GitHub."
])
, spacer
, para (concat
[ "Please update your bower.json file to point to a GitHub repository. "
, "Alternatively, if you would prefer not to host your package on "
, "GitHub, please open an issue:"
])
, indented (para "https://github.com/purescript/purescript/issues/new")
]
displayInternalError :: InternalError -> [String]
displayInternalError e = case e of
JSONError src r ->
[ "Error in JSON " ++ displayJSONSource src ++ ":"
, T.unpack (Bower.displayError r)
]
displayJSONSource :: JSONSource -> String
displayJSONSource s = case s of
FromFile fp ->
"in file " ++ show fp
FromBowerList ->
"in the output of `bower list --json --offline`"
displayOtherError :: OtherError -> Box
displayOtherError e = case e of
ProcessFailed prog args exc ->
successivelyIndented
[ "While running `" ++ prog ++ " " ++ unwords args ++ "`:"
, show exc
]
IOExceptionThrown exc ->
successivelyIndented
[ "An IO exception occurred:", show exc ]
data CollectedWarnings = CollectedWarnings
{ noResolvedVersions :: [PackageName]
, undeclaredDependencies :: [PackageName]
, unacceptableVersions :: [(PackageName, String)]
}
deriving (Show, Eq, Ord)
instance Monoid CollectedWarnings where
mempty = CollectedWarnings mempty mempty mempty
mappend (CollectedWarnings as bs cs) (CollectedWarnings as' bs' cs') =
CollectedWarnings (as <> as') (bs <> bs') (cs <> cs')
collectWarnings :: [PackageWarning] -> CollectedWarnings
collectWarnings = foldMap singular
where
singular w = case w of
NoResolvedVersion pn -> CollectedWarnings [pn] [] []
UndeclaredDependency pn -> CollectedWarnings [] [pn] []
UnacceptableVersion t -> CollectedWarnings [] [] [t]
renderWarnings :: [PackageWarning] -> Box
renderWarnings warns =
let CollectedWarnings{..} = collectWarnings warns
go toBox warns' = toBox <$> NonEmpty.nonEmpty warns'
mboxes = [ go warnNoResolvedVersions noResolvedVersions
, go warnUndeclaredDependencies undeclaredDependencies
, go warnUnacceptableVersions unacceptableVersions
]
in case catMaybes mboxes of
[] -> nullBox
boxes -> vcat [ para "Warnings:"
, indented (vcat (intersperse spacer boxes))
]
warnNoResolvedVersions :: NonEmpty PackageName -> Box
warnNoResolvedVersions pkgNames =
let singular = NonEmpty.length pkgNames == 1
pl a b = if singular then b else a
packages = pl "packages" "package"
anyOfThese = pl "any of these" "this"
these = pl "these" "this"
in vcat $
[ para (concat
["The following ", packages, " did not appear to have a resolved "
, "version:"])
] ++
bulletedList runPackageName (NonEmpty.toList pkgNames)
++
[ spacer
, para (concat
["Links to types in ", anyOfThese, " ", packages, " will not work. In "
, "order to make links work, edit your bower.json to specify a version"
, " or a version range for ", these, " ", packages, ", and rerun "
, "`bower install`."
])
]
warnUndeclaredDependencies :: NonEmpty PackageName -> Box
warnUndeclaredDependencies pkgNames =
let singular = NonEmpty.length pkgNames == 1
pl a b = if singular then b else a
packages = pl "packages" "package"
are = pl "are" "is"
dependencies = pl "dependencies" "a dependency"
in vcat $
para (concat
[ "The following Bower ", packages, " ", are, " installed, but not "
, "declared as ", dependencies, " in your bower.json file:"
])
: bulletedList runPackageName (NonEmpty.toList pkgNames)
warnUnacceptableVersions :: NonEmpty (PackageName, String) -> Box
warnUnacceptableVersions pkgs =
let singular = NonEmpty.length pkgs == 1
pl a b = if singular then b else a
packages' = pl "packages'" "package's"
packages = pl "packages" "package"
anyOfThese = pl "any of these" "this"
these = pl "these" "this"
versions = pl "versions" "version"
in vcat $
[ para (concat
[ "The following installed Bower ", packages', " ", versions, " could "
, "not be parsed:"
])
] ++
bulletedList showTuple (NonEmpty.toList pkgs)
++
[ spacer
, para (concat
["Links to types in ", anyOfThese, " ", packages, " will not work. In "
, "order to make links work, edit your bower.json to specify an "
, "acceptable version or version range for ", these, " ", packages, ", "
, "and rerun `bower install`."
])
]
where
showTuple (pkgName, tag) = runPackageName pkgName ++ "#" ++ tag
printWarnings :: [PackageWarning] -> IO ()
printWarnings = printToStderr . renderWarnings
|
michaelficarra/purescript
|
src/Language/PureScript/Publish/ErrorsWarnings.hs
|
mit
| 12,828
| 0
| 17
| 3,431
| 2,603
| 1,401
| 1,202
| 311
| 13
|
module Main where
import UI (uiMain)
main :: IO ()
main = uiMain
|
Bogdanp/ff
|
src/Main.hs
|
mit
| 77
| 0
| 6
| 25
| 27
| 16
| 11
| 4
| 1
|
module MonadLine where
import System.Console.ANSI
import PowerlineCharacters
import Data.List.Split
import Data.List
import Control.Monad
data TerminalColor
= TerminalColor { intensity :: ColorIntensity
, color :: Color}
| Normal
data ColorSet = ColorSet
{ foregroundColor :: TerminalColor
, backgroundColor :: TerminalColor
}
data Segment = Segment
{ contents :: IO String
, terminator :: Char
, colorSet :: ColorSet
, bold :: Bool
, transitionfg :: TerminalColor
, displayWhen :: IO Bool
}
-- Helpers for simple segments
alwaysDisplay
:: IO Bool
alwaysDisplay = return True
neverDisplay :: IO Bool
neverDisplay = return False
-- Helpers for bash text printing & colours
sep = " "
beginNonPrintable = putStr "\\["
endNonPrintable = putStr "\\]"
setSGR_escaped args = do
beginNonPrintable
setSGR args
endNonPrintable
resetColors :: IO ()
resetColors = setSGR_escaped [Reset]
-- Setting colours with support for single colours only
setColors
:: ColorSet -> IO ()
setColors (ColorSet Normal Normal) = resetColors
setColors (ColorSet ftcolor Normal) = do
resetColors
setSGR_escaped [SetColor Foreground (intensity ftcolor) (color ftcolor)]
setColors (ColorSet Normal btcolor) = do
resetColors
setSGR_escaped [SetColor Background (intensity btcolor) (color btcolor)]
setColors (ColorSet ftcolor btcolor) = do
setSGR_escaped [SetColor Foreground (intensity ftcolor) (color ftcolor)]
setSGR_escaped [SetColor Background (intensity btcolor) (color btcolor)]
setBold :: Bool -> IO ()
setBold True = setSGR_escaped [SetConsoleIntensity BoldIntensity]
setBold False = setSGR_escaped [SetConsoleIntensity NormalIntensity]
-- Takes a segment and displays it with regard to the colours of the next
-- segment's background for smooth blending
displaySegment
:: Segment -> TerminalColor -> IO ()
displaySegment segment nextbg = do
s <- contents segment
setBold $ bold segment
setColors $ colorSet segment
putStr (sep ++ s ++ sep)
resetColors
setColors $
ColorSet
(case (transitionfg segment) of
Normal -> (backgroundColor . colorSet $ segment)
_ -> transitionfg segment)
nextbg
putStr [terminator segment]
resetColors
-- Actually displays each segment that was previously determined to be
-- displayable
doDisplaySegments
:: [Segment] -> IO ()
doDisplaySegments [segment] = do
displaySegment segment Normal
putStr " "
doDisplaySegments segments = do
displaySegment
(head segments)
(backgroundColor . colorSet . head . tail $segments)
doDisplaySegments (tail segments)
-- Filters out any segments that aren't displayable and calss display
-- function
displaySegments
:: [Segment] -> IO ()
displaySegments segments = filterM displayWhen segments >>= doDisplaySegments
|
schnommus/monadline
|
MonadLine.hs
|
mit
| 2,921
| 0
| 15
| 635
| 745
| 376
| 369
| 78
| 2
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ConstraintKinds #-}
module EndToEndSpec (spec) where
import Prelude hiding (writeFile)
import qualified Prelude
import Helper
import Test.HUnit
import System.Directory (canonicalizePath, createDirectory)
import Data.Maybe
import Data.List
import Data.String.Interpolate
import Data.String.Interpolate.Util
import Data.Version (showVersion)
import qualified Hpack.Render as Hpack
import Hpack.Config (packageConfig, readPackageConfig, DecodeOptions(..), DecodeResult(..), defaultDecodeOptions)
import Hpack.Render.Hints (FormattingHints(..), sniffFormattingHints)
import qualified Paths_hpack as Hpack (version)
writeFile :: FilePath -> String -> IO ()
writeFile file c = touch file >> Prelude.writeFile file c
spec :: Spec
spec = around_ (inTempDirectoryNamed "foo") $ do
describe "hpack" $ do
it "ignores fields that start with an underscore" $ do
[i|
_foo:
bar: 23
library: {}
|] `shouldRenderTo` library [i|
other-modules:
Paths_foo
|]
it "warns on duplicate fields" $ do
[i|
name: foo
name: foo
|] `shouldWarn` [
"package.yaml: Duplicate field $.name"
]
describe "spec-version" $ do
it "accepts spec-version" $ do
[i|
spec-version: 0.29.5
|] `shouldRenderTo` package [i|
|]
it "fails on malformed spec-version" $ do
[i|
spec-version: foo
|] `shouldFailWith` "package.yaml: Error while parsing $.spec-version - invalid value \"foo\""
it "fails on unsupported spec-version" $ do
[i|
spec-version: 25.0
dependencies: foo == bar
|] `shouldFailWith` ("The file package.yaml requires version 25.0 of the Hpack package specification, however this version of hpack only supports versions up to " ++ showVersion Hpack.version ++ ". Upgrading to the latest version of hpack may resolve this issue.")
it "fails on unsupported spec-version from defaults" $ do
let file = joinPath ["defaults", "sol", "hpack-template", "2017", "defaults.yaml"]
writeFile file [i|
spec-version: 25.0
|]
[i|
defaults:
github: sol/hpack-template
path: defaults.yaml
ref: "2017"
library: {}
|] `shouldFailWith` ("The file " ++ file ++ " requires version 25.0 of the Hpack package specification, however this version of hpack only supports versions up to " ++ showVersion Hpack.version ++ ". Upgrading to the latest version of hpack may resolve this issue.")
describe "data-files" $ do
it "accepts data-files" $ do
touch "data/foo/index.html"
touch "data/bar/index.html"
[i|
data-files:
- data/**/*.html
|] `shouldRenderTo` package [i|
data-files:
data/bar/index.html
data/foo/index.html
|]
describe "data-dir" $ do
it "accepts data-dir" $ do
touch "data/foo.html"
touch "data/bar.html"
[i|
data-dir: data
data-files:
- "*.html"
|] `shouldRenderTo` package [i|
data-files:
bar.html
foo.html
data-dir: data
|]
describe "github" $ do
it "accepts owner/repo" $ do
[i|
github: hspec/hspec
|] `shouldRenderTo` package [i|
homepage: https://github.com/hspec/hspec#readme
bug-reports: https://github.com/hspec/hspec/issues
source-repository head
type: git
location: https://github.com/hspec/hspec
|]
it "accepts owner/repo/path" $ do
[i|
github: hspec/hspec/hspec-core
|] `shouldRenderTo` package [i|
homepage: https://github.com/hspec/hspec#readme
bug-reports: https://github.com/hspec/hspec/issues
source-repository head
type: git
location: https://github.com/hspec/hspec
subdir: hspec-core
|]
describe "homepage" $ do
it "accepts homepage URL" $ do
[i|
homepage: https://example.com/
|] `shouldRenderTo` package [i|
homepage: https://example.com/
|]
context "with github" $ do
it "gives homepage URL precedence" $ do
[i|
github: hspec/hspec
homepage: https://example.com/
|] `shouldRenderTo` package [i|
homepage: https://example.com/
bug-reports: https://github.com/hspec/hspec/issues
source-repository head
type: git
location: https://github.com/hspec/hspec
|]
it "omits homepage URL if it is null" $ do
[i|
github: hspec/hspec
homepage: null
|] `shouldRenderTo` package [i|
bug-reports: https://github.com/hspec/hspec/issues
source-repository head
type: git
location: https://github.com/hspec/hspec
|]
describe "bug-reports" $ do
it "accepts bug-reports URL" $ do
[i|
bug-reports: https://example.com/
|] `shouldRenderTo` package [i|
bug-reports: https://example.com/
|]
context "with github" $ do
it "gives bug-reports URL precedence" $ do
[i|
github: hspec/hspec
bug-reports: https://example.com/
|] `shouldRenderTo` package [i|
homepage: https://github.com/hspec/hspec#readme
bug-reports: https://example.com/
source-repository head
type: git
location: https://github.com/hspec/hspec
|]
it "omits bug-reports URL if it is null" $ do
[i|
github: hspec/hspec
bug-reports: null
|] `shouldRenderTo` package [i|
homepage: https://github.com/hspec/hspec#readme
source-repository head
type: git
location: https://github.com/hspec/hspec
|]
describe "defaults" $ do
it "accepts global defaults" $ do
writeFile "defaults/sol/hpack-template/2017/defaults.yaml" [i|
default-extensions:
- RecordWildCards
- DeriveFunctor
|]
[i|
defaults:
github: sol/hpack-template
path: defaults.yaml
ref: "2017"
library: {}
|] `shouldRenderTo` library_ [i|
default-extensions: RecordWildCards DeriveFunctor
|]
it "accepts library defaults" $ do
writeFile "defaults/sol/hpack-template/2017/defaults.yaml" [i|
exposed-modules: Foo
|]
[i|
library:
defaults:
github: sol/hpack-template
path: defaults.yaml
ref: "2017"
|] `shouldRenderTo` library [i|
exposed-modules:
Foo
other-modules:
Paths_foo
|]
it "accepts a list of defaults" $ do
writeFile "defaults/foo/bar/v1/.hpack/defaults.yaml" "default-extensions: RecordWildCards"
writeFile "defaults/foo/bar/v2/.hpack/defaults.yaml" "default-extensions: DeriveFunctor"
[i|
defaults:
- foo/bar@v1
- foo/bar@v2
library: {}
|] `shouldRenderTo` library_ [i|
default-extensions: RecordWildCards DeriveFunctor
|]
it "accepts defaults recursively" $ do
writeFile "defaults/foo/bar/v1/.hpack/defaults.yaml" "defaults: foo/bar@v2"
writeFile "defaults/foo/bar/v2/.hpack/defaults.yaml" "default-extensions: DeriveFunctor"
[i|
defaults: foo/bar@v1
library: {}
|] `shouldRenderTo` library_ [i|
default-extensions: DeriveFunctor
|]
it "fails on cyclic defaults" $ do
let
file1 = "defaults/foo/bar/v1/.hpack/defaults.yaml"
file2 = "defaults/foo/bar/v2/.hpack/defaults.yaml"
writeFile file1 "defaults: foo/bar@v2"
writeFile file2 "defaults: foo/bar@v1"
canonic1 <- canonicalizePath file1
canonic2 <- canonicalizePath file2
[i|
defaults: foo/bar@v1
library: {}
|] `shouldFailWith` [i|cycle in defaults (#{canonic1} -> #{canonic2} -> #{canonic1})|]
it "fails if defaults don't exist" $ do
pending
[i|
defaults:
github: sol/foo
ref: bar
library: {}
|] `shouldFailWith` "Invalid value for \"defaults\"! File https://raw.githubusercontent.com/sol/foo/bar/.hpack/defaults.yaml does not exist!"
it "fails on parse error" $ do
let file = joinPath ["defaults", "sol", "hpack-template", "2017", "defaults.yaml"]
writeFile file "[]"
[i|
defaults:
github: sol/hpack-template
path: defaults.yaml
ref: "2017"
library: {}
|] `shouldFailWith` (file ++ ": Error while parsing $ - expected Object, encountered Array")
it "warns on unknown fields" $ do
let file = joinPath ["defaults", "sol", "hpack-template", "2017", "defaults.yaml"]
writeFile file "foo: bar"
[i|
name: foo
defaults:
github: sol/hpack-template
path: defaults.yaml
ref: "2017"
bar: baz
library: {}
|] `shouldWarn` [
"package.yaml: Ignoring unrecognized field $.defaults.bar"
, file ++ ": Ignoring unrecognized field $.foo"
]
it "accepts defaults from local files" $ do
writeFile "defaults/foo.yaml" [i|
defaults:
local: bar.yaml
|]
writeFile "defaults/bar.yaml" [i|
default-extensions:
- RecordWildCards
- DeriveFunctor
|]
[i|
defaults:
local: defaults/foo.yaml
library: {}
|] `shouldRenderTo` library [i|
other-modules:
Paths_foo
default-extensions: RecordWildCards DeriveFunctor
|]
describe "version" $ do
it "accepts string" $ do
[i|
version: 0.1.0
|] `shouldRenderTo` (package "") {packageVersion = "0.1.0"}
it "accepts number" $ do
[i|
version: 0.1
|] `shouldRenderTo` (package [i|
|]) {packageVersion = "0.1"}
it "rejects other values" $ do
[i|
version: {}
|] `shouldFailWith` "package.yaml: Error while parsing $.version - expected Number or String, encountered Object"
describe "license" $ do
it "accepts cabal-style licenses" $ do
[i|
license: BSD3
|] `shouldRenderTo` (package [i|
license: BSD3
|])
it "accepts SPDX licenses" $ do
[i|
license: BSD-3-Clause
|] `shouldRenderTo` (package [i|
license: BSD-3-Clause
|]) {packageCabalVersion = "2.2"}
context "with an ambiguous license" $ do
it "treats it as a cabal-style license" $ do
[i|
license: MIT
|] `shouldRenderTo` (package [i|
license: MIT
|])
context "when cabal-version >= 2.2" $ do
it "maps license to SPDX license identifier" $ do
[i|
license: BSD3
library:
cxx-options: -Wall
|] `shouldRenderTo` (package [i|
license: BSD-3-Clause
library
other-modules:
Paths_foo
cxx-options: -Wall
default-language: Haskell2010
|]) {packageCabalVersion = "2.2"}
it "doesn't touch unknown licenses" $ do
[i|
license: some-license
library:
cxx-options: -Wall
|] `shouldRenderTo` (package [i|
license: some-license
library
other-modules:
Paths_foo
cxx-options: -Wall
default-language: Haskell2010
|]) {packageCabalVersion = "2.2"}
context "with a LICENSE file" $ do
before_ (writeFile "LICENSE" license) $ do
it "infers license" $ do
[i|
|] `shouldRenderTo` (package [i|
license-file: LICENSE
license: MIT
|])
context "when license can not be inferred" $ do
it "warns" $ do
writeFile "LICENSE" "some-licenese"
[i|
name: foo
|] `shouldWarn` ["Inferring license from file LICENSE failed!"]
context "when license is null" $ do
it "does not infer license" $ do
[i|
license: null
|] `shouldRenderTo` (package [i|
license-file: LICENSE
|])
describe "build-type" $ do
it "accept Simple" $ do
[i|
build-type: Simple
|] `shouldRenderTo` (package "") {packageBuildType = "Simple"}
it "accept Configure" $ do
[i|
build-type: Configure
|] `shouldRenderTo` (package "") {packageBuildType = "Configure"}
it "accept Make" $ do
[i|
build-type: Make
|] `shouldRenderTo` (package "") {packageBuildType = "Make"}
it "accept Custom" $ do
[i|
build-type: Custom
|] `shouldRenderTo` (package "") {packageBuildType = "Custom"}
it "rejects invalid values" $ do
[i|
build-type: foo
|] `shouldFailWith` "package.yaml: Error while parsing $.build-type - expected one of Simple, Configure, Make, or Custom"
describe "extra-doc-files" $ do
it "accepts a list of files" $ do
touch "CHANGES.markdown"
touch "README.markdown"
[i|
extra-doc-files:
- CHANGES.markdown
- README.markdown
|] `shouldRenderTo` (package [i|
extra-doc-files:
CHANGES.markdown
README.markdown
|]) {packageCabalVersion = "1.18"}
it "accepts glob patterns" $ do
touch "CHANGES.markdown"
touch "README.markdown"
[i|
extra-doc-files:
- "*.markdown"
|] `shouldRenderTo` (package [i|
extra-doc-files:
CHANGES.markdown
README.markdown
|]) {packageCabalVersion = "1.18"}
it "warns if a glob pattern does not match anything" $ do
[i|
name: foo
extra-doc-files:
- "*.markdown"
|] `shouldWarn` ["Specified pattern \"*.markdown\" for extra-doc-files does not match any files"]
describe "build-tools" $ do
it "adds known build tools to build-tools" $ do
[i|
executable:
build-tools:
alex == 0.1.0
|] `shouldRenderTo` executable_ "foo" [i|
build-tools:
alex ==0.1.0
|]
it "adds other build tools to build-tool-depends" $ do
[i|
executable:
build-tools:
hspec-discover: 0.1.0
|] `shouldRenderTo` (executable_ "foo" [i|
build-tool-depends:
hspec-discover:hspec-discover ==0.1.0
|]) {
-- NOTE: We do not set this to 2.0 on purpose, so that the .cabal
-- file is compatible with a wider range of Cabal versions!
packageCabalVersion = "1.12"
}
context "when the name of a build tool matches an executable from the same package" $ do
it "adds it to build-tools" $ do
[i|
executables:
bar:
build-tools:
- bar
|] `shouldRenderTo` executable_ "bar" [i|
build-tools:
bar
|]
it "gives per-section unqualified names precedence over global qualified names" $ do
[i|
build-tools:
- foo:bar == 0.1.0
executables:
bar:
build-tools:
- bar == 0.2.0
|] `shouldRenderTo` executable_ "bar" [i|
build-tools:
bar ==0.2.0
|]
it "gives per-section qualified names precedence over global unqualified names" $ do
[i|
build-tools:
- bar == 0.1.0
executables:
bar:
build-tools:
- foo:bar == 0.2.0
|] `shouldRenderTo` executable_ "bar" [i|
build-tools:
bar ==0.2.0
|]
context "when the name of a build tool matches a legacy system build tool" $ do
it "adds it to build-tools" $ do
[i|
executable:
build-tools:
ghc >= 7.10
|] `shouldRenderTo` (executable_ "foo" [i|
build-tools:
ghc >=7.10
|]) { packageWarnings = ["Listing \"ghc\" under build-tools is deperecated! Please list system executables under system-build-tools instead!"] }
describe "system-build-tools" $ do
it "adds system build tools to build-tools" $ do
[i|
executable:
system-build-tools:
ghc >= 7.10
|] `shouldRenderTo` executable_ "foo" [i|
build-tools:
ghc >=7.10
|]
context "with hpc" $ do
it "infers cabal-version 1.14" $ do
[i|
executable:
system-build-tools:
hpc
|] `shouldRenderTo` (executable_ "foo" [i|
build-tools:
hpc
|]) {packageCabalVersion = "1.14"}
context "with ghcjs" $ do
it "infers cabal-version 1.22" $ do
[i|
executable:
system-build-tools:
ghcjs
|] `shouldRenderTo` (executable_ "foo" [i|
build-tools:
ghcjs
|]) {packageCabalVersion = "1.22"}
context "with an unknown system build tool" $ do
it "infers cabal-version 2.0" $ do
[i|
executable:
system-build-tools:
g++ >= 5.4.0
|] `shouldRenderTo` (executable_ "foo" [i|
build-tools:
g++ >=5.4.0
|]) {packageCabalVersion = "2.0"}
describe "dependencies" $ do
it "accepts single dependency" $ do
[i|
executable:
dependencies: base
|] `shouldRenderTo` executable_ "foo" [i|
build-depends:
base
|]
it "accepts list of dependencies" $ do
[i|
executable:
dependencies:
- base
- transformers
|] `shouldRenderTo` executable_ "foo" [i|
build-depends:
base
, transformers
|]
context "with both global and section specific dependencies" $ do
it "combines dependencies" $ do
[i|
dependencies:
- base
executable:
dependencies: hspec
|] `shouldRenderTo` executable_ "foo" [i|
build-depends:
base
, hspec
|]
it "gives section specific dependencies precedence" $ do
[i|
dependencies:
- base
executable:
dependencies: base >= 2
|] `shouldRenderTo` executable_ "foo" [i|
build-depends:
base >=2
|]
describe "pkg-config-dependencies" $ do
it "accepts pkg-config-dependencies" $ do
[i|
pkg-config-dependencies:
- QtWebKit
- weston
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
pkgconfig-depends:
QtWebKit
, weston
|]
describe "include-dirs" $ do
it "accepts include-dirs" $ do
[i|
include-dirs:
- foo
- bar
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
include-dirs:
foo
bar
|]
describe "install-includes" $ do
it "accepts install-includes" $ do
[i|
install-includes:
- foo.h
- bar.h
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
install-includes:
foo.h
bar.h
|]
describe "js-sources" $ before_ (touch "foo.js" >> touch "jsbits/bar.js") $ do
it "accepts js-sources" $ do
[i|
executable:
js-sources:
- foo.js
- jsbits/*.js
|] `shouldRenderTo` executable_ "foo" [i|
js-sources:
foo.js
jsbits/bar.js
|]
it "accepts global js-sources" $ do
[i|
js-sources:
- foo.js
- jsbits/*.js
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
js-sources:
foo.js
jsbits/bar.js
|]
describe "cxx-options" $ do
it "accepts cxx-options" $ do
[i|
executable:
cxx-options: -Wall
|] `shouldRenderTo` (executable_ "foo" [i|
cxx-options: -Wall
|]) {packageCabalVersion = "2.2"}
context "when used inside a nested conditional" $ do
it "infers correct cabal-version" $ do
[i|
executable:
when:
condition: True
when:
condition: True
when:
condition: True
cxx-options: -Wall
|] `shouldRenderTo` (executable_ "foo" [i|
if true
if true
if true
cxx-options: -Wall
|]) {packageCabalVersion = "2.2"}
describe "cxx-sources" $ before_ (touch "foo.cc" >> touch "cxxbits/bar.cc") $ do
it "accepts cxx-sources" $ do
[i|
executable:
cxx-sources:
- foo.cc
- cxxbits/*.cc
|] `shouldRenderTo` (executable_ "foo" [i|
cxx-sources:
foo.cc
cxxbits/bar.cc
|]) {packageCabalVersion = "2.2"}
describe "extra-lib-dirs" $ do
it "accepts extra-lib-dirs" $ do
[i|
extra-lib-dirs:
- foo
- bar
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
extra-lib-dirs:
foo
bar
|]
describe "extra-libraries" $ do
it "accepts extra-libraries" $ do
[i|
extra-libraries:
- foo
- bar
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
extra-libraries:
foo
bar
|]
describe "extra-frameworks-dirs" $ do
it "accepts extra-frameworks-dirs" $ do
[i|
extra-frameworks-dirs:
- foo
- bar
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
extra-frameworks-dirs:
foo
bar
|]
describe "frameworks" $ do
it "accepts frameworks" $ do
[i|
frameworks:
- foo
- bar
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
frameworks:
foo
bar
|]
describe "c-sources" $ before_ (touch "cbits/foo.c" >> touch "cbits/bar.c" >> touch "cbits/baz.c") $ do
it "keeps declaration order" $ do
-- IMPORTANT: This is crucial as a workaround for https://ghc.haskell.org/trac/ghc/ticket/13786
[i|
library:
c-sources:
- cbits/foo.c
- cbits/bar.c
- cbits/baz.c
|] `shouldRenderTo` library_ [i|
c-sources:
cbits/foo.c
cbits/bar.c
cbits/baz.c
|]
it "accepts glob patterns" $ do
[i|
library:
c-sources: cbits/*.c
|] `shouldRenderTo` library_ [i|
c-sources:
cbits/bar.c
cbits/baz.c
cbits/foo.c
|]
it "warns when a glob pattern does not match any files" $ do
[i|
name: foo
library:
c-sources: foo/*.c
|] `shouldWarn` pure "Specified pattern \"foo/*.c\" for c-sources does not match any files"
it "quotes filenames with special characters" $ do
touch "cbits/foo bar.c"
[i|
library:
c-sources:
- cbits/foo bar.c
|] `shouldRenderTo` library_ [i|
c-sources:
"cbits/foo bar.c"
|]
describe "custom-setup" $ do
it "warns on unknown fields" $ do
[i|
name: foo
custom-setup:
foo: 1
bar: 2
|] `shouldWarn` [
"package.yaml: Ignoring unrecognized field $.custom-setup.bar"
, "package.yaml: Ignoring unrecognized field $.custom-setup.foo"
]
it "accepts dependencies" $ do
[i|
custom-setup:
dependencies:
- base
|] `shouldRenderTo` customSetup [i|
setup-depends:
base
|]
it "leaves build-type alone, if it exists" $ do
[i|
build-type: Make
custom-setup:
dependencies:
- base
|] `shouldRenderTo` (customSetup [i|
setup-depends:
base
|]) {packageBuildType = "Make"}
describe "library" $ do
it "accepts reexported-modules" $ do
[i|
library:
reexported-modules: Baz
|] `shouldRenderTo` (library_ [i|
reexported-modules:
Baz
|]) {packageCabalVersion = "1.22"}
it "accepts signatures" $ do
[i|
library:
signatures: Foo
|] `shouldRenderTo` (library_ [i|
signatures:
Foo
|]) {packageCabalVersion = "2.0"}
context "when package.yaml contains duplicate modules" $ do
it "generates a cabal file with duplicate modules" $ do
-- garbage in, garbage out
[i|
library:
exposed-modules: Foo
other-modules: Foo
|] `shouldRenderTo` library [i|
exposed-modules:
Foo
other-modules:
Foo
|]
context "when inferring modules" $ do
context "with exposed-modules" $ do
it "infers other-modules" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
library:
source-dirs: src
exposed-modules: Foo
|] `shouldRenderTo` library [i|
hs-source-dirs:
src
exposed-modules:
Foo
other-modules:
Bar
Paths_foo
|]
context "with other-modules" $ do
it "infers exposed-modules" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
library:
source-dirs: src
other-modules: Bar
|] `shouldRenderTo` library [i|
hs-source-dirs:
src
exposed-modules:
Foo
other-modules:
Bar
|]
context "with both exposed-modules and other-modules" $ do
it "doesn't infer any modules" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
library:
source-dirs: src
exposed-modules: Foo
other-modules: Bar
|] `shouldRenderTo` library [i|
hs-source-dirs:
src
exposed-modules:
Foo
other-modules:
Bar
|]
context "with neither exposed-modules nor other-modules" $ do
it "infers exposed-modules" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
library:
source-dirs: src
|] `shouldRenderTo` library [i|
hs-source-dirs:
src
exposed-modules:
Bar
Foo
other-modules:
Paths_foo
|]
context "with a conditional" $ do
it "doesn't infer any modules mentioned in that conditional" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
library:
source-dirs: src
when:
condition: os(windows)
exposed-modules:
- Foo
- Paths_foo
|] `shouldRenderTo` library [i|
hs-source-dirs:
src
if os(windows)
exposed-modules:
Foo
Paths_foo
exposed-modules:
Bar
|]
context "with a source-dir inside the conditional" $ do
it "infers other-modules" $ do
touch "windows/Foo.hs"
[i|
library:
when:
condition: os(windows)
source-dirs: windows
|] `shouldRenderTo` library [i|
other-modules:
Paths_foo
if os(windows)
other-modules:
Foo
hs-source-dirs:
windows
|]
it "does not infer outer modules" $ do
touch "windows/Foo.hs"
touch "unix/Foo.hs"
[i|
library:
exposed-modules: Foo
when:
condition: os(windows)
then:
source-dirs: windows/
else:
source-dirs: unix/
|] `shouldRenderTo` library [i|
exposed-modules:
Foo
other-modules:
Paths_foo
if os(windows)
hs-source-dirs:
windows/
else
hs-source-dirs:
unix/
|]
context "with generated modules" $ do
it "includes generated modules in autogen-modules" $ do
[i|
library:
generated-exposed-modules: Foo
generated-other-modules: Bar
|] `shouldRenderTo` (library [i|
exposed-modules:
Foo
other-modules:
Paths_foo
Bar
autogen-modules:
Foo
Bar
|]) {packageCabalVersion = "2.0"}
it "does not infer any mentioned generated modules" $ do
touch "src/Exposed.hs"
touch "src/Other.hs"
[i|
library:
source-dirs: src
generated-exposed-modules: Exposed
generated-other-modules: Other
|] `shouldRenderTo` (library [i|
hs-source-dirs:
src
exposed-modules:
Exposed
other-modules:
Paths_foo
Other
autogen-modules:
Exposed
Other
|]) {packageCabalVersion = "2.0"}
it "does not infer any generated modules mentioned inside conditionals" $ do
touch "src/Exposed.hs"
touch "src/Other.hs"
[i|
library:
source-dirs: src
when:
condition: os(windows)
generated-exposed-modules: Exposed
generated-other-modules: Other
|] `shouldRenderTo` (library [i|
other-modules:
Paths_foo
hs-source-dirs:
src
if os(windows)
exposed-modules:
Exposed
other-modules:
Other
autogen-modules:
Other
Exposed
|]) {packageCabalVersion = "2.0"}
context "mixins" $ do
it "sets cabal-version to 2.0 if mixins are used" $ do
[i|
library:
dependencies:
foo:
mixin:
- (Blah as Etc)
|] `shouldRenderTo` (library [i|
other-modules:
Paths_foo
build-depends:
foo
mixins:
foo (Blah as Etc)
|]) {packageCabalVersion = "2.0"}
describe "internal-libraries" $ do
it "accepts internal-libraries" $ do
touch "src/Foo.hs"
[i|
internal-libraries:
bar:
source-dirs: src
|] `shouldRenderTo` internalLibrary "bar" [i|
exposed-modules:
Foo
other-modules:
Paths_foo
hs-source-dirs:
src
|]
it "warns on unknown fields" $ do
[i|
name: foo
internal-libraries:
bar:
baz: 42
|] `shouldWarn` pure "package.yaml: Ignoring unrecognized field $.internal-libraries.bar.baz"
it "warns on missing source-dirs" $ do
[i|
name: foo
internal-libraries:
bar:
source-dirs: src
|] `shouldWarn` pure "Specified source-dir \"src\" does not exist"
describe "executables" $ do
it "accepts arbitrary entry points as main" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
executables:
foo:
source-dirs: src
main: Foo
|] `shouldRenderTo` executable "foo" [i|
main-is: Foo.hs
ghc-options: -main-is Foo
hs-source-dirs:
src
other-modules:
Bar
Paths_foo
|]
context "when inferring modules" $ do
it "infers other-modules" $ do
touch "src/Main.hs"
touch "src/Foo.hs"
[i|
executables:
foo:
main: Main.hs
source-dirs: src
|] `shouldRenderTo` executable "foo" [i|
main-is: Main.hs
hs-source-dirs:
src
other-modules:
Foo
Paths_foo
|]
it "allows to specify other-modules" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
executables:
foo:
main: Main.hs
source-dirs: src
other-modules: Baz
|] `shouldRenderTo` executable "foo" [i|
main-is: Main.hs
hs-source-dirs:
src
other-modules:
Baz
|]
it "does not infer any mentioned generated modules" $ do
touch "src/Foo.hs"
[i|
executables:
foo:
main: Main.hs
source-dirs: src
generated-other-modules: Foo
|] `shouldRenderTo` (executable "foo" [i|
main-is: Main.hs
hs-source-dirs:
src
other-modules:
Paths_foo
Foo
autogen-modules:
Foo
|]) {packageCabalVersion = "2.0"}
context "with conditional" $ do
it "doesn't infer any modules mentioned in that conditional" $ do
touch "src/Foo.hs"
touch "src/Bar.hs"
[i|
executables:
foo:
source-dirs: src
when:
condition: os(windows)
other-modules: Foo
|] `shouldRenderTo` executable "foo" [i|
other-modules:
Bar
Paths_foo
hs-source-dirs:
src
if os(windows)
other-modules:
Foo
|]
it "infers other-modules" $ do
touch "src/Foo.hs"
touch "windows/Bar.hs"
[i|
executables:
foo:
source-dirs: src
when:
condition: os(windows)
source-dirs: windows
|] `shouldRenderTo` executable "foo" [i|
other-modules:
Foo
Paths_foo
hs-source-dirs:
src
if os(windows)
other-modules:
Bar
hs-source-dirs:
windows
|]
context "with conditional" $ do
it "does not apply global options" $ do
-- related bug: https://github.com/sol/hpack/issues/214
[i|
ghc-options: -Wall
executables:
foo:
when:
condition: os(windows)
main: Foo.hs
|] `shouldRenderTo` executable_ "foo" [i|
ghc-options: -Wall
if os(windows)
main-is: Foo.hs
|]
it "accepts executable-specific fields" $ do
[i|
executables:
foo:
when:
condition: os(windows)
main: Foo
|] `shouldRenderTo` executable_ "foo" [i|
if os(windows)
main-is: Foo.hs
ghc-options: -main-is Foo
|]
describe "when" $ do
it "accepts conditionals" $ do
[i|
when:
condition: os(windows)
dependencies: Win32
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
if os(windows)
build-depends:
Win32
|]
it "warns on unknown fields" $ do
[i|
name: foo
foo: 23
when:
- condition: os(windows)
bar: 23
when:
condition: os(windows)
bar2: 23
- condition: os(windows)
baz: 23
|] `shouldWarn` [
"package.yaml: Ignoring unrecognized field $.foo"
, "package.yaml: Ignoring unrecognized field $.when[0].bar"
, "package.yaml: Ignoring unrecognized field $.when[0].when.bar2"
, "package.yaml: Ignoring unrecognized field $.when[1].baz"
]
context "when parsing conditionals with else-branch" $ do
it "accepts conditionals with else-branch" $ do
[i|
when:
condition: os(windows)
then:
dependencies: Win32
else:
dependencies: unix
executable: {}
|] `shouldRenderTo` executable_ "foo" [i|
if os(windows)
build-depends:
Win32
else
build-depends:
unix
|]
it "rejects invalid conditionals" $ do
[i|
when:
condition: os(windows)
then:
dependencies: Win32
else: null
|] `shouldFailWith` "package.yaml: Error while parsing $.when.else - expected Object, encountered Null"
it "rejects invalid conditionals" $ do
[i|
dependencies:
- foo
- 23
|] `shouldFailWith` "package.yaml: Error while parsing $.dependencies[1] - expected Object or String, encountered Number"
it "warns on unknown fields" $ do
[i|
name: foo
when:
condition: os(windows)
foo: null
then:
bar: null
else:
when:
condition: os(windows)
then: {}
else:
baz: null
|] `shouldWarn` [
"package.yaml: Ignoring unrecognized field $.when.foo"
, "package.yaml: Ignoring unrecognized field $.when.then.bar"
, "package.yaml: Ignoring unrecognized field $.when.else.when.else.baz"
]
describe "verbatim" $ do
it "accepts strings" $ do
[i|
library:
verbatim: |
foo: 23
bar: 42
|] `shouldRenderTo` package [i|
library
other-modules:
Paths_foo
default-language: Haskell2010
foo: 23
bar: 42
|]
it "accepts multi-line strings as field values" $ do
[i|
library:
verbatim:
build-depneds: |
foo
bar
baz
|] `shouldRenderTo` package [i|
library
other-modules:
Paths_foo
default-language: Haskell2010
build-depneds:
foo
bar
baz
|]
it "allows to null out existing fields" $ do
[i|
library:
verbatim:
default-language: null
|] `shouldRenderTo` package [i|
library
other-modules:
Paths_foo
|]
context "when specified globally" $ do
it "overrides header fields" $ do
[i|
verbatim:
cabal-version: foo
|] `shouldRenderTo` (package "") {packageCabalVersion = "foo"}
it "overrides other fields" $ do
touch "foo"
[i|
extra-source-files: foo
verbatim:
extra-source-files: bar
|] `shouldRenderTo` package [i|
extra-source-files: bar
|]
it "is not propagated into sections" $ do
[i|
verbatim:
foo: 23
library: {}
|] `shouldRenderTo` package [i|
foo: 23
library
other-modules:
Paths_foo
default-language: Haskell2010
|]
context "within a section" $ do
it "overrides section fields" $ do
[i|
tests:
spec:
verbatim:
type: detailed-0.9
|] `shouldRenderTo` package [i|
test-suite spec
type: detailed-0.9
other-modules:
Paths_foo
default-language: Haskell2010
|]
describe "default value of maintainer" $ do
it "gives maintainer precedence" $ do
[i|
author: John Doe
maintainer: Jane Doe
|] `shouldRenderTo` package [i|
author: John Doe
maintainer: Jane Doe
|]
context "with author" $ do
it "uses author if maintainer is not specified" $ do
[i|
author: John Doe
|] `shouldRenderTo` package [i|
author: John Doe
maintainer: John Doe
|]
it "omits maintainer if it is null" $ do
[i|
author: John Doe
maintainer: null
|] `shouldRenderTo` package [i|
author: John Doe
|]
run :: HasCallStack => FilePath -> FilePath -> String -> IO ([String], String)
run userDataDir c old = run_ userDataDir c old >>= either assertFailure return
run_ :: FilePath -> FilePath -> String -> IO (Either String ([String], String))
run_ userDataDir c old = do
mPackage <- readPackageConfig defaultDecodeOptions {decodeOptionsTarget = c, decodeOptionsUserDataDir = Just userDataDir}
return $ case mPackage of
Right (DecodeResult pkg cabalVersion _ warnings) ->
let
FormattingHints{..} = sniffFormattingHints (lines old)
alignment = fromMaybe 0 formattingHintsAlignment
settings = formattingHintsRenderSettings
output = cabalVersion ++ Hpack.renderPackageWith settings alignment formattingHintsFieldOrder formattingHintsSectionsFieldOrder pkg
in
Right (warnings, output)
Left err -> Left err
data RenderResult = RenderResult [String] String
deriving Eq
instance Show RenderResult where
show (RenderResult warnings output) = unlines (map ("WARNING: " ++) warnings) ++ output
shouldRenderTo :: HasCallStack => String -> Package -> Expectation
shouldRenderTo input p = do
writeFile packageConfig ("name: foo\n" ++ unindent input)
let currentDirectory = ".working-directory"
createDirectory currentDirectory
withCurrentDirectory currentDirectory $ do
(warnings, output) <- run ".." (".." </> packageConfig) expected
RenderResult warnings (dropEmptyLines output) `shouldBe` RenderResult (packageWarnings p) expected
where
expected = dropEmptyLines (renderPackage p)
dropEmptyLines = unlines . filter (not . null) . lines
shouldWarn :: HasCallStack => String -> [String] -> Expectation
shouldWarn input expected = do
writeFile packageConfig input
(warnings, _) <- run "" packageConfig ""
sort warnings `shouldBe` sort expected
shouldFailWith :: HasCallStack => String -> String -> Expectation
shouldFailWith input expected = do
writeFile packageConfig input
run_ "" packageConfig "" `shouldReturn` Left expected
customSetup :: String -> Package
customSetup a = (package content) {packageCabalVersion = "1.24", packageBuildType = "Custom"}
where
content = [i|
custom-setup
#{indentBy 2 $ unindent a}
|]
library_ :: String -> Package
library_ l = package content
where
content = [i|
library
other-modules:
Paths_foo
#{indentBy 2 $ unindent l}
default-language: Haskell2010
|]
library :: String -> Package
library l = package content
where
content = [i|
library
#{indentBy 2 $ unindent l}
default-language: Haskell2010
|]
internalLibrary :: String -> String -> Package
internalLibrary name e = (package content) {packageCabalVersion = "2.0"}
where
content = [i|
library #{name}
#{indentBy 2 $ unindent e}
default-language: Haskell2010
|]
executable_ :: String -> String -> Package
executable_ name e = package content
where
content = [i|
executable #{name}
other-modules:
Paths_foo
#{indentBy 2 $ unindent e}
default-language: Haskell2010
|]
executable :: String -> String -> Package
executable name e = package content
where
content = [i|
executable #{name}
#{indentBy 2 $ unindent e}
default-language: Haskell2010
|]
package :: String -> Package
package c = Package "foo" "0.0.0" "Simple" "1.12" c []
data Package = Package {
packageName :: String
, packageVersion :: String
, packageBuildType :: String
, packageCabalVersion :: String
, packageContent :: String
, packageWarnings :: [String]
}
renderPackage :: Package -> String
renderPackage Package{..} = unindent [i|
cabal-version: #{packageCabalVersion}
name: #{packageName}
version: #{packageVersion}
build-type: #{packageBuildType}
#{unindent packageContent}
|]
indentBy :: Int -> String -> String
indentBy n = unlines . map (replicate n ' ' ++) . lines
license :: String
license = [i|
Copyright (c) 2014-2018 Simon Hengel <sol@typeful.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|]
|
haskell-tinc/hpack
|
test/EndToEndSpec.hs
|
mit
| 47,936
| 0
| 28
| 18,715
| 6,315
| 3,468
| 2,847
| -1
| -1
|
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module JSONKit.KeyPath where
import Data.Aeson
import Data.Monoid
import qualified Data.HashMap.Lazy as HM
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.Attoparsec.Text as AT
import qualified Data.Vector as V
import Data.Scientific
import qualified Data.Text.Lazy.Builder as B
import qualified Data.Text.Lazy.Builder.Int as B
import qualified Data.Text.Lazy.Builder.RealFloat as B
import Data.Text (Text)
import qualified Data.Text as T
import Data.List (intersperse)
import Control.Applicative
-- CHANGEME These are output configs specific to TSV
-- TODO We should separate the evaluation functions from TSV-specific code
data Config = Config {
arrayDelim :: Text
, nullValueString :: Text
, trueString :: Text
, falseString :: Text
} deriving Show
-- | KeyPath may have an alias for the header output
data KeyPath = KeyPath [Key] (Maybe Text) deriving Show
data Key = Key Text | Index Int deriving (Eq, Show)
parseKeyPath :: Text -> [KeyPath]
parseKeyPath s = case AT.parseOnly pKeyPaths s of
Left err -> error $ "Parse error " ++ err
Right res -> res
spaces = AT.many1 AT.space
pKeyPaths :: AT.Parser [KeyPath]
pKeyPaths = pKeyPath `AT.sepBy` spaces
pKeyPath :: AT.Parser KeyPath
pKeyPath = KeyPath
<$> (AT.sepBy1 pKeyOrIndex (AT.takeWhile1 $ AT.inClass ".["))
<*> (pAlias <|> pure Nothing)
-- | A column header alias is designated by : followed by alphanum string after keypath
pAlias :: AT.Parser (Maybe Text)
pAlias = do
AT.char ':'
Just <$> AT.takeWhile1 (AT.inClass "a-zA-Z0-9_-")
pKeyOrIndex :: AT.Parser Key
pKeyOrIndex = pIndex <|> pKey
pKey = Key <$> AT.takeWhile1 (AT.notInClass " .[:")
pIndex = Index <$> AT.decimal <* AT.char ']'
evalToLineBuilder :: Config -> String -> [[Key]] -> Value -> B.Builder
evalToLineBuilder config@Config{..} outDelim ks v =
mconcat $ intersperse (B.fromText . T.pack $ outDelim) $ map (flip (evalToBuilder config) v) ks
type ArrayDelimiter = Text
evalToList :: Config -> [[Key]] -> Value -> [Text]
evalToList c@Config{..} ks v = map (flip (evalToText c) v) ks
evalToBuilder :: Config -> [Key] -> Value -> B.Builder
evalToBuilder c k v = valToBuilder c $ evalKeyPath c k v
evalToText :: Config -> [Key] -> Value -> Text
evalToText c k v = valToText c $ evalKeyPath c k v
-- evaluates the a JS key path against a Value context to a leaf Value
evalKeyPath :: Config -> [Key] -> Value -> Value
evalKeyPath config [] x@(String _) = x
evalKeyPath config [] x@Null = x
evalKeyPath config [] x@(Number _) = x
evalKeyPath config [] x@(Bool _) = x
evalKeyPath config [] x@(Object _) = x
evalKeyPath config [] x@(Array v) | V.null v = Null
evalKeyPath config [] x@(Array v) =
let vs = V.toList v
xs = intersperse (arrayDelim config) $ map (evalToText config []) vs
in String . mconcat $ xs
evalKeyPath config (Key key:ks) (Object s) =
case (HM.lookup key s) of
Just x -> evalKeyPath config ks x
Nothing -> Null
evalKeyPath config (Index idx:ks) (Array v) =
let e = (V.!?) v idx
in case e of
Just e' -> evalKeyPath config ks e'
Nothing -> Null
-- traverse array elements with additional keys
evalKeyPath _ ks@(Key key:_) (Array v) | V.null v = Null
evalKeyPath config@Config{..} ks@(Key key:_) (Array v) =
let vs = V.toList v
in String . mconcat . intersperse arrayDelim $ map (evalToText config ks) vs
evalKeyPath _ ((Index _):_) _ = Null
evalKeyPath _ _ _ = Null
valToBuilder :: Config -> Value -> B.Builder
valToBuilder _ (String x) = B.fromText x
valToBuilder Config{..} Null = B.fromText nullValueString
valToBuilder Config{..} (Bool True) = B.fromText trueString
valToBuilder Config{..} (Bool False) = B.fromText falseString
valToBuilder _ (Number x) =
case floatingOrInteger x of
Left float -> B.realFloat float
Right int -> B.decimal int
valToBuilder _ (Object _) = B.fromText "[Object]"
valToText :: Config -> Value -> Text
valToText _ (String x) = x
valToText Config{..} Null = nullValueString
valToText Config{..} (Bool True) = trueString
valToText Config{..} (Bool False) = falseString
valToText _ (Number x) =
case floatingOrInteger x of
Left float -> T.pack . show $ float
Right int -> T.pack . show $ int
valToText _ (Object _) = "[Object]"
|
danchoi/jsonkit
|
JSONKit/KeyPath.hs
|
mit
| 4,388
| 0
| 13
| 893
| 1,631
| 852
| 779
| 99
| 3
|
{-# LANGUAGE OverloadedStrings #-}
module Backends.Clojure where
import Backend.Language.Clojure as L
import Backend.Language.Common as L
import Data.Default.Class
import Data.Graph.Inductive as Graph
import Data.Maybe (fromMaybe)
import LevelGraphs as G
toClojureCode :: String -> NestedCodeGraph -> Serialized
toClojureCode _ = renderProgram def . toProgram convertLevels
convertLevels :: (Node -> [Node]) -> [[Graph.LNode CodeGraphNodeLabel]] -> Expr
convertLevels getSuc lvls = mkLet assigns [finalExpr]
where
toFun n = toFunClj n (map (Sym . varName) $ getSuc (fst n))
(assigns, finalExpr) = toAssign [] lvls
toAssign _ [] = error "empty"
toAssign l [x] =
case x of
[x] -> (l, toFun x)
_ -> error "last level must have exactly one node"
toAssign l (x:xs) = toAssign (e ++ l) xs
where
e = case x of
[] -> error "empty assignment"
[n@(id, _)] -> [(Sym $ varName id, toFun n)]
fs -> map (\n@(id, _) -> (Sym $ varName id, toFun n)) fs
toFunClj :: Graph.LNode CodeGraphNodeLabel -> [Expr] -> Expr
toFunClj node@(n, CodeGraphNodeLabel _ lab _) children =
case lab of
Custom "function" -> Form $ Sym (fnName n) : children
Custom "map" -> Form [Sym "count", Form [Sym "map", Sym (fnName n), Form $ Sym "vector" : children]]
Conditional cond true false -> mkIf (maybe (Bool True) mkRef cond) (maybe Nil mkRef true) (fmap mkRef false)
where mkRef = Sym . varName
Custom f -> Form $ Sym (Symbol f) : children
|
goens/rand-code-graph
|
src/Backends/Clojure.hs
|
mit
| 1,627
| 0
| 17
| 455
| 610
| 321
| 289
| 32
| 6
|
module ParserTest where
data Int : *
data State : * -> (* -> *) -> *
caseTest1 = case 0 of
1 -> 'b'
_ -> let id = \ x. x in id end
caseTest2 = case let f = \ x. x in 1 end of a -> a
main = caseTest1
|
pxqr/algorithm-wm
|
test/parser.hs
|
mit
| 206
| 7
| 9
| 62
| 114
| 59
| 55
| -1
| -1
|
module Data.Enumerator.Binary.Char8
( module Data.Enumerator.Binary
, Data.Enumerator.Binary.Char8.takeWhile
, Data.Enumerator.Binary.Char8.head
) where
import Data.Enumerator
import Data.Enumerator.Binary hiding (takeWhile, head)
import Data.Enumerator.Binary as EB
import Data.ByteString.Char8 as BS
import Data.ByteString.Lazy.Char8 as BS.Lazy
convert :: (Enum a, Enum b) => a -> b
convert = toEnum . fromEnum
takeWhile :: Monad m => (Char -> Bool)
-> Iteratee BS.ByteString m BS.Lazy.ByteString
takeWhile f = EB.takeWhile (f . convert)
head :: Monad m => Iteratee BS.ByteString m (Maybe Char)
head = fmap (fmap convert) EB.head
|
brow/redis-iteratee
|
src/Data/Enumerator/Binary/Char8.hs
|
mit
| 679
| 0
| 8
| 128
| 213
| 125
| 88
| 16
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.Graph.Test.Typed
-- Copyright : (c) Andrey Mokhov 2016-2022
-- License : MIT (see the file LICENSE)
-- Maintainer : anfelor@posteo.de, andrey.mokhov@gmail.com
-- Stability : experimental
--
-- Testsuite for "Data.Graph.Typed".
-----------------------------------------------------------------------------
module Data.Graph.Test.Typed (
-- * Testsuite
testTyped
) where
import qualified Algebra.Graph.AdjacencyMap as AM
import qualified Algebra.Graph.AdjacencyIntMap as AIM
import Algebra.Graph.Test
import Data.Array (array)
import Data.Graph.Typed
import Data.Tree
import Data.List (nub, sort)
import qualified Data.Graph as KL
import qualified Data.IntSet as IntSet
type AI = AM.AdjacencyMap Int
-- TODO: Improve the alignment in the testsuite to match the documentation.
(%) :: (GraphKL Int -> a) -> AM.AdjacencyMap Int -> a
a % g = a $ fromAdjacencyMap g
testTyped :: IO ()
testTyped = do
putStrLn "\n============ Typed ============"
putStrLn "\n============ Typed.fromAdjacencyMap ============"
test "toGraphKL (fromAdjacencyMap (1 * 2 + 3 * 1)) == array (0,2) [(0,[1]), (1,[]), (2,[0])]" $
toGraphKL (fromAdjacencyMap (1 * 2 + 3 * 1 :: AI)) == array (0,2) [(0,[1]), (1,[]), (2,[0])]
test "toGraphKL (fromAdjacencyMap (1 * 2 + 2 * 1)) == array (0,1) [(0,[1]), (1,[0])]" $
toGraphKL (fromAdjacencyMap (1 * 2 + 2 * 1 :: AI)) == array (0,1) [(0,[1]), (1,[0])]
test "map (fromVertexKL h) (vertices $ toGraphKL h) == vertexList g"
$ \(g :: AI) -> let h = fromAdjacencyMap g in
map (fromVertexKL h) (KL.vertices $ toGraphKL h) == AM.vertexList g
test "map (\\(x, y) -> (fromVertexKL h x, fromVertexKL h y)) (edges $ toGraphKL h) == edgeList g"
$ \(g :: AI) -> let h = fromAdjacencyMap g in
map (\(x, y) -> (fromVertexKL h x, fromVertexKL h y)) (KL.edges $ toGraphKL h) == AM.edgeList g
putStrLn "\n============ Typed.fromAdjacencyIntMap ============"
test "toGraphKL (fromAdjacencyIntMap (1 * 2 + 3 * 1)) == array (0,2) [(0,[1]), (1,[]), (2,[0])]" $
toGraphKL (fromAdjacencyIntMap (1 * 2 + 3 * 1)) == array (0,2) [(0,[1]), (1,[]), (2,[0])]
test "toGraphKL (fromAdjacencyIntMap (1 * 2 + 2 * 1)) == array (0,1) [(0,[1]), (1,[0])]" $
toGraphKL (fromAdjacencyIntMap (1 * 2 + 2 * 1)) == array (0,1) [(0,[1]), (1,[0])]
test "map (fromVertexKL h) (vertices $ toGraphKL h) == IntSet.toAscList (vertexIntSet g)"
$ \g -> let h = fromAdjacencyIntMap g in
map (fromVertexKL h) (KL.vertices $ toGraphKL h) == IntSet.toAscList (AIM.vertexIntSet g)
test "map (\\(x, y) -> (fromVertexKL h x, fromVertexKL h y)) (edges $ toGraphKL h) == edgeList g"
$ \g -> let h = fromAdjacencyIntMap g in
map (\(x, y) -> (fromVertexKL h x, fromVertexKL h y)) (KL.edges $ toGraphKL h) == AIM.edgeList g
putStrLn $ "\n============ Typed.dfsForest ============"
test "forest (dfsForest % edge 1 1) == vertex 1" $
AM.forest (dfsForest % AM.edge 1 1) == AM.vertex 1
test "forest (dfsForest % edge 1 2) == edge 1 2" $
AM.forest (dfsForest % AM.edge 1 2) == AM.edge 1 2
test "forest (dfsForest % edge 2 1) == vertices [1, 2]" $
AM.forest (dfsForest % AM.edge 2 1) == AM.vertices [1, 2]
test "isSubgraphOf (forest $ dfsForest % x) x == True" $ \x ->
AM.isSubgraphOf (AM.forest $ dfsForest % x) x == True
test "dfsForest % forest (dfsForest % x) == dfsForest % x" $ \x ->
dfsForest % AM.forest (dfsForest % x) == dfsForest % x
test "dfsForest % vertices vs == map (\\v -> Node v []) (nub $ sort vs)" $ \vs ->
dfsForest % AM.vertices vs == map (\v -> Node v []) (nub $ sort vs)
test "dfsForest % (3 * (1 + 4) * (1 + 5)) == <correct result>" $
dfsForest % (3 * (1 + 4) * (1 + 5)) == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 3
, subForest = [ Node { rootLabel = 4
, subForest = [] }]}]
putStrLn $ "\n============ Typed.dfsForestFrom ============"
test "forest (dfsForestFrom [1] % edge 1 1) == vertex 1" $
AM.forest (dfsForestFrom [1] % AM.edge 1 1) == AM.vertex 1
test "forest (dfsForestFrom [1] % edge 1 2) == edge 1 2" $
AM.forest (dfsForestFrom [1] % AM.edge 1 2) == AM.edge 1 2
test "forest (dfsForestFrom [2] % edge 1 2) == vertex 2" $
AM.forest (dfsForestFrom [2] % AM.edge 1 2) == AM.vertex 2
test "forest (dfsForestFrom [3] % edge 1 2) == empty" $
AM.forest (dfsForestFrom [3] % AM.edge 1 2) == AM.empty
test "forest (dfsForestFrom [2, 1] % edge 1 2) == vertices [1, 2]" $
AM.forest (dfsForestFrom [2, 1] % AM.edge 1 2) == AM.vertices [1, 2]
test "isSubgraphOf (forest $ dfsForestFrom vs % x) x == True" $ \vs x ->
AM.isSubgraphOf (AM.forest (dfsForestFrom vs % x)) x == True
test "dfsForestFrom (vertexList x) % x == dfsForest % x" $ \x ->
dfsForestFrom (AM.vertexList x) % x == dfsForest % x
test "dfsForestFrom vs % (AM.vertices vs) == map (\\v -> Node v []) (nub vs)" $ \vs ->
dfsForestFrom vs % AM.vertices vs == map (\v -> Node v []) (nub vs)
test "dfsForestFrom [] % x == []" $ \x ->
dfsForestFrom [] % x == []
test "dfsForestFrom [1, 4] % 3 * (1 + 4) * (1 + 5) == <correct result>" $
dfsForestFrom [1, 4] % (3 * (1 + 4) * (1 + 5)) == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 4
, subForest = [] }]
putStrLn $ "\n============ Typed.dfs ============"
test "dfs [1] % edge 1 1 == [1]" $
dfs [1] % AM.edge 1 1 == [1]
test "dfs [1] % edge 1 2 == [1,2]" $
dfs [1] % AM.edge 1 2 == [1,2]
test "dfs [2] % edge 1 2 == [2]" $
dfs [2] % AM.edge 1 2 == [2]
test "dfs [3] % edge 1 2 == []" $
dfs [3] % AM.edge 1 2 == []
test "dfs [1, 2] % edge 1 2 == [1, 2]" $
dfs [1, 2] % AM.edge 1 2 == [1, 2]
test "dfs [2, 1] % edge 1 2 == [2, 1]" $
dfs [2, 1] % AM.edge 1 2 == [2, 1]
test "dfs [] % x == []" $ \x ->
dfs [] % x == []
test "dfs [1, 4] % 3 * (1 + 4) * (1 + 5) == [1,5,4]" $
dfs [1, 4] % (3 * (1 + 4) * (1 + 5)) == [1,5,4]
test "isSubgraphOf (vertices $ dfs vs % x) x == True" $ \vs x ->
AM.isSubgraphOf (AM.vertices $ dfs vs % x) x == True
putStrLn "\n============ Typed.topSort ============"
test "topSort % (1 * 2 + 3 * 1) == [3,1,2]" $
topSort % (1 * 2 + 3 * 1) == ([3,1,2] :: [Int])
test "topSort % (1 * 2 + 2 * 1) == [1,2]" $
topSort % (1 * 2 + 2 * 1) == ([1,2] :: [Int])
|
snowleopard/alga
|
test/Data/Graph/Test/Typed.hs
|
mit
| 8,234
| 0
| 16
| 3,234
| 2,183
| 1,123
| 1,060
| -1
| -1
|
{- |
Module : Main
Description : parallel fibonacci benchmark.
Copyright : (c) liquid_amber, 2014
License : MIT
Maintainer : liquid.amber.ja@gmaill.com
Stability : experimental
Portability : portable
This example runs fibonacci in parallel.
-}
import Control.Concurrent.Async
-- | Calculate fibonacci n in parallel.
fib :: Int -> IO Int
fib n | n < 2 = return n
fib n = do
(r1, r2) <- (n -1 `seq` fib (n - 1)) `concurrently` (n - 2 `seq` fib (n - 2))
r1 `seq` r2 `seq` return (r1 + r2)
main :: IO ()
main = print =<< fib 40
|
liquidamber/rust-examples
|
b002_fib_para.hs
|
mit
| 546
| 0
| 13
| 121
| 162
| 87
| 75
| 8
| 1
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.SVGMaskElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.SVGMaskElement
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.SVGMaskElement
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/SVGMaskElement.hs
|
mit
| 355
| 0
| 5
| 33
| 33
| 26
| 7
| 4
| 0
|
{-# LANGUAGE ForeignFunctionInterface #-}
module Clingo.Raw.Inspection.Symbolic
(
symbolicAtomsSize,
symbolicAtomsBegin,
symbolicAtomsEnd,
symbolicAtomsFind,
symbolicAtomsIteratorIsEqualTo,
symbolicAtomsSymbol,
symbolicAtomsIsFact,
symbolicAtomsIsExternal,
symbolicAtomsLiteral,
symbolicAtomsSignaturesSize,
symbolicAtomsSignatures,
symbolicAtomsNext,
symbolicAtomsIsValid
)
where
import Control.Monad.IO.Class
import Foreign
import Foreign.C
import Clingo.Raw.Types
foreign import ccall "clingo.h clingo_symbolic_atoms_size" symbolicAtomsSizeFFI ::
SymbolicAtoms -> Ptr CSize -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_begin" symbolicAtomsBeginFFI ::
SymbolicAtoms -> Ptr Signature -> Ptr SymbolicAtomIterator -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_end" symbolicAtomsEndFFI ::
SymbolicAtoms -> Ptr SymbolicAtomIterator -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_find" symbolicAtomsFindFFI ::
SymbolicAtoms -> Symbol -> Ptr SymbolicAtomIterator -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_iterator_is_equal_to" symbolicAtomsIteratorIsEqualToFFI ::
SymbolicAtoms -> SymbolicAtomIterator -> SymbolicAtomIterator -> Ptr CBool -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_symbol" symbolicAtomsSymbolFFI ::
SymbolicAtoms -> SymbolicAtomIterator -> Ptr Symbol -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_is_fact" symbolicAtomsIsFactFFI ::
SymbolicAtoms -> SymbolicAtomIterator -> Ptr CBool -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_is_external" symbolicAtomsIsExternalFFI ::
SymbolicAtoms -> SymbolicAtomIterator -> Ptr CBool -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_literal" symbolicAtomsLiteralFFI ::
SymbolicAtoms -> SymbolicAtomIterator -> Ptr Literal -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_signatures_size" symbolicAtomsSignaturesSizeFFI ::
SymbolicAtoms -> Ptr CSize -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_signatures" symbolicAtomsSignaturesFFI ::
SymbolicAtoms -> Ptr Signature -> CSize -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_next" symbolicAtomsNextFFI ::
SymbolicAtoms -> SymbolicAtomIterator -> Ptr SymbolicAtomIterator -> IO CBool
foreign import ccall "clingo.h clingo_symbolic_atoms_is_valid" symbolicAtomsIsValidFFI ::
SymbolicAtoms -> SymbolicAtomIterator -> Ptr CBool -> IO CBool
symbolicAtomsSize :: MonadIO m => SymbolicAtoms -> Ptr CSize -> m CBool
symbolicAtomsSize a b = liftIO $ symbolicAtomsSizeFFI a b
symbolicAtomsBegin :: MonadIO m => SymbolicAtoms -> Ptr Signature -> Ptr SymbolicAtomIterator -> m CBool
symbolicAtomsBegin a b c = liftIO $ symbolicAtomsBeginFFI a b c
symbolicAtomsEnd :: MonadIO m => SymbolicAtoms -> Ptr SymbolicAtomIterator -> m CBool
symbolicAtomsEnd a b = liftIO $ symbolicAtomsEndFFI a b
symbolicAtomsFind :: MonadIO m => SymbolicAtoms -> Symbol -> Ptr SymbolicAtomIterator -> m CBool
symbolicAtomsFind a b c = liftIO $ symbolicAtomsFindFFI a b c
symbolicAtomsIteratorIsEqualTo :: MonadIO m => SymbolicAtoms -> SymbolicAtomIterator -> SymbolicAtomIterator -> Ptr CBool -> m CBool
symbolicAtomsIteratorIsEqualTo a b c d = liftIO $ symbolicAtomsIteratorIsEqualToFFI a b c d
symbolicAtomsSymbol :: MonadIO m => SymbolicAtoms -> SymbolicAtomIterator -> Ptr Symbol -> m CBool
symbolicAtomsSymbol a b c = liftIO $ symbolicAtomsSymbolFFI a b c
symbolicAtomsIsFact :: MonadIO m => SymbolicAtoms -> SymbolicAtomIterator -> Ptr CBool -> m CBool
symbolicAtomsIsFact a b c = liftIO $ symbolicAtomsIsFactFFI a b c
symbolicAtomsIsExternal :: MonadIO m => SymbolicAtoms -> SymbolicAtomIterator -> Ptr CBool -> m CBool
symbolicAtomsIsExternal a b c = liftIO $ symbolicAtomsIsExternalFFI a b c
symbolicAtomsLiteral :: MonadIO m => SymbolicAtoms -> SymbolicAtomIterator -> Ptr Literal -> m CBool
symbolicAtomsLiteral a b c = liftIO $ symbolicAtomsLiteralFFI a b c
symbolicAtomsSignaturesSize :: MonadIO m => SymbolicAtoms -> Ptr CSize -> m CBool
symbolicAtomsSignaturesSize a b = liftIO $ symbolicAtomsSignaturesSizeFFI a b
symbolicAtomsSignatures :: MonadIO m => SymbolicAtoms -> Ptr Signature -> CSize -> m CBool
symbolicAtomsSignatures a b c = liftIO $ symbolicAtomsSignaturesFFI a b c
symbolicAtomsNext :: MonadIO m => SymbolicAtoms -> SymbolicAtomIterator -> Ptr SymbolicAtomIterator -> m CBool
symbolicAtomsNext a b c = liftIO $ symbolicAtomsNextFFI a b c
symbolicAtomsIsValid :: MonadIO m => SymbolicAtoms -> SymbolicAtomIterator -> Ptr CBool -> m CBool
symbolicAtomsIsValid a b c = liftIO $ symbolicAtomsIsValidFFI a b c
|
tsahyt/clingo-haskell
|
src/Clingo/Raw/Inspection/Symbolic.hs
|
mit
| 4,730
| 0
| 10
| 674
| 1,132
| 558
| 574
| 72
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Data.Mole.Server where
import Control.Concurrent.STM
import Control.Monad.IO.Class
import Control.Applicative
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Maybe
import Data.List (find)
import Snap.Http.Server (httpServe, ConfigLog(..))
import qualified Snap.Http.Server.Config as SC
import Snap.Core (Snap, pass, getRequest, rqPathInfo, setContentType, modifyResponse, writeBS)
import Data.Mole.Types
import Data.Mole.Core
serveFiles :: Handle -> Int -> Maybe String -> IO ()
serveFiles h port mbSocketPath = do
snapConfig <- do
config <- return SC.emptyConfig :: IO (SC.Config Snap ())
let config' = SC.setAccessLog ConfigNoLog $ SC.setErrorLog ConfigNoLog config
return $ maybe (SC.setPort port config') (\x -> SC.setUnixSocket x config') mbSocketPath
httpServe snapConfig (snapHandler h)
snapHandler :: Handle -> Snap ()
snapHandler h = do
req <- getRequest
serve ("/" <> rqPathInfo req)
<|> serve ("/" <> rqPathInfo req <> "/index.html")
<|> serve ("/" <> rqPathInfo req <> "index.html")
<|> serve "/index.html"
<|> writeBS ("Asset " <> rqPathInfo req <> " not found")
where
serve p = do
s <- liftIO $ atomically $ readTVar (state h)
let asts = assetsByPublicIdentifier s (PublicIdentifier $ T.decodeUtf8 p)
-- liftIO $ print asts
if length asts == 0
then pass
else do
-- void $ liftIO $ require h $ S.fromList $ map fst asts
-- void $ liftIO $ require h $ S.singleton $ AssetId $ tail $ unpack p
let mbRes = find (\res -> isJust (resource res)) $ map snd asts
case mbRes of
Just (Result _ (Just (body, contentType))) -> do
modifyResponse $ setContentType (T.encodeUtf8 $ T.pack contentType)
writeBS body
_ -> pass
|
wereHamster/mole
|
src/Data/Mole/Server.hs
|
mit
| 2,076
| 0
| 22
| 629
| 584
| 303
| 281
| 41
| 3
|
module GHCJS.DOM.Internals (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/Internals.hs
|
mit
| 39
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-stepfunctionsaction.html
module Stratosphere.ResourceProperties.IoTTopicRuleStepFunctionsAction where
import Stratosphere.ResourceImports
-- | Full data type definition for IoTTopicRuleStepFunctionsAction. See
-- 'ioTTopicRuleStepFunctionsAction' for a more convenient constructor.
data IoTTopicRuleStepFunctionsAction =
IoTTopicRuleStepFunctionsAction
{ _ioTTopicRuleStepFunctionsActionExecutionNamePrefix :: Maybe (Val Text)
, _ioTTopicRuleStepFunctionsActionRoleArn :: Val Text
, _ioTTopicRuleStepFunctionsActionStateMachineName :: Val Text
} deriving (Show, Eq)
instance ToJSON IoTTopicRuleStepFunctionsAction where
toJSON IoTTopicRuleStepFunctionsAction{..} =
object $
catMaybes
[ fmap (("ExecutionNamePrefix",) . toJSON) _ioTTopicRuleStepFunctionsActionExecutionNamePrefix
, (Just . ("RoleArn",) . toJSON) _ioTTopicRuleStepFunctionsActionRoleArn
, (Just . ("StateMachineName",) . toJSON) _ioTTopicRuleStepFunctionsActionStateMachineName
]
-- | Constructor for 'IoTTopicRuleStepFunctionsAction' containing required
-- fields as arguments.
ioTTopicRuleStepFunctionsAction
:: Val Text -- ^ 'ittrsfaRoleArn'
-> Val Text -- ^ 'ittrsfaStateMachineName'
-> IoTTopicRuleStepFunctionsAction
ioTTopicRuleStepFunctionsAction roleArnarg stateMachineNamearg =
IoTTopicRuleStepFunctionsAction
{ _ioTTopicRuleStepFunctionsActionExecutionNamePrefix = Nothing
, _ioTTopicRuleStepFunctionsActionRoleArn = roleArnarg
, _ioTTopicRuleStepFunctionsActionStateMachineName = stateMachineNamearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-stepfunctionsaction.html#cfn-iot-topicrule-stepfunctionsaction-executionnameprefix
ittrsfaExecutionNamePrefix :: Lens' IoTTopicRuleStepFunctionsAction (Maybe (Val Text))
ittrsfaExecutionNamePrefix = lens _ioTTopicRuleStepFunctionsActionExecutionNamePrefix (\s a -> s { _ioTTopicRuleStepFunctionsActionExecutionNamePrefix = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-stepfunctionsaction.html#cfn-iot-topicrule-stepfunctionsaction-rolearn
ittrsfaRoleArn :: Lens' IoTTopicRuleStepFunctionsAction (Val Text)
ittrsfaRoleArn = lens _ioTTopicRuleStepFunctionsActionRoleArn (\s a -> s { _ioTTopicRuleStepFunctionsActionRoleArn = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-stepfunctionsaction.html#cfn-iot-topicrule-stepfunctionsaction-statemachinename
ittrsfaStateMachineName :: Lens' IoTTopicRuleStepFunctionsAction (Val Text)
ittrsfaStateMachineName = lens _ioTTopicRuleStepFunctionsActionStateMachineName (\s a -> s { _ioTTopicRuleStepFunctionsActionStateMachineName = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/IoTTopicRuleStepFunctionsAction.hs
|
mit
| 2,945
| 0
| 13
| 268
| 356
| 202
| 154
| 34
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.