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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
yes = foo (elem x y) | mpickering/hlint-refactor | tests/examples/Default41.hs | bsd-3-clause | 20 | 0 | 7 | 5 | 17 | 8 | 9 | 1 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2013
--
-----------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
module SPARC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import SPARC.Base
import SPARC.CodeGen.Sanity
import SPARC.CodeGen.Amode
import SPARC.CodeGen.CondCode
import SPARC.CodeGen.Gen64
import SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.Ppr ()
import SPARC.Instr
import SPARC.Imm
import SPARC.AddrMode
import SPARC.Regs
import SPARC.Stack
import Instruction
import Size
import NCGMonad
-- Our intermediate code:
import BlockId
import Cmm
import CmmUtils
import Hoopl
import PIC
import Reg
import CLabel
import CPrim
-- The rest:
import BasicTypes
import DynFlags
import FastString
import OrdList
import Outputable
import Platform
import Unique
import Control.Monad ( mapAndUnzipM )
-- | Top level code generation
cmmTopCodeGen :: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph)
= do let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
let tops = proc : concat statics
return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
-- | Do code generation on a single block of CMM code.
-- 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.
basicBlockCodeGen :: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (CmmEntry id, nodes, tail) = blockSplit block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
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)
-- do intra-block sanity checking
blocksChecked
= map (checkBlock block)
$ BasicBlock id top : other_blocks
return (blocksChecked, statics)
-- | Convert some Cmm statements to SPARC instructions.
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))
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode size reg src
| 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
| 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"
{-
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)
-- -----------------------------------------------------------------------------
-- 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
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
assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
r <- getRegister src
let dst = getRegisterReg (targetPlatform dflags) reg
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` OR False g0 (RIReg freg) dst
-- Floating point assignment to memory
assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_FltCode pk addr src = do
dflags <- getDynFlags
Amode dst__2 code1 <- getAmode addr
(src__2, code2) <- getSomeReg src
tmp1 <- getNewRegNat pk
let
pk__2 = cmmExprType dflags src
code__2 = code1 `appOL` code2 `appOL`
if sizeToWidth pk == typeWidth pk__2
then unitOL (ST pk src__2 dst__2)
else toOL [ FxTOy (cmmTypeSize pk__2) pk src__2 tmp1
, ST pk tmp1 dst__2]
return code__2
-- Floating point assignment to a register/temporary
assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_FltCode pk dstCmmReg srcCmmExpr = do
dflags <- getDynFlags
let platform = targetPlatform dflags
srcRegister <- getRegister srcCmmExpr
let dstReg = getRegisterReg platform dstCmmReg
return $ case srcRegister of
Any _ code -> code dstReg
Fixed _ srcFixedReg srcCode -> srcCode `snocOL` FMOV pk srcFixedReg dstReg
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (toOL [CALL (Left target) 0 True, NOP])
where
target = ImmCLbl lbl
genJump tree
= do
(target, code) <- getSomeReg tree
return (code `snocOL` JMP (AddrRegReg target g0) `snocOL` NOP)
-- -----------------------------------------------------------------------------
-- 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.
SPARC: First, we have to ensure that the condition codes are set
according to the supplied comparison operation. We generate slightly
different code for floating point comparisons, because a floating
point operation cannot directly precede a @BF@. We assume the worst
and fill that slot with a @NOP@.
SPARC: Do not fill the delay slots here; you will confuse the register
allocator.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump bid bool = do
CondCode is_float cond code <- getCondCode bool
return (
code `appOL`
toOL (
if is_float
then [NOP, BF cond False bid, NOP]
else [BI cond False bid, NOP]
)
)
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> [Maybe BlockId] -> NatM InstrBlock
genSwitch dflags expr ids
| gopt Opt_PIC dflags
= error "MachCodeGen: sparc genSwitch PIC not finished\n"
| otherwise
= do (e_reg, e_code) <- getSomeReg expr
base_reg <- getNewRegNat II32
offset_reg <- getNewRegNat II32
dst <- getNewRegNat II32
label <- getNewLabelNat
return $ e_code `appOL`
toOL
[ -- load base of jump table
SETHI (HI (ImmCLbl label)) base_reg
, OR False base_reg (RIImm $ LO $ ImmCLbl label) base_reg
-- the addrs in the table are 32 bits wide..
, SLL e_reg (RIImm $ ImmInt 2) offset_reg
-- load and jump to the destination
, LD II32 (AddrRegReg base_reg offset_reg) dst
, JMP_TBL (AddrRegImm dst (ImmInt 0)) ids label
, NOP ]
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids label) =
let jumpTable = map (jumpTableEntry dflags) ids
in Just (CmmData ReadOnlyData (Statics label jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- 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.
The SPARC calling convention is an absolute
nightmare. The first 6x32 bits of arguments are mapped into
%o0 through %o5, and the remaining arguments are dumped to the
stack, beginning at [%sp+92]. (Note that %o6 == %sp.)
If we have to put args on the stack, move %o6==%sp down by
the number of words to go on the stack, to ensure there's enough space.
According to Fraser and Hanson's lcc book, page 478, fig 17.2,
16 words above the stack pointer is a word for the address of
a structure return value. I use this as a temporary location
for moving values from float to int regs. Certainly it isn't
safe to put anything in the 16 words starting at %sp, since
this area can get trashed at any time due to window overflows
caused by signal handlers.
A final complication (if the above isn't enough) is that
we can't blithely calculate the arguments one by one into
%o0 .. %o5. Consider the following nested calls:
fff a (fff b c)
Naive code moves a into %o0, and (fff b c) into %o1. Unfortunately
the inner call will itself use %o0, which trashes the value put there
in preparation for the outer call. Upshot: we need to calculate the
args into temporary regs, and move those to arg regs or onto the
stack only immediately prior to the call proper. Sigh.
-}
genCCall
:: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
-- On SPARC under TSO (Total Store Ordering), writes earlier in the instruction stream
-- are guaranteed to take place before writes afterwards (unlike on PowerPC).
-- Ref: Section 8.4 of the SPARC V9 Architecture manual.
--
-- In the SPARC case we don't need a barrier.
--
genCCall (PrimTarget MO_WriteBarrier) _ _
= return $ nilOL
genCCall (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall target dest_regs args0
= do
-- need to remove alignment information
let args | PrimTarget mop <- target,
(mop == MO_Memcpy ||
mop == MO_Memset ||
mop == MO_Memmove)
= init args0
| otherwise
= args0
-- work out the arguments, and assign them to integer regs
argcode_and_vregs <- mapM arg_to_int_vregs args
let (argcodes, vregss) = unzip argcode_and_vregs
let vregs = concat vregss
let n_argRegs = length allArgRegs
let n_argRegs_used = min (length vregs) n_argRegs
-- deal with static vs dynamic call targets
callinsns <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ ->
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
ForeignTarget expr _
-> do (dyn_c, [dyn_r]) <- arg_to_int_vregs expr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
PrimTarget mop
-> do res <- outOfLineMachOp mop
lblOrMopExpr <- case res of
Left lbl -> do
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
Right mopExpr -> do
(dyn_c, [dyn_r]) <- arg_to_int_vregs mopExpr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
return lblOrMopExpr
let argcode = concatOL argcodes
let (move_sp_down, move_sp_up)
= let diff = length vregs - n_argRegs
nn = if odd diff then diff + 1 else diff -- keep 8-byte alignment
in if nn <= 0
then (nilOL, nilOL)
else (unitOL (moveSp (-1*nn)), unitOL (moveSp (1*nn)))
let transfer_code
= toOL (move_final vregs allArgRegs extraStackArgsHere)
dflags <- getDynFlags
return
$ argcode `appOL`
move_sp_down `appOL`
transfer_code `appOL`
callinsns `appOL`
unitOL NOP `appOL`
move_sp_up `appOL`
assign_code (targetPlatform dflags) dest_regs
-- | Generate code to calculate an argument, and move it into one
-- or two integer vregs.
arg_to_int_vregs :: CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs arg = do dflags <- getDynFlags
arg_to_int_vregs' dflags arg
arg_to_int_vregs' :: DynFlags -> CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs' dflags arg
-- If the expr produces a 64 bit int, then we can just use iselExpr64
| isWord64 (cmmExprType dflags arg)
= do (ChildCode64 code r_lo) <- iselExpr64 arg
let r_hi = getHiVRegFromLo r_lo
return (code, [r_hi, r_lo])
| otherwise
= do (src, code) <- getSomeReg arg
let pk = cmmExprType dflags arg
case cmmTypeSize pk of
-- Load a 64 bit float return value into two integer regs.
FF64 -> do
v1 <- getNewRegNat II32
v2 <- getNewRegNat II32
let code2 =
code `snocOL`
FMOV FF64 src f0 `snocOL`
ST FF32 f0 (spRel 16) `snocOL`
LD II32 (spRel 16) v1 `snocOL`
ST FF32 f1 (spRel 16) `snocOL`
LD II32 (spRel 16) v2
return (code2, [v1,v2])
-- Load a 32 bit float return value into an integer reg
FF32 -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
ST FF32 src (spRel 16) `snocOL`
LD II32 (spRel 16) v1
return (code2, [v1])
-- Move an integer return value into its destination reg.
_ -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
OR False g0 (RIReg src) v1
return (code2, [v1])
-- | Move args from the integer vregs into which they have been
-- marshalled, into %o0 .. %o5, and the rest onto the stack.
--
move_final :: [Reg] -> [Reg] -> Int -> [Instr]
-- all args done
move_final [] _ _
= []
-- out of aregs; move to stack
move_final (v:vs) [] offset
= ST II32 v (spRel offset)
: move_final vs [] (offset+1)
-- move into an arg (%o[0..5]) reg
move_final (v:vs) (a:az) offset
= OR False g0 (RIReg v) a
: move_final vs az offset
-- | Assign results returned from the call into their
-- destination regs.
--
assign_code :: Platform -> [LocalReg] -> OrdList Instr
assign_code _ [] = nilOL
assign_code platform [dest]
= let rep = localRegType dest
width = typeWidth rep
r_dest = getRegisterReg platform (CmmLocal dest)
result
| isFloatType rep
, W32 <- width
= unitOL $ FMOV FF32 (regSingle $ fReg 0) r_dest
| isFloatType rep
, W64 <- width
= unitOL $ FMOV FF64 (regSingle $ fReg 0) r_dest
| not $ isFloatType rep
, W32 <- width
= unitOL $ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest
| not $ isFloatType rep
, W64 <- width
, r_dest_hi <- getHiVRegFromLo r_dest
= toOL [ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest_hi
, mkRegRegMoveInstr platform (regSingle $ oReg 1) r_dest]
| otherwise
= panic "SPARC.CodeGen.GenCCall: no match"
in result
assign_code _ _
= panic "SPARC.CodeGen.GenCCall: no match"
-- | Generate a call to implement an out-of-line floating point operation
outOfLineMachOp
:: CallishMachOp
-> NatM (Either CLabel CmmExpr)
outOfLineMachOp mop
= do let functionName
= outOfLineMachOp_table mop
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference
$ mkForeignLabel functionName Nothing ForeignLabelInExternalPackage IsFunction
let mopLabelOrExpr
= case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return mopLabelOrExpr
-- | Decide what C function to use to implement a CallishMachOp
--
outOfLineMachOp_table
:: CallishMachOp
-> FastString
outOfLineMachOp_table mop
= case mop of
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Pwr -> fsLit "powf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Pwr -> fsLit "pow"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_UF_Conv w -> fsLit $ word2FloatLabel w
MO_Memcpy -> fsLit "memcpy"
MO_Memset -> fsLit "memset"
MO_Memmove -> fsLit "memmove"
MO_BSwap w -> fsLit $ bSwapLabel w
MO_PopCnt w -> fsLit $ popCntLabel w
MO_AtomicRMW w amop -> fsLit $ atomicRMWLabel w amop
MO_Cmpxchg w -> fsLit $ cmpxchgLabel w
MO_AtomicRead w -> fsLit $ atomicReadLabel w
MO_AtomicWrite w -> fsLit $ atomicWriteLabel w
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _) -> unsupported
where unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
| holzensp/ghc | compiler/nativeGen/SPARC/CodeGen.hs | bsd-3-clause | 22,539 | 0 | 29 | 7,505 | 4,566 | 2,268 | 2,298 | 382 | 44 |
--------------------------------------------------------------------------------
-- |
-- Module : LoadShaders
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- Utilities for shader handling, adapted from LoadShaders.cpp which is (c) The
-- Red Book Authors.
--
--------------------------------------------------------------------------------
module LoadShaders (
ShaderSource(..), ShaderInfo(..), loadShaders
) where
import Control.Exception
import Control.Monad
import qualified Data.ByteString as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Graphics.Rendering.OpenGL
--------------------------------------------------------------------------------
-- | The source of the shader source code.
data ShaderSource =
ByteStringSource B.ByteString
-- ^ The shader source code is directly given as a 'B.ByteString'.
| StringSource String
-- ^ The shader source code is directly given as a 'String'.
| FileSource FilePath
-- ^ The shader source code is located in the file at the given 'FilePath'.
deriving ( Eq, Ord, Show )
getSource :: ShaderSource -> IO B.ByteString
getSource (ByteStringSource bs) = return bs
getSource (StringSource str) = return $ packUtf8 str
getSource (FileSource path) = B.readFile path
packUtf8 :: String -> B.ByteString
packUtf8 = TE.encodeUtf8 . T.pack
--------------------------------------------------------------------------------
-- | A description of a shader: The type of the shader plus its source code.
data ShaderInfo = ShaderInfo ShaderType ShaderSource
deriving ( Eq, Ord, Show )
--------------------------------------------------------------------------------
-- | Create a new program object from the given shaders, throwing an
-- 'IOException' if something goes wrong.
loadShaders :: [ShaderInfo] -> IO Program
loadShaders infos =
createProgram `bracketOnError` deleteObjectName $ \program -> do
loadCompileAttach program infos
linkAndCheck program
return program
linkAndCheck :: Program -> IO ()
linkAndCheck = checked linkProgram linkStatus programInfoLog "link"
loadCompileAttach :: Program -> [ShaderInfo] -> IO ()
loadCompileAttach _ [] = return ()
loadCompileAttach program (ShaderInfo shType source : infos) =
createShader shType `bracketOnError` deleteObjectName $ \shader -> do
src <- getSource source
shaderSourceBS shader $= src
compileAndCheck shader
attachShader program shader
loadCompileAttach program infos
compileAndCheck :: Shader -> IO ()
compileAndCheck = checked compileShader compileStatus shaderInfoLog "compile"
checked :: (t -> IO ())
-> (t -> GettableStateVar Bool)
-> (t -> GettableStateVar String)
-> String
-> t
-> IO ()
checked action getStatus getInfoLog message object = do
action object
ok <- get (getStatus object)
unless ok $ do
infoLog <- get (getInfoLog object)
fail (message ++ " log: " ++ infoLog)
| fujiyan/toriaezuzakki | haskell/opengl/uniform-matrix/LoadShaders.hs | bsd-2-clause | 3,108 | 0 | 13 | 569 | 622 | 329 | 293 | 52 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
-- | Args parser test suite.
module Stack.ArgsSpec where
import Control.Monad
import Data.Attoparsec.Args (EscapingMode(..), parseArgsFromString)
import Data.Attoparsec.Interpreter (interpreterArgsParser)
import qualified Data.Attoparsec.Text as P
import Data.Text (pack)
import Stack.Constants (stackProgName)
import Stack.Prelude
import Test.Hspec
import Prelude (head)
-- | Test spec.
spec :: Spec
spec = do
argsSpec
interpreterArgsSpec
argsSpec :: Spec
argsSpec = forM_ argsInputOutput
(\(input,output) -> it input (parseArgsFromString Escaping input == output))
-- | Fairly comprehensive checks.
argsInputOutput :: [(String, Either String [String])]
argsInputOutput =
[ ("x", Right ["x"])
, ("x y z", Right ["x", "y", "z"])
, ("aaa bbb ccc", Right ["aaa", "bbb", "ccc"])
, (" aaa bbb ccc ", Right ["aaa", "bbb", "ccc"])
, ("aaa\"", Left "unterminated string: endOfInput")
, ("\"", Left "unterminated string: endOfInput")
, ("\"\"", Right [""])
, ("\"aaa", Left "unterminated string: endOfInput")
, ("\"aaa\" bbb ccc \"ddd\"", Right ["aaa", "bbb", "ccc", "ddd"])
, ("\"aa\\\"a\" bbb ccc \"ddd\"", Right ["aa\"a", "bbb", "ccc", "ddd"])
, ("\"aa\\\"a\" bb\\b ccc \"ddd\"", Right ["aa\"a", "bb\\b", "ccc", "ddd"])
, ("\"\" \"\" c", Right ["","","c"])]
interpreterArgsSpec :: Spec
interpreterArgsSpec =
describe "Script interpreter parser" $ do
describe "Success cases" $ do
describe "Line comments" $ do
checkLines ""
checkLines " --x"
checkLines " --x --y"
describe "Literate line comments" $ do
checkLiterateLines ""
checkLiterateLines " --x"
checkLiterateLines " --x --y"
describe "Block comments" $ do
checkBlocks ""
checkBlocks "\n"
checkBlocks " --x"
checkBlocks "\n--x"
checkBlocks " --x --y"
checkBlocks "\n--x\n--y"
checkBlocks "\n\t--x\n\t--y"
describe "Literate block comments" $ do
checkLiterateBlocks "" ""
checkLiterateBlocks "\n>" ""
checkLiterateBlocks " --x" " --x"
checkLiterateBlocks "\n>--x" "--x"
checkLiterateBlocks " --x --y " "--x --y"
checkLiterateBlocks "\n>--x\n>--y" "--x --y"
checkLiterateBlocks "\n>\t--x\n>\t--y" "--x --y"
describe "Failure cases" $ do
checkFailures
describe "Bare directives in literate files" $ do
forM_ (interpreterGenValid lineComment []) $
testAndCheck (acceptFailure True) []
forM_ (interpreterGenValid blockComment []) $
testAndCheck (acceptFailure True) []
where
parse isLiterate s =
P.parseOnly (interpreterArgsParser isLiterate stackProgName) (pack s)
acceptSuccess :: Bool -> String -> String -> Bool
acceptSuccess isLiterate args s = case parse isLiterate s of
Right x | words x == words args -> True
_ -> False
acceptFailure isLiterate _ s = case parse isLiterate s of
Left _ -> True
Right _ -> False
showInput i = "BEGIN =>" ++ i ++ "<= END"
testAndCheck checker out inp = it (showInput inp) $ checker out inp
checkLines args = forM_
(interpreterGenValid lineComment args)
(testAndCheck (acceptSuccess False) args)
checkLiterateLines args = forM_
(interpreterGenValid literateLineComment args)
(testAndCheck (acceptSuccess True) args)
checkBlocks args = forM_
(interpreterGenValid blockComment args)
(testAndCheck (acceptSuccess False) args)
checkLiterateBlocks inp args = forM_
(interpreterGenValid literateBlockComment inp)
(testAndCheck (acceptSuccess True) args)
checkFailures = forM_
interpreterGenInvalid
(testAndCheck (acceptFailure False) "unused")
-- Generate a set of acceptable inputs for given format and args
interpreterGenValid fmt args = shebang <++> newLine <++> fmt args
interpreterGenInvalid :: [String]
-- Generate a set of Invalid inputs
interpreterGenInvalid =
["-stack\n"] -- random input
-- just the shebang
<|> shebang <++> ["\n"]
-- invalid shebang
<|> blockSpace <++> [head (interpreterGenValid lineComment args)]
-- something between shebang and stack comment
<|> shebang
<++> newLine
<++> blockSpace
<++> ([head (lineComment args)] <|> [head (blockComment args)])
-- unterminated block comment
-- just chop the closing chars from a valid block comment
<|> shebang
<++> ["\n"]
<++> let
c = head (blockComment args)
l = length c - 2
in [assert (drop l c == "-}") (take l c)]
-- nested block comment
<|> shebang
<++> ["\n"]
<++> [head (blockComment "--x {- nested -} --y")]
where args = " --x --y"
(<++>) = liftA2 (++)
-- Generative grammar for the interpreter comments
shebang = ["#!/usr/bin/env stack"]
newLine = ["\n"] <|> ["\r\n"]
-- A comment may be the last line or followed by something else
postComment = [""] <|> newLine
-- A command starts with zero or more whitespace followed by "stack"
makeComment maker space args =
let makePrefix s = (s <|> [""]) <++> [stackProgName]
in (maker <$> (makePrefix space <++> [args])) <++> postComment
lineSpace = [" "] <|> ["\t"]
lineComment = makeComment makeLine lineSpace
where makeLine s = "--" ++ s
literateLineComment = makeComment ("> --" ++) lineSpace
blockSpace = lineSpace <|> newLine
blockComment = makeComment makeBlock blockSpace
where makeBlock s = "{-" ++ s ++ "-}"
literateBlockComment = makeComment
(\s -> "> {-" ++ s ++ "-}")
(lineSpace <|> map (++ ">") newLine)
| MichielDerhaeg/stack | src/test/Stack/ArgsSpec.hs | bsd-3-clause | 6,133 | 0 | 18 | 1,798 | 1,529 | 792 | 737 | 130 | 3 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Mem.Weak
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable
--
-- In general terms, a weak pointer is a reference to an object that is
-- not followed by the garbage collector - that is, the existence of a
-- weak pointer to an object has no effect on the lifetime of that
-- object. A weak pointer can be de-referenced to find out
-- whether the object it refers to is still alive or not, and if so
-- to return the object itself.
--
-- Weak pointers are particularly useful for caches and memo tables.
-- To build a memo table, you build a data structure
-- mapping from the function argument (the key) to its result (the
-- value). When you apply the function to a new argument you first
-- check whether the key\/value pair is already in the memo table.
-- The key point is that the memo table itself should not keep the
-- key and value alive. So the table should contain a weak pointer
-- to the key, not an ordinary pointer. The pointer to the value must
-- not be weak, because the only reference to the value might indeed be
-- from the memo table.
--
-- So it looks as if the memo table will keep all its values
-- alive for ever. One way to solve this is to purge the table
-- occasionally, by deleting entries whose keys have died.
--
-- The weak pointers in this library
-- support another approach, called /finalization/.
-- When the key referred to by a weak pointer dies, the storage manager
-- arranges to run a programmer-specified finalizer. In the case of memo
-- tables, for example, the finalizer could remove the key\/value pair
-- from the memo table.
--
-- Another difficulty with the memo table is that the value of a
-- key\/value pair might itself contain a pointer to the key.
-- So the memo table keeps the value alive, which keeps the key alive,
-- even though there may be no other references to the key so both should
-- die. The weak pointers in this library provide a slight
-- generalisation of the basic weak-pointer idea, in which each
-- weak pointer actually contains both a key and a value.
--
-----------------------------------------------------------------------------
module System.Mem.Weak (
-- * The @Weak@ type
Weak, -- abstract
-- * The general interface
mkWeak, -- :: k -> v -> Maybe (IO ()) -> IO (Weak v)
deRefWeak, -- :: Weak v -> IO (Maybe v)
finalize, -- :: Weak v -> IO ()
-- * Specialised versions
mkWeakPtr, -- :: k -> Maybe (IO ()) -> IO (Weak k)
addFinalizer, -- :: key -> IO () -> IO ()
mkWeakPair, -- :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))
-- replaceFinaliser -- :: Weak v -> IO () -> IO ()
-- * A precise semantics
-- $precise
) where
#ifdef __HUGS__
import Hugs.Weak
import Prelude
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.Weak
#endif
-- | A specialised version of 'mkWeak', where the key and the value are
-- the same object:
--
-- > mkWeakPtr key finalizer = mkWeak key key finalizer
--
mkWeakPtr :: k -> Maybe (IO ()) -> IO (Weak k)
mkWeakPtr key finalizer = mkWeak key key finalizer
{-|
A specialised version of 'mkWeakPtr', where the 'Weak' object
returned is simply thrown away (however the finalizer will be
remembered by the garbage collector, and will still be run
when the key becomes unreachable).
Note: adding a finalizer to a 'Foreign.ForeignPtr.ForeignPtr' using
'addFinalizer' won't work; use the specialised version
'Foreign.ForeignPtr.addForeignPtrFinalizer' instead. For discussion
see the 'Weak' type.
.
-}
addFinalizer :: key -> IO () -> IO ()
addFinalizer key finalizer = do
_ <- mkWeakPtr key (Just finalizer) -- throw it away
return ()
-- | A specialised version of 'mkWeak' where the value is actually a pair
-- of the key and value passed to 'mkWeakPair':
--
-- > mkWeakPair key val finalizer = mkWeak key (key,val) finalizer
--
-- The advantage of this is that the key can be retrieved by 'deRefWeak'
-- in addition to the value.
mkWeakPair :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))
mkWeakPair key val finalizer = mkWeak key (key,val) finalizer
{- $precise
The above informal specification is fine for simple situations, but
matters can get complicated. In particular, it needs to be clear
exactly when a key dies, so that any weak pointers that refer to it
can be finalized. Suppose, for example, the value of one weak pointer
refers to the key of another...does that keep the key alive?
The behaviour is simply this:
* If a weak pointer (object) refers to an /unreachable/
key, it may be finalized.
* Finalization means (a) arrange that subsequent calls
to 'deRefWeak' return 'Nothing'; and (b) run the finalizer.
This behaviour depends on what it means for a key to be reachable.
Informally, something is reachable if it can be reached by following
ordinary pointers from the root set, but not following weak pointers.
We define reachability more precisely as follows.
A heap object is /reachable/ if:
* It is a member of the /root set/.
* It is directly pointed to by a reachable object, other than
a weak pointer object.
* It is a weak pointer object whose key is reachable.
* It is the value or finalizer of a weak pointer object whose key is reachable.
-}
| jtojnar/haste-compiler | libraries/ghc-7.8/base/System/Mem/Weak.hs | bsd-3-clause | 5,526 | 14 | 11 | 1,101 | 317 | 204 | 113 | 18 | 1 |
-- !!! opening a file in WriteMode better truncate it
import System.IO
main = do
h <- openFile "openFile006.out" AppendMode
hPutStr h "hello, world"
size <- hFileSize h
print size
hClose h
h <- openFile "openFile006.out" WriteMode
size <- hFileSize h
print size
| urbanslug/ghc | libraries/base/tests/IO/openFile006.hs | bsd-3-clause | 282 | 0 | 8 | 63 | 82 | 34 | 48 | 10 | 1 |
module Foo where
data F = A | B
data G = A | C
| hferreiro/replay | testsuite/tests/rename/should_fail/rnfail009.hs | bsd-3-clause | 49 | 0 | 5 | 17 | 24 | 15 | 9 | 3 | 0 |
import Data.Char
import Data.List
import Data.String
import Network
import System.IO
import System.Time
import System.Exit
import Control.Monad.Reader
import Control.Exception
import Text.Printf
import Prelude hiding (catch)
server = "irc.freenode.org"
port = 6667
chan = "#rosedu"
nick = "irCri"
type Net = ReaderT Bot IO
data Bot = Bot
{ socket :: Handle
, starttime :: ClockTime
}
main :: IO ()
main = bracket connect disconnect loop
where
disconnect = hClose . socket
loop st = catch (runReaderT run st) ignore
ignore :: IOError -> IO ()
ignore = const $ return ()
connect :: IO Bot
connect = notify $ do
t <- getClockTime
h <- connectTo server (PortNumber (fromIntegral port))
hSetBuffering h NoBuffering
return (Bot h t)
where
notify a = bracket_
(printf "Connecting to %s ... " server >> hFlush stdout)
(putStrLn "done.")
a
run :: Net ()
run = do
write "NICK" nick
write "USER" (nick++" 0 * :tutorial bot")
write "JOIN" chan
asks socket >>= listen
listen :: Handle -> Net ()
listen h = forever $ do
s <- init `fmap` io (hGetLine h)
io (putStrLn s)
if ping s then pong s else eval (clean s)
where
clean = drop 1 . dropWhile (/= ':') . drop 1
ping x = "PING :" `isPrefixOf` x
pong x = write "PONG" (':' : drop 6 x)
privmsg :: String -> Net ()
privmsg s = write "PRIVMSG" (chan ++ " :" ++ s)
write :: String -> String -> Net ()
write s t = do
h <- asks socket
io $ hPrintf h "%s %s\r\n" s t
io $ printf "> %s %s\n" s t
io :: IO a -> Net a
io = liftIO
{-
dropWord :: String -> String
dropWord = unwords . drop 1 . words
-}
eval :: String -> Net ()
eval "!mmquit" = write "QUIT" ":Exiting" >> io (exitWith ExitSuccess)
--eval "!more" = privmsg "more is not implemented yet"
eval x
{-
| "!help" `isPrefixOf` x = help $ dropWord x
| "!ask" `isPrefixOf` x = ask' $ dropWord x
| "!hgrep" `isPrefixOf` x = hgrep $ dropWord x
| "!cgrep" `isPrefixOf` x = cgrep $ dropWord x
| "!stag" `isPrefixOf` x = stag $ dropWord x
| "!tags" `isPrefixOf` x = tags $ dropWord x
| "!huser" `isPrefixOf` x = huser $ dropWord x
| "!cuser" `isPrefixOf` x = cuser $ dropWord x
| "!" `isPrefixOf` x = noSuchCmd
-}
| any isDigit x = spam . read. fst . span isDigit . snd . span (not . isDigit) $ x
| otherwise = return ()
noSuchCmd :: Net ()
noSuchCmd = privmsg "No such command or invalid argument"
spam :: Integer -> Net ()
spam x = privmsg $ "Bug #" ++ (show $ x + 1)
{-
help :: String -> Net ()
help "" = do
privmsg "irCri bot: IRC bot for Conversation Retrieval"
privmsg "Commands are: quit, help, more, ask, hgrep, cgrep, stag, tags, huser, cuser"
help "quit" = privmsg "quit : Forces the bot to leave the channel."
help "help" = privmsg "help : Shows the generic help message."
help "more" = privmsg "more : Displays more lines from the last output."
help "ask" = privmsg "ask QUESTION : Retrieve conversations for QUESTION."
help "hgrep" = privmsg "hgrep PATTERN : Searches for PATTERN in conversation headers"
help "cgrep" = privmsg "cgrep PATTERN : Searches for PATTERN in entire conversation"
help "stag" = privmsg "stag TAG : Searches for conversations matching TAG"
help "tags" = privmsg "tags : Lists all tags"
help "huser" = privmsg "huser USER : Shows conversations initiated by USER"
help "cuser" = privmsg "cuser USER : Shows conversations in which USER participated"
help _ = noSuchCmd
ask' :: String -> Net ()
ask' _ = privmsg "Command not implemented yet"
hgrep :: String -> Net ()
hgrep _ = privmsg "Command not implemented yet"
cgrep :: String -> Net ()
cgrep _ = privmsg "Command not implemented yet"
stag :: String -> Net ()
stag _ = privmsg "Command not implemented yet"
tags :: String -> Net ()
tags _ = privmsg "Command not implemented yet"
huser :: String -> Net ()
huser _ = privmsg "Command not implemented yet"
cuser :: String -> Net ()
cuser _ = privmsg "Command not implemented yet"
-}
| mihaimaruseac/blog-demos | ircri/bot.hs | mit | 3,951 | 0 | 13 | 872 | 809 | 403 | 406 | 67 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Memento.Types
( Memento(..)
, runMemento
, startMemento
, lookupEnv
, requireEnv
, newMementoEnv
, liftIO
) where
import Control.Monad.State
import Memento.Config
import Control.Applicative
import qualified Data.Text as T
import Data.Configurator.Types
import Data.Configurator as Cfg
--------------------------------------------------------------------------------
data MementoEnv = MementoEnv {
config :: Config
}
newtype Memento a = Memento {
unMemento :: StateT MementoEnv IO a
} deriving (Functor, Applicative, Monad, MonadState MementoEnv, MonadIO)
--------------------------------------------------------------------------------
newMementoEnv :: IO MementoEnv
newMementoEnv = do
checkConfig
home <- userHomePath
MementoEnv <$> load [Required $ T.unpack $ mementoCfgPath home]
--------------------------------------------------------------------------------
lookupEnv :: Configured a => Name -> Memento (Maybe a)
lookupEnv key = do
env <- get
liftIO $ Cfg.lookup (config env) key
--------------------------------------------------------------------------------
requireEnv :: Configured a => Name -> Memento a
requireEnv key = do
env <- get
liftIO $ Cfg.require (config env) key
--------------------------------------------------------------------------------
runMemento :: MementoEnv -> Memento a -> IO a
runMemento env action = flip evalStateT env $ unMemento action
--------------------------------------------------------------------------------
startMemento :: Memento a -> IO a
startMemento action = do
env <- newMementoEnv
runMemento env action
| adinapoli/memento | src/Memento/Types.hs | mit | 1,691 | 0 | 12 | 231 | 381 | 202 | 179 | 40 | 1 |
module Types where
import Control.Monad.Error
import Text.ParserCombinators.Parsec (ParseError)
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| Float Double
| String String
| Char Char
| Bool Bool
instance Show LispVal where
show = showVal
showVal :: LispVal -> String
showVal (Atom name) = name
showVal (List contents) = "(" ++ showListContents contents ++ ")"
showVal (DottedList head tail) = "(" ++ showListContents head ++ " . " ++ showVal tail ++ ")"
showVal (Number n) = show n
showVal (Float d) = show d
showVal (String s) = "\"" ++ s ++ "\""
showVal (Char c) = "\\#" ++ case c of
' ' -> "space"
'\n' -> "newline"
'\t' -> "\\t"
'\r' -> "\\r"
_ -> [c]
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showListContents = unwords . map showVal
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Default String
showError :: LispError -> String
showError (UnboundVar message varname) = message ++ ": " ++ varname
showError (BadSpecialForm message form) = message ++ ": " ++ show form
showError (NotFunction message func) = message ++ ": " ++ show func
showError (NumArgs expected found) = "Expected " ++ show expected
++ " args; found values " ++ unwordsList found
showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected
++ ", found " ++ show found
showError (Parser parseErr) = "Parse error at " ++ show parseErr
instance Show LispError where
show = showError
instance Error LispError where
noMsg = Default "An error has occurred"
strMsg = Default
type ThrowsError = Either LispError
trapError action = catchError action (return . show)
extractValue :: ThrowsError a -> a
extractValue (Right val) = val
| dstruthers/WYAS | Types.hs | mit | 2,221 | 0 | 9 | 651 | 661 | 342 | 319 | 56 | 5 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Codec.Xlsx.Types
( Xlsx(..), xlSheets, xlStyles
, def
, Styles(..)
, emptyStyles
, ColumnsWidth(..)
, Worksheet(..), wsColumns, wsRowPropertiesMap, wsCells, wsMerges
, CellMap
, CellValue(..)
, Cell(..), cellValue, cellStyle
, RowProperties (..)
, int2col
, col2int
, toRows
, fromRows
) where
import Control.Lens.TH
import qualified Data.ByteString.Lazy as L
import Data.Char
import Data.Default
import Data.Function (on)
import Data.List (groupBy)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text as T
-- | Cell values include text, numbers and booleans,
-- standard includes date format also but actually dates
-- are represented by numbers with a date format assigned
-- to a cell containing it
data CellValue = CellText Text
| CellDouble Double
| CellBool Bool
deriving (Eq, Show)
-- | Currently cell details include only cell values and style ids
-- (e.g. formulas from @\<f\>@ and inline strings from @\<is\>@
-- subelements are ignored)
data Cell = Cell
{ _cellStyle :: Maybe Int
, _cellValue :: Maybe CellValue
} deriving (Eq, Show)
makeLenses ''Cell
instance Default Cell where
def = Cell Nothing Nothing
type CellMap = Map (Int, Int) Cell
data RowProperties = RowProps { rowHeight :: Maybe Double, rowStyle::Maybe Int}
deriving (Read,Eq,Show,Ord)
-- | Column range (from cwMin to cwMax) width
data ColumnsWidth = ColumnsWidth
{ cwMin :: Int
, cwMax :: Int
, cwWidth :: Double
, cwStyle :: Int
} deriving (Eq, Show)
-- | Xlsx worksheet
data Worksheet = Worksheet
{ _wsColumns :: [ColumnsWidth] -- ^ column widths
, _wsRowPropertiesMap :: Map Int RowProperties -- ^ custom row properties (height, style) map
, _wsCells :: CellMap -- ^ data mapped by (row, column) pairs
, _wsMerges :: [Text]
} deriving (Eq, Show)
makeLenses ''Worksheet
instance Default Worksheet where
def = Worksheet [] M.empty M.empty []
newtype Styles = Styles {unStyles :: L.ByteString}
deriving (Eq, Show)
-- | Structured representation of Xlsx file (currently a subset of its contents)
data Xlsx = Xlsx
{ _xlSheets :: Map Text Worksheet
, _xlStyles :: Styles
} deriving (Eq, Show)
makeLenses ''Xlsx
instance Default Xlsx where
def = Xlsx M.empty emptyStyles
emptyStyles :: Styles
emptyStyles = Styles "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\
\<styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"></styleSheet>"
-- | convert column number (starting from 1) to its textual form (e.g. 3 -> \"C\")
int2col :: Int -> Text
int2col = T.pack . reverse . map int2let . base26
where
int2let 0 = 'Z'
int2let x = chr $ (x - 1) + ord 'A'
base26 0 = []
base26 i = let i' = (i `mod` 26)
i'' = if i' == 0 then 26 else i'
in seq i' (i' : base26 ((i - i'') `div` 26))
-- | reverse to 'int2col'
col2int :: Text -> Int
col2int = T.foldl' (\i c -> i * 26 + let2int c) 0
where
let2int c = 1 + ord c - ord 'A'
-- | converts cells mapped by (row, column) into rows which contain
-- row index and cells as pairs of column indices and cell values
toRows :: CellMap -> [(Int, [(Int, Cell)])]
toRows cells =
map extractRow $ groupBy ((==) `on` (fst . fst)) $ M.toList cells
where
extractRow row@(((x,_),_):_) =
(x, map (\((_,y),v) -> (y,v)) row)
extractRow _ = error "invalid CellMap row"
-- | reverse to 'toRows'
fromRows :: [(Int, [(Int, Cell)])] -> CellMap
fromRows rows = M.fromList $ concatMap mapRow rows
where
mapRow (r, cells) = map (\(c, v) -> ((r, c), v)) cells
| lookunder/xlsx | src/Codec/Xlsx/Types.hs | mit | 4,035 | 0 | 16 | 1,066 | 1,067 | 621 | 446 | 88 | 4 |
comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb _ [] = []
comb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs
readInts :: IO [Int]
readInts = fmap (map read . words) getLine
listToString :: Show a => [a] -> String
listToString xs = unwords (map show xs)
main :: IO ()
main = do
[k, n] <- readInts
mapM_ (putStrLn . listToString) (comb k [0..n-1])
| da-eto-ya/trash | haskell/simplest/binomial.hs | mit | 371 | 0 | 11 | 96 | 231 | 120 | 111 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.MPD.Applicative.PlaybackControlSpec (main, spec) where
import TestUtil
import Network.MPD.Applicative.PlaybackControl
import Network.MPD.Commands.Types
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "next" $ do
it "sends a next request" $ do
next `with` [("next", Right "OK")] `shouldBe` Right ()
describe "play" $ do
it "sends a play request" $ do
play Nothing `with` [("play", Right "OK")] `shouldBe` Right ()
it "optionally takes a position to start playback at" $ do
play (Just 1) `with` [("play 1", Right "OK")] `shouldBe` Right ()
describe "playId" $ do
it "like 'play' but takes an id instead" $ do
playId (Id 1) `with` [("playid 1", Right "OK")] `shouldBe` Right ()
describe "previous" $ do
it "sends a request" $ do
previous `with` [("previous", Right "OK")] `shouldBe` Right ()
describe "seek" $ do
it "sends a seek request" $ do
seek 1 10 `with` [("seek 1 10.0", Right "OK")] `shouldBe` Right ()
describe "seekId" $ do
it "is like 'seek' but takes an id" $ do
seekId (Id 1) 10
`with` [("seekid 1 10.0", Right "OK")]
`shouldBe` Right ()
describe "stop" $ do
it "sends a stop request" $ do
stop `with` [("stop", Right "OK")] `shouldBe` Right ()
| matthewleon/libmpd-haskell | tests/Network/MPD/Applicative/PlaybackControlSpec.hs | mit | 1,491 | 0 | 17 | 472 | 505 | 259 | 246 | 34 | 1 |
module Accumulate (accumulate) where
accumulate :: (a -> b) -> [a] -> [b]
accumulate f xs = error "You need to implement this function."
| exercism/xhaskell | exercises/practice/accumulate/src/Accumulate.hs | mit | 138 | 0 | 7 | 25 | 48 | 27 | 21 | 3 | 1 |
module Main where
import Control.Monad.Trans.Free (FreeF(..), FreeT(..))
import Network.Http.Client (Connection)
import Web.Stripe.Client (StripeConfig(..), StripeError(..))
import Web.Stripe.Client.HttpStreams (withConnection, callAPI)
import Web.Stripe.Test.AllTests (allTests)
import Web.Stripe.Test.Prelude (Stripe, StripeRequestF(..))
main :: IO ()
main = allTests runStripe
runStripe :: StripeConfig
-> Stripe a
-> IO (Either StripeError a)
runStripe config stripe =
withConnection $ \conn ->
runStripe' conn config stripe
runStripe' :: Connection
-> StripeConfig
-> Stripe a
-> IO (Either StripeError a)
runStripe' conn config (FreeT m) =
do f <- m
case f of
(Pure a) -> return (Right a)
(Free (StripeRequestF req decode')) ->
do r <- callAPI conn decode' config req
case r of
(Left e) -> return (Left e)
(Right next) -> runStripe' conn config next
| dmjio/stripe | stripe-http-streams/tests/Main.hs | mit | 1,094 | 0 | 17 | 355 | 344 | 186 | 158 | 28 | 3 |
import Data.List
fibs :: [Int]
fibs = unfoldr (\(a,b) -> Just (a, (b,a+b)) ) (0,1)
result :: Int
result = sum $ filter (\x -> odd x) $ takeWhile (\x -> x < 4000000) fibs
main = putStrLn $ show(result)
| nbartlomiej/haskeuler | 002/problem-002.hs | mit | 204 | 0 | 11 | 43 | 127 | 71 | 56 | 6 | 1 |
module TestReentrantLock where
import Control.Concurrent.ReentrantLock
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Test.Tasty
import Test.Tasty.QuickCheck
test_lockThenUnlock = do
lock <- run new
mAcq <- run $ tryAcquire lock
assert $ isJust mAcq
case mAcq of
Nothing -> return ()
Just acq -> do
release acq
assert . not =<< run $ locked lock
reentrantLockTests =
[ testProperty "acquire then release" prop_lockThenUnlock
-- , testProperty "acquire, await, signal" prop_lockWithCondition
]
| iand675/disruptor | test/TestReentrantLock.hs | mit | 589 | 0 | 12 | 149 | 136 | 68 | 68 | 17 | 2 |
module Main where
import Test.Tasty as Tasty
import Aeson ( callbackTests
, requestTests
, responseTests
, staticTests
)
import UnitTest
main :: IO ()
main = Tasty.defaultMain $ Tasty.testGroup
"\nWeb.Facebook.Messenger"
[ aesonTests
, unitTests
]
aesonTests :: TestTree
aesonTests = Tasty.testGroup
"Aeson"
[ staticTests
, requestTests
, responseTests
, callbackTests
]
unitTests :: TestTree
unitTests = Tasty.testGroup
"Unit Tests"
[ profileRequestTest
, shortFunctionTests
, parseCallbackTests
, parseRequestTests
, parseResponseTests
]
| Vlix/facebookmessenger | test/Spec.hs | mit | 723 | 0 | 7 | 253 | 126 | 75 | 51 | 27 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Language.LSP.Types.DocumentSymbol where
import Data.Aeson
import Data.Aeson.TH
import Data.Scientific
import Data.Text (Text)
import Language.LSP.Types.TextDocument
import Language.LSP.Types.Common
import Language.LSP.Types.Location
import Language.LSP.Types.Progress
import Language.LSP.Types.Utils
-- ---------------------------------------------------------------------
makeExtendingDatatype "DocumentSymbolOptions"
[''WorkDoneProgressOptions]
[ ("_label", [t| Maybe Bool |])]
deriveJSON lspOptions ''DocumentSymbolOptions
makeExtendingDatatype "DocumentSymbolRegistrationOptions"
[ ''TextDocumentRegistrationOptions
, ''DocumentSymbolOptions
] []
deriveJSON lspOptions ''DocumentSymbolRegistrationOptions
-- ---------------------------------------------------------------------
makeExtendingDatatype "DocumentSymbolParams"
[ ''WorkDoneProgressParams
, ''PartialResultParams
]
[ ("_textDocument", [t| TextDocumentIdentifier |])]
deriveJSON lspOptions ''DocumentSymbolParams
-- -------------------------------------
data SymbolKind
= SkFile
| SkModule
| SkNamespace
| SkPackage
| SkClass
| SkMethod
| SkProperty
| SkField
| SkConstructor
| SkEnum
| SkInterface
| SkFunction
| SkVariable
| SkConstant
| SkString
| SkNumber
| SkBoolean
| SkArray
| SkObject
| SkKey
| SkNull
| SkEnumMember
| SkStruct
| SkEvent
| SkOperator
| SkTypeParameter
| SkUnknown Scientific
deriving (Read,Show,Eq)
instance ToJSON SymbolKind where
toJSON SkFile = Number 1
toJSON SkModule = Number 2
toJSON SkNamespace = Number 3
toJSON SkPackage = Number 4
toJSON SkClass = Number 5
toJSON SkMethod = Number 6
toJSON SkProperty = Number 7
toJSON SkField = Number 8
toJSON SkConstructor = Number 9
toJSON SkEnum = Number 10
toJSON SkInterface = Number 11
toJSON SkFunction = Number 12
toJSON SkVariable = Number 13
toJSON SkConstant = Number 14
toJSON SkString = Number 15
toJSON SkNumber = Number 16
toJSON SkBoolean = Number 17
toJSON SkArray = Number 18
toJSON SkObject = Number 19
toJSON SkKey = Number 20
toJSON SkNull = Number 21
toJSON SkEnumMember = Number 22
toJSON SkStruct = Number 23
toJSON SkEvent = Number 24
toJSON SkOperator = Number 25
toJSON SkTypeParameter = Number 26
toJSON (SkUnknown x) = Number x
instance FromJSON SymbolKind where
parseJSON (Number 1) = pure SkFile
parseJSON (Number 2) = pure SkModule
parseJSON (Number 3) = pure SkNamespace
parseJSON (Number 4) = pure SkPackage
parseJSON (Number 5) = pure SkClass
parseJSON (Number 6) = pure SkMethod
parseJSON (Number 7) = pure SkProperty
parseJSON (Number 8) = pure SkField
parseJSON (Number 9) = pure SkConstructor
parseJSON (Number 10) = pure SkEnum
parseJSON (Number 11) = pure SkInterface
parseJSON (Number 12) = pure SkFunction
parseJSON (Number 13) = pure SkVariable
parseJSON (Number 14) = pure SkConstant
parseJSON (Number 15) = pure SkString
parseJSON (Number 16) = pure SkNumber
parseJSON (Number 17) = pure SkBoolean
parseJSON (Number 18) = pure SkArray
parseJSON (Number 19) = pure SkObject
parseJSON (Number 20) = pure SkKey
parseJSON (Number 21) = pure SkNull
parseJSON (Number 22) = pure SkEnumMember
parseJSON (Number 23) = pure SkStruct
parseJSON (Number 24) = pure SkEvent
parseJSON (Number 25) = pure SkOperator
parseJSON (Number 26) = pure SkTypeParameter
parseJSON (Number x) = pure (SkUnknown x)
parseJSON _ = mempty
{-|
Symbol tags are extra annotations that tweak the rendering of a symbol.
@since 3.16.0
-}
data SymbolTag =
StDeprecated -- ^ Render a symbol as obsolete, usually using a strike-out.
| StUnknown Scientific
deriving (Read, Show, Eq)
instance ToJSON SymbolTag where
toJSON StDeprecated = Number 1
toJSON (StUnknown x) = Number x
instance FromJSON SymbolTag where
parseJSON (Number 1) = pure StDeprecated
parseJSON (Number x) = pure (StUnknown x)
parseJSON _ = mempty
-- -------------------------------------
data DocumentSymbolKindClientCapabilities =
DocumentSymbolKindClientCapabilities
{ -- | The symbol kind values the client supports. When this
-- property exists the client also guarantees that it will
-- handle values outside its set gracefully and falls back
-- to a default value when unknown.
--
-- If this property is not present the client only supports
-- the symbol kinds from `File` to `Array` as defined in
-- the initial version of the protocol.
_valueSet :: Maybe (List SymbolKind)
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''DocumentSymbolKindClientCapabilities
data DocumentSymbolTagClientCapabilities =
DocumentSymbolTagClientCapabilities
{ -- | The tags supported by the client.
_valueSet :: Maybe (List SymbolTag)
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''DocumentSymbolTagClientCapabilities
data DocumentSymbolClientCapabilities =
DocumentSymbolClientCapabilities
{ -- | Whether document symbol supports dynamic registration.
_dynamicRegistration :: Maybe Bool
-- | Specific capabilities for the `SymbolKind`.
, _symbolKind :: Maybe DocumentSymbolKindClientCapabilities
, _hierarchicalDocumentSymbolSupport :: Maybe Bool
-- | The client supports tags on `SymbolInformation`.
-- Clients supporting tags have to handle unknown tags gracefully.
--
-- @since 3.16.0
, _tagSupport :: Maybe DocumentSymbolTagClientCapabilities
-- | The client supports an additional label presented in the UI when
-- registering a document symbol provider.
--
-- @since 3.16.0
, _labelSupport :: Maybe Bool
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''DocumentSymbolClientCapabilities
-- ---------------------------------------------------------------------
-- | Represents programming constructs like variables, classes, interfaces etc.
-- that appear in a document. Document symbols can be hierarchical and they
-- have two ranges: one that encloses its definition and one that points to its
-- most interesting range, e.g. the range of an identifier.
data DocumentSymbol =
DocumentSymbol
{ _name :: Text -- ^ The name of this symbol.
-- | More detail for this symbol, e.g the signature of a function. If not
-- provided the name is used.
, _detail :: Maybe Text
, _kind :: SymbolKind -- ^ The kind of this symbol.
, _tags :: Maybe (List SymbolTag) -- ^ Tags for this document symbol.
, _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead.
-- | The range enclosing this symbol not including leading/trailing
-- whitespace but everything else like comments. This information is
-- typically used to determine if the the clients cursor is inside the symbol
-- to reveal in the symbol in the UI.
, _range :: Range
-- | The range that should be selected and revealed when this symbol is being
-- picked, e.g the name of a function. Must be contained by the the '_range'.
, _selectionRange :: Range
-- | Children of this symbol, e.g. properties of a class.
, _children :: Maybe (List DocumentSymbol)
} deriving (Read,Show,Eq)
deriveJSON lspOptions ''DocumentSymbol
-- ---------------------------------------------------------------------
-- | Represents information about programming constructs like variables, classes,
-- interfaces etc.
data SymbolInformation =
SymbolInformation
{ _name :: Text -- ^ The name of this symbol.
, _kind :: SymbolKind -- ^ The kind of this symbol.
, _tags :: Maybe (List SymbolTag) -- ^ Tags for this symbol.
, _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead.
-- | The location of this symbol. The location's range is used by a tool
-- to reveal the location in the editor. If the symbol is selected in the
-- tool the range's start information is used to position the cursor. So
-- the range usually spans more then the actual symbol's name and does
-- normally include things like visibility modifiers.
--
-- The range doesn't have to denote a node range in the sense of a abstract
-- syntax tree. It can therefore not be used to re-construct a hierarchy of
-- the symbols.
, _location :: Location
-- | The name of the symbol containing this symbol. This information is for
-- user interface purposes (e.g. to render a qualifier in the user interface
-- if necessary). It can't be used to re-infer a hierarchy for the document
-- symbols.
, _containerName :: Maybe Text
} deriving (Read,Show,Eq)
{-# DEPRECATED _deprecated "Use tags instead" #-}
deriveJSON lspOptions ''SymbolInformation
| alanz/haskell-lsp | lsp-types/src/Language/LSP/Types/DocumentSymbol.hs | mit | 9,369 | 0 | 11 | 2,250 | 1,629 | 864 | 765 | 165 | 0 |
module Iseq
where
import Types
iNil :: Iseq
iNil = INil
iStr :: String -> Iseq
iStr s = IStr s
iAppend :: Iseq -> Iseq -> Iseq
iAppend seq1 seq2 = IAppend seq1 seq2
iNewline :: Iseq
iNewline = INewline
iComma :: Iseq
iComma = IComma
iSemiColon :: Iseq
iSemiColon = ISemiColon
iSpace :: Iseq
iSpace = ISpace
iNum :: Int -> Iseq
iNum n = iStr (show n)
iFWNum :: Int -> Int -> Iseq
iFWNum width n
= iStr (space (width - length digits) ++ digits)
where
digits = show n
iIndent :: Iseq -> Iseq
iIndent seq' = IIndent seq'
iDisplay :: Iseq -> String
iDisplay seq' = flatten 0 [(seq',0)]
iConcat :: [Iseq] -> Iseq
iConcat = foldr iAppend iNil
iInterleave :: Iseq -> [Iseq] ->Iseq
iInterleave _ [] = iNil
iInterleave _ [seq'] = seq'
iInterleave sep (seq' : seqs) = seq' `iAppend` (sep `iAppend` iInterleave sep seqs)
flatten :: Int -> [(Iseq, Int)] -> String
flatten _ [] = ""
flatten _ ((INil, indent) : seqs) = flatten indent seqs
flatten _ ((IStr s, indent) : seqs) = s ++ (flatten indent seqs)
flatten col ((IAppend seq1 seq2, indent) : seqs) = flatten indent ((seq1, col) : (seq2, col) : seqs)
flatten _ ((INewline, indent) : seqs) = '\n' : (space indent) ++ (flatten indent seqs)
flatten _ ((IComma, indent) : seqs) = ',' : ' ' : (space indent) ++ (flatten indent seqs)
flatten _ ((ISemiColon, indent) : seqs) = ';' : ' ' : (space indent) ++ (flatten indent seqs)
flatten _ ((ISpace, indent) : seqs) = ' ' : (space indent) ++ (flatten indent seqs)
flatten col ((IIndent seq', _) : seqs) = flatten col ((seq', col) : seqs)
space :: Int -> String
space 0 = ""
space n = " " ++ (space (n - 1))
iLayn :: [Iseq] -> Iseq
iLayn seqs = iConcat (map layItem (zip [1..] seqs))
where
layItem (n, s)
= iConcat [ iFWNum 4 n, iStr ") ", iIndent s, iNewline ]
-- end of file
| typedvar/hLand | hcore/Iseq.hs | mit | 1,850 | 0 | 11 | 435 | 853 | 458 | 395 | 49 | 1 |
-- Problem 6
main :: IO ()
main = print result
result :: Integer
result = sum [1..100] ^ (2 :: Integer) - sum [x * x | x <- [1..100]]
| chetaldrich/euler | haskell/006/6.hs | mit | 136 | 0 | 10 | 33 | 75 | 40 | 35 | 4 | 1 |
module Main where
import qualified Patat.Presentation.Interactive.Tests
import qualified Patat.Presentation.Read.Tests
import qualified Test.Tasty as Tasty
main :: IO ()
main = Tasty.defaultMain $ Tasty.testGroup "patat"
[ Patat.Presentation.Interactive.Tests.tests
, Patat.Presentation.Read.Tests.tests
]
| jaspervdj/patat | tests/haskell/Main.hs | gpl-2.0 | 346 | 0 | 8 | 69 | 72 | 47 | 25 | 8 | 1 |
{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-}
module Synth where
import Instruments
import Midi
import Play
import Rendering
import Types
import Wave
import Control.Monad
import Data.Maybe
import System.Console.CmdArgs
import qualified System.FilePath as Path
data Args = Args {input :: String, outputArg :: String, playArg :: Bool}
deriving (Show, Data, Typeable)
argsDefs = Args {
input = def &= typ "INPUT" &= argPos 0,
outputArg = def &= typ "OUTPUT" &= argPos 1 &= opt "",
playArg = False &= typ "BOOL" }
&= program "synth"
&= verbosity
process :: String -> String -> IO FrameStream
process input output = do
(tones, dur) <- loadMidi input
let
toneStreams = map (\tone -> (tone, render tone)) $ uniqueTones tones
findStream tone = fromJust $ lookup tone toneStreams
streams = map (\(time, tone) -> timeShift time $ findStream tone) tones
finalAudio = sumStreams streams dur
saveWave output finalAudio
return finalAudio
main :: IO ()
main = do
Args{..} <- cmdArgs argsDefs
let output = if outputArg /= "" then outputArg
else Path.replaceExtension input "wav"
finalAudio <- process input output
when playArg $ play finalAudio
| garncarz/synth-haskell | Synth.hs | gpl-2.0 | 1,171 | 16 | 15 | 214 | 420 | 219 | 201 | 37 | 2 |
-- | This module provides access to the songs which can be played with /Easy Notes/
module SongCollection where
import Songs.Fun
import Songs.HaenschenKlein
import Songs.AlleMeineEntchen
import Songs.MadWorld
import Euterpea
-- | A song should be a list of /single/, /sequential/ Music Pitches
type Song = [Music Pitch]
-- | the current collection of songs as tuples of songnames and their corresponding list of Music Pitches
songCollection :: [(String,Song)]
songCollection = [("AlleMeineEntchen",entchenList),
("AllNotes",allNotes),
("HaenschenKlein", haenschenList),
("MadWorld",madList)]
-- | list of all names of the current song collection
allSongs :: [String]
allSongs = map fst songCollection
-- | song which contains all notes from C4 to B4
allNotes :: Song
allNotes = map (pitchToMusic qn) $ map pitch [60..71] | flofehrenbacher/music-project | EasyNotes/SongCollection.hs | gpl-3.0 | 883 | 0 | 8 | 179 | 150 | 92 | 58 | 16 | 1 |
{-# LANGUAGE FlexibleContexts,MultiParamTypeClasses,FlexibleInstances,
TypeSynonymInstances,ScopedTypeVariables,FunctionalDependencies #-}
-- | Some common utilites for a MonadReader that keeps track of variables in scope
module Lang.Scope where
import Control.Monad.Reader
import Data.Set (Set)
import qualified Data.Set as S
type Scope = Set
class HasScope v t | t -> v where
get_scope :: t -> Scope v
mod_scope :: (Scope v -> Scope v) -> t -> t
instance HasScope v (Scope v) where
get_scope = id
mod_scope = id
-- | Make a scope
makeScope :: Ord v => [v] -> Set v
makeScope = S.fromList
-- | Extend the scope with a list of variables
extendScope :: (HasScope v t,MonadReader t m,Ord v) => [v] -> m a -> m a
extendScope = local . mod_scope . S.union . makeScope
-- | Removes an entry from the scope
removeFromScope :: (HasScope v t,MonadReader t m,Ord v) => v -> m a -> m a
removeFromScope = local . mod_scope . S.delete
-- | Clear the scope
clearScope :: forall v t m a . (HasScope v t,MonadReader t m) => m a -> m a
clearScope = local (mod_scope (const (emptyScope :: Scope v)))
-- | The empty scope
emptyScope :: Scope v
emptyScope = S.empty
-- | True if the variable is in scope
inScope :: (HasScope v t,MonadReader t m,Ord v) => v -> m Bool
inScope x = asks (S.member x . get_scope)
-- | Returns only the elments that are in scope
pluckScoped :: (HasScope v t,MonadReader t m,Ord v) => [v] -> m [v]
pluckScoped = filterM inScope
-- | Gets the current scope
getScope :: (HasScope v t,MonadReader t m,Ord v) => m [v]
getScope = asks (S.toList . get_scope)
| danr/tfp1 | Lang/Scope.hs | gpl-3.0 | 1,604 | 0 | 11 | 326 | 531 | 286 | 245 | 29 | 1 |
{-# LANGUAGE NoImplicitPrelude, FlexibleContexts, OverloadedStrings, TypeFamilies, Rank2Types #-}
module Lamdu.Sugar.Convert.Expression
( convert
) where
import Control.Lens.Operators
import qualified Data.ByteString as SBS
import Data.Store.Property (Property(..))
import qualified Data.Store.Property as Property
import qualified Data.Store.Transaction as Transaction
import qualified Lamdu.Builtins.PrimVal as PrimVal
import qualified Lamdu.Calc.Val as V
import Lamdu.Calc.Val.Annotated (Val(..))
import qualified Lamdu.Calc.Val.Annotated as Val
import qualified Lamdu.Expr.IRef as ExprIRef
import qualified Lamdu.Sugar.Convert.Apply as ConvertApply
import qualified Lamdu.Sugar.Convert.Binder as ConvertBinder
import qualified Lamdu.Sugar.Convert.Case as ConvertCase
import Lamdu.Sugar.Convert.Expression.Actions (addActions)
import qualified Lamdu.Sugar.Convert.GetField as ConvertGetField
import qualified Lamdu.Sugar.Convert.GetVar as ConvertGetVar
import qualified Lamdu.Sugar.Convert.Hole as ConvertHole
import qualified Lamdu.Sugar.Convert.Inject as ConvertInject
import qualified Lamdu.Sugar.Convert.Input as Input
import Lamdu.Sugar.Convert.Monad (ConvertM)
import qualified Lamdu.Sugar.Convert.Nominal as ConvertNominal
import qualified Lamdu.Sugar.Convert.Record as ConvertRecord
import Lamdu.Sugar.Internal
import Lamdu.Sugar.Types
import Prelude.Compat
convertLiteralCommon ::
Monad m =>
(Transaction.Property m a -> Literal (Transaction.Property m)) ->
(a -> PrimVal.KnownPrim) -> a ->
Input.Payload m b -> ConvertM m (ExpressionU m b)
convertLiteralCommon mkLit mkBody val exprPl =
Property
{ _pVal = val
, _pSet =
ExprIRef.writeValBody iref . V.BLeaf . V.LLiteral .
PrimVal.fromKnown . mkBody
} & mkLit & BodyLiteral & addActions exprPl
where
iref = exprPl ^. Input.stored . Property.pVal
convertLiteralFloat ::
Monad m => Double -> Input.Payload m a -> ConvertM m (ExpressionU m a)
convertLiteralFloat = convertLiteralCommon LiteralNum PrimVal.Float
convertLiteralBytes ::
Monad m => SBS.ByteString -> Input.Payload m a -> ConvertM m (ExpressionU m a)
convertLiteralBytes = convertLiteralCommon LiteralBytes PrimVal.Bytes
convert :: (Monad m, Monoid a) => Val (Input.Payload m a) -> ConvertM m (ExpressionU m a)
convert v =
v ^. Val.payload
& case v ^. Val.body of
V.BLam x -> ConvertBinder.convertLam x
V.BApp x -> ConvertApply.convert x
V.BRecExtend x -> ConvertRecord.convertExtend x
V.BGetField x -> ConvertGetField.convert x
V.BInject x -> ConvertInject.convert x
V.BToNom x -> ConvertNominal.convertToNom x
V.BFromNom x -> ConvertNominal.convertFromNom x
V.BCase x -> ConvertCase.convert x
V.BLeaf (V.LVar x) -> ConvertGetVar.convert x
V.BLeaf (V.LLiteral literal) ->
case PrimVal.toKnown literal of
PrimVal.Float x -> convertLiteralFloat x
PrimVal.Bytes x -> convertLiteralBytes x
V.BLeaf V.LHole -> ConvertHole.convert
V.BLeaf V.LRecEmpty -> ConvertRecord.convertEmpty
V.BLeaf V.LAbsurd -> ConvertCase.convertAbsurd
| da-x/lamdu | Lamdu/Sugar/Convert/Expression.hs | gpl-3.0 | 3,218 | 0 | 15 | 608 | 864 | 481 | 383 | -1 | -1 |
module Status
( isIdle, isBusy, setIdle, setBusy
, pushTask, waitTask
) where
import System.IO.Unsafe
import Control.Monad.STM
import Control.Concurrent.STM.TVar
import Control.Concurrent.STM.TChan
{-# NOINLINE busyState #-}
busyState :: TVar Bool
busyState = unsafePerformIO $ newTVarIO False
isBusy, isIdle :: IO Bool
isBusy = readTVarIO busyState
isIdle = not <$> isBusy
setBusy, setIdle :: IO ()
setBusy = atomically $ writeTVar busyState True
setIdle = atomically $ writeTVar busyState False
{-# NOINLINE chan #-}
chan :: TChan ()
chan = unsafePerformIO newTChanIO
pushTask :: IO ()
pushTask = atomically $ do
clearChan
writeTChan chan ()
where clearChan = do
result <- tryReadTChan chan
case result of
Just _ -> clearChan
Nothing -> return ()
waitTask :: IO ()
waitTask = atomically $ readTChan chan
| shouya/poi | src/Status.hs | gpl-3.0 | 871 | 0 | 13 | 186 | 255 | 137 | 118 | 30 | 2 |
-- P08 Eliminate consecutive duplicates of list elements.
import Data.List
-- Built-in functions composition
f1 :: Eq a => [a] -> [a]
f1 = map head . group
-- Recursion with dropWhile
f2 :: Eq a => [a] -> [a]
f2 [] = []
f2 (x:xs) = x : (f2 $ dropWhile (== x) xs)
-- Recursion with pattern matching (look-ahead)
f3 :: Eq a => [a] -> [a]
f3 (a:(bs@(b:_)))
| a == b = f3 bs
| otherwise = a : f3 bs
f3 xs = xs
-- Tail recursion (look-behind)
f4 :: Eq a => [a] -> [a]
f4 = f4' []
where f4' acc [] = reverse acc
f4' [] (x:xs) = f4' [x] xs
f4' ys@(y:_) (x:xs) = if y == x then f4' ys xs else f4' (x : ys) xs
-- List folding
f5 :: Eq a => [a] -> [a]
f5 [] = []
f5 xs = foldr (\a b -> if a == (head b) then b else a : b) [last xs] xs
-- Using "zip"
f6 :: Eq a => [a] -> [a]
f6 [] = []
f6 xs@(x:_) = x : map snd (filter (uncurry (/=)) (zip xs (tail xs))) | pavelfatin/ninety-nine | haskell/p08.hs | gpl-3.0 | 883 | 0 | 12 | 240 | 513 | 272 | 241 | 22 | 4 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module Lamdu.GUI.ExpressionEdit.GetFieldEdit
( make
) where
import Control.Lens.Operators
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Lamdu.GUI.ExpressionEdit.TagEdit as TagEdit
import Lamdu.GUI.ExpressionGui (ExpressionGui)
import qualified Lamdu.GUI.ExpressionGui as ExpressionGui
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT
import Lamdu.Sugar.Names.Types (Name(..))
import qualified Lamdu.Sugar.Types as Sugar
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import Prelude.Compat
make ::
Monad m =>
Sugar.GetField (Name m) (ExprGuiT.SugarExpr m) ->
Sugar.Payload m ExprGuiT.Payload ->
ExprGuiM m (ExpressionGui m)
make (Sugar.GetField recExpr tagG) pl =
ExpressionGui.stdWrapParentExpr pl $ \myId ->
do
recExprEdit <-
ExprGuiM.makeSubexpression (ExpressionGui.precRight .~ 11) recExpr
dotLabel <- ExpressionGui.makeLabel "." (Widget.toAnimId myId)
tagEdit <-
TagEdit.makeRecordTag
(pl ^. Sugar.plData . ExprGuiT.plNearestHoles) tagG
return $ ExpressionGui.hbox [recExprEdit, dotLabel, tagEdit]
& ExprGuiM.assignCursor myId tagId
where
tagId = WidgetIds.fromEntityId (tagG ^. Sugar.tagInstance)
| da-x/lamdu | Lamdu/GUI/ExpressionEdit/GetFieldEdit.hs | gpl-3.0 | 1,470 | 0 | 15 | 298 | 353 | 204 | 149 | -1 | -1 |
{-# LANGUAGE DeriveFunctor #-}
module Predicate (
Condition(..), ECondition(..),
Var, Val(..), Op(..),
Tree,
parse, interpret, eval,
eval', evalString
) where
import Data.Functor
import Control.Monad.Free
import Predicate.Parser (Var, Val, Op, Expr)
import qualified Predicate.Parser as P
data OpBranch a = And a a | Or a a | Not a
deriving Functor
type Tree = Free OpBranch
data Condition = Exists Var | Is Op Var Val
data ECondition = Cond Condition | Const Bool
parse :: String -> Maybe (Tree ECondition)
parse s = convert <$> P.parseString s
convert :: Expr -> Tree ECondition
convert (P.Const b) = Pure (Const b)
convert (P.Leaf v) = Pure (Cond (Exists v))
convert (P.LeafOp o v1 v2) = Pure (Cond (Is o v1 v2))
convert (P.Not e) = Free (Not (convert e))
convert (P.Branch P.And a b) = Free (And (convert a) (convert b))
convert (P.Branch P.Or a b) = Free (Or (convert a) (convert b))
interpret :: (Condition -> Bool) -> Tree ECondition -> Tree Bool
interpret f = fmap (\c -> case c of
Cond c' -> f c'
Const b -> b )
eval :: Tree Bool -> Bool
eval (Pure b) = b
eval (Free (And a b)) = eval a && eval b
eval (Free (Or a b)) = eval a || eval b
eval (Free (Not a)) = not $ eval a
eval' :: (Condition -> Bool) -> Tree ECondition -> Bool
eval' f = eval . interpret f
evalString :: (Condition -> Bool) -> String -> Maybe Bool
evalString f s = eval' f <$> parse s
| ffwng/tagfs | Predicate.hs | gpl-3.0 | 1,382 | 12 | 11 | 282 | 705 | 367 | 338 | 38 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Games.TurnBasedMatches.Rematch
-- 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)
--
-- Create a rematch of a match that was previously completed, with the same
-- participants. This can be called by only one player on a match still in
-- their list; the player must have called Finish first. Returns the newly
-- created match; it will be the caller\'s turn.
--
-- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.turnBasedMatches.rematch@.
module Network.Google.Resource.Games.TurnBasedMatches.Rematch
(
-- * REST Resource
TurnBasedMatchesRematchResource
-- * Creating a Request
, turnBasedMatchesRematch
, TurnBasedMatchesRematch
-- * Request Lenses
, tbmrRequestId
, tbmrLanguage
, tbmrMatchId
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.turnBasedMatches.rematch@ method which the
-- 'TurnBasedMatchesRematch' request conforms to.
type TurnBasedMatchesRematchResource =
"games" :>
"v1" :>
"turnbasedmatches" :>
Capture "matchId" Text :>
"rematch" :>
QueryParam "requestId" (Textual Int64) :>
QueryParam "language" Text :>
QueryParam "alt" AltJSON :>
Post '[JSON] TurnBasedMatchRematch
-- | Create a rematch of a match that was previously completed, with the same
-- participants. This can be called by only one player on a match still in
-- their list; the player must have called Finish first. Returns the newly
-- created match; it will be the caller\'s turn.
--
-- /See:/ 'turnBasedMatchesRematch' smart constructor.
data TurnBasedMatchesRematch =
TurnBasedMatchesRematch'
{ _tbmrRequestId :: !(Maybe (Textual Int64))
, _tbmrLanguage :: !(Maybe Text)
, _tbmrMatchId :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TurnBasedMatchesRematch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tbmrRequestId'
--
-- * 'tbmrLanguage'
--
-- * 'tbmrMatchId'
turnBasedMatchesRematch
:: Text -- ^ 'tbmrMatchId'
-> TurnBasedMatchesRematch
turnBasedMatchesRematch pTbmrMatchId_ =
TurnBasedMatchesRematch'
{ _tbmrRequestId = Nothing
, _tbmrLanguage = Nothing
, _tbmrMatchId = pTbmrMatchId_
}
-- | A randomly generated numeric ID for each request specified by the
-- caller. This number is used at the server to ensure that the request is
-- handled correctly across retries.
tbmrRequestId :: Lens' TurnBasedMatchesRematch (Maybe Int64)
tbmrRequestId
= lens _tbmrRequestId
(\ s a -> s{_tbmrRequestId = a})
. mapping _Coerce
-- | The preferred language to use for strings returned by this method.
tbmrLanguage :: Lens' TurnBasedMatchesRematch (Maybe Text)
tbmrLanguage
= lens _tbmrLanguage (\ s a -> s{_tbmrLanguage = a})
-- | The ID of the match.
tbmrMatchId :: Lens' TurnBasedMatchesRematch Text
tbmrMatchId
= lens _tbmrMatchId (\ s a -> s{_tbmrMatchId = a})
instance GoogleRequest TurnBasedMatchesRematch where
type Rs TurnBasedMatchesRematch =
TurnBasedMatchRematch
type Scopes TurnBasedMatchesRematch =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.me"]
requestClient TurnBasedMatchesRematch'{..}
= go _tbmrMatchId _tbmrRequestId _tbmrLanguage
(Just AltJSON)
gamesService
where go
= buildClient
(Proxy :: Proxy TurnBasedMatchesRematchResource)
mempty
| brendanhay/gogol | gogol-games/gen/Network/Google/Resource/Games/TurnBasedMatches/Rematch.hs | mpl-2.0 | 4,445 | 0 | 15 | 1,011 | 496 | 295 | 201 | 77 | 1 |
module NGramCrackers.Ops.Text
(
bigrams
, trigrams
, getNGramsFromText
, getNGramsFromTextList
, getAlphasOnlyToText
, normToList
, getWordFrequency
, countWords
) where
import qualified Data.Text as T
import Data.Char (isAlpha, isAlphaNum, isSpace, toLower)
import Data.List (map, nub)
import Data.Monoid ((<>))
import NGramCrackers.DataTypes
import NGramCrackers.Ops.Infixes
import NGramCrackers.Utilities.List
{-| Extract bigrams from a string -}
bigrams :: T.Text -> [T.Text]
bigrams = getNGramsFromText 2
{-| Extract trigrams from a string -}
trigrams :: T.Text -> [T.Text]
trigrams = getNGramsFromText 3
{-| Extract n-grams from a string -}
getNGramsFromText :: Int -> T.Text -> [T.Text]
getNGramsFromText n packed -- packed is a packed T.Text string
| n < 0 = error "n must be a positive integer less than 7"
| n > 7 = error "n must be a positive integer less than 7"
| otherwise = map T.unwords $ getNGramsFromTextList n wordList
where wordList = T.words packed
getNGramsFromTextList :: Int -> [T.Text] -> [[T.Text]]
getNGramsFromTextList = getNSeqFromList
{-| Return only alphabetic characters from a string and return the
result as a string. Output of this function may need processing
into a list, tuple, etc. -}
getAlphasOnlyToText :: T.Text -> T.Text
getAlphasOnlyToText = T.filter (\char -> isAlpha char || isSpace char)
{-| Return only alphanumeric characters from a string and return the
result as a List.-}
normToList :: T.Text -> [T.Text]
normToList = T.words . getAlphasOnlyToText . T.toLower
{-| Get frequency of a single word's occurance in a string. Is eta-reduction
the easiest reading way to do this function? The arguments are fairly
instructive. However, the type declaration does say what kind of args
it takes. With type synonyms or further exploring the type system,
the declaration would be more informative-}
getWordFrequency:: T.Text -> T.Text -> Int
-- No eta-reduction for readability
getWordFrequency word text = (length . filter (== word) . T.words) text
{-| These functions output the specified strings, so they can be kept and
developed separately from the lists that get used in generating the
the help, version, and about type displays -}
countWords :: T.Text -> Int
countWords = length . T.words
| R-Morgan/NGramCrackers | src/NGramCrackers/Ops/Text.hs | agpl-3.0 | 2,326 | 0 | 10 | 431 | 430 | 241 | 189 | 37 | 1 |
{-# LANGUAGE
TypeFamilies #-}
module MaybeSet where
import Set
-- A type `Set (MaybeSet s)' denotes the same subsets as a type of class `Set s', except the value
-- `Nothing' may be contained in any of them.
data MaybeSet s = OnlyJust s | WithNothing s
deriving(Show,Eq)
withoutNothing :: LatticeSet s => MaybeSet s -> s
withoutNothing (OnlyJust a) = a
withoutNothing (WithNothing a) = a
instance LatticeSet s => LatticeSet (MaybeSet s) where
type MemberType (MaybeSet s) = Maybe (MemberType s)
empty = OnlyJust empty
univ = WithNothing univ
OnlyJust a /\ OnlyJust b = OnlyJust (a /\ b)
OnlyJust a /\ WithNothing b = OnlyJust (a /\ b)
WithNothing a /\ OnlyJust b = OnlyJust (a /\ b)
WithNothing a /\ WithNothing b = WithNothing (a /\ b)
OnlyJust a \/ OnlyJust b = OnlyJust (a \/ b)
WithNothing a \/ OnlyJust b = WithNothing (a \/ b)
OnlyJust a \/ WithNothing b = WithNothing (a \/ b)
WithNothing a \/ WithNothing b = WithNothing (a \/ b)
member (WithNothing a) Nothing = True
member (OnlyJust a) Nothing = False
member (WithNothing a) (Just x) = member a x
member (OnlyJust a) (Just x) = member a x
singleton Nothing = WithNothing empty
singleton (Just a) = OnlyJust (singleton a)
| ntoronto/drbayes | drbayes/direct/haskell-impl/MaybeSet.hs | lgpl-3.0 | 1,233 | 0 | 8 | 265 | 480 | 230 | 250 | 27 | 1 |
module BarthPar.Parallel where
import Control.Parallel.Strategies
smartMap :: NFData y => Int -> (x -> y) -> [x] -> [y]
smartMap 0 f xs = map f xs
smartMap 1 f xs = parMap rdeepseq f xs
smartMap cs f xs = map f xs `using` parListChunk cs rdeepseq
smartList :: NFData y => Int -> [y] -> [y]
smartList 0 ys = ys
smartList 1 ys = ys `using` parList rdeepseq
smartList cs ys = ys `using` parListChunk cs rdeepseq
| erochest/barth-scrape | src/BarthPar/Parallel.hs | apache-2.0 | 428 | 0 | 9 | 99 | 189 | 99 | 90 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Main where
import Control.Error
import Options.Applicative
import Prelude hiding (FilePath, mapM)
import Opts
import PopVox.Action.ExtractCF
import PopVox.Action.Transform
import PopVox.Action.RankBills
import PopVox.Action.ReportOn
import PopVox.Action.SearchPosition
import PopVox.Action.TestCsv
import PopVox.Action.TestJson
import PopVox.Types
main :: IO ()
main = execParser opts >>= popvox
popvox :: PopVoxOptions -> IO ()
popvox Transform{..} =
runScript $ transform contribDataFile maplightAPIDir outputFile
popvox RankBills{..} =
runScript $ rankBills rankBillScores rankBillBills rankBillIndex rankBillOutput
popvox ExtractCF{..} = runScript $ extractCF contribDataFile cfOutputFile
popvox TestJson{..} = testJSON maplightAPIDir
popvox TestCsv{..} = testCSV contribDataFile failFast
popvox SearchPosition{..} = runScript $ searchPosition maplightAPIDir maplightOrg
popvox ReportOn{..} = runScript $ reportOn reportCsvFile reportTarget
| erochest/popvox-scrape | Main.hs | apache-2.0 | 1,275 | 0 | 7 | 303 | 273 | 147 | 126 | 29 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Spark.Core.CachingSpec where
import Test.Hspec
import qualified Data.Text
import Spark.Core.Context
import Spark.Core.Functions
import Spark.Core.Column
import qualified Spark.Core.ColumnFunctions as C
import Spark.Core.StructuresInternal(ComputationID(..))
-- Collecting a dataset made from a list should yield the same list (modulo
-- some reordering)
collectIdempotent :: [Int] -> IO ()
collectIdempotent l = do
-- stats <- computationStatsDef (ComputationID "0")
-- print "STATS"
-- print (show stats)
let ds = dataset l
let ds' = autocache ds
let c1 = asCol ds'
let s1 = C.sum c1
let s2 = C.count c1
let x = s1 + s2
l2 <- exec1Def x
l2 `shouldBe` (sum l + length l)
run :: String -> IO () -> SpecWith (Arg (IO ()))
run s f = it s $ do
createSparkSessionDef $ defaultConf { confRequestedSessionName = Data.Text.pack s }
f
-- This is horribly not robust to any sort of failure, but it will do for now
-- TODO(kps) make more robust
closeSparkSessionDef
return ()
spec :: Spec
spec = do
describe "Integration test - caching on ints" $ do
run "cache_sum1" $
collectIdempotent ([1,2,3] :: [Int])
| tjhunter/karps | haskell/test-integration/Spark/Core/CachingSpec.hs | apache-2.0 | 1,229 | 0 | 13 | 240 | 341 | 179 | 162 | 31 | 1 |
-- Copyright 2013 Mario Pastorelli (pastorelli.mario@gmail.com) Samuel Gélineau (gelisam@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
import System.Environment (unsetEnv)
import Test.DocTest (doctest)
import Test.Hspec (hspec)
import qualified Build_doctests as CabalDoctest
import qualified System.Console.Hawk.Representable.Test as ReprTest
import qualified System.Console.Hawk.Test as HawkTest
main :: IO ()
main = do
unsetEnv "GHC_ENVIRONMENT" -- as explained in the cabal-doctest documentation
doctest $ CabalDoctest.flags
++ CabalDoctest.pkgs
++ CabalDoctest.module_sources
doctest $ CabalDoctest.flags_exe_hawk
++ CabalDoctest.pkgs_exe_hawk
++ CabalDoctest.module_sources_exe_hawk
hspec $ do
ReprTest.reprSpec'
ReprTest.reprSpec
HawkTest.run
| gelisam/hawk | tests/RunTests.hs | apache-2.0 | 1,379 | 0 | 10 | 268 | 157 | 93 | 64 | 19 | 1 |
module Tiling.A301976 where
import Helpers.LeafFreeGrids (leafFreeGridsList)
a301976_list :: [Integer]
a301976_list = leafFreeGridsList 3
a301976 :: Int -> Integer
a301976 n = a301976_list !! (n - 1)
| peterokagey/haskellOEIS | src/Tiling/A301976.hs | apache-2.0 | 202 | 0 | 7 | 28 | 60 | 34 | 26 | 6 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Token
( TokenResp(..)
, Vars (..)
, AppConfig (..)
, askNewAccessToken
, currentTokenConfig
, tokenCachedFileName
, newTokenIfNonLocalExisted
) where
import Control.Applicative
import qualified Control.Exception as E
import Control.Monad (liftM)
import Data.Aeson
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC
import qualified Data.ByteString.Lazy.UTF8 as U
import qualified Data.Map as Map
import Network (withSocketsDo)
import Network.HTTP.Conduit
import Network.HTTP.Types.Method (Method, StdMethod (GET, POST),
methodGet, methodPost)
import Network.HTTP.Types.Status
import System.Directory (doesFileExist, getHomeDirectory)
import System.Environment (getArgs)
import System.FilePath
import System.IO
import Text.Printf (printf)
import Util
--
tokenCachedFileName :: String
tokenCachedFileName = ".pcs-cli.token.json"
appConfigFileName :: String
appConfigFileName = ".pcs-cli.app.json"
appConfigFile :: IO FilePath
appConfigFile = liftM (</> appConfigFileName) getHomeDirectory
tokenCachedFileFullPath = liftM (</> tokenCachedFileName) getHomeDirectory
newTokenIfNonLocalExisted :: IO Vars
newTokenIfNonLocalExisted = currentTokenConfig >>= process
where
process Vars {token = Nothing, ..} = askNewAccessToken
process ac = return ac
currentToken :: IO (Maybe TokenResp)
currentToken = liftM parse'' $ tokenCachedFileFullPath >>= readFile
where
parse'' :: String -> Maybe TokenResp
parse'' = decodeStrict . LC.toStrict . LC.pack
currentTokenConfig :: IO Vars
currentTokenConfig = do
tok <- currentToken
conf <- loadAppConfig
return (Vars conf tok)
askNewAccessToken :: IO Vars
askNewAccessToken = do
mgr <- defaultManager
conf <- loadAppConfig
dcResp <- deviceCodeAuth mgr conf
tok <- requestForAccessToken mgr conf dcResp
return Vars { appConfig = conf, token = Just tok }
--
openApiUrl, openApiVersion, scope, oAuthUrl, deviceAuthUrl, tokenUrl :: String
openApiUrl = "https://openapi.baidu.com"
openApiVersion = "2.0"
scope = "basic netdisk"
oAuthUrl = openApiUrl ++ "/oauth/" ++ openApiVersion
deviceAuthUrl = oAuthUrl ++ "/device/code"
tokenUrl = oAuthUrl ++ "/token"
requestForAccessToken :: Manager -> AppConfig -> DeviceCodeResp -> IO TokenResp
requestForAccessToken mgr AppConfig{..} dc = do
putStrLn ">> 请求Token..."
resp <- doRequest mgr tokenUrl params POST
let resp' = handleJSONResponse resp :: Either Err TokenResp
case resp' of
Right t@TokenResp{} -> do
file' <- tokenCachedFileFullPath
printf ">> access token申请成功,写入以下文件:%s。\n" file'
writeFile file' (LC.unpack . responseBody $ resp)
putStrLn ">> 已完成token申请"
return t
Left err -> handleErr err
where
params = Map.fromList [("grant_type","device_token"),
("code", deviceCode dc),
("client_id", appKey),
("client_secret", secret)]
deviceCodeAuth :: Manager -> AppConfig -> IO DeviceCodeResp
deviceCodeAuth mgr AppConfig{..} = do
resp <- sendRequest mgr deviceAuthUrl params POST
case resp of
Right d@DeviceCodeResp{..} -> do
printf ">> 去这个地址[ %s ],\n输入Code: [ %s ]\n"
verifyUrl userCode
printf ">> 或者去这个地址直接扫描二维码授权:%s\n" qrCodeUrl
printf ">> 完成授权后按输入任意字符后回车继续..\n >> "
_ <- getLine
return d
Left Err{..} ->
error $ printf "请求出错了:[%s] [%s]\n" errCode description
where
params = Map.fromList [ ("client_id", appKey)
, ("scope", scope)
, ("response_type", "device_code")]
handleErr Err{..} =
error $ printf "请求出错了:[%s] [%s]\n" errCode description
convertStringPairToBS = map2 (LC.toStrict . LC.pack)
where map2 f (a,b) = (f a, f b)
loadAppConfig :: IO AppConfig
loadAppConfig = do
f <- appConfigFile
e <- doesFileExist f
cont <- if not e
then error ("需要App配置文件: " ++ f ++ "\n格式: " ++
(U.toString . encode $
AppConfig "your app key" "your app secret" "your app path"))
else L.readFile f
case eitherDecode cont of
Left err -> error $ "读取App配置出错:" ++ err
Right conf -> return conf
data Err = Err {
errCode :: String,
description :: String
} deriving Show
instance FromJSON Err where
parseJSON (Object v) =
Err <$> v .: "error"
<*> v .: "error_description"
data DeviceCodeResp = DeviceCodeResp {
deviceCode :: String,
userCode :: String,
verifyUrl :: String,
qrCodeUrl :: String,
dCodeExpiresIn :: Int,
interval :: Int
} deriving Show
instance FromJSON DeviceCodeResp where
parseJSON (Object v) =
DeviceCodeResp <$> v .: "device_code"
<*> v .: "user_code"
<*> v .: "verification_url"
<*> v .: "qrcode_url"
<*> v .: "expires_in"
<*> v .: "interval"
data TokenResp = TokenResp {
accessToken :: String,
tokenExpiresIn :: Int,
refreshToken :: String,
tokenScope :: String,
sessionKey :: String,
sessionSecret :: String
} deriving (Show, Eq)
instance FromJSON TokenResp where
parseJSON (Object v) =
TokenResp <$> v .: "access_token"
<*> v .: "expires_in"
<*> v .: "refresh_token"
<*> v .: "scope"
<*> v .: "session_key"
<*> v .: "session_secret"
data AppConfig = AppConfig {
appKey :: String,
secret :: String,
appPath :: FilePath
} deriving (Show, Eq)
instance FromJSON AppConfig where
parseJSON (Object v) =
AppConfig <$> v .: "appKey"
<*> v .: "secretKey"
<*> v .: "appPath"
instance ToJSON AppConfig where
toJSON AppConfig {appKey, secret, appPath} =
object [ "appKey" .= appKey
, "secretKey" .= secret
, "appPath" .= appPath
]
data Vars = Vars {
appConfig :: AppConfig,
token :: Maybe TokenResp
} deriving Show
| songpp/pcs-cli | src/Token.hs | apache-2.0 | 7,007 | 0 | 17 | 2,203 | 1,620 | 877 | 743 | 173 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
module Application.XournalConvert.ProgType where
import System.Console.CmdArgs
data Xournal_convert = Test
| MakeSVG { xojfile :: FilePath
, dest :: Maybe FilePath
}
deriving (Show,Data,Typeable)
test :: Xournal_convert
test = Test
makeSVG :: Xournal_convert
makeSVG = MakeSVG { xojfile = "test.xoj" &= typ "FILENAME" &= argPos 0
, dest = Nothing &= typ "DESTINATION"
}
mode = modes [test, makeSVG]
| wavewave/xournal-convert | lib/Application/XournalConvert/ProgType.hs | bsd-2-clause | 582 | 0 | 9 | 209 | 125 | 72 | 53 | 13 | 1 |
import Controller (withOR)
import Network.Wai.Handler.Warp (run)
main :: IO ()
main = withOR $ run 3000
| snoyberg/orangeroster | production.hs | bsd-2-clause | 105 | 0 | 6 | 17 | 43 | 24 | 19 | 4 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett and Dan Doel 2012
-- License : BSD2
-- Maintainer: Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability: non-portable
--
-- This module tells us how to unify types. We use a simplified form
-- of HMF-style unification to deal with unification of foralls.
--
--------------------------------------------------------------------
module Ermine.Unification.Type
( unifyType
, zonkKindsAndTypes
, zonkKindsAndTypesWith
) where
import Control.Applicative
import Control.Comonad
import Control.Lens
import Control.Monad
import Control.Monad.ST
import Control.Monad.ST.Class
import Control.Monad.Writer.Strict
import Data.Bitraversable
import Data.Set as Set
import Data.IntMap as IntMap
import Data.Set.Lens
import Data.STRef
import Data.Traversable
import Ermine.Diagnostic
import Ermine.Pretty
import Ermine.Pretty.Type
import Ermine.Inference.Kind (checkKind)
import Ermine.Syntax.Scope
import Ermine.Syntax.Type as Type
import Ermine.Syntax.Kind as Kind hiding (Var)
import Ermine.Unification.Kind
import Ermine.Unification.Meta
import Ermine.Unification.Sharing
-- | Perform an occurs check against a type.
--
-- This rules out infinite circular type signatures.
--
-- This returns the fully zonked 'Type' as a consequence, since it needs it anyways.
typeOccurs
:: (MonadWriter Any m, MonadMeta s m)
=> Depth -> TypeM s -> (MetaT s -> Bool) -> m (TypeM s)
typeOccurs depth1 t p = zonkKindsAndTypesWith t tweakDepth tweakType where
tweakDepth :: MonadST m => Meta (World m) f a -> m ()
tweakDepth m = liftST $ forMOf_ metaDepth m $ \d -> do
depth2 <- readSTRef d
when (depth2 > depth1) $ writeSTRef d depth1
tweakType m
| p m = do
zt <- sharing t $ zonk t
let st = setOf typeVars zt
mt = IntMap.fromList $ zipWith (\u n -> (u^.metaId, n)) (Set.toList st) names
sk = setOf kindVars zt
mk = IntMap.fromList $ zipWith (\u n -> (u^.metaId, n)) (Set.toList sk) names
v = mt ^?! ix (st ^?! folded.filtered p.metaId)
td = prettyType
(bimap (\u -> mk ^?! ix (u^.metaId))
(\u -> mt ^?! ix (u^.metaId)) zt)
(drop (Set.size st) names)
(-1)
r <- viewMeta rendering
throwM $ die r "infinite type detected" & footnotes .~ [text "cyclic type:" <+> hang 4 (group (pretty v </> char '=' </> td))]
| otherwise = tweakDepth m
zonkKindsAndTypes
:: (MonadMeta s m, MonadWriter Any m)
=> TypeM s -> m (TypeM s)
zonkKindsAndTypes t = zonkKindsAndTypesWith t (const $ return ()) (const $ return ())
zonkKindsAndTypesWith
:: (MonadMeta s m, MonadWriter Any m)
=> TypeM s -> (MetaK s -> m ()) -> (MetaT s -> m ()) -> m (TypeM s)
zonkKindsAndTypesWith fs0 tweakKind tweakType = go fs0 where
go fs = bindType id id <$> bitraverse handleKind handleType fs
handleType m = do
tweakType m
zmv <- zonkWith (m^.metaValue) tweakKind
readMeta m >>= \mv -> case mv of
Nothing -> return $ return $ m & metaValue .~ zmv
Just fmf -> do
tell $ Any True
r <- go fmf
r <$ writeMeta m r
handleKind m = do
tweakKind m
readMeta m >>= \mv -> case mv of
Nothing -> return (return m)
Just fmf -> do
tell $ Any True
r <- zonkWith fmf tweakKind
r <$ writeMeta m r
{-# INLINE zonkKindsAndTypesWith #-}
-- | Unify two types, with access to a visited set, logging via 'MonadWriter' whether or not the answer differs from the first type argument.
--
-- This returns the result of unification with any modifications expanded, as we calculated it in passing
unifyType
:: (MonadWriter Any m, MonadMeta s m)
=> TypeM s -> TypeM s -> m (TypeM s)
unifyType t1 t2 = do
t1' <- semiprune t1
t2' <- semiprune t2
go t1' t2'
where
go x@(Var tv1) (Var tv2) | tv1 == tv2 = return x
go x@(Var (Meta k _ i r d u)) y@(Var (Meta l _ j s e v)) = do
() <$ unifyKind k l -- TODO: put the result in x/y?
-- union-by-rank
m <- liftST $ readSTRef u
n <- liftST $ readSTRef v
case compare m n of
LT -> unifyTV True i r d y $ return ()
EQ -> unifyTV True i r d y $ writeSTRef v $! n + 1
GT -> unifyTV False j s e x $ return ()
go (Var (Meta k _ i r d _)) t = do
checkKind (view metaValue) t k
unifyTV True i r d t $ return ()
go t (Var (Meta k _ i r d _)) = do
checkKind (view metaValue) t k
unifyTV False i r d t $ return () -- not as boring as it could be
go (App f x) (App g y) = App <$> unifyType f g <*> unifyType x y
go (Loc l s) t = Loc l <$> unifyType s t
go s (Loc _ t) = unifyType s t
go Exists{} _ = fail "unifyType: existential"
go _ Exists{} = fail "unifyType: existential"
go t@(Forall m xs _ a) t'@(Forall n ys _ b)
| m /= n = fail "unifyType: forall: mismatched kind arity"
| length xs /= length ys = fail "unifyType: forall: mismatched type arity"
| otherwise = do
((sts, sks), Any modified) <- listen $ do
sks <- for m $ newMeta False
let nxs = instantiateVars sks <$> fmap extract xs
nys = instantiateVars sks <$> fmap extract ys
sts <- for (zip nxs nys) $ \(x,y) -> do
k <- unifyKind x y
newMeta k Nothing
_ <- unifyType (instantiateKindVars sks (instantiateVars sts a))
(instantiateKindVars sks (instantiateVars sts b))
return (sts, sks)
-- checking skolem escapes here is important for cases like:
-- ((f : some b r. (forall a. a -> b) -> r)
-- (g : some a r. (forall b. a -> b) -> r) ->
-- ((x y -> x) : some a. a -> a -> a) f g)
if modified
then do
_ <- checkDistinct sks
sts' <- checkDistinct sts
fst <$> checkSkolems Nothing both sts' (t, t')
else return t
go t@(HardType x) (HardType y) | x == y = return t
go _ _ = fail "type mismatch"
{-# INLINE unifyType #-}
-- | Unify with (the guts of) a type variable.
unifyTV
:: (MonadWriter Any m, MonadMeta s m)
=> Bool -> Int -> STRef s (Maybe (TypeM s)) -> STRef s Depth
-> TypeM s -> ST s () -> m (TypeM s)
unifyTV interesting i r d t bump = liftST (readSTRef r) >>= \ mt1 -> case mt1 of
Just j -> do
(t', Any m) <- listen $ unifyType j t
if m then liftST $ t' <$ writeSTRef r (Just t')
else j <$ tell (Any True)
Nothing -> case t of
Var v@(Meta k _ _ _ e _) -> do -- this has been semipruned so its not part of a chain
tell (Any interesting)
zk <- zonkWith k $ \kv -> liftST $ do
let f = kv^.metaDepth
depth1 <- readSTRef d
depth2 <- readSTRef f
when (depth2 > depth1) $ writeSTRef f depth1
liftST $ do
bump
writeSTRef r (Just t)
depth1 <- readSTRef d
depth2 <- readSTRef e
when (depth2 > depth1) $ writeSTRef e depth1
return $ Var $ v & metaValue .~ zk
_ -> do
tell (Any interesting)
depth1 <- liftST $ readSTRef d
zt <- typeOccurs depth1 t $ \v -> v^.metaId == i
zt <$ liftST (writeSTRef r (Just zt))
| PipocaQuemada/ermine | src/Ermine/Unification/Type.hs | bsd-2-clause | 7,590 | 0 | 24 | 2,317 | 2,598 | 1,276 | 1,322 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-| Implementation of the Ganeti Instance config object.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Objects.Nic where
import Ganeti.THH
import Ganeti.THH.Field
import Ganeti.Types
$(buildParam "Nic" "nicp"
[ simpleField "mode" [t| NICMode |]
, simpleField "link" [t| String |]
, simpleField "vlan" [t| String |]
])
$(buildObject "PartialNic" "nic" $
[ simpleField "mac" [t| String |]
, optionalField $ simpleField "ip" [t| String |]
, simpleField "nicparams" [t| PartialNicParams |]
, optionalField $ simpleField "network" [t| String |]
, optionalField $ simpleField "name" [t| String |]
] ++ uuidFields)
instance UuidObject PartialNic where
uuidOf = nicUuid
| ganeti-github-testing/ganeti-test-1 | src/Ganeti/Objects/Nic.hs | bsd-2-clause | 1,995 | 0 | 11 | 327 | 181 | 110 | 71 | 18 | 0 |
module Settings.Builders.Common (
includesArgs, cIncludeArgs, ldArgs, cArgs, cWarnings,
argSetting, argSettingList, argStagedBuilderPath, argStagedSettingList
) where
import Base
import Expression
import Oracles.Config.Flag
import Oracles.Config.Setting
import Oracles.PackageData
import Settings
includes :: [FilePath]
includes = [ "includes", "includes/dist-derivedconstants/header" ]
includesArgs :: Args
includesArgs = append $ map ("-I" ++) includes
cIncludeArgs :: Args
cIncludeArgs = do
stage <- getStage
pkg <- getPackage
incDirs <- getPkgDataList IncludeDirs
depDirs <- getPkgDataList DepIncludeDirs
let buildPath = targetPath stage pkg -/- "build"
mconcat [ arg $ "-I" ++ buildPath
, arg $ "-I" ++ buildPath -/- "autogen"
, append [ "-I" ++ pkgPath pkg -/- dir | dir <- incDirs ]
, append [ "-I" ++ dir | dir <- depDirs ] ]
ldArgs :: Args
ldArgs = mempty
-- TODO: put all validating options together in one file
cArgs :: Args
cArgs = validating ? cWarnings
-- TODO: should be in a different file
cWarnings :: Args
cWarnings = do
let gccGe46 = notM $ (flag GccIsClang ||^ flag GccLt46)
mconcat [ turnWarningsIntoErrors ? arg "-Werror"
, arg "-Wall"
, flag GccIsClang ? arg "-Wno-unknown-pragmas"
, gccGe46 ? notM windowsHost ? arg "-Werror=unused-but-set-variable"
, gccGe46 ? arg "-Wno-error=inline" ]
argM :: Action String -> Args
argM = (arg =<<) . lift
argSetting :: Setting -> Args
argSetting = argM . setting
argSettingList :: SettingList -> Args
argSettingList = (append =<<) . lift . settingList
argStagedSettingList :: (Stage -> SettingList) -> Args
argStagedSettingList ss = (argSettingList . ss) =<< getStage
argStagedBuilderPath :: (Stage -> Builder) -> Args
argStagedBuilderPath sb = (argM . builderPath . sb) =<< getStage
| quchen/shaking-up-ghc | src/Settings/Builders/Common.hs | bsd-3-clause | 1,907 | 0 | 13 | 421 | 514 | 277 | 237 | 46 | 1 |
{-# LANGUAGE CPP, DeriveGeneric, DeriveFunctor, RecordWildCards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.TargetSelector
-- Copyright : (c) Duncan Coutts 2012, 2015, 2016
-- License : BSD-like
--
-- Maintainer : duncan@community.haskell.org
--
-- Handling for user-specified target selectors.
--
-----------------------------------------------------------------------------
module Distribution.Client.TargetSelector (
-- * Target selectors
TargetSelector(..),
TargetImplicitCwd(..),
ComponentKind(..),
SubComponentTarget(..),
QualLevel(..),
componentKind,
-- * Reading target selectors
readTargetSelectors,
TargetSelectorProblem(..),
reportTargetSelectorProblems,
showTargetSelector,
TargetString,
showTargetString,
parseTargetString,
-- ** non-IO
readTargetSelectorsWith,
DirActions(..),
defaultDirActions,
) where
import Distribution.Package
( Package(..), PackageId, PackageIdentifier(..), packageName
, mkPackageName )
import Distribution.Version
( mkVersion )
import Distribution.Types.UnqualComponentName ( unUnqualComponentName )
import Distribution.Client.Types
( PackageLocation(..) )
import Distribution.Verbosity
import Distribution.PackageDescription
( PackageDescription
, Executable(..)
, TestSuite(..), TestSuiteInterface(..), testModules
, Benchmark(..), BenchmarkInterface(..), benchmarkModules
, BuildInfo(..), explicitLibModules, exeModules )
import Distribution.PackageDescription.Configuration
( flattenPackageDescription )
import Distribution.Solver.Types.SourcePackage
( SourcePackage(..) )
import Distribution.ModuleName
( ModuleName, toFilePath )
import Distribution.Simple.LocalBuildInfo
( Component(..), ComponentName(..)
, pkgComponents, componentName, componentBuildInfo )
import Distribution.Types.ForeignLib
import Distribution.Text
( display, simpleParse )
import Distribution.Simple.Utils
( die', lowercase, ordNub )
import Distribution.Client.Utils
( makeRelativeCanonical )
import Data.Either
( partitionEithers )
import Data.Function
( on )
import Data.List
( nubBy, stripPrefix, partition, intercalate, sortBy, groupBy )
import Data.Maybe
( maybeToList )
import Data.Ord
( comparing )
import Distribution.Compat.Binary (Binary)
import GHC.Generics (Generic)
#if MIN_VERSION_containers(0,5,0)
import qualified Data.Map.Lazy as Map.Lazy
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
#else
import qualified Data.Map as Map.Lazy
import qualified Data.Map as Map
import Data.Map (Map)
#endif
import qualified Data.Set as Set
import Control.Arrow ((&&&))
import Control.Monad
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative(..), (<$>))
#endif
import Control.Applicative (Alternative(..))
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP
( (+++), (<++) )
import Distribution.ParseUtils
( readPToMaybe )
import Data.Char
( isSpace, isAlphaNum )
import System.FilePath as FilePath
( takeExtension, dropExtension
, splitDirectories, joinPath, splitPath )
import qualified System.Directory as IO
( doesFileExist, doesDirectoryExist, canonicalizePath
, getCurrentDirectory )
import System.FilePath
( (</>), (<.>), normalise, dropTrailingPathSeparator )
import Text.EditDistance
( defaultEditCosts, restrictedDamerauLevenshteinDistance )
-- ------------------------------------------------------------
-- * Target selector terms
-- ------------------------------------------------------------
-- | A target selector is expression selecting a set of components (as targets
-- for a actions like @build@, @run@, @test@ etc). A target selector
-- corresponds to the user syntax for referring to targets on the command line.
--
-- From the users point of view a target can be many things: packages, dirs,
-- component names, files etc. Internally we consider a target to be a specific
-- component (or module\/file within a component), and all the users' notions
-- of targets are just different ways of referring to these component targets.
--
-- So target selectors are expressions in the sense that they are interpreted
-- to refer to one or more components. For example a 'TargetPackage' gets
-- interpreted differently by different commands to refer to all or a subset
-- of components within the package.
--
-- The syntax has lots of optional parts:
--
-- > [ package name | package dir | package .cabal file ]
-- > [ [lib:|exe:] component name ]
-- > [ module name | source file ]
--
data TargetSelector pkg =
-- | A package as a whole: the default components for the package or all
-- components of a particular kind.
--
TargetPackage TargetImplicitCwd pkg (Maybe ComponentKindFilter)
-- | All packages, or all components of a particular kind in all packages.
--
| TargetAllPackages (Maybe ComponentKindFilter)
-- | A specific component in a package.
--
| TargetComponent pkg ComponentName SubComponentTarget
deriving (Eq, Ord, Functor, Show, Generic)
-- | Does this 'TargetPackage' selector arise from syntax referring to a
-- packge in the current directory (e.g. @tests@ or no giving no explicit
-- target at all) or does it come from syntax referring to a package name
-- or location.
--
data TargetImplicitCwd = TargetImplicitCwd | TargetExplicitNamed
deriving (Eq, Ord, Show, Generic)
data ComponentKind = LibKind | FLibKind | ExeKind | TestKind | BenchKind
deriving (Eq, Ord, Enum, Show)
type ComponentKindFilter = ComponentKind
-- | Either the component as a whole or detail about a file or module target
-- within a component.
--
data SubComponentTarget =
-- | The component as a whole
WholeComponent
-- | A specific module within a component.
| ModuleTarget ModuleName
-- | A specific file within a component.
| FileTarget FilePath
deriving (Eq, Ord, Show, Generic)
instance Binary SubComponentTarget
-- ------------------------------------------------------------
-- * Top level, do everything
-- ------------------------------------------------------------
-- | Parse a bunch of command line args as 'TargetSelector's, failing with an
-- error if any are unrecognised. The possible target selectors are based on
-- the available packages (and their locations).
--
readTargetSelectors :: [SourcePackage (PackageLocation a)]
-> [String]
-> IO (Either [TargetSelectorProblem]
[TargetSelector PackageId])
readTargetSelectors = readTargetSelectorsWith defaultDirActions
readTargetSelectorsWith :: (Applicative m, Monad m) => DirActions m
-> [SourcePackage (PackageLocation a)]
-> [String]
-> m (Either [TargetSelectorProblem]
[TargetSelector PackageId])
readTargetSelectorsWith dirActions@DirActions{..} pkgs targetStrs =
case parseTargetStrings targetStrs of
([], utargets) -> do
utargets' <- mapM (getTargetStringFileStatus dirActions) utargets
pkgs' <- mapM (selectPackageInfo dirActions) pkgs
cwd <- getCurrentDirectory
let (cwdPkg, otherPkgs) = selectCwdPackage cwd pkgs'
case resolveTargetSelectors cwdPkg otherPkgs utargets' of
([], btargets) -> return (Right (map (fmap packageId) btargets))
(problems, _) -> return (Left problems)
(strs, _) -> return (Left (map TargetSelectorUnrecognised strs))
where
selectCwdPackage :: FilePath
-> [PackageInfo]
-> ([PackageInfo], [PackageInfo])
selectCwdPackage cwd pkgs' =
let (cwdpkg, others) = partition isPkgDirCwd pkgs'
in (cwdpkg, others)
where
isPkgDirCwd PackageInfo { pinfoDirectory = Just (dir,_) }
| dir == cwd = True
isPkgDirCwd _ = False
data DirActions m = DirActions {
doesFileExist :: FilePath -> m Bool,
doesDirectoryExist :: FilePath -> m Bool,
canonicalizePath :: FilePath -> m FilePath,
getCurrentDirectory :: m FilePath
}
defaultDirActions :: DirActions IO
defaultDirActions =
DirActions {
doesFileExist = IO.doesFileExist,
doesDirectoryExist = IO.doesDirectoryExist,
-- Workaround for <https://github.com/haskell/directory/issues/63>
canonicalizePath = IO.canonicalizePath . dropTrailingPathSeparator,
getCurrentDirectory = IO.getCurrentDirectory
}
makeRelativeToCwd :: Applicative m => DirActions m -> FilePath -> m FilePath
makeRelativeToCwd DirActions{..} path =
makeRelativeCanonical <$> canonicalizePath path <*> getCurrentDirectory
-- ------------------------------------------------------------
-- * Parsing target strings
-- ------------------------------------------------------------
-- | The outline parse of a target selector. It takes one of the forms:
--
-- > str1
-- > str1:str2
-- > str1:str2:str3
-- > str1:str2:str3:str4
--
data TargetString =
TargetString1 String
| TargetString2 String String
| TargetString3 String String String
| TargetString4 String String String String
| TargetString5 String String String String String
| TargetString7 String String String String String String String
deriving (Show, Eq)
-- | Parse a bunch of 'TargetString's (purely without throwing exceptions).
--
parseTargetStrings :: [String] -> ([String], [TargetString])
parseTargetStrings =
partitionEithers
. map (\str -> maybe (Left str) Right (parseTargetString str))
parseTargetString :: String -> Maybe TargetString
parseTargetString =
readPToMaybe parseTargetApprox
where
parseTargetApprox :: Parse.ReadP r TargetString
parseTargetApprox =
(do a <- tokenQ
return (TargetString1 a))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- tokenQ
return (TargetString2 a b))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- tokenQ
_ <- Parse.char ':'
c <- tokenQ
return (TargetString3 a b c))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- token
_ <- Parse.char ':'
c <- tokenQ
_ <- Parse.char ':'
d <- tokenQ
return (TargetString4 a b c d))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- token
_ <- Parse.char ':'
c <- tokenQ
_ <- Parse.char ':'
d <- tokenQ
_ <- Parse.char ':'
e <- tokenQ
return (TargetString5 a b c d e))
+++ (do a <- tokenQ0
_ <- Parse.char ':'
b <- token
_ <- Parse.char ':'
c <- tokenQ
_ <- Parse.char ':'
d <- tokenQ
_ <- Parse.char ':'
e <- tokenQ
_ <- Parse.char ':'
f <- tokenQ
_ <- Parse.char ':'
g <- tokenQ
return (TargetString7 a b c d e f g))
token = Parse.munch1 (\x -> not (isSpace x) && x /= ':')
tokenQ = parseHaskellString <++ token
token0 = Parse.munch (\x -> not (isSpace x) && x /= ':')
tokenQ0= parseHaskellString <++ token0
parseHaskellString :: Parse.ReadP r String
parseHaskellString = Parse.readS_to_P reads
-- | Render a 'TargetString' back as the external syntax. This is mainly for
-- error messages.
--
showTargetString :: TargetString -> String
showTargetString = intercalate ":" . components
where
components (TargetString1 s1) = [s1]
components (TargetString2 s1 s2) = [s1,s2]
components (TargetString3 s1 s2 s3) = [s1,s2,s3]
components (TargetString4 s1 s2 s3 s4) = [s1,s2,s3,s4]
components (TargetString5 s1 s2 s3 s4 s5) = [s1,s2,s3,s4,s5]
components (TargetString7 s1 s2 s3 s4 s5 s6 s7) = [s1,s2,s3,s4,s5,s6,s7]
showTargetSelector :: Package p => TargetSelector p -> String
showTargetSelector ts =
case [ t | ql <- [QL1 .. QLFull]
, t <- renderTargetSelector ql ts ]
of (t':_) -> showTargetString (forgetFileStatus t')
[] -> ""
showTargetSelectorKind :: TargetSelector a -> String
showTargetSelectorKind bt = case bt of
TargetPackage TargetExplicitNamed _ Nothing -> "package"
TargetPackage TargetExplicitNamed _ (Just _) -> "package:filter"
TargetPackage TargetImplicitCwd _ Nothing -> "cwd-package"
TargetPackage TargetImplicitCwd _ (Just _) -> "cwd-package:filter"
TargetAllPackages Nothing -> "all-packages"
TargetAllPackages (Just _) -> "all-packages:filter"
TargetComponent _ _ WholeComponent -> "component"
TargetComponent _ _ ModuleTarget{} -> "module"
TargetComponent _ _ FileTarget{} -> "file"
-- ------------------------------------------------------------
-- * Checking if targets exist as files
-- ------------------------------------------------------------
data TargetStringFileStatus =
TargetStringFileStatus1 String FileStatus
| TargetStringFileStatus2 String FileStatus String
| TargetStringFileStatus3 String FileStatus String String
| TargetStringFileStatus4 String String String String
| TargetStringFileStatus5 String String String String String
| TargetStringFileStatus7 String String String String String String String
deriving (Eq, Ord, Show)
data FileStatus = FileStatusExistsFile FilePath -- the canonicalised filepath
| FileStatusExistsDir FilePath -- the canonicalised filepath
| FileStatusNotExists Bool -- does the parent dir exist even?
deriving (Eq, Ord, Show)
noFileStatus :: FileStatus
noFileStatus = FileStatusNotExists False
getTargetStringFileStatus :: (Applicative m, Monad m) => DirActions m
-> TargetString -> m TargetStringFileStatus
getTargetStringFileStatus DirActions{..} t =
case t of
TargetString1 s1 ->
(\f1 -> TargetStringFileStatus1 s1 f1) <$> fileStatus s1
TargetString2 s1 s2 ->
(\f1 -> TargetStringFileStatus2 s1 f1 s2) <$> fileStatus s1
TargetString3 s1 s2 s3 ->
(\f1 -> TargetStringFileStatus3 s1 f1 s2 s3) <$> fileStatus s1
TargetString4 s1 s2 s3 s4 ->
return (TargetStringFileStatus4 s1 s2 s3 s4)
TargetString5 s1 s2 s3 s4 s5 ->
return (TargetStringFileStatus5 s1 s2 s3 s4 s5)
TargetString7 s1 s2 s3 s4 s5 s6 s7 ->
return (TargetStringFileStatus7 s1 s2 s3 s4 s5 s6 s7)
where
fileStatus f = do
fexists <- doesFileExist f
dexists <- doesDirectoryExist f
case splitPath f of
_ | fexists -> FileStatusExistsFile <$> canonicalizePath f
| dexists -> FileStatusExistsDir <$> canonicalizePath f
(d:_) -> FileStatusNotExists <$> doesDirectoryExist d
_ -> pure (FileStatusNotExists False)
forgetFileStatus :: TargetStringFileStatus -> TargetString
forgetFileStatus t = case t of
TargetStringFileStatus1 s1 _ -> TargetString1 s1
TargetStringFileStatus2 s1 _ s2 -> TargetString2 s1 s2
TargetStringFileStatus3 s1 _ s2 s3 -> TargetString3 s1 s2 s3
TargetStringFileStatus4 s1 s2 s3 s4 -> TargetString4 s1 s2 s3 s4
TargetStringFileStatus5 s1 s2 s3 s4
s5 -> TargetString5 s1 s2 s3 s4 s5
TargetStringFileStatus7 s1 s2 s3 s4
s5 s6 s7 -> TargetString7 s1 s2 s3 s4 s5 s6 s7
-- ------------------------------------------------------------
-- * Resolving target strings to target selectors
-- ------------------------------------------------------------
-- | Given a bunch of user-specified targets, try to resolve what it is they
-- refer to.
--
resolveTargetSelectors :: [PackageInfo] -- any pkg in the cur dir
-> [PackageInfo] -- all the other local packages
-> [TargetStringFileStatus]
-> ([TargetSelectorProblem],
[TargetSelector PackageInfo])
-- default local dir target if there's no given target:
resolveTargetSelectors [] [] [] =
([TargetSelectorNoTargetsInProject], [])
resolveTargetSelectors [] _opinfo [] =
([TargetSelectorNoTargetsInCwd], [])
resolveTargetSelectors ppinfo _opinfo [] =
([], [TargetPackage TargetImplicitCwd (head ppinfo) Nothing])
--TODO: in future allow multiple packages in the same dir
resolveTargetSelectors ppinfo opinfo targetStrs =
partitionEithers
. map (resolveTargetSelector ppinfo opinfo)
$ targetStrs
resolveTargetSelector :: [PackageInfo] -> [PackageInfo]
-> TargetStringFileStatus
-> Either TargetSelectorProblem
(TargetSelector PackageInfo)
resolveTargetSelector ppinfo opinfo targetStrStatus =
case findMatch (matcher targetStrStatus) of
Unambiguous _
| projectIsEmpty -> Left TargetSelectorNoTargetsInProject
Unambiguous (TargetPackage TargetImplicitCwd _ mkfilter)
| null ppinfo -> Left (TargetSelectorNoCurrentPackage targetStr)
| otherwise -> Right (TargetPackage TargetImplicitCwd
(head ppinfo) mkfilter)
--TODO: in future allow multiple packages in the same dir
Unambiguous target -> Right target
None errs
| projectIsEmpty -> Left TargetSelectorNoTargetsInProject
| otherwise -> Left (classifyMatchErrors errs)
Ambiguous exactMatch targets ->
case disambiguateTargetSelectors
matcher targetStrStatus exactMatch
targets of
Right targets' -> Left (TargetSelectorAmbiguous targetStr
(map (fmap (fmap packageId)) targets'))
Left ((m, ms):_) -> Left (MatchingInternalError targetStr
(fmap packageId m)
(map (fmap (map (fmap packageId))) ms))
Left [] -> internalError "resolveTargetSelector"
where
matcher = matchTargetSelector ppinfo opinfo
targetStr = forgetFileStatus targetStrStatus
projectIsEmpty = null ppinfo && null opinfo
classifyMatchErrors errs
| not (null expected)
= let (things, got:_) = unzip expected in
TargetSelectorExpected targetStr things got
| not (null nosuch)
= TargetSelectorNoSuch targetStr nosuch
| otherwise
= internalError $ "classifyMatchErrors: " ++ show errs
where
expected = [ (thing, got)
| (_, MatchErrorExpected thing got)
<- map (innerErr Nothing) errs ]
-- Trim the list of alternatives by dropping duplicates and
-- retaining only at most three most similar (by edit distance) ones.
nosuch = Map.foldrWithKey genResults [] $ Map.fromListWith Set.union $
[ ((inside, thing, got), Set.fromList alts)
| (inside, MatchErrorNoSuch thing got alts)
<- map (innerErr Nothing) errs
]
genResults (inside, thing, got) alts acc = (
inside
, thing
, got
, take maxResults
$ map fst
$ takeWhile distanceLow
$ sortBy (comparing snd)
$ map addLevDist
$ Set.toList alts
) : acc
where
addLevDist = id &&& restrictedDamerauLevenshteinDistance
defaultEditCosts got
distanceLow (_, dist) = dist < length got `div` 2
maxResults = 3
innerErr _ (MatchErrorIn kind thing m)
= innerErr (Just (kind,thing)) m
innerErr c m = (c,m)
-- | The various ways that trying to resolve a 'TargetString' to a
-- 'TargetSelector' can fail.
--
data TargetSelectorProblem
= TargetSelectorExpected TargetString [String] String
-- ^ [expected thing] (actually got)
| TargetSelectorNoSuch TargetString
[(Maybe (String, String), String, String, [String])]
-- ^ [([in thing], no such thing, actually got, alternatives)]
| TargetSelectorAmbiguous TargetString
[(TargetString, TargetSelector PackageId)]
| MatchingInternalError TargetString (TargetSelector PackageId)
[(TargetString, [TargetSelector PackageId])]
| TargetSelectorUnrecognised String
-- ^ Syntax error when trying to parse a target string.
| TargetSelectorNoCurrentPackage TargetString
| TargetSelectorNoTargetsInCwd
| TargetSelectorNoTargetsInProject
deriving (Show, Eq)
data QualLevel = QL1 | QL2 | QL3 | QLFull
deriving (Eq, Enum, Show)
disambiguateTargetSelectors
:: (TargetStringFileStatus -> Match (TargetSelector PackageInfo))
-> TargetStringFileStatus -> Bool
-> [TargetSelector PackageInfo]
-> Either [(TargetSelector PackageInfo,
[(TargetString, [TargetSelector PackageInfo])])]
[(TargetString, TargetSelector PackageInfo)]
disambiguateTargetSelectors matcher matchInput exactMatch matchResults =
case partitionEithers results of
(errs@(_:_), _) -> Left errs
([], ok) -> Right ok
where
-- So, here's the strategy. We take the original match results, and make a
-- table of all their renderings at all qualification levels.
-- Note there can be multiple renderings at each qualification level.
matchResultsRenderings :: [(TargetSelector PackageInfo,
[TargetStringFileStatus])]
matchResultsRenderings =
[ (matchResult, matchRenderings)
| matchResult <- matchResults
, let matchRenderings =
[ rendering
| ql <- [QL1 .. QLFull]
, rendering <- renderTargetSelector ql matchResult ]
]
-- Of course the point is that we're looking for renderings that are
-- unambiguous matches. So we build another memo table of all the matches
-- for all of those renderings. So by looking up in this table we can see
-- if we've got an unambiguous match.
memoisedMatches :: Map TargetStringFileStatus
(Match (TargetSelector PackageInfo))
memoisedMatches =
-- avoid recomputing the main one if it was an exact match
(if exactMatch then Map.insert matchInput (ExactMatch 0 matchResults)
else id)
$ Map.Lazy.fromList
[ (rendering, matcher rendering)
| rendering <- concatMap snd matchResultsRenderings ]
-- Finally, for each of the match results, we go through all their
-- possible renderings (in order of qualification level, though remember
-- there can be multiple renderings per level), and find the first one
-- that has an unambiguous match.
results :: [Either (TargetSelector PackageInfo,
[(TargetString, [TargetSelector PackageInfo])])
(TargetString, TargetSelector PackageInfo)]
results =
[ case findUnambiguous originalMatch matchRenderings of
Just unambiguousRendering ->
Right ( forgetFileStatus unambiguousRendering
, originalMatch)
-- This case is an internal error, but we bubble it up and report it
Nothing ->
Left ( originalMatch
, [ (forgetFileStatus rendering, matches)
| rendering <- matchRenderings
, let (ExactMatch _ matches) =
memoisedMatches Map.! rendering
] )
| (originalMatch, matchRenderings) <- matchResultsRenderings ]
findUnambiguous :: TargetSelector PackageInfo
-> [TargetStringFileStatus]
-> Maybe TargetStringFileStatus
findUnambiguous _ [] = Nothing
findUnambiguous t (r:rs) =
case memoisedMatches Map.! r of
ExactMatch _ [t'] | fmap packageName t == fmap packageName t'
-> Just r
ExactMatch _ _ -> findUnambiguous t rs
InexactMatch _ _ -> internalError "InexactMatch"
NoMatch _ _ -> internalError "NoMatch"
internalError :: String -> a
internalError msg =
error $ "TargetSelector: internal error: " ++ msg
-- | Throw an exception with a formatted message if there are any problems.
--
reportTargetSelectorProblems :: Verbosity -> [TargetSelectorProblem] -> IO a
reportTargetSelectorProblems verbosity problems = do
case [ str | TargetSelectorUnrecognised str <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Unrecognised target syntax for '" ++ name ++ "'."
| name <- targets ]
case [ (t, m, ms) | MatchingInternalError t m ms <- problems ] of
[] -> return ()
((target, originalMatch, renderingsAndMatches):_) ->
die' verbosity $ "Internal error in target matching. It should always "
++ "be possible to find a syntax that's sufficiently qualified to "
++ "give an unambiguous match. However when matching '"
++ showTargetString target ++ "' we found "
++ showTargetSelector originalMatch
++ " (" ++ showTargetSelectorKind originalMatch ++ ") which does "
++ "not have an unambiguous syntax. The possible syntax and the "
++ "targets they match are as follows:\n"
++ unlines
[ "'" ++ showTargetString rendering ++ "' which matches "
++ intercalate ", "
[ showTargetSelector match ++
" (" ++ showTargetSelectorKind match ++ ")"
| match <- matches ]
| (rendering, matches) <- renderingsAndMatches ]
case [ (t, e, g) | TargetSelectorExpected t e g <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Unrecognised target '" ++ showTargetString target
++ "'.\n"
++ "Expected a " ++ intercalate " or " expected
++ ", rather than '" ++ got ++ "'."
| (target, expected, got) <- targets ]
case [ (t, e) | TargetSelectorNoSuch t e <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Unknown target '" ++ showTargetString target ++
"'.\n" ++ unlines
[ (case inside of
Just (kind, "")
-> "The " ++ kind ++ " has no "
Just (kind, thing)
-> "The " ++ kind ++ " " ++ thing ++ " has no "
Nothing -> "There is no ")
++ intercalate " or " [ mungeThing thing ++ " '" ++ got ++ "'"
| (thing, got, _alts) <- nosuch' ] ++ "."
++ if null alternatives then "" else
"\nPerhaps you meant " ++ intercalate ";\nor "
[ "the " ++ thing ++ " '" ++ intercalate "' or '" alts ++ "'?"
| (thing, alts) <- alternatives ]
| (inside, nosuch') <- groupByContainer nosuch
, let alternatives =
[ (thing, alts)
| (thing,_got,alts@(_:_)) <- nosuch' ]
]
| (target, nosuch) <- targets
, let groupByContainer =
map (\g@((inside,_,_,_):_) ->
(inside, [ (thing,got,alts)
| (_,thing,got,alts) <- g ]))
. groupBy ((==) `on` (\(x,_,_,_) -> x))
. sortBy (compare `on` (\(x,_,_,_) -> x))
]
where
mungeThing "file" = "file target"
mungeThing thing = thing
case [ (t, ts) | TargetSelectorAmbiguous t ts <- problems ] of
[] -> return ()
targets ->
die' verbosity $ unlines
[ "Ambiguous target '" ++ showTargetString target
++ "'. It could be:\n "
++ unlines [ " "++ showTargetString ut ++
" (" ++ showTargetSelectorKind bt ++ ")"
| (ut, bt) <- amb ]
| (target, amb) <- targets ]
case [ t | TargetSelectorNoCurrentPackage t <- problems ] of
[] -> return ()
target:_ ->
die' verbosity $
"The target '" ++ showTargetString target ++ "' refers to the "
++ "components in the package in the current directory, but there "
++ "is no package in the current directory (or at least not listed "
++ "as part of the project)."
--TODO: report a different error if there is a .cabal file but it's
-- not a member of the project
case [ () | TargetSelectorNoTargetsInCwd <- problems ] of
[] -> return ()
_:_ ->
die' verbosity $
"No targets given and there is no package in the current "
++ "directory. Use the target 'all' for all packages in the "
++ "project or specify packages or components by name or location. "
++ "See 'cabal build --help' for more details on target options."
case [ () | TargetSelectorNoTargetsInProject <- problems ] of
[] -> return ()
_:_ ->
die' verbosity $
"There is no <pkgname>.cabal package file or cabal.project file. "
++ "To build packages locally you need at minimum a <pkgname>.cabal "
++ "file. You can use 'cabal init' to create one.\n"
++ "\n"
++ "For non-trivial projects you will also want a cabal.project "
++ "file in the root directory of your project. This file lists the "
++ "packages in your project and all other build configuration. "
++ "See the Cabal user guide for full details."
fail "reportTargetSelectorProblems: internal error"
----------------------------------
-- Syntax type
--
-- | Syntax for the 'TargetSelector': the matcher and renderer
--
data Syntax = Syntax QualLevel Matcher Renderer
| AmbiguousAlternatives Syntax Syntax
| ShadowingAlternatives Syntax Syntax
type Matcher = TargetStringFileStatus -> Match (TargetSelector PackageInfo)
type Renderer = TargetSelector PackageId -> [TargetStringFileStatus]
foldSyntax :: (a -> a -> a) -> (a -> a -> a)
-> (QualLevel -> Matcher -> Renderer -> a)
-> (Syntax -> a)
foldSyntax ambiguous unambiguous syntax = go
where
go (Syntax ql match render) = syntax ql match render
go (AmbiguousAlternatives a b) = ambiguous (go a) (go b)
go (ShadowingAlternatives a b) = unambiguous (go a) (go b)
----------------------------------
-- Top level renderer and matcher
--
renderTargetSelector :: Package p => QualLevel -> TargetSelector p
-> [TargetStringFileStatus]
renderTargetSelector ql ts =
foldSyntax
(++) (++)
(\ql' _ render -> guard (ql == ql') >> render (fmap packageId ts))
syntax
where
syntax = syntaxForms [] [] -- don't need pinfo for rendering
matchTargetSelector :: [PackageInfo] -> [PackageInfo]
-> TargetStringFileStatus
-> Match (TargetSelector PackageInfo)
matchTargetSelector ppinfo opinfo = \utarget ->
nubMatchesBy ((==) `on` (fmap packageName)) $
let ql = targetQualLevel utarget in
foldSyntax
(<|>) (<//>)
(\ql' match _ -> guard (ql == ql') >> match utarget)
syntax
where
syntax = syntaxForms ppinfo opinfo
targetQualLevel TargetStringFileStatus1{} = QL1
targetQualLevel TargetStringFileStatus2{} = QL2
targetQualLevel TargetStringFileStatus3{} = QL3
targetQualLevel TargetStringFileStatus4{} = QLFull
targetQualLevel TargetStringFileStatus5{} = QLFull
targetQualLevel TargetStringFileStatus7{} = QLFull
----------------------------------
-- Syntax forms
--
-- | All the forms of syntax for 'TargetSelector'.
--
syntaxForms :: [PackageInfo] -> [PackageInfo] -> Syntax
syntaxForms ppinfo opinfo =
-- The various forms of syntax here are ambiguous in many cases.
-- Our policy is by default we expose that ambiguity and report
-- ambiguous matches. In certain cases we override the ambiguity
-- by having some forms shadow others.
--
-- We make modules shadow files because module name "Q" clashes
-- with file "Q" with no extension but these refer to the same
-- thing anyway so it's not a useful ambiguity. Other cases are
-- not ambiguous like "Q" vs "Q.hs" or "Data.Q" vs "Data/Q".
ambiguousAlternatives
-- convenient single-component forms
[ shadowingAlternatives
[ ambiguousAlternatives
[ syntaxForm1All
, syntaxForm1Filter
, shadowingAlternatives
[ syntaxForm1Component pcinfo
, syntaxForm1Package pinfo
]
]
, syntaxForm1Component ocinfo
, syntaxForm1Module cinfo
, syntaxForm1File pinfo
]
-- two-component partially qualified forms
-- fully qualified form for 'all'
, syntaxForm2MetaAll
, syntaxForm2AllFilter
, syntaxForm2NamespacePackage pinfo
, syntaxForm2PackageComponent pinfo
, syntaxForm2PackageFilter pinfo
, syntaxForm2KindComponent cinfo
, shadowingAlternatives
[ syntaxForm2PackageModule pinfo
, syntaxForm2PackageFile pinfo
]
, shadowingAlternatives
[ syntaxForm2ComponentModule cinfo
, syntaxForm2ComponentFile cinfo
]
-- rarely used partially qualified forms
, syntaxForm3PackageKindComponent pinfo
, shadowingAlternatives
[ syntaxForm3PackageComponentModule pinfo
, syntaxForm3PackageComponentFile pinfo
]
, shadowingAlternatives
[ syntaxForm3KindComponentModule cinfo
, syntaxForm3KindComponentFile cinfo
]
, syntaxForm3NamespacePackageFilter pinfo
-- fully-qualified forms for all and cwd with filter
, syntaxForm3MetaAllFilter
, syntaxForm3MetaCwdFilter
-- fully-qualified form for package and package with filter
, syntaxForm3MetaNamespacePackage pinfo
, syntaxForm4MetaNamespacePackageFilter pinfo
-- fully-qualified forms for component, module and file
, syntaxForm5MetaNamespacePackageKindComponent pinfo
, syntaxForm7MetaNamespacePackageKindComponentNamespaceModule pinfo
, syntaxForm7MetaNamespacePackageKindComponentNamespaceFile pinfo
]
where
ambiguousAlternatives = foldr1 AmbiguousAlternatives
shadowingAlternatives = foldr1 ShadowingAlternatives
pinfo = ppinfo ++ opinfo
cinfo = concatMap pinfoComponents pinfo
pcinfo = concatMap pinfoComponents ppinfo
ocinfo = concatMap pinfoComponents opinfo
-- | Syntax: "all" to select all packages in the project
--
-- > cabal build all
--
syntaxForm1All :: Syntax
syntaxForm1All =
syntaxForm1 render $ \str1 _fstatus1 -> do
guardMetaAll str1
return (TargetAllPackages Nothing)
where
render (TargetAllPackages Nothing) =
[TargetStringFileStatus1 "all" noFileStatus]
render _ = []
-- | Syntax: filter
--
-- > cabal build tests
--
syntaxForm1Filter :: Syntax
syntaxForm1Filter =
syntaxForm1 render $ \str1 _fstatus1 -> do
kfilter <- matchComponentKindFilter str1
return (TargetPackage TargetImplicitCwd dummyPackageInfo (Just kfilter))
where
render (TargetPackage TargetImplicitCwd _ (Just kfilter)) =
[TargetStringFileStatus1 (dispF kfilter) noFileStatus]
render _ = []
-- Only used for TargetPackage TargetImplicitCwd
dummyPackageInfo :: PackageInfo
dummyPackageInfo =
PackageInfo {
pinfoId = PackageIdentifier
(mkPackageName "dummyPackageInfo")
(mkVersion []),
pinfoLocation = unused,
pinfoDirectory = unused,
pinfoPackageFile = unused,
pinfoComponents = unused
}
where
unused = error "dummyPackageInfo"
-- | Syntax: package (name, dir or file)
--
-- > cabal build foo
-- > cabal build ../bar ../bar/bar.cabal
--
syntaxForm1Package :: [PackageInfo] -> Syntax
syntaxForm1Package pinfo =
syntaxForm1 render $ \str1 fstatus1 -> do
guardPackage str1 fstatus1
p <- matchPackage pinfo str1 fstatus1
return (TargetPackage TargetExplicitNamed p Nothing)
where
render (TargetPackage TargetExplicitNamed p Nothing) =
[TargetStringFileStatus1 (dispP p) noFileStatus]
render _ = []
-- | Syntax: component
--
-- > cabal build foo
--
syntaxForm1Component :: [ComponentInfo] -> Syntax
syntaxForm1Component cs =
syntaxForm1 render $ \str1 _fstatus1 -> do
guardComponentName str1
c <- matchComponentName cs str1
return (TargetComponent (cinfoPackage c) (cinfoName c) WholeComponent)
where
render (TargetComponent p c WholeComponent) =
[TargetStringFileStatus1 (dispC p c) noFileStatus]
render _ = []
-- | Syntax: module
--
-- > cabal build Data.Foo
--
syntaxForm1Module :: [ComponentInfo] -> Syntax
syntaxForm1Module cs =
syntaxForm1 render $ \str1 _fstatus1 -> do
guardModuleName str1
let ms = [ (m,c) | c <- cs, m <- cinfoModules c ]
(m,c) <- matchModuleNameAnd ms str1
return (TargetComponent (cinfoPackage c) (cinfoName c) (ModuleTarget m))
where
render (TargetComponent _p _c (ModuleTarget m)) =
[TargetStringFileStatus1 (dispM m) noFileStatus]
render _ = []
-- | Syntax: file name
--
-- > cabal build Data/Foo.hs bar/Main.hsc
--
syntaxForm1File :: [PackageInfo] -> Syntax
syntaxForm1File ps =
-- Note there's a bit of an inconsistency here vs the other syntax forms
-- for files. For the single-part syntax the target has to point to a file
-- that exists (due to our use of matchPackageDirectoryPrefix), whereas for
-- all the other forms we don't require that.
syntaxForm1 render $ \str1 fstatus1 ->
expecting "file" str1 $ do
(pkgfile, p) <- matchPackageDirectoryPrefix ps fstatus1
orNoThingIn "package" (display (packageName p)) $ do
(filepath, c) <- matchComponentFile (pinfoComponents p) pkgfile
return (TargetComponent p (cinfoName c) (FileTarget filepath))
where
render (TargetComponent _p _c (FileTarget f)) =
[TargetStringFileStatus1 f noFileStatus]
render _ = []
---
-- | Syntax: :all
--
-- > cabal build :all
--
syntaxForm2MetaAll :: Syntax
syntaxForm2MetaAll =
syntaxForm2 render $ \str1 _fstatus1 str2 -> do
guardNamespaceMeta str1
guardMetaAll str2
return (TargetAllPackages Nothing)
where
render (TargetAllPackages Nothing) =
[TargetStringFileStatus2 "" noFileStatus "all"]
render _ = []
-- | Syntax: all : filer
--
-- > cabal build all:tests
--
syntaxForm2AllFilter :: Syntax
syntaxForm2AllFilter =
syntaxForm2 render $ \str1 _fstatus1 str2 -> do
guardMetaAll str1
kfilter <- matchComponentKindFilter str2
return (TargetAllPackages (Just kfilter))
where
render (TargetAllPackages (Just kfilter)) =
[TargetStringFileStatus2 "all" noFileStatus (dispF kfilter)]
render _ = []
-- | Syntax: package : filer
--
-- > cabal build foo:tests
--
syntaxForm2PackageFilter :: [PackageInfo] -> Syntax
syntaxForm2PackageFilter ps =
syntaxForm2 render $ \str1 fstatus1 str2 -> do
guardPackage str1 fstatus1
p <- matchPackage ps str1 fstatus1
kfilter <- matchComponentKindFilter str2
return (TargetPackage TargetExplicitNamed p (Just kfilter))
where
render (TargetPackage TargetExplicitNamed p (Just kfilter)) =
[TargetStringFileStatus2 (dispP p) noFileStatus (dispF kfilter)]
render _ = []
-- | Syntax: pkg : package name
--
-- > cabal build pkg:foo
--
syntaxForm2NamespacePackage :: [PackageInfo] -> Syntax
syntaxForm2NamespacePackage pinfo =
syntaxForm2 render $ \str1 _fstatus1 str2 -> do
guardNamespacePackage str1
guardPackageName str2
p <- matchPackage pinfo str2 noFileStatus
return (TargetPackage TargetExplicitNamed p Nothing)
where
render (TargetPackage TargetExplicitNamed p Nothing) =
[TargetStringFileStatus2 "pkg" noFileStatus (dispP p)]
render _ = []
-- | Syntax: package : component
--
-- > cabal build foo:foo
-- > cabal build ./foo:foo
-- > cabal build ./foo.cabal:foo
--
syntaxForm2PackageComponent :: [PackageInfo] -> Syntax
syntaxForm2PackageComponent ps =
syntaxForm2 render $ \str1 fstatus1 str2 -> do
guardPackage str1 fstatus1
guardComponentName str2
p <- matchPackage ps str1 fstatus1
orNoThingIn "package" (display (packageName p)) $ do
c <- matchComponentName (pinfoComponents p) str2
return (TargetComponent p (cinfoName c) WholeComponent)
--TODO: the error here ought to say there's no component by that name in
-- this package, and name the package
where
render (TargetComponent p c WholeComponent) =
[TargetStringFileStatus2 (dispP p) noFileStatus (dispC p c)]
render _ = []
-- | Syntax: namespace : component
--
-- > cabal build lib:foo exe:foo
--
syntaxForm2KindComponent :: [ComponentInfo] -> Syntax
syntaxForm2KindComponent cs =
syntaxForm2 render $ \str1 _fstatus1 str2 -> do
ckind <- matchComponentKind str1
guardComponentName str2
c <- matchComponentKindAndName cs ckind str2
return (TargetComponent (cinfoPackage c) (cinfoName c) WholeComponent)
where
render (TargetComponent p c WholeComponent) =
[TargetStringFileStatus2 (dispK c) noFileStatus (dispC p c)]
render _ = []
-- | Syntax: package : module
--
-- > cabal build foo:Data.Foo
-- > cabal build ./foo:Data.Foo
-- > cabal build ./foo.cabal:Data.Foo
--
syntaxForm2PackageModule :: [PackageInfo] -> Syntax
syntaxForm2PackageModule ps =
syntaxForm2 render $ \str1 fstatus1 str2 -> do
guardPackage str1 fstatus1
guardModuleName str2
p <- matchPackage ps str1 fstatus1
orNoThingIn "package" (display (packageName p)) $ do
let ms = [ (m,c) | c <- pinfoComponents p, m <- cinfoModules c ]
(m,c) <- matchModuleNameAnd ms str2
return (TargetComponent p (cinfoName c) (ModuleTarget m))
where
render (TargetComponent p _c (ModuleTarget m)) =
[TargetStringFileStatus2 (dispP p) noFileStatus (dispM m)]
render _ = []
-- | Syntax: component : module
--
-- > cabal build foo:Data.Foo
--
syntaxForm2ComponentModule :: [ComponentInfo] -> Syntax
syntaxForm2ComponentModule cs =
syntaxForm2 render $ \str1 _fstatus1 str2 -> do
guardComponentName str1
guardModuleName str2
c <- matchComponentName cs str1
orNoThingIn "component" (cinfoStrName c) $ do
let ms = cinfoModules c
m <- matchModuleName ms str2
return (TargetComponent (cinfoPackage c) (cinfoName c)
(ModuleTarget m))
where
render (TargetComponent p c (ModuleTarget m)) =
[TargetStringFileStatus2 (dispC p c) noFileStatus (dispM m)]
render _ = []
-- | Syntax: package : filename
--
-- > cabal build foo:Data/Foo.hs
-- > cabal build ./foo:Data/Foo.hs
-- > cabal build ./foo.cabal:Data/Foo.hs
--
syntaxForm2PackageFile :: [PackageInfo] -> Syntax
syntaxForm2PackageFile ps =
syntaxForm2 render $ \str1 fstatus1 str2 -> do
guardPackage str1 fstatus1
p <- matchPackage ps str1 fstatus1
orNoThingIn "package" (display (packageName p)) $ do
(filepath, c) <- matchComponentFile (pinfoComponents p) str2
return (TargetComponent p (cinfoName c) (FileTarget filepath))
where
render (TargetComponent p _c (FileTarget f)) =
[TargetStringFileStatus2 (dispP p) noFileStatus f]
render _ = []
-- | Syntax: component : filename
--
-- > cabal build foo:Data/Foo.hs
--
syntaxForm2ComponentFile :: [ComponentInfo] -> Syntax
syntaxForm2ComponentFile cs =
syntaxForm2 render $ \str1 _fstatus1 str2 -> do
guardComponentName str1
c <- matchComponentName cs str1
orNoThingIn "component" (cinfoStrName c) $ do
(filepath, _) <- matchComponentFile [c] str2
return (TargetComponent (cinfoPackage c) (cinfoName c)
(FileTarget filepath))
where
render (TargetComponent p c (FileTarget f)) =
[TargetStringFileStatus2 (dispC p c) noFileStatus f]
render _ = []
---
-- | Syntax: :all : filter
--
-- > cabal build :all:tests
--
syntaxForm3MetaAllFilter :: Syntax
syntaxForm3MetaAllFilter =
syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do
guardNamespaceMeta str1
guardMetaAll str2
kfilter <- matchComponentKindFilter str3
return (TargetAllPackages (Just kfilter))
where
render (TargetAllPackages (Just kfilter)) =
[TargetStringFileStatus3 "" noFileStatus "all" (dispF kfilter)]
render _ = []
syntaxForm3MetaCwdFilter :: Syntax
syntaxForm3MetaCwdFilter =
syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do
guardNamespaceMeta str1
guardNamespaceCwd str2
kfilter <- matchComponentKindFilter str3
return (TargetPackage TargetImplicitCwd dummyPackageInfo (Just kfilter))
where
render (TargetPackage TargetImplicitCwd _ (Just kfilter)) =
[TargetStringFileStatus3 "" noFileStatus "cwd" (dispF kfilter)]
render _ = []
-- | Syntax: :pkg : package name
--
-- > cabal build :pkg:foo
--
syntaxForm3MetaNamespacePackage :: [PackageInfo] -> Syntax
syntaxForm3MetaNamespacePackage pinfo =
syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do
guardNamespaceMeta str1
guardNamespacePackage str2
guardPackageName str3
p <- matchPackage pinfo str3 noFileStatus
return (TargetPackage TargetExplicitNamed p Nothing)
where
render (TargetPackage TargetExplicitNamed p Nothing) =
[TargetStringFileStatus3 "" noFileStatus "pkg" (dispP p)]
render _ = []
-- | Syntax: package : namespace : component
--
-- > cabal build foo:lib:foo
-- > cabal build foo/:lib:foo
-- > cabal build foo.cabal:lib:foo
--
syntaxForm3PackageKindComponent :: [PackageInfo] -> Syntax
syntaxForm3PackageKindComponent ps =
syntaxForm3 render $ \str1 fstatus1 str2 str3 -> do
guardPackage str1 fstatus1
ckind <- matchComponentKind str2
guardComponentName str3
p <- matchPackage ps str1 fstatus1
orNoThingIn "package" (display (packageName p)) $ do
c <- matchComponentKindAndName (pinfoComponents p) ckind str3
return (TargetComponent p (cinfoName c) WholeComponent)
where
render (TargetComponent p c WholeComponent) =
[TargetStringFileStatus3 (dispP p) noFileStatus (dispK c) (dispC p c)]
render _ = []
-- | Syntax: package : component : module
--
-- > cabal build foo:foo:Data.Foo
-- > cabal build foo/:foo:Data.Foo
-- > cabal build foo.cabal:foo:Data.Foo
--
syntaxForm3PackageComponentModule :: [PackageInfo] -> Syntax
syntaxForm3PackageComponentModule ps =
syntaxForm3 render $ \str1 fstatus1 str2 str3 -> do
guardPackage str1 fstatus1
guardComponentName str2
guardModuleName str3
p <- matchPackage ps str1 fstatus1
orNoThingIn "package" (display (packageName p)) $ do
c <- matchComponentName (pinfoComponents p) str2
orNoThingIn "component" (cinfoStrName c) $ do
let ms = cinfoModules c
m <- matchModuleName ms str3
return (TargetComponent p (cinfoName c) (ModuleTarget m))
where
render (TargetComponent p c (ModuleTarget m)) =
[TargetStringFileStatus3 (dispP p) noFileStatus (dispC p c) (dispM m)]
render _ = []
-- | Syntax: namespace : component : module
--
-- > cabal build lib:foo:Data.Foo
--
syntaxForm3KindComponentModule :: [ComponentInfo] -> Syntax
syntaxForm3KindComponentModule cs =
syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do
ckind <- matchComponentKind str1
guardComponentName str2
guardModuleName str3
c <- matchComponentKindAndName cs ckind str2
orNoThingIn "component" (cinfoStrName c) $ do
let ms = cinfoModules c
m <- matchModuleName ms str3
return (TargetComponent (cinfoPackage c) (cinfoName c)
(ModuleTarget m))
where
render (TargetComponent p c (ModuleTarget m)) =
[TargetStringFileStatus3 (dispK c) noFileStatus (dispC p c) (dispM m)]
render _ = []
-- | Syntax: package : component : filename
--
-- > cabal build foo:foo:Data/Foo.hs
-- > cabal build foo/:foo:Data/Foo.hs
-- > cabal build foo.cabal:foo:Data/Foo.hs
--
syntaxForm3PackageComponentFile :: [PackageInfo] -> Syntax
syntaxForm3PackageComponentFile ps =
syntaxForm3 render $ \str1 fstatus1 str2 str3 -> do
guardPackage str1 fstatus1
guardComponentName str2
p <- matchPackage ps str1 fstatus1
orNoThingIn "package" (display (packageName p)) $ do
c <- matchComponentName (pinfoComponents p) str2
orNoThingIn "component" (cinfoStrName c) $ do
(filepath, _) <- matchComponentFile [c] str3
return (TargetComponent p (cinfoName c) (FileTarget filepath))
where
render (TargetComponent p c (FileTarget f)) =
[TargetStringFileStatus3 (dispP p) noFileStatus (dispC p c) f]
render _ = []
-- | Syntax: namespace : component : filename
--
-- > cabal build lib:foo:Data/Foo.hs
--
syntaxForm3KindComponentFile :: [ComponentInfo] -> Syntax
syntaxForm3KindComponentFile cs =
syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do
ckind <- matchComponentKind str1
guardComponentName str2
c <- matchComponentKindAndName cs ckind str2
orNoThingIn "component" (cinfoStrName c) $ do
(filepath, _) <- matchComponentFile [c] str3
return (TargetComponent (cinfoPackage c) (cinfoName c)
(FileTarget filepath))
where
render (TargetComponent p c (FileTarget f)) =
[TargetStringFileStatus3 (dispK c) noFileStatus (dispC p c) f]
render _ = []
syntaxForm3NamespacePackageFilter :: [PackageInfo] -> Syntax
syntaxForm3NamespacePackageFilter ps =
syntaxForm3 render $ \str1 _fstatus1 str2 str3 -> do
guardNamespacePackage str1
guardPackageName str2
p <- matchPackage ps str2 noFileStatus
kfilter <- matchComponentKindFilter str3
return (TargetPackage TargetExplicitNamed p (Just kfilter))
where
render (TargetPackage TargetExplicitNamed p (Just kfilter)) =
[TargetStringFileStatus3 "pkg" noFileStatus (dispP p) (dispF kfilter)]
render _ = []
--
syntaxForm4MetaNamespacePackageFilter :: [PackageInfo] -> Syntax
syntaxForm4MetaNamespacePackageFilter ps =
syntaxForm4 render $ \str1 str2 str3 str4 -> do
guardNamespaceMeta str1
guardNamespacePackage str2
guardPackageName str3
p <- matchPackage ps str3 noFileStatus
kfilter <- matchComponentKindFilter str4
return (TargetPackage TargetExplicitNamed p (Just kfilter))
where
render (TargetPackage TargetExplicitNamed p (Just kfilter)) =
[TargetStringFileStatus4 "" "pkg" (dispP p) (dispF kfilter)]
render _ = []
-- | Syntax: :pkg : package : namespace : component
--
-- > cabal build :pkg:foo:lib:foo
--
syntaxForm5MetaNamespacePackageKindComponent :: [PackageInfo] -> Syntax
syntaxForm5MetaNamespacePackageKindComponent ps =
syntaxForm5 render $ \str1 str2 str3 str4 str5 -> do
guardNamespaceMeta str1
guardNamespacePackage str2
guardPackageName str3
ckind <- matchComponentKind str4
guardComponentName str5
p <- matchPackage ps str3 noFileStatus
orNoThingIn "package" (display (packageName p)) $ do
c <- matchComponentKindAndName (pinfoComponents p) ckind str5
return (TargetComponent p (cinfoName c) WholeComponent)
where
render (TargetComponent p c WholeComponent) =
[TargetStringFileStatus5 "" "pkg" (dispP p) (dispK c) (dispC p c)]
render _ = []
-- | Syntax: :pkg : package : namespace : component : module : module
--
-- > cabal build :pkg:foo:lib:foo:module:Data.Foo
--
syntaxForm7MetaNamespacePackageKindComponentNamespaceModule
:: [PackageInfo] -> Syntax
syntaxForm7MetaNamespacePackageKindComponentNamespaceModule ps =
syntaxForm7 render $ \str1 str2 str3 str4 str5 str6 str7 -> do
guardNamespaceMeta str1
guardNamespacePackage str2
guardPackageName str3
ckind <- matchComponentKind str4
guardComponentName str5
guardNamespaceModule str6
p <- matchPackage ps str3 noFileStatus
orNoThingIn "package" (display (packageName p)) $ do
c <- matchComponentKindAndName (pinfoComponents p) ckind str5
orNoThingIn "component" (cinfoStrName c) $ do
let ms = cinfoModules c
m <- matchModuleName ms str7
return (TargetComponent p (cinfoName c) (ModuleTarget m))
where
render (TargetComponent p c (ModuleTarget m)) =
[TargetStringFileStatus7 "" "pkg" (dispP p)
(dispK c) (dispC p c)
"module" (dispM m)]
render _ = []
-- | Syntax: :pkg : package : namespace : component : file : filename
--
-- > cabal build :pkg:foo:lib:foo:file:Data/Foo.hs
--
syntaxForm7MetaNamespacePackageKindComponentNamespaceFile
:: [PackageInfo] -> Syntax
syntaxForm7MetaNamespacePackageKindComponentNamespaceFile ps =
syntaxForm7 render $ \str1 str2 str3 str4 str5 str6 str7 -> do
guardNamespaceMeta str1
guardNamespacePackage str2
guardPackageName str3
ckind <- matchComponentKind str4
guardComponentName str5
guardNamespaceFile str6
p <- matchPackage ps str3 noFileStatus
orNoThingIn "package" (display (packageName p)) $ do
c <- matchComponentKindAndName (pinfoComponents p) ckind str5
orNoThingIn "component" (cinfoStrName c) $ do
(filepath,_) <- matchComponentFile [c] str7
return (TargetComponent p (cinfoName c) (FileTarget filepath))
where
render (TargetComponent p c (FileTarget f)) =
[TargetStringFileStatus7 "" "pkg" (dispP p)
(dispK c) (dispC p c)
"file" f]
render _ = []
---------------------------------------
-- Syntax utils
--
type Match1 = String -> FileStatus -> Match (TargetSelector PackageInfo)
type Match2 = String -> FileStatus -> String
-> Match (TargetSelector PackageInfo)
type Match3 = String -> FileStatus -> String -> String
-> Match (TargetSelector PackageInfo)
type Match4 = String -> String -> String -> String
-> Match (TargetSelector PackageInfo)
type Match5 = String -> String -> String -> String -> String
-> Match (TargetSelector PackageInfo)
type Match7 = String -> String -> String -> String -> String -> String -> String
-> Match (TargetSelector PackageInfo)
syntaxForm1 :: Renderer -> Match1 -> Syntax
syntaxForm2 :: Renderer -> Match2 -> Syntax
syntaxForm3 :: Renderer -> Match3 -> Syntax
syntaxForm4 :: Renderer -> Match4 -> Syntax
syntaxForm5 :: Renderer -> Match5 -> Syntax
syntaxForm7 :: Renderer -> Match7 -> Syntax
syntaxForm1 render f =
Syntax QL1 match render
where
match = \(TargetStringFileStatus1 str1 fstatus1) ->
f str1 fstatus1
syntaxForm2 render f =
Syntax QL2 match render
where
match = \(TargetStringFileStatus2 str1 fstatus1 str2) ->
f str1 fstatus1 str2
syntaxForm3 render f =
Syntax QL3 match render
where
match = \(TargetStringFileStatus3 str1 fstatus1 str2 str3) ->
f str1 fstatus1 str2 str3
syntaxForm4 render f =
Syntax QLFull match render
where
match (TargetStringFileStatus4 str1 str2 str3 str4)
= f str1 str2 str3 str4
match _ = mzero
syntaxForm5 render f =
Syntax QLFull match render
where
match (TargetStringFileStatus5 str1 str2 str3 str4 str5)
= f str1 str2 str3 str4 str5
match _ = mzero
syntaxForm7 render f =
Syntax QLFull match render
where
match (TargetStringFileStatus7 str1 str2 str3 str4 str5 str6 str7)
= f str1 str2 str3 str4 str5 str6 str7
match _ = mzero
dispP :: Package p => p -> String
dispP = display . packageName
dispC :: Package p => p -> ComponentName -> String
dispC = componentStringName
dispK :: ComponentName -> String
dispK = showComponentKindShort . componentKind
dispF :: ComponentKind -> String
dispF = showComponentKindFilterShort
dispM :: ModuleName -> String
dispM = display
-------------------------------
-- Package and component info
--
data PackageInfo = PackageInfo {
pinfoId :: PackageId,
pinfoLocation :: PackageLocation (),
pinfoDirectory :: Maybe (FilePath, FilePath),
pinfoPackageFile :: Maybe (FilePath, FilePath),
pinfoComponents :: [ComponentInfo]
}
-- not instance of Show due to recursive construction
data ComponentInfo = ComponentInfo {
cinfoName :: ComponentName,
cinfoStrName :: ComponentStringName,
cinfoPackage :: PackageInfo,
cinfoSrcDirs :: [FilePath],
cinfoModules :: [ModuleName],
cinfoHsFiles :: [FilePath], -- other hs files (like main.hs)
cinfoCFiles :: [FilePath],
cinfoJsFiles :: [FilePath]
}
-- not instance of Show due to recursive construction
type ComponentStringName = String
instance Package PackageInfo where
packageId = pinfoId
selectPackageInfo :: (Applicative m, Monad m) => DirActions m
-> SourcePackage (PackageLocation a) -> m PackageInfo
selectPackageInfo dirActions@DirActions{..}
SourcePackage {
packageDescription = pkg,
packageSource = loc
} = do
(pkgdir, pkgfile) <-
case loc of
--TODO: local tarballs, remote tarballs etc
LocalUnpackedPackage dir -> do
dirabs <- canonicalizePath dir
dirrel <- makeRelativeToCwd dirActions dirabs
--TODO: ought to get this earlier in project reading
let fileabs = dirabs </> display (packageName pkg) <.> "cabal"
filerel = dirrel </> display (packageName pkg) <.> "cabal"
exists <- doesFileExist fileabs
return ( Just (dirabs, dirrel)
, if exists then Just (fileabs, filerel) else Nothing
)
_ -> return (Nothing, Nothing)
let pinfo =
PackageInfo {
pinfoId = packageId pkg,
pinfoLocation = fmap (const ()) loc,
pinfoDirectory = pkgdir,
pinfoPackageFile = pkgfile,
pinfoComponents = selectComponentInfo pinfo
(flattenPackageDescription pkg)
}
return pinfo
selectComponentInfo :: PackageInfo -> PackageDescription -> [ComponentInfo]
selectComponentInfo pinfo pkg =
[ ComponentInfo {
cinfoName = componentName c,
cinfoStrName = componentStringName pkg (componentName c),
cinfoPackage = pinfo,
cinfoSrcDirs = ordNub (hsSourceDirs bi),
-- [ pkgroot </> srcdir
-- | (pkgroot,_) <- maybeToList (pinfoDirectory pinfo)
-- , srcdir <- hsSourceDirs bi ],
cinfoModules = ordNub (componentModules c),
cinfoHsFiles = ordNub (componentHsFiles c),
cinfoCFiles = ordNub (cSources bi),
cinfoJsFiles = ordNub (jsSources bi)
}
| c <- pkgComponents pkg
, let bi = componentBuildInfo c ]
componentStringName :: Package pkg => pkg -> ComponentName -> ComponentStringName
componentStringName pkg CLibName = display (packageName pkg)
componentStringName _ (CSubLibName name) = unUnqualComponentName name
componentStringName _ (CFLibName name) = unUnqualComponentName name
componentStringName _ (CExeName name) = unUnqualComponentName name
componentStringName _ (CTestName name) = unUnqualComponentName name
componentStringName _ (CBenchName name) = unUnqualComponentName name
componentModules :: Component -> [ModuleName]
-- I think it's unlikely users will ask to build a requirement
-- which is not mentioned locally.
componentModules (CLib lib) = explicitLibModules lib
componentModules (CFLib flib) = foreignLibModules flib
componentModules (CExe exe) = exeModules exe
componentModules (CTest test) = testModules test
componentModules (CBench bench) = benchmarkModules bench
componentHsFiles :: Component -> [FilePath]
componentHsFiles (CExe exe) = [modulePath exe]
componentHsFiles (CTest TestSuite {
testInterface = TestSuiteExeV10 _ mainfile
}) = [mainfile]
componentHsFiles (CBench Benchmark {
benchmarkInterface = BenchmarkExeV10 _ mainfile
}) = [mainfile]
componentHsFiles _ = []
------------------------------
-- Matching meta targets
--
guardNamespaceMeta :: String -> Match ()
guardNamespaceMeta = guardToken [""] "meta namespace"
guardMetaAll :: String -> Match ()
guardMetaAll = guardToken ["all"] "meta-target 'all'"
guardNamespacePackage :: String -> Match ()
guardNamespacePackage = guardToken ["pkg", "package"] "'pkg' namespace"
guardNamespaceCwd :: String -> Match ()
guardNamespaceCwd = guardToken ["cwd"] "'cwd' namespace"
guardNamespaceModule :: String -> Match ()
guardNamespaceModule = guardToken ["mod", "module"] "'module' namespace"
guardNamespaceFile :: String -> Match ()
guardNamespaceFile = guardToken ["file"] "'file' namespace"
guardToken :: [String] -> String -> String -> Match ()
guardToken tokens msg s
| caseFold s `elem` tokens = increaseConfidence
| otherwise = matchErrorExpected msg s
------------------------------
-- Matching component kinds
--
componentKind :: ComponentName -> ComponentKind
componentKind CLibName = LibKind
componentKind (CSubLibName _) = LibKind
componentKind (CFLibName _) = FLibKind
componentKind (CExeName _) = ExeKind
componentKind (CTestName _) = TestKind
componentKind (CBenchName _) = BenchKind
cinfoKind :: ComponentInfo -> ComponentKind
cinfoKind = componentKind . cinfoName
matchComponentKind :: String -> Match ComponentKind
matchComponentKind s
| s' `elem` liblabels = increaseConfidence >> return LibKind
| s' `elem` fliblabels = increaseConfidence >> return FLibKind
| s' `elem` exelabels = increaseConfidence >> return ExeKind
| s' `elem` testlabels = increaseConfidence >> return TestKind
| s' `elem` benchlabels = increaseConfidence >> return BenchKind
| otherwise = matchErrorExpected "component kind" s
where
s' = caseFold s
liblabels = ["lib", "library"]
fliblabels = ["flib", "foreign-library"]
exelabels = ["exe", "executable"]
testlabels = ["tst", "test", "test-suite"]
benchlabels = ["bench", "benchmark"]
matchComponentKindFilter :: String -> Match ComponentKind
matchComponentKindFilter s
| s' `elem` liblabels = increaseConfidence >> return LibKind
| s' `elem` fliblabels = increaseConfidence >> return FLibKind
| s' `elem` exelabels = increaseConfidence >> return ExeKind
| s' `elem` testlabels = increaseConfidence >> return TestKind
| s' `elem` benchlabels = increaseConfidence >> return BenchKind
| otherwise = matchErrorExpected "component kind filter" s
where
s' = caseFold s
liblabels = ["libs", "libraries"]
fliblabels = ["flibs", "foreign-libraries"]
exelabels = ["exes", "executables"]
testlabels = ["tests", "test-suites"]
benchlabels = ["benches", "benchmarks"]
showComponentKind :: ComponentKind -> String
showComponentKind LibKind = "library"
showComponentKind FLibKind = "foreign library"
showComponentKind ExeKind = "executable"
showComponentKind TestKind = "test-suite"
showComponentKind BenchKind = "benchmark"
showComponentKindShort :: ComponentKind -> String
showComponentKindShort LibKind = "lib"
showComponentKindShort FLibKind = "flib"
showComponentKindShort ExeKind = "exe"
showComponentKindShort TestKind = "test"
showComponentKindShort BenchKind = "bench"
showComponentKindFilterShort :: ComponentKind -> String
showComponentKindFilterShort LibKind = "libs"
showComponentKindFilterShort FLibKind = "flibs"
showComponentKindFilterShort ExeKind = "exes"
showComponentKindFilterShort TestKind = "tests"
showComponentKindFilterShort BenchKind = "benchmarks"
------------------------------
-- Matching package targets
--
guardPackage :: String -> FileStatus -> Match ()
guardPackage str fstatus =
guardPackageName str
<|> guardPackageDir str fstatus
<|> guardPackageFile str fstatus
guardPackageName :: String -> Match ()
guardPackageName s
| validPackageName s = increaseConfidence
| otherwise = matchErrorExpected "package name" s
validPackageName :: String -> Bool
validPackageName s =
all validPackageNameChar s
&& not (null s)
where
validPackageNameChar c = isAlphaNum c || c == '-'
guardPackageDir :: String -> FileStatus -> Match ()
guardPackageDir _ (FileStatusExistsDir _) = increaseConfidence
guardPackageDir str _ = matchErrorExpected "package directory" str
guardPackageFile :: String -> FileStatus -> Match ()
guardPackageFile _ (FileStatusExistsFile file)
| takeExtension file == ".cabal"
= increaseConfidence
guardPackageFile str _ = matchErrorExpected "package .cabal file" str
matchPackage :: [PackageInfo] -> String -> FileStatus -> Match PackageInfo
matchPackage pinfo = \str fstatus ->
orNoThingIn "project" "" $
matchPackageName pinfo str
<//> (matchPackageDir pinfo str fstatus
<|> matchPackageFile pinfo str fstatus)
matchPackageName :: [PackageInfo] -> String -> Match PackageInfo
matchPackageName ps = \str -> do
guard (validPackageName str)
orNoSuchThing "package" str
(map (display . packageName) ps) $
increaseConfidenceFor $
matchInexactly caseFold (display . packageName) ps str
matchPackageDir :: [PackageInfo]
-> String -> FileStatus -> Match PackageInfo
matchPackageDir ps = \str fstatus ->
case fstatus of
FileStatusExistsDir canondir ->
orNoSuchThing "package directory" str (map (snd . fst) dirs) $
increaseConfidenceFor $
fmap snd $ matchExactly (fst . fst) dirs canondir
_ -> mzero
where
dirs = [ ((dabs,drel),p)
| p@PackageInfo{ pinfoDirectory = Just (dabs,drel) } <- ps ]
matchPackageFile :: [PackageInfo] -> String -> FileStatus -> Match PackageInfo
matchPackageFile ps = \str fstatus -> do
case fstatus of
FileStatusExistsFile canonfile ->
orNoSuchThing "package .cabal file" str (map (snd . fst) files) $
increaseConfidenceFor $
fmap snd $ matchExactly (fst . fst) files canonfile
_ -> mzero
where
files = [ ((fabs,frel),p)
| p@PackageInfo{ pinfoPackageFile = Just (fabs,frel) } <- ps ]
--TODO: test outcome when dir exists but doesn't match any known one
--TODO: perhaps need another distinction, vs no such thing, point is the
-- thing is not known, within the project, but could be outside project
------------------------------
-- Matching component targets
--
guardComponentName :: String -> Match ()
guardComponentName s
| all validComponentChar s
&& not (null s) = increaseConfidence
| otherwise = matchErrorExpected "component name" s
where
validComponentChar c = isAlphaNum c || c == '.'
|| c == '_' || c == '-' || c == '\''
matchComponentName :: [ComponentInfo] -> String -> Match ComponentInfo
matchComponentName cs str =
orNoSuchThing "component" str (map cinfoStrName cs)
$ increaseConfidenceFor
$ matchInexactly caseFold cinfoStrName cs str
matchComponentKindAndName :: [ComponentInfo] -> ComponentKind -> String
-> Match ComponentInfo
matchComponentKindAndName cs ckind str =
orNoSuchThing (showComponentKind ckind ++ " component") str
(map render cs)
$ increaseConfidenceFor
$ matchInexactly (\(ck, cn) -> (ck, caseFold cn))
(\c -> (cinfoKind c, cinfoStrName c))
cs
(ckind, str)
where
render c = showComponentKindShort (cinfoKind c) ++ ":" ++ cinfoStrName c
------------------------------
-- Matching module targets
--
guardModuleName :: String -> Match ()
guardModuleName s =
case simpleParse s :: Maybe ModuleName of
Just _ -> increaseConfidence
_ | all validModuleChar s
&& not (null s) -> return ()
| otherwise -> matchErrorExpected "module name" s
where
validModuleChar c = isAlphaNum c || c == '.' || c == '_' || c == '\''
matchModuleName :: [ModuleName] -> String -> Match ModuleName
matchModuleName ms str =
orNoSuchThing "module" str (map display ms)
$ increaseConfidenceFor
$ matchInexactly caseFold display ms str
matchModuleNameAnd :: [(ModuleName, a)] -> String -> Match (ModuleName, a)
matchModuleNameAnd ms str =
orNoSuchThing "module" str (map (display . fst) ms)
$ increaseConfidenceFor
$ matchInexactly caseFold (display . fst) ms str
------------------------------
-- Matching file targets
--
matchPackageDirectoryPrefix :: [PackageInfo] -> FileStatus
-> Match (FilePath, PackageInfo)
matchPackageDirectoryPrefix ps (FileStatusExistsFile filepath) =
increaseConfidenceFor $
matchDirectoryPrefix pkgdirs filepath
where
pkgdirs = [ (dir, p)
| p@PackageInfo { pinfoDirectory = Just (dir,_) } <- ps ]
matchPackageDirectoryPrefix _ _ = mzero
matchComponentFile :: [ComponentInfo] -> String
-> Match (FilePath, ComponentInfo)
matchComponentFile cs str =
orNoSuchThing "file" str [] $
matchComponentModuleFile cs str
<|> matchComponentOtherFile cs str
matchComponentOtherFile :: [ComponentInfo] -> String
-> Match (FilePath, ComponentInfo)
matchComponentOtherFile cs =
matchFile
[ (file, c)
| c <- cs
, file <- cinfoHsFiles c
++ cinfoCFiles c
++ cinfoJsFiles c
]
matchComponentModuleFile :: [ComponentInfo] -> String
-> Match (FilePath, ComponentInfo)
matchComponentModuleFile cs str = do
matchFile
[ (normalise (d </> toFilePath m), c)
| c <- cs
, d <- cinfoSrcDirs c
, m <- cinfoModules c
]
(dropExtension (normalise str))
-- utils
matchFile :: [(FilePath, a)] -> FilePath -> Match (FilePath, a)
matchFile fs =
increaseConfidenceFor
. matchInexactly caseFold fst fs
matchDirectoryPrefix :: [(FilePath, a)] -> FilePath -> Match (FilePath, a)
matchDirectoryPrefix dirs filepath =
tryEach $
[ (file, x)
| (dir,x) <- dirs
, file <- maybeToList (stripDirectory dir) ]
where
stripDirectory :: FilePath -> Maybe FilePath
stripDirectory dir =
joinPath `fmap` stripPrefix (splitDirectories dir) filepathsplit
filepathsplit = splitDirectories filepath
------------------------------
-- Matching monad
--
-- | A matcher embodies a way to match some input as being some recognised
-- value. In particular it deals with multiple and ambiguous matches.
--
-- There are various matcher primitives ('matchExactly', 'matchInexactly'),
-- ways to combine matchers ('matchPlus', 'matchPlusShadowing') and finally we
-- can run a matcher against an input using 'findMatch'.
--
data Match a = NoMatch Confidence [MatchError]
| ExactMatch Confidence [a]
| InexactMatch Confidence [a]
deriving Show
type Confidence = Int
data MatchError = MatchErrorExpected String String -- thing got
| MatchErrorNoSuch String String [String] -- thing got alts
| MatchErrorIn String String MatchError -- kind thing
deriving (Show, Eq)
instance Functor Match where
fmap _ (NoMatch d ms) = NoMatch d ms
fmap f (ExactMatch d xs) = ExactMatch d (fmap f xs)
fmap f (InexactMatch d xs) = InexactMatch d (fmap f xs)
instance Applicative Match where
pure a = ExactMatch 0 [a]
(<*>) = ap
instance Alternative Match where
empty = NoMatch 0 []
(<|>) = matchPlus
instance Monad Match where
return = pure
NoMatch d ms >>= _ = NoMatch d ms
ExactMatch d xs >>= f = addDepth d
$ msum (map f xs)
InexactMatch d xs >>= f = addDepth d . forceInexact
$ msum (map f xs)
instance MonadPlus Match where
mzero = empty
mplus = matchPlus
(<//>) :: Match a -> Match a -> Match a
(<//>) = matchPlusShadowing
infixl 3 <//>
addDepth :: Confidence -> Match a -> Match a
addDepth d' (NoMatch d msgs) = NoMatch (d'+d) msgs
addDepth d' (ExactMatch d xs) = ExactMatch (d'+d) xs
addDepth d' (InexactMatch d xs) = InexactMatch (d'+d) xs
forceInexact :: Match a -> Match a
forceInexact (ExactMatch d ys) = InexactMatch d ys
forceInexact m = m
-- | Combine two matchers. Exact matches are used over inexact matches
-- but if we have multiple exact, or inexact then the we collect all the
-- ambiguous matches.
--
-- This operator is associative, has unit 'mzero' and is also commutative.
--
matchPlus :: Match a -> Match a -> Match a
matchPlus (ExactMatch d1 xs) (ExactMatch d2 xs') =
ExactMatch (max d1 d2) (xs ++ xs')
matchPlus a@(ExactMatch _ _ ) (InexactMatch _ _ ) = a
matchPlus a@(ExactMatch _ _ ) (NoMatch _ _ ) = a
matchPlus (InexactMatch _ _ ) b@(ExactMatch _ _ ) = b
matchPlus (InexactMatch d1 xs) (InexactMatch d2 xs') =
InexactMatch (max d1 d2) (xs ++ xs')
matchPlus a@(InexactMatch _ _ ) (NoMatch _ _ ) = a
matchPlus (NoMatch _ _ ) b@(ExactMatch _ _ ) = b
matchPlus (NoMatch _ _ ) b@(InexactMatch _ _ ) = b
matchPlus a@(NoMatch d1 ms) b@(NoMatch d2 ms')
| d1 > d2 = a
| d1 < d2 = b
| otherwise = NoMatch d1 (ms ++ ms')
-- | Combine two matchers. This is similar to 'matchPlus' with the
-- difference that an exact match from the left matcher shadows any exact
-- match on the right. Inexact matches are still collected however.
--
-- This operator is associative, has unit 'mzero' and is not commutative.
--
matchPlusShadowing :: Match a -> Match a -> Match a
matchPlusShadowing a@(ExactMatch _ _) _ = a
matchPlusShadowing a b = matchPlus a b
------------------------------
-- Various match primitives
--
matchErrorExpected :: String -> String -> Match a
matchErrorExpected thing got = NoMatch 0 [MatchErrorExpected thing got]
matchErrorNoSuch :: String -> String -> [String] -> Match a
matchErrorNoSuch thing got alts = NoMatch 0 [MatchErrorNoSuch thing got alts]
expecting :: String -> String -> Match a -> Match a
expecting thing got (NoMatch 0 _) = matchErrorExpected thing got
expecting _ _ m = m
orNoSuchThing :: String -> String -> [String] -> Match a -> Match a
orNoSuchThing thing got alts (NoMatch 0 _) = matchErrorNoSuch thing got alts
orNoSuchThing _ _ _ m = m
orNoThingIn :: String -> String -> Match a -> Match a
orNoThingIn kind name (NoMatch n ms) =
NoMatch n [ MatchErrorIn kind name m | m <- ms ]
orNoThingIn _ _ m = m
increaseConfidence :: Match ()
increaseConfidence = ExactMatch 1 [()]
increaseConfidenceFor :: Match a -> Match a
increaseConfidenceFor m = m >>= \r -> increaseConfidence >> return r
nubMatchesBy :: (a -> a -> Bool) -> Match a -> Match a
nubMatchesBy _ (NoMatch d msgs) = NoMatch d msgs
nubMatchesBy eq (ExactMatch d xs) = ExactMatch d (nubBy eq xs)
nubMatchesBy eq (InexactMatch d xs) = InexactMatch d (nubBy eq xs)
-- | Lift a list of matches to an exact match.
--
exactMatches, inexactMatches :: [a] -> Match a
exactMatches [] = mzero
exactMatches xs = ExactMatch 0 xs
inexactMatches [] = mzero
inexactMatches xs = InexactMatch 0 xs
tryEach :: [a] -> Match a
tryEach = exactMatches
------------------------------
-- Top level match runner
--
-- | Given a matcher and a key to look up, use the matcher to find all the
-- possible matches. There may be 'None', a single 'Unambiguous' match or
-- you may have an 'Ambiguous' match with several possibilities.
--
findMatch :: Match a -> MaybeAmbiguous a
findMatch match = case match of
NoMatch _ msgs -> None msgs
ExactMatch _ [x] -> Unambiguous x
InexactMatch _ [x] -> Unambiguous x
ExactMatch _ [] -> error "findMatch: impossible: ExactMatch []"
InexactMatch _ [] -> error "findMatch: impossible: InexactMatch []"
ExactMatch _ xs -> Ambiguous True xs
InexactMatch _ xs -> Ambiguous False xs
data MaybeAmbiguous a = None [MatchError] | Unambiguous a | Ambiguous Bool [a]
deriving Show
------------------------------
-- Basic matchers
--
-- | A primitive matcher that looks up a value in a finite 'Map'. The
-- value must match exactly.
--
matchExactly :: Ord k => (a -> k) -> [a] -> (k -> Match a)
matchExactly key xs =
\k -> case Map.lookup k m of
Nothing -> mzero
Just ys -> exactMatches ys
where
m = Map.fromListWith (++) [ (key x, [x]) | x <- xs ]
-- | A primitive matcher that looks up a value in a finite 'Map'. It checks
-- for an exact or inexact match. We get an inexact match if the match
-- is not exact, but the canonical forms match. It takes a canonicalisation
-- function for this purpose.
--
-- So for example if we used string case fold as the canonicalisation
-- function, then we would get case insensitive matching (but it will still
-- report an exact match when the case matches too).
--
matchInexactly :: (Ord k, Ord k') => (k -> k') -> (a -> k)
-> [a] -> (k -> Match a)
matchInexactly cannonicalise key xs =
\k -> case Map.lookup k m of
Just ys -> exactMatches ys
Nothing -> case Map.lookup (cannonicalise k) m' of
Just ys -> inexactMatches ys
Nothing -> mzero
where
m = Map.fromListWith (++) [ (key x, [x]) | x <- xs ]
-- the map of canonicalised keys to groups of inexact matches
m' = Map.mapKeysWith (++) cannonicalise m
------------------------------
-- Utils
--
caseFold :: String -> String
caseFold = lowercase
------------------------------
-- Example inputs
--
{-
ex1pinfo :: [PackageInfo]
ex1pinfo =
[ addComponent (CExeName (mkUnqualComponentName "foo-exe")) [] ["Data.Foo"] $
PackageInfo {
pinfoId = PackageIdentifier (mkPackageName "foo") (mkVersion [1]),
pinfoLocation = LocalUnpackedPackage "/the/foo",
pinfoDirectory = Just ("/the/foo", "foo"),
pinfoPackageFile = Just ("/the/foo/foo.cabal", "foo/foo.cabal"),
pinfoComponents = []
}
, PackageInfo {
pinfoId = PackageIdentifier (mkPackageName "bar") (mkVersion [1]),
pinfoLocation = LocalUnpackedPackage "/the/foo",
pinfoDirectory = Just ("/the/bar", "bar"),
pinfoPackageFile = Just ("/the/bar/bar.cabal", "bar/bar.cabal"),
pinfoComponents = []
}
]
where
addComponent n ds ms p =
p {
pinfoComponents =
ComponentInfo n (componentStringName (pinfoId p) n)
p ds (map mkMn ms)
[] [] []
: pinfoComponents p
}
mkMn :: String -> ModuleName
mkMn = ModuleName.fromString
-}
{-
stargets =
[ TargetComponent (CExeName "foo") WholeComponent
, TargetComponent (CExeName "foo") (ModuleTarget (mkMn "Foo"))
, TargetComponent (CExeName "tst") (ModuleTarget (mkMn "Foo"))
]
where
mkMn :: String -> ModuleName
mkMn = fromJust . simpleParse
ex_pkgid :: PackageIdentifier
Just ex_pkgid = simpleParse "thelib"
-}
{-
ex_cs :: [ComponentInfo]
ex_cs =
[ (mkC (CExeName "foo") ["src1", "src1/src2"] ["Foo", "Src2.Bar", "Bar"])
, (mkC (CExeName "tst") ["src1", "test"] ["Foo"])
]
where
mkC n ds ms = ComponentInfo n (componentStringName n) ds (map mkMn ms)
mkMn :: String -> ModuleName
mkMn = fromJust . simpleParse
pkgid :: PackageIdentifier
Just pkgid = simpleParse "thelib"
-}
| themoritz/cabal | cabal-install/Distribution/Client/TargetSelector.hs | bsd-3-clause | 81,010 | 0 | 26 | 20,978 | 19,102 | 9,854 | 9,248 | 1,446 | 13 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift Compiler (0.9.2) --
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING --
-----------------------------------------------------------------
module ReadOnlyScheduler_Client(getRoleSummary,getJobSummary,getTasksStatus,getTasksWithoutConfigs,getPendingReason,getConfigSummary,getJobs,getQuota,populateJobConfig,getLocks,getJobUpdateSummaries,getJobUpdateDetails) where
import qualified Data.IORef as R
import Prelude (($), (.), (>>=), (==), (++))
import qualified Prelude as P
import qualified Control.Exception as X
import qualified Control.Monad as M ( liftM, ap, when )
import Data.Functor ( (<$>) )
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Hashable as H
import qualified Data.Int as I
import qualified Data.Maybe as M (catMaybes)
import qualified Data.Text.Lazy.Encoding as E ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified Data.Typeable as TY ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as QC ( Arbitrary(..) )
import qualified Test.QuickCheck as QC ( elements )
import qualified Thrift as T
import qualified Thrift.Types as T
import qualified Thrift.Arbitraries as T
import Api_Types
import ReadOnlyScheduler
seqid = R.newIORef 0
getRoleSummary (ip,op) = do
send_getRoleSummary op
recv_getRoleSummary ip
send_getRoleSummary op = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getRoleSummary", T.M_CALL, seqn)
write_GetRoleSummary_args op (GetRoleSummary_args{})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getRoleSummary ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetRoleSummary_result ip
T.readMessageEnd ip
P.return $ getRoleSummary_result_success res
getJobSummary (ip,op) arg_role = do
send_getJobSummary op arg_role
recv_getJobSummary ip
send_getJobSummary op arg_role = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getJobSummary", T.M_CALL, seqn)
write_GetJobSummary_args op (GetJobSummary_args{getJobSummary_args_role=arg_role})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getJobSummary ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetJobSummary_result ip
T.readMessageEnd ip
P.return $ getJobSummary_result_success res
getTasksStatus (ip,op) arg_query = do
send_getTasksStatus op arg_query
recv_getTasksStatus ip
send_getTasksStatus op arg_query = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getTasksStatus", T.M_CALL, seqn)
write_GetTasksStatus_args op (GetTasksStatus_args{getTasksStatus_args_query=arg_query})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getTasksStatus ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetTasksStatus_result ip
T.readMessageEnd ip
P.return $ getTasksStatus_result_success res
getTasksWithoutConfigs (ip,op) arg_query = do
send_getTasksWithoutConfigs op arg_query
recv_getTasksWithoutConfigs ip
send_getTasksWithoutConfigs op arg_query = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getTasksWithoutConfigs", T.M_CALL, seqn)
write_GetTasksWithoutConfigs_args op (GetTasksWithoutConfigs_args{getTasksWithoutConfigs_args_query=arg_query})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getTasksWithoutConfigs ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetTasksWithoutConfigs_result ip
T.readMessageEnd ip
P.return $ getTasksWithoutConfigs_result_success res
getPendingReason (ip,op) arg_query = do
send_getPendingReason op arg_query
recv_getPendingReason ip
send_getPendingReason op arg_query = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getPendingReason", T.M_CALL, seqn)
write_GetPendingReason_args op (GetPendingReason_args{getPendingReason_args_query=arg_query})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getPendingReason ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetPendingReason_result ip
T.readMessageEnd ip
P.return $ getPendingReason_result_success res
getConfigSummary (ip,op) arg_job = do
send_getConfigSummary op arg_job
recv_getConfigSummary ip
send_getConfigSummary op arg_job = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getConfigSummary", T.M_CALL, seqn)
write_GetConfigSummary_args op (GetConfigSummary_args{getConfigSummary_args_job=arg_job})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getConfigSummary ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetConfigSummary_result ip
T.readMessageEnd ip
P.return $ getConfigSummary_result_success res
getJobs (ip,op) arg_ownerRole = do
send_getJobs op arg_ownerRole
recv_getJobs ip
send_getJobs op arg_ownerRole = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getJobs", T.M_CALL, seqn)
write_GetJobs_args op (GetJobs_args{getJobs_args_ownerRole=arg_ownerRole})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getJobs ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetJobs_result ip
T.readMessageEnd ip
P.return $ getJobs_result_success res
getQuota (ip,op) arg_ownerRole = do
send_getQuota op arg_ownerRole
recv_getQuota ip
send_getQuota op arg_ownerRole = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getQuota", T.M_CALL, seqn)
write_GetQuota_args op (GetQuota_args{getQuota_args_ownerRole=arg_ownerRole})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getQuota ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetQuota_result ip
T.readMessageEnd ip
P.return $ getQuota_result_success res
populateJobConfig (ip,op) arg_description = do
send_populateJobConfig op arg_description
recv_populateJobConfig ip
send_populateJobConfig op arg_description = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("populateJobConfig", T.M_CALL, seqn)
write_PopulateJobConfig_args op (PopulateJobConfig_args{populateJobConfig_args_description=arg_description})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_populateJobConfig ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_PopulateJobConfig_result ip
T.readMessageEnd ip
P.return $ populateJobConfig_result_success res
getLocks (ip,op) = do
send_getLocks op
recv_getLocks ip
send_getLocks op = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getLocks", T.M_CALL, seqn)
write_GetLocks_args op (GetLocks_args{})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getLocks ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetLocks_result ip
T.readMessageEnd ip
P.return $ getLocks_result_success res
getJobUpdateSummaries (ip,op) arg_jobUpdateQuery = do
send_getJobUpdateSummaries op arg_jobUpdateQuery
recv_getJobUpdateSummaries ip
send_getJobUpdateSummaries op arg_jobUpdateQuery = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getJobUpdateSummaries", T.M_CALL, seqn)
write_GetJobUpdateSummaries_args op (GetJobUpdateSummaries_args{getJobUpdateSummaries_args_jobUpdateQuery=arg_jobUpdateQuery})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getJobUpdateSummaries ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetJobUpdateSummaries_result ip
T.readMessageEnd ip
P.return $ getJobUpdateSummaries_result_success res
getJobUpdateDetails (ip,op) arg_updateId = do
send_getJobUpdateDetails op arg_updateId
recv_getJobUpdateDetails ip
send_getJobUpdateDetails op arg_updateId = do
seq <- seqid
seqn <- R.readIORef seq
T.writeMessageBegin op ("getJobUpdateDetails", T.M_CALL, seqn)
write_GetJobUpdateDetails_args op (GetJobUpdateDetails_args{getJobUpdateDetails_args_updateId=arg_updateId})
T.writeMessageEnd op
T.tFlush (T.getTransport op)
recv_getJobUpdateDetails ip = do
(fname, mtype, rseqid) <- T.readMessageBegin ip
M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn }
res <- read_GetJobUpdateDetails_result ip
T.readMessageEnd ip
P.return $ getJobUpdateDetails_result_success res
| futufeld/eclogues | eclogues-impl/gen-hs/ReadOnlyScheduler_Client.hs | bsd-3-clause | 9,918 | 0 | 12 | 1,459 | 3,111 | 1,535 | 1,576 | 224 | 1 |
-- |A type describing potentially pure or impure values (to preserve laziness when possible)
module ELisp.Joinable(Joinable,joined,impure,getPure) where
import Utils
-- |A type describing potentially pure or impure values (to preserve laziness when possible)
newtype Joinable a = Joinable (Either a (IO a))
instance Functor Joinable where
fmap f (Joinable j) = Joinable (either (Left . f) (Right . fmap f) j)
instance Applicative Joinable where
-- |Create a Joinable from a pure value
pure = Joinable . Left
Joinable (Left f) <*> Joinable (Left a) = Joinable (Left (f a))
a <*> b = Joinable (Right $ joined a <*> joined b)
instance Monad Joinable where
return = pure
Joinable (Left a) >>= k = k a
Joinable (Right a) >>= k = impure (a >>= joined . k)
-- |Evaluate a Joinable value
joined (Joinable j) = either return id j
-- |Create a Joinable from an IO value
impure = Joinable . Right
-- |Retrieves a pure value if it exists
getPure (Joinable (Left a)) = Just a
getPure _ = Nothing
| lih/Epsilon | src/ELisp/Joinable.hs | bsd-3-clause | 1,002 | 0 | 11 | 193 | 329 | 167 | 162 | 17 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Protolude hiding (get, put)
import Control.Monad.Except (ExceptT, liftEither, runExceptT,
throwError)
import Control.Monad.State (StateT, get, put, runStateT)
import Data.HashMap.Strict as HMS (HashMap, empty, insert, lookup)
import Data.IORef (IORef, atomicModifyIORef, newIORef,
readIORef)
import Data.List.Split
import Data.Text (Text, lines, pack, unpack)
import Safe (headMay, readMay)
import System.Random (randomIO)
import Error
import Game (GameState, Player (..), getBoard,
getMoves, getRandomShipsIO, getShips,
getWinner, makeMove, mkGameState,
setShips)
import Yesod hiding (get)
setupShips :: Monad m => GameState -> [((Char, Int), Bool)] -> [((Char, Int), Bool)]
-> ExceptT GameError m GameState
setupShips s s1 s2 = do
s' <- liftEither $ setShips s Player1 s1
liftEither $ setShips s' Player2 s2
setupRandomShipsIO :: GameState -> ExceptT GameError IO GameState
setupRandomShipsIO s = do
ms1 <- liftIO getRandomShipsIO
ms2 <- liftIO getRandomShipsIO
let mships = (,) <$> ms1 <*> ms2
case mships of
Just (s1, s2) -> setupShips s s1 s2
Nothing -> throwError $ GameErrorIllegalPlacement "random ship generation failed"
newtype App = App{
gameStates :: IORef (HashMap Int GameState)
}
mkYesod "App" [parseRoutes|
/ HomeR GET
/StartGame StartGameR POST
/MakeMove MakeMoveR POST
|]
instance Yesod App
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
newtype Game = Game
{ gameNoRes :: Int
}
deriving Show
updState :: Int -> GameState -> IORef (HashMap Int GameState) -> IO (HashMap Int GameState)
updState k st gs = atomicModifyIORef gs (\hm -> (HMS.insert k st hm, hm))
startForm :: Html -> MForm Handler (FormResult Game, Widget)
startForm extra = do
(gr, _gameNV) <- mreq intField "neither is this" (Just 0)
let gameRes = Game <$> gr
let widget = do
toWidget [lucius|
body{font-size:200%;font-family:sans-serif}
.button{font-size:200%;font-family:sans-serif}
|]
[whamlet|
#{extra}
Thar be storm seas and ye have just spied the navy.<br>
Your ships be showing where ya ships be and the navy '.'-misses and '*'-hits.<br>
Click on the squard to fire ya cannons!<br>
The enemy will fire after your turn.<br><br>
Thar be feature gaps:<br>
The navy tends to copy your cannon shots<br>
Your ships are where the are - ya cannot place them with your pirate cunning.<br>
Graphics could use `some` work.<br>
Arrrr...<br>
<p>
<input type=submit class="button" name="action" value="New Game"><br><br>
|]
return (gameRes, widget)
getHomeR :: Handler Html
getHomeR = do
((_res, widget), enctype) <- runFormPost startForm
--action <- lookupGetParam "action"
defaultLayout
[whamlet|
<form method=post action=@{StartGameR} type=#{enctype}>
^{widget}
|]
showInt :: Int -> Text
showInt = show
renderShipLayout :: GameState -> HandlerFor App Html
renderShipLayout st = defaultLayout $ do
let board = getBoard (getShips st Player2) (getMoves st Player1 ) False
let ls = lines $ pack board
let rows = zip ['a'..'j'] <$> map unpack ls
let coordRows = zip [1..10] rows
toWidget [lucius|
body{font-size:200%;font-family:sans-serif}
.button{font-size:300%;font-family:monospace}
.table {
display: table;
width: auto;
margin: 2px;
background-color: lightblue;
border: 1px solid #666666;
/* border-spacing:5px;/*cellspacing:poor IE support forthis*/
border-collapse: separate;
}
.table-cell {
float: left;
background-color: blue;
margin: 2px;
}
table {
table-layout: fixed;
}
|]
[whamlet|
Ya brave pirate ships:
<pre>
#{ getBoard (getShips st Player1) (getMoves st Player2 ) True}<br>
<pre>
Cannon shots:
<form method=post action=@{MakeMoveR}>
<div class="table">
$forall (rowId, row) <- coordRows
<div class="table-row">
$forall (colId, val) <- row
<div class="table-cell">
<button class=button type=submit name=move value="#{colId},#{showInt rowId}">#{val}
|]
gameErrorLayout :: Text -> HandlerFor App Html
gameErrorLayout s = defaultLayout $ do
toWidget [lucius|
body{font-size:200%;font-family:sans-serif}
.button{font-size:200%;font-family:sans-serif}
|]
[whamlet|
<p>Error: #{s}
<form method=get action=@{HomeR}>
<input type=submit class="button" name="action" value="New Game">
|]
gameEndedLayout :: Text -> HandlerFor App Html
gameEndedLayout s = defaultLayout $ do
toWidget [lucius|
body{font-size:200%;font-family:sans-serif}
.button{font-size:200%;font-family:sans-serif}
|]
[whamlet|
<p>#{s} <br>
<form method=get action=@{HomeR}>
<input type=submit class="button" name="action" value="New Game">
|]
postStartGameR :: Handler Html
postStartGameR = do
--((res, widget), enctype) <- runFormPost personForm
yesod <- getYesod
-- action <- lookupPostParam "action"
-- liftIO $ putStrLn $ show action
x <- liftIO $ runExceptT $ setupRandomShipsIO mkGameState
case x of
Right st -> do
liftIO $ putStrLn $ getBoard (getShips st Player2) (getMoves st Player1 ) True
session <- liftIO randomIO
setSession "gameId" (pack $ show session)
_ <- liftIO $ updState session st $ gameStates yesod
renderShipLayout st
Left y -> gameErrorLayout (pack $ show y)
getColRow :: Maybe Text -> Maybe (Char, Int)
getColRow move =
case move of
Just m ->
let s = splitOn "," $ unpack m
mcs = headMay s
mrs = s `atMay` 1 in
case (mcs, mrs) of
(Just cs, Just rs) -> (,) <$> headMay cs <*> readMay rs
_ -> Nothing
_ -> Nothing
getSesh :: Maybe Text -> Int
getSesh t = case t of
Just v -> fromMaybe 0 $ readMay (unpack v)
Nothing -> 0
moveModifyState :: Monad m => (Player, Char, Int)
-> ExceptT GameError (StateT GameState m) GameState
moveModifyState (player, r, c) = do
st <- get
st' <- liftEither $ makeMove st player r c
put st'
return st'
-- | Submits the moves updating the state, running in EitherT/StateT returns
-- | on Left or list end ()
playMoves_ :: [(Player, Char, Int)]
-> ExceptT GameError (StateT GameState IO) ()
playMoves_ = mapM_ moveModifyState
postMakeMoveR :: Handler Html
postMakeMoveR = do
yesod <- getYesod
gs <- liftIO $ readIORef $ gameStates yesod
move <- lookupPostParam "move"
let mcr = getColRow move
ses <- lookupSession "gameId"
let session = getSesh ses
let oGSt = HMS.lookup session gs
case (oGSt, mcr) of
(Just st, Just colRow) -> do
(eSt, st') <- liftIO $ flip runStateT st . runExceptT $ playMoves_
[ (Player1, fst colRow, snd colRow)
, (Player2, fst colRow, snd colRow) ]
case getWinner st' of
Just Player1 -> gameEndedLayout "You won! :-)"
Just Player2 -> gameEndedLayout "You lost :-("
Nothing -> case eSt of
Right _ -> do
_ <- liftIO $ updState session st' $ gameStates yesod
renderShipLayout st'
Left err -> gameErrorLayout (pack $ show err)
_ -> gameErrorLayout "Could not retrieve state"
main :: IO ()
main = do
hm <- newIORef HMS.empty
warp 3000 (App hm)
| tau-tao/pbs-web | src/Main.hs | bsd-3-clause | 8,371 | 0 | 23 | 2,510 | 1,820 | 940 | 880 | 144 | 5 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
module Parse.Helpers where
import Prelude hiding (until)
import Control.Monad (guard)
import qualified Data.Indexed as I
import Data.Map.Strict hiding (foldl)
import Parse.ParsecAdapter hiding (newline, spaces, State)
import AST.V0_16
import qualified AST.Helpers as Help
import AST.Structure (FixAST)
import ElmVersion
import qualified Parse.State as State
import Parse.Comments
import Parse.IParser
import Parse.Whitespace
import qualified Parse.Primitives as P
import qualified Parse.ParsecAdapter as Parsec
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Syntax as Syntax
reserveds :: [String]
reserveds =
[ "if", "then", "else"
, "case", "of"
, "let", "in"
, "type"
, "module", "where"
, "import", "exposing"
, "as"
, "port"
]
-- ERROR HELP
expecting :: String -> IParser a -> IParser a
expecting = flip (<?>)
-- SETUP
iParse :: IParser a -> String -> Either ParsecError a
iParse =
iParseWithState State.init
iParseWithState :: State.State -> IParser a -> String -> Either ParsecError a
iParseWithState state aParser input =
runIndent $ runParserT aParser state input
-- VARIABLES
var :: ElmVersion -> IParser (Ref [UppercaseIdentifier])
var elmVersion =
try (qualifiedVar elmVersion) <|> qualifiedTag elmVersion <?> "a name"
lowVar :: ElmVersion -> IParser LowercaseIdentifier
lowVar elmVersion =
LowercaseIdentifier <$> makeVar elmVersion lower <?> "a lower case name"
capVar :: ElmVersion -> IParser UppercaseIdentifier
capVar elmVersion =
UppercaseIdentifier <$> makeVar elmVersion upper <?> "an upper case name"
qualifiedVar :: ElmVersion -> IParser (Ref [UppercaseIdentifier])
qualifiedVar elmVersion =
VarRef
<$> many (const <$> capVar elmVersion <*> string ".")
<*> lowVar elmVersion
qualifiedTag :: ElmVersion -> IParser (Ref [UppercaseIdentifier])
qualifiedTag elmVersion =
TagRef
<$> many (try $ const <$> capVar elmVersion <*> string ".")
<*> capVar elmVersion
rLabel :: ElmVersion -> IParser LowercaseIdentifier
rLabel = lowVar
innerVarChar :: ElmVersion -> IParser Char
innerVarChar elmVersion =
if syntax_0_19_disallowApostropheInVars elmVersion
then alphaNum <|> char '_' <?> "more letters in this name"
else alphaNum <|> char '_' <|> char '\'' <?> "more letters in this name"
makeVar :: ElmVersion -> IParser Char -> IParser String
makeVar elmVersion firstChar =
do variable <- (:) <$> firstChar <*> many (innerVarChar elmVersion)
if variable `elem` reserveds
then parserFail $ parseError (Message (Syntax.keyword variable))
else return variable
reserved :: ElmVersion -> String -> IParser ()
reserved elmVersion word =
expecting ("reserved word `" ++ word ++ "`") $
do _ <- string word
notFollowedBy (innerVarChar elmVersion)
return ()
-- INFIX OPERATORS
anyOp :: ElmVersion -> IParser (Ref [UppercaseIdentifier])
anyOp elmVersion =
(betwixt '`' '`' (qualifiedVar elmVersion) <?> "an infix operator like `andThen`")
<|> (OpRef <$> symOp)
symOp :: IParser SymbolIdentifier
symOp =
do op <- many1 (satisfy Help.isSymbol) <?> "an infix operator like +"
guard (op `notElem` [ "=", "..", "->", "--", "|", "\8594", ":" ])
case op of
"." -> notFollowedBy lower >> return (SymbolIdentifier op)
_ -> return $ SymbolIdentifier op
symOpInParens :: IParser SymbolIdentifier
symOpInParens =
parens' symOp
-- COMMON SYMBOLS
equals :: IParser ()
equals =
const () <$> char '=' <?> "="
lenientEquals :: IParser ()
lenientEquals =
const () <$> (char '=' <|> char ':') <?> "="
rightArrow :: IParser ()
rightArrow =
const () <$> (string "->" <|> string "\8594") <?> "->"
cons :: IParser ()
cons =
const () <$> string "::" <?> "a cons operator '::'"
hasType :: IParser ()
hasType =
const () <$> char ':' <?> "the \"has type\" symbol ':'"
lenientHasType :: IParser ()
lenientHasType =
const () <$> (char ':' <|> char '=') <?> "the \"has type\" symbol ':'"
comma :: IParser ()
comma =
const () <$> char ',' <?> "a comma ','"
semicolon :: IParser ()
semicolon =
const () <$> char ';' <?> "a semicolon ';'"
verticalBar :: IParser ()
verticalBar =
const () <$> char '|' <?> "a vertical bar '|'"
commitIf :: IParser any -> IParser a -> IParser a
commitIf check p =
commit <|> try p
where
commit =
try (lookAhead check) >> p
-- SEPARATORS
spaceySepBy1 :: IParser sep -> IParser a -> IParser (ExposedCommentedList a)
spaceySepBy1 sep parser =
let
-- step :: PostCommented (WithEol a) -> [Commented (WithEol a)] -> Comments -> IParser (ExposedCommentedList a)
step first rest post =
do
(C eol next) <- withEol parser
choice
[ try (padded sep)
>>= (\(C (preSep, postSep) _) -> step first (C (post, preSep, eol) next : rest) postSep)
, return $ Multiple first (reverse rest) (C (post, eol) next)
]
in
do
(C eol value) <- withEol parser
choice
[ try (padded sep)
>>= (\(C (preSep, postSep) _) -> step (C (preSep, eol) value) [] postSep)
, return $ Single (C eol value)
]
-- DEPRECATED: use spaceySepBy1 instead
spaceySepBy1'' :: IParser sep -> IParser (Comments -> Comments -> a) -> IParser (Comments -> Comments -> [a])
spaceySepBy1'' sep parser =
let
combine eol post =
eolToComment eol ++ post
in
do
result <- spaceySepBy1 sep parser
case result of
Single (C eol item) ->
return $ \pre post -> [item pre (combine eol post)]
Multiple (C (postFirst, firstEol) first ) rest (C (preLast, eol) last) ->
return $ \preFirst postLast ->
concat
[ [first preFirst $ combine firstEol postFirst]
, fmap (\(C (pre, post, eol) item) -> item pre $ combine eol post) rest
, [last preLast $ combine eol postLast ]
]
-- DEPRECATED: use spaceySepBy1 instead
spaceySepBy1' :: IParser sep -> IParser a -> IParser (Comments -> Comments -> [C2 before after a])
spaceySepBy1' sep parser =
spaceySepBy1'' sep ((\x pre post -> C (pre, post) x) <$> parser)
commaSep1 :: IParser (Comments -> Comments -> a) -> IParser (Comments -> Comments -> [a])
commaSep1 =
spaceySepBy1'' comma
commaSep1' :: IParser a -> IParser (Comments -> Comments -> [C2 before after a])
commaSep1' =
spaceySepBy1' comma
toSet :: Ord k => (v -> v -> v) -> [C2 before after (k, v)] -> Map k (C2 before after v)
toSet merge values =
let
merge' (C (pre1, post1) a) (C (pre2, post2) b) =
C (pre1 ++ pre2, post1 ++ post2) (merge a b)
in
foldl (\m (C (pre, post) (k, v)) -> insertWith merge' k (C (pre, post) v) m) empty values
commaSep1Set' :: Ord k => IParser (k, v) -> (v -> v -> v) -> IParser (Comments -> Comments -> Map k (C2 before after v))
commaSep1Set' parser merge =
do
values <- commaSep1' parser
return $ \pre post -> toSet merge $ values pre post
commaSep :: IParser (Comments -> Comments -> a) -> IParser (Maybe (Comments -> Comments -> [a]))
commaSep term =
option Nothing (Just <$> commaSep1 term)
pipeSep1 :: IParser a -> IParser (ExposedCommentedList a)
pipeSep1 =
spaceySepBy1 verticalBar
keyValue :: IParser sep -> IParser key -> IParser val -> IParser (Comments -> Comments -> (C2 before after key, C2 before' after' val) )
keyValue parseSep parseKey parseVal =
do
key <- parseKey
preSep <- whitespace <* parseSep
postSep <- whitespace
val <- parseVal
return $ \pre post ->
( C (pre, preSep) key
, C (postSep, post) val
)
separated :: IParser sep -> IParser e -> IParser (Either e (A.Region, C0Eol e, Sequence e, Bool))
separated sep expr' =
let
subparser =
do start <- Parsec.getPosition
t1 <- expr'
arrow <- optionMaybe $ try ((,) <$> restOfLine <*> whitespace <* sep)
case arrow of
Nothing ->
return $ \_multiline -> Left t1
Just (eolT1, preArrow) ->
do postArrow <- whitespace
t2 <- separated sep expr'
end <- Parsec.getPosition
case t2 of
Right (_, C eolT2 t2', Sequence ts, _) ->
return $ \multiline -> Right
( A.Region start end
, C eolT1 t1
, Sequence (C (preArrow, postArrow, eolT2) t2' : ts)
, multiline
)
Left t2' ->
do
eol <- restOfLine
return $ \multiline -> Right
( A.Region start end
, C eolT1 t1
, Sequence [ C (preArrow, postArrow, eol) t2' ]
, multiline)
in
(\(f, multiline) -> f $ multilineToBool multiline) <$> trackNewline subparser
dotSep1 :: IParser a -> IParser [a]
dotSep1 p =
(:) <$> p <*> many (try (char '.') >> p)
spacePrefix :: IParser a -> IParser [C1 before a]
spacePrefix p =
fmap fst <$>
constrainedSpacePrefix' p (\_ -> return ())
constrainedSpacePrefix :: IParser a -> IParser [(C1 before a, Multiline)]
constrainedSpacePrefix parser =
constrainedSpacePrefix' parser constraint
where
constraint empty = if empty then notFollowedBy (char '-') else return ()
constrainedSpacePrefix' :: IParser a -> (Bool -> IParser b) -> IParser [(C1 before a, Multiline)]
constrainedSpacePrefix' parser constraint =
many $ trackNewline $ choice
[ C <$> try (const <$> spacing <*> lookAhead (oneOf "[({")) <*> parser
, try (C <$> spacing <*> parser)
]
where
spacing = do
(n, comments) <- whitespace'
_ <- constraint (not n) <?> Syntax.whitespace
indented
return comments
-- SURROUNDED BY
betwixt :: Char -> Char -> IParser a -> IParser a
betwixt a b c =
do _ <- char a
out <- c
_ <- char b <?> "a closing '" ++ [b] ++ "'"
return out
surround :: Char -> Char -> String -> IParser (Comments -> Comments -> Bool -> a) -> IParser a
surround a z name p =
let
-- subparser :: IParser (Bool -> a)
subparser = do
_ <- char a
(C (pre, post) v) <- padded p
_ <- char z <?> unwords ["a closing", name, show z]
return $ \multiline -> v pre post multiline
in
(\(f, multiline) -> f (multilineToBool multiline)) <$> trackNewline subparser
-- TODO: push the Multiline type further up in the AST and get rid of this
multilineToBool :: Multiline -> Bool
multilineToBool multine =
case multine of
SplitAll -> True
JoinAll -> False
braces :: IParser (Comments -> Comments -> Bool -> a) -> IParser a
braces =
surround '[' ']' "brace"
parens :: IParser (Comments -> Comments -> Bool -> a) -> IParser a
parens =
surround '(' ')' "paren"
brackets :: IParser (Comments -> Comments -> Bool -> a) -> IParser a
brackets =
surround '{' '}' "bracket"
braces' :: IParser a -> IParser a
braces' =
surround' '[' ']' "brace"
brackets' :: IParser a -> IParser a
brackets' =
surround' '{' '}' "bracket"
surround' :: Char -> Char -> String -> IParser a -> IParser a
surround' a z name p = do
_ <- char a
v <- p
_ <- char z <?> unwords ["a closing", name, show z]
return v
parens' :: IParser a -> IParser a
parens' =
surround' '(' ')' "paren"
parens'' :: IParser a -> IParser (Either Comments [C2 before after a])
parens'' = surround'' '(' ')'
braces'' :: IParser a -> IParser (Either Comments [C2 before after a])
braces'' = surround'' '[' ']'
surround'' :: Char -> Char -> IParser a -> IParser (Either Comments [C2 before after a])
surround'' leftDelim rightDelim inner =
let
sep''' =
do
v <- (\pre a post -> C (pre, post) a) <$> whitespace <*> inner <*> whitespace
option [v] ((\x -> v : x) <$> (char ',' >> sep'''))
sep'' =
do
pre <- whitespace
v <- optionMaybe ((\a post -> C (pre, post) a) <$> inner <*> whitespace)
case v of
Nothing ->
return $ Left pre
Just v' ->
Right <$> option [v'] ((\x -> v' : x) <$> (char ',' >> sep'''))
in
do
_ <- char leftDelim
vs <- sep''
_ <- char rightDelim
return vs
-- HELPERS FOR EXPRESSIONS
addLocation :: IParser a -> IParser (A.Located a)
addLocation expr =
do (start, e, end) <- located expr
return (A.at start end e)
located :: IParser a -> IParser (A.Position, a, A.Position)
located parser =
do start <- Parsec.getPosition
value <- parser
end <- Parsec.getPosition
return (start, value, end)
accessible :: ElmVersion -> IParser (FixAST A.Located typeRef ctorRef varRef 'ExpressionNK) -> IParser (FixAST A.Located typeRef ctorRef varRef 'ExpressionNK)
accessible elmVersion exprParser =
do start <- Parsec.getPosition
rootExpr <- exprParser
access <- optionMaybe (try dot <?> "a field access like .name")
case access of
Nothing ->
return rootExpr
Just _ ->
accessible elmVersion $
do v <- lowVar elmVersion
end <- Parsec.getPosition
return $ I.Fix $ A.at start end $ Access rootExpr v
dot :: IParser ()
dot =
do _ <- char '.'
notFollowedBy (char '.')
commentedKeyword :: ElmVersion -> String -> IParser a -> IParser (C2 beforeKeyword afterKeyword a)
commentedKeyword elmVersion word parser =
do
pre <- try (whitespace <* reserved elmVersion word)
post <- whitespace
value <- parser
return $ C (pre, post) value
-- ODD COMBINATORS
-- Behaves the same as `Parse.ParsecAdapter.fail` except that the consumed
-- continuation is called instead of the empty continuation.
failure :: String -> IParser String
failure msg =
P.Parser $ \s _ _ cerr _ ->
let
(P.Parser p) = parserFail $ parseError (Message msg)
in
-- This looks really unsound, but `p` which was created with `fail` will
-- only ever call the empty error continuation (which in this case
-- re-routes to the consumed error continuation)
p s undefined undefined undefined cerr
until :: IParser a -> IParser b -> IParser b
until p end =
go
where
go = end <|> (p >> go)
-- BASIC LANGUAGE LITERALS
shader :: IParser String
shader =
do _ <- try (string "[glsl|")
closeShader id
closeShader :: (String -> a) -> IParser a
closeShader builder =
choice
[ do _ <- try (string "|]")
return (builder "")
, do c <- anyChar
closeShader (builder . (c:))
]
sandwich :: Char -> String -> String
sandwich delim s =
delim : s ++ [delim]
escaped :: Char -> IParser String
escaped delim =
try $ do
_ <- char '\\'
c <- char '\\' <|> char delim
return ['\\', c]
processAs :: IParser a -> String -> IParser a
processAs processor s =
calloutParser s processor
where
calloutParser :: String -> IParser a -> IParser a
calloutParser inp p =
either (parserFail . const . const) return (iParse p inp)
| avh4/elm-format | elm-format-lib/src/Parse/Helpers.hs | bsd-3-clause | 15,548 | 0 | 28 | 4,433 | 5,306 | 2,660 | 2,646 | 380 | 3 |
-- |JavaScript's syntax.
module BrownPLT.JavaScript.Syntax(Expression(..),CaseClause(..),Statement(..),
InfixOp(..),CatchClause(..),VarDecl(..),JavaScript(..),
AssignOp(..),Id(..),PrefixOp(..),Prop(..),
ForInit(..),ForInInit(..),unId
, UnaryAssignOp (..)
, LValue (..)
) where
import Text.ParserCombinators.Parsec(SourcePos) -- used by data JavaScript
import Data.Generics(Data,Typeable)
data JavaScript a
-- |A script in <script> ... </script> tags. This may seem a little silly,
-- but the Flapjax analogue has an inline variant and attribute-inline
-- variant.
= Script a [Statement a]
deriving (Show,Data,Typeable,Eq,Ord)
data Id a = Id a String deriving (Show,Eq,Ord,Data,Typeable)
unId :: Id a -> String
unId (Id _ s) = s
-- http://developer.mozilla.org/en/docs/
-- Core_JavaScript_1.5_Reference:Operators:Operator_Precedence
data InfixOp = OpLT | OpLEq | OpGT | OpGEq | OpIn | OpInstanceof | OpEq | OpNEq
| OpStrictEq | OpStrictNEq | OpLAnd | OpLOr
| OpMul | OpDiv | OpMod | OpSub | OpLShift | OpSpRShift
| OpZfRShift | OpBAnd | OpBXor | OpBOr | OpAdd
deriving (Show,Data,Typeable,Eq,Ord,Enum)
data AssignOp = OpAssign | OpAssignAdd | OpAssignSub | OpAssignMul | OpAssignDiv
| OpAssignMod | OpAssignLShift | OpAssignSpRShift | OpAssignZfRShift
| OpAssignBAnd | OpAssignBXor | OpAssignBOr
deriving (Show,Data,Typeable,Eq,Ord)
data UnaryAssignOp
= PrefixInc | PrefixDec | PostfixInc | PostfixDec
deriving (Show, Data, Typeable, Eq, Ord)
data PrefixOp = PrefixLNot | PrefixBNot | PrefixPlus
| PrefixMinus | PrefixTypeof | PrefixVoid | PrefixDelete
deriving (Show,Data,Typeable,Eq,Ord)
data Prop a
= PropId a (Id a) | PropString a String | PropNum a Integer
deriving (Show,Data,Typeable,Eq,Ord)
data LValue a
= LVar a String
| LDot a (Expression a) String
| LBracket a (Expression a) (Expression a)
deriving (Show, Eq, Ord, Data, Typeable)
data Expression a
= StringLit a String
| RegexpLit a String Bool {- global? -} Bool {- case-insensitive? -}
| NumLit a Double
| IntLit a Int
| BoolLit a Bool
| NullLit a
| ArrayLit a [Expression a]
| ObjectLit a [(Prop a, Expression a)]
| ThisRef a
| VarRef a (Id a)
| DotRef a (Expression a) (Id a)
| BracketRef a (Expression a) {- container -} (Expression a) {- key -}
| NewExpr a (Expression a) {- constructor -} [Expression a]
| PrefixExpr a PrefixOp (Expression a)
| UnaryAssignExpr a UnaryAssignOp (LValue a)
| InfixExpr a InfixOp (Expression a) (Expression a)
| CondExpr a (Expression a) (Expression a) (Expression a)
| AssignExpr a AssignOp (LValue a) (Expression a)
| ParenExpr a (Expression a)
| ListExpr a [Expression a]
| CallExpr a (Expression a) [Expression a]
| FuncExpr a [(Id a)] (Statement a)
deriving (Show,Data,Typeable,Eq,Ord)
data CaseClause a
= CaseClause a (Expression a) [Statement a]
| CaseDefault a [Statement a]
deriving (Show,Data,Typeable,Eq,Ord)
data CatchClause a
= CatchClause a (Id a) (Statement a)
deriving (Show,Data,Typeable,Eq,Ord)
data VarDecl a
= VarDecl a (Id a) (Maybe (Expression a))
deriving (Show,Data,Typeable,Eq,Ord)
data ForInit a
= NoInit
| VarInit [VarDecl a]
| ExprInit (Expression a)
deriving (Show,Data,Typeable,Eq,Ord)
data ForInInit a
= ForInVar (Id a)
| ForInNoVar (Id a)
deriving (Show,Data,Typeable,Eq,Ord)
data Statement a
= BlockStmt a [Statement a]
| EmptyStmt a
| ExprStmt a (Expression a)
| IfStmt a (Expression a) (Statement a) (Statement a)
| IfSingleStmt a (Expression a) (Statement a)
| SwitchStmt a (Expression a) [CaseClause a]
| WhileStmt a (Expression a) (Statement a)
| DoWhileStmt a (Statement a) (Expression a)
| BreakStmt a (Maybe (Id a))
| ContinueStmt a (Maybe (Id a))
| LabelledStmt a (Id a) (Statement a)
| ForInStmt a (ForInInit a) (Expression a) (Statement a)
| ForStmt a (ForInit a)
(Maybe (Expression a)) -- increment
(Maybe (Expression a)) -- test
(Statement a) -- body
| TryStmt a (Statement a) {-body-} [CatchClause a] {-catches-}
(Maybe (Statement a)) {-finally-}
| ThrowStmt a (Expression a)
| ReturnStmt a (Maybe (Expression a))
| WithStmt a (Expression a) (Statement a)
| VarDeclStmt a [VarDecl a]
| FunctionStmt a (Id a) {-name-} [(Id a)] {-args-} (Statement a) {-body-}
deriving (Show,Data,Typeable,Eq,Ord)
| ducis/flapjax-fixed | WebBits-1.0/src/BrownPLT/JavaScript/Syntax.hs | bsd-3-clause | 4,477 | 0 | 10 | 945 | 1,717 | 963 | 754 | 105 | 1 |
{-# LANGUAGE LambdaCase, RecordWildCards #-}
module Transformations.Optimising.DeadParameterElimination where
import Data.Set (Set)
import Data.Map (Map)
import Data.Vector (Vector)
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.Vector as Vec
import Data.List
import qualified Data.Foldable
import Data.Functor.Foldable as Foldable
import Control.Monad.Trans.Except
import Grin.Grin
import Grin.TypeEnvDefs
import Transformations.Util
import AbstractInterpretation.LiveVariable.Result as LVA
type Trf = Except String
runTrf :: Trf a -> Either String a
runTrf = runExcept
-- P and F nodes are handled by Dead Data Elimination
deadParameterElimination :: LVAResult -> TypeEnv -> Exp -> Either String Exp
deadParameterElimination lvaResult tyEnv = runTrf . cataM alg where
alg :: ExpF Exp -> Trf Exp
alg = \case
DefF f args body -> do
liveArgs <- onlyLiveArgs f args
let deletedArgs = args \\ liveArgs
body' <- bindToUndefineds tyEnv body deletedArgs
return $ Def f liveArgs body'
SAppF f args -> do
liveArgs <- onlyLiveArgs f args
return $ SApp f liveArgs
e -> pure . embed $ e
onlyLiveArgs :: Name -> [a] -> Trf [a]
onlyLiveArgs f args = do
argsLv <- lookupArgLivenessM f lvaResult
return $ zipFilter args (Vec.toList argsLv)
lookupArgLivenessM :: Name -> LVAResult -> Trf (Vector Bool)
lookupArgLivenessM f LVAResult{..} = do
let funNotFound = "Function " ++ show f ++ " was not found in liveness analysis result"
(_,argLv) <- lookupExcept funNotFound f _functionLv
return $ Vec.map isLive argLv
| andorp/grin | grin/src/Transformations/Optimising/DeadParameterElimination.hs | bsd-3-clause | 1,618 | 0 | 15 | 308 | 477 | 249 | 228 | 41 | 3 |
------------------------------------------------------------------------------
-- | This module contains the documented data type.
--
module Autotool.XmlRpc.Types.Documented (
Documented (..)
) where
------------------------------------------------------------------------------
import Network.XmlRpc.Internals
import Autotool.XmlRpc.Types.Basic (Description)
------------------------------------------------------------------------------
data Documented a = Documented {
contents :: a
, documentation :: Description
} deriving Show
instance XmlRpcType a => XmlRpcType (Documented a) where
toValue s = toValue [("contents", toValue (contents s)),
("documentation", toValue (documentation s))]
fromValue v = do t <- fromValue v
s <- getField "Documented" t
c <- getField "contents" s
d <- getField "documentation" s
return $ Documented c d
getType _ = TStruct
| j-hannes/autotool-xmlrpc-client | src/Autotool/XmlRpc/Types/Documented.hs | bsd-3-clause | 987 | 0 | 11 | 221 | 207 | 112 | 95 | 17 | 0 |
module Zipper () where
import Prelude hiding (reverse)
import Data.Set
data Stack a = Stack { focus :: !a -- focused thing in this set
, up :: [a] -- jokers to the left
, down :: [a] } -- jokers to the right
{-@ type UListDif a N = {v:[a] | ((not (Set_mem N (listElts v))) && (Set_emp (listDup v)))} @-}
{-@
data Stack a = Stack { focus :: a
, up :: UListDif a focus
, down :: UListDif a focus }
@-}
{-@
measure listDup :: [a] -> (Set a)
listDup([]) = {v | Set_emp v }
listDup(x:xs) = {v | v = if (Set_mem x (listElts xs)) then (Set_cup (Set_sng x) (listDup xs)) else (listDup xs) }
@-}
{-@ type UStack a = {v:Stack a |(Set_emp (Set_cap (listElts (getUp v)) (listElts (getDown v))))}@-}
{-@ measure getFocus :: forall a. (Stack a) -> a
getFocus (Stack focus up down) = focus
@-}
{-@ measure getUp :: forall a. (Stack a) -> [a]
getUp (Stack focus up down) = up
@-}
{-@ measure getDown :: forall a. (Stack a) -> [a]
getDown (Stack focus up down) = down
@-}
-- QUALIFIERS
{-@ q :: x:a -> {v:[a] |(not (Set_mem x (listElts v)))} @-}
q :: a -> [a]
q = undefined
{-@ q1 :: x:a -> {v:[a] |(Set_mem x (listElts v))} @-}
q1 :: a -> [a]
q1 = undefined
{-@ q0 :: x:a -> {v:[a] |(Set_emp(listDup v))} @-}
q0 :: a -> [a]
q0 = undefined
{-@ focusUp :: UStack a -> UStack a @-}
focusUp :: Stack a -> Stack a
focusUp (Stack t [] rs) = Stack xiggety xs [] where (xiggety:xs) = reverse (t:rs)
focusUp (Stack t (l:ls) rs) = Stack l ls (t:rs)
{-@ reverse :: {v:[a] | Set_emp (listDup v)} -> {v:[a]|Set_emp (listDup v)} @-}
reverse :: [a] -> [a]
reverse = undefined
{-@ focusDown :: UStack a -> UStack a @-}
focusDown :: Stack a -> Stack a
focusDown = undefined
-- focusDown = reverseStack . focusUp . reverseStack
-- | reverse a stack: up becomes down and down becomes up.
{-@ reverseStack :: UStack a -> UStack a @-}
reverseStack :: Stack a -> Stack a
reverseStack = undefined
-- reverseStack (Stack t ls rs) = Stack t rs ls
| ssaavedra/liquidhaskell | tests/pos/zipper000.hs | bsd-3-clause | 2,066 | 0 | 9 | 541 | 296 | 173 | 123 | 23 | 1 |
-- | A renderer that produces a native Haskell 'String', mostly meant for
-- debugging purposes.
--
{-# LANGUAGE OverloadedStrings #-}
module Text.Blaze.Renderer.String
( fromChoiceString
, renderHtml
) where
import Data.List (isInfixOf)
import qualified Data.ByteString.Char8 as SBC
import qualified Data.Text as T
import qualified Data.ByteString as S
import Text.Blaze.Internal
-- | Escape HTML entities in a string
--
escapeHtmlEntities :: String -- ^ String to escape
-> String -- ^ String to append
-> String -- ^ Resulting string
escapeHtmlEntities [] k = k
escapeHtmlEntities (c:cs) k = case c of
'<' -> '&' : 'l' : 't' : ';' : escapeHtmlEntities cs k
'>' -> '&' : 'g' : 't' : ';' : escapeHtmlEntities cs k
'&' -> '&' : 'a' : 'm' : 'p' : ';' : escapeHtmlEntities cs k
'"' -> '&' : 'q' : 'u' : 'o' : 't' : ';' : escapeHtmlEntities cs k
x -> x : escapeHtmlEntities cs k
-- | Render a 'ChoiceString'.
--
fromChoiceString :: ChoiceString -- ^ String to render
-> String -- ^ String to append
-> String -- ^ Resulting string
fromChoiceString (Static s) = getString s
fromChoiceString (String s) = escapeHtmlEntities s
fromChoiceString (Text s) = escapeHtmlEntities $ T.unpack s
fromChoiceString (ByteString s) = (SBC.unpack s ++)
fromChoiceString (PreEscaped x) = case x of
String s -> (s ++)
Text s -> (\k -> T.foldr (:) k s)
s -> fromChoiceString s
fromChoiceString (External x) = case x of
-- Check that the sequence "</" is *not* in the external data.
String s -> if "</" `isInfixOf` s then id else (s ++)
Text s -> if "</" `T.isInfixOf` s then id else (\k -> T.foldr (:) k s)
ByteString s -> if "</" `S.isInfixOf` s then id else (SBC.unpack s ++)
s -> fromChoiceString s
fromChoiceString (AppendChoiceString x y) =
fromChoiceString x . fromChoiceString y
fromChoiceString EmptyChoiceString = id
{-# INLINE fromChoiceString #-}
-- | Render some 'Html' to an appending 'String'.
--
renderString :: Html -- ^ HTML to render
-> String -- ^ String to append
-> String -- ^ Resulting String
renderString = go id
where
go :: (String -> String) -> HtmlM b -> String -> String
go attrs (Parent _ open close content) =
getString open . attrs . ('>' :) . go id content . getString close
go attrs (Leaf _ begin end) = getString begin . attrs . getString end
go attrs (AddAttribute _ key value h) = flip go h $
getString key . fromChoiceString value . ('"' :) . attrs
go attrs (AddCustomAttribute _ key value h) = flip go h $
fromChoiceString key . fromChoiceString value . ('"' :) . attrs
go _ (Content content) = fromChoiceString content
go attrs (Append h1 h2) = go attrs h1 . go attrs h2
go _ Empty = id
{-# NOINLINE go #-}
{-# INLINE renderString #-}
-- | Render HTML to a lazy 'String'.
--
renderHtml :: Html -- ^ HTML to render
-> String -- ^ Resulting 'String'
renderHtml html = renderString html ""
{-# INLINE renderHtml #-}
| jgm/blaze-html | Text/Blaze/Renderer/String.hs | bsd-3-clause | 3,220 | 0 | 13 | 902 | 919 | 487 | 432 | 60 | 9 |
module Json.Internal where
import Data.Char (isSpace)
import qualified Text.Parse as Parse
import qualified Text.ParserCombinators.Poly.Plain as PolyPlain
import qualified Text.ParserCombinators.Poly.Base as PolyBase
comp2 :: (a -> b) -> (c -> d -> a) -> c -> d -> b
comp2 f1 f2 x y = f1 $ f2 x y
runParser :: Parse.TextParser a -> String -> Either String a
runParser = fst `comp2` PolyPlain.runParser
wrapString2 :: Char -> Char -> String -> String
wrapString2 start end str = start : str ++ cend
where
cend = [end]
wrapString :: Char -> String -> String
wrapString a = wrapString2 a a
wrapQuote :: String -> String
wrapQuote = wrapString '"'
wrapBracket :: String -> String
wrapBracket = wrapString2 '[' ']'
wrapBrace :: String -> String
wrapBrace = wrapString2 '{' '}'
matchQuote :: Parse.TextParser Char
matchQuote = PolyPlain.satisfy (=='"')
dropWhitespace :: Parse.TextParser ()
dropWhitespace = do
m <- (PolyPlain.optional $ PolyPlain.satisfy isSpace)
case m of
Nothing -> return ()
Just _ -> dropWhitespace
dropTrailingWhitespace :: Parse.TextParser a -> Parse.TextParser a
dropTrailingWhitespace p = do { x <- p; dropWhitespace; return x; }
satisfyAndDropWhitespace :: (Char -> Bool) -> Parse.TextParser Char
satisfyAndDropWhitespace fn = dropTrailingWhitespace $ PolyPlain.satisfy fn
parseQuoted :: Parse.TextParser a -> Parse.TextParser a
parseQuoted parser = do { matchQuote; result <- parser; matchQuote; return result }
| dyreshark/learn-haskell | Json/Internal.hs | bsd-3-clause | 1,487 | 0 | 11 | 268 | 496 | 262 | 234 | 34 | 2 |
{-# LANGUAGE UnicodeSyntax, DeriveDataTypeable, FlexibleContexts #-}
module Data.Dates.Internal where
import Data.Char
import Text.Parsec
-- | Parser version of Prelude.read
tryRead :: (Read a, Stream s m Char) => String -> ParsecT s st m a
tryRead str =
case reads str of
[(res, "")] -> return res
_ -> fail $ "Cannot read: " ++ str
tryReadInt ∷ (Stream s m Char, Num a) ⇒ String → ParsecT s st m a
tryReadInt str =
if all isDigit str
then return $ fromIntegral $ foldl (\a b → 10*a+b) 0 $ map digitToInt str
else fail $ "Cannot read: " ++ str
-- | Apply parser N times
times ∷ (Stream s m Char)
⇒ Int
→ ParsecT s st m t
→ ParsecT s st m [t]
times 0 _ = return []
times n p = do
ts ← times (n-1) p
t ← optionMaybe p
case t of
Just t' → return (ts ++ [t'])
Nothing → return ts
-- | Parse natural number of N digits
-- which is not greater than M
number ∷ Stream s m Char
⇒ Int -- ^ Number of digits
→ Int -- ^ Maximum value
→ ParsecT s st m Int
number n m = do
t ← tryReadInt =<< (n `times` digit)
if t > m
then fail "number too large"
else return t
pYear ∷ Stream s m Char => ParsecT s st m Int
pYear = do
y ← number 4 10000
if y < 2000
then return (y+2000)
else return y
pMonth ∷ Stream s m Char => ParsecT s st m Int
pMonth = number 2 12
pDay ∷ Stream s m Char => ParsecT s st m Int
pDay = number 2 31
| portnov/dates | Data/Dates/Internal.hs | bsd-3-clause | 1,487 | 0 | 13 | 430 | 577 | 292 | 285 | 44 | 2 |
{-#LANGUAGE TransformListComp #-}
module Language.Asdf.Parser where
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Indent
import Control.Monad
import Control.Monad.Trans.State
import Control.Applicative ((<*))
import Data.Functor.Identity
import GHC.Exts
import Language.Asdf.Lexer
import Language.Asdf.AST
import Language.Asdf.Misc
type OperatorParser = Operator String Operators (StateT SourcePos Identity) ParsedExpr
newtype Operators = Operators [(OperatorParser, Rational)]
type Parser a = IndentParser String Operators a
parseSmplExpr :: Parser ParsedExpr
parseSmplExpr = parseId
<|> indentParens lexer parseExpr
<?> "simple expression"
parseStatement :: Parser ParsedStatement
parseStatement = parseAssign
<|> parseIf
<?> "statement"
parseId :: Parser ParsedExpr
parseId = parseExprWithPos $ liftM (Id . VarId) identifier
parseIf :: Parser ParsedStatement
parseIf = parseStatementWithPos $ do
reserved "if"
cond <- parseExpr
thenBody <- indented >> block parseStatement
elseBody <- optionMaybe $ do
reserved "else"
indented >> indented >> block parseStatement
return $ If cond thenBody elseBody
parseAssign :: Parser ParsedStatement
parseAssign = parseStatementWithPos $ do
-- same
name <- try $ identifier <* reservedOp "="
expr <- parseExpr
return $ Assign name expr
parseOpDef :: Parser (OperatorParser, Rational)
parseOpDef = parseOpType "infixr" InR (flip Infix AssocRight . liftM call2)
<|> parseOpType "infix" In (flip Infix AssocNone . liftM call2)
<|> parseOpType "infixl" InL (flip Infix AssocLeft . liftM call2)
<|> parseOpType "prefix" Pre (Prefix . liftM call)
<|> parseOpType "postfix" Post (Postfix . liftM call)
<?> "operator definition"
where
parseOpType tag fixityCons opCons = do
reserved tag
name <- operator
precedence <- rational
return (opCons $ parseExprWithPos $ reservedOp name >> return (Id $ OpId (fixityCons precedence) name), precedence)
call f@(ParsedExpr pos _) a = ParsedExpr pos (Call f [a])
call2 f@(ParsedExpr pos _) a b = ParsedExpr pos (Call f [a, b])
parseExpr :: Parser ParsedExpr
parseExpr = do
Operators opList <- getState
--let opTable = fmap (fmap fst) $ groupBy ((==) `on` snd) $ reverse $ sortBy (compare `on` snd) opList
let opTable = [ op | (op, prec) <- opList, then reverse ... sortWith by prec, then group by prec]
buildExpressionParser opTable parseSmplExpr <?> "expression"
parseExprWithPos :: Parser Expr -> Parser ParsedExpr
parseExprWithPos p = liftM2 ParsedExpr getPosition p
parseStatementWithPos :: Parser Statement -> Parser ParsedStatement
parseStatementWithPos p = liftM2 ParsedStatement getPosition p
parseLex :: Parser a -> Parser a
parseLex p = do
whiteSpace
x <- p
eof
return x
parseSource :: Parser [ParsedStatement]
parseSource = parseLex $ many parseOpDef >>= putState . Operators >> block parseStatement
parseFile :: String -> IO (Either ParseError [ParsedStatement])
parseFile filename = do
input <- readFile filename
-- the seq is here because of the stupid lazy IO! >:|
return $ seq (length input) $ runIndent filename $ runParserT parseSource (Operators []) filename input
| sw17ch/Asdf | src/Language/Asdf/Parser.hs | bsd-3-clause | 3,295 | 29 | 17 | 654 | 937 | 481 | 456 | 75 | 1 |
module Ghazan.Area (
-- Convert Square Inches to Square Kilometer
sqInTOsqKm
-- Convert Square Inches to Square Meters
, sqInTOsqM
-- Convert Square Inches to Square Feet
, sqInTOsqFt
-- Convert Square Inches to Hectares
, sqInTOhec
-- Convert Square Inches to Acres
, sqInTOacre
-- Convert Square Inches to Square Centimeter
, sqInTOsqCm
-- Convert Square Inches to Square Decimeter
, sqInTOsqDm
-- Convert Square Inches to Square Mile
, sqInTOsqMi
-- Convert Square Inches to Square Millimeter
, sqInTOsqMm
-- Convert Square Inches to Square Yards
, sqInTOsqYd
) where
{- Converting Square Inches -}
sqInTOsqKm :: Floating a => a -> a
sqInTOsqKm x = x^2 / 1550000000
sqInTOsqM :: Floating a => a -> a
sqInTOsqM x = x^2 * 0.00064516
sqInTOsqFt :: Floating a => a -> a
sqInTOsqFt x = x^2 * 0.0069444
sqInTOhec :: Floating a => a -> a
sqInTOhec x = x^2 * 0.000000064516
sqInTOacre :: Floating a => a -> a
sqInTOacre x = x^2 / 6272640
sqInTOsqCm :: Floating a => a -> a
sqInTOsqCm x = x^2 * 6.4516
sqInTOsqDm :: Floating a => a -> a
sqInTOsqDm x = x^2 * 0.064516
sqInTOsqMi :: Floating a => a -> a
sqInTOsqMi x = x^2 / 4014489600
sqInTOsqMm :: Floating a => a -> a
sqInTOsqMm x = x^2 * 645.16
sqInTOsqYd :: Floating a => a -> a
sqInTOsqYd x = x^2 / 1296
| Cortlandd/ConversionFormulas | src/Ghazan/Area.hs | bsd-3-clause | 1,308 | 0 | 6 | 293 | 369 | 196 | 173 | 31 | 1 |
-- This is the leftmost column
-- Its' fine for top level declarations to start in any column...
firstGoodIndentation = 1
-- ...provided all subsequent declarations do, too!
secondGoodIndentation = 2
| NeonGraal/rwh-stack | ch03/GoodIndent.hs | bsd-3-clause | 210 | 0 | 4 | 41 | 14 | 9 | 5 | 2 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Distance.Rules
( rules
) where
import Data.String
import Prelude
import Duckling.Dimensions.Types
import Duckling.Distance.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
ruleNumeralAsDistance :: Rule
ruleNumeralAsDistance = Rule
{ name = "number as distance"
, pattern =
[ dimension Numeral
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData {TNumeral.value = v}:_) ->
Just . Token Distance $ distance v
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleNumeralAsDistance
]
| facebookincubator/duckling | Duckling/Distance/Rules.hs | bsd-3-clause | 897 | 0 | 16 | 173 | 178 | 109 | 69 | 23 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module Hierarchy where
import Control.Applicative
import Control.Foldl (Fold (..))
import qualified Control.Foldl as CF
import Control.Lens (At, FoldableWithIndex, Rewrapped,
Traversable, Unwrapped, Wrapped,
makeLenses, traversed, view,
_Unwrapping, _Wrapped)
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Monad (forM)
import Data.ByteString (ByteString)
import qualified Data.Csv as Csv
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as HM
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid (Monoid (..), Sum (Sum), mempty, (<>))
import Data.Set (Set)
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Typeable
import qualified Data.Vector as V
import Dimensions
import Pipes
import Pipes.Csv as PCsv
import Pipes.Csv.Encoding as PCsv
import qualified Pipes.Extras as P
import Test.QuickCheck (Arbitrary)
import qualified Test.QuickCheck as QC
-- import qualified Test.QuickCheck.Monadic as QC
import qualified Text.Show.Pretty as Pr
type Dim = Text
type Measure = Text
type TradeId = Int
newtype Dimensions = Dimensions { _unDims :: Map Dim Text } deriving (Show, Typeable)
mkDims :: [(Dim, Text)] -> Dimensions
mkDims = Dimensions . Map.fromList
type Measures = Map Measure Double
data Hierarchy a =
Node Dim [Hierarchy a]
| Leaf Measure a
data Trade = Trade {
_tId :: TradeId
, _dimensions :: Dimensions
, _measures :: Measures
} deriving Show
instance Arbitrary Trade where
arbitrary = do
tid <- QC.arbitrary
dims <- forM dimensionMapping $ \(fst -> dim) ->
(dim,) <$> maybe (fromString <$> QC.arbitrary) QC.elements (Map.lookup dim dimChoices)
ms <- forM measureMapping $ \(fst -> m) -> (m,) <$> QC.arbitrary
return $ Trade tid (mkDims dims) (Map.fromList ms)
makeLenses ''Trade
trades :: [Trade]
trades = [ Trade 1 (mkDims [("BOOK", "A")]) $ Map.fromList [("ONE", 1), ("TWO", 107), ("THREE", 1)]
, Trade 2 (mkDims [("BOOK", "A")]) $ Map.fromList [("ONE", 2), ("TWO", 118), ("FOUR", 40)]
, Trade 3 (mkDims [("BOOK", "B")]) $ Map.fromList [("ONE", 3), ("TWO", 109), ("THREE", 70)]
, Trade 4 (mkDims [("BOOK", "A")]) $ Map.fromList [("ONE", 4), ("TWO", 114), ("FOUR", 20)]
, Trade 5 (mkDims [("BOOK", "D")]) $ Map.fromList [("ONE", 5), ("TWO", 106), ("THREE", 90)]
, Trade 6 (mkDims [("BOOK", "A")]) $ Map.fromList [("ONE", 6), ("TWO", 112), ("FOUR", 10)]
, Trade 7 (mkDims [("BOOK", "C")]) $ Map.fromList [("ONE", 1), ("TWO", 102), ("THREE", 40)]
, Trade 8 (mkDims [("BOOK", "A")]) $ Map.fromList [("ONE", 7), ("TWO", 115), ("FOUR", 30)]
, Trade 9 (mkDims [("BOOK", "B")]) $ Map.fromList [("ONE", 1), ("TWO", 102), ("THREE", 50)]
]
--trades ^.. traversed.filtered (has $ measures.ix "ONE")
foldMon
:: (Monoid s, Rewrapped s s, Traversable f,
Unwrapped s ~ Double) =>
(Double -> s) -> f Trade -> Map Measure Double
foldMon mon t =
view _Wrapped <$> F.foldr (Map.unionWith mappend) Map.empty (fmap (view (_Unwrapping mon)) <$> t ^.. Lens.traversed.measures)
range :: (Ord a) => CF.Fold a (Maybe (a, a))
range = fmap (Lens.sequenceOf Lens.both) $ (,) <$> CF.minimum <*> CF.maximum
-- let one = CF.pretraverse (measures.ix "ONE") CF.sum
-- let two = CF.pretraverse (measures.ix "TWO") range
-- CF.fold ((,) <$> one <*> two) trades
-- (3.0,Just (10.0,11.0))
-- CF.fold (CF.pretraverse (measures) keys) trades
keys
:: Ord k =>
Fold (Map k a) (Set k)
keys = Fold Map.union Map.empty Map.keysSet
counts :: Ord k => Fold (Map k m) (Map k Integer)
counts = Fold step Map.empty id
where
step acc m = Map.foldrWithKey (Map.insertWith (+)) (fmap (const 1) m) acc
overMaps :: (Ord k) => Fold a b -> Fold (Map k a) (Map k b)
overMaps (Fold step begin done) = Fold step' Map.empty (fmap done)
where
step' acc m = Map.foldrWithKey insert acc m
insert k el acc = Map.insert k (step (fromMaybe begin $ Map.lookup k acc) el) acc
overFoldable :: (Ord k) => Fold a b -> Fold (Map k a) (Map k b)
-- overFoldable :: (Ord i, At (f i a), FoldableWithIndex i (f i))
-- => Fold a b -> Fold (f i a) (f i b)
overFoldable (Fold step begin done) = Fold step' Map.empty (fmap done)
where
step' acc m = Lens.ifoldr insert acc m
insert k el acc = Lens.at k %~ return . flip step el . fromMaybe begin $ acc
data Stats a = Stats {
_min :: Maybe a
, _max :: Maybe a
, _avg :: Double
} deriving (Show, Eq, Ord)
-- instance ToNamedRecord Stats where
-- toNamedRecord (Stats name age) = namedRecord [
-- "name" .= name, "age" .= age]
groupedBy :: (Ord k) => (a -> k) -> Fold a b -> Fold a (Map k b)
groupedBy f (Fold step begin done) = Fold step' Map.empty (fmap done)
where
step' acc k = Lens.at (f k) %~ return . flip step k . fromMaybe begin $ acc
grouped :: (Ord a) => Fold a b -> Fold a (Map a b)
grouped = groupedBy id
stats :: Fold Double (Stats Double)
stats = Stats <$> CF.minimum
<*> CF.maximum
<*> ((/) <$> CF.sum <*> CF.genericLength)
produceNTrades :: Int -> Producer Trade IO ()
produceNTrades 0 = return ()
produceNTrades n = do
t <- liftIO $ QC.generate QC.arbitrary
yield t
produceNTrades (n - 1)
test :: IO ()
test = putStrLn =<< Pr.ppShow <$> P.fold fld (produceNTrades 10000)
where
fld = groupedBy (Lens.firstOf (dimensions . Lens.to _unDims . Lens.ix "Book.BookName"))
(CF.pretraverse (measures) (overFoldable ((,) <$> CF.sum <*> stats)))
-- foldlWithKey' :: (a -> k -> b -> a) -> a -> Map k b -> a
formatRecord :: Map k a
-> (k -> [(ByteString, ByteString)])
-> (a -> NamedRecord)
-> Producer NamedRecord IO (Map k ())
formatRecord m kfn vfn = Map.traverseWithKey f m
where
f k a = yield $ Csv.namedRecord (kfn k) <> vfn a
formatFolded :: Map Text (Double, Stats Double) -> Csv.NamedRecord
formatFolded m = Map.foldlWithKey' f HM.empty m
where
f acc k (sm, (Stats mn mx av)) = acc <> Csv.namedRecord [
toKV k "sum" sm
--, toKV k "max" mx
--, toKV k "min" mn
, toKV k "avg" av
]
toKV :: Csv.ToField v => Text -> Text -> v -> (ByteString, ByteString)
toKV k sub v = (Csv.toField $ Text.concat [k, "_", sub]) ..= Csv.toField v
(..=) = (Csv..=)
namedRecordToHeader :: HM.HashMap k v -> V.Vector (k, v)
namedRecordToHeader = V.fromList . HM.toList
resultsToCsv m = PCsv.encodeByName undefined
| boothead/hierarchy | src/Hierarchy.hs | bsd-3-clause | 7,455 | 0 | 15 | 2,063 | 2,603 | 1,435 | 1,168 | -1 | -1 |
{- $Id: IdentityList.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* I N V A D E R S *
* *
* Module: IdentityList *
* Purpose: Association list with automatic key assignment and *
* identity-preserving map and filter operations. *
* Author: Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module IdentityList (
ILKey, -- Identity-list key type
IL, -- Identity-list, abstract. Instance of functor.
emptyIL, -- :: IL a
insertIL_, -- :: a -> IL a -> IL a
insertIL, -- :: a -> IL a -> (ILKey, IL a)
listToIL, -- :: [a] -> IL a
keysIL, -- :: IL a -> [ILKey]
elemsIL, -- :: IL a -> [a]
assocsIL, -- :: IL a -> [(ILKey, a)]
deleteIL, -- :: ILKey -> IL a -> IL a
mapIL, -- :: ((ILKey, a) -> b) -> IL a -> IL b
filterIL, -- :: ((ILKey, a) -> Bool) -> IL a -> IL a
mapFilterIL, -- :: ((ILKey, a) -> Maybe b) -> IL a -> IL b
lookupIL, -- :: ILKey -> IL a -> Maybe a
findIL, -- :: ((ILKey, a) -> Bool) -> IL a -> Maybe a
mapFindIL, -- :: ((ILKey, a) -> Maybe b) -> IL a -> Maybe b
findAllIL, -- :: ((ILKey, a) -> Bool) -> IL a -> [a]
mapFindAllIL -- :: ((ILKey, a) -> Maybe b) -> IL a -> [b]
) where
------------------------------------------------------------------------------
-- Data type definitions
------------------------------------------------------------------------------
type ILKey = Int
-- Invariants:
-- * Sorted in descending key order. (We don't worry about
-- key wrap around).
-- * Keys are NOT reused
data IL a = IL { ilNextKey :: ILKey, ilAssocs :: [(ILKey, a)] }
deriving (Show)
------------------------------------------------------------------------------
-- Class instances
------------------------------------------------------------------------------
instance Functor IL where
fmap f (IL {ilNextKey = nk, ilAssocs = kas}) =
IL {ilNextKey = nk, ilAssocs = [ (i, f a) | (i, a) <- kas ]}
------------------------------------------------------------------------------
-- Constructors
------------------------------------------------------------------------------
emptyIL :: IL a
emptyIL = IL {ilNextKey = 0, ilAssocs = []}
insertIL_ :: a -> IL a -> IL a
insertIL_ a il = snd (insertIL a il)
insertIL :: a -> IL a -> (ILKey, IL a)
insertIL a (IL {ilNextKey = k, ilAssocs = kas}) = (k, il') where
il' = IL {ilNextKey = k + 1, ilAssocs = (k, a) : kas}
listToIL :: [a] -> IL a
listToIL as = IL {ilNextKey = length as,
ilAssocs = reverse (zip [0..] as)} -- Maintain invariant!
------------------------------------------------------------------------------
-- Additional selectors
------------------------------------------------------------------------------
assocsIL :: IL a -> [(ILKey, a)]
assocsIL = ilAssocs
keysIL :: IL a -> [ILKey]
keysIL = map fst . ilAssocs
elemsIL :: IL a -> [a]
elemsIL = map snd . ilAssocs
------------------------------------------------------------------------------
-- Mutators
------------------------------------------------------------------------------
deleteIL :: ILKey -> IL a -> IL a
deleteIL k (IL {ilNextKey = nk, ilAssocs = kas}) =
IL {ilNextKey = nk, ilAssocs = deleteHlp kas}
where
deleteHlp [] = []
deleteHlp kakas@(ka@(k', _) : kas') | k > k' = kakas
| k == k' = kas'
| otherwise = ka : deleteHlp kas'
------------------------------------------------------------------------------
-- Filter and map operations
------------------------------------------------------------------------------
-- These are "identity-preserving", i.e. the key associated with an element
-- in the result is the same as the key of the element from which the
-- result element was derived.
mapIL :: ((ILKey, a) -> b) -> IL a -> IL b
mapIL f (IL {ilNextKey = nk, ilAssocs = kas}) =
IL {ilNextKey = nk, ilAssocs = [(k, f ka) | ka@(k,_) <- kas]}
filterIL :: ((ILKey, a) -> Bool) -> IL a -> IL a
filterIL p (IL {ilNextKey = nk, ilAssocs = kas}) =
IL {ilNextKey = nk, ilAssocs = filter p kas}
mapFilterIL :: ((ILKey, a) -> Maybe b) -> IL a -> IL b
mapFilterIL p (IL {ilNextKey = nk, ilAssocs = kas}) =
IL {
ilNextKey = nk,
ilAssocs = [(k, b) | ka@(k, _) <- kas, Just b <- [p ka]]
}
------------------------------------------------------------------------------
-- Lookup operations
------------------------------------------------------------------------------
lookupIL :: ILKey -> IL a -> Maybe a
lookupIL k il = lookup k (ilAssocs il)
findIL :: ((ILKey, a) -> Bool) -> IL a -> Maybe a
findIL p (IL {ilAssocs = kas}) = findHlp kas
where
findHlp [] = Nothing
findHlp (ka@(_, a) : kas') = if p ka then Just a else findHlp kas'
mapFindIL :: ((ILKey, a) -> Maybe b) -> IL a -> Maybe b
mapFindIL p (IL {ilAssocs = kas}) = mapFindHlp kas
where
mapFindHlp [] = Nothing
mapFindHlp (ka : kas') = case p ka of
Nothing -> mapFindHlp kas'
jb@(Just _) -> jb
findAllIL :: ((ILKey, a) -> Bool) -> IL a -> [a]
findAllIL p (IL {ilAssocs = kas}) = [ a | ka@(_, a) <- kas, p ka ]
mapFindAllIL:: ((ILKey, a) -> Maybe b) -> IL a -> [b]
mapFindAllIL p (IL {ilAssocs = kas}) = [ b | ka <- kas, Just b <- [p ka] ]
| markgrebe/Blankeroids | IdentityList.hs | bsd-3-clause | 5,842 | 9 | 13 | 1,591 | 1,386 | 789 | 597 | 75 | 3 |
{-# Language OverloadedStrings #-}
{-|
Module : Client.State.Extensions
Description : Integration between the client and external extensions
Copyright : (c) Eric Mertens, 2018
License : ISC
Maintainer : emertens@gmail.com
This module implements the interaction between the client and its extensions.
This includes aspects of the extension system that depend on the current client
state.
-}
module Client.State.Extensions
( clientChatExtension
, clientCommandExtension
, clientStartExtensions
, clientNotifyExtensions
, clientStopExtensions
, clientExtTimer
, clientThreadJoin
) where
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import Control.Exception
import Control.Lens
import Control.Monad
import Data.Foldable
import Data.Text (Text)
import Data.Time
import Foreign.Ptr
import Foreign.StablePtr
import qualified Data.Text as Text
import qualified Data.IntMap as IntMap
import Irc.RawIrcMsg
import Client.State
import Client.Message
import Client.CApi
import Client.CApi.Types
import Client.Configuration
-- | Start extensions after ensuring existing ones are stopped
clientStartExtensions ::
ClientState {- ^ client state -} ->
IO ClientState {- ^ client state with new extensions -}
clientStartExtensions st =
do let cfg = view clientConfig st
st1 <- clientStopExtensions st
foldM start1 st1 (view configExtensions cfg)
-- | Start a single extension and register it with the client or
-- record the error message.
start1 :: ClientState -> ExtensionConfiguration -> IO ClientState
start1 st config =
do res <- try (openExtension config) :: IO (Either IOError ActiveExtension)
case res of
Left err ->
do now <- getZonedTime
return $! recordNetworkMessage ClientMessage
{ _msgTime = now
, _msgBody = ErrorBody (Text.pack (displayException err))
, _msgNetwork = ""
} st
Right ae ->
-- allocate a new identity for this extension
do let i = case IntMap.maxViewWithKey (view (clientExtensions . esActive) st) of
Just ((k,_),_) -> k+1
Nothing -> 0
let st1 = st & clientExtensions . esActive . at i ?~ ae
(st2, h) <- clientPark i st1 (startExtension (clientToken st1) config ae)
-- save handle back into active extension
return $! st2 & clientExtensions . esActive . ix i %~ \ae' ->
ae' { aeSession = h }
-- | Unload all active extensions.
clientStopExtensions ::
ClientState {- ^ client state -} ->
IO ClientState {- ^ client state with extensions unloaded -}
clientStopExtensions st =
do let (aes,st1) = st & clientExtensions . esActive %%~ upd
ifoldlM step st1 aes
where
upd = fmap (fmap disable) . IntMap.partition readyToClose
disable ae = ae { aeLive = False }
readyToClose ae = aeThreads ae == 0
step i st2 ae =
do (st3,_) <- clientPark i st2 (stopExtension ae)
return st3
-- | Dispatch chat messages through extensions before sending to server.
clientChatExtension ::
Text {- ^ network -} ->
Text {- ^ target -} ->
Text {- ^ message -} ->
ClientState {- ^ client state, allow message -} ->
IO (ClientState, Bool)
clientChatExtension net tgt msg st
| noCallback = return (st, True)
| otherwise = evalNestedIO $
do chat <- withChat net tgt msg
liftIO (chat1 chat st (IntMap.toList (IntMap.filter aeLive aes)))
where
aes = view (clientExtensions . esActive) st
noCallback = all (\ae -> fgnChat (aeFgn ae) == nullFunPtr) aes
chat1 ::
Ptr FgnChat {- ^ serialized chat message -} ->
ClientState {- ^ client state -} ->
[(Int,ActiveExtension)] {- ^ extensions needing callback -} ->
IO (ClientState, Bool) {- ^ new state and allow -}
chat1 _ st [] = return (st, True)
chat1 chat st ((i,ae):aes) =
do (st1, allow) <- clientPark i st (chatExtension ae chat)
if allow then chat1 chat st1 aes
else return (st1, False)
-- | Dispatch incoming IRC message through extensions
clientNotifyExtensions ::
Text {- ^ network -} ->
RawIrcMsg {- ^ incoming message -} ->
ClientState {- ^ client state -} ->
IO (ClientState, Bool) {- ^ drop message when false -}
clientNotifyExtensions network raw st
| noCallback = return (st, True)
| otherwise = evalNestedIO $
do fgn <- withRawIrcMsg network raw
liftIO (message1 fgn st (IntMap.toList (IntMap.filter aeLive aes)))
where
aes = view (clientExtensions . esActive) st
noCallback = all (\ae -> fgnMessage (aeFgn ae) == nullFunPtr) aes
message1 ::
Ptr FgnMsg {- ^ serialized IRC message -} ->
ClientState {- ^ client state -} ->
[(Int,ActiveExtension)] {- ^ extensions needing callback -} ->
IO (ClientState, Bool) {- ^ new state and allow -}
message1 _ st [] = return (st, True)
message1 chat st ((i,ae):aes) =
do (st1, allow) <- clientPark i st (notifyExtension ae chat)
if allow then message1 chat st1 aes
else return (st1, False)
-- | Dispatch @/extension@ command to correct extension. Returns
-- 'Nothing' when no matching extension is available.
clientCommandExtension ::
Text {- ^ extension name -} ->
Text {- ^ command -} ->
ClientState {- ^ client state -} ->
IO (Maybe ClientState) {- ^ new client state on success -}
clientCommandExtension name command st =
case find (\(_,ae) -> aeName ae == name)
(IntMap.toList (IntMap.filter aeLive (view (clientExtensions . esActive) st))) of
Nothing -> return Nothing
Just (i,ae) ->
do (st', _) <- clientPark i st (commandExtension command ae)
return (Just st')
-- | Prepare the client to support reentry from the extension API.
clientPark ::
Int {- ^ extension ID -} ->
ClientState {- ^ client state -} ->
IO a {- ^ continuation using the stable pointer to the client -} ->
IO (ClientState, a)
clientPark i st k =
do let mvar = view (clientExtensions . esMVar) st
putMVar mvar (i,st)
res <- k
(_,st') <- takeMVar mvar
return (st', res)
-- | Get the pointer used by C extensions to reenter the client.
clientToken :: ClientState -> Ptr ()
clientToken = views (clientExtensions . esStablePtr) castStablePtrToPtr
-- | Run the next available timer event on a particular extension.
clientExtTimer ::
Int {- ^ extension ID -} ->
ClientState {- ^ client state -} ->
IO ClientState
clientExtTimer i st =
do let ae = st ^?! clientExtensions . esActive . ix i
case popTimer ae of
Nothing -> return st
Just (_, timerId, fun, dat, ae') ->
do let st1 = set (clientExtensions . esActive . ix i) ae' st
(st2,_) <- clientPark i st1 (runTimerCallback fun dat timerId)
return st2
-- | Run the thread join action on a given extension.
clientThreadJoin ::
Int {- ^ extension ID -} ->
ThreadEntry {- ^ thread result -} ->
ClientState {- ^ client state -} ->
IO ClientState
clientThreadJoin i thread st =
let ae = st ^?! clientExtensions . esActive . ix i
in finish ae { aeThreads = aeThreads ae - 1}
where
finish ae
| aeLive ae = -- normal behavior, run finalizer
do let st1 = set (clientExtensions . esActive . ix i) ae st
(st2,_) <- clientPark i st1 (threadFinish thread)
pure st2
| aeThreads ae == 0 = -- delayed stop, all threads done
do let st1 = over (clientExtensions . esActive) (sans i) st
(st2,_) <- clientPark i st1 (stopExtension ae)
return st2
| otherwise = -- delayed stop, more threads remain
do pure (set (clientExtensions . esActive . ix i) ae st)
| dolio/irc-core | src/Client/State/Extensions.hs | isc | 8,285 | 0 | 20 | 2,487 | 2,063 | 1,067 | 996 | -1 | -1 |
module CIDemo.Api.Reverse.Internal where
import Prelude hiding (reverse)
import Rest
import qualified Rest.Resource as R
import CIDemo.Types
resource :: Resource CIDemo CIDemo () Void Void
resource = mkResourceId
{ R.name = "reverse"
, R.schema = noListing $ named []
, R.create = Just create
}
create :: Handler CIDemo
create = mkInputHandler (stringO . someO . stringI . someI) $ \txt ->
return $ reverse txt
reverse :: [a] -> [a]
reverse = foldl (flip (:)) []
| AndrewRademacher/ci-demo-cloudfoundry | src/CIDemo/Api/Reverse/Internal.hs | mit | 546 | 0 | 10 | 159 | 176 | 100 | 76 | 15 | 1 |
-- |
-- Module: Math.NumberTheory.Primes.Factorisation.Utils
-- Copyright: (c) 2011 Daniel Fischer
-- Licence: MIT
-- Maintainer: Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability: Provisional
-- Portability: Non-portable (GHC extensions)
--
-- Some utilities related to factorisation, defined here to avoid import cycles.
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_HADDOCK hide #-}
module Math.NumberTheory.Primes.Factorisation.Utils
( ppTotient
, totientFromCanonical
, carmichaelFromCanonical
, divisorsFromCanonical
, tauFromCanonical
, divisorSumFromCanonical
, sigmaFromCanonical
) where
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Bits
import Data.List
import Math.NumberTheory.Powers.Integer
-- | Totient of a prime power.
ppTotient :: (Integer,Int) -> Integer
ppTotient (p,1) = p-1
ppTotient (p,k) = (p-1)*(integerPower p (k-1)) -- slightly faster than (^) usually
-- | Calculate the totient from the canonical factorisation.
totientFromCanonical :: [(Integer,Int)] -> Integer
totientFromCanonical = product . map ppTotient
-- | Calculate the Carmichael function from the factorisation.
-- Requires that the list of prime factors is strictly ascending.
carmichaelFromCanonical :: [(Integer,Int)] -> Integer
carmichaelFromCanonical = go2
where
go2 ((2,k):ps) = let acc = case k of
1 -> 1
2 -> 2
_ -> 1 `shiftL` (k-2)
in go acc ps
go2 ps = go 1 ps
go !acc ((p,1):pps) = go (lcm acc (p-1)) pps
go acc ((p,k):pps) = go ((lcm acc (p-1))*integerPower p (k-1)) pps
go acc [] = acc
-- | The set of divisors, efficiently calculated from the canonical factorisation.
divisorsFromCanonical :: [(Integer,Int)] -> Set Integer
divisorsFromCanonical = foldl' step (Set.singleton 1)
where
step st (p,k) = Set.unions (st:[Set.mapMonotonic (*pp) st | pp <- take k (iterate (*p) p) ])
-- | The number of divisors, efficiently calculated from the canonical factorisation.
tauFromCanonical :: [(a,Int)] -> Integer
tauFromCanonical pps = product [fromIntegral k + 1 | (_,k) <- pps]
-- | The sum of all divisors, efficiently calculated from the canonical factorisation.
divisorSumFromCanonical :: [(Integer,Int)] -> Integer
divisorSumFromCanonical = product . map ppDivSum
ppDivSum :: (Integer,Int) -> Integer
ppDivSum (p,1) = p+1
ppDivSum (p,k) = (p^(k+1)-1) `quot` (p-1)
-- | The sum of the powers (with fixed exponent) of all divisors,
-- efficiently calculated from the canonical factorisation.
sigmaFromCanonical :: Int -> [(Integer,Int)] -> Integer
sigmaFromCanonical k = product . map (ppDivPowerSum k)
ppDivPowerSum :: Int -> (Integer,Int) -> Integer
ppDivPowerSum k (p,m) = (p^(k*(m+1)) - 1) `quot` (p^k - 1)
| shlevy/arithmoi | Math/NumberTheory/Primes/Factorisation/Utils.hs | mit | 2,860 | 0 | 16 | 596 | 808 | 461 | 347 | 45 | 6 |
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
--
-- Module : Base
-- Copyright :
-- License : MIT
--
-- Maintainer : agocorona@gmail.com
-- Stability :
-- Portability :
--
-- | Transient provides high level concurrency allowing you to do concurrent
-- processing without requiring any knowledge of threads or synchronization.
-- From the programmer's perspective, the programming model is single threaded.
-- Concurrent tasks are created and composed seamlessly resulting in highly
-- modular and composable concurrent programs. Transient has diverse
-- applications from simple concurrent applications to massively parallel and
-- distributed map-reduce problems. If you are considering Apache Spark or
-- Cloud Haskell then transient might be a simpler yet better solution for you
-- (see
-- <https://github.com/transient-haskell/transient-universe transient-universe>).
-- Transient makes it easy to write composable event driven reactive UI
-- applications. For example, <https://hackage.haskell.org/package/axiom Axiom>
-- is a transient based unified client and server side framework that provides
-- a better programming model and composability compared to frameworks like
-- ReactJS.
--
-- = Overview
--
-- The 'TransientIO' monad allows you to:
--
-- * Split a problem into concurrent task sets
-- * Compose concurrent task sets using non-determinism
-- * Collect and combine results of concurrent tasks
--
-- You can think of 'TransientIO' as a concurrent list transformer monad with
-- many other features added on top e.g. backtracking, logging and recovery to
-- move computations across machines for distributed processing.
--
-- == Non-determinism
--
-- In its non-concurrent form, the 'TransientIO' monad behaves exactly like a
-- <http://hackage.haskell.org/package/list-transformer list transformer monad>.
-- It is like a list whose elements are generated using IO effects. It composes
-- in the same way as a list monad. Let's see an example:
--
-- @
-- import Control.Concurrent (threadDelay)
-- import Control.Monad.IO.Class (liftIO)
-- import System.Random (randomIO)
-- import Transient.Base (keep, threads, waitEvents)
--
-- main = keep $ threads 0 $ do
-- x <- waitEvents (randomIO :: IO Int)
-- liftIO $ threadDelay 1000000
-- liftIO $ putStrLn $ show x
-- @
--
-- 'keep' runs the 'TransientIO' monad. The 'threads' primitive limits the
-- number of threads to force non-concurrent operation. The 'waitEvents'
-- primitive generates values (list elements) in a loop using the 'randomIO' IO
-- action. The above code behaves like a list monad as if we are drawing
-- elements from a list generated by 'waitEvents'. The sequence of actions
-- following 'waitEvents' is executed for each element of the list. We see a
-- random value printed on the screen every second. As you can see this
-- behavior is identical to a list transformer monad.
--
-- == Concurrency
--
-- 'TransientIO' monad is a concurrent list transformer i.e. each element of
-- the generated list can be processed concurrently. In the previous example
-- if we change the number of threads to 10 we can see concurrency in action:
--
-- @
-- ...
-- main = keep $ threads 10 $ do
-- ...
-- @
--
-- Now each element of the list is processed concurrently in a separate thread,
-- up to 10 threads are used. Therefore we see 10 results printed every second
-- instead of 1 in the previous version.
--
-- In the above examples the list elements are generated using a synchronous IO
-- action. These elements can also be asynchronous events, for example an
-- interactive user input. In transient, the elements of the list are known as
-- tasks. The tasks terminology is general and intuitive in the context of
-- transient as tasks can be triggered by asynchronous events and multiple of
-- them can run simultaneously in an unordered fashion.
--
-- == Composing Tasks
--
-- The type @TransientIO a@ represents a /task set/ with each task in
-- the set returning a value of type @a@. A task set could be /finite/ or
-- /infinite/; multiple tasks could run simultaneously. The absence of a task,
-- a void task set or failure is denoted by a special value 'empty' in an
-- 'Alternative' composition, or the 'stop' primitive in a monadic composition.
-- In the transient programming model the programmer thinks in terms of tasks
-- and composes tasks. Whether the tasks run synchronously or concurrently does
-- not matter; concurrency is hidden from the programmer for the most part. In
-- the previous example the code written for a single threaded list transformer
-- works concurrently as well.
--
-- We have already seen that the 'Monad' instance provides a way to compose the
-- tasks in a sequential, non-deterministic and concurrent manner. When a void
-- task set is encountered, the monad stops processing any further computations
-- as we have nothing to do. The following example does not generate any
-- output after "stop here":
--
-- @
-- main = keep $ threads 0 $ do
-- x <- waitEvents (randomIO :: IO Int)
-- liftIO $ threadDelay 1000000
-- liftIO $ putStrLn $ "stop here"
-- stop
-- liftIO $ putStrLn $ show x
-- @
--
-- When a task creation primitive creates a task concurrently in a new thread
-- (e.g. 'waitEvents'), it returns a void task set in the current thread
-- making it stop further processing. However, processing resumes from the same
-- point onwards with the same state in the new task threads as and when they
-- are created; as if the current thread along with its state has branched into
-- multiple threads, one for each new task. In the following example you can
-- see that the thread id changes after the 'waitEvents' call:
--
-- @
-- main = keep $ threads 1 $ do
-- mainThread <- liftIO myThreadId
-- liftIO $ putStrLn $ "Main thread: " ++ show mainThread
-- x <- waitEvents (randomIO :: IO Int)
--
-- liftIO $ threadDelay 1000000
-- evThread <- liftIO myThreadId
-- liftIO $ putStrLn $ "Event thread: " ++ show evThread
-- @
--
-- Note that if we use @threads 0@ then the new task thread is the same as the
-- main thread because 'waitEvents' falls back to synchronous non-concurrent
-- mode, and therefore returns a non void task set.
--
-- In an 'Alternative' composition, when a computation results in 'empty'
-- the next alternative is tried. When a task creation primitive creates a
-- concurrent task, it returns 'empty' allowing tasks to run concurrently when
-- composed with the '<|>' combinator. The following example combines two
-- single concurrent tasks generated by 'async':
--
-- @
-- main = keep $ do
-- x <- event 1 \<|\> event 2
-- liftIO $ putStrLn $ show x
-- where event n = async (return n :: IO Int)
-- @
--
-- Note that availability of threads can impact the behavior of an application.
-- An infinite task set generator (e.g. 'waitEvents' or 'sample') running
-- synchronously (due to lack of threads) can block all other computations in
-- an 'Alternative' composition. The following example does not trigger the
-- 'async' task unless we increase the number of threads to make 'waitEvents'
-- asynchronous:
--
-- @
-- main = keep $ threads 0 $ do
-- x <- waitEvents (randomIO :: IO Int) \<|\> async (return 0 :: IO Int)
-- liftIO $ threadDelay 1000000
-- liftIO $ putStrLn $ show x
-- @
--
-- == Parallel Map Reduce
--
-- The following example uses 'choose' to send the items in a list to parallel
-- tasks for squaring and then folds the results of those tasks using 'collect'.
--
-- @
-- import Control.Monad.IO.Class (liftIO)
-- import Data.List (sum)
-- import Transient.Base (keep)
-- import Transient.Indeterminism (choose, collect)
--
-- main = keep $ do
-- collect 100 squares >>= liftIO . putStrLn . show . sum
-- where
-- squares = do
-- x <- choose [1..100]
-- return (x * x)
-- @
--
-- == State Isolation
--
-- State is inherited but never shared. A transient application is written as
-- a composition of task sets. New concurrent tasks can be triggered from
-- inside a task. A new task inherits the state of the monad at the point
-- where it got started. However, the state of a task is always completely
-- isolated from other tasks irrespective of whether it is started in a new
-- thread or not. The state is referentially transparent i.e. any changes to
-- the state creates a new copy of the state. Therefore a programmer does not
-- have to worry about synchronization or unintended side effects.
--
-- The monad starts with an empty state. At any point you can add ('setData'),
-- retrieve ('getSData') or delete ('delData') a data item to or from the
-- current state. Creation of a task /branches/ the computation, inheriting
-- the previous state, and collapsing (e.g. 'collect') discards the state of
-- the tasks being collapsed. If you want to use the state in the results you
-- will have to pass it as part of the results of the tasks.
--
-- = Reactive Applications
--
-- A popular model to handle asynchronous events in imperative languages is the
-- callback model. The control flow of the program is driven by events and
-- callbacks; callbacks are event handlers that are hooked into the event
-- generation code and are invoked every time an event happens. This model
-- makes the overall control flow hard to understand resulting into a "callback
-- hell" because the logic is distributed across various isolated callback
-- handlers, and many different event threads work on the same global state.
--
-- Transient provides a better programming model for reactive applications. In
-- contrast to the callback model, transient transparently moves the relevant
-- state to the respective event threads and composes the results to arrive at
-- the new state. The programmer is not aware of the threads, there is no
-- shared state to worry about, and a seamless sequential flow enabling easy
-- reasoning and composable application components.
-- <https://hackage.haskell.org/package/axiom Axiom> is a client and server
-- side web UI and reactive application framework built using the transient
-- programming model.
--
-- = Further Reading
--
-- * <https://github.com/transient-haskell/transient/wiki/Transient-tutorial Tutorial>
-- * <https://github.com/transient-haskell/transient-examples Examples>
--
-----------------------------------------------------------------------------
module Transient.Base(
-- * The Monad
TransIO, TransientIO
-- * Task Composition Operators
, (**>), (<**), (<***)
-- * Running the monad
,keep, keep', stop, exit
-- * Asynchronous console IO
,option, input,input'
-- * Task Creation
-- $taskgen
, StreamData(..)
,parallel, async, waitEvents, sample, spawn, react, abduce
-- * State management
,setData, getSData, getData, delData, modifyData, modifyData', try, setState, getState, delState, getRState,setRState, modifyState
,labelState, findState, killState
-- * Thread management
, threads,addThreads, freeThreads, hookedThreads,oneThread, killChilds
-- * Exceptions
-- $exceptions
,onException, onException', cutExceptions, continue, catcht, throwt
-- * Utilities
,genId, Loggable
)
where
import Transient.Internals
-- $taskgen
--
-- These primitives are used to create asynchronous and concurrent tasks from
-- an IO action.
--
-- $exceptions
--
-- Exception handlers are implemented using the backtracking mechanism.
-- (see 'Transient.Backtrack.back'). Several exception handlers can be
-- installed using 'onException'; handlers are run in reverse order when an
-- exception is raised. The following example prints "3" and then "2".
--
-- @
-- {-\# LANGUAGE ScopedTypeVariables #-}
-- import Transient.Base (keep, onException, cutExceptions)
-- import Control.Monad.IO.Class (liftIO)
-- import Control.Exception (ErrorCall)
--
-- main = keep $ do
-- onException $ \\(e:: ErrorCall) -> liftIO $ putStrLn "1"
-- cutExceptions
-- onException $ \\(e:: ErrorCall) -> liftIO $ putStrLn "2"
-- onException $ \\(e:: ErrorCall) -> liftIO $ putStrLn "3"
-- liftIO $ error "Raised ErrorCall exception" >> return ()
-- @
| agocorona/transient | src/Transient/Base.hs | mit | 12,207 | 0 | 5 | 2,169 | 440 | 384 | 56 | 14 | 0 |
wabbits factor = map fst $ iterate (\(n0, n1) -> (n1, n0 * factor + n1)) (1, 1)
wabbitCount factor months = last $ take months $ wabbits factor
main = do
putStrLn "huh?"
| abingham/rosalind | wabbits.hs | mit | 174 | 0 | 11 | 38 | 90 | 46 | 44 | 4 | 1 |
module DetalhesSobreListasERecursao where
import IntroducaoAProgramacaoFuncionalEHaskell
-- notação alternativa
procIndice l i = case l of
[] -> []
(e:l) -> if (i == 0) then [e]
else procIndice l (i-1)
-- Testando
i1 = procurarIndice [12,3,4,5,9] 3
i2 = procurarIndice [12,3,4,5,9] 6
i3 = procIndice [12,3,4,5,9] 3
i4 = procIndice [12,3,4,5,9] 6
-- procurarP n [] = []
-- procurarP n ((n,s):cs) = [(n,s)]
-- variável não pode ser repetida no padrão...
-- procurarP n ((n1,s):cs) = procurarP n cs
-- Mais funções sobre listas, agora com contas
cadastrarBugado c l = l ++ [c]
procurar n [] = []
procurar n1 ((n2,s):l) | n1 == n2 = [(n2,s)]
| n1 /= n2 = procurar n1 l
remover n [] = []
remover n1 ((n2,s):l) | n1 == n2 = l
| n1 /= n2 = (n2,s) : remover n1 l
creditar n v [] = []
creditar n1 v ((n2,s):l) | n1 == n2 = (creditarConta (n2,s) v) : l
| n1 /= n2 = (n2,s) : (creditar n1 v l)
debitar n v [] = []
debitar n1 v ((n2,s):l) | n1 == n2 = (debitarConta (n2,s) v) : l
| n1 /= n2 = (n2,s) : (debitar n1 v l)
existe n l = (procurar n l) /= []
cadastrar c l = if (existe (fst c) l) then l else l ++ [c]
-- Testando
banco1 = []
banco2 = cadastrar ("12-3",100) (cadastrar ("45-6",0) (cadastrar ("12-3",0) banco1))
conta1 = procurar "12-3" banco2
banco3 = creditar "12-3" 55 banco2
conta2 = procurar "12-3" banco3
banco4 = remover "45-6" banco3
tamanhoBanco = tamanho banco4
-- Exercício: definir ++
-- definir reverse
-- não precisa (rev l) ++ [e], nem e:(conc l m), aplicação de função puxa pela esquerda…
rev [] = []
rev (e:l) = rev l ++ [e]
conc [] l = l
conc (e:l) m = e:conc l m
| henvic/plc | src/DetalhesSobreListasERecursao.hs | cc0-1.0 | 1,782 | 0 | 11 | 501 | 794 | 428 | 366 | 36 | 3 |
module SimilarNegation where
test :: Float
test = - (3.0 + 6.0)
test' :: Int
test' = - 3
{- dit zijn nu syntax errors:
test'' :: Float -> Float
test'' (- 1.0) = 1.0
test'' x = x +. 1.0
test''' :: Int -> Bool
test''' (-. 1) = True
test''' _ = False
-} | roberth/uu-helium | test/typeerrors/Heuristics/SimilarNegation.hs | gpl-3.0 | 265 | 0 | 7 | 70 | 36 | 22 | 14 | 5 | 1 |
main = 3/0
| roberth/uu-helium | test/simple/thompson/Thompson33.hs | gpl-3.0 | 11 | 0 | 5 | 3 | 10 | 5 | 5 | 1 | 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.EC2.ImportSnapshot
-- 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)
--
-- Imports a disk into an EBS snapshot.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ImportSnapshot.html AWS API Reference> for ImportSnapshot.
module Network.AWS.EC2.ImportSnapshot
(
-- * Creating a Request
importSnapshot
, ImportSnapshot
-- * Request Lenses
, isDiskContainer
, isClientToken
, isRoleName
, isDescription
, isDryRun
, isClientData
-- * Destructuring the Response
, importSnapshotResponse
, ImportSnapshotResponse
-- * Response Lenses
, isrsSnapshotTaskDetail
, isrsImportTaskId
, isrsDescription
, isrsResponseStatus
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'importSnapshot' smart constructor.
data ImportSnapshot = ImportSnapshot'
{ _isDiskContainer :: !(Maybe SnapshotDiskContainer)
, _isClientToken :: !(Maybe Text)
, _isRoleName :: !(Maybe Text)
, _isDescription :: !(Maybe Text)
, _isDryRun :: !(Maybe Bool)
, _isClientData :: !(Maybe ClientData)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ImportSnapshot' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'isDiskContainer'
--
-- * 'isClientToken'
--
-- * 'isRoleName'
--
-- * 'isDescription'
--
-- * 'isDryRun'
--
-- * 'isClientData'
importSnapshot
:: ImportSnapshot
importSnapshot =
ImportSnapshot'
{ _isDiskContainer = Nothing
, _isClientToken = Nothing
, _isRoleName = Nothing
, _isDescription = Nothing
, _isDryRun = Nothing
, _isClientData = Nothing
}
-- | Information about the disk container.
isDiskContainer :: Lens' ImportSnapshot (Maybe SnapshotDiskContainer)
isDiskContainer = lens _isDiskContainer (\ s a -> s{_isDiskContainer = a});
-- | Token to enable idempotency for VM import requests.
isClientToken :: Lens' ImportSnapshot (Maybe Text)
isClientToken = lens _isClientToken (\ s a -> s{_isClientToken = a});
-- | The name of the role to use when not using the default role,
-- \'vmimport\'.
isRoleName :: Lens' ImportSnapshot (Maybe Text)
isRoleName = lens _isRoleName (\ s a -> s{_isRoleName = a});
-- | The description string for the import snapshot task.
isDescription :: Lens' ImportSnapshot (Maybe Text)
isDescription = lens _isDescription (\ s a -> s{_isDescription = a});
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
isDryRun :: Lens' ImportSnapshot (Maybe Bool)
isDryRun = lens _isDryRun (\ s a -> s{_isDryRun = a});
-- | The client-specific data.
isClientData :: Lens' ImportSnapshot (Maybe ClientData)
isClientData = lens _isClientData (\ s a -> s{_isClientData = a});
instance AWSRequest ImportSnapshot where
type Rs ImportSnapshot = ImportSnapshotResponse
request = postQuery eC2
response
= receiveXML
(\ s h x ->
ImportSnapshotResponse' <$>
(x .@? "snapshotTaskDetail") <*>
(x .@? "importTaskId")
<*> (x .@? "description")
<*> (pure (fromEnum s)))
instance ToHeaders ImportSnapshot where
toHeaders = const mempty
instance ToPath ImportSnapshot where
toPath = const "/"
instance ToQuery ImportSnapshot where
toQuery ImportSnapshot'{..}
= mconcat
["Action" =: ("ImportSnapshot" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"DiskContainer" =: _isDiskContainer,
"ClientToken" =: _isClientToken,
"RoleName" =: _isRoleName,
"Description" =: _isDescription,
"DryRun" =: _isDryRun, "ClientData" =: _isClientData]
-- | /See:/ 'importSnapshotResponse' smart constructor.
data ImportSnapshotResponse = ImportSnapshotResponse'
{ _isrsSnapshotTaskDetail :: !(Maybe SnapshotTaskDetail)
, _isrsImportTaskId :: !(Maybe Text)
, _isrsDescription :: !(Maybe Text)
, _isrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ImportSnapshotResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'isrsSnapshotTaskDetail'
--
-- * 'isrsImportTaskId'
--
-- * 'isrsDescription'
--
-- * 'isrsResponseStatus'
importSnapshotResponse
:: Int -- ^ 'isrsResponseStatus'
-> ImportSnapshotResponse
importSnapshotResponse pResponseStatus_ =
ImportSnapshotResponse'
{ _isrsSnapshotTaskDetail = Nothing
, _isrsImportTaskId = Nothing
, _isrsDescription = Nothing
, _isrsResponseStatus = pResponseStatus_
}
-- | Information about the import snapshot task.
isrsSnapshotTaskDetail :: Lens' ImportSnapshotResponse (Maybe SnapshotTaskDetail)
isrsSnapshotTaskDetail = lens _isrsSnapshotTaskDetail (\ s a -> s{_isrsSnapshotTaskDetail = a});
-- | The ID of the import snapshot task.
isrsImportTaskId :: Lens' ImportSnapshotResponse (Maybe Text)
isrsImportTaskId = lens _isrsImportTaskId (\ s a -> s{_isrsImportTaskId = a});
-- | A description of the import snapshot task.
isrsDescription :: Lens' ImportSnapshotResponse (Maybe Text)
isrsDescription = lens _isrsDescription (\ s a -> s{_isrsDescription = a});
-- | The response status code.
isrsResponseStatus :: Lens' ImportSnapshotResponse Int
isrsResponseStatus = lens _isrsResponseStatus (\ s a -> s{_isrsResponseStatus = a});
| olorin/amazonka | amazonka-ec2/gen/Network/AWS/EC2/ImportSnapshot.hs | mpl-2.0 | 6,545 | 0 | 14 | 1,395 | 1,102 | 652 | 450 | 127 | 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.IAM.DeleteGroup
-- 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)
--
-- Deletes the specified group. The group must not contain any users or
-- have any attached policies.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteGroup.html AWS API Reference> for DeleteGroup.
module Network.AWS.IAM.DeleteGroup
(
-- * Creating a Request
deleteGroup
, DeleteGroup
-- * Request Lenses
, dgGroupName
-- * Destructuring the Response
, deleteGroupResponse
, DeleteGroupResponse
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'deleteGroup' smart constructor.
newtype DeleteGroup = DeleteGroup'
{ _dgGroupName :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dgGroupName'
deleteGroup
:: Text -- ^ 'dgGroupName'
-> DeleteGroup
deleteGroup pGroupName_ =
DeleteGroup'
{ _dgGroupName = pGroupName_
}
-- | The name of the group to delete.
dgGroupName :: Lens' DeleteGroup Text
dgGroupName = lens _dgGroupName (\ s a -> s{_dgGroupName = a});
instance AWSRequest DeleteGroup where
type Rs DeleteGroup = DeleteGroupResponse
request = postQuery iAM
response = receiveNull DeleteGroupResponse'
instance ToHeaders DeleteGroup where
toHeaders = const mempty
instance ToPath DeleteGroup where
toPath = const "/"
instance ToQuery DeleteGroup where
toQuery DeleteGroup'{..}
= mconcat
["Action" =: ("DeleteGroup" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"GroupName" =: _dgGroupName]
-- | /See:/ 'deleteGroupResponse' smart constructor.
data DeleteGroupResponse =
DeleteGroupResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteGroupResponse' with the minimum fields required to make a request.
--
deleteGroupResponse
:: DeleteGroupResponse
deleteGroupResponse = DeleteGroupResponse'
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/DeleteGroup.hs | mpl-2.0 | 2,872 | 0 | 9 | 606 | 364 | 223 | 141 | 51 | 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="ur-PK">
<title>Code Dx | 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/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_ur_PK/helpset_ur_PK.hs | apache-2.0 | 969 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Clr.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:43
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qt.Glome.Clr where
type CFlt = Double
data Color = Color {r,g,b :: !CFlt} deriving Show
c_black = Color 0 0 0
c_white = Color 1 1 1
c_red = Color 1 0 0
c_green = Color 0 1 0
c_blue = Color 0 0 1
cadd :: Color -> Color -> Color
cadd (Color r1 g1 b1) (Color r2 g2 b2) =
Color (r1+r2) (g1+g2) (b1+b2)
cdiv :: Color -> CFlt -> Color
cdiv c1 div =
cscale c1 (1/div)
cscale :: Color -> CFlt -> Color
cscale (Color r g b) mul =
Color (r * mul)
(g * mul)
(b * mul)
cmul :: Color -> Color -> Color
cmul (Color r1 g1 b1) (Color r2 g2 b2) =
Color (r1*r2) (g1*g2) (b1*b2)
cavg :: Color -> Color -> Color
cavg c1 c2 = cscale (cadd c1 c2) 0.5
cscaleadd :: Color -> Color -> CFlt -> Color
cscaleadd (Color r1 g1 b1) (Color r2 g2 b2) mul =
Color (r1+(r2*mul)) (g1+(g2*mul)) (b1+(b2*mul))
cclamp :: Color -> Color
cclamp (Color r g b) =
Color (if r > 0.0 then r else 0.0)
(if g > 0.0 then g else 0.0)
(if b > 0.0 then b else 0.0)
| keera-studios/hsQt | extra-pkgs/Glome/Qt/Glome/Clr.hs | bsd-2-clause | 1,373 | 0 | 9 | 323 | 551 | 296 | 255 | 35 | 4 |
-- |
-- Module : Crypto.Random.Entropy.Unix
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : Good
--
{-# LANGUAGE ScopedTypeVariables #-}
module Crypto.Random.Entropy.Unix
( DevRandom
, DevURandom
) where
import Foreign.Ptr
import Data.Word (Word8)
import Crypto.Random.Entropy.Source
import Control.Exception as E
--import System.Posix.Types (Fd)
import System.IO
type H = Handle
type DeviceName = String
-- | Entropy device /dev/random on unix system
newtype DevRandom = DevRandom DeviceName
-- | Entropy device /dev/urandom on unix system
newtype DevURandom = DevURandom DeviceName
instance EntropySource DevRandom where
entropyOpen = fmap DevRandom `fmap` testOpen "/dev/random"
entropyGather (DevRandom name) ptr n =
withDev name $ \h -> gatherDevEntropyNonBlock h ptr n
entropyClose (DevRandom _) = return ()
instance EntropySource DevURandom where
entropyOpen = fmap DevURandom `fmap` testOpen "/dev/urandom"
entropyGather (DevURandom name) ptr n =
withDev name $ \h -> gatherDevEntropy h ptr n
entropyClose (DevURandom _) = return ()
testOpen :: DeviceName -> IO (Maybe DeviceName)
testOpen filepath = do
d <- openDev filepath
case d of
Nothing -> return Nothing
Just h -> closeDev h >> return (Just filepath)
openDev :: String -> IO (Maybe H)
openDev filepath = (Just `fmap` openAndNoBuffering) `E.catch` \(_ :: IOException) -> return Nothing
where openAndNoBuffering = do
h <- openBinaryFile filepath ReadMode
hSetBuffering h NoBuffering
return h
withDev :: String -> (H -> IO a) -> IO a
withDev filepath f = openDev filepath >>= \h ->
case h of
Nothing -> error ("device " ++ filepath ++ " cannot be grabbed")
Just fd -> f fd >>= \r -> (closeDev fd >> return r)
closeDev :: H -> IO ()
closeDev h = hClose h
gatherDevEntropy :: H -> Ptr Word8 -> Int -> IO Int
gatherDevEntropy h ptr sz =
(fromIntegral `fmap` hGetBufSome h ptr (fromIntegral sz))
`E.catch` \(_ :: IOException) -> return 0
gatherDevEntropyNonBlock :: H -> Ptr Word8 -> Int -> IO Int
gatherDevEntropyNonBlock h ptr sz =
(fromIntegral `fmap` hGetBufNonBlocking h ptr (fromIntegral sz))
`E.catch` \(_ :: IOException) -> return 0
| nomeata/cryptonite | Crypto/Random/Entropy/Unix.hs | bsd-3-clause | 2,355 | 0 | 14 | 518 | 710 | 371 | 339 | 50 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Update
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : lemmih@gmail.com
-- Stability : provisional
-- Portability : portable
--
--
-----------------------------------------------------------------------------
{-# LANGUAGE RecordWildCards #-}
module Distribution.Client.Update
( update
) where
import Distribution.Client.Types
( Repo(..), RemoteRepo(..), maybeRepoRemote )
import Distribution.Client.HttpUtils
( DownloadResult(..), HttpTransport(..) )
import Distribution.Client.FetchUtils
( downloadIndex )
import Distribution.Client.IndexUtils
( updateRepoIndexCache, Index(..) )
import Distribution.Client.JobControl
( newParallelJobControl, spawnJob, collectJob )
import Distribution.Simple.Utils
( writeFileAtomic, warn, notice )
import Distribution.Verbosity
( Verbosity )
import qualified Data.ByteString.Lazy as BS
import Distribution.Client.GZipUtils (maybeDecompress)
import System.FilePath (dropExtension)
import Data.Maybe (catMaybes)
-- | 'update' downloads the package list from all known servers
update :: HttpTransport -> Verbosity -> Bool -> [Repo] -> IO ()
update _ verbosity _ [] =
warn verbosity $ "No remote package servers have been specified. Usually "
++ "you would have one specified in the config file."
update transport verbosity ignoreExpiry repos = do
jobCtrl <- newParallelJobControl
let remoteRepos = catMaybes (map maybeRepoRemote repos)
case remoteRepos of
[] -> return ()
[remoteRepo] ->
notice verbosity $ "Downloading the latest package list from "
++ remoteRepoName remoteRepo
_ -> notice verbosity . unlines
$ "Downloading the latest package lists from: "
: map (("- " ++) . remoteRepoName) remoteRepos
mapM_ (spawnJob jobCtrl . updateRepo transport verbosity ignoreExpiry) repos
mapM_ (\_ -> collectJob jobCtrl) repos
updateRepo :: HttpTransport -> Verbosity -> Bool -> Repo -> IO ()
updateRepo transport verbosity _ignoreExpiry repo = case repo of
RepoLocal{..} -> return ()
RepoRemote{..} -> do
downloadResult <- downloadIndex transport verbosity repoRemote repoLocalDir
case downloadResult of
FileAlreadyInCache -> return ()
FileDownloaded indexPath -> do
writeFileAtomic (dropExtension indexPath) . maybeDecompress
=<< BS.readFile indexPath
updateRepoIndexCache verbosity (RepoIndex repo)
| randen/cabal | cabal-install/Distribution/Client/Update.hs | bsd-3-clause | 2,667 | 0 | 19 | 572 | 562 | 305 | 257 | 49 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-|
A WAI adapter to the HTML5 Server-Sent Events API.
-}
module Network.Wai.EventSource (
ServerEvent(..),
eventSourceAppChan,
eventSourceAppIO
) where
import Blaze.ByteString.Builder (Builder)
import Data.Function (fix)
import Control.Concurrent.Chan (Chan, dupChan, readChan)
import Control.Monad.IO.Class (liftIO)
import Network.HTTP.Types (status200)
import Network.Wai (Application, Response, responseStream)
import Network.Wai.EventSource.EventStream
-- | Make a new WAI EventSource application reading events from
-- the given channel.
eventSourceAppChan :: Chan ServerEvent -> Application
eventSourceAppChan chan req sendResponse = do
chan' <- liftIO $ dupChan chan
eventSourceAppIO (readChan chan') req sendResponse
-- | Make a new WAI EventSource application reading events from
-- the given IO action.
eventSourceAppIO :: IO ServerEvent -> Application
eventSourceAppIO src _ sendResponse =
sendResponse $ responseStream
status200
[("Content-Type", "text/event-stream")]
$ \sendChunk flush -> fix $ \loop -> do
se <- src
case eventToBuilder se of
Nothing -> return ()
Just b -> sendChunk b >> flush >> loop
| jberryman/wai | wai-extra/Network/Wai/EventSource.hs | mit | 1,330 | 0 | 16 | 324 | 276 | 154 | 122 | 26 | 2 |
{-# OPTIONS -XOverloadedStrings #-}
import Network.AMQP
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.Text as DT
import System.Environment (getArgs)
import Text.Printf
logsExchange = "direct_logs"
main :: IO ()
main = do
args <- getArgs
let body = bodyFor args
severity = severityFor args
conn <- openConnection "127.0.0.1" "/" "guest" "guest"
ch <- openChannel conn
declareExchange ch newExchange {exchangeName = logsExchange,
exchangeType = "direct",
exchangeDurable = False}
publishMsg ch logsExchange (DT.pack severity)
(newMsg {msgBody = (BL.pack body),
msgDeliveryMode = Just NonPersistent})
putStrLn $ printf " [x] Sent '%s'" (body)
closeConnection conn
bodyFor :: [String] -> String
bodyFor [] = "Hello, world!"
bodyFor xs = unwords $ tail xs
severityFor :: [String] -> String
severityFor [] = "info"
severityFor xs = head xs
| bwong199/rabbitmq-tutorials | haskell/emitLogDirect.hs | apache-2.0 | 1,048 | 0 | 13 | 309 | 280 | 147 | 133 | 28 | 1 |
import Data.List
main = print $ fst $ max' [ (n,d) | d <- [1..1000000], n <- [3*d `div` 7 .. d `div` 2], gcd d n == 1, toFloat (n,d) < toFloat (3,7) ]
toFloat :: (Int, Int) -> Float
toFloat (a,b) = (fromIntegral a) / (fromIntegral b)
max' :: [(Int, Int)] -> (Int, Int)
max' [x] = x
max' [(a,b),(c,d)] = if a*d > c*b then (a,b) else (c,d)
max' (x:xs:xss) = max' $ max' (x:[xs]) : xss
| lekto/haskell | Project-Euler-Solutions/problem0071.hs | mit | 387 | 0 | 12 | 84 | 291 | 164 | 127 | 8 | 2 |
{-# LANGUAGE TypeFamilies #-}
module SoOSiM.Components.ResourceManager.Interface where
import Data.HashMap.Strict (empty)
import SoOSiM
import SoOSiM.Components.Common
import SoOSiM.Components.ResourceDescriptor
import {-# SOURCE #-} SoOSiM.Components.ResourceManager.Behaviour (behaviour)
import SoOSiM.Components.ResourceManager.Types
data ResourceManager = ResourceManager
instance ComponentInterface ResourceManager where
type State ResourceManager = RM_State
type Receive ResourceManager = RM_Cmd
type Send ResourceManager = RM_Msg
initState = const (RM_State empty empty [] [] "all")
componentName = const "Resource Manager"
componentBehaviour = const behaviour
resourceManager :: String -> Sim ComponentId
resourceManager dist = do
componentLookup ResourceManager >>= \x -> case x of
Nothing -> createComponentNPS Nothing Nothing (Just iState) ResourceManager
Just cId -> return cId
where
iState = RM_State empty empty [] [] dist
addResource :: ComponentId -> ResourceId -> ResourceDescriptor -> Sim ()
addResource cId rId rd = notify ResourceManager cId (AddResource rId rd)
requestResources :: ComponentId -> AppId -> ResourceRequestList -> Sim [ResourceId]
requestResources cId appId rl = invoke ResourceManager cId (RequestResources appId rl) >>= (\(RM_Resources r) -> return r)
freeAllResources :: ComponentId -> AppId -> Sim ()
freeAllResources cId appId = notify ResourceManager cId (FreeAllResources appId)
freeResources :: ComponentId -> AppId -> [ResourceId] -> Sim ()
freeResources cId appId rIds = notify ResourceManager cId (FreeResources appId rIds)
getResourceDescription :: ComponentId -> ResourceId -> Sim (Maybe ResourceDescriptor)
getResourceDescription cId rId = invoke ResourceManager cId (GetResourceDescription rId) >>= (\(RM_Descriptor r) -> return r)
| christiaanb/SoOSiM-components | src/SoOSiM/Components/ResourceManager/Interface.hs | mit | 1,878 | 0 | 14 | 310 | 512 | 266 | 246 | 32 | 2 |
module CFDI.Types.Locality where
import CFDI.Types.Type
import Control.Error.Safe (justErr)
import Text.Read (readMaybe)
newtype Locality = Locality Int deriving (Eq, Read, Show)
instance Type Locality where
parseExpr c = justErr NotInCatalog maybeLocality
where
maybeLocality = Locality <$> (readMaybe c >>= isValid)
isValid x
| x > 0 && x < 63 = Just x
| x > 65 && x < 70 = Just x
| otherwise = Nothing
render (Locality x) = replicate (2 - length xStr) '0' ++ xStr
where
xStr = show x
| yusent/cfdis | src/CFDI/Types/Locality.hs | mit | 555 | 0 | 13 | 152 | 204 | 105 | 99 | 14 | 0 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
-- | Common types for the FP15 compiler.
module FP15.Compiler.Types (
ImportedNames(..)
, module FP15.Compiler.Types
, module FP15.Compiler.Lookup
, module FP15.Compiler.Modules
) where
import GHC.Generics
import Control.DeepSeq
import FP15.Types
import FP15.Compiler.Lookup
import FP15.Compiler.ImportedNames as IN
import FP15.Compiler.Modules
-- * Type Synonyms
-- | The function signature of 'FP15.Parsing.Parser.parse'.
type Parser = ModuleSource -> Either String ModuleAST
-- * Names
-- | The 'UnName' type represents an unresolved name.
data UnName f
-- | A name relative to an environment.
= RN (RName f)
-- | A name that requies the syntax provider of the enviornment to resolve.
| SN String
-- ^ An name meant to be absolute regardless of context.
| AN (AName f)
deriving (Eq, Ord, Show, Read, Generic)
instance NFData f => NFData (UnName f) where
-- | The 'EnvName' type represents a name relative to an environment @e@.
data EnvName f e
-- | A name relative to an environment.
= REN e (RName f)
-- ^ An absolute name.
| AEN e (AName f)
deriving (Eq, Ord, Show, Read, Generic, Functor)
-- TODO the env doesn't need to lookup infix operators
instance (NFData e, NFData f) => NFData (EnvName e f) where
type LocUnName f = Located (UnName f)
-- * Expression Types
-- | A desugared FP15 expression.
type BExpr = XExpr (LocUnName F) (LocUnName Fl) ()
-- * Reduction
-- | Variables in the reduction process that do not change.
data StaticState
= SS { ssCMS :: CompiledModuleSet
-- ^ The modules that are already compiled
, ssMN :: ModuleName
-- ^ The name of the module being compiled
, ssMI :: ModuleInterface
-- ^ The module interface of the module being compiled
, ssSM :: Maybe SourceMapping
-- ^ The source mappings of names in this module
, ssIN :: ImportedNames
-- ^ The names imported by this module
}
deriving (Eq, Ord, Show, Read)
instance LookupF StaticState where
lookupF SS { ssMN, ssIN, ssMI } = lookupF (Fallback ssIN (MIContext ssMN ssMI))
instance LookupFl StaticState where
lookupFl SS { ssMN, ssIN, ssMI } = lookupFl (Fallback ssIN (MIContext ssMN ssMI))
instance LookupOp StaticState where
lookupOp SS { ssMN, ssIN, ssMI } = lookupOp (Fallback ssIN (MIContext ssMN ssMI))
instance Lookup StaticState where
-- | A module that is being reduced.
newtype ReducingModule
= Reducing (ModuleBody Id ExprState FunctionalDefinition FFixity FlFixity)
deriving (Eq, Ord, Show, Read)
-- | The state of the reducing module.
data ReducingTag
= Normal -- ^ The module is being reduced and is not blocked.
| Blocked [ModuleName] -- ^ Waiting for modules to be compiled.
| Finished -- ^ Module has finished reducing.
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ReducingTag where rnf x = seq x ()
data ReducingModuleState
= ReducingModuleState { rmsSS :: StaticState
, rmsTag :: ReducingTag
, rmsRM :: ReducingModule }
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ReducingModuleState where rnf x = seq x ()
-- | An 'ExprState' represents an expression in various stages of the reduction
-- stage.
--
-- TODO error states.
data ExprState = Unresolved ExprAST
| Unreduced BExpr
| Reduced Expr
deriving (Eq, Ord, Show, Read, Generic)
-- * Compiled
-- | A 'CompiledModule' represents a module with functions in compiled state.
newtype CompiledModule
= Compiled (ModuleBody Id Expr FunctionalDefinition FFixity FlFixity)
deriving (Eq, Ord, Show, Read, Generic)
instance NFData CompiledModule where rnf x = seq x ()
data CompiledModuleItem
= CompiledModuleItem { cmiCM :: CompiledModule
, cmiMI :: ModuleInterface
, cmiSM :: Maybe SourceMapping }
deriving (Eq, Ord, Show, Read, Generic)
instance NFData CompiledModuleItem where rnf x = seq x ()
-- | A 'CompiledModuleSet' represents a set of compiled modules with module
-- interface and source mapping (optional) as additional information.
newtype CompiledModuleSet
= CompiledModuleSet (Map ModuleName CompiledModuleItem)
deriving (Eq, Ord, Show, Read, Generic)
instance NFData CompiledModuleSet where rnf x = seq x ()
getCompiledModule
:: CompiledModule -> ModuleBody Id Expr FunctionalDefinition FFixity FlFixity
getReducingModule
:: ReducingModule
-> ModuleBody Id ExprState FunctionalDefinition FFixity FlFixity
getCompiledModuleSet :: CompiledModuleSet -> Map ModuleName CompiledModuleItem
getReducingModule (Reducing r) = r
getCompiledModule (Compiled c) = c
getCompiledModuleSet (CompiledModuleSet c) = c
| Ming-Tang/FP15 | src/FP15/Compiler/Types.hs | mit | 4,905 | 0 | 10 | 1,069 | 1,067 | 594 | 473 | -1 | -1 |
n = a `div` length xs
where
a = 10
xs = [1, 2, 3, 4, 5]
last xs = drop (length xs - 1) xs
| jugalps/edX | FP101x/week1/ex1.hs | mit | 105 | 0 | 8 | 41 | 65 | 36 | 29 | 4 | 1 |
replaceWithP :: b -> Char
replaceWithP = const 'p'
lms :: [Maybe [Char]]
lms = [Just "Ave", Nothing, Just "woohoo"]
replaceWithP' :: [Maybe [Char]] -> Char
replaceWithP' = replaceWithP
liftedReplace :: Functor f => f a -> f Char
liftedReplace = fmap replaceWithP
liftedReplace' :: [Maybe [Char]] -> [Char]
liftedReplace' = liftedReplace
twiceLifted :: (Functor f1, Functor f) => f (f1 a) -> f (f1 Char)
twiceLifted = (fmap . fmap) replaceWithP
twiceLifted' :: [Maybe [Char]] -> [Maybe Char]
twiceLifted' = twiceLifted
main :: IO ()
main = do
putStr "replaceWithP' lms: "
print (replaceWithP' lms)
putStr "liftedReplace lms: "
print (liftedReplace lms)
putStr "liftedReplace' lms: "
print (liftedReplace' lms)
putStr "twiceLifted lms: "
print (twiceLifted lms)
| JustinUnger/haskell-book | ch16/functor-ex.hs | mit | 813 | 0 | 9 | 170 | 304 | 151 | 153 | 24 | 1 |
{-# OPTIONS_GHC -F -pgmF htfpp #-}
import Test.Framework
import {-@ HTF_TESTS @-} TestLabyrinthServer
import {-@ HTF_TESTS @-} TestLabyrinthServer.JSON
main = htfMain htf_importedTests
| koterpillar/labyrinth-server | testsuite/TestMain.hs | mit | 188 | 0 | 5 | 25 | 25 | 15 | 10 | 5 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-- | provide backends for `katip`
module Pos.Util.Log.Scribes
( mkStdoutScribe
, mkStderrScribe
, mkDevNullScribe
, mkTextFileScribe
, mkJsonFileScribe
) where
import Universum
import Control.AutoUpdate (UpdateSettings (..), defaultUpdateSettings,
mkAutoUpdate)
import Control.Concurrent.MVar (modifyMVar_)
import Control.Exception.Safe (catchIO)
import Data.Aeson.Text (encodeToLazyText)
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import Data.Text.Lazy.Builder
import qualified Data.Text.Lazy.IO as TIO
import Data.Time (diffUTCTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import Katip.Core
import Katip.Scribes.Handle (brackets)
import qualified Pos.Util.Log.Internal as Internal
import Pos.Util.Log.LoggerConfig (NamedSeverity,
RotationParameters (..))
import Pos.Util.Log.LoggerName (LoggerName)
import Pos.Util.Log.Rotator (cleanupRotator, evalRotator,
initializeRotator)
import qualified Pos.Util.Log.Severity as Log (Severity (..))
import System.Directory (createDirectoryIfMissing)
import System.IO (BufferMode (LineBuffering), Handle,
IOMode (WriteMode), hClose, hSetBuffering, stderr, stdout)
-- | create a katip scribe for logging to a file in JSON representation
mkJsonFileScribe :: RotationParameters -> NamedSeverity -> Internal.FileDescription -> Log.Severity -> Verbosity -> IO Scribe
mkJsonFileScribe rot sevfilter fdesc s v = do
mkFileScribe rot sevfilter fdesc formatter False s v
where
formatter :: (LogItem a) => Handle -> Bool -> Verbosity -> Item a -> IO Int
formatter hdl _ v' item = do
let tmsg = encodeToLazyText $ itemJson v' item
TIO.hPutStrLn hdl tmsg
return $ length tmsg
-- | create a katip scribe for logging to a file in textual representation
mkTextFileScribe :: RotationParameters -> NamedSeverity -> Internal.FileDescription -> Bool -> Log.Severity -> Verbosity -> IO Scribe
mkTextFileScribe rot sevfilter fdesc colorize s v = do
mkFileScribe rot sevfilter fdesc formatter colorize s v
where
formatter :: Handle -> Bool -> Verbosity -> Item a -> IO Int
formatter hdl colorize' v' item = do
let tmsg = toLazyText $ formatItem colorize' v' item
TIO.hPutStrLn hdl tmsg
return $ length tmsg
-- | create a katip scribe for logging to a file
-- and handle file rotation within the katip-invoked logging function
mkFileScribe
:: RotationParameters
-> NamedSeverity
-> Internal.FileDescription
-> (forall a . LogItem a => Handle -> Bool -> Verbosity -> Item a -> IO Int) -- format and output function, returns written bytes
-> Bool -- whether the output is colourized
-> Log.Severity -> Verbosity
-> IO Scribe
mkFileScribe rot sevfilter fdesc formatter colorize s v = do
let prefixDir = Internal.prefixpath fdesc
(createDirectoryIfMissing True prefixDir)
`catchIO` (Internal.prtoutException ("cannot log prefix directory: " ++ prefixDir))
trp <- initializeRotator rot fdesc
scribestate <- newMVar trp -- triple of (handle), (bytes remaining), (rotate time)
-- sporadically remove old log files - every 10 seconds
cleanup <- mkAutoUpdate defaultUpdateSettings { updateAction = cleanupRotator rot fdesc, updateFreq = 10000000 }
let finalizer :: IO ()
finalizer = do
modifyMVar_ scribestate $ \(hdl, b, t) -> do
hClose hdl
return (hdl, b, t)
let logger :: forall a. LogItem a => Item a -> IO ()
logger item =
when (checkItem s sevfilter item) $
modifyMVar_ scribestate $ \(hdl, bytes, rottime) -> do
byteswritten <- formatter hdl colorize v item
-- remove old files
cleanup
-- detect log file rotation
let bytes' = bytes - (toInteger $ byteswritten)
let tdiff' = round $ diffUTCTime rottime (_itemTime item)
if bytes' < 0 || tdiff' < (0 :: Integer)
then do -- log file rotation
hClose hdl
(hdl2, bytes2, rottime2) <- evalRotator rot fdesc
return (hdl2, bytes2, rottime2)
else
return (hdl, bytes', rottime)
return $ Scribe logger finalizer
-- | create a katip scribe for logging to a file
mkFileScribeH :: Handle -> Bool -> NamedSeverity -> Log.Severity -> Verbosity -> IO Scribe
mkFileScribeH h colorize sevfilter s v = do
hSetBuffering h LineBuffering
locklocal <- newMVar ()
let logger :: Item a -> IO ()
logger item = when (checkItem s sevfilter item) $
bracket_ (takeMVar locklocal) (putMVar locklocal ()) $
TIO.hPutStrLn h $! toLazyText $ formatItem colorize v item
pure $ Scribe logger (hClose h)
-- | create a katip scribe for logging to the console
mkStdoutScribe :: NamedSeverity -> Log.Severity -> Verbosity -> IO Scribe
mkStdoutScribe = mkFileScribeH stdout True
-- | create a katip scribe for logging to stderr
mkStderrScribe :: NamedSeverity -> Log.Severity -> Verbosity -> IO Scribe
mkStderrScribe = mkFileScribeH stderr True
-- | @Scribe@ that outputs to '/dev/null' without locking
mkDevNullScribe :: Internal.LoggingHandler -> NamedSeverity -> Log.Severity -> Verbosity -> IO Scribe
mkDevNullScribe lh sevfilter s v = do
h <- openFile "/dev/null" WriteMode
let colorize = False
hSetBuffering h LineBuffering
let logger :: Item a -> IO ()
logger item = when (checkItem s sevfilter item) $
Internal.incrementLinesLogged lh
>> (TIO.hPutStrLn h $! toLazyText $ formatItem colorize v item)
pure $ Scribe logger (hClose h)
-- | check if item passes severity filter
checkItem :: Log.Severity -> NamedSeverity -> Item a -> Bool
checkItem s sevfilter item@Item{..} =
permitItem (Internal.sev2klog severity) item
where
severity :: Log.Severity
severity = fromMaybe s $ HM.lookup namedcontext sevfilter
namedcontext :: LoggerName
namedcontext = mconcat $ intercalateNs _itemNamespace
-- | format a @Item@
formatItem :: Bool -> Verbosity -> Item a -> Builder
formatItem withColor _verb Item{..} =
fromText header <>
fromText " " <>
brackets (fromText timestamp) <>
fromText " " <>
unLogStr _itemMessage
where
header = colorBySeverity _itemSeverity $
"[" <> mconcat namedcontext <> ":" <> severity <> ":" <> threadid <> "]"
namedcontext = intercalateNs _itemNamespace
severity = renderSeverity _itemSeverity
threadid = getThreadIdText _itemThread
timestamp = T.pack $ formatTime defaultTimeLocale tsformat _itemTime
tsformat :: String
tsformat = "%F %T%2Q %Z"
colorBySeverity s m = case s of
EmergencyS -> red m
AlertS -> red m
CriticalS -> red m
ErrorS -> red m
NoticeS -> magenta m
WarningS -> yellow m
InfoS -> blue m
_ -> m
red = colorize "31"
yellow = colorize "33"
magenta = colorize "35"
blue = colorize "34"
colorize c m
| withColor = "\ESC["<> c <> "m" <> m <> "\ESC[0m"
| otherwise = m
| input-output-hk/pos-haskell-prototype | util/src/Pos/Util/Log/Scribes.hs | mit | 7,555 | 0 | 20 | 2,072 | 1,936 | 996 | 940 | 144 | 8 |
module BlogToolsSpec where
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
import Web.Blog.Tools
spec :: Spec
spec = do
describe "hoge" $ do
it "return hoge" $ do
"hoge" `shouldBe` "hoge"
| suzuki-shin/blogtools | test/BlogToolsSpec.hs | mit | 231 | 0 | 13 | 44 | 69 | 38 | 31 | 10 | 1 |
module Main where
import LLVM.Context
import LLVM.Pretty (ppllvm)
import qualified LLVM.Module as M
import Control.Monad (filterM)
import Control.Monad.Except
import Data.Functor
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import System.IO
import System.Exit
import System.Directory
import System.FilePath
import System.Environment
import Test.Tasty
import Test.Tasty.HUnit
-------------------------------------------------------------------------------
-- Harness
-------------------------------------------------------------------------------
llvmFile :: FilePath -> IO Bool
llvmFile fname = do
str <- readFile fname
withContext $ \ctx -> do
res <- M.withModuleFromLLVMAssembly ctx str $ \mod -> do
ast <- M.moduleAST mod
let str = ppllvm ast
T.writeFile ("tests/output" </> takeFileName fname) str
trip <- M.withModuleFromLLVMAssembly ctx (T.unpack str) (const $ return ())
{-T.putStrLn str-}
pure ()
return True
makeTest :: FilePath -> TestTree
makeTest fname = testCase fname $ assertBool "" =<< llvmFile fname
testPath :: FilePath
testPath = "tests/input/"
suite :: IO TestTree
suite = do
dirFiles <- listDirectory testPath
createDirectoryIfMissing True "tests/output"
let testFiles = fmap (\x -> testPath </> x) dirFiles
pure $ testGroup "Test Suite" [
testGroup "Roundtrip Tests" $ fmap makeTest testFiles
]
main :: IO ()
main = defaultMain =<< suite
| llvm-hs/llvm-hs-pretty | tests/Main.hs | mit | 1,467 | 0 | 21 | 251 | 413 | 215 | 198 | 40 | 1 |
{-# LANGUAGE EmptyDataDecls #-}
module Grid (
Grid(..),
InUse,
Won,
Tied,
GridIndex,
Either3(..),
emptyGrid,
showGrid,
printGrid,
getSquareAt,
isSquareX,
isSquareEmpty,
isValidMove,
setSquare,
isGridFull,
isGridWon,
finalizeGridIfGameFinished
) where
import Prelude hiding (Either(..))
import Data.List (intercalate, intersperse)
import Square
import Player
type Grid a = [[Square]]
data InUse
data Won
data Tied
type GridIndex = (Int, Int)
data Either3 a b c = Left a | Middle b | Right c
emptyGrid :: Grid a
emptyGrid = replicate 3 (replicate 3 Empty)
showLine :: SquareRendering -> [Square] -> String
showLine rendering = intercalate "\9474" . map (show' rendering)
-- \9474 is a vertical bar
emptyLine :: String
emptyLine = "\9472\9532\9472\9532\9472"
-- \9472 is horizontal bar
-- \9532 is something like + but full
-- so as a result this looks like something like "-+-+-"
showGrid :: SquareRendering -> Grid a -> String
showGrid rendering = unlines . intersperse emptyLine . map (showLine rendering)
printGrid :: SquareRendering -> Grid a -> IO ()
printGrid rendering = putStrLn . showGrid rendering
isIndexValid :: GridIndex -> Bool
isIndexValid (i1, i2) = (0 <= i1 && i1 <= 2) && (0 <= i2 && i2 <= 2)
getSquareAt :: Grid a -> GridIndex -> Square
grid `getSquareAt` i@(index1, index2)
| isIndexValid i = grid !! (2 - index2) !! index1
| otherwise = error "Index out of range."
isSquareX :: Grid a -> GridIndex -> Square -> Bool
isSquareX grid gIndex value = grid `getSquareAt` gIndex == value
isSquareEmpty :: Grid a -> GridIndex -> Bool
isSquareEmpty grid gIndex = isSquareX grid gIndex Empty
isValidMove :: Grid InUse -> GridIndex -> Bool
isValidMove grid index = isIndexValid index && isSquareEmpty grid index
setSquare :: Grid InUse -> GridIndex -> Square -> Grid InUse
setSquare grid gIndex square
| square == Empty = error "Can't empty a square."
| not . isIndexValid $ gIndex = error "Index out of range."
| not . isSquareEmpty grid $ gIndex = error "Trying to access already used square."
| otherwise = changeSquare grid gIndex square
changeSquare :: Grid InUse -> GridIndex -> Square -> Grid InUse
changeSquare grid (i1, i2) sq
= map (\(x, i) -> if i /= index then x else changeSquare' x i1 sq) (zip grid [0..])
where index = 2 - i2
changeSquare' :: [Square] -> Int -> Square -> [Square]
changeSquare' squares index sq
= map (\(x, i) -> if i /= index then x else sq) (zip squares [0..])
isGridWon :: Grid InUse -> Bool
isGridWon grid
= any (\x -> all (== P1mark) x || all (== P2mark) x) squaresInAllDirs
where squaresInAllDirs = map (map (getSquareAt grid)) allDirections
allDirections = [
-- Rows:
[(0,0), (1,0), (2,0)],
[(0,1), (1,1), (2,1)],
[(0,2), (1,2), (2,2)],
-- Columns:
[(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)],
-- Diagonals:
[(0,0), (1,1), (2,2)],
[(0,2), (1,1), (2,0)]
]
isGridFull :: Grid InUse -> Bool
isGridFull = all (notElem Empty)
finalizeGridIfGameFinished :: Grid InUse -> Either3 (Grid InUse) (Grid Tied) (Grid Won)
finalizeGridIfGameFinished grid
| isGridWon grid = Right grid
| isGridFull grid = Middle grid
| otherwise = Left grid
| Purlox/Foxe-Wolf-Pone | src/Grid.hs | mit | 3,452 | 38 | 11 | 864 | 1,318 | 729 | 589 | -1 | -1 |
module Main where
import Lib
main :: IO ()
main = someFunc
cup f1Oz = \message -> message f1Oz
coffeeCup = cup 12
getOz aCup = aCup (\f1Oz -> f1Oz)
drink aCup ozDrank = if ozDiff >= 0 then cup ozDiff else cup 0
where
flOz = getOz aCup
ozDiff = flOz - ozDrank
isEmpty aCup = getOz aCup == 0
afterManySips = foldl drink coffeeCup [1, 1, 1, 1, 1]
--
robot (name, attack, hp) = \message -> message (name, attack, hp)
killerRobot = robot ("Kill3r", 25, 200)
name (n, _, _) = n
attack (_, a, _) = a
hp (_, _, hp) = hp
-- `object method`
getName aRobot = aRobot name
getAttack aRobot = aRobot attack
getHP aRobot = aRobot hp
-- `method object`
setName aRobot newName = aRobot (\(n, a, h) -> robot (newName, a, h))
setAttack aRobot newAttack = aRobot (\(n, a, h) -> robot (n, newAttack, h))
setHP aRobot newHP = aRobot (\(n, a, h) -> robot (n, a, newHP))
-- experiment to change to `object method`
setName2 (_, a, h) newName = robot (newName, a, h)
nicerRobot = setName killerRobot "kitty"
gentlerRobot = setAttack killerRobot 5
softerRobot = setHP killerRobot 50
printRobot aRobot = aRobot (\(n, a, h) -> n ++ " attack:" ++ (show a) ++ " hp:" ++ (show h))
printRobot2 (n, a, h) = mconcat [n, " attack:", show a, " hp:", show h]
damage aRobot attackDamage = aRobot (\(n, a, h) -> robot (n, a, h - attackDamage))
fight aRobot defender = damage defender attack where attack = if getHP aRobot > 10 then getAttack aRobot else 0
gentleGiant = robot ("Mr. Friendly", 10, 300)
gentleGiantRound1 = fight killerRobot gentleGiant
killerRobotRound1 = fight gentleGiant killerRobot
gentleGiantRound2 = fight killerRobotRound1 gentleGiantRound1
killerRobotRound2 = fight gentleGiantRound1 killerRobotRound1
gentleGiantRound3 = fight killerRobotRound2 gentleGiantRound2
killerRobotRound3 = fight gentleGiantRound2 killerRobotRound2
| NickAger/LearningHaskell | GetProgrammingWithHaskell/10-FunctionalOOWithRobots/FunctionalOOWithRobots/app/Main.hs | mit | 1,848 | 0 | 12 | 345 | 740 | 405 | 335 | 38 | 2 |
module Main (main) where
import qualified Gennoise
main :: IO ()
main = Gennoise.main
| danplubell/color-noise | executable/Main.hs | mit | 88 | 0 | 6 | 16 | 30 | 18 | 12 | 4 | 1 |
module Database.Kayvee.Common where
import Prelude hiding (catch)
import Control.Applicative((<$>))
import Control.Exception
import Data.Hash.MD5
import Data.Word
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits
import Data.List (genericLength)
import Data.ByteString.Char8 (pack)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Internal as BS (c2w, w2c)
import System.Directory
import System.IO
import System.IO.Error hiding (catch)
import System.Posix.Types
import System.Posix.Files
import Database.Kayvee.Log
type Hash = (Word32, Word32, Word32, Word32)
data Error = Error String
type Pointer = Word64
hashSize :: Word64
hashSize = 16
ptrSize :: Word64
ptrSize = 8
splitEvery :: Int -> [a] -> [[a]]
splitEvery i xs =
helper 0 xs [] []
where helper k (y:ys) acc res =
let newAcc = y : acc in
if k == i - 1
then helper 0 ys [] (newAcc:res)
else helper (k + 1) ys (y : acc) res
helper _ [] _ res = res
entrySize :: Int
entrySize = 24 --bytes
tup4 :: (Maybe a, Maybe b, Maybe c, Maybe d) -> Maybe (a, b, c, d)
tup4 (Just w, Just x, Just y, Just z) = Just (w, x, y, z)
tup4 _ = Nothing
toWord8List :: String -> [Word8]
toWord8List s = BS.c2w <$> s
readWord :: Get a -> Get (Maybe a)
readWord get' = do
empty <- isEmpty
if empty
then return Nothing
else do word <- get'
return $ Just word
readAt :: FilePath
-> Pointer --position
-> Word64 --size of data to read
-> IO BL.ByteString
readAt fp pos size = do
logAll $ "Reading " ++ show size ++ " bytes starting from " ++ show pos
h <- openBinaryFile fp ReadMode
hSeek h AbsoluteSeek (toInteger pos)
chars <- getChars h (toInteger size)
hClose h
logAll $ "Read data " ++ show chars
return $ BL.pack (toWord8List chars)
getChars :: Handle -> Integer -> IO [Char]
getChars h i = do
helper i
where helper i = if i == 0
then return []
else do c <- hGetChar h
rest <- helper (i - 1)
return $ c : rest
createIfNotExists :: FilePath -> IO ()
createIfNotExists fp = do
exists <- doesFileExist fp
if not exists || True
then writeFile fp ""
else return ()
toString :: BL.ByteString -> String
toString x = BS.w2c <$> BL.unpack x
getSize :: FilePath -> IO FileOffset
getSize path =
fileSize <$> getFileStatus path
toPointer :: Integer -> Pointer
toPointer = fromInteger
fromPointer :: Pointer -> Integer
fromPointer = toInteger
makeHash :: String -> Hash
makeHash str =
let (ABCD wds) = md5 (Str str) in
wds
hashPut :: String -> Pointer -> Put
hashPut s p = do
let (h0, h1, h2, h3) = makeHash s
putWord32be h0
putWord32be h1
putWord32be h2
putWord32be h3
putWord64be p
valuePut :: String -> String -> Put
valuePut s v = do
let ss = toPointer $ (genericLength s)
uLogAll ("Putting value: " ++ show ss) $ putWord64be ss
let ps = pack s
uLogAll ("Putting value: " ++ show ps) $ putByteString ps
let sv = toPointer $ (genericLength v)
uLogAll ("Putting value: " ++ show sv) $ putWord64be sv
let pv = pack v
uLogAll ("Putting value: " ++ show pv) $ putByteString pv
listToTuple4 :: Show a => [a] -> (a, a, a, a)
listToTuple4 (w:x:y:z:[]) = (w, x, y, z)
listToTuple4 xs = error $ "Malformed list " ++ show xs
bsToHash :: BL.ByteString -> Hash
bsToHash bs =
let bytes = (fromInteger . toInteger) <$> BL.unpack bs in
let words' = splitEvery 4 bytes in
listToTuple4 $ bytesToWord32 <$> words'
where bytesToWord32 :: [Word32] -> Word32
bytesToWord32 (b0:b1:b2:b3:[]) =
shiftL b0 24
.|. shiftL b1 16
.|. shiftL b2 8
.|. shiftL b3 0
bytesToWord32 xs = error $ "Malformed bytes " ++ show xs
bsToSize :: BL.ByteString -> Word64
bsToSize bs =
case (fromInteger . toInteger) <$> BL.unpack bs of
(b0:b1:b2:b3:b4:b5:b6:b7:[]) ->
shiftL b0 56
.|. shiftL b1 48
.|. shiftL b2 40
.|. shiftL b3 32
.|. shiftL b4 24
.|. shiftL b5 16
.|. shiftL b6 8
.|. shiftL b7 0
xs -> error $ "malformed size " ++ show bs ++ " of length " ++ show (length xs)
removeIfExists :: FilePath -> IO ()
removeIfExists fileName = removeFile fileName `catch` handleExists
where handleExists e
| isDoesNotExistError e = return ()
| otherwise = throwIO e
moveFile :: FilePath -> FilePath -> IO ()
moveFile x y = renameFile x y
| deweyvm/kayvee | src/Database/Kayvee/Common.hs | mit | 4,752 | 0 | 17 | 1,386 | 1,801 | 913 | 888 | 142 | 3 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.PerformanceObserverEntryList
(getEntries, getEntries_, getEntriesByType, getEntriesByType_,
getEntriesByName, getEntriesByName_,
PerformanceObserverEntryList(..),
gTypePerformanceObserverEntryList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList.getEntries Mozilla PerformanceObserverEntryList.getEntries documentation>
getEntries ::
(MonadDOM m) =>
PerformanceObserverEntryList -> m PerformanceEntryList
getEntries self
= liftDOM ((self ^. jsf "getEntries" ()) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList.getEntries Mozilla PerformanceObserverEntryList.getEntries documentation>
getEntries_ :: (MonadDOM m) => PerformanceObserverEntryList -> m ()
getEntries_ self = liftDOM (void (self ^. jsf "getEntries" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList.getEntriesByType Mozilla PerformanceObserverEntryList.getEntriesByType documentation>
getEntriesByType ::
(MonadDOM m, ToJSString type') =>
PerformanceObserverEntryList -> type' -> m PerformanceEntryList
getEntriesByType self type'
= liftDOM
((self ^. jsf "getEntriesByType" [toJSVal type']) >>=
fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList.getEntriesByType Mozilla PerformanceObserverEntryList.getEntriesByType documentation>
getEntriesByType_ ::
(MonadDOM m, ToJSString type') =>
PerformanceObserverEntryList -> type' -> m ()
getEntriesByType_ self type'
= liftDOM (void (self ^. jsf "getEntriesByType" [toJSVal type']))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList.getEntriesByName Mozilla PerformanceObserverEntryList.getEntriesByName documentation>
getEntriesByName ::
(MonadDOM m, ToJSString name, ToJSString type') =>
PerformanceObserverEntryList ->
name -> Maybe type' -> m PerformanceEntryList
getEntriesByName self name type'
= liftDOM
((self ^. jsf "getEntriesByName" [toJSVal name, toJSVal type']) >>=
fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList.getEntriesByName Mozilla PerformanceObserverEntryList.getEntriesByName documentation>
getEntriesByName_ ::
(MonadDOM m, ToJSString name, ToJSString type') =>
PerformanceObserverEntryList -> name -> Maybe type' -> m ()
getEntriesByName_ self name type'
= liftDOM
(void
(self ^. jsf "getEntriesByName" [toJSVal name, toJSVal type']))
| ghcjs/jsaddle-dom | src/JSDOM/Generated/PerformanceObserverEntryList.hs | mit | 3,685 | 0 | 12 | 598 | 743 | 428 | 315 | 55 | 1 |
-- Copyright (c) 2016-present, SoundCloud Ltd.
-- All rights reserved.
--
-- This source code is distributed under the terms of a MIT license,
-- found in the LICENSE file.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Kubernetes.Model.V1.SecretKeySelector
( SecretKeySelector (..)
, name
, key
, mkSecretKeySelector
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson.TH (defaultOptions, deriveJSON,
fieldLabelModifier)
import Data.Text (Text)
import GHC.Generics (Generic)
import Prelude hiding (drop, error, max, min)
import qualified Prelude as P
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Instances ()
-- | SecretKeySelector selects a key of a Secret.
data SecretKeySelector = SecretKeySelector
{ _name :: !(Maybe Text)
, _key :: !(Text)
} deriving (Show, Eq, Generic)
makeLenses ''SecretKeySelector
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''SecretKeySelector)
instance Arbitrary SecretKeySelector where
arbitrary = SecretKeySelector <$> arbitrary <*> arbitrary
-- | Use this method to build a SecretKeySelector
mkSecretKeySelector :: Text -> SecretKeySelector
mkSecretKeySelector xkeyx = SecretKeySelector Nothing xkeyx
| soundcloud/haskell-kubernetes | lib/Kubernetes/Model/V1/SecretKeySelector.hs | mit | 1,574 | 0 | 14 | 444 | 277 | 166 | 111 | 31 | 1 |
module Feature.AuthSpec where
import Network.Wai (Application)
import Network.HTTP.Types
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
import Text.Heredoc
import PostgREST.Types (PgVersion, pgVersion112)
import Protolude hiding (get)
import SpecHelper
spec :: PgVersion -> SpecWith Application
spec actualPgVersion = describe "authorization" $ do
let single = ("Accept","application/vnd.pgrst.object+json")
it "denies access to tables that anonymous does not own" $
get "/authors_only" `shouldRespondWith` (
if actualPgVersion >= pgVersion112 then
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for table authors_only"} |]
else
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for relation authors_only"} |]
)
{ matchStatus = 401
, matchHeaders = ["WWW-Authenticate" <:> "Bearer"]
}
it "denies access to tables that postgrest_test_author does not own" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIn0.Xod-F15qsGL0WhdOCr2j3DdKuTw9QJERVgoFD3vGaWA" in
request methodGet "/private_table" [auth] ""
`shouldRespondWith` (
if actualPgVersion >= pgVersion112 then
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for table private_table"} |]
else
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for relation private_table"} |]
)
{ matchStatus = 403
, matchHeaders = []
}
it "denies execution on functions that anonymous does not own" $
post "/rpc/privileged_hello" [json|{"name": "anonymous"}|] `shouldRespondWith` 401
it "allows execution on a function that postgrest_test_author owns" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIn0.Xod-F15qsGL0WhdOCr2j3DdKuTw9QJERVgoFD3vGaWA" in
request methodPost "/rpc/privileged_hello" [auth] [json|{"name": "jdoe"}|]
`shouldRespondWith` [json|"Privileged hello to jdoe"|]
{ matchStatus = 200
, matchHeaders = [matchContentTypeJson]
}
it "returns jwt functions as jwt tokens" $
request methodPost "/rpc/login" [single]
[json| { "id": "jdoe", "pass": "1234" } |]
`shouldRespondWith` [json| {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xuYW1lIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.KO-0PGp_rU-utcDBP6qwdd-Th2Fk-ICVt01I7QtTDWs"} |]
{ matchStatus = 200
, matchHeaders = [matchContentTypeSingular]
}
it "sql functions can encode custom and standard claims" $
request methodPost "/rpc/jwt_test" [single] "{}"
`shouldRespondWith` [json| {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqb2UiLCJzdWIiOiJmdW4iLCJhdWQiOiJldmVyeW9uZSIsImV4cCI6MTMwMDgxOTM4MCwibmJmIjoxMzAwODE5MzgwLCJpYXQiOjEzMDA4MTkzODAsImp0aSI6ImZvbyIsInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdCIsImh0dHA6Ly9wb3N0Z3Jlc3QuY29tL2ZvbyI6dHJ1ZX0.G2REtPnOQMUrVRDA9OnkPJTd8R0tf4wdYOlauh1E2Ek"} |]
{ matchStatus = 200
, matchHeaders = [matchContentTypeSingular]
}
it "sql functions can read custom and standard claims variables" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmdW4iLCJqdGkiOiJmb28iLCJuYmYiOjEzMDA4MTkzODAsImV4cCI6OTk5OTk5OTk5OSwiaHR0cDovL3Bvc3RncmVzdC5jb20vZm9vIjp0cnVlLCJpc3MiOiJqb2UiLCJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWF0IjoxMzAwODE5MzgwfQ.V5fEpXfpb7feqwVqlcDleFdKu86bdwU2cBRT4fcMhXg"
request methodPost "/rpc/reveal_big_jwt" [auth] "{}"
`shouldRespondWith` [str|[{"iss":"joe","sub":"fun","exp":9999999999,"nbf":1300819380,"iat":1300819380,"jti":"foo","http://postgrest.com/foo":true}]|]
it "allows users with permissions to see their tables" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.B-lReuGNDwAlU1GOC476MlO0vAt9JNoHIlxg2vwMaO0"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
it "works with tokens which have extra fields" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIiwia2V5MSI6InZhbHVlMSIsImtleTIiOiJ2YWx1ZTIiLCJrZXkzIjoidmFsdWUzIiwiYSI6MSwiYiI6MiwiYyI6M30.b0eglDKYEmGi-hCvD-ddSqFl7vnDO5qkUaviaHXm3es"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
-- this test will stop working 9999999999s after the UNIX EPOCH
it "succeeds with an unexpired token" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjk5OTk5OTk5OTksInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdF9hdXRob3IiLCJpZCI6Impkb2UifQ.Dpss-QoLYjec5OTsOaAc3FNVsSjA89wACoV-0ra3ClA"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
it "fails with an expired token" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NDY2NzgxNDksInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdF9hdXRob3IiLCJpZCI6Impkb2UifQ.f8__E6VQwYcDqwHmr9PG03uaZn8Zh1b0vbJ9DYS0AdM"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` [json| {"message":"JWT expired"} |]
{ matchStatus = 401
, matchHeaders = [
"WWW-Authenticate" <:>
"Bearer error=\"invalid_token\", error_description=\"JWT expired\""
]
}
it "hides tables from users with invalid JWT" $ do
let auth = authHeaderJWT "ey9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.y4vZuu1dDdwAl0-S00MCRWRYMlJ5YAMSir6Es6WtWx0"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` [json| {"message":"JWSError (CompactDecodeError Invalid number of parts: Expected 3 parts; got 2)"} |]
{ matchStatus = 401
, matchHeaders = [
"WWW-Authenticate" <:>
"Bearer error=\"invalid_token\", error_description=\"JWSError (CompactDecodeError Invalid number of parts: Expected 3 parts; got 2)\""
]
}
it "should fail when jwt contains no claims" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.CUIP5V9thWsGGFsFyGijSZf1fJMfarLHI9CEJL-TGNk"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 401
it "hides tables from users with JWT that contain no claims about role" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Impkb2UifQ.RVlZDaSyKbFPvxUf3V_NQXybfRB4dlBIkAUQXVXLUAI"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 401
it "recovers after 401 error with logged in user" $ do
_ <- post "/authors_only" [json| { "owner": "jdoe", "secret": "test content" } |]
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.B-lReuGNDwAlU1GOC476MlO0vAt9JNoHIlxg2vwMaO0"
_ <- request methodPost "/rpc/problem" [auth] ""
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
describe "custom pre-request proc acting on id claim" $ do
it "able to switch to postgrest_test_author role (id=1)" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MX0.gKw7qI50i9hMrSJW8BlTpdMEVmMXJYxlAqueGqpa_mE" in
request methodPost "/rpc/get_current_user" [auth]
[json| {} |]
`shouldRespondWith` [str|"postgrest_test_author"|]
{ matchStatus = 200
, matchHeaders = []
}
it "able to switch to postgrest_test_default_role (id=2)" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Mn0.nwzjMI0YLvVGJQTeoCPEBsK983b__gxdpLXisBNaO2A" in
request methodPost "/rpc/get_current_user" [auth]
[json| {} |]
`shouldRespondWith` [str|"postgrest_test_default_role"|]
{ matchStatus = 200
, matchHeaders = []
}
it "raises error (id=3)" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6M30.OGxEJAf60NKZiTn-tIb2jy4rqKs_ZruLGWZ40TjrJsM" in
request methodPost "/rpc/get_current_user" [auth]
[json| {} |]
`shouldRespondWith` [str|{"hint":"Please contact administrator","details":null,"code":"P0001","message":"Disabled ID --> 3"}|]
{ matchStatus = 400
, matchHeaders = []
}
| diogob/postgrest | test/Feature/AuthSpec.hs | mit | 8,581 | 0 | 17 | 1,642 | 1,135 | 622 | 513 | -1 | -1 |
module Types (
Mass
) where
type Mass = Float
| ThatSnail/hs-softbody | Types.hs | mit | 57 | 0 | 4 | 21 | 15 | 10 | 5 | 3 | 0 |
data BExp = T
| F
| Var Int
| Neg BExp
| Disj BExp BExp
| Conj BExp BExp
deriving Show
eval :: (Int -> Bool) -> BExp -> Bool
eval _ T = True
eval _ F = False
eval f (Var i) = f i
eval f (Neg e) = not (eval f e)
eval f (Disj a b) = (eval f a) || (eval f b)
eval f (Conj a b) = (eval f a) && (eval f b)
evalListEnv :: [Bool] -> BExp -> Bool
evalListEnv vars e = eval (\i -> vars !! i) e
environments :: Int -> [[Bool]]
environments 0 = [[]]
environments n = [True:e | e <- ens] ++ [False:e | e <- ens]
where ens = environments (n - 1)
equiv :: Int -> BExp -> BExp -> Bool
equiv n a b = (evalAll a) == (evalAll b)
where evalAll ex = map (flip evalListEnv ex) en
en = environments n
main = do
print $ evalListEnv [True, False] (Conj (Var 0) (Var 1))
print $ evalListEnv [True, False] (Disj (Var 0) (Var 1))
print $ environments 3
print $ equiv 2 (Conj (Var 0) (Var 1)) (Disj (Var 0) (Var 1))
| kdungs/coursework-functional-programming | 07/bool.hs | mit | 990 | 0 | 12 | 306 | 551 | 282 | 269 | 29 | 1 |
import Data.MotionPlanningProblem
import Data.Spaces.StandardSpace
import Planners.RRT
fk :: [(Double, Double)] -> [(Double, Double)]
fk links =
let (jointAngles, linkLengths) = unzip links
angleSums = scanl1 (+) jointAngles
xs = scanl1 (+) $ zipWith (*) linkLengths $ map cos angleSums
ys = scanl1 (+) $ zipWith (*) linkLengths $ map sin angleSums
in zip xs ys
isCollisionFree :: [(Double, Double)] -> Bool
isCollisionFree links =
let jointPositions = fk links
jointInBounds (_, y) = y < 1.0 && y > -1.0
in all jointInBounds jointPositions
goalReached :: [(Double, Double)] -> (Double, Double) -> Double -> Bool
goalReached links (gx, gy) goalRadius =
let (x, y) = last $ fk links
dx = x - gx
dy = y - gy
in dx*dx + dy*dy <= goalRadius*goalRadius
toState :: [Double] -> State
toState = CompoundState . map SO2State
fromState :: State -> [Double]
fromState (CompoundState so2States) =
map (\(SO2State a) -> a) so2States
main :: IO ()
main =
let linkLengths = [0.8, 0.8]
ss = mkRotationalVectorSpace $ length linkLengths
goalSatisfied s =
goalReached (zip (fromState s) linkLengths) (-1.6, 0.0) 0.01
q = MotionPlanningQuery
{ _startState = toState [0.0, 0.0]
, _goalSatisfied = goalSatisfied
}
stateValid s = isCollisionFree $ zip (fromState s) linkLengths
motionValid = discreteMotionValid ss stateValid 0.03
rrt = buildRRTDefault ss q motionValid 0.3 10000
motionPlan = getPathToGoal rrt
in do
print $ fk (zip [0.0, 0.0] linkLengths)
putStrLn $ "Computed a motion plan with " ++ show (Prelude.length motionPlan) ++ " states."
putStrLn $ "Num states in tree: " ++ show (getNumStates rrt)
putStrLn "Plan:"
mapM_ print motionPlan
| giogadi/hs-motion-planning | app-src/Examples/RRTPSMExample.hs | mit | 1,792 | 0 | 14 | 424 | 657 | 344 | 313 | 45 | 1 |
-- That's mean
-- http://www.codewars.com/kata/54b709b811ac249fdb000296
module Mean where
mean :: (Integral a, Fractional b) => [a] -> b
mean xs = fromIntegral (sum xs) / fromIntegral (length xs)
| gafiatulin/codewars | src/Beta/Mean.hs | mit | 198 | 0 | 8 | 30 | 63 | 34 | 29 | 3 | 1 |
{-# LANGUAGE Arrows, FlexibleContexts #-}
module QNDA.Toc where
import Text.XML.HXT.Core hiding (xshow)
import Data.Hashable ( hash )
import Control.Monad.State as S hiding (when)
import Data.Char (chr)
--import qualified Debug.Trace as DT (trace)
type HeaderTag = String -- h1, h2, and so on.
type HeaderText = String -- text of header
type HeaderCnt = (String, String) -- (header counter string, header type)
type InTocText = String -- header prefix text appearing in toc
type Header = (HeaderTag, (HeaderText, (FilePath, HeaderCnt)))
type HeaderList = [((Header, InTocText), Int)]
mkNcx :: String -> [Header] -> IO [XmlTree]
mkNcx isbn headers = runX (
spi "xml" "version=\"1.0\" encoding=\"UTF-8\""
<+>
(eelem "ncx"
+= sattr "version" "2005-1"
+= sattr "xmlns" "http://www.daisy.org/z3986/2005/ncx/"
+= (eelem "head"
+= (eelem "meta" += sattr "name" "dtb:uid" += sattr "content" ("urn:isbn:"++isbn))
+= (eelem "meta" += sattr "name" "dtb:depth" += sattr "content" "2")
+= (eelem "meta" += sattr "name" "dtb:totalPageCount" += sattr "content" "0")
+= (eelem "meta" += sattr "name" "dtb:maxPageNumber" += sattr "content" "0"))
+= (eelem "docTitle"
+= eelem "text")
+= (eelem "navMap"
+= (mkNavTree $ zip (zip headers (evalState (chapSectNum headers) (0,0,[]))) [1..]))))
chapSectNum :: [Header] -> S.State (Int,Int,[InTocText]) [InTocText]
chapSectNum [] = do
(_,_,result) <- get
return $ reverse result
chapSectNum ((t, (h, (f, c))) : cs) = do
(chap, sect, result) <- get
let h1cnt = h1Prefix c
h2cnt = h2Prefix c sect
put $
case t of
"h1" -> (chap+1, 0, h1cnt : result)
"h2" -> (chap, sect+1, h2cnt : result)
_ -> (chap, sect, ((show sect) : result))
chapSectNum cs
mkHeaderCnt :: String -> Int -> HeaderCnt
mkHeaderCnt "chapter" n = (show n, "chapter")
mkHeaderCnt "appendix" n = ([chr $ 64+n], "appendix")
mkHeaderCnt _ n = ("", "other")
h1Prefix :: HeaderCnt -> String
h1Prefix (c, "chapter") = "Chapter "++c
h1Prefix (c, "appendix") = "Appendix "++c++" "
h1Prefix (c, "other") = ""
h2Prefix :: HeaderCnt -> Int -> String
h2Prefix (c, "chapter") n = c++"."++(show $ n+1)++" "
h2Prefix (c, "appendix") n = c++"."++(show $ n+1)++" "
h2Prefix (c, "other") n = ""
takeChildren prod = takeWhile (prod . fst . fst . fst)
dropChildren prod = dropWhile (prod . fst . fst . fst)
mkTreeFromHeaderList :: (ArrowList a, ArrowXml a) =>
(HeaderTag -> FilePath -> InTocText -> Int -> (String -> Bool) -> HeaderList -> a b XmlTree)
-> (HeaderTag -> FilePath -> InTocText -> Int -> a b XmlTree)
-> HeaderList
-> a b XmlTree
mkTreeFromHeaderList whenRoot whenNode [] = none
mkTreeFromHeaderList whenRoot whenNode c@(((("appendix",(h,(f,cnt))),cs),n) : ((("h2",(_,_)),_),_) : _) = -- when head is "appendix"
whenRoot ("h1"++h) f cs n (\h -> (h=="h2") || (h=="h3")) (tail c)
mkTreeFromHeaderList whenRoot whenNode c@(((("h1",(h,(f,cnt))),cs),n) : ((("h1",(_,_)),_),_) : _) = -- when head is h1 and the rest are h1
whenRoot ("h1"++h) f cs n (\h -> (h=="h2") || (h=="h3")) (tail c)
mkTreeFromHeaderList whenRoot whenNode c@(((("h1",(h,(f,cnt))),cs),n) : ((("h2",(_,_)),_),_) : _) = -- when head is h1 and the rest are h2 or h3
whenRoot ("h1"++h) f cs n (\h -> (h=="h2") || (h=="h3")) (tail c)
mkTreeFromHeaderList whenRoot whenNode c@(((("h2",(h,(f,cnt))),cs),n) : ((("h3",(_,_)),_),_) : _) = -- when head is h1 and the rest are h3 but h2
whenRoot ("h1"++h) f cs n (=="h3") (tail c)
mkTreeFromHeaderList whenRoot whenNode c = -- when head is not h1, so is h2 or h3
let typeOfHead = fst $ fst $ fst $ head c
in (catA (map (\(((_,(h,(f,cnt))),cs),n) -> whenNode ("h2"++h) f cs n) $ takeChildren (==typeOfHead) c))
<+> (mkTreeFromHeaderList whenRoot whenNode $ dropChildren (==typeOfHead) c)
---------
-- NCX --
---------
mkNavTree :: (ArrowList a, ArrowXml a) => HeaderList -> a b XmlTree
mkNavTree = mkTreeFromHeaderList mkNavRoot mkNavNode
mkNavRoot :: (ArrowList a, ArrowXml a) => HeaderText -> FilePath -> InTocText -> Int -> (String -> Bool) -> HeaderList -> a b XmlTree
mkNavRoot headertext filename chapsec number children rest =
(mkNavNode headertext filename chapsec number
+= (mkNavTree $ takeChildren children rest))
<+> (mkNavTree $ dropChildren children rest)
mkNavNode :: (ArrowList a, ArrowXml a) => HeaderText -> FilePath -> InTocText -> Int -> a b XmlTree
mkNavNode headertext filename chapsec number =
eelem "navPoint"
+= sattr "id" ("navPoint-"++(show number))
+= sattr "playOrder" (show number)
+= (eelem "navLabel"
+= (eelem "text" += (txt $ (chapsec++(drop 2 headertext)))))
+= (eelem "content"
+= (sattr "src" $ filename++"#"++"name"++(show $ hash headertext)))
---------
-- TOC --
---------
mkTocpage headers = runX (
spi "xml" "version=\"1.0\" encoding=\"UTF-8\""
<+>
(eelem "html"
+= sattr "xmlns" "http://www.w3.org/1999/xhtml"
+= sattr "xml:lang" "ja-JP"
+= (eelem "head"
+= (eelem "title"
+= txt "Table of Contents")
+= (eelem "link"
+= sattr "rel" "stylesheet"
+= sattr "type" "text/css"
+= sattr "href" "public/css/epub.css"))
+= (eelem "body"
+= (eelem "nav" += sattr "xmlns:epub" "http://www.idpf.org/2007/ops" += sattr "epub:type" "toc"
+= (eelem "h1" += txt "Table of Contents")
+= (eelem "ol"
+= (mkTocTree $ zip (zip headers (evalState (chapSectNum headers) (0,0,[]))) [1..]))))))
mkTocTree :: (ArrowList a, ArrowXml a) => HeaderList -> a b XmlTree
mkTocTree = mkTreeFromHeaderList mkTocRoot mkTocNode
mkTocRoot :: (ArrowList a, ArrowXml a) => HeaderText -> FilePath -> InTocText -> Int -> (String -> Bool) -> HeaderList -> a b XmlTree
mkTocRoot headertext filename chapsec number children rest =
(mkTocNode headertext filename chapsec number
+= (eelem "ol"
+= (mkTocTree $ takeChildren children rest)))
<+> (mkTocTree $ dropChildren children rest)
mkTocNode :: (ArrowList a, ArrowXml a) => HeaderText -> FilePath -> InTocText -> Int -> a b XmlTree
mkTocNode headertext filename chapsec number =
(eelem "li"
+= (eelem "a"
+= (sattr "href" $ filename++"#"++"name"++(show $ hash headertext))
+= (txt $ chapsec)
+= (txt $ drop 2 headertext)))
| k16shikano/wikipepub | QNDA/Toc.hs | mit | 6,445 | 0 | 24 | 1,387 | 2,588 | 1,398 | 1,190 | 123 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.