code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE 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"
-- NCG stuff:
import GhcPrelude
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.Instr
import SPARC.Imm
import SPARC.AddrMode
import SPARC.Regs
import SPARC.Stack
import Instruction
import Format
import NCGMonad ( NatM, getNewRegNat, getNewLabelNat )
-- Our intermediate code:
import GHC.Cmm.BlockId
import GHC.Cmm
import GHC.Cmm.Utils
import GHC.Cmm.Switch
import GHC.Cmm.Dataflow.Block
import GHC.Cmm.Dataflow.Graph
import PIC
import Reg
import GHC.Cmm.CLabel
import CPrim
-- The rest:
import BasicTypes
import DynFlags
import FastString
import OrdList
import Outputable
import GHC.Platform
import Control.Monad ( mapAndUnzipM )
-- | Top level code generation
cmmTopCodeGen :: RawCmmDecl
-> NatM [NatCmmDecl RawCmmStatics 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 RawCmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
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))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode format reg src
| isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode format reg src
where ty = cmmRegType dflags reg
format = cmmTypeFormat ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode format addr src
| isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode format addr src
where ty = cmmExprType dflags src
format = cmmTypeFormat 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 a 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 = blockLbl 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 :: Format -> 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 :: Format -> 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 :: Format -> 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 formatToWidth pk == typeWidth pk__2
then unitOL (ST pk src__2 dst__2)
else toOL [ FxTOy (cmmTypeFormat pk__2) pk src__2 tmp1
, ST pk tmp1 dst__2]
return code__2
-- Floating point assignment to a register/temporary
assignReg_FltCode :: Format -> 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 -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| positionIndependent dflags
= error "MachCodeGen: sparc genSwitch PIC not finished\n"
| otherwise
= do (e_reg, e_code) <- getSomeReg (cmmOffset dflags expr offset)
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 ]
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl RawCmmStatics Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids label) =
let jumpTable = map (jumpTableEntry dflags) ids
in Just (CmmData (Section ReadOnlyData label) (RawCmmStatics 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_ReadBarrier) _ _
= return $ nilOL
genCCall (PrimTarget MO_WriteBarrier) _ _
= return $ nilOL
genCCall (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall target dest_regs args
= do -- 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_rs) <- arg_to_int_vregs expr
let dyn_r = case dyn_rs of
[dyn_r'] -> dyn_r'
_ -> panic "SPARC.CodeGen.genCCall: arg_to_int"
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_rs) <- arg_to_int_vregs mopExpr
let dyn_r = case dyn_rs of
[dyn_r'] -> dyn_r'
_ -> panic "SPARC.CodeGen.genCCall: arg_to_int"
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 cmmTypeFormat 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_ExpM1 -> fsLit "expm1f"
MO_F32_Log -> fsLit "logf"
MO_F32_Log1P -> fsLit "log1pf"
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Fabs -> unsupported
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_F32_Asinh -> fsLit "asinhf"
MO_F32_Acosh -> fsLit "acoshf"
MO_F32_Atanh -> fsLit "atanhf"
MO_F64_Exp -> fsLit "exp"
MO_F64_ExpM1 -> fsLit "expm1"
MO_F64_Log -> fsLit "log"
MO_F64_Log1P -> fsLit "log1p"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Fabs -> unsupported
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_F64_Asinh -> fsLit "asinh"
MO_F64_Acosh -> fsLit "acosh"
MO_F64_Atanh -> fsLit "atanh"
MO_UF_Conv w -> fsLit $ word2FloatLabel w
MO_Memcpy _ -> fsLit "memcpy"
MO_Memset _ -> fsLit "memset"
MO_Memmove _ -> fsLit "memmove"
MO_Memcmp _ -> fsLit "memcmp"
MO_BSwap w -> fsLit $ bSwapLabel w
MO_BRev w -> fsLit $ bRevLabel w
MO_PopCnt w -> fsLit $ popCntLabel w
MO_Pdep w -> fsLit $ pdepLabel w
MO_Pext w -> fsLit $ pextLabel w
MO_Clz w -> fsLit $ clzLabel w
MO_Ctz w -> fsLit $ ctzLabel 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_Mul2 {} -> unsupported
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_AddWordC {} -> unsupported
MO_SubWordC {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_ReadBarrier -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _) -> unsupported
where unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
|
sdiehl/ghc
|
compiler/nativeGen/SPARC/CodeGen.hs
|
bsd-3-clause
| 23,833 | 0 | 29 | 7,876 | 4,926 | 2,440 | 2,486 | 413 | 68 |
--------------------------------------------------------------------------------
-- |
-- Module : Network.Cosmodesic.Values
-- Copyright : (C) 2015 Yorick Laupa
-- License : (see the file LICENSE)
--
-- Maintainer : Yorick Laupa <[email protected]>
-- Stability : provisional
-- Portability : non-portable
--
--------------------------------------------------------------------------------
module Network.Cosmodesic.Values where
--------------------------------------------------------------------------------
import Control.Monad
import Data.ByteString
import Data.Monoid
--------------------------------------------------------------------------------
import qualified Data.Map.Strict as M
--------------------------------------------------------------------------------
import Network.Cosmodesic.Response
import Network.Cosmodesic.Types
--------------------------------------------------------------------------------
type Register = M.Map ByteString Value
--------------------------------------------------------------------------------
data RegError = AlreadyBounded ByteString
--------------------------------------------------------------------------------
newtype Declarations = Decls (Register -> Either RegError Register)
--------------------------------------------------------------------------------
instance Monoid Declarations where
mempty = Decls Right
mappend (Decls kl) (Decls kr) = Decls (kl >=> kr)
--------------------------------------------------------------------------------
declare :: Valuable v => ByteString -> v -> Declarations
declare n v = Decls $ \rg ->
if M.member n rg
then Left (AlreadyBounded n)
else Right $ M.insert n (valuable v) rg
--------------------------------------------------------------------------------
emptyValues :: Values
emptyValues = Values M.empty
--------------------------------------------------------------------------------
register :: Declarations -> Values -> Either RegError Values
register (Decls k) (Values m) = fmap Values $ k m
|
YoEight/cosmodesic
|
Network/Cosmodesic/Values.hs
|
bsd-3-clause
| 2,028 | 0 | 11 | 196 | 301 | 170 | 131 | 22 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Language.Haskell.Liquid.Types.Variance ( Variance(..), VarianceInfo ) where
import Prelude hiding (error)
import Control.DeepSeq
import Data.Typeable
import Data.Data
import GHC.Generics
type VarianceInfo = [Variance]
data Variance = Invariant | Bivariant | Contravariant | Covariant
deriving (Data, Typeable, Show, Generic)
instance NFData Variance
|
ssaavedra/liquidhaskell
|
src/Language/Haskell/Liquid/Types/Variance.hs
|
bsd-3-clause
| 447 | 0 | 6 | 72 | 103 | 64 | 39 | 12 | 0 |
-- 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. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.FR.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Resolve
import Duckling.Time.Corpus
import Duckling.Time.Types hiding (Month)
import Duckling.TimeGrain.Types hiding (add)
import Duckling.Testing.Types hiding (examples)
corpus :: Corpus
corpus = (testContext {lang = FR}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (datetime (2013, 2, 12, 4, 30, 0) Second)
[ "maintenant"
, "tout de suite"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "aujourd'hui"
, "ce jour"
, "dans la journée"
, "en ce moment"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "hier"
, "le jour d'avant"
, "le jour précédent"
, "la veille"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "avant-hier"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "demain"
, "jour suivant"
, "le jour d'après"
, "le lendemain"
, "un jour après"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "après-demain"
, "le lendemain du 13 février"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "lundi"
, "lun."
, "ce lundi"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "lundi 18 février"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "mardi"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "mercredi 13 février"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "jeudi"
, "deux jours plus tard"
, "deux jours après"
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "vendredi"
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "samedi"
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "dimanche"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "le 1er mars"
, "premier mars"
, "le 1 mars"
, "vendredi 1er mars"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "le premier mars 2013"
, "1/3/2013"
, "2013-03-01"
]
, examples (datetime (2013, 3, 2, 0, 0, 0) Day)
[ "le 2 mars"
, "2 mars"
, "le 2/3"
]
, examples (datetime (2013, 3, 2, 5, 0, 0) Hour)
[ "le 2 mars à 5h"
, "2 mars à 5h"
, "le 2/3 à 5h"
, "le 2 mars à 5h du matin"
, "le 2 mars vers 5h"
, "2 mars vers 5h"
, "2 mars à environ 5h"
, "2 mars aux alentours de 5h"
, "2 mars autour de 5h"
, "le 2/3 vers 5h"
]
, examples (datetime (2013, 3, 2, 0, 0, 0) Day)
[ "le 2"
]
, examples (datetime (2013, 3, 2, 5, 0, 0) Hour)
[ "le 2 à 5h"
, "le 2 vers 5h"
, "le 2 à 5h du mat"
]
, examples (datetime (2013, 3, 3, 0, 0, 0) Day)
[ "le 3 mars"
, "3 mars"
, "le 3/3"
]
, examples (datetime (2013, 4, 5, 0, 0, 0) Day)
[ "le 5 avril"
, "5 avril"
]
, examples (datetime (2015, 3, 3, 0, 0, 0) Day)
[ "le 3 mars 2015"
, "3 mars 2015"
, "3/3/2015"
, "2015-3-3"
, "2015-03-03"
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "le 15 février"
, "15 février"
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "15/02/2013"
, "15 fev 2013"
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "le 16"
]
, examples (datetime (2013, 2, 16, 18, 0, 0) Hour)
[ "le 16 à 18h"
, "le 16 vers 18h"
, "le 16 plutôt vers 18h"
, "le 16 à 6h du soir"
, "le 16 vers 6h du soir"
, "le 16 vers 6h dans la soirée"
, "samedi 16 à 18h"
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "17 février"
, "le 17 février"
, "17/2"
, "17/02"
, "le 17/02"
, "17 02"
, "17 2"
, "le 17 02"
, "le 17 2"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "mercredi 13"
]
, examples (datetime (2014, 2, 20, 0, 0, 0) Day)
[ "20/02/2014"
, "20/2/2014"
, "20/02/14"
, "le 20/02/14"
, "le 20/2/14"
, "20 02 2014"
, "20 02 14"
, "20 2 2014"
, "20 2 14"
, "le 20 02 2014"
, "le 20 02 14"
, "le 20 2 2014"
, "le 20 2 14"
]
, examples (datetime (2013, 10, 31, 0, 0, 0) Day)
[ "31 octobre"
, "le 31 octobre"
, "31/10"
, "le 31/10"
, "31 10"
, "le 31 10"
]
, examples (datetime (2014, 12, 24, 0, 0, 0) Day)
[ "24/12/2014"
, "24/12/14"
, "le 24/12/14"
, "24 12 2014"
, "24 12 14"
, "le 24 12 2014"
, "le 24 12 14"
]
, examples (datetime (1974, 10, 31, 0, 0, 0) Day)
[ "31/10/1974"
, "31/10/74"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "lundi prochain"
, "lundi la semaine prochaine"
, "lundi de la semaine prochaine"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "mardi prochain"
, "mardi suivant"
, "mardi d'après"
, "mardi la semaine prochaine"
, "mardi de la semaine prochaine"
, "mardi la semaine suivante"
, "mardi de la semaine suivante"
, "mardi la semaine d'après"
, "mardi de la semaine d'après"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "mercredi prochain"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "mercredi suivant"
, "mercredi d'après"
, "mercredi la semaine prochaine"
, "mercredi de la semaine prochaine"
, "mercredi la semaine suivante"
, "mercredi de la semaine suivante"
, "mercredi la semaine d'après"
, "mercredi de la semaine d'après"
]
, examples (datetime (2013, 2, 25, 0, 0, 0) Day)
[ "lundi en huit"
, "lundi en 8"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "mardi en huit"
, "mardi en 8"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "mercredi en huit"
, "mercredi en 8"
]
, examples (datetime (2013, 3, 4, 0, 0, 0) Day)
[ "lundi en quinze"
, "lundi en 15"
]
, examples (datetime (2013, 2, 26, 0, 0, 0) Day)
[ "mardi en quinze"
, "mardi en 15"
]
, examples (datetime (2013, 2, 27, 0, 0, 0) Day)
[ "mercredi en quinze"
, "mercredi en 15"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "lundi cette semaine"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "mardi cette semaine"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "mercredi cette semaine"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Week)
[ "cette semaine"
, "dans la semaine"
]
, examples (datetime (2013, 2, 4, 0, 0, 0) Week)
[ "la semaine dernière"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Week)
[ "la semaine prochaine"
, "la semaine suivante"
, "la semaine qui suit"
]
, examples (datetime (2013, 1, 0, 0, 0, 0) Month)
[ "le mois dernier"
]
, examples (datetime (2013, 3, 0, 0, 0, 0) Month)
[ "le mois prochain"
, "le mois suivant"
]
, examples (datetime (2012, 0, 0, 0, 0, 0) Year)
[ "l'année dernière"
]
, examples (datetime (2013, 0, 0, 0, 0, 0) Year)
[ "cette année"
]
, examples (datetime (2014, 0, 0, 0, 0, 0) Year)
[ "l'année prochaine"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "dimanche dernier"
, "dimanche de la semaine dernière"
]
, examples (datetime (2013, 10, 3, 0, 0, 0) Day)
[ "3eme jour d'octobre"
, "le 3eme jour d'octobre"
]
, examples (datetime (2014, 10, 6, 0, 0, 0) Week)
[ "premiere semaine d'octobre 2014"
, "la premiere semaine d'octobre 2014"
]
, examples (datetime (2013, 10, 7, 0, 0, 0) Week)
[ "la semaine du 6 octobre"
, "la semaine du 7 octobre"
]
, examples (datetime (2015, 10, 31, 0, 0, 0) Day)
[ "dernier jour d'octobre 2015"
, "le dernier jour d'octobre 2015"
]
, examples (datetime (2014, 9, 22, 0, 0, 0) Week)
[ "dernière semaine de septembre 2014"
, "la dernière semaine de septembre 2014"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Hour)
[ "à quinze heures"
, "à 15 heures"
, "à 3 heures cet après-midi"
, "15h"
, "15H"
, "vers 15 heures"
, "à environ 15 heures"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Minute)
[ "15:00"
, "15h00"
, "15H00"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Hour)
[ "minuit"
]
, examples (datetime (2013, 2, 12, 12, 0, 0) Hour)
[ "midi"
, "aujourd'hui à midi"
]
, examples (datetime (2013, 2, 12, 12, 15, 0) Minute)
[ "midi et quart"
, "midi quinze"
]
, examples (datetime (2013, 2, 12, 11, 55, 0) Minute)
[ "midi moins cinq"
]
, examples (datetime (2013, 2, 12, 12, 30, 0) Minute)
[ "midi et demi"
, "midi trente"
]
, examples (datetime (2013, 2, 13, 0, 3, 0) Minute)
[ "minuit trois"
]
, examples (datetime (2013, 2, 12, 0, 3, 0) Minute)
[ "aujourd'hui à minuit trois"
]
, examples (datetime (2013, 2, 12, 15, 15, 0) Minute)
[ "à quinze heures quinze"
, "à quinze heures et quinze minutes"
, "15h passé de 15 minutes"
, "à trois heures et quart cet après-midi"
, "15:15"
, "15h15"
]
, examples (datetime (2013, 2, 13, 15, 15, 0) Minute)
[ "à trois heures et quart demain après-midi"
]
, examples (datetime (2013, 2, 12, 15, 30, 0) Minute)
[ "à quinze heures trente"
, "à quinze heures passé de trente minutes"
, "à trois heures et demi cet après-midi"
, "15:30"
, "15h30"
]
, examples (datetime (2013, 2, 12, 11, 45, 0) Minute)
[ "midi moins le quart"
, "11h45"
, "onze heures trois quarts"
, "aujourd'hui à 11h45"
]
, examples (datetime (2013, 2, 13, 11, 0, 0) Hour)
[ "mercredi à 11h"
]
, examples (datetime (2013, 2, 13, 11, 0, 0) Hour)
[ "demain à 11 heures"
, "demain à 11H"
]
, examples (datetime (2013, 2, 14, 11, 0, 0) Hour)
[ "jeudi à 11h"
, "après-demain à 11 heures"
, "après-demain à 11H"
]
, examples (datetime (2013, 2, 15, 12, 0, 0) Hour)
[ "vendredi à midi"
, "vendredi à 12h"
]
, examples (datetime (2013, 2, 15, 16, 0, 0) Hour)
[ "vendredi quinze à seize heures"
, "vendredi 15 à 16h"
, "vendredi quinze à 16h"
]
, examples (datetime (2013, 2, 12, 4, 30, 1) Second)
[ "dans une seconde"
, "dans 1\""
]
, examples (datetime (2013, 2, 12, 4, 31, 0) Second)
[ "dans une minute"
, "dans 1 min"
]
, examples (datetime (2013, 2, 12, 4, 32, 0) Second)
[ "dans 2 minutes"
, "dans deux min"
, "dans 2'"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Second)
[ "dans 60 minutes"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Minute)
[ "dans une heure"
]
, examples (datetime (2013, 2, 12, 2, 30, 0) Minute)
[ "il y a deux heures"
]
, examples (datetime (2013, 2, 13, 4, 30, 0) Minute)
[ "dans 24 heures"
, "dans vingt quatre heures"
]
, examples (datetime (2013, 2, 13, 4, 0, 0) Hour)
[ "dans un jour"
]
, examples (datetime (2013, 2, 19, 4, 0, 0) Hour)
[ "dans 7 jours"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "dans 1 semaine"
, "dans une semaine"
]
, examples (datetime (2013, 1, 22, 0, 0, 0) Day)
[ "il y a trois semaines"
]
, examples (datetime (2013, 4, 12, 0, 0, 0) Day)
[ "dans deux mois"
]
, examples (datetime (2012, 11, 12, 0, 0, 0) Day)
[ "il y a trois mois"
]
, examples (datetime (2014, 2, 0, 0, 0, 0) Month)
[ "dans une année"
, "dans 1 an"
]
, examples (datetime (2011, 2, 0, 0, 0, 0) Month)
[ "il y a deux ans"
]
, examples (datetimeInterval ((2013, 6, 21, 0, 0, 0), (2013, 9, 24, 0, 0, 0)) Day)
[ "cet été"
]
, examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day)
[ "cet hiver"
]
, examples (datetime (2013, 12, 25, 0, 0, 0) Day)
[ "Noel"
, "noël"
, "jour de noel"
]
, examples (datetimeInterval ((2013, 12, 24, 18, 0, 0), (2013, 12, 25, 0, 0, 0)) Hour)
[ "le soir de noël"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Day)
[ "jour de l'an"
, "nouvel an"
, "premier janvier"
]
, examples (datetime (2013, 11, 1, 0, 0, 0) Day)
[ "la toussaint"
, "le jour de la toussaint"
, "la journée de la toussaint"
, "toussaint"
, "le jour des morts"
]
, examples (datetime (2013, 5, 1, 0, 0, 0) Day)
[ "fête du travail"
]
, examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "cet après-midi"
, "l'après-midi"
]
, examples (datetimeInterval ((2013, 2, 12, 7, 0, 0), (2013, 2, 12, 9, 0, 0)) Hour)
[ "en début de matinée"
, "aujourd'hui très tôt le matin"
, "aujourd'hui tôt le matin"
, "aujourd'hui le matin tôt"
, "aujourd'hui le matin très tôt"
]
, examples (datetimeInterval ((2013, 2, 12, 10, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour)
[ "en fin de matinée"
]
, examples (datetimeInterval ((2013, 2, 12, 13, 0, 0), (2013, 2, 12, 17, 0, 0)) Hour)
[ "après déjeuner"
]
, examples (datetimeInterval ((2013, 2, 12, 10, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour)
[ "avant déjeuner"
]
, examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 14, 0, 0)) Hour)
[ "aujourd'hui pendant le déjeuner"
]
, examples (datetimeInterval ((2013, 2, 12, 17, 0, 0), (2013, 2, 12, 21, 0, 0)) Hour)
[ "après le travail"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour)
[ "dès le matin"
, "dès la matinée"
]
, examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 14, 0, 0)) Hour)
[ "en début d'après-midi"
]
, examples (datetimeInterval ((2013, 2, 12, 17, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "en fin d'après-midi"
]
, examples (datetimeInterval ((2013, 2, 12, 6, 0, 0), (2013, 2, 12, 10, 0, 0)) Hour)
[ "en début de journée"
]
, examples (datetimeInterval ((2013, 2, 12, 17, 0, 0), (2013, 2, 12, 21, 0, 0)) Hour)
[ "en fin de journée"
]
, examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "ce soir"
]
, examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 12, 21, 0, 0)) Hour)
[ "en début de soirée"
]
, examples (datetimeInterval ((2013, 2, 12, 21, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "en fin de soirée"
]
, examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour)
[ "demain soir"
, "mercredi soir"
, "mercredi en soirée"
]
, examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "hier soir"
, "la veille au soir"
]
, examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour)
[ "ce week-end"
]
, examples (datetimeInterval ((2013, 2, 11, 0, 0, 0), (2013, 2, 13, 0, 0, 0)) Day)
[ "en début de semaine"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 15, 0, 0, 0)) Day)
[ "en milieu de semaine"
]
, examples (datetimeInterval ((2013, 2, 14, 0, 0, 0), (2013, 2, 18, 0, 0, 0)) Day)
[ "en fin de semaine"
]
, examples (datetimeInterval ((2013, 2, 11, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "en semaine"
]
, examples (datetimeInterval ((2013, 9, 6, 18, 0, 0), (2013, 9, 9, 0, 0, 0)) Hour)
[ "le premier week-end de septembre"
]
, examples (datetimeInterval ((2013, 9, 13, 18, 0, 0), (2013, 9, 16, 0, 0, 0)) Hour)
[ "le deuxième week-end de septembre"
]
, examples (datetimeInterval ((2013, 9, 27, 18, 0, 0), (2013, 9, 30, 0, 0, 0)) Hour)
[ "le dernier week-end de septembre"
]
, examples (datetimeInterval ((2013, 2, 18, 4, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour)
[ "lundi matin"
]
, examples (datetimeInterval ((2013, 2, 18, 12, 0, 0), (2013, 2, 18, 19, 0, 0)) Hour)
[ "lundi après-midi"
, "lundi dans l'après-midi"
]
, examples (datetimeInterval ((2013, 2, 18, 17, 0, 0), (2013, 2, 18, 19, 0, 0)) Hour)
[ "lundi fin d'après-midi"
, "lundi en fin d'après-midi"
]
, examples (datetimeInterval ((2013, 2, 15, 4, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour)
[ "le 15 février dans la matinée"
, "matinée du 15 février"
, "le 15 février le matin"
]
, examples (datetime (2013, 2, 12, 20, 0, 0) Hour)
[ "8 heures ce soir"
, "8h du soir"
]
, examples (datetime (2013, 2, 13, 3, 0, 0) Hour)
[ "3 heures du matin"
, "3h du mat"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second)
[ "2 dernières secondes"
, "deux dernieres secondes"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second)
[ "3 prochaines secondes"
, "trois prochaines secondes"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute)
[ "2 dernieres minutes"
, "deux dernières minutes"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute)
[ "3 prochaines minutes"
, "trois prochaines minutes"
]
, examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour)
[ "3 prochaines heures"
, "3 heures suivantes"
]
, examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day)
[ "2 dernier jours"
, "deux derniers jour"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "3 prochains jours"
]
, examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week)
[ "2 dernieres semaines"
, "2 semaines passées"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week)
[ "3 prochaines semaines"
]
, examples (datetimeInterval ((2012, 12, 0, 0, 0, 0), (2013, 2, 0, 0, 0, 0)) Month)
[ "2 derniers mois"
]
, examples (datetimeInterval ((2013, 3, 0, 0, 0, 0), (2013, 6, 0, 0, 0, 0)) Month)
[ "3 prochains mois"
, "3 mois suivant"
]
, examples (datetimeInterval ((2011, 0, 0, 0, 0, 0), (2013, 0, 0, 0, 0, 0)) Year)
[ "2 dernieres annees"
, "2 années passées"
]
, examples (datetimeInterval ((2014, 0, 0, 0, 0, 0), (2017, 0, 0, 0, 0, 0)) Year)
[ "3 prochaines années"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "13-15 juillet"
, "13 au 15 juillet"
, "13 jusqu'au 15 juillet"
, "13 juillet au 15 juillet"
, "13 juillet - 15 juillet"
, "entre le 13 et le 15 juillet"
, "samedi 13 au dimanche 15 juillet"
, "du samedi 13 au dimanche 15 juillet"
, "du 13 au dimanche 15 juillet"
]
, examples (datetimeInterval ((2013, 7, 1, 0, 0, 0), (2013, 7, 11, 0, 0, 0)) Day)
[ "1er au 10 juillet"
, "lundi 1er au mercredi 10 juillet"
, "lundi 1 au mercredi 10 juillet"
, "du lundi 1er au mercredi 10 juillet"
, "du 1er au mercredi 10 juillet"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 19, 0, 0, 0)) Day)
[ "du 13 au 18"
, "entre le 13 et le 18"
]
, examples (datetimeInterval ((2013, 6, 10, 0, 0, 0), (2013, 7, 2, 0, 0, 0)) Day)
[ "10 juin au 1er juillet"
, "entre le 10 juin et le 1er juillet"
, "du 10 juin au 1er juillet"
]
, examples (datetimeInterval ((2013, 2, 14, 9, 30, 0), (2013, 2, 14, 12, 0, 0)) Minute)
[ "de 9h30 jusqu'à 11h jeudi"
, "de 9 heures 30 à 11h jeudi"
, "de 9 heures 30 a 11h jeudi"
, "entre 9h30 et 11h jeudi"
, "jeudi mais entre 9h30 et 11h"
, "jeudi par exemple entre 9h30 et 11h"
]
, examples (datetimeInterval ((2013, 2, 14, 9, 30, 0), (2013, 2, 14, 11, 1, 0)) Minute)
[ "9h30 - 11h00 Jeudi"
]
, examples (datetimeOpenInterval After (2013, 3, 8, 0, 0, 0) Day)
[ "à partir du 8"
, "à partir du 8 mars"
]
, examples (datetimeOpenInterval After (2013, 2, 14, 9, 30, 0) Minute)
[ "à partir de 9h30 jeudi"
, "jeudi après 9h30"
, "jeudi matin à partir de 9 heures 30"
]
, examples (datetimeOpenInterval After (2013, 11, 1, 16, 0, 0) Hour)
[ "après 16h le 1er novembre"
]
, examples (datetimeOpenInterval After (2013, 11, 1, 0, 0, 0) Day)
[ "après le 1er novembre"
]
, examples (datetimeOpenInterval Before (2013, 2, 12, 16, 0, 0) Hour)
[ "avant 16h"
, "n'importe quand avant 16h"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 13, 17, 0, 0)) Hour)
[ "demain jusqu'à 16h"
]
, examples (datetimeOpenInterval After (2013, 2, 20, 10, 0, 0) Hour)
[ "le 20 à partir de 10h"
]
, examples (datetimeOpenInterval After (2013, 2, 15, 12, 0, 0) Hour)
[ "vendredi à partir de midi"
]
, examples (datetimeInterval ((2013, 2, 20, 0, 0, 0), (2013, 2, 20, 19, 0, 0)) Hour)
[ "le 20 jusqu'à 18h"
]
, examples (datetimeInterval ((2014, 9, 14, 0, 0, 0), (2014, 9, 21, 0, 0, 0)) Day)
[ "14 - 20 sept. 2014"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 26, 0, 0, 0)) Second)
[ "d'ici 2 semaines"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 27, 4, 0, 0)) Second)
[ "dans les 15 jours"
]
, examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour)
[ "de 5 à 7"
]
, examples (datetimeInterval ((2013, 2, 14, 9, 0, 0), (2013, 2, 14, 12, 0, 0)) Hour)
[ "jeudi de 9h à 11h"
]
, examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 15, 0, 0)) Hour)
[ "entre midi et 2"
]
, examples (datetimeInterval ((2013, 2, 12, 11, 30, 0), (2013, 2, 12, 13, 31, 0)) Minute)
[ "11h30-1h30"
, "de 11h30 à 1h30"
, "de 11h30 jusqu'à 1h30"
]
, examples (datetime (2013, 9, 21, 13, 30, 0) Minute)
[ "13h30 samedi 21 septembre"
]
, examples (datetime (2013, 2, 12, 13, 0, 0) Minute)
[ "à seize heures CET"
]
, examples (datetimeInterval ((2013, 3, 25, 0, 0, 0), (2013, 4, 1, 0, 0, 0)) Day)
[ "fin mars"
, "fin du mois de mars"
]
, examples (datetimeInterval ((2013, 4, 1, 0, 0, 0), (2013, 4, 6, 0, 0, 0)) Day)
[ "début avril"
, "début du mois d'avril"
]
, examples (datetimeInterval ((2013, 4, 1, 0, 0, 0), (2013, 4, 15, 0, 0, 0)) Day)
[ "la première quinzaine d'avril"
]
, examples (datetimeInterval ((2013, 4, 15, 0, 0, 0), (2013, 5, 1, 0, 0, 0)) Day)
[ "la deuxième quinzaine d'avril"
]
, examples (datetimeInterval ((2013, 4, 1, 0, 0, 0), (2013, 4, 6, 0, 0, 0)) Day)
[ "début avril"
, "début du mois d'avril"
]
, examples (datetimeInterval ((2013, 12, 10, 0, 0, 0), (2013, 12, 20, 0, 0, 0)) Day)
[ "mi-décembre"
]
, examples (datetime (2013, 3, 0, 0, 0, 0) Month)
[ "mars"
, "en mars"
, "au mois de mars"
, "le mois de mars"
]
, examples (datetime (2013, 8, 15, 0, 0, 0) Day)
[ "jeudi 15"
]
, examples (datetime (2013, 8, 15, 8, 0, 0) Hour)
[ "jeudi 15 à 8h"
]
]
|
rfranek/duckling
|
Duckling/Time/FR/Corpus.hs
|
bsd-3-clause
| 28,593 | 0 | 11 | 11,884 | 8,909 | 5,464 | 3,445 | 583 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Data.Monoid (mconcat)
main = scotty 3000 $ do
get "/:word" $ do
beam <- param "word"
html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"]
|
jhedev/sloppy-test
|
app/Main.hs
|
bsd-3-clause
| 212 | 0 | 13 | 45 | 68 | 34 | 34 | 7 | 1 |
module LambdaQuest.LetPoly.PrettyPrint
(prettyPrintTypeP
,prettyPrintType
,prettyPrintTypeSchemeP
,prettyPrintTermP
,prettyPrintTerm
) where
import LambdaQuest.LetPoly.Type
import LambdaQuest.LetPoly.Parse (NameBinding(..))
varNames :: [NameBinding] -> [String]
varNames = foldr (\x ys -> case x of
NVarBind n -> n:ys
_ -> ys) []
tyVarNames :: [NameBinding] -> [String]
tyVarNames = foldr (\x ys -> case x of
NTyVarBind n -> n:ys
_ -> ys) []
rename :: [String] -> String -> String
rename ctx name | name `notElem` ctx = name
| otherwise = loop 1
where loop :: Int -> String
loop i = case name ++ show i of
m | m `notElem` ctx -> m
_ -> loop (i + 1)
-- <2>: Int | Real | Bool | <type variable> | <0>
-- <1>: <2> -> <1>
-- <0>: forall a. <0>
prettyPrintTypeP :: (Show a) => Int -> [NameBinding] -> TypeT a -> ShowS
prettyPrintTypeP p ctx t = case t of
TyPrim PTyInt -> showString "Int"
TyPrim PTyReal -> showString "Real"
TyPrim PTyBool -> showString "Bool"
TyPrim PTyUnit -> showString "Unit"
TyArr s t -> showParen (p > 1) $ prettyPrintTypeP 2 ctx s . showString " -> " . prettyPrintTypeP 1 (NAnonymousBind : ctx) t
TyRef i | i < length ctx -> case ctx !! i of
NTyVarBind n -> showString n
n -> showString "<invalid type variable reference #" . shows i . showString ": " . shows n . showChar '>'
| otherwise -> showString "<invalid reference #" . shows i . showString ", index out of range>"
-- TyAll name t -> let name' = rename (tyVarNames ctx) name
-- in showParen (p > 0) $ showString "forall " . showString name' . showString ". " . prettyPrintTypeP 0 (NTyVarBind name' : ctx) t
TyExtra x -> showsPrec p x
prettyPrintTypeSchemeP :: (Show a) => Int -> [NameBinding] -> TypeSchemeT a -> ShowS
prettyPrintTypeSchemeP p ctx sc = case sc of
Monotype ty -> prettyPrintTypeP p ctx ty
TyScAll sc -> showParen (p > 0) $ showString "forall " . showString name' . showString ". " . prettyPrintTypeSchemeP 0 (NTyVarBind name' : ctx) sc
where name' = rename (tyVarNames ctx) "a"
prettyPrintType :: (Show a) => TypeT a -> String
prettyPrintType t = prettyPrintTypeP 0 [] t ""
-- <2>: <primitive> | <variable> | (<0>)
-- <1>: <1> <2> | <1> [ty]
-- <0>: \x:t. <0> | ?a. <0> | let x = <0> in <0> | if <0> then <0> else <0>
prettyPrintTermP :: (Show a) => Int -> [NameBinding] -> TermT a -> ShowS
prettyPrintTermP p ctx t = case t of
TPrimValue (PVInt x) -> shows x
TPrimValue (PVReal x) -> shows x
TPrimValue (PVBool x) -> shows x
TPrimValue PVUnit -> showString "unit"
TPrimValue (PVBuiltinUnary f) -> showString $ case f of
BNegateInt -> "negateInt"
BNegateReal -> "negateReal"
BIntToReal -> "intToReal"
TPrimValue (PVBuiltinBinary f) -> showString $ case f of
BAddInt -> "addInt"
BSubInt -> "subInt"
BMulInt -> "mulInt"
BLtInt -> "ltInt"
BLeInt -> "leInt"
BEqualInt -> "equalInt"
BAddReal -> "addReal"
BSubReal -> "subReal"
BMulReal -> "mulReal"
BDivReal -> "divReal"
BLtReal -> "ltReal"
BLeReal -> "leReal"
BEqualReal -> "equalReal"
TAbs name ty body -> let name' = rename (varNames ctx) name
in showParen (p > 0) $ showChar '\\' . showString name' . showChar ':' . prettyPrintTypeP 1 ctx ty . showString ". " . prettyPrintTermP 0 (NVarBind name' : ctx) body
-- TTyAbs name body -> let name' = rename (tyVarNames ctx) name
-- in showParen (p > 0) $ showString "?" . showString name' . showString ". " . prettyPrintTermP 0 (NTyVarBind name' : ctx) body
TRef i _ | i < length ctx -> case ctx !! i of
NVarBind n -> showString n
n -> showString "<invalid variable reference #" . shows i . showString ": " . shows n . showChar '>'
| otherwise -> showString "<invalid variable reference #" . shows i . showString ", index out of range>"
TApp u v -> showParen (p > 1) $ prettyPrintTermP 1 ctx u . showChar ' ' . prettyPrintTermP 2 ctx v
-- TTyApp u t -> showParen (p > 1) $ prettyPrintTermP 1 ctx u . showString " [" . prettyPrintTypeP 0 ctx t . showChar ']'
TLet name def body -> let name' = rename (varNames ctx) name
in showParen (p > 0) $ showString "let " . showString name' . showString " = " . prettyPrintTermP 0 ctx def . showString " in " . prettyPrintTermP 0 (NVarBind name' : ctx) body
TIf cond then_ else_ -> showParen (p > 0) $ showString "if " . prettyPrintTermP 0 ctx cond . showString " then " . prettyPrintTermP 0 ctx then_ . showString " else " . prettyPrintTermP 0 ctx else_
prettyPrintTerm :: (Show a) => TermT a -> String
prettyPrintTerm t = prettyPrintTermP 0 [] t ""
|
minoki/LambdaQuest
|
src/LambdaQuest/LetPoly/PrettyPrint.hs
|
bsd-3-clause
| 4,913 | 0 | 18 | 1,341 | 1,485 | 718 | 767 | 78 | 26 |
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell, Rank2Types, ScopedTypeVariables #-}
{-# OPTIONS -Wall #-}
module TuringMachine.State (
TMState(TMState),
-- TMState1, initialTMState, TMTrans, compile,
--TMState2, initialTMState2, TMTrans2, compile2,
TMStaten, initialTMStaten, TMTransn, gcompile, translate
) where
import Basic.Types
import Basic.Memory
import Basic.Features
import Control.Lens
---------------------------------------------------------------------
---- Turing Machine State
---------------------------------------------------------------------
----------------------------------------------------------------------
-- 5.1 State of Turing Machine
-- q - type of states
-- t - type of characters on tape
-- tape - container type of type (should be of class FixedTape/MoveTape)
data TMState tap qs = TMState {_tape :: tap, _ir :: qs}
makeLenses ''TMState
{- This is not actually used anywhere! This implies a lack of generality.-}
instance HasMemory (TMState tap qs) where
type Memory (TMState tap qs) = tap
memory = tape
instance HasQ (TMState tap qs) where
type Q (TMState tap qs) = qs
q = ir
----------------------------------------------------------------------
-- Generic Compile Function (with n tapes and n threads)
----------------------------------------------------------------------
type TMStaten n map t tape qs = TMState (map n (tape t)) qs
initialTapen :: (Ord a, Pointed v, FixedTape s, MapLike map) =>
v -> map a (s v) -> map a (s v)
initialTapen v mapn = mapWithKeyM mapn (\_ _ -> tapewrite inited v)
initialTMStaten :: (FixedTape tape, Pointed t1, Ord i, Enum i,
Bounded i, InitMapLike map) => t1 -> qs -> TMStaten i map t1 tape qs
initialTMStaten v1 st = TMState (initialTapen v1 initM) st
-- Convert between the more traditional representation of a TM and
-- a more 'universal' representation:
type TMTransn m n a b d = a -> m n b -> (a, m n b, m n d)
gcompile :: (Ord a, HasQ st, HasMemory st, MoveTape s d,
MapLike m1, MapLike m2, MapLike m3, Memory st ~ m2 a (s v)) =>
(Q st -> m2 a v -> (Q st, m1 a v, m3 a d)) -> Trans x st
gcompile f = Trans g
where g _ st = q .~ qs' $ memory %~ (tapeoperate v' d') $ st
where v = mapWithKeyM (st^.memory) (\_ -> taperead)
(qs', v', d') = f (st^.q) v
tapeoperate vals moves tapmap = mapWithKeyM tapmap sop
where sop k tp = tapemove d $ tapewrite tp $ lookupM vals k
where d = lookupM moves k
translate :: forall a b d m n. (Ord n, Bounded n, Enum n, AscListLike m) =>
(a -> [b] -> (a, [b], [d])) -> TMTransn m n a b d
translate f q0 vals = (q', mapFromL (minBound::n) vals', mapFromL (minBound::n) dirs)
where
(q', vals', dirs) = f q0 v
v = map snd $ mapToL vals
|
davidzhulijun/TAM
|
TuringMachine/State.hs
|
bsd-3-clause
| 2,847 | 2 | 13 | 596 | 879 | 476 | 403 | 44 | 1 |
{-# LANGUAGE CPP, ScopedTypeVariables, OverloadedStrings, LambdaCase #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Leksah
-- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GNU-GPL
--
-- Maintainer : <maintainer at leksah.org>
-- Stability : provisional
-- Portability : portable
--
--
-- Main function of Leksah, an Haskell IDE written in Haskell
--
---------------------------------------------------------------------------------
module IDE.Leksah (
leksah
) where
import Graphics.UI.Gtk
import Control.Concurrent
import Data.IORef
import Data.Maybe
import qualified Data.Map as Map
import System.Console.GetOpt
import System.Environment
import Data.Version
import Prelude hiding(catch)
import qualified IDE.OSX as OSX
import qualified IDE.YiConfig as Yi
#ifdef LEKSAH_WITH_YI_DYRE
import System.Directory (getAppUserDataDirectory)
import System.FilePath ((</>))
import Control.Applicative ((<$>))
import qualified Config.Dyre as Dyre
#endif
import IDE.Session
import IDE.Core.State
import Control.Event
import IDE.SourceCandy
import IDE.Utils.FileUtils
import Graphics.UI.Editor.MakeEditor
import Graphics.UI.Editor.Parameters
import IDE.Command
import IDE.Preferences
import IDE.Keymap
import IDE.Pane.SourceBuffer
import IDE.Find
import Graphics.UI.Editor.Composite (filesEditor, maybeEditor)
import Graphics.UI.Editor.Simple
(stringEditor, enumEditor, textEditor)
import IDE.Metainfo.Provider (initInfo)
import IDE.Workspaces
(workspaceAddPackage', workspaceTryQuiet, workspaceNewHere,
workspaceOpenThis, backgroundMake)
import IDE.Utils.GUIUtils
import Network (withSocketsDo)
import Control.Exception
import System.Exit(exitFailure)
import qualified IDE.StrippedPrefs as SP
import IDE.Utils.Tool (runTool, toolline, waitForProcess)
import System.Log
import System.Log.Logger
(getLevel, getRootLogger, debugM, updateGlobalLogger,
rootLoggerName, setLevel)
import Data.List (stripPrefix)
import System.Directory
(doesDirectoryExist, copyFile, createDirectoryIfMissing,
getHomeDirectory, doesFileExist)
import System.FilePath (dropExtension, splitExtension, (</>))
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Data.Conduit (($$))
import Control.Monad (void, when, unless, liftM)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Applicative ((<$>))
import qualified Data.Text as T (pack, unpack, stripPrefix, unlines)
import Data.Text (Text)
import Data.Monoid ((<>))
import Graphics.UI.Gtk.General.CssProvider
(cssProviderLoadFromString, cssProviderNew)
import Graphics.UI.Gtk.General.StyleContext
(styleContextAddProviderForScreen)
import qualified Data.Sequence as Seq (empty)
-- --------------------------------------------------------------------
-- Command line options
--
data Flag = VersionF | SessionN Text | EmptySession | DefaultSession | Help | Verbosity Text
deriving (Show,Eq)
options :: [OptDescr Flag]
options = [Option "e" ["emptySession"] (NoArg EmptySession)
"Start with empty session"
, Option "d" ["defaultSession"] (NoArg DefaultSession)
"Start with default session (can be used together with a source file)"
, Option "l" ["loadSession"] (ReqArg (SessionN . T.pack) "NAME")
"Load session"
, Option "h" ["help"] (NoArg Help)
"Display command line options"
, Option "v" ["version"] (NoArg VersionF)
"Show the version number of ide"
, Option "e" ["verbosity"] (ReqArg (Verbosity . T.pack) "Verbosity")
"One of DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY"]
header = "Usage: leksah [OPTION...] [file(.lkshs|.lkshw|.hs|.lhs)]"
ideOpts :: [Text] -> IO ([Flag], [Text])
ideOpts argv =
case getOpt Permute options $ map T.unpack argv of
(o,n,[] ) -> return (o,map T.pack n)
(_,_,errs) -> ioError $ userError $ concat errs ++ usageInfo header options
-- ---------------------------------------------------------------------
-- | Main function
--
#ifdef LEKSAH_WITH_YI_DYRE
leksahDriver = Dyre.wrapMain Dyre.defaultParams
{ Dyre.projectName = "yi"
, Dyre.realMain = \(config, mbError) -> do
case mbError of
Just error -> putStrLn $ "Error in yi configuration file : " ++ error
Nothing -> return ()
realMain config
, Dyre.showError = \(config, _) error -> (config, Just error)
, Dyre.configDir = Just . getAppUserDataDirectory $ "yi"
, Dyre.cacheDir = Just $ ((</> "leksah") <$> (getAppUserDataDirectory "cache"))
, Dyre.hidePackages = ["mtl"]
, Dyre.ghcOpts = ["-DLEKSAH"]
}
leksah yiConfig = leksahDriver (yiConfig, Nothing)
#else
leksah = realMain
#endif
realMain yiConfig =
withSocketsDo $ handleExceptions $ do
dataDir <- getDataDir
args <- getArgs
(o,files) <- ideOpts $ map T.pack args
isFirstStart <- liftM not $ hasSavedConfigFile standardPreferencesFilename
let sessions = mapMaybe (\case
SessionN s -> Just s
_ -> Nothing) o
let sessionFPs = filter (\f -> snd (splitExtension f) == leksahSessionFileExtension) $ map T.unpack files
let workspaceFPs = filter (\f -> snd (splitExtension f) == leksahWorkspaceFileExtension) $ map T.unpack files
let sourceFPs = filter (\f -> let (_,s) = splitExtension f
in s == ".hs" || s == ".lhs" || s == ".chs") $ map T.unpack files
let mbWorkspaceFP'= case workspaceFPs of
[] -> Nothing
w:_ -> Just w
(mbWSessionFP, mbWorkspaceFP) <-
case mbWorkspaceFP' of
Nothing -> return (Nothing,Nothing)
Just fp -> let spath = dropExtension fp ++ leksahSessionFileExtension
in do
exists <- liftIO $ doesFileExist spath
if exists
then return (Just spath,Nothing)
else return (Nothing,Just fp)
let ssession = case sessions of
(s:_) -> T.unpack s <> leksahSessionFileExtension
_ -> if null sourceFPs
then standardSessionFilename
else emptySessionFilename
sessionFP <- if EmptySession `elem` o
then getConfigFilePathForLoad
emptySessionFilename Nothing dataDir
else if DefaultSession `elem` o
then getConfigFilePathForLoad
standardSessionFilename Nothing dataDir
else case mbWSessionFP of
Just fp -> return fp
Nothing -> getConfigFilePathForLoad
ssession Nothing dataDir
let verbosity' = mapMaybe (\case
Verbosity s -> Just s
_ -> Nothing) o
let verbosity = case verbosity' of
[] -> INFO
h:_ -> read $ T.unpack h
updateGlobalLogger rootLoggerName (setLevel verbosity)
when (VersionF `elem` o)
(sysMessage Normal $ "Leksah the Haskell IDE, version " <> T.pack (showVersion version))
when (Help `elem` o)
(sysMessage Normal $ "Leksah the Haskell IDE " <> T.pack (usageInfo header options))
prefsPath <- getConfigFilePathForLoad standardPreferencesFilename Nothing dataDir
prefs <- readPrefs prefsPath
when (notElem VersionF o && notElem Help o)
(startGUI yiConfig sessionFP mbWorkspaceFP sourceFPs prefs isFirstStart)
handleExceptions inner =
catch inner (\(exception :: SomeException) -> do
sysMessage Normal ("leksah: internal IDE error: " <> T.pack (show exception))
exitFailure
)
-- ---------------------------------------------------------------------
-- | Start the GUI
startGUI :: Yi.Config -> FilePath -> Maybe FilePath -> [FilePath] -> Prefs -> Bool -> IO ()
startGUI yiConfig sessionFP mbWorkspaceFP sourceFPs iprefs isFirstStart =
Yi.start yiConfig $ \yiControl -> do
st <- unsafeInitGUIForThreadedRTS
timeout <- if rtsSupportsBoundThreads
then do
setNumCapabilities 2
sysMessage Normal "Linked with -threaded"
return Nothing
else Just <$> timeoutAddFull (yield >> return True) priorityLow 10
mbScreen <- screenGetDefault
case mbScreen of
Just screen -> do
provider <- cssProviderNew
cssProviderLoadFromString provider $
T.unlines [ ".window-frame,"
, ".window-frame:backdrop {"
, " box-shadow: none;"
, " margin: 0;}"
, "#errorLabel {"
, " padding: 10px;"
, " background: #F2DEDE;"
, " color: #A94442;"
, " border: 1px solid #EBCCD1;"
, " border-radius: 5px;}"
]
styleContextAddProviderForScreen screen provider 600
Nothing -> debugM "leksah" "Unable to add style provider for screen"
mapM_ (sysMessage Normal . T.pack) st
dataDir <- getDataDir
mbStartupPrefs <- if not isFirstStart
then return $ Just iprefs
else do
firstStartOK <- firstStart iprefs
if not firstStartOK
then return Nothing
else do
prefsPath <- getConfigFilePathForLoad standardPreferencesFilename Nothing dataDir
prefs <- readPrefs prefsPath
return $ Just prefs
maybe (return ()) timeoutRemove timeout
postGUIAsync $
case mbStartupPrefs of
Nothing -> return ()
Just startupPrefs -> startMainWindow yiControl sessionFP mbWorkspaceFP sourceFPs
startupPrefs isFirstStart
debugM "leksah" "starting mainGUI"
mainGUI
debugM "leksah" "finished mainGUI"
mainLoop :: IO () -> IO ()
mainLoop = mainLoopSingleThread
mainLoopThreaded :: IO () -> IO ()
mainLoopThreaded onIdle = loop
where
loop = do
quit <- loopTillIdle
unless quit $ do
active <- newEmptyMVar
mvarSentIdleMessage <- newEmptyMVar
idleThread <- forkIO $ do
threadDelay 200000
isActive <- isJust <$> tryTakeMVar active
unless isActive $ do
putMVar mvarSentIdleMessage ()
postGUIAsync onIdle
quit <- mainIteration
putMVar active ()
unless quit $ do
-- If an idle message was sent then wait again
sentIdleMessage <- isJust <$> tryTakeMVar mvarSentIdleMessage
quit <- if sentIdleMessage
then mainIteration
else return False
unless quit loop
loopTillIdle = do
pending <- eventsPending
if pending == 0
then return False
else do
quit <- loopn (pending + 2)
if quit
then return True
else loopTillIdle
mainLoopSingleThread :: IO () -> IO ()
mainLoopSingleThread onIdle = eventsPending >>= loop False 50
where
loop :: Bool -> Int -> Int -> IO ()
loop False delay 0 | delay > 2000 = onIdle >> loop True delay 0
loop isIdle delay n = do
quit <- if n > 0
then do
timeout <- timeoutAddFull (yield >> return True) priorityLow 10
quit <- loopn (n+2)
timeoutRemove timeout
return quit
else
loopn (n+2)
unless quit $ do
yield
pending <- eventsPending
if pending > 0
then loop False 50 pending
else do
threadDelay delay
eventsPending >>= loop isIdle (if n > 0
then 50
else min (delay+delay) 50000)
loopn :: Int -> IO Bool
loopn 0 = return False
loopn n = do
quit <- mainIterationDo False
if quit
then return True
else loopn (n - 1)
startMainWindow :: Yi.Control -> FilePath -> Maybe FilePath -> [FilePath] ->
Prefs -> Bool -> IO ()
startMainWindow yiControl sessionFP mbWorkspaceFP sourceFPs startupPrefs isFirstStart = do
timeout <- if rtsSupportsBoundThreads
then return Nothing
else Just <$> timeoutAddFull (yield >> return True) priorityLow 10
debugM "leksah" "startMainWindow"
osxApp <- OSX.applicationNew
uiManager <- uiManagerNew
newIcons
dataDir <- getDataDir
candyPath <- getConfigFilePathForLoad
(case sourceCandy startupPrefs of
(_,name) -> T.unpack name <> leksahCandyFileExtension) Nothing dataDir
candySt <- parseCandy candyPath
-- keystrokes
keysPath <- getConfigFilePathForLoad (T.unpack (keymapName startupPrefs) <> leksahKeymapFileExtension) Nothing dataDir
keyMap <- parseKeymap keysPath
let accelActions = setKeymap (keyMap :: KeymapI) mkActions
specialKeys <- buildSpecialKeys keyMap accelActions
win <- windowNew
widgetSetName win ("Leksah Main Window"::Text)
let fs = FrameState
{ windows = [win]
, uiManager = uiManager
, panes = Map.empty
, activePane = Nothing
, paneMap = Map.empty
, layout = TerminalP Map.empty Nothing (-1) Nothing Nothing
, panePathFromNB = Map.empty
}
let ide = IDE
{ frameState = fs
, recentPanes = []
, specialKeys = specialKeys
, specialKey = Nothing
, candy = candySt
, prefs = startupPrefs
, workspace = Nothing
, activePack = Nothing
, activeExe = Nothing
, bufferProjCache = Map.empty
, allLogRefs = Seq.empty
, currentHist = 0
, currentEBC = (Nothing, Nothing, Nothing)
, systemInfo = Nothing
, packageInfo = Nothing
, workspaceInfo = Nothing
, workspInfoCache = Map.empty
, handlers = Map.empty
, currentState = IsStartingUp
, guiHistory = (False,[],-1)
, findbar = (False,Nothing)
, toolbar = (True,Nothing)
, recentFiles = []
, recentWorkspaces = []
, runningTool = Nothing
, debugState = Nothing
, completion = ((750,400),Nothing)
, yiControl = yiControl
, serverQueue = Nothing
, server = Nothing
, hlintQueue = Nothing
, vcsData = (Map.empty, Nothing)
, logLaunches = Map.empty
, autoCommand = return ()
, autoURI = Nothing
}
ideR <- newIORef ide
menuDescription' <- menuDescription
reflectIDE (makeMenu uiManager accelActions menuDescription') ideR
nb <- reflectIDE (newNotebook []) ideR
after nb switchPage (\i -> reflectIDE (handleNotebookSwitch nb i) ideR)
widgetSetName nb ("root"::Text)
on win deleteEvent . liftIO $ reflectIDE quit ideR >> return True
reflectIDE (instrumentWindow win startupPrefs (castToWidget nb)) ideR
reflectIDE (do
setBackgroundBuildToggled (backgroundBuild startupPrefs)
setRunUnitTests (runUnitTests startupPrefs)
setMakeModeToggled (makeMode startupPrefs)) ideR
let (x,y) = defaultSize startupPrefs
windowSetDefaultSize win x y
(tbv,fbv) <- reflectIDE (do
registerLeksahEvents
pair <- recoverSession sessionFP
workspaceOpenThis False mbWorkspaceFP
mapM_ fileOpenThis sourceFPs
wins <- getWindows
mapM_ instrumentSecWindow (tail wins)
return pair
) ideR
on win realize $ widgetGetWindow win >>= maybe (return ()) OSX.allowFullscreen
debugM "leksah" "Show main window"
widgetShowAll win
reflectIDE (do
triggerEventIDE UpdateRecent
if tbv
then showToolbar
else hideToolbar
if fbv
then showFindbar
else hideFindbar
OSX.updateMenu osxApp uiManager) ideR
OSX.applicationReady osxApp
configDir <- getConfigDir
let welcomePath = configDir</>"leksah-welcome"
welcomeExists <- doesDirectoryExist welcomePath
unless welcomeExists $ do
let welcomeSource = dataDir</>"data"</>"leksah-welcome"
welcomeCabal = welcomePath</>"leksah-welcome.cabal"
welcomeMain = welcomePath</>"src"</>"Main.hs"
createDirectoryIfMissing True $ welcomePath</>"src"
createDirectoryIfMissing True $ welcomePath</>"test"
copyFile (welcomeSource</>"Setup.lhs") (welcomePath</>"Setup.lhs")
copyFile (welcomeSource</>"leksah-welcome.cabal") welcomeCabal
copyFile (welcomeSource</>"LICENSE") (welcomePath</>"LICENSE")
copyFile (welcomeSource</>"src"</>"Main.hs") welcomeMain
copyFile (welcomeSource</>"test"</>"Main.hs") (welcomePath</>"test"</>"Main.hs")
defaultWorkspace <- liftIO $ (</> "leksah.lkshw") <$> getHomeDirectory
defaultExists <- liftIO $ doesFileExist defaultWorkspace
reflectIDE (do
if defaultExists
then workspaceOpenThis False (Just defaultWorkspace)
else workspaceNewHere defaultWorkspace
workspaceTryQuiet $ void (workspaceAddPackage' welcomeCabal)
fileOpenThis welcomeMain) ideR
reflectIDE (initInfo (modifyIDE_ (\ide -> ide{currentState = IsRunning}))) ideR
maybe (return ()) timeoutRemove timeout
postGUIAsync . mainLoop $
reflectIDE (do
currentPrefs <- readIDE prefs
when (backgroundBuild currentPrefs) backgroundMake) ideR
-- timeoutAddFull (do
-- reflectIDE (do
-- currentPrefs <- readIDE prefs
-- when (backgroundBuild currentPrefs) $ backgroundMake) ideR
-- return True) priorityDefaultIdle 1000
reflectIDE (triggerEvent ideR (Sensitivity [(SensitivityInterpreting, False)])) ideR
return ()
-- mainGUI
fDescription :: FilePath -> FieldDescription Prefs
fDescription configPath = VFD emptyParams [
mkField
(paraName <<<- ParaName "Paths under which haskell sources for packages may be found"
$ paraDirection <<<- ParaDirection Vertical
$ paraMinSize <<<- ParaMinSize (-1, 150)
$ emptyParams)
sourceDirectories
(\b a -> a{sourceDirectories = b})
(filesEditor Nothing FileChooserActionSelectFolder "Select folders")
, mkField
(paraName <<<- ParaName "Unpack source for cabal packages to" $ emptyParams)
unpackDirectory
(\b a -> a{unpackDirectory = b})
(maybeEditor (stringEditor (const True) True,emptyParams) True "")
, mkField
(paraName <<<- ParaName "URL from which to download prebuilt metadata" $ emptyParams)
retrieveURL
(\b a -> a{retrieveURL = b})
(textEditor (const True) True)
, mkField
(paraName <<<- ParaName "Strategy for downloading prebuilt metadata" $ emptyParams)
retrieveStrategy
(\b a -> a{retrieveStrategy = b})
(enumEditor ["Try to download and then build locally if that fails","Try to build locally and then download if that fails","Never download (just try to build locally)"])]
--
-- | Called when leksah is first called (the .leksah-xx directory does not exist)
--
firstStart :: Prefs -> IO Bool
firstStart prefs = do
dataDir <- getDataDir
prefsPath <- getConfigFilePathForLoad standardPreferencesFilename Nothing dataDir
prefs <- readPrefs prefsPath
configDir <- getConfigDir
dialog <- dialogNew
setLeksahIcon dialog
set dialog [
windowTitle := ("Welcome to Leksah, the Haskell IDE"::Text),
windowWindowPosition := WinPosCenter]
dialogAddButton dialog ("gtk-ok"::Text) ResponseOk
dialogAddButton dialog ("gtk-cancel"::Text) ResponseCancel
vb <- dialogGetContentArea dialog
label <- labelNew (Just (
"Before you start using Leksah it will collect and download metadata about your installed Haskell packages.\n" <>
"You can add folders under which you have sources for Haskell packages not available from Hackage."::Text))
(widget, setInj, getExt,notifier) <- buildEditor (fDescription configDir) prefs
boxPackStart (castToBox vb) label PackNatural 7
sw <- scrolledWindowNew Nothing Nothing
scrolledWindowAddWithViewport sw widget
scrolledWindowSetPolicy sw PolicyNever PolicyAutomatic
boxPackStart (castToBox vb) sw PackGrow 7
windowSetDefaultSize dialog 800 630
widgetShowAll dialog
response <- dialogRun dialog
widgetHide dialog
case response of
ResponseOk -> do
mbNewPrefs <- extract prefs [getExt]
widgetDestroy dialog
case mbNewPrefs of
Nothing -> do
sysMessage Normal "No dialog results"
return False
Just newPrefs -> do
fp <- getConfigFilePathForSave standardPreferencesFilename
writePrefs fp newPrefs
fp2 <- getConfigFilePathForSave strippedPreferencesFilename
SP.writeStrippedPrefs fp2
SP.Prefs {SP.sourceDirectories = sourceDirectories newPrefs,
SP.unpackDirectory = unpackDirectory newPrefs,
SP.retrieveURL = retrieveURL newPrefs,
SP.retrieveStrategy = retrieveStrategy newPrefs,
SP.serverPort = serverPort newPrefs,
SP.endWithLastConn = endWithLastConn newPrefs}
firstBuild newPrefs
return True
_ -> do
widgetDestroy dialog
return False
setLeksahIcon :: (WindowClass self) => self -> IO ()
setLeksahIcon window = do
dataDir <- getDataDir
let iconPath = dataDir </> "pics" </> "leksah.png"
iconExists <- doesFileExist iconPath
when iconExists $
windowSetIconFromFile window iconPath
firstBuild newPrefs = do
dialog <- dialogNew
setLeksahIcon dialog
set dialog [
windowTitle := ("Leksah: Updating Metadata"::Text),
windowWindowPosition := WinPosCenter,
windowDeletable := False]
vb <- dialogGetContentArea dialog
progressBar <- progressBarNew
progressBarSetText progressBar ("Please wait while Leksah collects information about Haskell packages on your system"::Text)
progressBarSetFraction progressBar 0.0
boxPackStart (castToBox vb) progressBar PackGrow 7
forkIO $ do
logger <- getRootLogger
let verbosity = case getLevel logger of
Just level -> ["--verbosity=" <> T.pack (show level)]
Nothing -> []
(output, pid) <- runTool "leksah-server" (["-sbo", "+RTS", "-N2", "-RTS"] ++ verbosity) Nothing
output $$ CL.mapM_ (update progressBar)
waitForProcess pid
postGUIAsync (dialogResponse dialog ResponseOk)
widgetShowAll dialog
dialogRun dialog
widgetHide dialog
widgetDestroy dialog
return ()
where
update pb to = do
let str = toolline to
case T.stripPrefix "update_toolbar " str of
Just rest -> postGUIAsync $ progressBarSetFraction pb (read $ T.unpack rest)
Nothing -> liftIO $ debugM "leksah" $ T.unpack str
|
jaccokrijnen/leksah
|
src/IDE/Leksah.hs
|
gpl-2.0
| 25,932 | 0 | 21 | 9,151 | 5,764 | 2,933 | 2,831 | 497 | 12 |
-- this example show a image gallery. It advances each 20 seconds and by pressing the button
{-# LANGUAGE DeriveDataTypeable #-}
import Haste.HPlay.View
import Data.Typeable
import Control.Applicative
newtype GalleryIndex= G Int deriving Typeable
main= runBody gallery
gallery :: Widget ()
gallery = p "this example show a image gallery. It advances each 20 seconds and by\
\ pressing the button" ++>
(wtimeout 20000 $ do
G i <- getSData <|> return (G 0)
let i' = if i == length gall-1 then 0 else i+1
setSData $ G i'
wraw $ do
img ! src (gall !! i) ! width "100%" ! height "100%" -- raw Perch code
br
submitButton ">" `fire` OnClick
`wcallback` \_ -> gallery)
where
gall=["http://almaer.com/blog/uploads/interview-haskell.png"
,"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQmmC4kV3NPFIpGL_x4H_iHG_p-c93DGjWfkxVtjxEFVng7A8o-nw"
,"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ_ywj-zxDq3h_B4l48XHsjTywrdbK5egxvhxkYJ1HOkDFXd_-H"
,"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcS53axpzkDyzEUAdaIP3YsaHuR-_YqN9qFK3W4bp_D2OBZfW5BU_Q"
,"https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSfP70npv4FOrkBjScP0tVu2t3veSNoFQ6MMxX6LDO8kldNeu-DxQ"
,"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRAgKkpDyzk8kdIqk5ECsZ14XgbpBzyWFvrCrHombkSBAUn6jFo"
]
|
agocorona/tryhplay
|
examples/gallery.hs
|
gpl-3.0
| 1,372 | 0 | 19 | 221 | 225 | 117 | 108 | 24 | 2 |
<?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="ro-RO">
<title>Replacer | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/replacer/src/main/javahelp/org/zaproxy/zap/extension/replacer/resources/help_ro_RO/helpset_ro_RO.hs
|
apache-2.0
| 970 | 80 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
module CoinJam where
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Prime
import Data.Maybe
getCoinJam :: String -> String
getCoinJam x = getCoinJamByNum y z
where datas = words x
y = read (head datas)::Int
z = read (last datas)::Int
getCoinJamByNum :: Int -> Int -> String
getCoinJamByNum x y =
let datas = fmap (\x -> (1:x)++[1]) $ getPosibleList (x-2)
ss = Set.fromList [2,3,5,7,11,13,17,19]
s = PrimeRepo {primeSet=ss, maxChecked=20}
rets = take y $ filter (\x -> isJust (snd (snd x))) $ fmap (isCoinJam s) datas
in show rets
--take 3 $ snd $ mapAccumL isCoinJam s $ getPosibleList 6
getPosibleList :: Int -> [[Int]]
getPosibleList x = fmap (\y -> (1:y)++[1]) (sequence $ replicate (x-2) [0,1])
isCoinJam :: PrimeRepo-> [Int] -> (PrimeRepo, (String, Maybe [Int]))
isCoinJam s xs =
let ms = fmap (getPowerNumber xs) [2..10]
(ss,ys) = mapAccumL getDivisorNum s ms
in (ss, (concat (fmap show xs), sequence $ ys))
getDivisorNum:: PrimeRepo -> Int -> (PrimeRepo, Maybe Int)
getDivisorNum s x = (z, y)
where (y,z) = runWithScope x s
getPowerNumber :: [Int] -> Int -> Int
getPowerNumber xs y = sum $ fmap (\(a,b) -> if b==0 then 0 else y ^ a) $ zip [0..(length xs + 1)] (reverse xs)
|
lihlcnkr/codejam
|
src/QR/CoinJam.hs
|
apache-2.0
| 1,285 | 0 | 18 | 281 | 626 | 342 | 284 | 30 | 2 |
{- |
Module : $Header$
Description : symbol map analysis for the CASL logic.
Copyright : (c) Till Mossakowski, C. Maeder and Uni Bremen 2002-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Symbol map analysis for the CASL logic.
Follows Sect. III:4.1 of the CASL Reference Manual.
-}
module CASL.SymbolMapAnalysis
( inducedFromMorphism
, inducedFromToMorphism
, inducedFromMorphismExt
, inducedFromToMorphismExt
, cogeneratedSign
, generatedSign
, finalUnion
, constMorphExt
, revealSym
, profileContainsSort
) where
import CASL.Sign
import CASL.AS_Basic_CASL
import CASL.Morphism
import CASL.Overload (leqF, leqP)
import qualified Common.Lib.MapSet as MapSet
import qualified Common.Lib.Rel as Rel
import Common.Doc
import Common.DocUtils
import Common.ExtSign
import Common.Id
import Common.Result
import Data.List (partition, find)
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
{-
inducedFromMorphism :: RawSymbolMap -> sign -> Result morphism
Here is Bartek Klin's algorithm that has benn used for CATS.
Our algorithm deviates from it. The exact details need to be checked.
Inducing morphism from raw symbol map and signature
Input: raw symbol map "Rsm"
signature "Sigma1"
Output: morphims "Mrph": Sigma1 -> "Sigma2".
//preparation
1. let "Ssm" be an empty list of pairs (symbol, raw symbol).
2. for each pair "Rsym1,Rsym2" in Rsm do:
2.1. if there is no symbol in Sigma1 matching Rsym1, return error.
2.2. for each symbol "Sym" from Sigma1 matching Rsym1
2.2.1. add a pair "Sym,Rsym2" to Ssm.
//computing the "sort part" of the morphism
3. let Sigma2 be an empty signature.
4. let Mrph be an empty "morphism" from Sigma1 to Sigma2.
5. for each pair "Sym,Rsym2" in Ssm such that Sym is a sort symbol
5.1. if Rsym2 is not a sort raw symbol, return error.
5.2. if in Mrph there is a mapping of sort in Sym to sort with
name other than that in Rsym2, return error.
5.3. if in Mrph there is no mappinh of sort in Sym
5.3.1. add sort from Rsym2 to Sigma2
5.3.2. add mapping from sort(Sym) to sort(Rsym2) to Mrph.
6. for each sort symbol "S" in Sigma1
6.1. if S is not mapped by Mrph,
6.1.1. add sort S to Sigma2
6.1.2. add mapping from S to S to Mrph.
//computing the "function/predicate part" of the morphism
7. for each pair "Sym,Rsym2" in Ssm such that Sym is a function/predicate
symbol
7.1. let "F" be name contained in Sym, let "Fprof" be the profile.
7.2. let "Fprof1" be the value of Fprof via Mrph
(it can be computed, as we already have the "sort" part of
morphism)
7.3. if Rsym2 is not of appriopriate type, return error, otherwise
let "F2" be the name of the symbol.
7.4. if Rsym2 enforces the profile of the symbol (i.e., it is not
an implicit symbol), compare the profile to Fprof1. If it is
not equal, return error.
7.5. if in Mrph there is a mapping of F1 with profile Fprof to
some name different than F2, return error.
7.6. add an operation/predicate with name F2 and profile Fprof1 to
Sigma2. If it is a partial function and if in Sigma2 there
exists a total function with the same name and profile, do not
add it. Otherwise if it is a total function and if in Sigma2
there exists a partial function with the same name and profile,
add the total function removing the partial one.
7.7. add to Mrph a mapping from operation/predicate of name F1 and
profile Fprof to name F2.
8. for each operation/predicate symbol "F" with profile "Fprof" in Sigma1
that is not mapped by Mrph,
8.1. as in 7.2
8.2. as in 7.6, replacing F2 with F1.
8.3. as in 7.7, replacing F2 with F1.
9. for each sort relation "S1,S2" in Sigma1,
9.1. compute S3=(S1 via Mrph) and S4=(S2 via Mrph)
9.2. add sort relation "S3,S4" in Sigma2.
10. Compute transitive closure of subsorting relation in Sigma2.
-}
type InducedMorphism e m = RawSymbolMap -> e -> Result m
constMorphExt :: m -> InducedMorphism e m
constMorphExt m _ _ = return m
{- | function and preds in the overloading relation are mapped in the same way
thus preserving the overload-relation -}
inducedFromMorphism :: (Pretty e, Show f) => m -> RawSymbolMap -> Sign f e
-> Result (Morphism f e m)
inducedFromMorphism =
inducedFromMorphismExt (\ _ _ _ _ -> extendedInfo) . constMorphExt
inducedFromMorphismExt :: (Pretty e, Show f) => InducedSign f e m e
-> InducedMorphism e m
-> RawSymbolMap -> Sign f e -> Result (Morphism f e m)
inducedFromMorphismExt extInd extEm rmap sigma = do
-- compute the sort map (as a Map)
sort_Map <- Set.fold (\ s m -> do
s' <- sortFun rmap s
m1 <- m
return $ if s' == s then m1 else Map.insert s s' m1)
(return Map.empty) (sortSet sigma)
-- compute the op map (as a Map)
op_Map <- Map.foldWithKey (opFun sigma rmap sort_Map)
(return Map.empty) (MapSet.toMap $ opMap sigma)
-- compute the pred map (as a Map)
pred_Map <- Map.foldWithKey (predFun sigma rmap sort_Map)
(return Map.empty) (MapSet.toMap $ predMap sigma)
em <- extEm rmap $ extendedInfo sigma
-- return assembled morphism
return (embedMorphism em sigma
$ inducedSignAux extInd sort_Map op_Map pred_Map em sigma)
{ sort_map = sort_Map
, op_map = op_Map
, pred_map = pred_Map }
{- the sorts of the source signature
sortFun is the sort map as a Haskell function -}
sortFun :: RawSymbolMap -> Id -> Result Id
sortFun rmap s
-- rsys contains the raw symbols to which s is mapped to
| Set.null rsys = return s -- use default = identity mapping
| Set.null $ Set.deleteMin rsys =
return $ rawSymName $ Set.findMin rsys -- take the unique rsy
| otherwise = plain_error s -- ambiguity! generate an error
("sort " ++ showId s
" is mapped ambiguously: " ++ showDoc rsys "")
$ getRange rsys
where
-- get all raw symbols to which s is mapped to
rsys = Set.fromList $ mapMaybe (`Map.lookup` rmap)
[ ASymbol $ idToSortSymbol s
, AKindedSymb Implicit s ]
{- to a Op_map, add everything resulting from mapping (id, ots)
according to rmap -}
opFun :: Sign f e -> RawSymbolMap -> Sort_map -> Id -> Set.Set OpType
-> Result Op_map -> Result Op_map
opFun src rmap sort_Map ide ots m =
-- first consider all directly mapped profiles
let otls = Rel.partSet (leqF src) ots
m1 = foldr (directOpMap rmap sort_Map ide) m otls
-- now try the remaining ones with (un)kinded raw symbol
in case (Map.lookup (AKindedSymb Ops_kind ide) rmap,
Map.lookup (AKindedSymb Implicit ide) rmap) of
(Just rsy1, Just rsy2) -> let
m2 = Set.fold (insertmapOpSym sort_Map ide rsy1) m1 ots
in Set.fold (insertmapOpSym sort_Map ide rsy2) m2 ots
(Just rsy, Nothing) ->
Set.fold (insertmapOpSym sort_Map ide rsy) m1 ots
(Nothing, Just rsy) ->
Set.fold (insertmapOpSym sort_Map ide rsy) m1 ots
-- Anything not mapped explicitly is left unchanged
(Nothing, Nothing) -> m1
{- try to map an operation symbol directly
collect all opTypes that cannot be mapped directly -}
directOpMap :: RawSymbolMap -> Sort_map -> Id -> Set.Set OpType
-> Result Op_map -> Result Op_map
directOpMap rmap sort_Map ide ots m =
let ol = Set.toList ots
rl = map (lookupOpSymbol rmap ide) ol
(ms, os) = partition (isJust . fst) $ zip rl ol
in case ms of
l@((Just rsy, _) : rs) ->
foldr (\ (_, ot) ->
insertmapOpSym sort_Map ide
(ASymbol $ idToOpSymbol (rawSymName rsy)
$ mapOpType sort_Map ot) ot)
(foldr (\ (rsy2, ot) ->
insertmapOpSym sort_Map ide (fromJust rsy2) ot) m l)
$ rs ++ os
_ -> m
lookupOpSymbol :: RawSymbolMap -> Id -> OpType -> Maybe RawSymbol
lookupOpSymbol rmap ide' ot = let mkS = idToOpSymbol ide' in
case Map.lookup (ASymbol (mkS $ mkPartial ot)) rmap of
Nothing -> Map.lookup
(ASymbol (mkS $ mkTotal ot)) rmap
res -> res
-- map op symbol (ide, ot) to raw symbol rsy
mappedOpSym :: Sort_map -> Id -> OpType -> RawSymbol -> Result (Id, OpKind)
mappedOpSym sort_Map ide ot rsy =
let opSym = "operation symbol " ++ showDoc (idToOpSymbol ide ot)
" is mapped to "
kind = opKind ot
ot2 = mapOpType sort_Map ot
in case rsy of
ASymbol (Symbol ide' (OpAsItemType ot')) ->
if compatibleOpTypes ot2 ot'
then return (ide', opKind ot')
else plain_error (ide, kind)
(opSym ++ "type " ++ showDoc ot'
" but should be mapped to type " ++
showDoc ot2 "") $ getRange rsy
AKindedSymb k ide' | elem k [Implicit, Ops_kind] -> return (ide', kind)
_ -> plain_error (ide, kind)
(opSym ++ "symbol of wrong kind: " ++ showDoc rsy "")
$ getRange rsy
-- insert mapping of op symbol (ide, ot) to raw symbol rsy into m
insertmapOpSym :: Sort_map -> Id -> RawSymbol -> OpType
-> Result Op_map -> Result Op_map
insertmapOpSym sort_Map ide rsy ot m = do
m1 <- m
(ide', kind') <- mappedOpSym sort_Map ide ot rsy
let otsy = Symbol ide $ OpAsItemType ot
pos = getRange rsy
m2 = Map.insert (ide, mkPartial ot) (ide', kind') m1
case Map.lookup (ide, mkPartial ot) m1 of
Nothing -> if ide == ide' && kind' == opKind ot then
case rsy of
ASymbol _ -> return m1
_ -> hint m1 ("identity mapping of "
++ showDoc otsy "") pos
else return m2
Just (ide'', kind'') -> if ide' == ide'' then
warning (if kind' < kind'' then m2 else m1)
("ignoring duplicate mapping of " ++ showDoc otsy "")
pos
else plain_error m1
("conflicting mapping of " ++ showDoc otsy " to " ++
show ide' ++ " and " ++ show ide'') pos
{- to a Pred_map, add evering resulting from mapping (ide, pts)
according to rmap -}
predFun :: Sign f e -> RawSymbolMap -> Sort_map -> Id -> Set.Set PredType
-> Result Pred_map -> Result Pred_map
predFun src rmap sort_Map ide pts m =
-- first consider all directly mapped profiles
let ptls = Rel.partSet (leqP src) pts
m1 = foldr (directPredMap rmap sort_Map ide) m ptls
-- now try the remaining ones with (un)kinded raw symbol
in case (Map.lookup (AKindedSymb Preds_kind ide) rmap,
Map.lookup (AKindedSymb Implicit ide) rmap) of
(Just rsy1, Just rsy2) -> let
m2 = Set.fold (insertmapPredSym sort_Map ide rsy1) m1 pts
in Set.fold (insertmapPredSym sort_Map ide rsy2) m2 pts
(Just rsy, Nothing) ->
Set.fold (insertmapPredSym sort_Map ide rsy) m1 pts
(Nothing, Just rsy) ->
Set.fold (insertmapPredSym sort_Map ide rsy) m1 pts
-- Anything not mapped explicitly is left unchanged
(Nothing, Nothing) -> m1
{- try to map a predicate symbol directly
collect all predTypes that cannot be mapped directly -}
directPredMap :: RawSymbolMap -> Sort_map -> Id -> Set.Set PredType
-> Result Pred_map -> Result Pred_map
directPredMap rmap sort_Map ide pts m =
let pl = Set.toList pts
rl = map (\ pt -> Map.lookup (ASymbol $ idToPredSymbol ide pt) rmap) pl
(ms, ps) = partition (isJust . fst) $ zip rl pl
in case ms of
l@((Just rsy, _) : rs) ->
foldr (\ (_, pt) ->
insertmapPredSym sort_Map ide
(ASymbol $ idToPredSymbol (rawSymName rsy)
$ mapPredType sort_Map pt) pt)
(foldr (\ (rsy2, pt) ->
insertmapPredSym sort_Map ide (fromJust rsy2) pt) m l)
$ rs ++ ps
_ -> m
-- map pred symbol (ide, pt) to raw symbol rsy
mappedPredSym :: Sort_map -> Id -> PredType -> RawSymbol -> Result Id
mappedPredSym sort_Map ide pt rsy =
let predSym = "predicate symbol " ++ showDoc (idToPredSymbol ide pt)
" is mapped to "
pt2 = mapPredType sort_Map pt
in case rsy of
ASymbol (Symbol ide' (PredAsItemType pt')) ->
if pt2 == pt'
then return ide'
else plain_error ide
(predSym ++ "type " ++ showDoc pt'
" but should be mapped to type " ++
showDoc pt2 "") $ getRange rsy
AKindedSymb k ide' | elem k [Implicit, Preds_kind] -> return ide'
_ -> plain_error ide
(predSym ++ "symbol of wrong kind: " ++ showDoc rsy "")
$ getRange rsy
-- insert mapping of pred symbol (ide, pt) to raw symbol rsy into m
insertmapPredSym :: Sort_map -> Id -> RawSymbol -> PredType
-> Result Pred_map -> Result Pred_map
insertmapPredSym sort_Map ide rsy pt m = do
m1 <- m
ide' <- mappedPredSym sort_Map ide pt rsy
let ptsy = Symbol ide $ PredAsItemType pt
pos = getRange rsy
m2 = Map.insert (ide, pt) ide' m1
case Map.lookup (ide, pt) m1 of
Nothing -> if ide == ide' then
case rsy of
ASymbol _ -> return m1
_ -> hint m1 ("identity mapping of "
++ showDoc ptsy "") pos
else return m2
Just ide'' -> if ide' == ide'' then
warning m1
("ignoring duplicate mapping of " ++ showDoc ptsy "") pos
else plain_error m1
("conflicting mapping of " ++ showDoc ptsy " to " ++
show ide' ++ " and " ++ show ide'') pos
{-
inducedFromToMorphism :: RawSymbolMap -> sign -> sign -> Result morphism
Algorithm adapted from Bartek Klin's algorithm for CATS.
Inducing morphisms from raw symbol map and source and target signature.
This problem is NP-hard (The problem of 3-colouring can be reduced to it).
This means that we have exponential runtime in the worst case.
However, in many cases the runtime can be kept rather short by
using some basic principles of constraint programming.
We use a depth-first search with some weak form of constraint
propagation and MRV (minimum remaining values), see
Stuart Russell and Peter Norvig:
Artificial Intelligence - A Modern Approach.
Prentice Hall International
The algorithm has additionally to take care of default values (i.e.
symbol names are mapped identically be default, and the number of
identitically mapped names should be maximized). Moreover, it does
not suffice to find just one solution, but also its uniqueness
(among those maximizing he number of identitically mapped names)
must be checked (still, MRV is useful here).
The algorithm
Input: raw symbol map "rmap"
signatures "sigma1,sigma2"
Output: morphism "mor": sigma1 -> sigma2
1. compute the morphism mor1 induced by rmap and sigma1 (i.e. the renaming)
1.1. if target mor1 is a subsignature of sigma2, return the composition
of this inclusion with mor1
(cf. Theorem 6 of Bartek Klin's Master's Thesis)
otherwise some heuristics is needed, because merely forgetting one renaming
may lead to unacceptable run-time for signatures with just about 10 symbols
-}
-- the main function
inducedFromToMorphism :: (Eq e, Show f, Pretty e, Pretty m)
=> m -- ^ extended morphism
-> (e -> e -> Bool) -- ^ subsignature test of extensions
-> (e -> e -> e) -- ^ difference of extensions
-> RawSymbolMap
-> ExtSign (Sign f e) Symbol
-> ExtSign (Sign f e) Symbol -> Result (Morphism f e m)
inducedFromToMorphism m =
inducedFromToMorphismExt (\ _ _ _ _ -> extendedInfo) (constMorphExt m)
(\ _ _ -> return m)
inducedFromToMorphismExt
:: (Eq e, Show f, Pretty e, Pretty m)
=> InducedSign f e m e
-> InducedMorphism e m -- ^ compute extended morphism
-> (Morphism f e m -> Morphism f e m -> Result m)
-- ^ composition of extensions
-> (e -> e -> Bool) -- ^ subsignature test of extensions
-> (e -> e -> e) -- ^ difference of extensions
-> RawSymbolMap
-> ExtSign (Sign f e) Symbol
-> ExtSign (Sign f e) Symbol
-> Result (Morphism f e m)
inducedFromToMorphismExt extInd extEm compM isSubExt diffExt rmap
sig1@(ExtSign _ sy1) sig2@(ExtSign _ sy2) =
let iftm rm = (inducedFromToMorphismAuxExt extInd extEm compM isSubExt
diffExt rm sig1 sig2, rm)
isOk = isJust . resultToMaybe
res = fst $ iftm rmap
pos = concatMapRange getRange $ Map.keys rmap
in if isOk res then res else
let ss1 = Set.filter (\ s -> Set.null $ Set.filter
(compatibleSymbols True s) sy2)
$ Set.filter (\ s -> not $ any (matches s) $ Map.keys rmap)
sy1
fcombs = filteredPairs compatibleRawSymbs
(map ASymbol $ Set.toList ss1)
$ map ASymbol $ Set.toList sy2
in if null (drop 20 fcombs) then
case filter (isOk . fst) $ map (iftm . Map.union rmap . Map.fromList)
fcombs of
[] -> res
[(r, m)] -> (if length fcombs > 1 then warning else hint)
() ("derived symbol map:\n" ++ showDoc m "") pos >> r
l -> fatal_error
("ambiguous symbol maps:\n" ++ show
(vcat $ map (pretty . snd) l)) pos
else warning () "too many possibilities for symbol maps" pos >> res
compatibleSymbTypes :: SymbType -> SymbType -> Bool
compatibleSymbTypes s1 s2 = case (s1, s2) of
(SortAsItemType, SortAsItemType) -> True
(OpAsItemType t1, OpAsItemType t2) ->
length (opArgs t1) == length (opArgs t2)
(PredAsItemType p1, PredAsItemType p2) ->
length (predArgs p1) == length (predArgs p2)
_ -> False
compatibleSymbols :: Bool -> Symbol -> Symbol -> Bool
compatibleSymbols alsoId (Symbol i1 k1) (Symbol i2 k2) =
compatibleSymbTypes k1 k2 && (not alsoId || i1 == i2)
compatibleRawSymbs :: RawSymbol -> RawSymbol -> Bool
compatibleRawSymbs r1 r2 = case (r1, r2) of
(ASymbol s1, ASymbol s2) -> compatibleSymbols False s1 s2
_ -> False -- irrelevant
filteredPairs :: (a -> b -> Bool) -> [a] -> [b] -> [[(a, b)]]
filteredPairs p s l = sequence [[(a, b) | b <- filter (p a) l] | a <- s]
-- http://www.haskell.org/pipermail/haskell-cafe/2009-December/069957.html
inducedFromToMorphismAuxExt
:: (Eq e, Show f, Pretty e, Pretty m)
=> InducedSign f e m e
-> InducedMorphism e m -- ^ compute extended morphism
-> (Morphism f e m -> Morphism f e m -> Result m)
-- ^ composition of extensions
-> (e -> e -> Bool) -- ^ subsignature test of extensions
-> (e -> e -> e) -- ^ difference of extensions
-> RawSymbolMap
-> ExtSign (Sign f e) Symbol
-> ExtSign (Sign f e) Symbol
-> Result (Morphism f e m)
inducedFromToMorphismAuxExt extInd extEm compM isSubExt diffExt rmap
(ExtSign sigma1 _) (ExtSign sigma2 _) = do
-- 1. use rmap to get a renaming...
mor1 <- inducedFromMorphismExt extInd extEm rmap sigma1
-- 1.1 ... is the renamed source signature contained in the target signature?
let inducedSign = mtarget mor1
em = extended_map mor1
if isSubSig isSubExt inducedSign sigma2
-- yes => we are done
then composeM compM mor1 $ idOrInclMorphism
$ embedMorphism em inducedSign sigma2
{- here the empty mapping should be used, but it will be overwritten
by the first argument of composeM -}
else fatal_error
("No signature morphism for symbol map found.\n" ++
"The following mapped symbols are missing in the target signature:\n"
++ showDoc (diffSig diffExt inducedSign sigma2) "")
$ concatMapRange getRange $ Map.keys rmap
{-
Computing signature generated by a symbol set.
Algorithm adapted from Bartek Klin's algorithm for CATS.
Input: symbol set "Syms"
signature "Sigma"
Output: signature "Sigma1"<=Sigma.
1. get a set "Sigma_symbols" of symbols in Sigma.
2. if Syms is not a subset of Sigma_symbols, return error.
3. let Sigma1 be an empty signature.
4. for each symbol "Sym" in Syms do:
4.1. if Sym is a:
4.1.1. sort "S": add sort S to Sigma1.
4.1.2. total function "F" with profile "Fargs,Fres":
4.1.2.1. add all sorts from Fargs to Sigma1.
4.1.2.2. add sort Fres to Sigma1.
4.1.2.3. add F with the needed profile to Sigma1.
4.1.3. partial function: as in 4.1.2.
4.1.4. predicate: as in 4.1.2., except that Fres is omitted.
5. get a list "Sig_sub" of subsort relations in Sigma.
6. for each pair "S1,S2" in Sig_sub do:
6.1. if S1,S2 are sorts in Sigma1, add "S1,S2" to sort relations in
Sigma1.
7. return the inclusion of sigma1 into sigma.
-}
generatedSign :: m -> SymbolSet -> Sign f e -> Result (Morphism f e m)
generatedSign extEm sys sigma = let
symset = symsetOf sigma -- 1.
sigma1 = Set.fold revealSym sigma
{ sortRel = Rel.empty
, opMap = MapSet.empty
, predMap = MapSet.empty } sys -- 4.
sigma2 = sigma1
{ sortRel = sortRel sigma `Rel.restrict` sortSet sigma1
, emptySortSet = Set.intersection (sortSet sigma1) $ emptySortSet sigma }
in if not $ Set.isSubsetOf sys symset -- 2.
then let diffsyms = sys Set.\\ symset in
fatal_error ("Revealing: The following symbols "
++ showDoc diffsyms " are not in the signature")
$ getRange diffsyms
else sigInclusion extEm sigma2 sigma -- 7.
revealSym :: Symbol -> Sign f e -> Sign f e
revealSym sy sigma1 = let
n = symName sy
insSort = Rel.insertKey
in case symbType sy of
SortAsItemType -> -- 4.1.1.
sigma1 {sortRel = insSort n $ sortRel sigma1}
SubsortAsItemType _ -> sigma1 -- ignore
OpAsItemType ot -> -- 4.1.2./4.1.3.
sigma1 { sortRel = foldr insSort (sortRel sigma1)
$ opSorts ot
, opMap = MapSet.insert n ot $ opMap sigma1 }
PredAsItemType pt -> -- 4.1.4.
sigma1 { sortRel = foldr insSort (sortRel sigma1) $ predArgs pt
, predMap = MapSet.insert n pt $ predMap sigma1 }
{-
Computing signature co-generated by a raw symbol set.
Algorithm adapted from Bartek Klin's algorithm for CATS.
Input: symbol set "Syms"
signature "Sigma"
Output: signature "Sigma1"<=Sigma.
1. get a set "Sigma_symbols" of symbols in Sigma.
2. if Syms is not a subset of Sigma_symbols, return error.
3. for each symbol "Sym" in Syms do:
3.1. if Sym is a:
3.1.1. sort "S":
3.1.1.1. Remove S from Sigma_symbols
3.1.1.2. For each function/predicate symbol in
Sigma_symbols, if its profile contains S
remove it from Sigma_symbols.
3.1.2. any other symbol: remove if from Sigma_symbols.
4. let Sigma1 be a signature generated by Sigma_symbols in Sigma.
5. return the inclusion of sigma1 into sigma.
-}
cogeneratedSign :: m -> SymbolSet -> Sign f e -> Result (Morphism f e m)
cogeneratedSign extEm symset sigma = let
symset0 = symsetOf sigma -- 1.
symset1 = Set.fold hideSym symset0 symset -- 3.
in if Set.isSubsetOf symset symset0 -- 2.
then generatedSign extEm symset1 sigma -- 4./5.
else let diffsyms = symset Set.\\ symset0 in
fatal_error ("Hiding: The following symbols "
++ showDoc diffsyms " are not in the signature")
$ getRange diffsyms
hideSym :: Symbol -> Set.Set Symbol -> Set.Set Symbol
hideSym sy set1 = let set2 = Set.delete sy set1 in case symbType sy of
SortAsItemType -> -- 3.1.1.
Set.filter (not . profileContainsSort (symName sy) . symbType) set2
_ -> set2 -- 3.1.2
profileContainsSort :: SORT -> SymbType -> Bool
profileContainsSort s symbT = elem s $ case symbT of
OpAsItemType ot -> opSorts ot
PredAsItemType pt -> predArgs pt
SubsortAsItemType t -> [t]
SortAsItemType -> []
leCl :: Ord a => (a -> a -> Bool) -> MapSet.MapSet Id a
-> Map.Map Id [Set.Set a]
leCl f = Map.map (Rel.partSet f) . MapSet.toMap
mkp :: OpMap -> OpMap
mkp = MapSet.mapSet makePartial
finalUnion :: (e -> e -> e) -- ^ join signature extensions
-> Sign f e -> Sign f e -> Result (Sign f e)
finalUnion addSigExt s1 s2 =
let extP = Map.map (map $ \ s -> (s, [], False))
o1 = extP $ leCl (leqF s1) $ mkp $ opMap s1
o2 = extP $ leCl (leqF s2) $ mkp $ opMap s2
p1 = extP $ leCl (leqP s1) $ predMap s1
p2 = extP $ leCl (leqP s2) $ predMap s2
s3 = addSig addSigExt s1 s2
o3 = leCl (leqF s3) $ mkp $ opMap s3
p3 = leCl (leqP s3) $ predMap s3
d1 = Map.differenceWith (listOfSetDiff True) o1 o3
d2 = Map.union d1 $ Map.differenceWith (listOfSetDiff False) o2 o3
e1 = Map.differenceWith (listOfSetDiff True) p1 p3
e2 = Map.union e1 $ Map.differenceWith (listOfSetDiff False) p2 p3
prL (s, l, b) = fsep
$ text ("(" ++ (if b then "left" else "right")
++ " side of union)")
: map pretty l ++ [mapsto <+> pretty s]
prM str = ppMap ((text str <+>) . pretty)
(vcat . map prL) (const id) vcat (\ v1 v2 -> sep [v1, v2])
in if Map.null d2 && Map.null e2 then return s3
else fail $ "illegal overload relation identifications for profiles of:\n"
++ show (prM "op" d2 $+$ prM "pred" e2)
listOfSetDiff :: Ord a => Bool -> [(Set.Set a, [Set.Set a], Bool)]
-> [Set.Set a] -> Maybe [(Set.Set a, [Set.Set a], Bool)]
listOfSetDiff b rl1 l2 = let
fst3 (s, _, _) = s
l1 = map fst3 rl1 in
(\ l3 -> if null l3 then Nothing else Just l3)
$ fst $ foldr
(\ s (l, r) ->
let sIn = Set.isSubsetOf s
(r1, r2) = partition sIn r in
case r1 of
[] -> case find sIn l2 of
Nothing -> error "CASL.finalUnion.listOfSetDiff1"
Just s2 -> (if elem s2 $ map fst3 l then l else
(s2, filter (`Set.isSubsetOf` s2) l1, b) : l, r)
[_] -> (l, r2)
_ -> error "CASL.finalUnion.listOfSetDiff2")
([], l2) l1
|
keithodulaigh/Hets
|
CASL/SymbolMapAnalysis.hs
|
gpl-2.0
| 26,714 | 0 | 24 | 7,738 | 6,304 | 3,184 | 3,120 | 396 | 6 |
module Base.Application (
appState,
runAppState,
setRenderable,
) where
import Control.Monad.State.Strict (get, evalStateT)
import Graphics.Qt
import Utils
import Base.Types
import Base.Renderable.Common ()
appState :: Renderable r => r -> M AppState -> AppState
appState r = AppState (RenderableInstance r)
runAppState :: Application -> AppState -> M ()
runAppState app (AppState renderable cmd) = do
io $ postGUI $ setRenderingLooped (window app) False
io $ postGUI $ setArrowAutoRepeat (window app) True
config <- get
io $ setRenderable app config renderable
cmd >>= runAppState app
runAppState app (AppStateLooped renderable cmd) = do
io $ postGUI $ setRenderingLooped (window app) True
io $ postGUI $ setArrowAutoRepeat (window app) True
config <- get
io $ setRenderable app config renderable
cmd >>= runAppState app
runAppState app (NoGUIAppState cmd) = do
io $ postGUI $ setRenderingLooped (window app) False
cmd >>= runAppState app
runAppState app (GameAppState renderable cmd initialGameState) = do
io $ postGUI $ setRenderingLooped (window app) True
io $ postGUI $ setArrowAutoRepeat (window app) False
config <- get
io $ setRenderable app config renderable
follower <- evalStateT cmd initialGameState
runAppState app follower
runAppState app (UnManagedAppState cmd) = do
io $ postGUI $ setRenderingLooped (window app) False
io $ postGUI $ setArrowAutoRepeat (window app) True
cmd >>= runAppState app
runAppState app FinalAppState = return ()
setRenderable app config renderable = do
setDrawingCallbackMainWindow (window app) (Just renderCallback)
where
renderCallback :: Ptr QPainter -> IO ()
renderCallback ptr = do
size <- io $ sizeQPainter ptr
io $ resetMatrix ptr
snd =<< render ptr app config size renderable
|
geocurnoff/nikki
|
src/Base/Application.hs
|
lgpl-3.0
| 1,873 | 0 | 11 | 398 | 638 | 302 | 336 | 46 | 1 |
{-# LANGUAGE TemplateHaskell, FlexibleInstances, MultiParamTypeClasses #-}
-- | Talk to hot chixxors.
-- (c) Mark Wotton
-- Serialisation (c) 2007 Don Stewart
module Plugin.Vixen where
-- import Data.Int (for code to read old state data)
import Data.Binary
import Data.Binary.Put
import Data.Binary.Get
import Control.Arrow ((***))
import System.Directory
import qualified Data.ByteString.Char8 as P
import File (findFile)
import Plugin
$(plugin "Vixen")
instance Module VixenModule (Bool, String -> IO String) where
moduleCmds _ = ["vixen"]
modulePrivs _ = ["vixen-on", "vixen-off"] -- could be noisy
moduleHelp _ _ = "vixen <phrase>. Sergeant Curry's lonely hearts club"
-- if vixen-chat is on, we can just respond to anything
contextual _ _ _ txt = do
(alive, k) <- readMS
if alive then ios (k txt)
else return []
process_ _ "vixen-on" _ =
withMS $ \(_,r) k -> do k (True, r)
return ["What's this channel about?"]
process_ _ "vixen-off" _ =
withMS $ \(_,r) k -> do k (False, r)
return ["Bye!"]
process_ _ _ txt = readMS >>= ios . ($ txt) . snd
moduleDefState _ = return (False, const (return "<undefined>"))
-- suck in our (read only) regex state from disk
-- compile it, and stick it in the plugin state
moduleInit _ = do
b <- io $ doesFileExist =<< findFile "vixen"
when b $ do
s <- io $ do st <- decodeFile =<< findFile "vixen"
let compiled = map (regex *** id) st
return (vixen (mkResponses compiled))
modifyMS $ \(v,_) -> (v, s)
------------------------------------------------------------------------
vixen :: (String -> WTree) -> String -> IO String
vixen k key = P.unpack `fmap` randomW (k key)
randomW :: WTree -> IO P.ByteString
randomW (Leaf a) = return a
randomW (Node ls) = randomElem ls >>= randomW
mkResponses :: RChoice -> String -> WTree
mkResponses choices them = (\((_,wtree):_) -> wtree) $
filter (\(reg,_) -> matches' reg them) choices
------------------------------------------------------------------------
-- serialisation for the vixen state
--
-- The tree of regexes and responses is written in binary form to
-- State/vixen, and we suck it in on module init, then lazily regexify it all
data WTree = Leaf !P.ByteString | Node ![WTree]
deriving Show
instance Binary WTree where
put (Leaf s) = putWord8 0 >> put s
put (Node ls) = putWord8 1 >> put ls
get = do
tag <- getWord8
case tag of
0 -> liftM Leaf get
1 -> liftM Node get
type Choice = [(P.ByteString, WTree)]
type RChoice = [(Regex, WTree)] -- compiled choices
{- Sample of how to rescue data in the old 32-bit Binary format
newtype OldChoice = OC { unOC :: Choice }
deriving Show
instance Binary OldChoice where
get = do liftM OC (getList (getPair getBS getWTree))
where
getList :: (Get a) -> Get [a]
getList getA = do
n <- liftM fromIntegral (get :: Get Int32)
replicateM n getA
getShort :: Get Int
getShort = liftM fromIntegral (get :: Get Int32)
getPair = liftM2 (,)
getBS = getShort >>= getByteString
getWTree = do
tag <- getWord8
case tag of
0 -> liftM Leaf getBS
1 -> liftM Node (getList getWTree)
-}
|
zeekay/lambdabot
|
Plugin/Vixen.hs
|
mit
| 3,530 | 0 | 20 | 1,044 | 802 | 427 | 375 | 58 | 1 |
module Syntax where
data Expr
= Var String
| Num Int
| Print Expr
| Assign String Int
deriving (Eq,Show)
|
FranklinChen/write-you-a-haskell
|
chapter9/assign/Syntax.hs
|
mit
| 116 | 0 | 6 | 31 | 41 | 24 | 17 | 7 | 0 |
<?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="ms-MY">
<title>Automation Framework</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/automation/src/main/javahelp/org/zaproxy/addon/automation/resources/help_ms_MY/helpset_ms_MY.hs
|
apache-2.0
| 965 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>ToDo-List</title>
<maps>
<homeID>todo</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/todo/src/main/javahelp/help_tr_TR/helpset_tr_TR.hs
|
apache-2.0
| 955 | 77 | 67 | 155 | 408 | 207 | 201 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="id-ID">
<title>Aturan Pindai Pasif | Eksistensi ZAP</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Konten</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Telusuri</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorit</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_id_ID/helpset_id_ID.hs
|
apache-2.0
| 980 | 78 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ro-RO">
<title>AdvFuzzer Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/fuzz/src/main/javahelp/org/zaproxy/zap/extension/fuzz/resources/help_ro_RO/helpset_ro_RO.hs
|
apache-2.0
| 961 | 77 | 67 | 156 | 411 | 208 | 203 | -1 | -1 |
{-# LANGUAGE CPP, BangPatterns #-}
{-# OPTIONS_GHC -Wall -fno-warn-name-shadowing #-}
module Main ( main, test, maxDistances ) where
import System.Environment
import Data.Array.Repa
-- <<Graph
type Weight = Int
type Graph r = Array r DIM2 Weight
-- >>
-- -----------------------------------------------------------------------------
-- shortestPaths
-- <<shortestPaths
shortestPaths :: Graph U -> Graph U
shortestPaths g0 = go g0 0 -- <2>
where
Z :. _ :. n = extent g0 -- <1>
go !g !k | k == n = g -- <3>
| otherwise =
let g' = computeS (fromFunction (Z:.n:.n) sp) -- <4>
in go g' (k+1) -- <5>
where
sp (Z:.i:.j) = min (g ! (Z:.i:.j)) (g ! (Z:.i:.k) + g ! (Z:.k:.j)) -- <6>
-- >>
-- -----------------------------------------------------------------------------
-- <<maxDistance
maxDistance :: Weight -> Weight -> Weight
maxDistance x y
| x == inf = y
| y == inf = x
| otherwise = max x y
-- >>
maxDistances :: Graph U -> Array U DIM1 Weight
maxDistances = foldS maxDistance inf
-- -----------------------------------------------------------------------------
-- Testing
-- <<inf
inf :: Weight
inf = 999
-- >>
testGraph :: Graph U
testGraph = toAdjMatrix $
[[ 0, inf, inf, 13, inf, inf],
[inf, 0, inf, inf, 4, 9],
[ 11, inf, 0, inf, inf, inf],
[inf, 3, inf, 0, inf, 7],
[ 15, 5, inf, 1, 0, inf],
[ 11, inf, inf, 14, inf, 0]]
-- correct result:
expectedResult :: Graph U
expectedResult = toAdjMatrix $
[[0, 16, inf, 13, 20, 20],
[19, 0, inf, 5, 4, 9],
[11, 27, 0, 24, 31, 31],
[18, 3, inf, 0, 7, 7],
[15, 4, inf, 1, 0, 8],
[11, 17, inf, 14, 21, 0] ]
test :: Bool
test = shortestPaths testGraph == expectedResult
toAdjMatrix :: [[Weight]] -> Graph U
toAdjMatrix xs = fromListUnboxed (Z :. k :. k) (concat xs)
where k = length xs
main :: IO ()
main = do
[n] <- fmap (fmap read) getArgs
let g = fromListUnboxed (Z:.n:.n) [0..n^(2::Int)-1] :: Graph U
print (sumAllS (shortestPaths g))
|
prt2121/haskell-practice
|
parconc/fwdense.hs
|
apache-2.0
| 2,331 | 0 | 17 | 785 | 836 | 476 | 360 | 50 | 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="en-GB">
<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>
|
thc202/zap-extensions
|
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help/helpset.hs
|
apache-2.0
| 981 | 90 | 29 | 172 | 403 | 219 | 184 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude, MagicHash #-}
module GHC.Char (chr) where
import GHC.Base
import GHC.Show
import GHC.HasteWordInt
-- | The 'Prelude.toEnum' method restricted to the type 'Data.Char.Char'.
chr :: Int -> Char
chr i@(I# i#)
| isTrue# (i2w i# `leWord#` 0x10FFFF##) = C# (chr# i#)
| otherwise
= error ("Prelude.chr: bad argument: " ++ showSignedInt (I# 9#) i "")
|
beni55/haste-compiler
|
libraries/ghc-7.8/base/GHC/Char.hs
|
bsd-3-clause
| 385 | 0 | 11 | 68 | 116 | 61 | 55 | 10 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Setup
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
--
-----------------------------------------------------------------------------
module Distribution.Client.Setup
( globalCommand, GlobalFlags(..), defaultGlobalFlags, globalRepos
, configureCommand, ConfigFlags(..), filterConfigureFlags
, configureExCommand, ConfigExFlags(..), defaultConfigExFlags
, configureExOptions
, buildCommand, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
, replCommand, testCommand, benchmarkCommand
, installCommand, InstallFlags(..), installOptions, defaultInstallFlags
, listCommand, ListFlags(..)
, updateCommand
, upgradeCommand
, uninstallCommand
, infoCommand, InfoFlags(..)
, fetchCommand, FetchFlags(..)
, freezeCommand, FreezeFlags(..)
, getCommand, unpackCommand, GetFlags(..)
, checkCommand
, formatCommand
, uploadCommand, UploadFlags(..)
, reportCommand, ReportFlags(..)
, runCommand
, initCommand, IT.InitFlags(..)
, sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..)
, win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..)
, actAsSetupCommand, ActAsSetupFlags(..)
, sandboxCommand, defaultSandboxLocation, SandboxFlags(..)
, execCommand, ExecFlags(..)
, userConfigCommand, UserConfigFlags(..)
, parsePackageArgs
--TODO: stop exporting these:
, showRepo
, parseRepo
, readRepo
) where
import Distribution.Client.Types
( Username(..), Password(..), Repo(..), RemoteRepo(..), LocalRepo(..) )
import Distribution.Client.BuildReports.Types
( ReportLevel(..) )
import Distribution.Client.Dependency.Types
( AllowNewer(..), PreSolver(..), ConstraintSource(..) )
import qualified Distribution.Client.Init.Types as IT
( InitFlags(..), PackageType(..) )
import Distribution.Client.Targets
( UserConstraint, readUserConstraint )
import Distribution.Utils.NubList
( NubList, toNubList, fromNubList)
import Distribution.Simple.Compiler (PackageDB)
import Distribution.Simple.Program
( defaultProgramConfiguration )
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import qualified Distribution.Simple.Command as Command
import qualified Distribution.Simple.Setup as Cabal
import Distribution.Simple.Setup
( ConfigFlags(..), BuildFlags(..), ReplFlags
, TestFlags(..), BenchmarkFlags(..)
, SDistFlags(..), HaddockFlags(..)
, readPackageDbList, showPackageDbList
, Flag(..), toFlag, fromFlag, flagToMaybe, flagToList
, optionVerbosity, boolOpt, boolOpt', trueArg, falseArg, optionNumJobs )
import Distribution.Simple.InstallDirs
( PathTemplate, InstallDirs(sysconfdir)
, toPathTemplate, fromPathTemplate )
import Distribution.Version
( Version(Version), anyVersion, thisVersion )
import Distribution.Package
( PackageIdentifier, packageName, packageVersion, Dependency(..) )
import Distribution.PackageDescription
( BuildType(..), RepoKind(..) )
import Distribution.Text
( Text(..), display )
import Distribution.ReadE
( ReadE(..), readP_to_E, succeedReadE )
import qualified Distribution.Compat.ReadP as Parse
( ReadP, readP_to_S, readS_to_P, char, munch1, pfail, sepBy1, (+++) )
import Distribution.Verbosity
( Verbosity, normal )
import Distribution.Simple.Utils
( wrapText, wrapLine )
import Data.Char
( isSpace, isAlphaNum )
import Data.List
( intercalate, deleteFirstsBy )
import Data.Maybe
( listToMaybe, maybeToList, fromMaybe )
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( Monoid(..) )
#endif
import Control.Monad
( liftM )
import System.FilePath
( (</>) )
import Network.URI
( parseAbsoluteURI, uriToString )
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool,
globalNumericVersion :: Flag Bool,
globalConfigFile :: Flag FilePath,
globalSandboxConfigFile :: Flag FilePath,
globalRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers.
globalCacheDir :: Flag FilePath,
globalLocalRepos :: NubList FilePath,
globalLogsDir :: Flag FilePath,
globalWorldFile :: Flag FilePath,
globalRequireSandbox :: Flag Bool,
globalIgnoreSandbox :: Flag Bool,
globalHttpTransport :: Flag String
}
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False,
globalNumericVersion = Flag False,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalRemoteRepos = mempty,
globalCacheDir = mempty,
globalLocalRepos = mempty,
globalLogsDir = mempty,
globalWorldFile = mempty,
globalRequireSandbox = Flag False,
globalIgnoreSandbox = Flag False,
globalHttpTransport = mempty
}
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
commandName = "",
commandSynopsis =
"Command line interface to the Haskell Cabal infrastructure.",
commandUsage = \pname ->
"See http://www.haskell.org/cabal/ for more information.\n"
++ "\n"
++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
commandDescription = Just $ \pname ->
let
commands' = commands ++ [commandAddAction helpCommandUI undefined]
cmdDescs = getNormalCommandDescriptions commands'
-- if new commands are added, we want them to appear even if they
-- are not included in the custom listing below. Thus, we calculate
-- the `otherCmds` list and append it under the `other` category.
-- Alternatively, a new testcase could be added that ensures that
-- the set of commands listed here is equal to the set of commands
-- that are actually available.
otherCmds = deleteFirstsBy (==) (map fst cmdDescs)
[ "help"
, "update"
, "install"
, "fetch"
, "list"
, "info"
, "user-config"
, "get"
, "init"
, "configure"
, "build"
, "clean"
, "run"
, "repl"
, "test"
, "bench"
, "check"
, "sdist"
, "upload"
, "report"
, "freeze"
, "haddock"
, "hscolour"
, "copy"
, "register"
, "sandbox"
, "exec"
]
maxlen = maximum $ [length name | (name, _) <- cmdDescs]
align str = str ++ replicate (maxlen - length str) ' '
startGroup n = " ["++n++"]"
par = ""
addCmd n = case lookup n cmdDescs of
Nothing -> ""
Just d -> " " ++ align n ++ " " ++ d
addCmdCustom n d = case lookup n cmdDescs of -- make sure that the
-- command still exists.
Nothing -> ""
Just _ -> " " ++ align n ++ " " ++ d
in
"Commands:\n"
++ unlines (
[ startGroup "global"
, addCmd "update"
, addCmd "install"
, par
, addCmd "help"
, addCmd "info"
, addCmd "list"
, addCmd "fetch"
, addCmd "user-config"
, par
, startGroup "package"
, addCmd "get"
, addCmd "init"
, par
, addCmd "configure"
, addCmd "build"
, addCmd "clean"
, par
, addCmd "run"
, addCmd "repl"
, addCmd "test"
, addCmd "bench"
, par
, addCmd "check"
, addCmd "sdist"
, addCmd "upload"
, addCmd "report"
, par
, addCmd "freeze"
, addCmd "haddock"
, addCmd "hscolour"
, addCmd "copy"
, addCmd "register"
, par
, startGroup "sandbox"
, addCmd "sandbox"
, addCmd "exec"
, addCmdCustom "repl" "Open interpreter with access to sandbox packages."
] ++ if null otherCmds then [] else par
:startGroup "other"
:[addCmd n | n <- otherCmds])
++ "\n"
++ "For more information about a command use:\n"
++ " " ++ pname ++ " COMMAND --help\n"
++ "or " ++ pname ++ " help COMMAND\n"
++ "\n"
++ "To install Cabal packages from hackage use:\n"
++ " " ++ pname ++ " install foo [--dry-run]\n"
++ "\n"
++ "Occasionally you need to update the list of available packages:\n"
++ " " ++ pname ++ " update\n",
commandNotes = Nothing,
commandDefaultFlags = mempty,
commandOptions = \showOrParseArgs ->
(case showOrParseArgs of ShowArgs -> take 7; ParseArgs -> id)
[option ['V'] ["version"]
"Print version information"
globalVersion (\v flags -> flags { globalVersion = v })
trueArg
,option [] ["numeric-version"]
"Print just the version number"
globalNumericVersion (\v flags -> flags { globalNumericVersion = v })
trueArg
,option [] ["config-file"]
"Set an alternate location for the config file"
globalConfigFile (\v flags -> flags { globalConfigFile = v })
(reqArgFlag "FILE")
,option [] ["sandbox-config-file"]
"Set an alternate location for the sandbox config file (default: './cabal.sandbox.config')"
globalConfigFile (\v flags -> flags { globalSandboxConfigFile = v })
(reqArgFlag "FILE")
,option [] ["require-sandbox"]
"requiring the presence of a sandbox for sandbox-aware commands"
globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v })
(boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"]))
,option [] ["ignore-sandbox"]
"Ignore any existing sandbox"
globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v })
trueArg
,option [] ["http-transport"]
"Set a transport for http(s) requests. Accepts 'curl', 'wget', 'powershell', and 'plain-http'. (default: 'curl')"
globalConfigFile (\v flags -> flags { globalHttpTransport = v })
(reqArgFlag "HttpTransport")
,option [] ["remote-repo"]
"The name and url for a remote repository"
globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
(reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList))
,option [] ["remote-repo-cache"]
"The location where downloads from all remote repos are cached"
globalCacheDir (\v flags -> flags { globalCacheDir = v })
(reqArgFlag "DIR")
,option [] ["local-repo"]
"The location of a local repository"
globalLocalRepos (\v flags -> flags { globalLocalRepos = v })
(reqArg' "DIR" (\x -> toNubList [x]) fromNubList)
,option [] ["logs-dir"]
"The location to put log files"
globalLogsDir (\v flags -> flags { globalLogsDir = v })
(reqArgFlag "DIR")
,option [] ["world-file"]
"The location of the world file"
globalWorldFile (\v flags -> flags { globalWorldFile = v })
(reqArgFlag "FILE")
]
}
instance Monoid GlobalFlags where
mempty = GlobalFlags {
globalVersion = mempty,
globalNumericVersion = mempty,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalRemoteRepos = mempty,
globalCacheDir = mempty,
globalLocalRepos = mempty,
globalLogsDir = mempty,
globalWorldFile = mempty,
globalRequireSandbox = mempty,
globalIgnoreSandbox = mempty,
globalHttpTransport = mempty
}
mappend a b = GlobalFlags {
globalVersion = combine globalVersion,
globalNumericVersion = combine globalNumericVersion,
globalConfigFile = combine globalConfigFile,
globalSandboxConfigFile = combine globalConfigFile,
globalRemoteRepos = combine globalRemoteRepos,
globalCacheDir = combine globalCacheDir,
globalLocalRepos = combine globalLocalRepos,
globalLogsDir = combine globalLogsDir,
globalWorldFile = combine globalWorldFile,
globalRequireSandbox = combine globalRequireSandbox,
globalIgnoreSandbox = combine globalIgnoreSandbox,
globalHttpTransport = combine globalHttpTransport
}
where combine field = field a `mappend` field b
globalRepos :: GlobalFlags -> [Repo]
globalRepos globalFlags = remoteRepos ++ localRepos
where
remoteRepos =
[ Repo (Left remote) cacheDir
| remote <- fromNubList $ globalRemoteRepos globalFlags
, let cacheDir = fromFlag (globalCacheDir globalFlags)
</> remoteRepoName remote ]
localRepos =
[ Repo (Right LocalRepo) local
| local <- fromNubList $ globalLocalRepos globalFlags ]
-- ------------------------------------------------------------
-- * Config flags
-- ------------------------------------------------------------
configureCommand :: CommandUI ConfigFlags
configureCommand = c
{ commandDefaultFlags = mempty
, commandNotes = Just $ \pname -> (case commandNotes c of
Nothing -> ""
Just n -> n pname ++ "\n")
++ "Examples:\n"
++ " " ++ pname ++ " configure\n"
++ " Configure with defaults;\n"
++ " " ++ pname ++ " configure --enable-tests -fcustomflag\n"
++ " Configure building package including tests,\n"
++ " with some package-specific flag.\n"
}
where
c = Cabal.configureCommand defaultProgramConfiguration
configureOptions :: ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
filterConfigureFlags flags cabalLibVersion
| cabalLibVersion >= Version [1,23,0] [] = flags_latest
-- ^ NB: we expect the latest version to be the most common case.
| cabalLibVersion < Version [1,3,10] [] = flags_1_3_10
| cabalLibVersion < Version [1,10,0] [] = flags_1_10_0
| cabalLibVersion < Version [1,14,0] [] = flags_1_14_0
| cabalLibVersion < Version [1,18,0] [] = flags_1_18_0
| cabalLibVersion < Version [1,19,1] [] = flags_1_19_0
| cabalLibVersion < Version [1,19,2] [] = flags_1_19_1
| cabalLibVersion < Version [1,21,1] [] = flags_1_20_0
| cabalLibVersion < Version [1,22,0] [] = flags_1_21_0
| cabalLibVersion < Version [1,23,0] [] = flags_1_22_0
| otherwise = flags_latest
where
-- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
flags_latest = flags { configConstraints = [] }
-- Cabal < 1.23 doesn't know about '--profiling-detail'.
flags_1_22_0 = flags_latest { configProfDetail = NoFlag
, configProfLibDetail = NoFlag }
-- Cabal < 1.22 doesn't know about '--disable-debug-info'.
flags_1_21_0 = flags_1_22_0 { configDebugInfo = NoFlag }
-- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
-- Cabal < 1.21.1 doesn't know about 'enable-profiling'
flags_1_20_0 =
flags_1_21_0 { configRelocatable = NoFlag
, configProf = NoFlag
, configProfExe = configProf flags
, configProfLib =
mappend (configProf flags) (configProfLib flags)
, configCoverage = NoFlag
, configLibCoverage = configCoverage flags
}
-- Cabal < 1.19.2 doesn't know about '--exact-configuration' and
-- '--enable-library-stripping'.
flags_1_19_1 = flags_1_20_0 { configExactConfiguration = NoFlag
, configStripLibs = NoFlag }
-- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
flags_1_19_0 = flags_1_19_1 { configDependencies = []
, configConstraints = configConstraints flags }
-- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList []
, configInstallDirs = configInstallDirs_1_18_0}
configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
-- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
flags_1_14_0 = flags_1_18_0 { configBenchmarks = NoFlag }
-- Cabal < 1.10.0 doesn't know about '--disable-tests'.
flags_1_10_0 = flags_1_14_0 { configTests = NoFlag }
-- Cabal < 1.3.10 does not grok the '--constraints' flag.
flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------
-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
configCabalVersion :: Flag Version,
configExConstraints:: [(UserConstraint, ConstraintSource)],
configPreferences :: [Dependency],
configSolver :: Flag PreSolver,
configAllowNewer :: Flag AllowNewer
}
defaultConfigExFlags :: ConfigExFlags
defaultConfigExFlags = mempty { configSolver = Flag defaultSolver
, configAllowNewer = Flag AllowNewerNone }
configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
commandDefaultFlags = (mempty, defaultConfigExFlags),
commandOptions = \showOrParseArgs ->
liftOptions fst setFst
(filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
. optionName) $ configureOptions showOrParseArgs)
++ liftOptions snd setSnd
(configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
}
where
setFst a (_,b) = (a,b)
setSnd b (a,_) = (a,b)
configureExOptions :: ShowOrParseArgs
-> ConstraintSource
-> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs src =
[ option [] ["cabal-lib-version"]
("Select which version of the Cabal lib to use to build packages "
++ "(useful for testing).")
configCabalVersion (\v flags -> flags { configCabalVersion = v })
(reqArg "VERSION" (readP_to_E ("Cannot parse cabal lib version: "++)
(fmap toFlag parse))
(map display . flagToList))
, option [] ["constraint"]
"Specify constraints on a package (version, installed/source, flags)"
configExConstraints (\v flags -> flags { configExConstraints = v })
(reqArg "CONSTRAINT"
((\x -> [(x, src)]) `fmap` ReadE readUserConstraint)
(map $ display . fst))
, option [] ["preference"]
"Specify preferences (soft constraints) on the version of a package"
configPreferences (\v flags -> flags { configPreferences = v })
(reqArg "CONSTRAINT"
(readP_to_E (const "dependency expected")
(fmap (\x -> [x]) parse))
(map display))
, optionSolver configSolver (\v flags -> flags { configSolver = v })
, option [] ["allow-newer"]
("Ignore upper bounds in all dependencies or " ++ allowNewerArgument)
configAllowNewer (\v flags -> flags { configAllowNewer = v})
(optArg allowNewerArgument
(fmap Flag allowNewerParser) (Flag AllowNewerAll)
allowNewerPrinter)
]
where allowNewerArgument = "DEPS"
instance Monoid ConfigExFlags where
mempty = ConfigExFlags {
configCabalVersion = mempty,
configExConstraints= mempty,
configPreferences = mempty,
configSolver = mempty,
configAllowNewer = mempty
}
mappend a b = ConfigExFlags {
configCabalVersion = combine configCabalVersion,
configExConstraints= combine configExConstraints,
configPreferences = combine configPreferences,
configSolver = combine configSolver,
configAllowNewer = combine configAllowNewer
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------
data SkipAddSourceDepsCheck =
SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
deriving Eq
data BuildExFlags = BuildExFlags {
buildOnly :: Flag SkipAddSourceDepsCheck
}
buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
option [] ["only"]
"Don't reinstall add-source dependencies (sandbox-only)"
buildOnly (\v flags -> flags { buildOnly = v })
(noArg (Flag SkipAddSourceDepsCheck))
: []
buildCommand :: CommandUI (BuildFlags, BuildExFlags)
buildCommand = parent {
commandDefaultFlags = (commandDefaultFlags parent, mempty),
commandOptions =
\showOrParseArgs -> liftOptions fst setFst
(commandOptions parent showOrParseArgs)
++
liftOptions snd setSnd (buildExOptions showOrParseArgs)
}
where
setFst a (_,b) = (a,b)
setSnd b (a,_) = (a,b)
parent = Cabal.buildCommand defaultProgramConfiguration
instance Monoid BuildExFlags where
mempty = BuildExFlags {
buildOnly = mempty
}
mappend a b = BuildExFlags {
buildOnly = combine buildOnly
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Repl command
-- ------------------------------------------------------------
replCommand :: CommandUI (ReplFlags, BuildExFlags)
replCommand = parent {
commandDefaultFlags = (commandDefaultFlags parent, mempty),
commandOptions =
\showOrParseArgs -> liftOptions fst setFst
(commandOptions parent showOrParseArgs)
++
liftOptions snd setSnd (buildExOptions showOrParseArgs)
}
where
setFst a (_,b) = (a,b)
setSnd b (a,_) = (a,b)
parent = Cabal.replCommand defaultProgramConfiguration
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
testCommand = parent {
commandDefaultFlags = (commandDefaultFlags parent,
Cabal.defaultBuildFlags, mempty),
commandOptions =
\showOrParseArgs -> liftOptions get1 set1
(commandOptions parent showOrParseArgs)
++
liftOptions get2 set2
(Cabal.buildOptions progConf showOrParseArgs)
++
liftOptions get3 set3 (buildExOptions showOrParseArgs)
}
where
get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c)
get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c)
get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c)
parent = Cabal.testCommand
progConf = defaultProgramConfiguration
-- ------------------------------------------------------------
-- * Bench command
-- ------------------------------------------------------------
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
benchmarkCommand = parent {
commandDefaultFlags = (commandDefaultFlags parent,
Cabal.defaultBuildFlags, mempty),
commandOptions =
\showOrParseArgs -> liftOptions get1 set1
(commandOptions parent showOrParseArgs)
++
liftOptions get2 set2
(Cabal.buildOptions progConf showOrParseArgs)
++
liftOptions get3 set3 (buildExOptions showOrParseArgs)
}
where
get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c)
get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c)
get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c)
parent = Cabal.benchmarkCommand
progConf = defaultProgramConfiguration
-- ------------------------------------------------------------
-- * Fetch command
-- ------------------------------------------------------------
data FetchFlags = FetchFlags {
-- fetchOutput :: Flag FilePath,
fetchDeps :: Flag Bool,
fetchDryRun :: Flag Bool,
fetchSolver :: Flag PreSolver,
fetchMaxBackjumps :: Flag Int,
fetchReorderGoals :: Flag Bool,
fetchIndependentGoals :: Flag Bool,
fetchShadowPkgs :: Flag Bool,
fetchStrongFlags :: Flag Bool,
fetchVerbosity :: Flag Verbosity
}
defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
-- fetchOutput = mempty,
fetchDeps = toFlag True,
fetchDryRun = toFlag False,
fetchSolver = Flag defaultSolver,
fetchMaxBackjumps = Flag defaultMaxBackjumps,
fetchReorderGoals = Flag False,
fetchIndependentGoals = Flag False,
fetchShadowPkgs = Flag False,
fetchStrongFlags = Flag False,
fetchVerbosity = toFlag normal
}
fetchCommand :: CommandUI FetchFlags
fetchCommand = CommandUI {
commandName = "fetch",
commandSynopsis = "Downloads packages for later installation.",
commandUsage = usageAlternatives "fetch" [ "[FLAGS] PACKAGES"
],
commandDescription = Just $ \_ ->
"Note that it currently is not possible to fetch the dependencies for a\n"
++ "package in the current directory.\n",
commandNotes = Nothing,
commandDefaultFlags = defaultFetchFlags,
commandOptions = \ showOrParseArgs -> [
optionVerbosity fetchVerbosity (\v flags -> flags { fetchVerbosity = v })
-- , option "o" ["output"]
-- "Put the package(s) somewhere specific rather than the usual cache."
-- fetchOutput (\v flags -> flags { fetchOutput = v })
-- (reqArgFlag "PATH")
, option [] ["dependencies", "deps"]
"Resolve and fetch dependencies (default)"
fetchDeps (\v flags -> flags { fetchDeps = v })
trueArg
, option [] ["no-dependencies", "no-deps"]
"Ignore dependencies"
fetchDeps (\v flags -> flags { fetchDeps = v })
falseArg
, option [] ["dry-run"]
"Do not install anything, only print what would be installed."
fetchDryRun (\v flags -> flags { fetchDryRun = v })
trueArg
] ++
optionSolver fetchSolver (\v flags -> flags { fetchSolver = v }) :
optionSolverFlags showOrParseArgs
fetchMaxBackjumps (\v flags -> flags { fetchMaxBackjumps = v })
fetchReorderGoals (\v flags -> flags { fetchReorderGoals = v })
fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
fetchShadowPkgs (\v flags -> flags { fetchShadowPkgs = v })
fetchStrongFlags (\v flags -> flags { fetchStrongFlags = v })
}
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------
data FreezeFlags = FreezeFlags {
freezeDryRun :: Flag Bool,
freezeTests :: Flag Bool,
freezeBenchmarks :: Flag Bool,
freezeSolver :: Flag PreSolver,
freezeMaxBackjumps :: Flag Int,
freezeReorderGoals :: Flag Bool,
freezeIndependentGoals :: Flag Bool,
freezeShadowPkgs :: Flag Bool,
freezeStrongFlags :: Flag Bool,
freezeVerbosity :: Flag Verbosity
}
defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
freezeDryRun = toFlag False,
freezeTests = toFlag False,
freezeBenchmarks = toFlag False,
freezeSolver = Flag defaultSolver,
freezeMaxBackjumps = Flag defaultMaxBackjumps,
freezeReorderGoals = Flag False,
freezeIndependentGoals = Flag False,
freezeShadowPkgs = Flag False,
freezeStrongFlags = Flag False,
freezeVerbosity = toFlag normal
}
freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
commandName = "freeze",
commandSynopsis = "Freeze dependencies.",
commandDescription = Just $ \_ -> wrapText $
"Calculates a valid set of dependencies and their exact versions. "
++ "If successful, saves the result to the file `cabal.config`.\n"
++ "\n"
++ "The package versions specified in `cabal.config` will be used for "
++ "any future installs.\n"
++ "\n"
++ "An existing `cabal.config` is ignored and overwritten.\n",
commandNotes = Nothing,
commandUsage = usageFlags "freeze",
commandDefaultFlags = defaultFreezeFlags,
commandOptions = \ showOrParseArgs -> [
optionVerbosity freezeVerbosity (\v flags -> flags { freezeVerbosity = v })
, option [] ["dry-run"]
"Do not freeze anything, only print what would be frozen"
freezeDryRun (\v flags -> flags { freezeDryRun = v })
trueArg
, option [] ["tests"]
"freezing of the dependencies of any tests suites in the package description file."
freezeTests (\v flags -> flags { freezeTests = v })
(boolOpt [] [])
, option [] ["benchmarks"]
"freezing of the dependencies of any benchmarks suites in the package description file."
freezeBenchmarks (\v flags -> flags { freezeBenchmarks = v })
(boolOpt [] [])
] ++
optionSolver freezeSolver (\v flags -> flags { freezeSolver = v }) :
optionSolverFlags showOrParseArgs
freezeMaxBackjumps (\v flags -> flags { freezeMaxBackjumps = v })
freezeReorderGoals (\v flags -> flags { freezeReorderGoals = v })
freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v })
freezeShadowPkgs (\v flags -> flags { freezeShadowPkgs = v })
freezeStrongFlags (\v flags -> flags { freezeStrongFlags = v })
}
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------
updateCommand :: CommandUI (Flag Verbosity)
updateCommand = CommandUI {
commandName = "update",
commandSynopsis = "Updates list of known packages.",
commandDescription = Just $ \_ ->
"For all known remote repositories, download the package list.\n",
commandNotes = Just $ \_ ->
relevantConfigValuesText ["remote-repo"
,"remote-repo-cache"
,"local-repo"],
commandUsage = usageFlags "update",
commandDefaultFlags = toFlag normal,
commandOptions = \_ -> [optionVerbosity id const]
}
upgradeCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
upgradeCommand = configureCommand {
commandName = "upgrade",
commandSynopsis = "(command disabled, use install instead)",
commandDescription = Nothing,
commandUsage = usageFlagsOrPackages "upgrade",
commandDefaultFlags = (mempty, mempty, mempty, mempty),
commandOptions = commandOptions installCommand
}
{-
cleanCommand :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
where
name = "clean"
shortDesc = "Removes downloaded files"
longDesc = Nothing
emptyFlags = ()
options _ = []
-}
checkCommand :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
commandName = "check",
commandSynopsis = "Check the package for common mistakes.",
commandDescription = Just $ \_ -> wrapText $
"Expects a .cabal package file in the current directory.\n"
++ "\n"
++ "The checks correspond to the requirements to packages on Hackage. "
++ "If no errors and warnings are reported, Hackage will accept this "
++ "package.\n",
commandNotes = Nothing,
commandUsage = \pname -> "Usage: " ++ pname ++ " check\n",
commandDefaultFlags = toFlag normal,
commandOptions = \_ -> []
}
formatCommand :: CommandUI (Flag Verbosity)
formatCommand = CommandUI {
commandName = "format",
commandSynopsis = "Reformat the .cabal file using the standard style.",
commandDescription = Nothing,
commandNotes = Nothing,
commandUsage = usageAlternatives "format" ["[FILE]"],
commandDefaultFlags = toFlag normal,
commandOptions = \_ -> []
}
uninstallCommand :: CommandUI (Flag Verbosity)
uninstallCommand = CommandUI {
commandName = "uninstall",
commandSynopsis = "Warn about 'uninstall' not being implemented.",
commandDescription = Nothing,
commandNotes = Nothing,
commandUsage = usageAlternatives "uninstall" ["PACKAGES"],
commandDefaultFlags = toFlag normal,
commandOptions = \_ -> []
}
runCommand :: CommandUI (BuildFlags, BuildExFlags)
runCommand = CommandUI {
commandName = "run",
commandSynopsis = "Builds and runs an executable.",
commandDescription = Just $ \pname -> wrapText $
"Builds and then runs the specified executable. If no executable is "
++ "specified, but the package contains just one executable, that one "
++ "is built and executed.\n"
++ "\n"
++ "Use `" ++ pname ++ " test --show-details=streaming` to run a "
++ "test-suite and get its full output.\n",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " run\n"
++ " Run the only executable in the current package;\n"
++ " " ++ pname ++ " run foo -- --fooflag\n"
++ " Works similar to `./foo --fooflag`.\n",
commandUsage = usageAlternatives "run"
["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"],
commandDefaultFlags = mempty,
commandOptions =
\showOrParseArgs -> liftOptions fst setFst
(commandOptions parent showOrParseArgs)
++
liftOptions snd setSnd
(buildExOptions showOrParseArgs)
}
where
setFst a (_,b) = (a,b)
setSnd b (a,_) = (a,b)
parent = Cabal.buildCommand defaultProgramConfiguration
-- ------------------------------------------------------------
-- * Report flags
-- ------------------------------------------------------------
data ReportFlags = ReportFlags {
reportUsername :: Flag Username,
reportPassword :: Flag Password,
reportVerbosity :: Flag Verbosity
}
defaultReportFlags :: ReportFlags
defaultReportFlags = ReportFlags {
reportUsername = mempty,
reportPassword = mempty,
reportVerbosity = toFlag normal
}
reportCommand :: CommandUI ReportFlags
reportCommand = CommandUI {
commandName = "report",
commandSynopsis = "Upload build reports to a remote server.",
commandDescription = Nothing,
commandNotes = Just $ \_ ->
"You can store your Hackage login in the ~/.cabal/config file\n",
commandUsage = usageAlternatives "report" ["[FLAGS]"],
commandDefaultFlags = defaultReportFlags,
commandOptions = \_ ->
[optionVerbosity reportVerbosity (\v flags -> flags { reportVerbosity = v })
,option ['u'] ["username"]
"Hackage username."
reportUsername (\v flags -> flags { reportUsername = v })
(reqArg' "USERNAME" (toFlag . Username)
(flagToList . fmap unUsername))
,option ['p'] ["password"]
"Hackage password."
reportPassword (\v flags -> flags { reportPassword = v })
(reqArg' "PASSWORD" (toFlag . Password)
(flagToList . fmap unPassword))
]
}
instance Monoid ReportFlags where
mempty = ReportFlags {
reportUsername = mempty,
reportPassword = mempty,
reportVerbosity = mempty
}
mappend a b = ReportFlags {
reportUsername = combine reportUsername,
reportPassword = combine reportPassword,
reportVerbosity = combine reportVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Get flags
-- ------------------------------------------------------------
data GetFlags = GetFlags {
getDestDir :: Flag FilePath,
getPristine :: Flag Bool,
getSourceRepository :: Flag (Maybe RepoKind),
getVerbosity :: Flag Verbosity
}
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
getDestDir = mempty,
getPristine = mempty,
getSourceRepository = mempty,
getVerbosity = toFlag normal
}
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
commandName = "get",
commandSynopsis = "Download/Extract a package's source code (repository).",
commandDescription = Just $ \_ -> wrapText $
"Creates a local copy of a package's source code. By default it gets "
++ "the source\ntarball and unpacks it in a local subdirectory. "
++ "Alternatively, with -s it will\nget the code from the source "
++ "repository specified by the package.\n",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " get hlint\n"
++ " Download the latest stable version of hlint;\n"
++ " " ++ pname ++ " get lens --source-repository=head\n"
++ " Download the source repository (i.e. git clone from github).\n",
commandUsage = usagePackages "get",
commandDefaultFlags = defaultGetFlags,
commandOptions = \_ -> [
optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
,option "d" ["destdir"]
"Where to place the package source, defaults to the current directory."
getDestDir (\v flags -> flags { getDestDir = v })
(reqArgFlag "PATH")
,option "s" ["source-repository"]
"Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
getSourceRepository (\v flags -> flags { getSourceRepository = v })
(optArg "[head|this|...]" (readP_to_E (const "invalid source-repository")
(fmap (toFlag . Just) parse))
(Flag Nothing)
(map (fmap show) . flagToList))
, option [] ["pristine"]
("Unpack the original pristine tarball, rather than updating the "
++ ".cabal file with the latest revision from the package archive.")
getPristine (\v flags -> flags { getPristine = v })
trueArg
]
}
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
commandName = "unpack",
commandUsage = usagePackages "unpack"
}
instance Monoid GetFlags where
mempty = GetFlags {
getDestDir = mempty,
getPristine = mempty,
getSourceRepository = mempty,
getVerbosity = mempty
}
mappend a b = GetFlags {
getDestDir = combine getDestDir,
getPristine = combine getPristine,
getSourceRepository = combine getSourceRepository,
getVerbosity = combine getVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * List flags
-- ------------------------------------------------------------
data ListFlags = ListFlags {
listInstalled :: Flag Bool,
listSimpleOutput :: Flag Bool,
listVerbosity :: Flag Verbosity,
listPackageDBs :: [Maybe PackageDB]
}
defaultListFlags :: ListFlags
defaultListFlags = ListFlags {
listInstalled = Flag False,
listSimpleOutput = Flag False,
listVerbosity = toFlag normal,
listPackageDBs = []
}
listCommand :: CommandUI ListFlags
listCommand = CommandUI {
commandName = "list",
commandSynopsis = "List packages matching a search string.",
commandDescription = Just $ \_ -> wrapText $
"List all packages, or all packages matching one of the search"
++ " strings.\n"
++ "\n"
++ "If there is a sandbox in the current directory and "
++ "config:ignore-sandbox is False, use the sandbox package database. "
++ "Otherwise, use the package database specified with --package-db. "
++ "If not specified, use the user package database.\n",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " list pandoc\n"
++ " Will find pandoc, pandoc-citeproc, pandoc-lens, ...\n",
commandUsage = usageAlternatives "list" [ "[FLAGS]"
, "[FLAGS] STRINGS"],
commandDefaultFlags = defaultListFlags,
commandOptions = \_ -> [
optionVerbosity listVerbosity (\v flags -> flags { listVerbosity = v })
, option [] ["installed"]
"Only print installed packages"
listInstalled (\v flags -> flags { listInstalled = v })
trueArg
, option [] ["simple-output"]
"Print in a easy-to-parse format"
listSimpleOutput (\v flags -> flags { listSimpleOutput = v })
trueArg
, option "" ["package-db"]
( "Append the given package database to the list of package"
++ " databases used (to satisfy dependencies and register into)."
++ " May be a specific file, 'global' or 'user'. The initial list"
++ " is ['global'], ['global', 'user'], or ['global', $sandbox],"
++ " depending on context. Use 'clear' to reset the list to empty."
++ " See the user guide for details.")
listPackageDBs (\v flags -> flags { listPackageDBs = v })
(reqArg' "DB" readPackageDbList showPackageDbList)
]
}
instance Monoid ListFlags where
mempty = ListFlags {
listInstalled = mempty,
listSimpleOutput = mempty,
listVerbosity = mempty,
listPackageDBs = mempty
}
mappend a b = ListFlags {
listInstalled = combine listInstalled,
listSimpleOutput = combine listSimpleOutput,
listVerbosity = combine listVerbosity,
listPackageDBs = combine listPackageDBs
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Info flags
-- ------------------------------------------------------------
data InfoFlags = InfoFlags {
infoVerbosity :: Flag Verbosity,
infoPackageDBs :: [Maybe PackageDB]
}
defaultInfoFlags :: InfoFlags
defaultInfoFlags = InfoFlags {
infoVerbosity = toFlag normal,
infoPackageDBs = []
}
infoCommand :: CommandUI InfoFlags
infoCommand = CommandUI {
commandName = "info",
commandSynopsis = "Display detailed information about a particular package.",
commandDescription = Just $ \_ -> wrapText $
"If there is a sandbox in the current directory and "
++ "config:ignore-sandbox is False, use the sandbox package database. "
++ "Otherwise, use the package database specified with --package-db. "
++ "If not specified, use the user package database.\n",
commandNotes = Nothing,
commandUsage = usageAlternatives "info" ["[FLAGS] PACKAGES"],
commandDefaultFlags = defaultInfoFlags,
commandOptions = \_ -> [
optionVerbosity infoVerbosity (\v flags -> flags { infoVerbosity = v })
, option "" ["package-db"]
( "Append the given package database to the list of package"
++ " databases used (to satisfy dependencies and register into)."
++ " May be a specific file, 'global' or 'user'. The initial list"
++ " is ['global'], ['global', 'user'], or ['global', $sandbox],"
++ " depending on context. Use 'clear' to reset the list to empty."
++ " See the user guide for details.")
infoPackageDBs (\v flags -> flags { infoPackageDBs = v })
(reqArg' "DB" readPackageDbList showPackageDbList)
]
}
instance Monoid InfoFlags where
mempty = InfoFlags {
infoVerbosity = mempty,
infoPackageDBs = mempty
}
mappend a b = InfoFlags {
infoVerbosity = combine infoVerbosity,
infoPackageDBs = combine infoPackageDBs
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------
-- | Install takes the same flags as configure along with a few extras.
--
data InstallFlags = InstallFlags {
installDocumentation :: Flag Bool,
installHaddockIndex :: Flag PathTemplate,
installDryRun :: Flag Bool,
installMaxBackjumps :: Flag Int,
installReorderGoals :: Flag Bool,
installIndependentGoals :: Flag Bool,
installShadowPkgs :: Flag Bool,
installStrongFlags :: Flag Bool,
installReinstall :: Flag Bool,
installAvoidReinstalls :: Flag Bool,
installOverrideReinstall :: Flag Bool,
installUpgradeDeps :: Flag Bool,
installOnly :: Flag Bool,
installOnlyDeps :: Flag Bool,
installRootCmd :: Flag String,
installSummaryFile :: NubList PathTemplate,
installLogFile :: Flag PathTemplate,
installBuildReports :: Flag ReportLevel,
installReportPlanningFailure :: Flag Bool,
installSymlinkBinDir :: Flag FilePath,
installOneShot :: Flag Bool,
installNumJobs :: Flag (Maybe Int),
installRunTests :: Flag Bool,
installOfflineMode :: Flag Bool
}
defaultInstallFlags :: InstallFlags
defaultInstallFlags = InstallFlags {
installDocumentation = Flag False,
installHaddockIndex = Flag docIndexFile,
installDryRun = Flag False,
installMaxBackjumps = Flag defaultMaxBackjumps,
installReorderGoals = Flag False,
installIndependentGoals= Flag False,
installShadowPkgs = Flag False,
installStrongFlags = Flag False,
installReinstall = Flag False,
installAvoidReinstalls = Flag False,
installOverrideReinstall = Flag False,
installUpgradeDeps = Flag False,
installOnly = Flag False,
installOnlyDeps = Flag False,
installRootCmd = mempty,
installSummaryFile = mempty,
installLogFile = mempty,
installBuildReports = Flag NoReports,
installReportPlanningFailure = Flag False,
installSymlinkBinDir = mempty,
installOneShot = Flag False,
installNumJobs = mempty,
installRunTests = mempty,
installOfflineMode = Flag False
}
where
docIndexFile = toPathTemplate ("$datadir" </> "doc"
</> "$arch-$os-$compiler" </> "index.html")
allowNewerParser :: ReadE AllowNewer
allowNewerParser = ReadE $ \s ->
case s of
"" -> Right AllowNewerNone
"False" -> Right AllowNewerNone
"True" -> Right AllowNewerAll
_ ->
case readPToMaybe pkgsParser s of
Just pkgs -> Right . AllowNewerSome $ pkgs
Nothing -> Left ("Cannot parse the list of packages: " ++ s)
where
pkgsParser = Parse.sepBy1 parse (Parse.char ',')
allowNewerPrinter :: Flag AllowNewer -> [Maybe String]
allowNewerPrinter (Flag AllowNewerNone) = [Just "False"]
allowNewerPrinter (Flag AllowNewerAll) = [Just "True"]
allowNewerPrinter (Flag (AllowNewerSome pkgs)) =
[Just . intercalate "," . map display $ pkgs]
allowNewerPrinter NoFlag = []
defaultMaxBackjumps :: Int
defaultMaxBackjumps = 2000
defaultSolver :: PreSolver
defaultSolver = Choose
allSolvers :: String
allSolvers = intercalate ", " (map display ([minBound .. maxBound] :: [PreSolver]))
installCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
installCommand = CommandUI {
commandName = "install",
commandSynopsis = "Install packages.",
commandUsage = usageAlternatives "install" [ "[FLAGS]"
, "[FLAGS] PACKAGES"
],
commandDescription = Just $ \_ -> wrapText $
"Installs one or more packages. By default, the installed package"
++ " will be registered in the user's package database or, if a sandbox"
++ " is present in the current directory, inside the sandbox.\n"
++ "\n"
++ "If PACKAGES are specified, downloads and installs those packages."
++ " Otherwise, install the package in the current directory (and/or its"
++ " dependencies) (there must be exactly one .cabal file in the current"
++ " directory).\n"
++ "\n"
++ "When using a sandbox, the flags for `install` only affect the"
++ " current command and have no effect on future commands. (To achieve"
++ " that, `configure` must be used.)\n"
++ " In contrast, without a sandbox, the flags to `install` are saved and"
++ " affect future commands such as `build` and `repl`. See the help for"
++ " `configure` for a list of commands being affected.\n"
++ "\n"
++ "Installed executables will by default (and without a sandbox)"
++ " be put into `~/.cabal/bin/`."
++ " If you want installed executable to be available globally, make"
++ " sure that the PATH environment variable contains that directory.\n"
++ "When using a sandbox, executables will be put into"
++ " `$SANDBOX/bin/` (by default: `./.cabal-sandbox/bin/`).\n"
++ "\n"
++ "When specifying --bindir, consider also specifying --datadir;"
++ " this way the sandbox can be deleted and the executable should"
++ " continue working as long as bindir and datadir are left untouched.",
commandNotes = Just $ \pname ->
( case commandNotes
$ Cabal.configureCommand defaultProgramConfiguration
of Just desc -> desc pname ++ "\n"
Nothing -> ""
)
++ "Examples:\n"
++ " " ++ pname ++ " install "
++ " Package in the current directory\n"
++ " " ++ pname ++ " install foo "
++ " Package from the hackage server\n"
++ " " ++ pname ++ " install foo-1.0 "
++ " Specific version of a package\n"
++ " " ++ pname ++ " install 'foo < 2' "
++ " Constrained package version\n"
++ " " ++ pname ++ " install haddock --bindir=$HOME/hask-bin/ --datadir=$HOME/hask-data/\n"
++ " " ++ (map (const ' ') pname)
++ " "
++ " Change installation destination\n",
commandDefaultFlags = (mempty, mempty, mempty, mempty),
commandOptions = \showOrParseArgs ->
liftOptions get1 set1
(filter ((`notElem` ["constraint", "dependency"
, "exact-configuration"])
. optionName) $
configureOptions showOrParseArgs)
++ liftOptions get2 set2 (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
++ liftOptions get3 set3 (installOptions showOrParseArgs)
++ liftOptions get4 set4 (haddockOptions showOrParseArgs)
}
where
get1 (a,_,_,_) = a; set1 a (_,b,c,d) = (a,b,c,d)
get2 (_,b,_,_) = b; set2 b (a,_,c,d) = (a,b,c,d)
get3 (_,_,c,_) = c; set3 c (a,b,_,d) = (a,b,c,d)
get4 (_,_,_,d) = d; set4 d (a,b,c,_) = (a,b,c,d)
haddockOptions :: ShowOrParseArgs -> [OptionField HaddockFlags]
haddockOptions showOrParseArgs
= [ opt { optionName = "haddock-" ++ name,
optionDescr = [ fmapOptFlags (\(_, lflags) -> ([], map ("haddock-" ++) lflags)) descr
| descr <- optionDescr opt] }
| opt <- commandOptions Cabal.haddockCommand showOrParseArgs
, let name = optionName opt
, name `elem` ["hoogle", "html", "html-location"
,"executables", "tests", "benchmarks", "all", "internal", "css"
,"hyperlink-source", "hscolour-css"
,"contents-location"]
]
where
fmapOptFlags :: (OptFlags -> OptFlags) -> OptDescr a -> OptDescr a
fmapOptFlags modify (ReqArg d f p r w) = ReqArg d (modify f) p r w
fmapOptFlags modify (OptArg d f p r i w) = OptArg d (modify f) p r i w
fmapOptFlags modify (ChoiceOpt xs) = ChoiceOpt [(d, modify f, i, w) | (d, f, i, w) <- xs]
fmapOptFlags modify (BoolOpt d f1 f2 r w) = BoolOpt d (modify f1) (modify f2) r w
installOptions :: ShowOrParseArgs -> [OptionField InstallFlags]
installOptions showOrParseArgs =
[ option "" ["documentation"]
"building of documentation"
installDocumentation (\v flags -> flags { installDocumentation = v })
(boolOpt [] [])
, option [] ["doc-index-file"]
"A central index of haddock API documentation (template cannot use $pkgid)"
installHaddockIndex (\v flags -> flags { installHaddockIndex = v })
(reqArg' "TEMPLATE" (toFlag.toPathTemplate)
(flagToList . fmap fromPathTemplate))
, option [] ["dry-run"]
"Do not install anything, only print what would be installed."
installDryRun (\v flags -> flags { installDryRun = v })
trueArg
] ++
optionSolverFlags showOrParseArgs
installMaxBackjumps (\v flags -> flags { installMaxBackjumps = v })
installReorderGoals (\v flags -> flags { installReorderGoals = v })
installIndependentGoals (\v flags -> flags { installIndependentGoals = v })
installShadowPkgs (\v flags -> flags { installShadowPkgs = v })
installStrongFlags (\v flags -> flags { installStrongFlags = v }) ++
[ option [] ["reinstall"]
"Install even if it means installing the same version again."
installReinstall (\v flags -> flags { installReinstall = v })
(yesNoOpt showOrParseArgs)
, option [] ["avoid-reinstalls"]
"Do not select versions that would destructively overwrite installed packages."
installAvoidReinstalls (\v flags -> flags { installAvoidReinstalls = v })
(yesNoOpt showOrParseArgs)
, option [] ["force-reinstalls"]
"Reinstall packages even if they will most likely break other installed packages."
installOverrideReinstall (\v flags -> flags { installOverrideReinstall = v })
(yesNoOpt showOrParseArgs)
, option [] ["upgrade-dependencies"]
"Pick the latest version for all dependencies, rather than trying to pick an installed version."
installUpgradeDeps (\v flags -> flags { installUpgradeDeps = v })
(yesNoOpt showOrParseArgs)
, option [] ["only-dependencies"]
"Install only the dependencies necessary to build the given packages"
installOnlyDeps (\v flags -> flags { installOnlyDeps = v })
(yesNoOpt showOrParseArgs)
, option [] ["dependencies-only"]
"A synonym for --only-dependencies"
installOnlyDeps (\v flags -> flags { installOnlyDeps = v })
(yesNoOpt showOrParseArgs)
, option [] ["root-cmd"]
"Command used to gain root privileges, when installing with --global."
installRootCmd (\v flags -> flags { installRootCmd = v })
(reqArg' "COMMAND" toFlag flagToList)
, option [] ["symlink-bindir"]
"Add symlinks to installed executables into this directory."
installSymlinkBinDir (\v flags -> flags { installSymlinkBinDir = v })
(reqArgFlag "DIR")
, option [] ["build-summary"]
"Save build summaries to file (name template can use $pkgid, $compiler, $os, $arch)"
installSummaryFile (\v flags -> flags { installSummaryFile = v })
(reqArg' "TEMPLATE" (\x -> toNubList [toPathTemplate x]) (map fromPathTemplate . fromNubList))
, option [] ["build-log"]
"Log all builds to file (name template can use $pkgid, $compiler, $os, $arch)"
installLogFile (\v flags -> flags { installLogFile = v })
(reqArg' "TEMPLATE" (toFlag.toPathTemplate)
(flagToList . fmap fromPathTemplate))
, option [] ["remote-build-reporting"]
"Generate build reports to send to a remote server (none, anonymous or detailed)."
installBuildReports (\v flags -> flags { installBuildReports = v })
(reqArg "LEVEL" (readP_to_E (const $ "report level must be 'none', "
++ "'anonymous' or 'detailed'")
(toFlag `fmap` parse))
(flagToList . fmap display))
, option [] ["report-planning-failure"]
"Generate build reports when the dependency solver fails. This is used by the Hackage build bot."
installReportPlanningFailure (\v flags -> flags { installReportPlanningFailure = v })
trueArg
, option [] ["one-shot"]
"Do not record the packages in the world file."
installOneShot (\v flags -> flags { installOneShot = v })
(yesNoOpt showOrParseArgs)
, option [] ["run-tests"]
"Run package test suites during installation."
installRunTests (\v flags -> flags { installRunTests = v })
trueArg
, optionNumJobs
installNumJobs (\v flags -> flags { installNumJobs = v })
, option [] ["offline"]
"Don't download packages from the Internet."
installOfflineMode (\v flags -> flags { installOfflineMode = v })
(yesNoOpt showOrParseArgs)
] ++ case showOrParseArgs of -- TODO: remove when "cabal install"
-- avoids
ParseArgs ->
[ option [] ["only"]
"Only installs the package in the current directory."
installOnly (\v flags -> flags { installOnly = v })
trueArg ]
_ -> []
instance Monoid InstallFlags where
mempty = InstallFlags {
installDocumentation = mempty,
installHaddockIndex = mempty,
installDryRun = mempty,
installReinstall = mempty,
installAvoidReinstalls = mempty,
installOverrideReinstall = mempty,
installMaxBackjumps = mempty,
installUpgradeDeps = mempty,
installReorderGoals = mempty,
installIndependentGoals= mempty,
installShadowPkgs = mempty,
installStrongFlags = mempty,
installOnly = mempty,
installOnlyDeps = mempty,
installRootCmd = mempty,
installSummaryFile = mempty,
installLogFile = mempty,
installBuildReports = mempty,
installReportPlanningFailure = mempty,
installSymlinkBinDir = mempty,
installOneShot = mempty,
installNumJobs = mempty,
installRunTests = mempty,
installOfflineMode = mempty
}
mappend a b = InstallFlags {
installDocumentation = combine installDocumentation,
installHaddockIndex = combine installHaddockIndex,
installDryRun = combine installDryRun,
installReinstall = combine installReinstall,
installAvoidReinstalls = combine installAvoidReinstalls,
installOverrideReinstall = combine installOverrideReinstall,
installMaxBackjumps = combine installMaxBackjumps,
installUpgradeDeps = combine installUpgradeDeps,
installReorderGoals = combine installReorderGoals,
installIndependentGoals= combine installIndependentGoals,
installShadowPkgs = combine installShadowPkgs,
installStrongFlags = combine installStrongFlags,
installOnly = combine installOnly,
installOnlyDeps = combine installOnlyDeps,
installRootCmd = combine installRootCmd,
installSummaryFile = combine installSummaryFile,
installLogFile = combine installLogFile,
installBuildReports = combine installBuildReports,
installReportPlanningFailure = combine installReportPlanningFailure,
installSymlinkBinDir = combine installSymlinkBinDir,
installOneShot = combine installOneShot,
installNumJobs = combine installNumJobs,
installRunTests = combine installRunTests,
installOfflineMode = combine installOfflineMode
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Upload flags
-- ------------------------------------------------------------
data UploadFlags = UploadFlags {
uploadCheck :: Flag Bool,
uploadUsername :: Flag Username,
uploadPassword :: Flag Password,
uploadPasswordCmd :: Flag [String],
uploadVerbosity :: Flag Verbosity
}
defaultUploadFlags :: UploadFlags
defaultUploadFlags = UploadFlags {
uploadCheck = toFlag False,
uploadUsername = mempty,
uploadPassword = mempty,
uploadPasswordCmd = mempty,
uploadVerbosity = toFlag normal
}
uploadCommand :: CommandUI UploadFlags
uploadCommand = CommandUI {
commandName = "upload",
commandSynopsis = "Uploads source packages to Hackage.",
commandDescription = Nothing,
commandNotes = Just $ \_ ->
"You can store your Hackage login in the ~/.cabal/config file\n"
++ relevantConfigValuesText ["username", "password"],
commandUsage = \pname ->
"Usage: " ++ pname ++ " upload [FLAGS] TARFILES\n",
commandDefaultFlags = defaultUploadFlags,
commandOptions = \_ ->
[optionVerbosity uploadVerbosity (\v flags -> flags { uploadVerbosity = v })
,option ['c'] ["check"]
"Do not upload, just do QA checks."
uploadCheck (\v flags -> flags { uploadCheck = v })
trueArg
,option ['u'] ["username"]
"Hackage username."
uploadUsername (\v flags -> flags { uploadUsername = v })
(reqArg' "USERNAME" (toFlag . Username)
(flagToList . fmap unUsername))
,option ['p'] ["password"]
"Hackage password."
uploadPassword (\v flags -> flags { uploadPassword = v })
(reqArg' "PASSWORD" (toFlag . Password)
(flagToList . fmap unPassword))
,option ['P'] ["password-command"]
"Command to get Hackage password."
uploadPasswordCmd (\v flags -> flags { uploadPasswordCmd = v })
(reqArg' "PASSWORD" (Flag . words) (fromMaybe [] . flagToMaybe))
]
}
instance Monoid UploadFlags where
mempty = UploadFlags {
uploadCheck = mempty,
uploadUsername = mempty,
uploadPassword = mempty,
uploadPasswordCmd = mempty,
uploadVerbosity = mempty
}
mappend a b = UploadFlags {
uploadCheck = combine uploadCheck,
uploadUsername = combine uploadUsername,
uploadPassword = combine uploadPassword,
uploadPasswordCmd = combine uploadPasswordCmd,
uploadVerbosity = combine uploadVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Init flags
-- ------------------------------------------------------------
emptyInitFlags :: IT.InitFlags
emptyInitFlags = mempty
defaultInitFlags :: IT.InitFlags
defaultInitFlags = emptyInitFlags { IT.initVerbosity = toFlag normal }
initCommand :: CommandUI IT.InitFlags
initCommand = CommandUI {
commandName = "init",
commandSynopsis = "Create a new .cabal package file (interactively).",
commandDescription = Just $ \_ -> wrapText $
"Cabalise a project by creating a .cabal, Setup.hs, and "
++ "optionally a LICENSE file.\n"
++ "\n"
++ "Calling init with no arguments (recommended) uses an "
++ "interactive mode, which will try to guess as much as "
++ "possible and prompt you for the rest. Command-line "
++ "arguments are provided for scripting purposes. "
++ "If you don't want interactive mode, be sure to pass "
++ "the -n flag.\n",
commandNotes = Nothing,
commandUsage = \pname ->
"Usage: " ++ pname ++ " init [FLAGS]\n",
commandDefaultFlags = defaultInitFlags,
commandOptions = \_ ->
[ option ['n'] ["non-interactive"]
"Non-interactive mode."
IT.nonInteractive (\v flags -> flags { IT.nonInteractive = v })
trueArg
, option ['q'] ["quiet"]
"Do not generate log messages to stdout."
IT.quiet (\v flags -> flags { IT.quiet = v })
trueArg
, option [] ["no-comments"]
"Do not generate explanatory comments in the .cabal file."
IT.noComments (\v flags -> flags { IT.noComments = v })
trueArg
, option ['m'] ["minimal"]
"Generate a minimal .cabal file, that is, do not include extra empty fields. Also implies --no-comments."
IT.minimal (\v flags -> flags { IT.minimal = v })
trueArg
, option [] ["overwrite"]
"Overwrite any existing .cabal, LICENSE, or Setup.hs files without warning."
IT.overwrite (\v flags -> flags { IT.overwrite = v })
trueArg
, option [] ["package-dir"]
"Root directory of the package (default = current directory)."
IT.packageDir (\v flags -> flags { IT.packageDir = v })
(reqArgFlag "DIRECTORY")
, option ['p'] ["package-name"]
"Name of the Cabal package to create."
IT.packageName (\v flags -> flags { IT.packageName = v })
(reqArg "PACKAGE" (readP_to_E ("Cannot parse package name: "++)
(toFlag `fmap` parse))
(flagToList . fmap display))
, option [] ["version"]
"Initial version of the package."
IT.version (\v flags -> flags { IT.version = v })
(reqArg "VERSION" (readP_to_E ("Cannot parse package version: "++)
(toFlag `fmap` parse))
(flagToList . fmap display))
, option [] ["cabal-version"]
"Required version of the Cabal library."
IT.cabalVersion (\v flags -> flags { IT.cabalVersion = v })
(reqArg "VERSION_RANGE" (readP_to_E ("Cannot parse Cabal version range: "++)
(toFlag `fmap` parse))
(flagToList . fmap display))
, option ['l'] ["license"]
"Project license."
IT.license (\v flags -> flags { IT.license = v })
(reqArg "LICENSE" (readP_to_E ("Cannot parse license: "++)
(toFlag `fmap` parse))
(flagToList . fmap display))
, option ['a'] ["author"]
"Name of the project's author."
IT.author (\v flags -> flags { IT.author = v })
(reqArgFlag "NAME")
, option ['e'] ["email"]
"Email address of the maintainer."
IT.email (\v flags -> flags { IT.email = v })
(reqArgFlag "EMAIL")
, option ['u'] ["homepage"]
"Project homepage and/or repository."
IT.homepage (\v flags -> flags { IT.homepage = v })
(reqArgFlag "URL")
, option ['s'] ["synopsis"]
"Short project synopsis."
IT.synopsis (\v flags -> flags { IT.synopsis = v })
(reqArgFlag "TEXT")
, option ['c'] ["category"]
"Project category."
IT.category (\v flags -> flags { IT.category = v })
(reqArg' "CATEGORY" (\s -> toFlag $ maybe (Left s) Right (readMaybe s))
(flagToList . fmap (either id show)))
, option ['x'] ["extra-source-file"]
"Extra source file to be distributed with tarball."
IT.extraSrc (\v flags -> flags { IT.extraSrc = v })
(reqArg' "FILE" (Just . (:[]))
(fromMaybe []))
, option [] ["is-library"]
"Build a library."
IT.packageType (\v flags -> flags { IT.packageType = v })
(noArg (Flag IT.Library))
, option [] ["is-executable"]
"Build an executable."
IT.packageType
(\v flags -> flags { IT.packageType = v })
(noArg (Flag IT.Executable))
, option [] ["main-is"]
"Specify the main module."
IT.mainIs
(\v flags -> flags { IT.mainIs = v })
(reqArgFlag "FILE")
, option [] ["language"]
"Specify the default language."
IT.language
(\v flags -> flags { IT.language = v })
(reqArg "LANGUAGE" (readP_to_E ("Cannot parse language: "++)
(toFlag `fmap` parse))
(flagToList . fmap display))
, option ['o'] ["expose-module"]
"Export a module from the package."
IT.exposedModules
(\v flags -> flags { IT.exposedModules = v })
(reqArg "MODULE" (readP_to_E ("Cannot parse module name: "++)
((Just . (:[])) `fmap` parse))
(maybe [] (fmap display)))
, option [] ["extension"]
"Use a LANGUAGE extension (in the other-extensions field)."
IT.otherExts
(\v flags -> flags { IT.otherExts = v })
(reqArg "EXTENSION" (readP_to_E ("Cannot parse extension: "++)
((Just . (:[])) `fmap` parse))
(maybe [] (fmap display)))
, option ['d'] ["dependency"]
"Package dependency."
IT.dependencies (\v flags -> flags { IT.dependencies = v })
(reqArg "PACKAGE" (readP_to_E ("Cannot parse dependency: "++)
((Just . (:[])) `fmap` parse))
(maybe [] (fmap display)))
, option [] ["source-dir"]
"Directory containing package source."
IT.sourceDirs (\v flags -> flags { IT.sourceDirs = v })
(reqArg' "DIR" (Just . (:[]))
(fromMaybe []))
, option [] ["build-tool"]
"Required external build tool."
IT.buildTools (\v flags -> flags { IT.buildTools = v })
(reqArg' "TOOL" (Just . (:[]))
(fromMaybe []))
, optionVerbosity IT.initVerbosity (\v flags -> flags { IT.initVerbosity = v })
]
}
where readMaybe s = case reads s of
[(x,"")] -> Just x
_ -> Nothing
-- ------------------------------------------------------------
-- * SDist flags
-- ------------------------------------------------------------
-- | Extra flags to @sdist@ beyond runghc Setup sdist
--
data SDistExFlags = SDistExFlags {
sDistFormat :: Flag ArchiveFormat
}
deriving Show
data ArchiveFormat = TargzFormat | ZipFormat -- | ...
deriving (Show, Eq)
defaultSDistExFlags :: SDistExFlags
defaultSDistExFlags = SDistExFlags {
sDistFormat = Flag TargzFormat
}
sdistCommand :: CommandUI (SDistFlags, SDistExFlags)
sdistCommand = Cabal.sdistCommand {
commandDefaultFlags = (commandDefaultFlags Cabal.sdistCommand, defaultSDistExFlags),
commandOptions = \showOrParseArgs ->
liftOptions fst setFst (commandOptions Cabal.sdistCommand showOrParseArgs)
++ liftOptions snd setSnd sdistExOptions
}
where
setFst a (_,b) = (a,b)
setSnd b (a,_) = (a,b)
sdistExOptions =
[option [] ["archive-format"] "archive-format"
sDistFormat (\v flags -> flags { sDistFormat = v })
(choiceOpt
[ (Flag TargzFormat, ([], ["targz"]),
"Produce a '.tar.gz' format archive (default and required for uploading to hackage)")
, (Flag ZipFormat, ([], ["zip"]),
"Produce a '.zip' format archive")
])
]
instance Monoid SDistExFlags where
mempty = SDistExFlags {
sDistFormat = mempty
}
mappend a b = SDistExFlags {
sDistFormat = combine sDistFormat
}
where
combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Win32SelfUpgrade flags
-- ------------------------------------------------------------
data Win32SelfUpgradeFlags = Win32SelfUpgradeFlags {
win32SelfUpgradeVerbosity :: Flag Verbosity
}
defaultWin32SelfUpgradeFlags :: Win32SelfUpgradeFlags
defaultWin32SelfUpgradeFlags = Win32SelfUpgradeFlags {
win32SelfUpgradeVerbosity = toFlag normal
}
win32SelfUpgradeCommand :: CommandUI Win32SelfUpgradeFlags
win32SelfUpgradeCommand = CommandUI {
commandName = "win32selfupgrade",
commandSynopsis = "Self-upgrade the executable on Windows",
commandDescription = Nothing,
commandNotes = Nothing,
commandUsage = \pname ->
"Usage: " ++ pname ++ " win32selfupgrade PID PATH\n",
commandDefaultFlags = defaultWin32SelfUpgradeFlags,
commandOptions = \_ ->
[optionVerbosity win32SelfUpgradeVerbosity
(\v flags -> flags { win32SelfUpgradeVerbosity = v})
]
}
instance Monoid Win32SelfUpgradeFlags where
mempty = Win32SelfUpgradeFlags {
win32SelfUpgradeVerbosity = mempty
}
mappend a b = Win32SelfUpgradeFlags {
win32SelfUpgradeVerbosity = combine win32SelfUpgradeVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * ActAsSetup flags
-- ------------------------------------------------------------
data ActAsSetupFlags = ActAsSetupFlags {
actAsSetupBuildType :: Flag BuildType
}
defaultActAsSetupFlags :: ActAsSetupFlags
defaultActAsSetupFlags = ActAsSetupFlags {
actAsSetupBuildType = toFlag Simple
}
actAsSetupCommand :: CommandUI ActAsSetupFlags
actAsSetupCommand = CommandUI {
commandName = "act-as-setup",
commandSynopsis = "Run as-if this was a Setup.hs",
commandDescription = Nothing,
commandNotes = Nothing,
commandUsage = \pname ->
"Usage: " ++ pname ++ " act-as-setup\n",
commandDefaultFlags = defaultActAsSetupFlags,
commandOptions = \_ ->
[option "" ["build-type"]
"Use the given build type."
actAsSetupBuildType (\v flags -> flags { actAsSetupBuildType = v })
(reqArg "BUILD-TYPE" (readP_to_E ("Cannot parse build type: "++)
(fmap toFlag parse))
(map display . flagToList))
]
}
instance Monoid ActAsSetupFlags where
mempty = ActAsSetupFlags {
actAsSetupBuildType = mempty
}
mappend a b = ActAsSetupFlags {
actAsSetupBuildType = combine actAsSetupBuildType
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Sandbox-related flags
-- ------------------------------------------------------------
data SandboxFlags = SandboxFlags {
sandboxVerbosity :: Flag Verbosity,
sandboxSnapshot :: Flag Bool, -- FIXME: this should be an 'add-source'-only
-- flag.
sandboxLocation :: Flag FilePath
}
defaultSandboxLocation :: FilePath
defaultSandboxLocation = ".cabal-sandbox"
defaultSandboxFlags :: SandboxFlags
defaultSandboxFlags = SandboxFlags {
sandboxVerbosity = toFlag normal,
sandboxSnapshot = toFlag False,
sandboxLocation = toFlag defaultSandboxLocation
}
sandboxCommand :: CommandUI SandboxFlags
sandboxCommand = CommandUI {
commandName = "sandbox",
commandSynopsis = "Create/modify/delete a sandbox.",
commandDescription = Just $ \pname -> concat
[ paragraph $ "Sandboxes are isolated package databases that can be used"
++ " to prevent dependency conflicts that arise when many different"
++ " packages are installed in the same database (i.e. the user's"
++ " database in the home directory)."
, paragraph $ "A sandbox in the current directory (created by"
++ " `sandbox init`) will be used instead of the user's database for"
++ " commands such as `install` and `build`. Note that (a directly"
++ " invoked) GHC will not automatically be aware of sandboxes;"
++ " only if called via appropriate " ++ pname
++ " commands, e.g. `repl`, `build`, `exec`."
, paragraph $ "Currently, " ++ pname ++ " will not search for a sandbox"
++ " in folders above the current one, so cabal will not see the sandbox"
++ " if you are in a subfolder of a sandbox."
, paragraph "Subcommands:"
, headLine "init:"
, indentParagraph $ "Initialize a sandbox in the current directory."
++ " An existing package database will not be modified, but settings"
++ " (such as the location of the database) can be modified this way."
, headLine "delete:"
, indentParagraph $ "Remove the sandbox; deleting all the packages"
++ " installed inside."
, headLine "add-source:"
, indentParagraph $ "Make one or more local packages available in the"
++ " sandbox. PATHS may be relative or absolute."
++ " Typical usecase is when you need"
++ " to make a (temporary) modification to a dependency: You download"
++ " the package into a different directory, make the modification,"
++ " and add that directory to the sandbox with `add-source`."
, indentParagraph $ "Unless given `--snapshot`, any add-source'd"
++ " dependency that was modified since the last build will be"
++ " re-installed automatically."
, headLine "delete-source:"
, indentParagraph $ "Remove an add-source dependency; however, this will"
++ " not delete the package(s) that have been installed in the sandbox"
++ " from this dependency. You can either unregister the package(s) via"
++ " `" ++ pname ++ " sandbox hc-pkg unregister` or re-create the"
++ " sandbox (`sandbox delete; sandbox init`)."
, headLine "list-sources:"
, indentParagraph $ "List the directories of local packages made"
++ " available via `" ++ pname ++ " add-source`."
, headLine "hc-pkg:"
, indentParagraph $ "Similar to `ghc-pkg`, but for the sandbox package"
++ " database. Can be used to list specific/all packages that are"
++ " installed in the sandbox. For subcommands, see the help for"
++ " ghc-pkg. Affected by the compiler version specified by `configure`."
],
commandNotes = Just $ \pname ->
relevantConfigValuesText ["require-sandbox"
,"ignore-sandbox"]
++ "\n"
++ "Examples:\n"
++ " Set up a sandbox with one local dependency, located at ../foo:\n"
++ " " ++ pname ++ " sandbox init\n"
++ " " ++ pname ++ " sandbox add-source ../foo\n"
++ " " ++ pname ++ " install --only-dependencies\n"
++ " Reset the sandbox:\n"
++ " " ++ pname ++ " sandbox delete\n"
++ " " ++ pname ++ " sandbox init\n"
++ " " ++ pname ++ " install --only-dependencies\n"
++ " List the packages in the sandbox:\n"
++ " " ++ pname ++ " sandbox hc-pkg list\n"
++ " Unregister the `broken` package from the sandbox:\n"
++ " " ++ pname ++ " sandbox hc-pkg -- --force unregister broken\n",
commandUsage = usageAlternatives "sandbox"
[ "init [FLAGS]"
, "delete [FLAGS]"
, "add-source [FLAGS] PATHS"
, "delete-source [FLAGS] PATHS"
, "list-sources [FLAGS]"
, "hc-pkg [FLAGS] [--] COMMAND [--] [ARGS]"
],
commandDefaultFlags = defaultSandboxFlags,
commandOptions = \_ ->
[ optionVerbosity sandboxVerbosity
(\v flags -> flags { sandboxVerbosity = v })
, option [] ["snapshot"]
"Take a snapshot instead of creating a link (only applies to 'add-source')"
sandboxSnapshot (\v flags -> flags { sandboxSnapshot = v })
trueArg
, option [] ["sandbox"]
"Sandbox location (default: './.cabal-sandbox')."
sandboxLocation (\v flags -> flags { sandboxLocation = v })
(reqArgFlag "DIR")
]
}
instance Monoid SandboxFlags where
mempty = SandboxFlags {
sandboxVerbosity = mempty,
sandboxSnapshot = mempty,
sandboxLocation = mempty
}
mappend a b = SandboxFlags {
sandboxVerbosity = combine sandboxVerbosity,
sandboxSnapshot = combine sandboxSnapshot,
sandboxLocation = combine sandboxLocation
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Exec Flags
-- ------------------------------------------------------------
data ExecFlags = ExecFlags {
execVerbosity :: Flag Verbosity
}
defaultExecFlags :: ExecFlags
defaultExecFlags = ExecFlags {
execVerbosity = toFlag normal
}
execCommand :: CommandUI ExecFlags
execCommand = CommandUI {
commandName = "exec",
commandSynopsis = "Give a command access to the sandbox package repository.",
commandDescription = Just $ \pname -> wrapText $
-- TODO: this is too GHC-focused for my liking..
"A directly invoked GHC will not automatically be aware of any"
++ " sandboxes: the GHC_PACKAGE_PATH environment variable controls what"
++ " GHC uses. `" ++ pname ++ " exec` can be used to modify this variable:"
++ " COMMAND will be executed in a modified environment and thereby uses"
++ " the sandbox package database.\n"
++ "\n"
++ "If there is no sandbox, behaves as identity (executing COMMAND).\n"
++ "\n"
++ "Note that other " ++ pname ++ " commands change the environment"
++ " variable appropriately already, so there is no need to wrap those"
++ " in `" ++ pname ++ " exec`. But with `" ++ pname ++ " exec`, the user"
++ " has more control and can, for example, execute custom scripts which"
++ " indirectly execute GHC.\n"
++ "\n"
++ "Note that `" ++ pname ++ " repl` is different from `" ++ pname
++ " exec -- ghci` as the latter will not forward any additional flags"
++ " being defined in the local package to ghci.\n"
++ "\n"
++ "See `" ++ pname ++ " sandbox`.\n",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " exec -- ghci -Wall\n"
++ " Start a repl session with sandbox packages and all warnings;\n"
++ " " ++ pname ++ " exec gitit -- -f gitit.cnf\n"
++ " Give gitit access to the sandbox packages, and pass it a flag;\n"
++ " " ++ pname ++ " exec runghc Foo.hs\n"
++ " Execute runghc on Foo.hs with runghc configured to use the\n"
++ " sandbox package database (if a sandbox is being used).\n",
commandUsage = \pname ->
"Usage: " ++ pname ++ " exec [FLAGS] [--] COMMAND [--] [ARGS]\n",
commandDefaultFlags = defaultExecFlags,
commandOptions = \_ ->
[ optionVerbosity execVerbosity
(\v flags -> flags { execVerbosity = v })
]
}
instance Monoid ExecFlags where
mempty = ExecFlags {
execVerbosity = mempty
}
mappend a b = ExecFlags {
execVerbosity = combine execVerbosity
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * UserConfig flags
-- ------------------------------------------------------------
data UserConfigFlags = UserConfigFlags {
userConfigVerbosity :: Flag Verbosity
}
instance Monoid UserConfigFlags where
mempty = UserConfigFlags {
userConfigVerbosity = toFlag normal
}
mappend a b = UserConfigFlags {
userConfigVerbosity = combine userConfigVerbosity
}
where combine field = field a `mappend` field b
userConfigCommand :: CommandUI UserConfigFlags
userConfigCommand = CommandUI {
commandName = "user-config",
commandSynopsis = "Display and update the user's global cabal configuration.",
commandDescription = Just $ \_ -> wrapText $
"When upgrading cabal, the set of configuration keys and their default"
++ " values may change. This command provides means to merge the existing"
++ " config in ~/.cabal/config"
++ " (i.e. all bindings that are actually defined and not commented out)"
++ " and the default config of the new version.\n"
++ "\n"
++ "diff: Shows a pseudo-diff of the user's ~/.cabal/config file and"
++ " the default configuration that would be created by cabal if the"
++ " config file did not exist.\n"
++ "update: Applies the pseudo-diff to the configuration that would be"
++ " created by default, and write the result back to ~/.cabal/config.",
commandNotes = Nothing,
commandUsage = usageAlternatives "user-config" ["diff", "update"],
commandDefaultFlags = mempty,
commandOptions = \ _ -> [
optionVerbosity userConfigVerbosity (\v flags -> flags { userConfigVerbosity = v })
]
}
-- ------------------------------------------------------------
-- * GetOpt Utils
-- ------------------------------------------------------------
reqArgFlag :: ArgPlaceHolder ->
MkOptDescr (b -> Flag String) (Flag String -> b -> b) b
reqArgFlag ad = reqArg ad (succeedReadE Flag) flagToList
liftOptions :: (b -> a) -> (a -> b -> b)
-> [OptionField a] -> [OptionField b]
liftOptions get set = map (liftOption get set)
yesNoOpt :: ShowOrParseArgs -> MkOptDescr (b -> Flag Bool) (Flag Bool -> b -> b) b
yesNoOpt ShowArgs sf lf = trueArg sf lf
yesNoOpt _ sf lf = Command.boolOpt' flagToMaybe Flag (sf, lf) ([], map ("no-" ++) lf) sf lf
optionSolver :: (flags -> Flag PreSolver)
-> (Flag PreSolver -> flags -> flags)
-> OptionField flags
optionSolver get set =
option [] ["solver"]
("Select dependency solver to use (default: " ++ display defaultSolver ++ "). Choices: " ++ allSolvers ++ ", where 'choose' chooses between 'topdown' and 'modular' based on compiler version.")
get set
(reqArg "SOLVER" (readP_to_E (const $ "solver must be one of: " ++ allSolvers)
(toFlag `fmap` parse))
(flagToList . fmap display))
optionSolverFlags :: ShowOrParseArgs
-> (flags -> Flag Int ) -> (Flag Int -> flags -> flags)
-> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags)
-> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags)
-> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags)
-> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags)
-> [OptionField flags]
optionSolverFlags showOrParseArgs getmbj setmbj getrg setrg _getig _setig getsip setsip getstrfl setstrfl =
[ option [] ["max-backjumps"]
("Maximum number of backjumps allowed while solving (default: " ++ show defaultMaxBackjumps ++ "). Use a negative number to enable unlimited backtracking. Use 0 to disable backtracking completely.")
getmbj setmbj
(reqArg "NUM" (readP_to_E ("Cannot parse number: "++)
(fmap toFlag (Parse.readS_to_P reads)))
(map show . flagToList))
, option [] ["reorder-goals"]
"Try to reorder goals according to certain heuristics. Slows things down on average, but may make backtracking faster for some packages."
getrg setrg
(yesNoOpt showOrParseArgs)
-- TODO: Disabled for now because it does not work as advertised (yet).
{-
, option [] ["independent-goals"]
"Treat several goals on the command line as independent. If several goals depend on the same package, different versions can be chosen."
getig setig
(yesNoOpt showOrParseArgs)
-}
, option [] ["shadow-installed-packages"]
"If multiple package instances of the same version are installed, treat all but one as shadowed."
getsip setsip
(yesNoOpt showOrParseArgs)
, option [] ["strong-flags"]
"Do not defer flag choices (this used to be the default in cabal-install <= 1.20)."
getstrfl setstrfl
(yesNoOpt showOrParseArgs)
]
usageFlagsOrPackages :: String -> String -> String
usageFlagsOrPackages name pname =
"Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n"
++ " or: " ++ pname ++ " " ++ name ++ " [PACKAGES]\n"
usagePackages :: String -> String -> String
usagePackages name pname =
"Usage: " ++ pname ++ " " ++ name ++ " [PACKAGES]\n"
usageFlags :: String -> String -> String
usageFlags name pname =
"Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n"
--TODO: do we want to allow per-package flags?
parsePackageArgs :: [String] -> Either String [Dependency]
parsePackageArgs = parsePkgArgs []
where
parsePkgArgs ds [] = Right (reverse ds)
parsePkgArgs ds (arg:args) =
case readPToMaybe parseDependencyOrPackageId arg of
Just dep -> parsePkgArgs (dep:ds) args
Nothing -> Left $
show arg ++ " is not valid syntax for a package name or"
++ " package dependency."
readPToMaybe :: Parse.ReadP a a -> String -> Maybe a
readPToMaybe p str = listToMaybe [ r | (r,s) <- Parse.readP_to_S p str
, all isSpace s ]
parseDependencyOrPackageId :: Parse.ReadP r Dependency
parseDependencyOrPackageId = parse Parse.+++ liftM pkgidToDependency parse
where
pkgidToDependency :: PackageIdentifier -> Dependency
pkgidToDependency p = case packageVersion p of
Version [] _ -> Dependency (packageName p) anyVersion
version -> Dependency (packageName p) (thisVersion version)
showRepo :: RemoteRepo -> String
showRepo repo = remoteRepoName repo ++ ":"
++ uriToString id (remoteRepoURI repo) []
readRepo :: String -> Maybe RemoteRepo
readRepo = readPToMaybe parseRepo
parseRepo :: Parse.ReadP r RemoteRepo
parseRepo = do
name <- Parse.munch1 (\c -> isAlphaNum c || c `elem` "_-.")
_ <- Parse.char ':'
uriStr <- Parse.munch1 (\c -> isAlphaNum c || c `elem` "+-=._/*()@'$:;&!?~")
uri <- maybe Parse.pfail return (parseAbsoluteURI uriStr)
return RemoteRepo {
remoteRepoName = name,
remoteRepoURI = uri,
remoteRepoRootKeys = (),
remoteRepoShouldTryHttps = False
}
-- ------------------------------------------------------------
-- * Helpers for Documentation
-- ------------------------------------------------------------
headLine :: String -> String
headLine = unlines
. map unwords
. wrapLine 79
. words
paragraph :: String -> String
paragraph = (++"\n")
. unlines
. map unwords
. wrapLine 79
. words
indentParagraph :: String -> String
indentParagraph = unlines
. map ((" "++).unwords)
. wrapLine 77
. words
relevantConfigValuesText :: [String] -> String
relevantConfigValuesText vs =
"Relevant global configuration keys:\n"
++ concat [" " ++ v ++ "\n" |v <- vs]
|
gridaphobe/cabal
|
cabal-install/Distribution/Client/Setup.hs
|
bsd-3-clause
| 92,305 | 0 | 40 | 25,805 | 18,729 | 10,545 | 8,184 | 1,787 | 5 |
import Control.Concurrent
import Control.Exception
import Control.Monad
import System.IO
import System.Environment
-- test for deadlocks
main = do
hSetBuffering stdout NoBuffering
[n] <- getArgs
replicateM_ (read n) $ do
chan <- newChan
wid <- forkIO $ forever $ writeChan chan (5::Int)
rid <- forkIO $ forever $ void $ readChan chan
threadDelay 1000
throwTo rid ThreadKilled
putStr "."
readChan chan
throwTo wid ThreadKilled
|
holzensp/ghc
|
libraries/base/tests/Concurrent/Chan002.hs
|
bsd-3-clause
| 505 | 1 | 13 | 141 | 158 | 72 | 86 | 17 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
-- | An unstructured grab-bag of various tools and inspection
-- functions that didn't really fit anywhere else.
module Futhark.Tools
( module Futhark.Construct,
redomapToMapAndReduce,
dissectScrema,
sequentialStreamWholeArray,
partitionChunkedFoldParameters,
-- * Primitive expressions
module Futhark.Analysis.PrimExp.Convert,
)
where
import Control.Monad.Identity
import Futhark.Analysis.PrimExp.Convert
import Futhark.Construct
import Futhark.IR
import Futhark.IR.SOACS.SOAC
import Futhark.Util
-- | Turns a binding of a @redomap@ into two seperate bindings, a
-- @map@ binding and a @reduce@ binding (returned in that order).
--
-- Reuses the original pattern for the @reduce@, and creates a new
-- pattern with new 'Ident's for the result of the @map@.
redomapToMapAndReduce ::
( MonadFreshNames m,
Buildable rep,
ExpDec rep ~ (),
Op rep ~ SOAC rep
) =>
Pat rep ->
( SubExp,
[Reduce rep],
LambdaT rep,
[VName]
) ->
m (Stm rep, Stm rep)
redomapToMapAndReduce (Pat pes) (w, reds, map_lam, arrs) = do
(map_pat, red_pat, red_arrs) <-
splitScanOrRedomap pes w map_lam $ map redNeutral reds
let map_stm = mkLet map_pat $ Op $ Screma w arrs (mapSOAC map_lam)
red_stm <-
Let red_pat (defAux ()) . Op
<$> (Screma w red_arrs <$> reduceSOAC reds)
return (map_stm, red_stm)
splitScanOrRedomap ::
(Typed dec, MonadFreshNames m) =>
[PatElemT dec] ->
SubExp ->
LambdaT rep ->
[[SubExp]] ->
m ([Ident], PatT dec, [VName])
splitScanOrRedomap pes w map_lam nes = do
let (acc_pes, arr_pes) =
splitAt (length $ concat nes) pes
(acc_ts, _arr_ts) =
splitAt (length (concat nes)) $ lambdaReturnType map_lam
map_accpat <- zipWithM accMapPatElem acc_pes acc_ts
map_arrpat <- mapM arrMapPatElem arr_pes
let map_pat = map_accpat ++ map_arrpat
return (map_pat, Pat acc_pes, map identName map_accpat)
where
accMapPatElem pe acc_t =
newIdent (baseString (patElemName pe) ++ "_map_acc") $ acc_t `arrayOfRow` w
arrMapPatElem = return . patElemIdent
-- | Turn a Screma into a Scanomap (possibly with mapout parts) and a
-- Redomap. This is used to handle Scremas that are so complicated
-- that we cannot directly generate efficient parallel code for them.
-- In essense, what happens is the opposite of horisontal fusion.
dissectScrema ::
( MonadBuilder m,
Op (Rep m) ~ SOAC (Rep m),
Buildable (Rep m)
) =>
Pat (Rep m) ->
SubExp ->
ScremaForm (Rep m) ->
[VName] ->
m ()
dissectScrema pat w (ScremaForm scans reds map_lam) arrs = do
let num_reds = redResults reds
num_scans = scanResults scans
(scan_res, red_res, map_res) =
splitAt3 num_scans num_reds $ patNames pat
to_red <- replicateM num_reds $ newVName "to_red"
let scanomap = scanomapSOAC scans map_lam
letBindNames (scan_res <> to_red <> map_res) $
Op $ Screma w arrs scanomap
reduce <- reduceSOAC reds
letBindNames red_res $ Op $ Screma w to_red reduce
-- | Turn a stream SOAC into statements that apply the stream lambda
-- to the entire input.
sequentialStreamWholeArray ::
(MonadBuilder m, Buildable (Rep m)) =>
Pat (Rep m) ->
SubExp ->
[SubExp] ->
LambdaT (Rep m) ->
[VName] ->
m ()
sequentialStreamWholeArray pat w nes lam arrs = do
-- We just set the chunksize to w and inline the lambda body. There
-- is no difference between parallel and sequential streams here.
let (chunk_size_param, fold_params, arr_params) =
partitionChunkedFoldParameters (length nes) $ lambdaParams lam
-- The chunk size is the full size of the array.
letBindNames [paramName chunk_size_param] $ BasicOp $ SubExp w
-- The accumulator parameters are initialised to the neutral element.
forM_ (zip fold_params nes) $ \(p, ne) ->
letBindNames [paramName p] $ BasicOp $ SubExp ne
-- Finally, the array parameters are set to the arrays (but reshaped
-- to make the types work out; this will be simplified rapidly).
forM_ (zip arr_params arrs) $ \(p, arr) ->
letBindNames [paramName p] $
BasicOp $
Reshape (map DimCoercion $ arrayDims $ paramType p) arr
-- Then we just inline the lambda body.
mapM_ addStm $ bodyStms $ lambdaBody lam
-- The number of results in the body matches exactly the size (and
-- order) of 'pat', so we bind them up here, again with a reshape to
-- make the types work out.
forM_ (zip (patElems pat) $ bodyResult $ lambdaBody lam) $ \(pe, SubExpRes cs se) ->
certifying cs $ case (arrayDims $ patElemType pe, se) of
(dims, Var v)
| not $ null dims ->
letBindNames [patElemName pe] $ BasicOp $ Reshape (map DimCoercion dims) v
_ -> letBindNames [patElemName pe] $ BasicOp $ SubExp se
-- | Split the parameters of a stream reduction lambda into the chunk
-- size parameter, the accumulator parameters, and the input chunk
-- parameters. The integer argument is how many accumulators are
-- used.
partitionChunkedFoldParameters ::
Int ->
[Param dec] ->
(Param dec, [Param dec], [Param dec])
partitionChunkedFoldParameters _ [] =
error "partitionChunkedFoldParameters: lambda takes no parameters"
partitionChunkedFoldParameters num_accs (chunk_param : params) =
let (acc_params, arr_params) = splitAt num_accs params
in (chunk_param, acc_params, arr_params)
|
HIPERFIT/futhark
|
src/Futhark/Tools.hs
|
isc
| 5,396 | 0 | 18 | 1,132 | 1,414 | 721 | 693 | 107 | 2 |
-- Weather proxy device
module Main where
import System.ZMQ4.Monadic
main :: IO ()
main = runZMQ $ do
-- This is where the weather service sits
frontend <- socket XSub
connect frontend "tcp://192.168.55.210:5556"
-- This is our public endpoint for subscribers
backend <- socket XPub
bind backend "tcp://10.1.1.0:8100"
-- Run the proxy until the user interrupts us
proxy frontend backend Nothing
|
soscpd/bee
|
root/tests/zguide/examples/Haskell/wuproxy.hs
|
mit
| 433 | 0 | 9 | 99 | 79 | 39 | 40 | 9 | 1 |
{-# htermination foldFM_LE :: (Float -> b -> c -> c) -> c -> Float -> FiniteMap Float b -> c #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_foldFM_LE_6.hs
|
mit
| 114 | 0 | 3 | 24 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGFilterPrimitiveStandardAttributes
(js_getX, getX, js_getY, getY, js_getWidth, getWidth, js_getHeight,
getHeight, js_getResult, getResult,
SVGFilterPrimitiveStandardAttributes,
castToSVGFilterPrimitiveStandardAttributes,
gTypeSVGFilterPrimitiveStandardAttributes)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"x\"]" js_getX ::
SVGFilterPrimitiveStandardAttributes ->
IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.x Mozilla SVGFilterPrimitiveStandardAttributes.x documentation>
getX ::
(MonadIO m) =>
SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength)
getX self = liftIO (nullableToMaybe <$> (js_getX (self)))
foreign import javascript unsafe "$1[\"y\"]" js_getY ::
SVGFilterPrimitiveStandardAttributes ->
IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.y Mozilla SVGFilterPrimitiveStandardAttributes.y documentation>
getY ::
(MonadIO m) =>
SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength)
getY self = liftIO (nullableToMaybe <$> (js_getY (self)))
foreign import javascript unsafe "$1[\"width\"]" js_getWidth ::
SVGFilterPrimitiveStandardAttributes ->
IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.width Mozilla SVGFilterPrimitiveStandardAttributes.width documentation>
getWidth ::
(MonadIO m) =>
SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength)
getWidth self = liftIO (nullableToMaybe <$> (js_getWidth (self)))
foreign import javascript unsafe "$1[\"height\"]" js_getHeight ::
SVGFilterPrimitiveStandardAttributes ->
IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.height Mozilla SVGFilterPrimitiveStandardAttributes.height documentation>
getHeight ::
(MonadIO m) =>
SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength)
getHeight self = liftIO (nullableToMaybe <$> (js_getHeight (self)))
foreign import javascript unsafe "$1[\"result\"]" js_getResult ::
SVGFilterPrimitiveStandardAttributes ->
IO (Nullable SVGAnimatedString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.result Mozilla SVGFilterPrimitiveStandardAttributes.result documentation>
getResult ::
(MonadIO m) =>
SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedString)
getResult self = liftIO (nullableToMaybe <$> (js_getResult (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGFilterPrimitiveStandardAttributes.hs
|
mit
| 3,633 | 30 | 10 | 513 | 727 | 424 | 303 | 56 | 1 |
-- and [] = True
-- and (x:xs) = x && and xs
and' :: [Bool] -> Bool
and' [] = True
and' (False:_) = False
and' (True:xs) = and' xs
concat' :: [[a]] -> [a]
concat' [] = []
concat' (x:xs) = x ++ concat xs
replicate' :: Int -> a -> [a]
replicate' 0 _ = []
replicate' n x = x : replicate' (n - 1) x
(!!!) :: [a] -> Int -> a
(!!!) [] _ = error "out of bounds"
(!!!) (x:_) 0 = x
(!!!) (_:xs) n = xs !!! (n - 1)
elem' :: Eq a => a -> [a] -> Bool
elem' _ [] = False
elem' n (x:xs)
| n == x = True
| otherwise = elem' n xs
main = do
print $ and' [True, False]
print $ and' [True, True]
print $ concat' [[1,2,3], [4,5,6]]
print $ replicate' 3 True
print $ [3,2,1] !!! 2
print $ elem' 1 [3,2,1]
print $ elem' 1 [3]
|
fabioyamate/programming-in-haskell
|
ch06/ex03.hs
|
mit
| 746 | 1 | 10 | 209 | 461 | 245 | 216 | 27 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.Functors.Wrapped where
import Prelude hiding (Functor, fmap)
import qualified Prelude
import qualified Data.Functor.Contravariant as Contravariant
import qualified Data.Functor.Invariant as Invariant
import qualified Data.Bifunctor as Bifunctor
import qualified Data.Profunctor as Profunctor
import Data.Functors.Types
newtype WrappedFunctor f a = WrappedFunctor { unwrapFunctor :: f a }
instance Prelude.Functor f => Functor (WrappedFunctor f) Covariant where
mapf f (WrappedFunctor a) = WrappedFunctor (Prelude.fmap f a)
newtype WrappedContravariant f a = WrappedContravariant { unwrapCovariant :: f a }
instance Contravariant.Contravariant f => Functor (WrappedContravariant f) Contravariant where
mapf f (WrappedContravariant a) = WrappedContravariant (Contravariant.contramap f a)
newtype WrappedInvariant f a = WrappedInvariant { unwrapInvariant :: f a }
instance Invariant.Invariant f => Functor (WrappedInvariant f) Invariant where
mapf (f, f') (WrappedInvariant a) = WrappedInvariant (Invariant.invmap f f' a)
newtype WrappedInvariant2 f a b = WrappedInvariant2 { unwrapInvariant2 :: f a b }
instance Invariant.Invariant2 f => Functor (WrappedInvariant2 f a) Invariant where
mapf (f, f') (WrappedInvariant2 a) = WrappedInvariant2 (Invariant.invmap2 id id f f' a)
instance Invariant.Invariant2 f => Bifunctor (WrappedInvariant2 f) Invariant Invariant where
mapbi (f, f') (g, g') (WrappedInvariant2 a) = WrappedInvariant2 (Invariant.invmap2 f f' g g' a)
newtype WrappedBifunctor f a b = WrappedBifunctor { unwrapBifunctor :: f a b }
instance Bifunctor.Bifunctor f => Functor (WrappedBifunctor f a) Covariant where
mapf f (WrappedBifunctor a) = WrappedBifunctor (Bifunctor.second f a)
instance Bifunctor.Bifunctor f => Bifunctor (WrappedBifunctor f) Covariant Covariant where
mapbi f g (WrappedBifunctor a) = WrappedBifunctor (Bifunctor.bimap f g a)
newtype WrappedProfunctor f a b = WrappedProfunctor { unwrapProfunctor :: f a b }
instance Profunctor.Profunctor f => Functor (WrappedProfunctor f a) Covariant where
mapf f (WrappedProfunctor a) = WrappedProfunctor (Profunctor.rmap f a)
instance Profunctor.Profunctor f => Bifunctor (WrappedProfunctor f) Contravariant Covariant where
mapbi f g (WrappedProfunctor a) = WrappedProfunctor (Profunctor.dimap f g a)
|
srijs/haskell-generalized-functors
|
src/Data/Functors/Wrapped.hs
|
mit
| 2,383 | 0 | 9 | 340 | 728 | 394 | 334 | 34 | 0 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE QuasiQuotes, OverloadedStrings, RecordWildCards #-}
{-# OPTIONS_GHC -Wwarn #-}
module Language.Bond.Codegen.Cpp.Util
( openNamespace
, closeNamespace
, structName
, structParams
, template
, modifierTag
, defaultValue
, attributeInit
, schemaMetadata
, ifndef
, defaultedFunctions
, rvalueReferences
, enumDefinition
) where
import Data.Monoid
import Prelude
import Data.Text.Lazy (Text)
import Text.Shakespeare.Text
import Language.Bond.Syntax.Types
import Language.Bond.Syntax.Util
import Language.Bond.Util
import Language.Bond.Codegen.Util
import Language.Bond.Codegen.TypeMapping
-- open namespaces
openNamespace :: MappingContext -> Text
openNamespace cpp = newlineSep 0 open $ getNamespace cpp
where
open n = [lt|namespace #{n}
{|]
-- close namespaces in reverse order
closeNamespace :: MappingContext -> Text
closeNamespace cpp = newlineSep 0 close (reverse $ getNamespace cpp)
where
close n = [lt|} // namespace #{n}|]
structName :: Declaration -> String
structName s@Struct {..} = declName <> structParams s
structName _ = error "structName: impossible happened."
structParams :: Declaration -> String
structParams Struct {..} = angles $ sepBy ", " paramName declParams
structParams _ = error "structName: impossible happened."
template :: Declaration -> Text
template d = if null $ declParams d then mempty else [lt|template <typename #{params}>
|]
where
params = sepBy ", typename " paramName $ declParams d
-- attribute initializer
attributeInit :: [Attribute] -> Text
attributeInit [] = "bond::reflection::Attributes()"
attributeInit xs = [lt|boost::assign::map_list_of<std::string, std::string>#{newlineBeginSep 5 attrNameValue xs}|]
where
idl = MappingContext idlTypeMapping [] [] []
attrNameValue Attribute {..} = [lt|("#{getQualifiedName idl attrName}", "#{attrValue}")|]
-- modifier tag type for a field
modifierTag :: Field -> Text
modifierTag Field {..} = [lt|bond::reflection::#{modifier fieldType fieldModifier}_field_modifier|]
where
modifier BT_MetaName _ = [lt|required_optional|]
modifier BT_MetaFullName _ = [lt|required_optional|]
modifier _ RequiredOptional = [lt|required_optional|]
modifier _ Required = [lt|required|]
modifier _ _ = [lt|optional|]
defaultValue :: MappingContext -> Type -> Default -> Text
defaultValue _ BT_WString (DefaultString x) = [lt|L"#{x}"|]
defaultValue _ BT_String (DefaultString x) = [lt|"#{x}"|]
defaultValue _ BT_Float (DefaultFloat x) = [lt|#{x}f|]
defaultValue _ BT_Int64 (DefaultInteger (-9223372036854775808)) = [lt|-9223372036854775807LL-1|]
defaultValue _ BT_Int64 (DefaultInteger x) = [lt|#{x}LL|]
defaultValue _ BT_UInt64 (DefaultInteger x) = [lt|#{x}ULL|]
defaultValue _ BT_Int32 (DefaultInteger (-2147483648)) = [lt|-2147483647-1|]
defaultValue m t (DefaultEnum x) = enumValue m t x
defaultValue _ _ (DefaultBool True) = "true"
defaultValue _ _ (DefaultBool False) = "false"
defaultValue _ _ (DefaultInteger x) = [lt|#{x}|]
defaultValue _ _ (DefaultFloat x) = [lt|#{x}|]
defaultValue _ _ (DefaultNothing) = mempty
defaultValue m (BT_UserDefined a@Alias {..} args) d = defaultValue m (resolveAlias a args) d
defaultValue _ _ _ = error "defaultValue: impossible happened."
enumValue :: ToText a => MappingContext -> Type -> a -> Text
enumValue cpp (BT_UserDefined e@Enum {..} _) x =
[lt|#{getQualifiedName cpp $ getDeclNamespace cpp e}::_bond_enumerators::#{declName}::#{x}|]
enumValue _ _ _ = error "enumValue: impossible happened."
-- schema metadata static member definitions
schemaMetadata :: MappingContext -> Declaration -> Text
schemaMetadata cpp s@Struct {..} = [lt|
#{template s}const bond::Metadata #{structName s}::Schema::metadata
= #{structName s}::Schema::GetMetadata();#{newlineBeginSep 1 staticDef structFields}|]
where
-- static member definition for field metadata
staticDef f@Field {..}
| fieldModifier == Optional && null fieldAttributes = [lt|
#{template s}const bond::Metadata #{structName s}::Schema::s_#{fieldName}_metadata
= bond::reflection::MetadataInit(#{defaultInit f}"#{fieldName}");|]
| otherwise = [lt|
#{template s}const bond::Metadata #{structName s}::Schema::s_#{fieldName}_metadata
= bond::reflection::MetadataInit(#{defaultInit f}"#{fieldName}", #{modifierTag f}::value,
#{attributeInit fieldAttributes});|]
where
defaultInit Field {fieldDefault = (Just def)} = [lt|#{explicitDefault def}, |]
defaultInit _ = mempty
explicitDefault (DefaultNothing) = "bond::nothing"
explicitDefault d@(DefaultInteger _) = staticCast d
explicitDefault d@(DefaultFloat _) = staticCast d
explicitDefault d = defaultValue cpp fieldType d
staticCast d = [lt|static_cast<#{getTypeName cpp fieldType}>(#{defaultValue cpp fieldType d})|]
schemaMetadata _ _ = error "schemaMetadata: impossible happened."
defaultedFunctions, rvalueReferences :: Text
defaultedFunctions = [lt|BOND_NO_CXX11_DEFAULTED_FUNCTIONS|]
rvalueReferences = [lt|BOND_NO_CXX11_RVALUE_REFERENCES|]
ifndef :: ToText a => a -> Text -> Text
ifndef m = between [lt|
#ifndef #{m}|] [lt|
#endif|]
enumDefinition :: Declaration -> Text
enumDefinition Enum {..} = [lt|enum #{declName}
{
#{commaLineSep 3 constant enumConstants}
};|]
where
constant Constant {..} = [lt|#{constantName}#{optional value constantValue}|]
value (-2147483648) = [lt| = -2147483647-1|]
value x = [lt| = #{x}|]
enumDefinition _ = error "enumDefinition: impossible happened."
|
alfpark/bond
|
compiler/src/Language/Bond/Codegen/Cpp/Util.hs
|
mit
| 5,770 | 0 | 16 | 965 | 1,330 | 761 | 569 | -1 | -1 |
module IODiscrete (displayTasks, getFiles, getNewTask, initIO, isGui) where
import Data.Char (toLower)
import Data.List (stripPrefix)
import Data.Map (Map)
import qualified Data.Map as Map
import Numeric.Natural
import System.Directory (doesDirectoryExist, listDirectory)
import System.IO
import System.IO.Error
import TodoData (Days(..), Datetime, Task(..), mkDate, mkDatetime, noDays)
import Utils
-- |'displayTasks' @tasks@ displays the passed tasks in the appropriate format.
-- TODO: implement
displayTasks :: Map FilePath [Task] -> IO ()
displayTasks = const $ return ()
-- |'initIO' is unnecessary for command line, since I/O is provided by the
-- system.
initIO :: IO ()
initIO = return ()
-- |'isGui' describes whether the configuration provides GUI capability.
isGui :: Bool
isGui = False
-- |'expandDir' converts a single file path to a list of all non-directory
-- descendents.
expandDir :: FilePath -> IO [FilePath]
expandDir fp = do
de <- doesDirectoryExist fp
if de
then do
conts <- listDirectory fp >>= mapM expandDir
return . map ((fp ++) . ('/':)) $ concat conts
else return [fp]
-- |'getFiles' provides a list of files to read as task files.
getFiles :: IO [FilePath]
getFiles = do
filename <- prompt "Enter file or folder name: "
if filename == ""
then return []
else do
rest <- getFiles
first <- expandDir filename
return $ first ++ rest
-- |'getNewTask' provides a new task to be added.
getNewTask :: IO (FilePath, Task)
getNewTask = do
name <- prompt "Enter task name: "
maxRep <- promptNatural "Enter number of repeats (0 to repeat forever): "
repNum <- (if maxRep > 0
then promptNatural "Enter current repeat: "
else return 0)
reps <- (if maxRep /= 1
then (prompt "Enter days to repeat (sun mon tue wed thu fri sat): "
>>= return . readRepDays)
else return noDays)
fp <- defaultTo (prompt "Enter file to save task to (default \"tasks.lst\"): ") "tasks.lst"
dt <- (do
dateStr <- prompt "Enter date (yyyymmdd): "
timeStr <- defaultTo (prompt "Enter time (hhmm, default 0000): ") "0000"
return $ read (dateStr ++ timeStr))
return $ (fp, Task name maxRep repNum reps dt)
where
defaultTo f s = f >>= (\v -> return $ if v == "" then s else v)
days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
readRepDays s = let [su, mo, tu, we, th, fr, sa] = checkConts days . map toLower $ s
in Days su mo tu we th fr sa
where
checkConts :: [String] -> String -> [Bool]
checkConts [] str = []
checkConts (day:rest) str =
let sfx = stripPrefix day str
in case sfx of
Nothing -> False:(checkConts rest str)
Just tl -> True:(checkConts rest $ drop 1 tl)
promptNatural p = prompt p >>= return . read :: IO Natural
|
dragonrider7225/TodoList
|
src/IOCmd.hs
|
mit
| 3,013 | 0 | 17 | 838 | 852 | 450 | 402 | 63 | 6 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.SVGPathSegArcRel (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.SVGPathSegArcRel
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.SVGPathSegArcRel
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/SVGPathSegArcRel.hs
|
mit
| 361 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
module SvgArcSegment (
convertSvgArc
) where
import Types
radiansPerDegree :: Double
radiansPerDegree = pi / 180.0
calculateVectorAngle :: Double -> Double -> Double -> Double -> Double
calculateVectorAngle ux uy vx vy
| tb >= ta
= tb - ta
| otherwise
= pi * 2 - (ta - tb)
where
ta = atan2 uy ux
tb = atan2 vy vx
-- ported from: https://github.com/vvvv/SVG/blob/master/Source/Paths/SvgArcSegment.cs
convertSvgArc :: Point -> Double -> Double -> Double -> Bool -> Bool -> Point -> [DrawOp]
convertSvgArc (x0,y0) radiusX radiusY angle largeArcFlag sweepFlag (x,y)
| x0 == x && y0 == y
= []
| radiusX == 0.0 && radiusY == 0.0
= [DLineTo (x,y)]
| otherwise
= calcSegments x0 y0 theta1' segments'
where
sinPhi = sin (angle * radiansPerDegree)
cosPhi = cos (angle * radiansPerDegree)
x1dash = cosPhi * (x0 - x) / 2.0 + sinPhi * (y0 - y) / 2.0
y1dash = -sinPhi * (x0 - x) / 2.0 + cosPhi * (y0 - y) / 2.0
numerator = radiusX * radiusX * radiusY * radiusY - radiusX * radiusX * y1dash * y1dash - radiusY * radiusY * x1dash * x1dash
s = sqrt(1.0 - numerator / (radiusX * radiusX * radiusY * radiusY))
rx = if' (numerator < 0.0) (radiusX * s) radiusX
ry = if' (numerator < 0.0) (radiusY * s) radiusY
root = if' (numerator < 0.0)
(0.0)
((if' ((largeArcFlag && sweepFlag) || (not largeArcFlag && not sweepFlag)) (-1.0) 1.0) *
sqrt(numerator / (radiusX * radiusX * y1dash * y1dash + radiusY * radiusY * x1dash * x1dash)))
cxdash = root * rx * y1dash / ry
cydash = -root * ry * x1dash / rx
cx = cosPhi * cxdash - sinPhi * cydash + (x0 + x) / 2.0
cy = sinPhi * cxdash + cosPhi * cydash + (y0 + y) / 2.0
theta1' = calculateVectorAngle 1.0 0.0 ((x1dash - cxdash) / rx) ((y1dash - cydash) / ry)
dtheta' = calculateVectorAngle ((x1dash - cxdash) / rx) ((y1dash - cydash) / ry) ((-x1dash - cxdash) / rx) ((-y1dash - cydash) / ry)
dtheta = if' (not sweepFlag && dtheta' > 0)
(dtheta' - 2 * pi)
(if' (sweepFlag && dtheta' < 0) (dtheta' + 2 * pi) dtheta')
segments' = ceiling (abs (dtheta / (pi / 2.0)))
delta = dtheta / fromInteger segments'
t = 8.0 / 3.0 * sin(delta / 4.0) * sin(delta / 4.0) / sin(delta / 2.0)
calcSegments startX startY theta1 segments
| segments == 0
= []
| otherwise
= (DBezierTo (startX + dx1, startY + dy1) (endpointX + dxe, endpointY + dye) (endpointX, endpointY) : calcSegments endpointX endpointY theta2 (segments - 1))
where
cosTheta1 = cos theta1
sinTheta1 = sin theta1
theta2 = theta1 + delta
cosTheta2 = cos theta2
sinTheta2 = sin theta2
endpointX = cosPhi * rx * cosTheta2 - sinPhi * ry * sinTheta2 + cx
endpointY = sinPhi * rx * cosTheta2 + cosPhi * ry * sinTheta2 + cy
dx1 = t * (-cosPhi * rx * sinTheta1 - sinPhi * ry * cosTheta1)
dy1 = t * (-sinPhi * rx * sinTheta1 + cosPhi * ry * cosTheta1)
dxe = t * (cosPhi * rx * sinTheta2 + sinPhi * ry * cosTheta2)
dye = t * (sinPhi * rx * sinTheta2 - cosPhi * ry * cosTheta2)
|
domoszlai/juicy-gcode
|
src/SvgArcSegment.hs
|
mit
| 3,563 | 0 | 20 | 1,287 | 1,328 | 698 | 630 | 61 | 1 |
module Main where
import Test.DocTest
main :: IO ()
main = doctest ["src"]
|
bioboxes/signature-validator
|
doctest.hs
|
mit
| 77 | 0 | 6 | 15 | 30 | 17 | 13 | 4 | 1 |
module GHCJS.DOM.XMLSerializer (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/XMLSerializer.hs
|
mit
| 43 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
import Text.Printf
main = do
line <- getLine
let arr = (map read $ words line) :: [Double]
putStrLn . printf "%.3f" $ sum arr / 3
|
Voleking/ICPC
|
references/aoapc-book/BeginningAlgorithmContests/haskell/ch1/ex1-1.hs
|
mit
| 137 | 0 | 12 | 34 | 67 | 32 | 35 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Querying for a financial organization takes a
-- FinancialOrganizationPermalink, which can be obtained from a
-- search.
module Data.API.CrunchBase.FinancialOrganizationQuery
( FinancialOrganizationQuery(..)
, FinancialOrganizationPermalink(..)
) where
import Data.API.CrunchBase.Query
import qualified Data.Text as T
import Data.Aeson (FromJSON(..), Value(..))
newtype FinancialOrganizationQuery =
FinancialOrganizationQuery FinancialOrganizationPermalink
deriving (Eq, Show, Read)
instance Query FinancialOrganizationQuery where
toPathSegments (FinancialOrganizationQuery
(FinancialOrganizationPermalink permalink)) =
["v", "1", "financial-organization", permalink `T.append` ".js"]
toQueryItems _ = []
newtype FinancialOrganizationPermalink =
FinancialOrganizationPermalink T.Text
deriving (Eq, Show, Read)
instance FromJSON FinancialOrganizationPermalink where
parseJSON (String s) = return . FinancialOrganizationPermalink $ s
|
whittle/crunchbase
|
Data/API/CrunchBase/FinancialOrganizationQuery.hs
|
mit
| 1,039 | 0 | 10 | 159 | 200 | 120 | 80 | 20 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RecordWildCards #-}
module Db.Model where
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import Data.Aeson (ToJSON, FromJSON)
import Control.Monad.Reader
import GHC.Generics (Generic)
import Database.Persist.Sql
import Database.Persist.TH (mkMigrate, mkPersist, persistLowerCase,
share, sqlSettings)
import Config (Action, WithConfig, getPool)
share [mkMigrate "migrateAll", mkPersist sqlSettings] [persistLowerCase|
Course json
program Text
term Text
code Text
name Text
level Text
importance Text
block Text
credits Int
wholeTerm Bool
created UTCTime default=now()
deriving Show
|]
doMigrations :: SqlPersistM ()
doMigrations = runMigration migrateAll
runDb :: SqlPersistT IO a -> WithConfig a
runDb query = do
pool <- asks getPool
liftIO $ runSqlPool query pool
|
SebastianCallh/liu-courses
|
src/Db/Model.hs
|
mit
| 1,306 | 0 | 8 | 296 | 200 | 118 | 82 | 29 | 1 |
--
-- Programazio Funtzionala - 2002/2003 PRAKTIKA Huffman kodeketa
--
import DmaAVL
import DmaZuBiP
---------------------------------------------------------------------------------------
-- OHARRA: txertatuRAVL funtzioaren inplementazioa DmaAVL.hs fitxategian dago --
-- eta modulu horrek esportatu egin behar du funtzio hori honek funtziona --
-- dezan --
---------------------------------------------------------------------------------------
-- mergeSort ordenazio algoritmoarean inplementazioa
-- praktika guztian zehar erabiliko denez, funtzio bat
-- du parametro gisa, zerrendako elementu bakoitzaren gakoa
-- lortzeko. Gako horren arabera egingo da ordenazioa
mergeSort :: (Ord b) => [a] -> (a -> b) -> [a]
mergeSort list gakoaLortu
| luzera > 1 = merge (mergeSort (take erdia list) gakoaLortu)
(mergeSort (drop erdia list) gakoaLortu)
gakoaLortu
| otherwise = list
where
erdia = luzera `div` 2
luzera = length list
merge :: (Ord b) => [a] -> [a] -> (a -> b) -> [a]
merge [] list2 gakoaLortu = list2
merge list1 [] gakoaLortu = list1
merge (x:xs) (y:ys) gakoaLortu
| gakoaLortu x < gakoaLortu y = (x:(merge xs (y:ys) gakoaLortu))
| gakoaLortu x == gakoaLortu y = (x:y:(merge xs ys gakoaLortu))
| otherwise = (y:(merge (x:xs) ys) gakoaLortu)
----------------
-- 1.go fasea --
----------------
----
--Zuhaitzekin
----
type AVL = ZuAVL (Char,Int)
--txertatuRAVL :: (Char,Int) -> ZuAVL (Char,Int) -> ZuAVL (Char,Int)
--txertatuRAVL x Hutsa = Errotu 0 Hutsa x Hutsa
--txertatuRAVL (x1,x2) (Errotu h xt (y1,y2) zt)
-- | (x1<y1) = batuAVL (txertatuRAVL (x1,x2) xt) (y1,y2) zt
-- | (x1==y1) = Errotu h xt (x1,1 + y2) zt
-- | (x1>y1) = batuAVL xt (y1,y2) (txertatuRAVL (x1,x2) zt)
eginZuhaitza :: String -> ZuAVL (Char,Int)
eginZuhaitza [] = Hutsa
--txertatuRAVL egitean (x,1) jartzen dut, baina (x,_) izango litzateke (sistemak ez du
--onartzen) bilaketa lehen elementuaren arabera egiten du "fst" funtzioari esker. Zuhaitzean
--elementu hori (x,_) baldin badago, jadanik zuhaitzean dagoenari batu funtzioa aplikatzen
--dio bigarren elementuaren balioa inkrementatzeko
eginZuhaitza (x:xs) = txertatuRAVL (x,1) (eginZuhaitza xs) fst batu
where batu (x1,x2) = (x1,x2 + 1)
zuhaitza = Hutsa
lautuZuhaitza :: ZuAVL (Char,Int) -> [(Char,Int)]
lautuZuhaitza Hutsa = []
lautuZuhaitza (Errotu h xt y zt) = (lautuZuhaitza xt) ++ [y] ++ (lautuZuhaitza zt)
scanTestua :: String -> [(Char,Int)]
scanTestua [] = []
scanTestua x = mergeSort ((lautuZuhaitza.eginZuhaitza) x) snd
----
--Zerrendekin
----
sortuZerrenda :: String -> [(Char,Int)]
sortuZerrenda [] = []
sortuZerrenda (x:xs) = ((x,1):sortuZerrenda xs)
ordena1 :: [(Char,Int)] -> [(Char,Int)]
ordena1 xs = mergeSort xs fst
batulehenak :: [(Char,Int)] -> [(Char,Int)]
batulehenak [] = []
batulehenak (x:[]) = [x]
batulehenak (x:(y:xs))
| fst x == fst y = batulehenak ((fst x,(snd x) +1): xs)
| otherwise = (x:batulehenak (y:xs))
scanTestua1 :: String -> [(Char,Int)]
scanTestua1 [] = []
scanTestua1 xs = mergeSort ((batulehenak.ordena1.sortuZerrenda) xs) snd
----------------
-- 2. fasea --
----------------
type HuffmanZu = ZuBiP (Char,Int) Int
hostoZerrenda :: [(Char,Int)] -> [HuffmanZu]
hostoZerrenda = map hostoZuBiP
eginHuffmanZu :: [HuffmanZu] -> HuffmanZu
eginHuffmanZu (x:[]) = x
eginHuffmanZu (x:(y:xs)) = eginHuffmanZu (mergeSort ((eraikiZuBiP
((esan x) + (esan y)) x y ) : xs) esan)
where esan (HP z) = snd z
esan (EP e _ _) = e
huffZu :: String -> HuffmanZu
huffZu = eginHuffmanZu.hostoZerrenda.scanTestua
----------------
-- 3. fasea --
----------------
type Kode = String
lortuTaula :: HuffmanZu -> [(Char,Kode)]
lortuTaula (HP a) = [(fst a,[])]
lortuTaula (EP m xt yt) = hufmerge (lortuTaula xt) (lortuTaula yt)
hufmerge :: [(Char,Kode)] -> [(Char,Kode)] -> [(Char,Kode)]
hufmerge [] ycs = [(y,'1':cs)|(y,cs) <- ycs]
hufmerge xbs [] = [(x,'0':bs)|(x,bs) <- xbs]
hufmerge ((x,bs):xbs)((y,cs):ycs)
| length bs <= length cs = (x,'0':bs):hufmerge xbs ((y,cs):ycs)
| otherwise = (y,'1':cs):hufmerge((x,bs):xbs) ycs
kodeaSortu :: [(Char,Kode)] -> Char -> Kode
kodeaSortu ((y,cs):ycs) x
| x == y = cs
| otherwise = kodeaSortu ycs x
kodetu :: String -> HuffmanZu -> Kode
kodetu xs zu = concat (map (kodeaSortu codetable) xs)
where codetable = lortuTaula zu
----------------
-- 4. fasea --
----------------
deskodetu :: HuffmanZu-> Kode -> String
deskodetu zu [] = []
deskodetu zu xs = deskod zu xs
where deskod (EP a ez es) ('0':cs) = deskod ez cs
deskod (EP a ez es) ('1':cs) = deskod es cs
deskod (HP (x1,x2)) cs = x1:deskodetu zu cs
|
erral/huffman_kodeketa
|
praktika.hs
|
gpl-2.0
| 4,757 | 7 | 16 | 934 | 1,728 | 939 | 789 | 77 | 3 |
module Test where {
f x = let {g y = a + y;a=10} in g 3;
}
|
bredelings/BAli-Phy
|
tests/optimizer/3/test.hs
|
gpl-2.0
| 59 | 0 | 9 | 18 | 44 | 25 | 19 | 2 | 1 |
module Ch7_2 where
import qualified Data.Char as C
-- given a function that takes pair as parameter
add :: Num a => (a,a) -> a
add (x,y) = x + y
-- Given the curry function
cur :: ((a,b) -> c) -> a -> b -> c
cur f = \x -> \y -> f (x,y)
-- here are examples:
-- *Ch7_2> (cur add) 1 2
-- 3
-- *Ch7_2> ((cur add) 1) 2
-- 3
-- which can be put simply
currify :: ((a,b) -> c) -> a -> b -> c
currify f x y = f (x,y)
-- *Ch7_2> (currify add) 1 2
-- 3
-- *Ch7_2> ((currify add) 1) 2
-- 3
uncur :: (a -> b -> c) -> (a, b) -> c
uncur f = \ (x, y) -> (f x y)
-- *Ch7_2> add (1,2)
-- 3
-- *Ch7_2> (cur add) 1 2
-- 3
-- *Ch7_2> uncur (cur add) (1,2)
-- 3
-- which can be put simply
uncurrify :: (a -> b -> c) -> (a, b) -> c
uncurrify f (x, y) = f x y
-- *Ch7_2> uncurrify (currify add) (1,2)
-- 3
unfold :: (t -> Bool) -> (t -> a) -> (t -> t) -> t -> [a]
unfold p h t x | p x = []
| otherwise = h x : unfold p h t (t x)
type Bit = Int
-- int2bin :: Int -> [Bit]
-- int2bin 0 = []
-- int2bin n = int2bin (n `div` 2) ++ [n `mod` 2]
-- then
int2bin0 :: Int -> [Bit]
int2bin0 = unfold (== 0) (`mod` 2) (`div` 2)
-- *Ch7_2> int2bin 20
-- [0,0,1,0,1]
-- *Ch7_2> int2bin 128
-- [0,0,0,0,0,0,0,1]
chop8 :: [Bit] -> [[Bit]]
chop8 = unfold null (take 8) (drop 8)
-- *Ch7_2> chop8 [1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0]
-- [[1,1,0,1,0,0,1,0],[1,1,0,1,0,0,1,0],[1,1,0,1,0,0,1,0]]
mapu :: (a -> b) -> [a] -> [b]
mapu f = unfold null (f . head) tail
-- *Ch7_2> mapu (+1) [1,2,4]
-- [2,3,5]
-- *Ch7_2> mapu even [1,2,4]
-- [False,True,True]
-- *Ch7_2> mapu int2bin [1,2,4,8,16]
-- [[1],[0,1],[0,0,1],[0,0,0,1],[0,0,0,0,1]]
iter :: (a -> a) -> a -> [a]
iter f x = x : iter f (f x)
-- *Ch7_2> take 10 (iter (+1) 10)
-- [10,11,12,13,14,15,16,17,18,19]
iter2 :: (a -> a) -> a -> [a]
iter2 f = unfold (\ _ -> False) id f
-- *Ch7_2> take 10 (iter2 (+1) 10)
-- [10,11,12,13,14,15,16,17,18,19]
-- *Ch7_2> take 10 (iter2 (+2) 0)
-- [0,2,4,6,8,10,12,14,16,18]
iter3 :: (a -> a) -> a -> [a]
iter3 f = unfold (const False) id f
-- *Ch7_2> take 10 (iter3 (*2) 0)
-- [0,2,4,6,8,10,12,14,16,18]
bin2int :: [Bit] -> Int
bin2int = foldl (\ x y -> x * 2 + y) 0
-- *Ch7> bin2int [0,0,0,0,1,1,0,1]
-- 13
-- make sure a list of bits is of same length 8
make8 :: [Bit] -> [Bit]
make8 bits = reverse (take 8 (reverse bits ++ repeat 0))
-- *Ch7> make8 [1,1,0,1]
-- [0,0,0,0,1,1,0,1]
-- *Ch7> bin2int (make8 [1,1,0,1])
-- 13
parbit :: [Bit] -> [Bit]
parbit xs | even (sum xs) = xs ++ [0] -- even number of ones
| otherwise = xs ++ [1] -- odd number of ones
-- *Ch7_2> parbit [1,1,0]
-- [1,1,0,0]
-- *Ch7_2> parbit [1,1,1]
-- [1,1,1,1]
int2bin :: Int -> [Bit]
int2bin 0 = []
int2bin n = int2bin (n `div` 2) ++ [n `mod` 2]
encode :: String -> [Bit]
encode = concat . map (parbit . make8 . int2bin . C.ord)
checkParbit :: [Bit] -> [Bit]
checkParbit xs | (parbit (take 8 xs) == xs) = (take 8 xs)
| otherwise = error "Not ok"
-- *Ch7_2> checkParbit (encode "a")
-- [0,1,0,0,0,0,1,1]
-- *Ch7_2> checkParbit [0,1,0,0,0,0,1,0]
-- *** Exception: Not ok
chop9 :: [Bit] -> [[Bit]]
chop9 = unfold null (take 9) (drop 9)
decode :: [Bit] -> String
decode = map (C.chr . bin2int . checkParbit) . chop9
channel :: [a] -> [a]
channel = tail
transmit :: String -> String
transmit = decode . channel . encode
-- *Ch7_2> transmit "haskell is great"
-- "\209\195\231\215\202\216\216A\210\231A\207\228\202\195*** Exception: Not ok
|
ardumont/haskell-lab
|
src/programming-in-haskell/ch7_2.hs
|
gpl-2.0
| 3,451 | 0 | 12 | 765 | 1,139 | 647 | 492 | 51 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Estuary.Help.Saborts where
import Reflex
import Reflex.Dom
import Data.Text
import GHCJS.DOM.EventM
import Estuary.Widgets.Reflex
import Estuary.Widgets.Reflex
sabortsHelpFile :: MonadWidget t m => m ()
sabortsHelpFile = divClass "languageHelpContainer" $ divClass "languageHelp" $ do
about
functionRef "g"
functionRef "b"
functionRef "v"
functionRef "d"
functionRef "k"
functionRef "m"
functionRef "h"
functionRef "i"
functionRef "t"
functionRef "a"
functionRef "c"
functionRef "o"
functionRef "e"
functionRef "w"
functionRef "q"
functionRef "s"
functionRef "z"
return ()
-- about
about :: MonadWidget t m => m ()
about = do
divClass "about primary-color code-font" $ text "Saborts"
divClass "about primary-color code-font" $ text "A mini live coding esolang developed in Quito, Ecuador by RGGTRN."
exampleText :: Text -> Text
exampleText "g" = ":> g"
exampleText "b" = ":> b"
exampleText "v" = ":> v"
exampleText "d" = ":> d"
exampleText "k" = ":> k"
exampleText "m" = ":> m"
exampleText "h" = ":> h"
exampleText "i" = ":> i"
exampleText "t" = ":> t"
exampleText "a" = ":> a"
exampleText "c" = ":> c"
exampleText "o" = ":> o"
exampleText "e" = ":> e"
exampleText "w" = ":> gw"
exampleText "q" = ":> bq3"
exampleText "s" = ":> vs0.5"
exampleText "z" = ":> dz8"
referenceText :: Text -> Text
referenceText "g" = "returns Dirt's \"drumtraks\" sample"
referenceText "b" = "returns Dirt's \"bd\" sample"
referenceText "v" = "returns Dirt's \"bd:1\" sample"
referenceText "d" = "returns Dirt's \"bd:2\" sample"
referenceText "k" = "returns Dirt's \"bd:3\" sample"
referenceText "m" = "returns Dirt's \"bass:1\" sample"
referenceText "h" = "returns Dirt's \"hh27\" sample"
referenceText "i" = "returns Dirt's \"hh:7\" sample"
referenceText "t" = "returns Dirt's \"sn:1\" sample"
referenceText "a" = "returns Dirt's \"sn:2\" sample"
referenceText "c" = "returns Dirt's \"cp:1\" sample"
referenceText "o" = "returns Dirt's \"drum\" sample"
referenceText "e" = "returns Dirt's \"drum:1\" sample"
referenceText "w" = "returns TidalCycles' brak"
referenceText "q" = "returns TidalCycles' fast"
referenceText "s" = "returns TidalCycles' slow"
referenceText "z" = "returns TidalCycles' gap"
-- help files for samples
functionRef :: MonadWidget t m => Text -> m ()
functionRef x = divClass "helpWrapper" $ do
switchToReference <- buttonWithClass' x
exampleVisible <- toggle True switchToReference
referenceVisible <- toggle False switchToReference
hideableWidget exampleVisible "exampleText primary-color code-font" $ text (exampleText x)
hideableWidget referenceVisible "referenceText code-font" $ text (referenceText x)
return ()
|
d0kt0r0/estuary
|
client/src/Estuary/Help/Saborts.hs
|
gpl-3.0
| 2,732 | 0 | 11 | 446 | 654 | 305 | 349 | 77 | 1 |
module AutoRefresh (AutoSignal(..), autoSignal, autoRunner) where
import Control.Applicative
import Control.Concurrent
import Control.Exception
import Control.Monad
import Network.Tremulous.MicroTime
import Monad2
import Config
data AutoSignal = AutoUpdate | AutoStop | AutoStart | AutoPause | AutoResume
deriving Show
data State = Running !ThreadId | Paused | Stopped
autoSignal :: MVar AutoSignal -> AutoSignal -> IO ()
autoSignal = putMVar
autoRunner :: MVar AutoSignal -> MVar Config -> IO a -> IO ThreadId
autoRunner m mconfig refreshAction = forkIO $ go Stopped Nothing
where
go :: State -> Maybe MicroTime -> IO a
go state timestamp = do
st <- takeMVar m
case st of
AutoStart -> case state of
Running _ -> go state timestamp
_ -> do tid <- startAuto mconfig timestamp refreshAction
go (Running tid) timestamp
AutoStop -> case state of
Running tid -> killThread tid >> go Stopped timestamp
_ -> go Stopped timestamp
AutoUpdate -> do
timestamp' <- Just <$> getMicroTime
case state of
Running tid -> do
killThread tid
tid' <- startAuto mconfig timestamp' refreshAction
go (Running tid') timestamp'
_ -> go state timestamp'
AutoPause | Running tid <- state -> do
killThread tid
go Paused timestamp
AutoResume | Paused <- state -> do
tid <- startAuto mconfig timestamp refreshAction
go (Running tid) timestamp
_ -> go state timestamp
startAuto :: MVar Config -> Maybe MicroTime -> IO a -> IO ThreadId
startAuto mconfig lastRefresh refreshAction = uninterruptibleMask $ \restore -> forkIO $ do
delay <- autoRefreshDelay <$> readMVar mconfig
whenJust lastRefresh $ \past -> do
now <- getMicroTime
when (past+delay > now) $
restore $ threadDelay (fromIntegral (past+delay-now))
refreshAction
return ()
|
Cadynum/Apelsin
|
src/AutoRefresh.hs
|
gpl-3.0
| 1,830 | 4 | 21 | 392 | 628 | 300 | 328 | 52 | 9 |
{-# LANGUAGE ScopedTypeVariables #-}
module Math.Structure.Tasty.NonZero.SmallCheck
where
import Data.Functor.Identity
import Test.SmallCheck.Series
import Math.Structure.Additive
instance (Monad m, DecidableZero a, Serial Identity a)
=> Serial m (NonZero a) where
series = generate $ \d ->
map nonZero . filter (not . isZero) $
list d (series::Series Identity a)
|
martinra/algebraic-structures
|
src/Math/Structure/Tasty/NonZero/SmallCheck.hs
|
gpl-3.0
| 409 | 0 | 12 | 91 | 118 | 66 | 52 | -1 | -1 |
import Minitel.Minitel
import Minitel.Generate.Generator
import Minitel.Generate.Configuration
import Minitel.Type.MString
import Minitel.Type.Videotex
import Minitel.UI.Widget
import Minitel.UI.Interface
import Minitel.UI.Dispatcher
import Minitel.UI.TextField
-- | Defines the background of our textual user interface
back :: [MString]
back =
[ mVisibleCursor True
, mClear ReallyEverything
, mLocate 1 0
, mString VideoTex "HaMinitel, Haskell’s Minitel library"
, mLocate 1 2
, mSize DoubleWidth DoubleHeight
, mForeground Green
, mString VideoTex "Interface demo"
, mRectangle 2 4 36 15 Blue
, mLocate 3 5
, mSize DoubleWidth SimpleHeight
, mString VideoTex "Tell me about you"
, mLocate 3 6
, mRepeat 34 0x5f
, mLocate 3 8
, mForeground Yellow
, mString VideoTex "First name:"
, mLocate 3 10
, mForeground Yellow
, mString VideoTex "Last name:"
, mLocate 3 12
, mForeground Yellow
, mString VideoTex "Age:"
]
-- | Defines the interactive elements of our textual user interface
focuss :: [IO TextField]
focuss =
[ newTextField att { posX = 17, posY = 8 } 15 ""
, newTextField att { posX = 17, posY = 10 } 15 ""
, newTextField att { posX = 17, posY = 12 } 3 ""
]
where att = CommonAttributes { mode = VideoTex
, posX = 1
, posY = 1
, foreground = White
, background = Blue
}
main :: IO ()
main = do
m <- minitel "/dev/ttyUSB0" baseSettings
m <<< [ mExtendedKeyboard True
, mCursorKeys True
, mLowercaseKeyboard True
, mEchoing False
]
fss <- sequence focuss
_ <- runInterface m (newInterface back fss)
waitForMinitel m
|
Zigazou/HaMinitel
|
example/testInterface.hs
|
gpl-3.0
| 2,063 | 0 | 10 | 793 | 468 | 253 | 215 | 54 | 1 |
module Exprs where
data Val = IntV Integer
| FloatV Float
| CharV Char
| StringV String
| BooleanV Bool
-- since we are implementing a Functional language, functions are
-- first class citizens.
| LambdaV [String] Expr Env
deriving (Show, Eq)
-----------------------------------------------------------
data Expr =
Const Val
-- represents a variable
| Var String
-- integer multiplication
| Expr :*: Expr
-- integer addition and string concatenation
| Expr :+: Expr
-- equality test. Defined for all Val except FunVal
| Expr :==: Expr
-- semantically equivalent to a Haskell `if`
| If Expr Expr Expr
-- binds a Var (the first `Expr`) to a value (the second `Expr`),
-- and makes that binding available in the third expression
| Let String Expr Expr
-- similar to Let but allows for recursive definitions. You can also make
-- the above Let support this, and simply remove this expression. But since
-- implementing a recursive definition of Let is a bit trickier, you will want
-- at least implement a non-recursive Let.
| Letrec String Expr Expr
-- creates an anonymous function with an arbitrary number of parameters
| Lambda [String] Expr
-- calls a function with an arbitrary number values for parameters
| Apply Expr [Expr]
deriving (Show, Eq)
data Env = EmptyEnv
| ExtendEnv String Val Env
deriving (Show, Eq)
|
2016-Fall-UPT-PLDA/labs
|
week-04/Exprs.hs
|
gpl-3.0
| 1,695 | 0 | 7 | 601 | 192 | 117 | 75 | 23 | 0 |
module Language.VHDL.Quote.Quoters
( ident
, name
, expr
, seqstm
, seqstms
, constm
, constms
, designfile
, designunit
, libraryunit
, primaryunit
, contextitem
, contextitems
, blockdecl
, blockdecls
, assocel
, assocels
, wave
, procdecl
, procdecls
, lit
, slit
, clit
, elassoc
, casealt
, ifacedecl
, subtyind
, packdeclit
) where
import Language.Haskell.TH.Quote (QuasiQuoter)
import Language.VHDL.Parser
import Language.VHDL.Quote.Internal
ident, name, expr, seqstm, seqstms, constm, constms, designfile, designunit, libraryunit, primaryunit, contextitem, contextitems, blockdecl, blockdecls, assocel, assocels, wave, procdecl, procdecls, slit, clit, lit, elassoc, casealt, ifacedecl, subtyind, packdeclit :: QuasiQuoter
ident = quasiquote parseName
name = quasiquote parseName
expr = quasiquote parseExpr
seqstm = quasiquote parseSeqStm
seqstms = quasiquote parseSeqStms
constm = quasiquote parseConStm
constms = quasiquote parseConStms
designfile = quasiquote parseDesignFileQ
designunit = quasiquote parseDesignUnit
libraryunit = quasiquote parseLibraryUnit
primaryunit = quasiquote parsePrimaryUnit
contextitem = quasiquote parseContextItem
contextitems = quasiquote parseContextItems
blockdecl = quasiquote parseBlockDeclIt
blockdecls = quasiquote parseBlockDeclIts
assocel = quasiquote parseAssociationEl
assocels = quasiquote parseAssociationEls
wave = quasiquote parseWaveform
procdecl = quasiquote parseProcDecl
procdecls = quasiquote parseProcDecls
lit = quasiquote parseLiteral
slit = quasiquote parseStringLit
clit = quasiquote parseCharLit
elassoc = quasiquote parseElAssoc
casealt = quasiquote parseCaseAlt
ifacedecl = quasiquote parseIfaceDecl
subtyind = quasiquote parseSubtyInd
packdeclit = quasiquote parsePackDecl
|
truls/language-vhdl-quote
|
src/Language/VHDL/Quote/Quoters.hs
|
mpl-2.0
| 1,837 | 0 | 5 | 304 | 402 | 249 | 153 | 61 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.CloudPrivateCatalogProducer.Catalogs.TestIAMPermissions
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Tests the IAM permissions for the specified Catalog.
--
-- /See:/ <https://cloud.google.com/private-catalog/ Cloud Private Catalog Producer API Reference> for @cloudprivatecatalogproducer.catalogs.testIamPermissions@.
module Network.Google.Resource.CloudPrivateCatalogProducer.Catalogs.TestIAMPermissions
(
-- * REST Resource
CatalogsTestIAMPermissionsResource
-- * Creating a Request
, catalogsTestIAMPermissions
, CatalogsTestIAMPermissions
-- * Request Lenses
, ctipXgafv
, ctipUploadProtocol
, ctipAccessToken
, ctipUploadType
, ctipPayload
, ctipResource
, ctipCallback
) where
import Network.Google.CloudPrivateCatalogProducer.Types
import Network.Google.Prelude
-- | A resource alias for @cloudprivatecatalogproducer.catalogs.testIamPermissions@ method which the
-- 'CatalogsTestIAMPermissions' request conforms to.
type CatalogsTestIAMPermissionsResource =
"v1beta1" :>
CaptureMode "resource" "testIamPermissions" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] GoogleIAMV1TestIAMPermissionsRequest
:> Post '[JSON] GoogleIAMV1TestIAMPermissionsResponse
-- | Tests the IAM permissions for the specified Catalog.
--
-- /See:/ 'catalogsTestIAMPermissions' smart constructor.
data CatalogsTestIAMPermissions =
CatalogsTestIAMPermissions'
{ _ctipXgafv :: !(Maybe Xgafv)
, _ctipUploadProtocol :: !(Maybe Text)
, _ctipAccessToken :: !(Maybe Text)
, _ctipUploadType :: !(Maybe Text)
, _ctipPayload :: !GoogleIAMV1TestIAMPermissionsRequest
, _ctipResource :: !Text
, _ctipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CatalogsTestIAMPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctipXgafv'
--
-- * 'ctipUploadProtocol'
--
-- * 'ctipAccessToken'
--
-- * 'ctipUploadType'
--
-- * 'ctipPayload'
--
-- * 'ctipResource'
--
-- * 'ctipCallback'
catalogsTestIAMPermissions
:: GoogleIAMV1TestIAMPermissionsRequest -- ^ 'ctipPayload'
-> Text -- ^ 'ctipResource'
-> CatalogsTestIAMPermissions
catalogsTestIAMPermissions pCtipPayload_ pCtipResource_ =
CatalogsTestIAMPermissions'
{ _ctipXgafv = Nothing
, _ctipUploadProtocol = Nothing
, _ctipAccessToken = Nothing
, _ctipUploadType = Nothing
, _ctipPayload = pCtipPayload_
, _ctipResource = pCtipResource_
, _ctipCallback = Nothing
}
-- | V1 error format.
ctipXgafv :: Lens' CatalogsTestIAMPermissions (Maybe Xgafv)
ctipXgafv
= lens _ctipXgafv (\ s a -> s{_ctipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ctipUploadProtocol :: Lens' CatalogsTestIAMPermissions (Maybe Text)
ctipUploadProtocol
= lens _ctipUploadProtocol
(\ s a -> s{_ctipUploadProtocol = a})
-- | OAuth access token.
ctipAccessToken :: Lens' CatalogsTestIAMPermissions (Maybe Text)
ctipAccessToken
= lens _ctipAccessToken
(\ s a -> s{_ctipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ctipUploadType :: Lens' CatalogsTestIAMPermissions (Maybe Text)
ctipUploadType
= lens _ctipUploadType
(\ s a -> s{_ctipUploadType = a})
-- | Multipart request metadata.
ctipPayload :: Lens' CatalogsTestIAMPermissions GoogleIAMV1TestIAMPermissionsRequest
ctipPayload
= lens _ctipPayload (\ s a -> s{_ctipPayload = a})
-- | REQUIRED: The resource for which the policy detail is being requested.
-- See the operation documentation for the appropriate value for this
-- field.
ctipResource :: Lens' CatalogsTestIAMPermissions Text
ctipResource
= lens _ctipResource (\ s a -> s{_ctipResource = a})
-- | JSONP
ctipCallback :: Lens' CatalogsTestIAMPermissions (Maybe Text)
ctipCallback
= lens _ctipCallback (\ s a -> s{_ctipCallback = a})
instance GoogleRequest CatalogsTestIAMPermissions
where
type Rs CatalogsTestIAMPermissions =
GoogleIAMV1TestIAMPermissionsResponse
type Scopes CatalogsTestIAMPermissions =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient CatalogsTestIAMPermissions'{..}
= go _ctipResource _ctipXgafv _ctipUploadProtocol
_ctipAccessToken
_ctipUploadType
_ctipCallback
(Just AltJSON)
_ctipPayload
cloudPrivateCatalogProducerService
where go
= buildClient
(Proxy :: Proxy CatalogsTestIAMPermissionsResource)
mempty
|
brendanhay/gogol
|
gogol-cloudprivatecatalogproducer/gen/Network/Google/Resource/CloudPrivateCatalogProducer/Catalogs/TestIAMPermissions.hs
|
mpl-2.0
| 5,685 | 0 | 16 | 1,198 | 778 | 454 | 324 | 115 | 1 |
-- A regression test for <https://bugs.freedesktop.org/show_bug.cgi?id=44714>.
--
-- log-with-h.bustle is a log file containing a file handle. This used to make
-- readPcap call 'error'.
module Main where
import System.Exit (exitFailure)
import Bustle.Loader.Pcap (readPcap)
path = "Test/data/log-with-h.bustle"
main = do
ret <- readPcap path
case ret of
Left e -> do
putStrLn $ "Failed to read '" ++ path ++ "': " ++ show e
exitFailure
-- TODO: check there are no warnings (but there are because we don't
-- understand 'h', so we just skip it)
Right _ -> return ()
|
wjt/bustle
|
Test/PcapCrash.hs
|
lgpl-2.1
| 633 | 0 | 15 | 159 | 106 | 56 | 50 | 11 | 2 |
module Moonbase.Util.Cairo where
import qualified Graphics.Rendering.Cairo as Cairo
import Moonbase.Core
import Moonbase.Theme
import Moonbase.Util.Gtk
sourceColor :: Color -> Cairo.Render ()
sourceColor color = Cairo.setSourceRGBA r g b a
where
(r,g,b,a) = clamp $ parseColorTuple color
|
felixsch/moonbase-ng
|
src/Moonbase/Util/Cairo.hs
|
lgpl-2.1
| 327 | 0 | 8 | 74 | 94 | 54 | 40 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
-------------------------------------------------------------------------------
import Aws
import Aws.DynamoDb.Commands
import Aws.DynamoDb.Core
import Control.Concurrent
import Control.Monad
import Control.Monad.Catch
import Data.Conduit
import qualified Data.Conduit.List as C
import qualified Data.Text as T
import Network.HTTP.Conduit (withManager)
-------------------------------------------------------------------------------
createTableAndWait :: IO ()
createTableAndWait = do
let req0 = createTable "devel-1"
[AttributeDefinition "name" AttrString]
(HashOnly "name")
(ProvisionedThroughput 1 1)
resp0 <- runCommand req0
print resp0
print "Waiting for table to be created"
threadDelay (30 * 1000000)
let req1 = DescribeTable "devel-1"
resp1 <- runCommand req1
print resp1
main :: IO ()
main = do
cfg <- Aws.baseConfiguration
createTableAndWait `catch` (\DdbError{} -> putStrLn "Table already exists")
putStrLn "Putting an item..."
let x = item [ attrAs text "name" "josh"
, attrAs text "class" "not-so-awesome"]
let req1 = (putItem "devel-1" x ) { piReturn = URAllOld
, piRetCons = RCTotal
, piRetMet = RICMSize
}
resp1 <- runCommand req1
print resp1
putStrLn "Getting the item back..."
let req2 = getItem "devel-1" (hk "name" "josh")
resp2 <- runCommand req2
print resp2
print =<< runCommand
(updateItem "devel-1" (hk "name" "josh") [au (Attribute "class" "awesome")])
echo "Updating with false conditional."
(print =<< runCommand
(updateItem "devel-1" (hk "name" "josh") [au (Attribute "class" "awesomer")])
{ uiExpect = Conditions CondAnd [Condition "name" (DEq "john")] })
`catch` (\ (e :: DdbError) -> echo ("Eating exception: " ++ show e))
echo "Getting the item back..."
print =<< runCommand req2
echo "Updating with true conditional"
print =<< runCommand
(updateItem "devel-1" (hk "name" "josh") [au (Attribute "class" "awesomer")])
{ uiExpect = Conditions CondAnd [Condition "name" (DEq "josh")] }
echo "Getting the item back..."
print =<< runCommand req2
echo "Running a Query command..."
print =<< runCommand (query "devel-1" (Slice (Attribute "name" "josh") Nothing))
echo "Running a Scan command..."
print =<< runCommand (scan "devel-1")
echo "Filling table with several items..."
forM_ [0..30] $ \ i -> do
threadDelay 50000
runCommand $ putItem "devel-1" $
item [Attribute "name" (toValue $ T.pack ("lots-" ++ show i)), attrAs int "val" i]
echo "Now paginating in increments of 5..."
let q0 = (scan "devel-1") { sLimit = Just 5 }
xs <- withManager $ \mgr -> do
awsIteratedList cfg debugServiceConfig mgr q0 $$ C.consume
echo ("Pagination returned " ++ show (length xs) ++ " items")
-- runCommand :: forall r a . r -> IO (MemoryResponse a)
runCommand r = do
cfg <- Aws.baseConfiguration
let
myServiceConfig :: DdbConfiguration NormalQuery
myServiceConfig = ddbHttps euWest1
-- Aws.simpleAws cfg debugServiceConfig r
Aws.simpleAws cfg myServiceConfig r
-- Aws.simpleAws cfg _ r
echo = putStr
euWest1 = Region "dynamodb.eu-west-1.amazonaws.com" "eu-west-1"
|
alanz/aws-dynamodb-play
|
src/DynamoDb.hs
|
unlicense
| 3,601 | 0 | 20 | 862 | 947 | 461 | 486 | 82 | 1 |
module SimpleJSON
(
JValue(..),
getString,
getInt,
getDouble,
getBool,
getObject,
getArray,
isNull
) where
data JValue = JString String
| JNumber Double
| JBool Bool
| JNull
| JObject [(String, JValue)]
| JArray [JValue]
deriving (Eq, Ord, Show)
getString :: JValue -> Maybe String
getString (JString val) = Just val
getString _ = Nothing
getInt :: JValue -> Maybe Int
getInt (JNumber n) = Just (truncate n)
getInt _ = Nothing
getDouble :: JValue -> Maybe Double
getDouble (JNumber n) = Just n
getDouble _ = Nothing
getBool :: JValue -> Maybe Bool
getBool (JBool b) = Just b
getBool _ = Nothing
getObject :: JValue -> Maybe [(String, JValue)]
getObject (JObject o) = Just o
getObject _ = Nothing
getArray :: JValue -> Maybe [JValue]
getArray (JArray a) = Just a
getArray _ = Nothing
isNull :: JValue -> Bool
isNull v = v == JNull
|
shashikiranrp/RealWorldHaskell
|
Chapter 5/SimpleJSON.hs
|
apache-2.0
| 994 | 0 | 8 | 310 | 354 | 188 | 166 | 37 | 1 |
module Network.HTTPMock.RequestMatchers ( matchPath
, matchEverything
, matchMethod
, matchPathAndMethod) where
import Prelude (and)
import ClassyPrelude
import Network.HTTPMock.Types
import Network.HTTP.Types (Method)
import Network.HTTPMock.Utils
matchEverything :: RequestMatcher
matchEverything = RequestMatcher $ const True
matchPath :: Text -> RequestMatcher
matchPath path = RequestMatcher $ matchPath' path
matchMethod :: Method -> RequestMatcher
matchMethod meth = RequestMatcher $ matchMethod' meth
matchPathAndMethod :: Text -> Method -> RequestMatcher
matchPathAndMethod path meth = RequestMatcher checkAll
where checkAll req = and $ map ($req) [matchPath' path, matchMethod' meth]
matchPath' :: Text -> Request -> Bool
matchPath' path = (== path) . requestPath
matchMethod' :: Method -> Request -> Bool
matchMethod' meth = (== meth) . _requestMethod
|
MichaelXavier/HTTPMock
|
src/Network/HTTPMock/RequestMatchers.hs
|
bsd-2-clause
| 992 | 0 | 10 | 238 | 239 | 131 | 108 | 22 | 1 |
{-# LANGUAGE PatternGuards #-}
module IRTS.CodegenJavaScript (codegenJavaScript, codegenNode, JSTarget(..)) where
import Idris.AbsSyntax hiding (TypeCase)
import IRTS.Bytecode
import IRTS.Lang
import IRTS.Simplified
import IRTS.CodegenCommon
import Idris.Core.TT
import Paths_idris
import Util.System
import Control.Arrow
import Control.Applicative ((<$>), (<*>), pure)
import Data.Char
import Numeric
import Data.List
import Data.Maybe
import Data.Word
import System.IO
import System.Directory
idrNamespace :: String
idrNamespace = "__IDR__"
idrRTNamespace = "__IDRRT__"
idrLTNamespace = "__IDRLT__"
idrCTRNamespace = "__IDRCTR__"
data JSTarget = Node | JavaScript deriving Eq
data JSType = JSIntTy
| JSStringTy
| JSIntegerTy
| JSFloatTy
| JSCharTy
| JSPtrTy
| JSForgotTy
deriving Eq
data JSInteger = JSBigZero
| JSBigOne
| JSBigInt Integer
deriving Eq
data JSNum = JSInt Int
| JSFloat Double
| JSInteger JSInteger
deriving Eq
data JSWord = JSWord8 Word8
| JSWord16 Word16
| JSWord32 Word32
| JSWord64 Word64
deriving Eq
data JSAnnotation = JSConstructor deriving Eq
instance Show JSAnnotation where
show JSConstructor = "constructor"
data JS = JSRaw String
| JSIdent String
| JSFunction [String] JS
| JSType JSType
| JSSeq [JS]
| JSReturn JS
| JSApp JS [JS]
| JSNew String [JS]
| JSError String
| JSBinOp String JS JS
| JSPreOp String JS
| JSPostOp String JS
| JSProj JS String
| JSVar LVar
| JSNull
| JSThis
| JSTrue
| JSFalse
| JSArray [JS]
| JSString String
| JSNum JSNum
| JSWord JSWord
| JSAssign JS JS
| JSAlloc String (Maybe JS)
| JSIndex JS JS
| JSCond [(JS, JS)]
| JSTernary JS JS JS
| JSParens JS
| JSWhile JS JS
| JSFFI String [JS]
| JSAnnotation JSAnnotation JS
| JSNoop
deriving Eq
data FFI = FFICode Char | FFIArg Int | FFIError String
ffi :: String -> [String] -> String
ffi code args = let parsed = ffiParse code in
case ffiError parsed of
Just err -> error err
Nothing -> renderFFI parsed args
where
ffiParse :: String -> [FFI]
ffiParse "" = []
ffiParse ['%'] = [FFIError $ "FFI - Invalid positional argument"]
ffiParse ('%':'%':ss) = FFICode '%' : ffiParse ss
ffiParse ('%':s:ss)
| isDigit s =
FFIArg (read $ s : takeWhile isDigit ss) : ffiParse (dropWhile isDigit ss)
| otherwise =
[FFIError $ "FFI - Invalid positional argument"]
ffiParse (s:ss) = FFICode s : ffiParse ss
ffiError :: [FFI] -> Maybe String
ffiError [] = Nothing
ffiError ((FFIError s):xs) = Just s
ffiError (x:xs) = ffiError xs
renderFFI :: [FFI] -> [String] -> String
renderFFI [] _ = ""
renderFFI ((FFICode c) : fs) args = c : renderFFI fs args
renderFFI ((FFIArg i) : fs) args
| i < length args && i >= 0 = args !! i ++ renderFFI fs args
| otherwise = error "FFI - Argument index out of bounds"
compileJS :: JS -> String
compileJS JSNoop = ""
compileJS (JSAnnotation annotation js) =
"/** @" ++ show annotation ++ " */\n" ++ compileJS js
compileJS (JSFFI raw args) =
ffi raw (map compileJS args)
compileJS (JSRaw code) =
code
compileJS (JSIdent ident) =
ident
compileJS (JSFunction args body) =
"function("
++ intercalate "," args
++ "){\n"
++ compileJS body
++ "\n}"
compileJS (JSType ty)
| JSIntTy <- ty = idrRTNamespace ++ "Int"
| JSStringTy <- ty = idrRTNamespace ++ "String"
| JSIntegerTy <- ty = idrRTNamespace ++ "Integer"
| JSFloatTy <- ty = idrRTNamespace ++ "Float"
| JSCharTy <- ty = idrRTNamespace ++ "Char"
| JSPtrTy <- ty = idrRTNamespace ++ "Ptr"
| JSForgotTy <- ty = idrRTNamespace ++ "Forgot"
compileJS (JSSeq seq) =
intercalate ";\n" (map compileJS seq)
compileJS (JSReturn val) =
"return " ++ compileJS val
compileJS (JSApp lhs rhs)
| JSFunction {} <- lhs =
concat ["(", compileJS lhs, ")(", args, ")"]
| otherwise =
concat [compileJS lhs, "(", args, ")"]
where args :: String
args = intercalate "," $ map compileJS rhs
compileJS (JSNew name args) =
"new " ++ name ++ "(" ++ intercalate "," (map compileJS args) ++ ")"
compileJS (JSError exc) =
"throw new Error(\"" ++ exc ++ "\")"
compileJS (JSBinOp op lhs rhs) =
compileJS lhs ++ " " ++ op ++ " " ++ compileJS rhs
compileJS (JSPreOp op val) =
op ++ compileJS val
compileJS (JSProj obj field)
| JSFunction {} <- obj =
concat ["(", compileJS obj, ").", field]
| JSAssign {} <- obj =
concat ["(", compileJS obj, ").", field]
| otherwise =
compileJS obj ++ '.' : field
compileJS (JSVar var) =
translateVariableName var
compileJS JSNull =
"null"
compileJS JSThis =
"this"
compileJS JSTrue =
"true"
compileJS JSFalse =
"false"
compileJS (JSArray elems) =
"[" ++ intercalate "," (map compileJS elems) ++ "]"
compileJS (JSString str) =
"\"" ++ str ++ "\""
compileJS (JSNum num)
| JSInt i <- num = show i
| JSFloat f <- num = show f
| JSInteger JSBigZero <- num = "__IDRRT__ZERO"
| JSInteger JSBigOne <- num = "__IDRRT__ONE"
| JSInteger (JSBigInt i) <- num = show i
compileJS (JSAssign lhs rhs) =
compileJS lhs ++ "=" ++ compileJS rhs
compileJS (JSAlloc name val) =
"var " ++ name ++ maybe "" ((" = " ++) . compileJS) val
compileJS (JSIndex lhs rhs) =
compileJS lhs ++ "[" ++ compileJS rhs ++ "]"
compileJS (JSCond branches) =
intercalate " else " $ map createIfBlock branches
where
createIfBlock (JSNoop, e) =
"{\n"
++ compileJS e
++ ";\n}"
createIfBlock (cond, e) =
"if (" ++ compileJS cond ++") {\n"
++ compileJS e
++ ";\n}"
compileJS (JSTernary cond true false) =
let c = compileJS cond
t = compileJS true
f = compileJS false in
"(" ++ c ++ ")?(" ++ t ++ "):(" ++ f ++ ")"
compileJS (JSParens js) =
"(" ++ compileJS js ++ ")"
compileJS (JSWhile cond body) =
"while (" ++ compileJS cond ++ ") {\n"
++ compileJS body
++ "\n}"
compileJS (JSWord word)
| JSWord8 b <- word = "new Uint8Array([" ++ show b ++ "])"
| JSWord16 b <- word = "new Uint16Array([" ++ show b ++ "])"
| JSWord32 b <- word = "new Uint32Array([" ++ show b ++ "])"
| JSWord64 b <- word = idrRTNamespace ++ "bigInt(\"" ++ show b ++ "\")"
jsTailcall :: JS -> JS
jsTailcall call =
jsCall (idrRTNamespace ++ "tailcall") [
JSFunction [] (JSReturn call)
]
jsCall :: String -> [JS] -> JS
jsCall fun = JSApp (JSIdent fun)
jsMeth :: JS -> String -> [JS] -> JS
jsMeth obj meth =
JSApp (JSProj obj meth)
jsInstanceOf :: JS -> JS -> JS
jsInstanceOf = JSBinOp "instanceof"
jsEq :: JS -> JS -> JS
jsEq = JSBinOp "=="
jsAnd :: JS -> JS -> JS
jsAnd = JSBinOp "&&"
jsOr :: JS -> JS -> JS
jsOr = JSBinOp "||"
jsType :: JS
jsType = JSIdent $ idrRTNamespace ++ "Type"
jsCon :: JS
jsCon = JSIdent $ idrRTNamespace ++ "Con"
jsTag :: JS -> JS
jsTag obj = JSProj obj "tag"
jsTypeTag :: JS -> JS
jsTypeTag obj = JSProj obj "type"
jsBigInt :: JS -> JS
jsBigInt (JSString "0") = JSNum $ JSInteger JSBigZero
jsBigInt (JSString "1") = JSNum $ JSInteger JSBigOne
jsBigInt val = JSApp (JSIdent $ idrRTNamespace ++ "bigInt") [val]
jsVar :: Int -> String
jsVar = ("__var_" ++) . show
jsLet :: String -> JS -> JS -> JS
jsLet name value body =
JSApp (
JSFunction [name] (
JSReturn body
)
) [value]
jsError :: String -> JS
jsError err = JSApp (JSFunction [] (JSError err)) []
jsUnPackBits :: JS -> JS
jsUnPackBits js = JSIndex js $ JSNum (JSInt 0)
jsPackUBits8 :: JS -> JS
jsPackUBits8 js = JSNew "Uint8Array" [JSArray [js]]
jsPackUBits16 :: JS -> JS
jsPackUBits16 js = JSNew "Uint16Array" [JSArray [js]]
jsPackUBits32 :: JS -> JS
jsPackUBits32 js = JSNew "Uint32Array" [JSArray [js]]
jsPackSBits8 :: JS -> JS
jsPackSBits8 js = JSNew "Int8Array" [JSArray [js]]
jsPackSBits16 :: JS -> JS
jsPackSBits16 js = JSNew "Int16Array" [JSArray [js]]
jsPackSBits32 :: JS -> JS
jsPackSBits32 js = JSNew "Int32Array" [JSArray [js]]
foldJS :: (JS -> a) -> (a -> a -> a) -> a -> JS -> a
foldJS tr add acc js =
fold js
where
fold js
| JSFunction args body <- js =
add (tr js) (fold body)
| JSSeq seq <- js =
add (tr js) $ foldl' add acc (map fold seq)
| JSReturn ret <- js =
add (tr js) (fold ret)
| JSApp lhs rhs <- js =
add (tr js) $ add (fold lhs) (foldl' add acc $ map fold rhs)
| JSNew _ args <- js =
add (tr js) $ foldl' add acc $ map fold args
| JSBinOp _ lhs rhs <- js =
add (tr js) $ add (fold lhs) (fold rhs)
| JSPreOp _ val <- js =
add (tr js) $ fold val
| JSPostOp _ val <- js =
add (tr js) $ fold val
| JSProj obj _ <- js =
add (tr js) (fold obj)
| JSArray vals <- js =
add (tr js) $ foldl' add acc $ map fold vals
| JSAssign lhs rhs <- js =
add (tr js) $ add (fold lhs) (fold rhs)
| JSIndex lhs rhs <- js =
add (tr js) $ add (fold lhs) (fold rhs)
| JSAlloc _ val <- js =
add (tr js) $ fromMaybe acc $ fmap fold val
| JSTernary c t f <- js =
add (tr js) $ add (fold c) (add (fold t) (fold f))
| JSParens val <- js =
add (tr js) $ fold val
| JSCond conds <- js =
add (tr js) $ foldl' add acc $ map (uncurry add . (fold *** fold)) conds
| JSWhile cond body <- js =
add (tr js) $ add (fold cond) (fold body)
| JSFFI raw args <- js =
add (tr js) $ foldl' add acc $ map fold args
| JSAnnotation a js <- js =
add (tr js) $ fold js
| otherwise =
tr js
transformJS :: (JS -> JS) -> JS -> JS
transformJS tr js =
transformHelper js
where
transformHelper :: JS -> JS
transformHelper js
| JSFunction args body <- js = JSFunction args $ tr body
| JSSeq seq <- js = JSSeq $ map tr seq
| JSReturn ret <- js = JSReturn $ tr ret
| JSApp lhs rhs <- js = JSApp (tr lhs) $ map tr rhs
| JSNew con args <- js = JSNew con $ map tr args
| JSBinOp op lhs rhs <- js = JSBinOp op (tr lhs) (tr rhs)
| JSPreOp op val <- js = JSPreOp op (tr val)
| JSPostOp op val <- js = JSPostOp op (tr val)
| JSProj obj field <- js = JSProj (tr obj) field
| JSArray vals <- js = JSArray $ map tr vals
| JSAssign lhs rhs <- js = JSAssign (tr lhs) (tr rhs)
| JSAlloc var val <- js = JSAlloc var $ fmap tr val
| JSIndex lhs rhs <- js = JSIndex (tr lhs) (tr rhs)
| JSCond conds <- js = JSCond $ map (tr *** tr) conds
| JSTernary c t f <- js = JSTernary (tr c) (tr t) (tr f)
| JSParens val <- js = JSParens $ tr val
| JSWhile cond body <- js = JSWhile (tr cond) (tr body)
| JSFFI raw args <- js = JSFFI raw (map tr args)
| JSAnnotation a js <- js = JSAnnotation a (tr js)
| otherwise = js
moveJSDeclToTop :: String -> [JS] -> [JS]
moveJSDeclToTop decl js = move ([], js)
where
move :: ([JS], [JS]) -> [JS]
move (front, js@(JSAnnotation _ (JSAlloc name _)):back)
| name == decl = js : front ++ back
move (front, js@(JSAlloc name _):back)
| name == decl = js : front ++ back
move (front, js:back) =
move (front ++ [js], back)
jsSubst :: JS -> JS -> JS -> JS
jsSubst var new old
| var == old = new
jsSubst (JSIdent var) new (JSVar old)
| var == translateVariableName old = new
| otherwise = JSVar old
jsSubst var new old@(JSIdent _)
| var == old = new
| otherwise = old
jsSubst var new (JSArray fields) =
JSArray (map (jsSubst var new) fields)
jsSubst var new (JSNew con vals) =
JSNew con $ map (jsSubst var new) vals
jsSubst (JSIdent var) new (JSApp (JSProj (JSFunction args body) "apply") vals)
| var `notElem` args =
JSApp (JSProj (JSFunction args (jsSubst (JSIdent var) new body)) "apply") (
map (jsSubst (JSIdent var) new) vals
)
| otherwise =
JSApp (JSProj (JSFunction args body) "apply") (
map (jsSubst (JSIdent var) new) vals
)
jsSubst (JSIdent var) new (JSApp (JSFunction [arg] body) vals)
| var /= arg =
JSApp (JSFunction [arg] (
jsSubst (JSIdent var) new body
)) $ map (jsSubst (JSIdent var) new) vals
| otherwise =
JSApp (JSFunction [arg] (
body
)) $ map (jsSubst (JSIdent var) new) vals
jsSubst var new js = transformJS (jsSubst var new) js
removeAllocations :: JS -> JS
removeAllocations (JSSeq body) =
let opt = removeHelper (map removeAllocations body) in
case opt of
[ret] -> ret
_ -> JSSeq opt
where
removeHelper :: [JS] -> [JS]
removeHelper [js] = [js]
removeHelper ((JSAlloc name (Just val@(JSIdent _))):js) =
map (jsSubst (JSIdent name) val) (removeHelper js)
removeHelper (j:js) = j : removeHelper js
removeAllocations js = transformJS removeAllocations js
isJSConstant :: JS -> Bool
isJSConstant js
| JSString _ <- js = True
| JSNum _ <- js = True
| JSType _ <- js = True
| JSNull <- js = True
| JSArray vals <- js = all isJSConstant vals
| JSApp (JSIdent "__IDRRT__bigInt") _ <- js = True
| otherwise = False
isJSConstantConstructor :: [String] -> JS -> Bool
isJSConstantConstructor constants js
| isJSConstant js =
True
| JSArray vals <- js =
all (isJSConstantConstructor constants) vals
| JSNew "__IDRRT__Con" args <- js =
all (isJSConstantConstructor constants) args
| JSIndex (JSProj (JSIdent name) "vars") (JSNum _) <- js
, name `elem` constants =
True
| JSIdent name <- js
, name `elem` constants =
True
| otherwise = False
inlineJS :: JS -> JS
inlineJS = inlineAssign . inlineError . inlineApply . inlineCaseMatch . inlineJSLet
where
inlineJSLet :: JS -> JS
inlineJSLet (JSApp (JSFunction [arg] (JSReturn ret)) [val])
| opt <- inlineJSLet val =
inlineJS $ jsSubst (JSIdent arg) opt ret
inlineJSLet js = transformJS inlineJSLet js
inlineCaseMatch (JSReturn (JSApp (JSFunction ["cse"] body) [val]))
| opt <- inlineCaseMatch val =
inlineCaseMatch $ jsSubst (JSIdent "cse") opt body
inlineCaseMatch js = transformJS inlineCaseMatch js
inlineApply js
| JSApp (
JSProj (JSFunction args (JSReturn body)) "apply"
) [JSThis, JSProj var "vars"] <- js =
inlineApply $ inlineApply' var args body 0
| JSReturn (JSApp (
JSProj (JSFunction args body@(JSCond _)) "apply"
) [JSThis, JSProj var "vars"]) <- js =
inlineApply $ inlineApply' var args body 0
where
inlineApply' _ [] body _ = body
inlineApply' var (a:as) body n =
inlineApply' var as (
jsSubst (JSIdent a) (
JSIndex (JSProj var "vars") (JSNum (JSInt n))
) body
) (n + 1)
inlineApply js = transformJS inlineApply js
inlineError (JSReturn (JSApp (JSFunction [] error@(JSError _)) [])) =
inlineError error
inlineError js = transformJS inlineError js
inlineAssign (JSAssign lhs rhs)
| JSVar _ <- lhs
, JSVar _ <- rhs
, lhs == rhs =
lhs
inlineAssign (JSAssign lhs rhs)
| JSIdent _ <- lhs
, JSIdent _ <- rhs
, lhs == rhs =
lhs
inlineAssign js = transformJS inlineAssign js
removeEval :: [JS] -> [JS]
removeEval js =
let (ret, isReduced) = checkEval js in
if isReduced
then removeEvalApp ret
else ret
where
removeEvalApp js = catMaybes (map removeEvalApp' js)
where
removeEvalApp' :: JS -> Maybe JS
removeEvalApp' (JSAlloc "__IDR__mEVAL0" _) = Nothing
removeEvalApp' js = Just $ transformJS match js
where
match (JSApp (JSIdent "__IDR__mEVAL0") [val]) = val
match js = transformJS match js
checkEval :: [JS] -> ([JS], Bool)
checkEval js = foldr f ([], False) $ map checkEval' js
where
f :: (Maybe JS, Bool) -> ([JS], Bool) -> ([JS], Bool)
f (Just js, isReduced) (ret, b) = (js : ret, isReduced || b)
f (Nothing, isReduced) (ret, b) = (ret, isReduced || b)
checkEval' :: JS -> (Maybe JS, Bool)
checkEval' (JSAlloc "__IDRLT__EVAL" (Just (JSApp (JSFunction [] (
JSSeq [ _
, JSReturn (JSIdent "t")
]
)) []))) = (Nothing, True)
checkEval' js = (Just js, False)
reduceJS :: [JS] -> [JS]
reduceJS js = moveJSDeclToTop "__IDRRT__Con" $ reduceLoop [] ([], js)
funName :: JS -> String
funName (JSAlloc fun _) = fun
elimDeadLoop :: [JS] -> [JS]
elimDeadLoop js
| ret <- deadEvalApplyCases js
, ret /= js = elimDeadLoop ret
| otherwise = js
deadEvalApplyCases :: [JS] -> [JS]
deadEvalApplyCases js =
let tags = sort $ nub $ concatMap (getTags) js in
map (removeHelper tags) js
where
getTags :: JS -> [Int]
getTags = foldJS match (++) []
where
match js
| JSNew "__IDRRT__Con" [JSNum (JSInt tag), _] <- js = [tag]
| otherwise = []
removeHelper :: [Int] -> JS -> JS
removeHelper tags (JSAlloc fun (Just (
JSApp (JSFunction [] (JSSeq seq)) []))
) =
(JSAlloc fun (Just (
JSApp (JSFunction [] (JSSeq $ remover tags seq)) []))
)
removeHelper _ js = js
remover :: [Int] -> [JS] -> [JS]
remover tags (
j@(JSAssign ((JSIndex (JSIdent "t") (JSNum (JSInt tag)))) _):js
)
| tag `notElem` tags = remover tags js
remover tags (j:js) = j : remover tags js
remover _ [] = []
initConstructors :: [JS] -> [JS]
initConstructors js =
let tags = nub $ sort $ concat (map getTags js) in
rearrangePrelude $ map createConstant tags ++ replaceConstructors tags js
where
rearrangePrelude :: [JS] -> [JS]
rearrangePrelude = moveJSDeclToTop $ idrRTNamespace ++ "Con"
getTags :: JS -> [Int]
getTags = foldJS match (++) []
where
match js
| JSNew "__IDRRT__Con" [JSNum (JSInt tag), JSArray []] <- js = [tag]
| otherwise = []
replaceConstructors :: [Int] -> [JS] -> [JS]
replaceConstructors tags js = map (replaceHelper tags) js
where
replaceHelper :: [Int] -> JS -> JS
replaceHelper tags (JSNew "__IDRRT__Con" [JSNum (JSInt tag), JSArray []])
| tag `elem` tags = JSIdent (idrCTRNamespace ++ show tag)
replaceHelper tags js = transformJS (replaceHelper tags) js
createConstant :: Int -> JS
createConstant tag =
JSAlloc (idrCTRNamespace ++ show tag) (Just (
JSNew (idrRTNamespace ++ "Con") [JSNum (JSInt tag), JSArray []]
))
removeIDs :: [JS] -> [JS]
removeIDs js =
case partition isID js of
([], rest) -> rest
(ids, rest) -> removeIDs $ map (removeIDCall (map idFor ids)) rest
where isID :: JS -> Bool
isID (JSAlloc _ (Just (JSFunction _ (JSSeq body))))
| JSReturn (JSVar _) <- last body = True
isID _ = False
idFor :: JS -> (String, Int)
idFor (JSAlloc fun (Just (JSFunction _ (JSSeq body))))
| JSReturn (JSVar (Loc pos)) <- last body = (fun, pos)
removeIDCall :: [(String, Int)] -> JS -> JS
removeIDCall ids (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
JSReturn (JSApp (JSIdent fun) args)
)])
| Just pos <- lookup fun ids
, pos < length args = removeIDCall ids (args !! pos)
removeIDCall ids (JSNew _ [JSFunction [] (
JSReturn (JSApp (JSIdent fun) args)
)])
| Just pos <- lookup fun ids
, pos < length args = removeIDCall ids (args !! pos)
removeIDCall ids js@(JSApp id@(JSIdent fun) args)
| Just pos <- lookup fun ids
, pos < length args = removeIDCall ids (args !! pos)
removeIDCall ids js = transformJS (removeIDCall ids) js
inlineFunction :: String -> [String] -> JS -> JS -> JS
inlineFunction fun args body js = inline' js
where
inline' :: JS -> JS
inline' (JSApp (JSIdent name) vals)
| name == fun =
let (js, phs) = insertPlaceHolders args body in
inline' $ foldr (uncurry jsSubst) js (zip phs vals)
inline' js = transformJS inline' js
insertPlaceHolders :: [String] -> JS -> (JS, [JS])
insertPlaceHolders args body = insertPlaceHolders' args body []
where
insertPlaceHolders' :: [String] -> JS -> [JS] -> (JS, [JS])
insertPlaceHolders' (a:as) body ph
| (body', ph') <- insertPlaceHolders' as body ph =
let phvar = JSIdent $ "__PH_" ++ show (length ph') in
(jsSubst (JSIdent a) phvar body', phvar : ph')
insertPlaceHolders' [] body ph = (body, ph)
inlineFunctions :: [JS] -> [JS]
inlineFunctions js =
inlineHelper ([], js)
where
inlineHelper :: ([JS], [JS]) -> [JS]
inlineHelper (front , (JSAlloc fun (Just (JSFunction args body))):back)
| countAll fun front + countAll fun back == 0 =
inlineHelper (front, back)
| Just new <- inlineAble (
countAll fun front + countAll fun back
) fun args body =
let f = map (inlineFunction fun args new) in
inlineHelper (f front, f back)
inlineHelper (front, next:back) = inlineHelper (front ++ [next], back)
inlineHelper (front, []) = front
inlineAble :: Int -> String -> [String] -> JS -> Maybe JS
inlineAble 1 fun args (JSReturn body)
| nonRecur fun body =
if all (<= 1) (map ($ body) (map countIDOccurences args))
then Just body
else Nothing
inlineAble _ _ _ _ = Nothing
nonRecur :: String -> JS -> Bool
nonRecur name body = countInvokations name body == 0
countAll :: String -> [JS] -> Int
countAll name js = sum $ map (countInvokations name) js
countIDOccurences :: String -> JS -> Int
countIDOccurences name = foldJS match (+) 0
where
match :: JS -> Int
match js
| JSIdent ident <- js
, name == ident = 1
| otherwise = 0
countInvokations :: String -> JS -> Int
countInvokations name = foldJS match (+) 0
where
match :: JS -> Int
match js
| JSApp (JSIdent ident) _ <- js
, name == ident = 1
| JSNew con _ <- js
, name == con = 1
| otherwise = 0
reduceContinuations :: JS -> JS
reduceContinuations = inlineTC . reduceJS
where
reduceJS :: JS -> JS
reduceJS (JSNew "__IDRRT__Cont" [JSFunction [] (
JSReturn js@(JSNew "__IDRRT__Cont" [JSFunction [] body])
)]) = reduceJS js
reduceJS js = transformJS reduceJS js
inlineTC :: JS -> JS
inlineTC js
| JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
JSReturn (JSNew "__IDRRT__Cont" [JSFunction [] (
JSReturn ret@(JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
JSReturn (JSNew "__IDRRT__Cont" _)
)])
)])
)] <- js = inlineTC ret
inlineTC js = transformJS inlineTC js
reduceConstant :: JS -> JS
reduceConstant
(JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
JSReturn (JSApp (JSIdent "__IDR__mEVAL0") [val])
)])
| JSNum num <- val = val
| JSBinOp op lhs rhs <- val =
JSParens $ JSBinOp op (reduceConstant lhs) (reduceConstant rhs)
| JSApp (JSProj lhs op) [rhs] <- val
, op `elem` [ "subtract"
, "add"
, "multiply"
, "divide"
, "mod"
, "equals"
, "lesser"
, "lesserOrEquals"
, "greater"
, "greaterOrEquals"
] = val
reduceConstant (JSApp ident [(JSParens js)]) =
JSApp ident [reduceConstant js]
reduceConstant js = transformJS reduceConstant js
reduceConstants :: JS -> JS
reduceConstants js
| ret <- reduceConstant js
, ret /= js = reduceConstants ret
| otherwise = js
elimDuplicateEvals :: JS -> JS
elimDuplicateEvals (JSAlloc fun (Just (JSFunction args (JSSeq seq)))) =
JSAlloc fun $ Just (JSFunction args $ JSSeq (elimHelper seq))
where
elimHelper :: [JS] -> [JS]
elimHelper (j@(JSAlloc var (Just val)):js) =
j : map (jsSubst val (JSIdent var)) (elimHelper js)
elimHelper (j:js) =
j : elimHelper js
elimHelper [] = []
elimDuplicateEvals js = js
optimizeRuntimeCalls :: String -> String -> [JS] -> [JS]
optimizeRuntimeCalls fun tc js =
optTC tc : map optHelper js
where
optHelper :: JS -> JS
optHelper (JSApp (JSIdent "__IDRRT__tailcall") [
JSFunction [] (JSReturn (JSApp (JSIdent n) args))
])
| n == fun = JSApp (JSIdent tc) $ map optHelper args
optHelper js = transformJS optHelper js
optTC :: String -> JS
optTC tc@"__IDRRT__EVALTC" =
JSAlloc tc (Just $ JSFunction ["arg0"] (
JSSeq [ JSAlloc "ret" $ Just (
JSTernary (
(JSIdent "arg0" `jsInstanceOf` jsCon) `jsAnd`
(hasProp "__IDRLT__EVAL" "arg0")
) (JSApp
(JSIndex
(JSIdent "__IDRLT__EVAL")
(JSProj (JSIdent "arg0") "tag")
)
[JSIdent "arg0"]
) (JSIdent "arg0")
)
, JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
JSAssign (JSIdent "ret") (
JSApp (JSProj (JSIdent "ret") "k") []
)
)
, JSReturn $ JSIdent "ret"
]
))
optTC tc@"__IDRRT__APPLYTC" =
JSAlloc tc (Just $ JSFunction ["fn0", "arg0"] (
JSSeq [ JSAlloc "ret" $ Just (
JSTernary (
(JSIdent "fn0" `jsInstanceOf` jsCon) `jsAnd`
(hasProp "__IDRLT__APPLY" "fn0")
) (JSApp
(JSIndex
(JSIdent "__IDRLT__APPLY")
(JSProj (JSIdent "fn0") "tag")
)
[JSIdent "fn0", JSIdent "arg0", JSIdent "fn0"]
) JSNull
)
, JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
JSAssign (JSIdent "ret") (
JSApp (JSProj (JSIdent "ret") "k") []
)
)
, JSReturn $ JSIdent "ret"
]
))
hasProp :: String -> String -> JS
hasProp table var =
JSIndex (JSIdent table) (JSProj (JSIdent var) "tag")
unfoldLookupTable :: [JS] -> [JS]
unfoldLookupTable input =
let (evals, evalunfold) = unfoldLT "__IDRLT__EVAL" input
(applys, applyunfold) = unfoldLT "__IDRLT__APPLY" evalunfold
js = applyunfold in
adaptRuntime $ expandCons evals applys js
where
adaptRuntime :: [JS] -> [JS]
adaptRuntime =
adaptEvalTC . adaptApplyTC . adaptEval . adaptApply . adaptCon
adaptApply :: [JS] -> [JS]
adaptApply js = adaptApply' [] js
where
adaptApply' :: [JS] -> [JS] -> [JS]
adaptApply' front ((JSAlloc "__IDR__mAPPLY0" (Just _)):back) =
front ++ (new:back)
adaptApply' front (next:back) =
adaptApply' (front ++ [next]) back
adaptApply' front [] = front
new =
JSAlloc "__IDR__mAPPLY0" (Just $ JSFunction ["mfn0", "marg0"] (JSReturn $
JSTernary (
(JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
(JSProj (JSIdent "mfn0") "app")
) (JSApp
(JSProj (JSIdent "mfn0") "app")
[JSIdent "mfn0", JSIdent "marg0"]
) JSNull
)
)
adaptApplyTC :: [JS] -> [JS]
adaptApplyTC js = adaptApplyTC' [] js
where
adaptApplyTC' :: [JS] -> [JS] -> [JS]
adaptApplyTC' front ((JSAlloc "__IDRRT__APPLYTC" (Just _)):back) =
front ++ (new:back)
adaptApplyTC' front (next:back) =
adaptApplyTC' (front ++ [next]) back
adaptApplyTC' front [] = front
new =
JSAlloc "__IDRRT__APPLYTC" (Just $ JSFunction ["mfn0", "marg0"] (
JSSeq [ JSAlloc "ret" $ Just (
JSTernary (
(JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
(JSProj (JSIdent "mfn0") "app")
) (JSApp
(JSProj (JSIdent "mfn0") "app")
[JSIdent "mfn0", JSIdent "marg0"]
) JSNull
)
, JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
JSAssign (JSIdent "ret") (
JSApp (JSProj (JSIdent "ret") "k") []
)
)
, JSReturn $ JSIdent "ret"
]
))
adaptEval :: [JS] -> [JS]
adaptEval js = adaptEval' [] js
where
adaptEval' :: [JS] -> [JS] -> [JS]
adaptEval' front ((JSAlloc "__IDR__mEVAL0" (Just _)):back) =
front ++ (new:back)
adaptEval' front (next:back) =
adaptEval' (front ++ [next]) back
adaptEval' front [] = front
new =
JSAlloc "__IDR__mEVAL0" (Just $ JSFunction ["marg0"] (JSReturn $
JSTernary (
(JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
(JSProj (JSIdent "marg0") "eval")
) (JSApp
(JSProj (JSIdent "marg0") "eval")
[JSIdent "marg0"]
) (JSIdent "marg0")
)
)
adaptEvalTC :: [JS] -> [JS]
adaptEvalTC js = adaptEvalTC' [] js
where
adaptEvalTC' :: [JS] -> [JS] -> [JS]
adaptEvalTC' front ((JSAlloc "__IDRRT__EVALTC" (Just _)):back) =
front ++ (new:back)
adaptEvalTC' front (next:back) =
adaptEvalTC' (front ++ [next]) back
adaptEvalTC' front [] = front
new =
JSAlloc "__IDRRT__EVALTC" (Just $ JSFunction ["marg0"] (
JSSeq [ JSAlloc "ret" $ Just (
JSTernary (
(JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
(JSProj (JSIdent "marg0") "eval")
) (JSApp
(JSProj (JSIdent "marg0") "eval")
[JSIdent "marg0"]
) (JSIdent "marg0")
)
, JSWhile (JSIdent "ret" `jsInstanceOf` (JSIdent "__IDRRT__Cont")) (
JSAssign (JSIdent "ret") (
JSApp (JSProj (JSIdent "ret") "k") []
)
)
, JSReturn $ JSIdent "ret"
]
))
adaptCon js =
adaptCon' [] js
where
adaptCon' front ((JSAnnotation _ (JSAlloc "__IDRRT__Con" _)):back) =
front ++ (new:back)
adaptCon' front (next:back) =
adaptCon' (front ++ [next]) back
adaptCon' front [] = front
new =
JSAnnotation JSConstructor $
JSAlloc "__IDRRT__Con" (Just $
JSFunction newArgs (
JSSeq (map newVar newArgs)
)
)
where
newVar var = JSAssign (JSProj JSThis var) (JSIdent var)
newArgs = ["tag", "eval", "app", "vars"]
unfoldLT :: String -> [JS] -> ([Int], [JS])
unfoldLT lt js =
let (table, code) = extractLT lt js
expanded = expandLT lt table in
(map fst expanded, map snd expanded ++ code)
expandCons :: [Int] -> [Int] -> [JS] -> [JS]
expandCons evals applys js =
map expandCons' js
where
expandCons' :: JS -> JS
expandCons' (JSNew "__IDRRT__Con" [JSNum (JSInt tag), JSArray args])
| evalid <- getId "__IDRLT__EVAL" tag evals
, applyid <- getId "__IDRLT__APPLY" tag applys =
JSNew "__IDRRT__Con" [ JSNum (JSInt tag)
, maybe JSNull JSIdent evalid
, maybe JSNull JSIdent applyid
, JSArray (map expandCons' args)
]
expandCons' js = transformJS expandCons' js
getId :: String -> Int -> [Int] -> Maybe String
getId lt tag entries
| tag `elem` entries = Just $ ltIdentifier lt tag
| otherwise = Nothing
ltIdentifier :: String -> Int -> String
ltIdentifier "__IDRLT__EVAL" id = idrLTNamespace ++ "EVAL" ++ show id
ltIdentifier "__IDRLT__APPLY" id = idrLTNamespace ++ "APPLY" ++ show id
extractLT :: String -> [JS] -> (JS, [JS])
extractLT lt js =
extractLT' ([], js)
where
extractLT' :: ([JS], [JS]) -> (JS, [JS])
extractLT' (front, js@(JSAlloc fun _):back)
| fun == lt = (js, front ++ back)
extractLT' (front, js:back) = extractLT' (front ++ [js], back)
extractLT' (front, back) = (JSNoop, front ++ back)
expandLT :: String -> JS -> [(Int, JS)]
expandLT lt (
JSAlloc _ (Just (JSApp (JSFunction [] (JSSeq seq)) []))
) = catMaybes (map expandEntry seq)
where
expandEntry :: JS -> Maybe (Int, JS)
expandEntry (JSAssign (JSIndex _ (JSNum (JSInt id))) body) =
Just $ (id, JSAlloc (ltIdentifier lt id) (Just body))
expandEntry js = Nothing
expandLT lt JSNoop = []
removeInstanceChecks :: JS -> JS
removeInstanceChecks (JSCond conds) =
removeNoopConds $ JSCond $ eliminateDeadBranches $ map (
removeHelper *** removeInstanceChecks
) conds
where
removeHelper (
JSBinOp "&&" (JSBinOp "instanceof" _ (JSIdent "__IDRRT__Con")) check
) = removeHelper check
removeHelper js = js
eliminateDeadBranches ((JSTrue, cond):_) = [(JSNoop, cond)]
eliminateDeadBranches [(_, js)] = [(JSNoop, js)]
eliminateDeadBranches (x:xs) = x : eliminateDeadBranches xs
eliminateDeadBranches [] = []
removeNoopConds :: JS -> JS
removeNoopConds (JSCond [(JSNoop, js)]) = js
removeNoopConds js = js
removeInstanceChecks js = transformJS removeInstanceChecks js
reduceLoop :: [String] -> ([JS], [JS]) -> [JS]
reduceLoop reduced (cons, program) =
case partition findConstructors program of
([], js) -> cons ++ js
(candidates, rest) ->
let names = reduced ++ map funName candidates in
reduceLoop names (
cons ++ map reduce candidates, map (reduceCall names) rest
)
where findConstructors :: JS -> Bool
findConstructors js
| (JSAlloc fun (Just (JSFunction _ (JSSeq body)))) <- js =
reducable $ last body
| otherwise = False
where reducable :: JS -> Bool
reducable js
| JSReturn ret <- js = reducable ret
| JSNew _ args <- js = and $ map reducable args
| JSArray fields <- js = and $ map reducable fields
| JSNum _ <- js = True
| JSNull <- js = True
| JSIdent _ <- js = True
| otherwise = False
reduce :: JS -> JS
reduce (JSAlloc fun (Just (JSFunction _ (JSSeq body))))
| JSReturn js <- last body = (JSAlloc fun (Just js))
reduce js = js
reduceCall :: [String] -> JS -> JS
reduceCall funs (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
JSReturn (JSApp id@(JSIdent ret) _)
)])
| ret `elem` funs = id
reduceCall funs js@(JSApp id@(JSIdent fun) _)
| fun `elem` funs = id
reduceCall funs js = transformJS (reduceCall funs) js
extractLocalConstructors :: [JS] -> [JS]
extractLocalConstructors js =
concatMap extractLocalConstructors' js
where
globalCons :: [String]
globalCons = concatMap (getGlobalCons) js
extractLocalConstructors' :: JS -> [JS]
extractLocalConstructors' js@(JSAlloc fun (Just (JSFunction args body))) =
addCons cons [foldr (uncurry jsSubst) js (reverse cons)]
where
cons :: [(JS, JS)]
cons = zipWith genName (foldJS match (++) [] body) [1..]
where
genName :: JS -> Int -> (JS, JS)
genName js id =
(js, JSIdent $ idrCTRNamespace ++ fun ++ "_" ++ show id)
match :: JS -> [JS]
match js
| JSNew "__IDRRT__Con" args <- js
, all isConstant args = [js]
| otherwise = []
addCons :: [(JS, JS)] -> [JS] -> [JS]
addCons [] js = js
addCons (con@(_, name):cons) js
| sum (map (countOccur name) js) > 0 =
addCons cons ((allocCon con) : js)
| otherwise =
addCons cons js
countOccur :: JS -> JS -> Int
countOccur ident js = foldJS match (+) 0 js
where
match :: JS -> Int
match js
| js == ident = 1
| otherwise = 0
allocCon :: (JS, JS) -> JS
allocCon (js, JSIdent name) =
JSAlloc name (Just js)
isConstant :: JS -> Bool
isConstant js
| JSNew "__IDRRT__Con" args <- js
, all isConstant args =
True
| otherwise =
isJSConstantConstructor globalCons js
extractLocalConstructors' js = [js]
getGlobalCons :: JS -> [String]
getGlobalCons js = foldJS match (++) [] js
where
match :: JS -> [String]
match js
| (JSAlloc name (Just (JSNew "__IDRRT__Con" _))) <- js =
[name]
| otherwise =
[]
evalCons :: [JS] -> [JS]
evalCons js =
map (collapseCont . collapseTC . expandProj . evalCons') js
where
cons :: [(String, JS)]
cons = concatMap getGlobalCons js
evalCons' :: JS -> JS
evalCons' js = transformJS match js
where
match :: JS -> JS
match (JSApp (JSIdent "__IDRRT__EVALTC") [arg])
| JSIdent name <- arg
, Just (JSNew _ [_, JSNull, _, _]) <- lookupConstructor name cons =
arg
match (JSApp (JSIdent "__IDR__mEVAL0") [arg])
| JSIdent name <- arg
, Just (JSNew _ [_, JSNull, _, _]) <- lookupConstructor name cons =
arg
match js = transformJS match js
lookupConstructor :: String -> [(String, JS)] -> Maybe JS
lookupConstructor ctr cons
| Just (JSIdent name) <- lookup ctr cons = lookupConstructor name cons
| Just con@(JSNew _ _) <- lookup ctr cons = Just con
| otherwise = Nothing
expandProj :: JS -> JS
expandProj js = transformJS match js
where
match :: JS -> JS
match (
JSIndex (
JSProj (JSIdent name) "vars"
) (
JSNum (JSInt idx)
)
)
| Just (JSNew _ [_, _, _, JSArray args]) <- lookup name cons =
args !! idx
match js = transformJS match js
collapseTC :: JS -> JS
collapseTC js = transformJS match js
where
match :: JS -> JS
match (JSApp (JSIdent "__IDRRT__tailcall") [JSFunction [] (
JSReturn (JSIdent name)
)])
| Just _ <- lookup name cons = (JSIdent name)
match js = transformJS match js
collapseCont :: JS -> JS
collapseCont js = transformJS match js
where
match :: JS -> JS
match (JSNew "__IDRRT__Cont" [JSFunction [] (
JSReturn ret@(JSNew "__IDRRT__Cont" [JSFunction [] _])
)]) = collapseCont ret
match (JSNew "__IDRRT__Cont" [JSFunction [] (
JSReturn (JSIdent name)
)]) = JSIdent name
match (JSNew "__IDRRT__Cont" [JSFunction [] (
JSReturn ret@(JSNew "__IDRRT__Con" [_, _, _, JSArray args])
)])
| all collapsable args = ret
where
collapsable :: JS -> Bool
collapsable (JSIdent _) = True
collapsable js = isJSConstantConstructor (map fst cons) js
match js = transformJS match js
elimConds :: [JS] -> [JS]
elimConds js =
let (conds, rest) = partition isCond js in
foldl' eraseCond rest conds
where
isCond :: JS -> Bool
isCond (JSAlloc
fun (Just (JSFunction args (JSCond
[ (JSBinOp "==" (JSNum (JSInt tag)) (JSProj (JSIdent _) "tag"), JSReturn t)
, (JSNoop, JSReturn f)
])))
)
| isJSConstant t && isJSConstant f =
True
| JSIdent _ <- t
, JSIdent _ <- f =
True
isCond (JSAlloc
fun (Just (JSFunction args (JSCond
[ (JSBinOp "==" (JSIdent _) c, JSReturn t)
, (JSNoop, JSReturn f)
])))
)
| isJSConstant t && isJSConstant f && isJSConstant c =
True
| JSIdent _ <- t
, JSIdent _ <- f
, isJSConstant c =
True
isCond _ = False
eraseCond :: [JS] -> JS -> [JS]
eraseCond js (JSAlloc
fun (Just (JSFunction args (JSCond
[ (c, JSReturn t)
, (_, JSReturn f)
])
)
)) = map (inlineFunction fun args (JSTernary c t f)) js
removeUselessCons :: [JS] -> [JS]
removeUselessCons js =
let (cons, rest) = partition isUseless js in
foldl' eraseCon rest cons
where
isUseless :: JS -> Bool
isUseless (JSAlloc fun (Just JSNull)) = True
isUseless (JSAlloc fun (Just (JSIdent _))) = True
isUseless _ = False
eraseCon :: [JS] -> JS -> [JS]
eraseCon js (JSAlloc fun (Just val)) = map (jsSubst (JSIdent fun) val) js
getGlobalCons :: JS -> [(String, JS)]
getGlobalCons js = foldJS match (++) [] js
where
match :: JS -> [(String, JS)]
match js
| (JSAlloc name (Just con@(JSNew "__IDRRT__Con" _))) <- js =
[(name, con)]
| (JSAlloc name (Just con@(JSIdent _))) <- js =
[(name, con)]
| otherwise =
[]
getIncludes :: [FilePath] -> IO [String]
getIncludes = mapM readFile
codegenJavaScript :: CodeGenerator
codegenJavaScript ci = codegenJS_all JavaScript (simpleDecls ci)
(includes ci) (outputFile ci) (outputType ci)
codegenNode :: CodeGenerator
codegenNode ci = codegenJS_all Node (simpleDecls ci)
(includes ci) (outputFile ci) (outputType ci)
codegenJS_all
:: JSTarget
-> [(Name, SDecl)]
-> [FilePath]
-> FilePath
-> OutputType
-> IO ()
codegenJS_all target definitions includes filename outputType = do
let (header, rt) = case target of
Node ->
("#!/usr/bin/env node\n", "-node")
JavaScript ->
("", "-browser")
included <- getIncludes includes
path <- (++) <$> getDataDir <*> (pure "/jsrts/")
idrRuntime <- readFile $ path ++ "Runtime-common.js"
tgtRuntime <- readFile $ concat [path, "Runtime", rt, ".js"]
jsbn <- readFile $ path ++ "jsbn/jsbn.js"
writeFile filename $ header ++ (
intercalate "\n" $ included ++ runtime jsbn idrRuntime tgtRuntime ++ functions
)
setPermissions filename (emptyPermissions { readable = True
, executable = target == Node
, writable = True
})
where
def :: [(String, SDecl)]
def = map (first translateNamespace) definitions
checkForBigInt :: [JS] -> Bool
checkForBigInt js = occur
where
occur :: Bool
occur = or $ map (foldJS match (||) False) js
match :: JS -> Bool
match (JSIdent "__IDRRT__bigInt") = True
match (JSWord (JSWord64 _)) = True
match (JSNum (JSInteger _)) = True
match js = False
runtime :: String -> String -> String -> [String]
runtime jsbn idrRuntime tgtRuntime =
if checkForBigInt optimized
then [jsbn, idrRuntime, tgtRuntime]
else [idrRuntime, tgtRuntime]
optimized :: [JS]
optimized = translate >>> optimize $ def
where
translate p =
prelude ++ concatMap translateDeclaration p ++ [mainLoop, invokeLoop]
optimize p =
foldl' (flip ($)) p opt
opt =
[ removeEval
, map inlineJS
, removeIDs
, reduceJS
, map reduceConstants
, initConstructors
, map removeAllocations
, elimDeadLoop
, map elimDuplicateEvals
, optimizeRuntimeCalls "__IDR__mEVAL0" "__IDRRT__EVALTC"
, optimizeRuntimeCalls "__IDR__mAPPLY0" "__IDRRT__APPLYTC"
, map removeInstanceChecks
, inlineFunctions
, map reduceContinuations
, extractLocalConstructors
, unfoldLookupTable
, evalCons
, elimConds
, removeUselessCons
]
functions :: [String]
functions = map compileJS optimized
prelude :: [JS]
prelude =
[ JSAnnotation JSConstructor $
JSAlloc (idrRTNamespace ++ "Cont") (Just $ JSFunction ["k"] (
JSAssign (JSProj JSThis "k") (JSIdent "k")
))
, JSAnnotation JSConstructor $
JSAlloc (idrRTNamespace ++ "Con") (Just $ JSFunction ["tag", "vars"] (
JSSeq [ JSAssign (JSProj JSThis "tag") (JSIdent "tag")
, JSAssign (JSProj JSThis "vars") (JSIdent "vars")
]
))
]
mainLoop :: JS
mainLoop =
JSAlloc "main" $ Just $ JSFunction [] (
case target of
Node -> mainFun
JavaScript -> JSCond [(isReady, mainFun), (JSTrue, jsMeth (JSIdent "window") "addEventListener" [
JSString "DOMContentLoaded", JSFunction [] (
mainFun
), JSFalse
])]
)
where
mainFun :: JS
mainFun = jsTailcall $ jsCall runMain []
isReady :: JS
isReady = readyState `jsEq` JSString "complete" `jsOr` readyState `jsEq` JSString "loaded"
readyState :: JS
readyState = JSProj (JSIdent "document") "readyState"
runMain :: String
runMain = idrNamespace ++ translateName (sMN 0 "runMain")
invokeLoop :: JS
invokeLoop = jsCall "main" []
translateIdentifier :: String -> String
translateIdentifier =
replaceReserved . concatMap replaceBadChars
where replaceBadChars :: Char -> String
replaceBadChars c
| ' ' <- c = "_"
| '_' <- c = "__"
| isDigit c = '_' : show (ord c)
| not (isLetter c && isAscii c) = '_' : show (ord c)
| otherwise = [c]
replaceReserved s
| s `elem` reserved = '_' : s
| otherwise = s
reserved = [ "break"
, "case"
, "catch"
, "continue"
, "debugger"
, "default"
, "delete"
, "do"
, "else"
, "finally"
, "for"
, "function"
, "if"
, "in"
, "instanceof"
, "new"
, "return"
, "switch"
, "this"
, "throw"
, "try"
, "typeof"
, "var"
, "void"
, "while"
, "with"
, "class"
, "enum"
, "export"
, "extends"
, "import"
, "super"
, "implements"
, "interface"
, "let"
, "package"
, "private"
, "protected"
, "public"
, "static"
, "yield"
]
translateNamespace :: Name -> String
translateNamespace (UN _) = idrNamespace
translateNamespace (NS _ ns) = idrNamespace ++ concatMap (translateIdentifier . str) ns
translateNamespace (MN _ _) = idrNamespace
translateNamespace (SN name) = idrNamespace ++ translateSpecialName name
translateNamespace NErased = idrNamespace
translateName :: Name -> String
translateName (UN name) = 'u' : translateIdentifier (str name)
translateName (NS name _) = 'n' : translateName name
translateName (MN i name) = 'm' : translateIdentifier (str name) ++ show i
translateName (SN name) = 's' : translateSpecialName name
translateName NErased = "e"
translateSpecialName :: SpecialName -> String
translateSpecialName name
| WhereN i m n <- name =
'w' : translateName m ++ translateName n ++ show i
| InstanceN n s <- name =
'i' : translateName n ++ concatMap (translateIdentifier . str) s
| ParentN n s <- name =
'p' : translateName n ++ translateIdentifier (str s)
| MethodN n <- name =
'm' : translateName n
| CaseN n <- name =
'c' : translateName n
translateConstant :: Const -> JS
translateConstant (I i) = JSNum (JSInt i)
translateConstant (Fl f) = JSNum (JSFloat f)
translateConstant (Ch c) = JSString $ translateChar c
translateConstant (Str s) = JSString $ concatMap translateChar s
translateConstant (AType (ATInt ITNative)) = JSType JSIntTy
translateConstant StrType = JSType JSStringTy
translateConstant (AType (ATInt ITBig)) = JSType JSIntegerTy
translateConstant (AType ATFloat) = JSType JSFloatTy
translateConstant (AType (ATInt ITChar)) = JSType JSCharTy
translateConstant PtrType = JSType JSPtrTy
translateConstant Forgot = JSType JSForgotTy
translateConstant (BI i) = jsBigInt $ JSString (show i)
translateConstant (B8 b) = JSWord (JSWord8 b)
translateConstant (B16 b) = JSWord (JSWord16 b)
translateConstant (B32 b) = JSWord (JSWord32 b)
translateConstant (B64 b) = JSWord (JSWord64 b)
translateConstant c =
jsError $ "Unimplemented Constant: " ++ show c
translateChar :: Char -> String
translateChar ch
| '\a' <- ch = "\\u0007"
| '\b' <- ch = "\\b"
| '\f' <- ch = "\\f"
| '\n' <- ch = "\\n"
| '\r' <- ch = "\\r"
| '\t' <- ch = "\\t"
| '\v' <- ch = "\\v"
| '\SO' <- ch = "\\u000E"
| '\DEL' <- ch = "\\u007F"
| '\\' <- ch = "\\\\"
| '\"' <- ch = "\\\""
| '\'' <- ch = "\\\'"
| ch `elem` asciiTab = "\\u00" ++ fill (showIntAtBase 16 intToDigit (ord ch) "")
| otherwise = [ch]
where
fill :: String -> String
fill s = if length s == 1
then '0' : s
else s
asciiTab =
['\NUL', '\SOH', '\STX', '\ETX', '\EOT', '\ENQ', '\ACK', '\BEL',
'\BS', '\HT', '\LF', '\VT', '\FF', '\CR', '\SO', '\SI',
'\DLE', '\DC1', '\DC2', '\DC3', '\DC4', '\NAK', '\SYN', '\ETB',
'\CAN', '\EM', '\SUB', '\ESC', '\FS', '\GS', '\RS', '\US']
translateDeclaration :: (String, SDecl) -> [JS]
translateDeclaration (path, SFun name params stackSize body)
| (MN _ ap) <- name
, (SChkCase var cases) <- body
, ap == txt "APPLY" =
[ lookupTable "APPLY" [] var cases
, jsDecl $ JSFunction ["mfn0", "marg0"] (JSReturn $
JSTernary (
(JSIdent "mfn0" `jsInstanceOf` jsCon) `jsAnd`
(hasProp (idrLTNamespace ++ "APPLY") "mfn0")
) (JSApp
(JSIndex
(JSIdent (idrLTNamespace ++ "APPLY"))
(JSProj (JSIdent "mfn0") "tag")
)
[JSIdent "mfn0", JSIdent "marg0"]
) JSNull
)
]
| (MN _ ev) <- name
, (SChkCase var cases) <- body
, ev == txt "EVAL" =
[ lookupTable "EVAL" [] var cases
, jsDecl $ JSFunction ["marg0"] (JSReturn $
JSTernary (
(JSIdent "marg0" `jsInstanceOf` jsCon) `jsAnd`
(hasProp (idrLTNamespace ++ "EVAL") "marg0")
) (JSApp
(JSIndex
(JSIdent (idrLTNamespace ++ "EVAL"))
(JSProj (JSIdent "marg0") "tag")
)
[JSIdent "marg0"]
) (JSIdent "marg0")
)
]
| otherwise =
let fun = translateExpression body in
[jsDecl $ jsFun fun]
where
hasProp :: String -> String -> JS
hasProp table var =
JSIndex (JSIdent table) (JSProj (JSIdent var) "tag")
caseFun :: [(LVar, String)] -> LVar -> SAlt -> JS
caseFun aux var cse =
let (JSReturn c) = translateCase (Just (translateVariableName var)) cse in
jsFunAux aux c
getTag :: SAlt -> Maybe Int
getTag (SConCase _ tag _ _ _) = Just tag
getTag _ = Nothing
lookupTable :: String -> [(LVar, String)] -> LVar -> [SAlt] -> JS
lookupTable table aux var cases =
JSAlloc (idrLTNamespace ++ table) $ Just (
JSApp (JSFunction [] (
JSSeq $ [
JSAlloc "t" $ Just (JSArray [])
] ++ assignEntries (catMaybes $ map (lookupEntry aux var) cases) ++ [
JSReturn (JSIdent "t")
]
)) []
)
where
assignEntries :: [(Int, JS)] -> [JS]
assignEntries entries =
map (\(tag, fun) ->
JSAssign (JSIndex (JSIdent "t") (JSNum $ JSInt tag)) fun
) entries
lookupEntry :: [(LVar, String)] -> LVar -> SAlt -> Maybe (Int, JS)
lookupEntry aux var alt = do
tag <- getTag alt
return (tag, caseFun aux var alt)
jsDecl :: JS -> JS
jsDecl = JSAlloc (path ++ translateName name) . Just
jsFun body = jsFunAux [] body
jsFunAux :: [(LVar, String)] -> JS -> JS
jsFunAux aux body =
JSFunction (p ++ map snd aux) (
JSSeq $
zipWith assignVar [0..] p ++
map assignAux aux ++
[JSReturn body]
)
where
assignVar :: Int -> String -> JS
assignVar n s = JSAlloc (jsVar n) (Just $ JSIdent s)
assignAux :: (LVar, String) -> JS
assignAux (Loc var, val) =
JSAlloc (jsVar var) (Just $ JSIdent val)
p :: [String]
p = map translateName params
translateVariableName :: LVar -> String
translateVariableName (Loc i) =
jsVar i
translateExpression :: SExp -> JS
translateExpression (SLet name value body) =
jsLet (translateVariableName name) (
translateExpression value
) (translateExpression body)
translateExpression (SConst cst) =
translateConstant cst
translateExpression (SV var) =
JSVar var
translateExpression (SApp tc name vars)
| False <- tc =
jsTailcall $ translateFunctionCall name vars
| True <- tc =
JSNew (idrRTNamespace ++ "Cont") [JSFunction [] (
JSReturn $ translateFunctionCall name vars
)]
where
translateFunctionCall name vars =
jsCall (translateNamespace name ++ translateName name) (map JSVar vars)
translateExpression (SOp op vars)
| LNoOp <- op = JSVar (last vars)
| (LZExt (ITFixed IT8) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
| (LZExt (ITFixed IT16) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
| (LZExt (ITFixed IT32) ITNative) <- op = jsUnPackBits $ JSVar (last vars)
| (LZExt _ ITBig) <- op = jsBigInt $ jsCall "String" [JSVar (last vars)]
| (LPlus (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "add" [rhs]
| (LMinus (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "subtract" [rhs]
| (LTimes (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "multiply" [rhs]
| (LSDiv (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
| (LSRem (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "mod" [rhs]
| (LEq (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "equals" [rhs]
| (LSLt (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "lesser" [rhs]
| (LSLe (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "lesserOrEquals" [rhs]
| (LSGt (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "greater" [rhs]
| (LSGe (ATInt ITBig)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "greaterOrEquals" [rhs]
| (LPlus ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "+" lhs rhs
| (LMinus ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "-" lhs rhs
| (LTimes ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "*" lhs rhs
| (LSDiv ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "/" lhs rhs
| (LEq ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
| (LSLt ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
| (LSLe ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "<=" lhs rhs
| (LSGt ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp ">" lhs rhs
| (LSGe ATFloat) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp ">=" lhs rhs
| (LPlus (ATInt ITChar)) <- op
, (lhs:rhs:_) <- vars =
jsCall "__IDRRT__fromCharCode" [
JSBinOp "+" (
jsCall "__IDRRT__charCode" [JSVar lhs]
) (
jsCall "__IDRRT__charCode" [JSVar rhs]
)
]
| (LTrunc (ITFixed IT16) (ITFixed IT8)) <- op
, (arg:_) <- vars =
jsPackUBits8 (
JSBinOp "&" (jsUnPackBits $ JSVar arg) (JSNum (JSInt 0xFF))
)
| (LTrunc (ITFixed IT32) (ITFixed IT16)) <- op
, (arg:_) <- vars =
jsPackUBits16 (
JSBinOp "&" (jsUnPackBits $ JSVar arg) (JSNum (JSInt 0xFFFF))
)
| (LTrunc (ITFixed IT64) (ITFixed IT32)) <- op
, (arg:_) <- vars =
jsPackUBits32 (
jsMeth (jsMeth (JSVar arg) "and" [
jsBigInt (JSString $ show 0xFFFFFFFF)
]) "intValue" []
)
| (LTrunc ITBig (ITFixed IT64)) <- op
, (arg:_) <- vars =
jsMeth (JSVar arg) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LLSHR (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
)
| (LLSHR (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
)
| (LLSHR (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp ">>" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
)
| (LLSHR (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars =
jsMeth (JSVar lhs) "shiftRight" [JSVar rhs]
| (LSHL (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
)
| (LSHL (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
)
| (LSHL (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "<<" (jsUnPackBits $ JSVar lhs) (jsUnPackBits $ JSVar rhs)
)
| (LSHL (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars =
jsMeth (jsMeth (JSVar lhs) "shiftLeft" [JSVar rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LAnd (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LAnd (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LAnd (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "&" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LAnd (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars =
jsMeth (JSVar lhs) "and" [JSVar rhs]
| (LOr (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LOr (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LOr (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "|" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LOr (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars =
jsMeth (JSVar lhs) "or" [JSVar rhs]
| (LXOr (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LXOr (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LXOr (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "^" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LXOr (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars =
jsMeth (JSVar lhs) "xor" [JSVar rhs]
| (LPlus (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LPlus (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LPlus (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "+" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LPlus (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- vars =
jsMeth (jsMeth (JSVar lhs) "add" [JSVar rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LMinus (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LMinus (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LMinus (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "-" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LMinus (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- vars =
jsMeth (jsMeth (JSVar lhs) "subtract" [JSVar rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LTimes (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LTimes (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LTimes (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "*" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LTimes (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- vars =
jsMeth (jsMeth (JSVar lhs) "multiply" [JSVar rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LEq (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LEq (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LEq (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "==" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LEq (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- vars =
jsMeth (jsMeth (JSVar lhs) "equals" [JSVar rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LLt (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LLt (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LLt (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "<" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LLt (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "lesser" [rhs]
| (LLe (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LLe (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LLe (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "<=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LLe (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "lesserOrEquals" [rhs]
| (LGt (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LGt (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LGt (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp ">" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LGt (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "greater" [rhs]
| (LGe (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LGe (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LGe (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp ">=" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LGe (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "greaterOrEquals" [rhs]
| (LUDiv (ITFixed IT8)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits8 (
JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LUDiv (ITFixed IT16)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits16 (
JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LUDiv (ITFixed IT32)) <- op
, (lhs:rhs:_) <- vars =
jsPackUBits32 (
JSBinOp "/" (jsUnPackBits (JSVar lhs)) (jsUnPackBits (JSVar rhs))
)
| (LUDiv (ITFixed IT64)) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
| (LSDiv (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- vars =
jsPackSBits8 (
JSBinOp "/" (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar lhs)
) (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar rhs)
)
)
| (LSDiv (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- vars =
jsPackSBits16 (
JSBinOp "/" (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar lhs)
) (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar rhs)
)
)
| (LSDiv (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- vars =
jsPackSBits32 (
JSBinOp "/" (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar lhs)
) (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar rhs)
)
)
| (LSDiv (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "divide" [rhs]
| (LSRem (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- vars =
jsPackSBits8 (
JSBinOp "%" (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar lhs)
) (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (JSVar rhs)
)
)
| (LSRem (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- vars =
jsPackSBits16 (
JSBinOp "%" (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar lhs)
) (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (JSVar rhs)
)
)
| (LSRem (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- vars =
jsPackSBits32 (
JSBinOp "%" (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar lhs)
) (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (JSVar rhs)
)
)
| (LSRem (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "mod" [rhs]
| (LCompl (ITFixed IT8)) <- op
, (arg:_) <- vars =
jsPackSBits8 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
| (LCompl (ITFixed IT16)) <- op
, (arg:_) <- vars =
jsPackSBits16 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
| (LCompl (ITFixed IT32)) <- op
, (arg:_) <- vars =
jsPackSBits32 $ JSPreOp "~" $ jsUnPackBits (JSVar arg)
| (LCompl (ITFixed IT64)) <- op
, (arg:_) <- vars =
invokeMeth arg "not" []
| (LPlus _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "+" lhs rhs
| (LMinus _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "-" lhs rhs
| (LTimes _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "*" lhs rhs
| (LSDiv _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "/" lhs rhs
| (LSRem _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "%" lhs rhs
| (LEq _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
| (LSLt _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
| (LSLe _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "<=" lhs rhs
| (LSGt _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp ">" lhs rhs
| (LSGe _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp ">=" lhs rhs
| (LAnd _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "&" lhs rhs
| (LOr _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "|" lhs rhs
| (LXOr _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "^" lhs rhs
| (LSHL _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "<<" rhs lhs
| (LASHR _) <- op
, (lhs:rhs:_) <- vars = translateBinaryOp ">>" rhs lhs
| (LCompl _) <- op
, (arg:_) <- vars = JSPreOp "~" (JSVar arg)
| LStrConcat <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "concat" [rhs]
| LStrEq <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "==" lhs rhs
| LStrLt <- op
, (lhs:rhs:_) <- vars = translateBinaryOp "<" lhs rhs
| LStrLen <- op
, (arg:_) <- vars = JSProj (JSVar arg) "length"
| (LStrInt ITNative) <- op
, (arg:_) <- vars = jsCall "parseInt" [JSVar arg]
| (LIntStr ITNative) <- op
, (arg:_) <- vars = jsCall "String" [JSVar arg]
| (LSExt ITNative ITBig) <- op
, (arg:_) <- vars = jsBigInt $ jsCall "String" [JSVar arg]
| (LTrunc ITBig ITNative) <- op
, (arg:_) <- vars = jsMeth (JSVar arg) "intValue" []
| (LIntStr ITBig) <- op
, (arg:_) <- vars = jsMeth (JSVar arg) "toString" []
| (LStrInt ITBig) <- op
, (arg:_) <- vars = jsBigInt $ JSVar arg
| LFloatStr <- op
, (arg:_) <- vars = jsCall "String" [JSVar arg]
| LStrFloat <- op
, (arg:_) <- vars = jsCall "parseFloat" [JSVar arg]
| (LIntFloat ITNative) <- op
, (arg:_) <- vars = JSVar arg
| (LFloatInt ITNative) <- op
, (arg:_) <- vars = JSVar arg
| (LChInt ITNative) <- op
, (arg:_) <- vars = jsCall "__IDRRT__charCode" [JSVar arg]
| (LIntCh ITNative) <- op
, (arg:_) <- vars = jsCall "__IDRRT__fromCharCode" [JSVar arg]
| LFExp <- op
, (arg:_) <- vars = jsCall "Math.exp" [JSVar arg]
| LFLog <- op
, (arg:_) <- vars = jsCall "Math.log" [JSVar arg]
| LFSin <- op
, (arg:_) <- vars = jsCall "Math.sin" [JSVar arg]
| LFCos <- op
, (arg:_) <- vars = jsCall "Math.cos" [JSVar arg]
| LFTan <- op
, (arg:_) <- vars = jsCall "Math.tan" [JSVar arg]
| LFASin <- op
, (arg:_) <- vars = jsCall "Math.asin" [JSVar arg]
| LFACos <- op
, (arg:_) <- vars = jsCall "Math.acos" [JSVar arg]
| LFATan <- op
, (arg:_) <- vars = jsCall "Math.atan" [JSVar arg]
| LFSqrt <- op
, (arg:_) <- vars = jsCall "Math.sqrt" [JSVar arg]
| LFFloor <- op
, (arg:_) <- vars = jsCall "Math.floor" [JSVar arg]
| LFCeil <- op
, (arg:_) <- vars = jsCall "Math.ceil" [JSVar arg]
| LStrCons <- op
, (lhs:rhs:_) <- vars = invokeMeth lhs "concat" [rhs]
| LStrHead <- op
, (arg:_) <- vars = JSIndex (JSVar arg) (JSNum (JSInt 0))
| LStrRev <- op
, (arg:_) <- vars = JSProj (JSVar arg) "split('').reverse().join('')"
| LStrIndex <- op
, (lhs:rhs:_) <- vars = JSIndex (JSVar lhs) (JSVar rhs)
| LStrTail <- op
, (arg:_) <- vars = let v = translateVariableName arg in
JSApp (JSProj (JSIdent v) "substr") [
JSNum (JSInt 1),
JSBinOp "-" (JSProj (JSIdent v) "length") (JSNum (JSInt 1))
]
| LNullPtr <- op
, (_) <- vars = JSNull
where
translateBinaryOp :: String -> LVar -> LVar -> JS
translateBinaryOp f lhs rhs = JSParens $ JSBinOp f (JSVar lhs) (JSVar rhs)
invokeMeth :: LVar -> String -> [LVar] -> JS
invokeMeth obj meth args = jsMeth (JSVar obj) meth (map JSVar args)
translateExpression (SError msg) =
jsError msg
translateExpression (SForeign _ _ "putStr" [(FString, var)]) =
jsCall (idrRTNamespace ++ "print") [JSVar var]
translateExpression (SForeign _ _ "isNull" [(FPtr, var)]) =
JSBinOp "==" (JSVar var) JSNull
translateExpression (SForeign _ _ "idris_eqPtr" [(FPtr, lhs),(FPtr, rhs)]) =
JSBinOp "==" (JSVar lhs) (JSVar rhs)
translateExpression (SForeign _ _ "idris_time" []) =
JSRaw "(new Date()).getTime()"
translateExpression (SForeign _ _ fun args) =
JSFFI fun (map generateWrapper args)
where
generateWrapper (ffunc, name)
| FFunction <- ffunc =
JSApp (
JSIdent $ idrRTNamespace ++ "ffiWrap"
) [JSIdent $ translateVariableName name]
| FFunctionIO <- ffunc =
JSApp (
JSIdent $ idrRTNamespace ++ "ffiWrap"
) [JSIdent $ translateVariableName name]
generateWrapper (_, name) =
JSIdent $ translateVariableName name
translateExpression patterncase
| (SChkCase var cases) <- patterncase = caseHelper var cases "chk"
| (SCase var cases) <- patterncase = caseHelper var cases "cse"
where
caseHelper var cases param =
JSApp (JSFunction [param] (
JSCond $ map (expandCase param . translateCaseCond param) cases
)) [JSVar var]
expandCase :: String -> (Cond, JS) -> (JS, JS)
expandCase _ (RawCond cond, branch) = (cond, branch)
expandCase _ (CaseCond DefaultCase, branch) = (JSTrue , branch)
expandCase var (CaseCond caseTy, branch)
| ConCase tag <- caseTy =
let checkCon = JSIdent var `jsInstanceOf` jsCon
checkTag = (JSNum $ JSInt tag) `jsEq` jsTag (JSIdent var) in
(checkCon `jsAnd` checkTag, branch)
| TypeCase ty <- caseTy =
let checkTy = JSIdent var `jsInstanceOf` jsType
checkTag = jsTypeTag (JSIdent var) `jsEq` JSType ty in
(checkTy `jsAnd` checkTag, branch)
translateExpression (SCon i name vars) =
JSNew (idrRTNamespace ++ "Con") [ JSNum $ JSInt i
, JSArray $ map JSVar vars
]
translateExpression (SUpdate var@(Loc i) e) =
JSAssign (JSVar var) (translateExpression e)
translateExpression (SProj var i) =
JSIndex (JSProj (JSVar var) "vars") (JSNum $ JSInt i)
translateExpression SNothing = JSNull
translateExpression e =
jsError $ "Not yet implemented: " ++ filter (/= '\'') (show e)
data CaseType = ConCase Int
| TypeCase JSType
| DefaultCase
deriving Eq
data Cond = CaseCond CaseType
| RawCond JS
translateCaseCond :: String -> SAlt -> (Cond, JS)
translateCaseCond _ cse@(SDefaultCase _) =
(CaseCond DefaultCase, translateCase Nothing cse)
translateCaseCond var cse@(SConstCase ty _)
| StrType <- ty = matchHelper JSStringTy
| PtrType <- ty = matchHelper JSPtrTy
| Forgot <- ty = matchHelper JSForgotTy
| (AType ATFloat) <- ty = matchHelper JSFloatTy
| (AType (ATInt ITBig)) <- ty = matchHelper JSIntegerTy
| (AType (ATInt ITNative)) <- ty = matchHelper JSIntTy
| (AType (ATInt ITChar)) <- ty = matchHelper JSCharTy
where
matchHelper :: JSType -> (Cond, JS)
matchHelper ty = (CaseCond $ TypeCase ty, translateCase Nothing cse)
translateCaseCond var cse@(SConstCase cst@(BI _) _) =
let cond = jsMeth (JSIdent var) "equals" [translateConstant cst] in
(RawCond cond, translateCase Nothing cse)
translateCaseCond var cse@(SConstCase cst _) =
let cond = JSIdent var `jsEq` translateConstant cst in
(RawCond cond, translateCase Nothing cse)
translateCaseCond var cse@(SConCase _ tag _ _ _) =
(CaseCond $ ConCase tag, translateCase (Just var) cse)
translateCase :: Maybe String -> SAlt -> JS
translateCase _ (SDefaultCase e) = JSReturn $ translateExpression e
translateCase _ (SConstCase _ e) = JSReturn $ translateExpression e
translateCase (Just var) (SConCase a _ _ vars e) =
let params = map jsVar [a .. (a + length vars)] in
JSReturn $ jsMeth (JSFunction params (JSReturn $ translateExpression e)) "apply" [
JSThis, JSProj (JSIdent var) "vars"
]
|
DanielWaterworth/Idris-dev
|
src/IRTS/CodegenJavaScript.hs
|
bsd-3-clause
| 81,010 | 0 | 30 | 28,092 | 30,829 | 15,476 | 15,353 | 1,902 | 17 |
{-# LANGUAGE TemplateHaskell #-}
module Player where
import Common
import Prelude()
type Cooldown = Time
data Player = Player {
_position :: Position
, _velocity :: Velocity
, _direction :: Direction
, _cooldown :: Cooldown
} deriving Show
friction = 100 *~ newton
engineForce = 100 *~ newton
enginePower = 1000 *~ watt
shipMass = 1 *~ kilo gram
step :: Time -> InputState -> Player -> Player
step dt input (Player pos speed dir cooldown) =
Player
(pos `addPV` mulSV dt speed)
(speed `addV` mulSV dt accel)
(dir + dt * angleSpeed)
(cooldown - dt)
where
accel :: Vector DAcceleration
accel | isDown 's' input = negate friction `mulSV` normZV speed `divVS` shipMass
| isDown 'w' input = limitPower enginePower (mulSV engineForce (directionV dir)) speed `divVS` shipMass
| otherwise = (0 *~ (meter / second / second),0 *~ (meter / second / second))
angleSpeed | isDown 'd' input = (-5) *~ (radian / second)
| isDown 'a' input = 5 *~ (radian / second)
| otherwise = 0 *~ (radian / second)
$(mkLabels [''Player])
|
Rotsor/wheeled-vehicle
|
Player.hs
|
bsd-3-clause
| 1,093 | 0 | 13 | 260 | 413 | 220 | 193 | 30 | 1 |
module Parse.TemplateParserTest(tests) where
import Test.HUnit
import Test.Framework
import Test.Framework.Providers.HUnit
import Except.TypeDef
import Parse.TemplateParser
import Tree.TemplateExpression
testIncorrect1 = TestCase (assertEqual "Incorrect text" (Left (ParseException "")) (parseText "incorrect {{input"))
testIncorrect2 = TestCase (assertEqual "Incorrect text" (Left (ParseException "")) (parseText "incorrect}} input"))
testCorrect1 = TestCase (assertEqual "Correct text" (Right [Literal "foo ", Template "bar"]) (parseText "foo {{bar}}"))
testCorrect2 = TestCase (assertEqual "Correct text" (Right [Literal "literal"]) (parseText "literal"))
testCorrect3 = TestCase (assertEqual "Correct text" (Right [Template "template"]) (parseText "{{template}}"))
tests = hUnitTestToTests $ TestList [
TestLabel "testIncorrect1" testIncorrect1,
TestLabel "testIncorrect2" testIncorrect2,
TestLabel "testCorrect1" testCorrect1,
TestLabel "testCorrect2" testCorrect2,
TestLabel "testCorrect3" testCorrect3
]
|
sergioifg94/Hendoman
|
test/Parse/TemplateParserTest.hs
|
bsd-3-clause
| 1,032 | 0 | 11 | 119 | 281 | 146 | 135 | 18 | 1 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RecordWildCards #-}
module Cryptol.ModuleSystem.Renamer (
NamingEnv(), shadowing
, BindsNames(..)
, checkNamingEnv
, Rename(..), runRenamer
, RenamerError(..)
, RenamerWarning(..)
) where
import Cryptol.ModuleSystem.NamingEnv
import Cryptol.Prims.Syntax
import Cryptol.Parser.AST
import Cryptol.Parser.Names (tnamesP)
import Cryptol.Parser.Position
import Cryptol.Utils.Panic (panic)
import Cryptol.Utils.PP
import MonadLib
import qualified Data.Map as Map
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative(Applicative(..),(<$>))
import Data.Foldable (foldMap)
import Data.Monoid (Monoid(..))
import Data.Traversable (traverse)
#endif
-- Errors ----------------------------------------------------------------------
data RenamerError
= MultipleSyms (Located QName) [NameOrigin]
-- ^ Multiple imported symbols contain this name
| UnboundExpr (Located QName)
-- ^ Expression name is not bound to any definition
| UnboundType (Located QName)
-- ^ Type name is not bound to any definition
| OverlappingSyms [NameOrigin]
-- ^ An environment has produced multiple overlapping symbols
| ExpectedValue (Located QName)
-- ^ When a value is expected from the naming environment, but one or more
-- types exist instead.
| ExpectedType (Located QName)
-- ^ When a type is missing from the naming environment, but one or more
-- values exist with the same name.
| FixityError (Located QName) (Located QName)
-- ^ When the fixity of two operators conflict
| InvalidConstraint Type
-- ^ When it's not possible to produce a Prop from a Type.
deriving (Show)
instance PP RenamerError where
ppPrec _ e = case e of
MultipleSyms lqn qns ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 $ (text "Multiple definitions for symbol:" <+> pp (thing lqn))
$$ vcat (map pp qns)
UnboundExpr lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (text "Value not in scope:" <+> pp (thing lqn))
UnboundType lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (text "Type not in scope:" <+> pp (thing lqn))
OverlappingSyms qns ->
hang (text "[error]")
4 $ text "Overlapping symbols defined:"
$$ vcat (map pp qns)
ExpectedValue lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (fsep [ text "Expected a value named", quotes (pp (thing lqn))
, text "but found a type instead"
, text "Did you mean `(" <> pp (thing lqn) <> text")?" ])
ExpectedType lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (fsep [ text "Expected a type named", quotes (pp (thing lqn))
, text "but found a value instead" ])
FixityError o1 o2 ->
hang (text "[error]")
4 (fsep [ text "The fixities of", pp o1, text "and", pp o2
, text "are not compatible. "
, text "You may use explicit parenthesis to disambiguate" ])
InvalidConstraint ty ->
hang (text "[error]" <+> maybe empty (\r -> text "at" <+> pp r) (getLoc ty))
4 (fsep [ pp ty, text "is not a valid constraint" ])
-- Warnings --------------------------------------------------------------------
data RenamerWarning
= SymbolShadowed NameOrigin [NameOrigin]
deriving (Show)
instance PP RenamerWarning where
ppPrec _ (SymbolShadowed new originals) =
hang (text "[warning] at" <+> loc)
4 $ fsep [ text "This binding for" <+> sym
, text "shadows the existing binding" <> plural <+> text "from" ]
$$ vcat (map pp originals)
where
plural | length originals > 1 = char 's'
| otherwise = empty
(loc,sym) = case new of
Local lqn -> (pp (srcRange lqn), pp (thing lqn))
Imported qn -> (empty, pp qn)
-- Renaming Monad --------------------------------------------------------------
data RO = RO
{ roLoc :: Range
, roNames :: NamingEnv
}
data Out = Out
{ oWarnings :: [RenamerWarning]
, oErrors :: [RenamerError]
} deriving (Show)
instance Monoid Out where
mempty = Out [] []
mappend l r = Out (oWarnings l `mappend` oWarnings r)
(oErrors l `mappend` oErrors r)
newtype RenameM a = RenameM
{ unRenameM :: ReaderT RO (WriterT Out Id) a }
instance Functor RenameM where
{-# INLINE fmap #-}
fmap f m = RenameM (fmap f (unRenameM m))
instance Applicative RenameM where
{-# INLINE pure #-}
pure x = RenameM (pure x)
{-# INLINE (<*>) #-}
l <*> r = RenameM (unRenameM l <*> unRenameM r)
instance Monad RenameM where
{-# INLINE return #-}
return x = RenameM (return x)
{-# INLINE (>>=) #-}
m >>= k = RenameM (unRenameM m >>= unRenameM . k)
runRenamer :: NamingEnv -> RenameM a
-> (Either [RenamerError] a,[RenamerWarning])
runRenamer env m = (res,oWarnings out)
where
(a,out) = runM (unRenameM m) RO { roLoc = emptyRange, roNames = env }
res | null (oErrors out) = Right a
| otherwise = Left (oErrors out)
record :: RenamerError -> RenameM ()
record err = records [err]
records :: [RenamerError] -> RenameM ()
records errs = RenameM (put mempty { oErrors = errs })
located :: a -> RenameM (Located a)
located a = RenameM $ do
ro <- ask
return Located { srcRange = roLoc ro, thing = a }
withLoc :: HasLoc loc => loc -> RenameM a -> RenameM a
withLoc loc m = RenameM $ case getLoc loc of
Just range -> do
ro <- ask
local ro { roLoc = range } (unRenameM m)
Nothing -> unRenameM m
-- | Shadow the current naming environment with some more names.
shadowNames :: BindsNames env => env -> RenameM a -> RenameM a
shadowNames names m = RenameM $ do
let env = namingEnv names
ro <- ask
put (checkEnv env (roNames ro))
let ro' = ro { roNames = env `shadowing` roNames ro }
local ro' (unRenameM m)
-- | Generate warnings when the left environment shadows things defined in
-- the right. Additionally, generate errors when two names overlap in the
-- left environment.
checkEnv :: NamingEnv -> NamingEnv -> Out
checkEnv l r = Map.foldlWithKey (step neExprs) mempty (neExprs l)
`mappend` Map.foldlWithKey (step neTypes) mempty (neTypes l)
where
step prj acc k ns = acc `mappend` mempty
{ oWarnings = case Map.lookup k (prj r) of
Nothing -> []
Just os -> [SymbolShadowed (origin (head ns)) (map origin os)]
, oErrors = containsOverlap ns
}
-- | Check the RHS of a single name rewrite for conflicting sources.
containsOverlap :: HasQName a => [a] -> [RenamerError]
containsOverlap [_] = []
containsOverlap [] = panic "Renamer" ["Invalid naming environment"]
containsOverlap ns = [OverlappingSyms (map origin ns)]
-- | Throw errors for any names that overlap in a rewrite environment.
checkNamingEnv :: NamingEnv -> ([RenamerError],[RenamerWarning])
checkNamingEnv env = (out, [])
where
out = Map.foldr check outTys (neExprs env)
outTys = Map.foldr check mempty (neTypes env)
check ns acc = containsOverlap ns ++ acc
-- Renaming --------------------------------------------------------------------
class Rename a where
rename :: a -> RenameM a
instance Rename a => Rename [a] where
rename = traverse rename
instance Rename a => Rename (Maybe a) where
rename = traverse rename
instance Rename a => Rename (Located a) where
rename loc = withLoc loc $ do
a' <- rename (thing loc)
return loc { thing = a' }
instance Rename a => Rename (Named a) where
rename n = do
a' <-rename (value n)
return n { value = a' }
instance Rename Module where
rename m = do
decls' <- rename (mDecls m)
return m { mDecls = decls' }
instance Rename TopDecl where
rename td = case td of
Decl d -> Decl <$> rename d
TDNewtype n -> TDNewtype <$> rename n
Include{} -> return td
instance Rename a => Rename (TopLevel a) where
rename tl = do
a' <- rename (tlValue tl)
return tl { tlValue = a' }
instance Rename Decl where
rename d = case d of
DSignature ns sig -> DSignature ns <$> rename sig
DPragma ns p -> DPragma ns <$> rename p
DBind b -> DBind <$> rename b
DPatBind pat e -> DPatBind pat <$> shadowNames (namingEnv pat) (rename e)
DType syn -> DType <$> rename syn
DLocated d' r -> withLoc r
$ DLocated <$> rename d' <*> pure r
DFixity{} -> panic "Renamer" ["Unexpected fixity declaration", show d]
instance Rename Newtype where
rename n = do
name' <- renameLoc renameType (nName n)
body' <- shadowNames (nParams n) (rename (nBody n))
return Newtype { nName = name'
, nParams = nParams n
, nBody = body' }
renameVar :: QName -> RenameM QName
renameVar qn = do
ro <- RenameM ask
case Map.lookup qn (neExprs (roNames ro)) of
Just [en] -> return (qname en)
Just [] ->
panic "Renamer" ["Invalid expression renaming environment"]
Just syms ->
do n <- located qn
record (MultipleSyms n (map origin syms))
return qn
Nothing ->
do n <- located qn
case Map.lookup qn (neTypes (roNames ro)) of
-- types existed with the name of the value expected
Just _ -> record (ExpectedValue n)
-- the value is just missing
Nothing -> record (UnboundExpr n)
return qn
renameType :: QName -> RenameM QName
renameType qn = do
ro <- RenameM ask
case Map.lookup qn (neTypes (roNames ro)) of
Just [tn] -> return (qname tn)
Just [] -> panic "Renamer" ["Invalid type renaming environment"]
Just syms ->
do n <- located qn
record (MultipleSyms n (map origin syms))
return qn
Nothing ->
do n <- located qn
case Map.lookup qn (neExprs (roNames ro)) of
-- values exist with the same name, so throw a different error
Just _ -> record (ExpectedType n)
-- no terms with the same name, so the type is just unbound
Nothing -> record (UnboundType n)
return qn
-- | Rename a schema, assuming that none of its type variables are already in
-- scope.
instance Rename Schema where
rename s@(Forall ps _ _ _) = shadowNames ps (renameSchema s)
-- | Rename a schema, assuming that the type variables have already been brought
-- into scope.
renameSchema :: Schema -> RenameM Schema
renameSchema (Forall ps p ty loc) = Forall ps <$> rename p <*> rename ty
<*> pure loc
instance Rename Prop where
rename p = case p of
CFin t -> CFin <$> rename t
CEqual l r -> CEqual <$> rename l <*> rename r
CGeq l r -> CGeq <$> rename l <*> rename r
CArith t -> CArith <$> rename t
CCmp t -> CCmp <$> rename t
CLocated p' r -> withLoc r
$ CLocated <$> rename p' <*> pure r
-- here, we rename the type and then require that it produces something that
-- looks like a Prop
CType t -> translateProp t
translateProp :: Type -> RenameM Prop
translateProp ty = go =<< rnType True ty
where
go t = case t of
TLocated t' r -> (`CLocated` r) <$> go t'
TUser (QName Nothing (Name p)) [l,r]
| p == "==" -> pure (CEqual l r)
| p == ">=" -> pure (CGeq l r)
| p == "<=" -> pure (CGeq r l)
_ ->
do record (InvalidConstraint ty)
return (CType t)
instance Rename Type where
rename = rnType False
rnType :: Bool -> Type -> RenameM Type
rnType isProp = go
where
go t = case t of
TFun a b -> TFun <$> go a <*> go b
TSeq n a -> TSeq <$> go n <*> go a
TBit -> return t
TNum _ -> return t
TChar _ -> return t
TInf -> return t
TUser (QName Nothing (Name n)) ps
| n == "inf", null ps -> return TInf
| n == "Bit", null ps -> return TBit
| n == "min" -> TApp TCMin <$> traverse go ps
| n == "max" -> TApp TCMax <$> traverse go ps
| n == "lengthFromThen" -> TApp TCLenFromThen <$> traverse go ps
| n == "lengthFromThenTo" -> TApp TCLenFromThenTo <$> traverse go ps
| n == "width" -> TApp TCWidth <$> traverse go ps
TUser qn ps -> TUser <$> renameType qn <*> traverse go ps
TApp f xs -> TApp f <$> traverse go xs
TRecord fs -> TRecord <$> traverse (traverse go) fs
TTuple fs -> TTuple <$> traverse go fs
TWild -> return t
TLocated t' r -> withLoc r
$ TLocated <$> go t' <*> pure r
TParens t' -> TParens <$> go t'
TInfix a o _ b ->
do op <- renameTypeOp isProp o
a' <- go a
b' <- go b
mkTInfix a' op b'
type TOp = Type -> Type -> Type
mkTInfix :: Type -> (TOp,Fixity) -> Type -> RenameM Type
-- this should be one of the props, or an error, so just assume that its fixity
-- is `infix 0`.
mkTInfix t@(TUser o1 [x,y]) op@(o2,f2) z =
do let f1 = Fixity NonAssoc 0
case compareFixity f1 f2 of
FCLeft -> return (o2 t z)
FCRight -> do r <- mkTInfix y op z
return (TUser o1 [x,r])
FCError -> panic "Renamer" [ "fixity problem for type operators"
, show (o2 t z) ]
mkTInfix t@(TApp o1 [x,y]) op@(o2,f2) z
| Just (a1,p1) <- Map.lookup o1 tBinOpPrec =
case compareFixity (Fixity a1 p1) f2 of
FCLeft -> return (o2 t z)
FCRight -> do r <- mkTInfix y op z
return (TApp o1 [x,r])
FCError -> panic "Renamer" [ "fixity problem for type operators"
, show (o2 t z) ]
mkTInfix (TLocated t _) op z =
mkTInfix t op z
mkTInfix t (op,_) z =
return (op t z)
-- | Rename a type operator, mapping it to a real type function. When isProp is
-- True, it's assumed that the renaming is happening in the context of a Prop,
-- which allows unresolved operators to propagate without an error. They will
-- be resolved in the CType case for Prop.
renameTypeOp :: Bool -> Located QName -> RenameM (TOp,Fixity)
renameTypeOp isProp op =
do let sym = unqual (thing op)
props = [ Name "==", Name ">=", Name "<=" ]
lkp = do n <- Map.lookup (thing op) tfunNames
(fAssoc,fLevel) <- Map.lookup n tBinOpPrec
return (n,Fixity { .. })
case lkp of
Just (p,f) ->
return (\x y -> TApp p [x,y], f)
Nothing
| isProp && sym `elem` props ->
return (\x y -> TUser (thing op) [x,y], Fixity NonAssoc 0)
| otherwise ->
do record (UnboundType op)
return (\x y -> TUser (thing op) [x,y], defaultFixity)
instance Rename Pragma where
rename p = case p of
PragmaNote _ -> return p
PragmaProperty -> return p
-- | The type renaming environment generated by a binding.
bindingTypeEnv :: Bind -> NamingEnv
bindingTypeEnv b = patParams `shadowing` sigParams
where
-- type parameters
sigParams = namingEnv (bSignature b)
-- pattern type parameters
patParams = foldMap (foldMap qualType . tnamesP) (bParams b)
qualType qn = singletonT qn (TFromParam qn)
-- | Rename a binding.
--
-- NOTE: this does not bind its own name into the naming context of its body.
-- The assumption here is that this has been done by the enclosing environment,
-- to allow for top-level renaming
instance Rename Bind where
rename b = do
n' <- renameLoc renameVar (bName b)
shadowNames (bindingTypeEnv b) $ do
(patenv,pats') <- renamePats (bParams b)
sig' <- traverse renameSchema (bSignature b)
shadowNames patenv $
do e' <- rename (bDef b)
p' <- rename (bPragmas b)
return b { bName = n'
, bParams = pats'
, bDef = e'
, bSignature = sig'
, bPragmas = p'
}
instance Rename BindDef where
rename DPrim = return DPrim
rename (DExpr e) = DExpr <$> rename e
-- NOTE: this only renames types within the pattern.
instance Rename Pattern where
rename p = case p of
PVar _ -> pure p
PWild -> pure p
PTuple ps -> PTuple <$> rename ps
PRecord nps -> PRecord <$> rename nps
PList elems -> PList <$> rename elems
PTyped p' t -> PTyped <$> rename p' <*> rename t
PSplit l r -> PSplit <$> rename l <*> rename r
PLocated p' loc -> withLoc loc
$ PLocated <$> rename p' <*> pure loc
instance Rename Expr where
rename e = case e of
EVar n -> EVar <$> renameVar n
ELit _ -> return e
ETuple es -> ETuple <$> rename es
ERecord fs -> ERecord <$> rename fs
ESel e' s -> ESel <$> rename e' <*> pure s
EList es -> EList <$> rename es
EFromTo s n e'-> EFromTo <$> rename s <*> rename n <*> rename e'
EInfFrom a b -> EInfFrom<$> rename a <*> rename b
EComp e' bs -> do bs' <- mapM renameMatch bs
shadowNames (namingEnv bs')
(EComp <$> rename e' <*> pure bs')
EApp f x -> EApp <$> rename f <*> rename x
EAppT f ti -> EAppT <$> rename f <*> rename ti
EIf b t f -> EIf <$> rename b <*> rename t <*> rename f
EWhere e' ds -> shadowNames ds (EWhere <$> rename e' <*> rename ds)
ETyped e' ty -> ETyped <$> rename e' <*> rename ty
ETypeVal ty -> ETypeVal<$> rename ty
EFun ps e' -> do ps' <- rename ps
shadowNames ps' (EFun ps' <$> rename e')
ELocated e' r -> withLoc r
$ ELocated <$> rename e' <*> pure r
EParens p -> EParens <$> rename p
EInfix x y _ z-> do op <- renameOp y
x' <- rename x
z' <- rename z
mkEInfix x' op z'
mkEInfix :: Expr -- ^ May contain infix expressions
-> (Located QName,Fixity) -- ^ The operator to use
-> Expr -- ^ Will not contain infix expressions
-> RenameM Expr
mkEInfix e@(EInfix x o1 f1 y) op@(o2,f2) z =
case compareFixity f1 f2 of
FCLeft -> return (EInfix e o2 f2 z)
FCRight -> do r <- mkEInfix y op z
return (EInfix x o1 f1 r)
FCError -> do record (FixityError o1 o2)
return (EInfix e o2 f2 z)
mkEInfix (ELocated e' _) op z =
mkEInfix e' op z
mkEInfix e (o,f) z =
return (EInfix e o f z)
renameOp :: Located QName -> RenameM (Located QName,Fixity)
renameOp ln = withLoc ln $
do n <- renameVar (thing ln)
ro <- RenameM ask
case Map.lookup n (neFixity (roNames ro)) of
Just [fixity] -> return (ln { thing = n },fixity)
_ -> return (ln { thing = n },defaultFixity)
instance Rename TypeInst where
rename ti = case ti of
NamedInst nty -> NamedInst <$> rename nty
PosInst ty -> PosInst <$> rename ty
renameMatch :: [Match] -> RenameM [Match]
renameMatch = loop
where
loop ms = case ms of
m:rest -> do
m' <- rename m
(m':) <$> shadowNames m' (loop rest)
[] -> return []
renamePats :: [Pattern] -> RenameM (NamingEnv,[Pattern])
renamePats = loop
where
loop ps = case ps of
p:rest -> do
p' <- rename p
let pe = namingEnv p'
(env',rest') <- loop rest
return (pe `mappend` env', p':rest')
[] -> return (mempty, [])
instance Rename Match where
rename m = case m of
Match p e -> Match <$> rename p <*> rename e
MatchLet b -> shadowNames b (MatchLet <$> rename b)
instance Rename TySyn where
rename (TySyn n ps ty) =
shadowNames ps (TySyn <$> renameLoc renameType n <*> pure ps <*> rename ty)
renameLoc :: (a -> RenameM b) -> Located a -> RenameM (Located b)
renameLoc by loc = do
a' <- by (thing loc)
return loc { thing = a' }
|
ntc2/cryptol
|
src/Cryptol/ModuleSystem/Renamer.hs
|
bsd-3-clause
| 20,524 | 0 | 18 | 6,340 | 6,918 | 3,380 | 3,538 | 445 | 15 |
module Hans.Simple (
-- * UDP Messages
renderUdp
, renderIp4
-- * Ident
, Ident
, newIdent
, nextIdent
) where
import Hans.Address.IP4 (IP4)
import Hans.Message.Ip4 (IP4Packet(..),IP4Header(..),IP4Protocol(..)
,mkIP4PseudoHeader,splitPacket,renderIP4Packet
,emptyIP4Header)
import Hans.Message.Udp (UdpHeader(..),UdpPort,UdpPacket(..),renderUdpPacket)
import qualified Hans.Message.Ip4 as IP4
import Control.Concurrent (MVar,newMVar,modifyMVar)
import Data.Word (Word16)
import qualified Data.ByteString as S
newtype Ident = Ident (MVar IP4.Ident)
newIdent :: IO Ident
newIdent = Ident `fmap` newMVar 0
nextIdent :: Ident -> IO IP4.Ident
nextIdent (Ident var) = modifyMVar var (\i -> return (i+1, i))
type MTU = Word16
fromMTU :: Maybe MTU -> Int
fromMTU = maybe ip4Max (min ip4Max . fromIntegral)
where ip4Max = 0xffff
-- | Render a UDP message to an unfragmented IP4 packet.
renderUdp :: Ident -> Maybe MTU -> IP4 -> IP4 -> UdpPort -> UdpPort
-> S.ByteString
-> IO [S.ByteString]
renderUdp i mb source dest srcPort destPort payload = do
let prot = IP4Protocol 0x11
let mk = mkIP4PseudoHeader source dest prot
let hdr = UdpHeader
{ udpSourcePort = srcPort
, udpDestPort = destPort
, udpChecksum = 0
}
udp <- renderUdpPacket (UdpPacket hdr payload) mk
renderIp4 i mb prot source dest udp
-- | Render an IP4 packet.
renderIp4 :: Ident -> Maybe MTU -> IP4Protocol -> IP4 -> IP4 -> S.ByteString
-> IO [S.ByteString]
renderIp4 ident mb prot source dest payload = do
i <- nextIdent ident
let hdr = (emptyIP4Header prot source dest) { ip4Ident = i }
mapM renderIP4Packet (splitPacket (fromMTU mb) (IP4Packet hdr payload))
|
Tener/HaNS
|
src/Hans/Simple.hs
|
bsd-3-clause
| 1,786 | 0 | 14 | 412 | 573 | 315 | 258 | 42 | 1 |
module Level where
-- | Experience points.
newtype Experience = Experience Int
deriving (Eq, Show, Read)
-- | Levels are calculated from experience points
-- using the function toLevel.
newtype Level = Level Int
deriving (Eq, Show, Read)
-- | The calculation for the Level.
-- Basically, is log base 2.
toLevel :: Experience -> Level
toLevel (Experience 0) = error "Zero Experience"
toLevel (Experience xp) = Level $ floor $ logBase 2 (toEnum xp :: Double)
-- | Returns the range of experience a level cover.
toExpBound :: Level -> (Experience, Experience)
toExpBound (Level lvl) = (Experience (2 ^ lvl), Experience (2 ^ (lvl + 1) - 1 ))
|
Megaleo/Minehack
|
src/Level.hs
|
bsd-3-clause
| 675 | 0 | 11 | 147 | 184 | 102 | 82 | 10 | 1 |
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}
--
-- Module : Event
-- Copyright : Copyright © 2014, Quixoftic, LLC <[email protected]>
-- License : BSD3 (see LICENSE file)
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- SXSW music event representation.
--
module Event (Event(..)) where
import Data.Data (Data, Typeable)
import Data.Time as Time
import qualified Data.Text.Lazy as T
import GHC.Generics
import Data.Aeson
-- Some fields are optional, and are represented either as Maybe a, or as
-- an empty list.
--
-- The day of the event (e.g., "2014-03-12") is recorded along with
-- the exact start and end times because some events don't have a
-- start and end time.
data Event = Event { url :: T.Text
, artist :: T.Text
, venue :: T.Text
, day :: T.Text
, start :: Maybe UTCTime
, end :: Maybe UTCTime
, ages :: Maybe T.Text
, hashTags :: [T.Text]
} deriving (Show, Data, Typeable, Generic)
instance ToJSON Event
instance FromJSON Event
|
quixoftic/Sxcrape
|
src/Event.hs
|
bsd-3-clause
| 1,168 | 0 | 10 | 337 | 183 | 116 | 67 | 18 | 0 |
module Brain.Submitted where
import Core
import Logic
import Brain
import MonadBrain
import BUtils
import Control.Arrow
import Control.Applicative
import Control.Monad (forever, when)
import Data.Maybe
import Data.List (sort, (\\), sortBy)
import qualified Data.Vector as V
import Prelude hiding (break)
import Data.Ord
submittedBrain :: Brain
submittedBrain = toBrain $ do
mm <- lastOpponentMove
when (isNothing mm) $ move nop
forever $ do
reviveOne
(zombieSlot:_) <- free
zombieSlot `applyFieldToCard` Help
(opSlot1:_) <- interesting
zombieSlot `applyInt` opSlot1
(opSlot2:_) <- exclude [opSlot1] <$> interesting
zombieSlot `applyInt` opSlot2
K `applyCardToField` zombieSlot
S `applyCardToField` zombieSlot
reviveOne
(zombieArgSlot:_) <- exclude [zombieSlot] <$> free
v <- MonadBrain.vitality opSlot1 opponent
load v zombieArgSlot
K `applyCardToField` zombieArgSlot
zombieSlot `apply` zombieArgSlot
Put `applyCardToField` zombieArgSlot
reviveOne
freeSlots <- exclude [zombieSlot, zombieArgSlot] <$> free
when (null feeSlots) $ do
printState
allFree <- free
alert $ "free: " ++ show allFrees
break
(zombieAttackSlot:_) <- exclude [zombieSlot, zombieArgSlot] <$> free
zombieAttackSlot `applyFieldToCard` Zombie
ds <- deadSlots
if (null ds)
then do
slot <- doAttack
zombieAttackSlot `applyInt` slot
else do
zombieAttackSlot `applyInt` (255 - head ds)
zombieAttackSlot `apply` zombieSlot
Put `applyCardToField` zombieSlot
exclude :: [SlotNr] -> [SlotNr] -> [SlotNr]
exclude blackList sluts = sluts \\ blackList
reviveOne :: B ()
reviveOne = availableSlot $ \slot -> do
findSlot (return . dead) $ \j -> do
slot `applyFieldToCard` Revive
applyInt slot j
-- | Opponent's slots that are alive, sorted by size
interesting :: B [SlotNr]
interesting = do
slts <- slots opponent
let ss = map snd . reverse . sortBy (comparing fst) . reverse . (map . first $ size . Core.field)
$ filter (alive . fst) $ zip (V.toList slts) [0 :: Int ..]
return $ ss ++ [0..255] -- In case there's a bug, return everything
-- | Opponent's slots that are dead, with the biggest expresssion
deadSlots :: B [SlotNr]
deadSlots = do
slts <- slots opponent
let ss = map snd . reverse . sort . (map . first $ size . Core.field)
$ filter (dead . fst) $ zip (V.toList slts) [0 :: Int ..]
return $ ss
-- | Proponent's slots that are empty, sorted by vitality
free :: B [SlotNr]
free = do
slts <- slots proponent
let ss = map snd . sortBy cmpInv . (map . first $ Core.vitality)
$ filter (\(s,_) -> isI s && alive s) $ zip (V.toList slts) [0 :: Int ..]
return $ ss
-- | Attack the opponent's weakest slot, return the slot number of a dead slot
doAttack :: B SlotNr
doAttack = do
opSlots <- slots opponent
let ss = map snd . sortBy cmp . (map . first $ Core.vitality &&& size . Core.field)
$ zip (V.toList opSlots) [255,254..]
(s:_) <- return ss
let opSlot = opSlots V.! (255 - s)
let v = Core.vitality opSlot
if v == 0
then return s
else if v == 1
then do
(p:_) <- free
p `applyFieldToCard` Dec
p `applyInt` s
doAttack
else do
(p:q:_) <- free
proSlots <- slots proponent
let proSlot = proSlots V.! p
let v' = Core.vitality proSlot
attack p s (minimum [v * 10 `div` 9 + 1, v' - 1, 5556]) q
doAttack
isI :: Slot -> Bool
isI (Slot (Card I) _) = True
isI _ = False
cmpInv :: Ord a => (a, Int) -> (a, Int) -> Ordering
cmpInv (a, i) (b, j)
| a == b = intMoves i `compare` intMoves j
| otherwise = b `compare` a
cmp :: Ord a => (a, Int) -> (a, Int) -> Ordering
cmp (a, i) (b, j)
| a == b = intMoves i `compare` intMoves j
| otherwise = a `compare` b
intMoves :: Int -> Int
intMoves n | n == 0 = 1
| odd n = 1 + intMoves (n - 1)
| otherwise = 1 + intMoves (n `div` 2)
|
sjoerdvisscher/icfp2011
|
src/Brain/Submitted.hs
|
bsd-3-clause
| 4,093 | 0 | 17 | 1,106 | 1,579 | 810 | 769 | -1 | -1 |
module Main where
import Conduit.Simple as S
import Control.Exception
import Criterion.Main
import Data.Conduit as C
import Data.Conduit.Combinators as C
import Fusion as F
import Pipes as P
import qualified Pipes.Prelude as P
import Test.Hspec
import Test.Hspec.Expectations
main :: IO ()
main = do
hspec $ do
describe "basic tests" $
it "passes tests" $ True `shouldBe` True
defaultMain [
bgroup "basic" [ -- bench "pipes" $ nfIO pipes_basic
-- ,
bench "conduit" $ nfIO conduit_basic
, -- bench "simple-conduit" $ nfIO simple_conduit_basic
-- ,
bench "fusion" $ nfIO fusion_basic
, bench "conduit" $ nfIO conduit_basic
, bench "fusion" $ nfIO fusion_basic
]
]
pipes_basic :: IO Int
pipes_basic = do
xs <- P.toListM $ P.each [1..1000000]
P.>-> P.filter even
P.>-> P.map (+1)
P.>-> P.drop 1000
P.>-> P.map (+1)
P.>-> P.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length xs)
conduit_basic :: IO Int
conduit_basic = do
xs <- C.yieldMany [1..1000000]
C.$= C.filter even
C.$= C.map ((+1) :: Int -> Int)
C.$= (C.drop 1000 >> C.awaitForever C.yield)
C.$= C.map ((+1) :: Int -> Int)
C.$= C.filter (\x -> x `mod` 2 == 0)
C.$$ C.sinkList
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
simple_conduit_basic :: IO Int
simple_conduit_basic = do
xs <- S.sourceList [1..1000000]
S.$= S.filterC even
S.$= S.mapC ((+1) :: Int -> Int)
S.$= S.dropC 1000
S.$= S.mapC ((+1) :: Int -> Int)
S.$= S.filterC (\x -> x `mod` 2 == 0)
S.$$ S.sinkList
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
fusion_basic :: IO Int
fusion_basic = do
xs <- F.toList $ F.each [1..1000000]
F.>-> F.filter even
F.>-> F.map (+1)
F.>-> F.drop 1000
F.>-> F.map (+1)
F.>-> F.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
|
jwiegley/streaming-tests
|
test/Main.hs
|
bsd-3-clause
| 2,404 | 0 | 15 | 868 | 865 | 453 | 412 | 64 | 1 |
module Text.RE.Tools
(
-- * The Tools
-- $tools
-- * Sed
sed
, sed'
-- * Grep
, grep
, grepLines
, GrepScript
, grepScript
, linesMatched
-- * Lex
, alex
, alex'
-- * IsRegex
, IsRegex(..)
-- * Edit
, Edits(..)
, Edit(..)
, LineEdit(..)
, applyEdits
, applyEdit
, applyLineEdit
-- * LineNo
, LineNo(..)
, firstLine
, getLineNo
, lineNo
-- * Text.RE
, module Text.RE
) where
import Text.RE
import Text.RE.Tools.Edit
import Text.RE.Tools.Grep
import Text.RE.Tools.Lex
import Text.RE.Tools.Sed
|
Lainepress/easy
|
Text/RE/Tools.hs
|
bsd-3-clause
| 609 | 0 | 5 | 202 | 137 | 97 | 40 | 28 | 0 |
module Astro.Time.Barycentric.TestAsA2009 where
-- TODO: Clean out an keep only TDB/TCB test cases.
import Numeric.Units.Dimensional.Prelude
import qualified Prelude
import Astro
import Astro.DefaultData
import Astro.Time
import Astro.Time.Convert
import Astro.Time.Barycentric.AsA2009
--import Astro.Time.TDB.TT
import Test.QuickCheck
import Data.Time hiding (utc)
import Data.Time.Clock.TAI
-- Preliminaries
-- =============
onceCheck = quickCheckWith stdArgs { maxSuccess = 1 }
conv t = runAstro (convert t) defaultAstroData
-- | Comparison allowing for inaccuracy.
cmpE :: (Fractional a, Ord a) => Time a -> E t a -> E t a -> Bool
cmpE accuracy t t' = abs (diffEpoch t t') < accuracy
-- Accuracies.
tdbError = 20 *~ micro second -- About 10 us according to Kaplan, but for Vallado's cases the difference is greater...
dblError = 1 *~ nano second
noError = 0 *~ second
-- Specific epochs
-- ===============
-- J200 epoch.
prop_J2000_jd = j2000 == jd 2451545 TT
prop_J2000_mjd = j2000 == mjd 51544.5 TT
prop_J2000_clock = j2000 == clock 2000 1 1 12 0 0 TT
prop_J2000_TAI = conv j2000 == clock 2000 1 1 11 59 27.816 TAI
-- prop_J2000_UTC = convertUTC () j2000 == clock 2000 1 1 11 58 55.816 UTC
-- Convergence epoch
-- -----------------
ttConverges = clock 1977 01 01 00 00 32.184 TT == conv (clock 1977 1 1 0 0 0 TAI)
tcgConverges = clock 1977 01 01 00 00 32.184 TCG == conv (clock 1977 1 1 0 0 0 TAI)
-- The accuracy of TDB and TCB are limited by the TDB conversions.
tcbConverges = cmpE tdbError (clock 1977 01 01 00 00 32.184 TCB) (conv $ clock 1977 1 1 0 0 0 TAI)
tdbConverges = cmpE tdbError (clock 1977 01 01 00 00 32.1839345 TDB) (conv $ clock 1977 1 1 0 0 0 TAI)
-- This first test isn't adversely affected by conversion to Double while the second is.
prop_TDBTCB_conv = clock 1977 01 01 00 00 32.184 TCB == conv (clock 1977 01 01 00 00 32.1839345 TDB)
prop_TDBTCB_conv' = cmpE dblError (conv $ clock 1977 01 01 00 00 32.184 TCB) (clock 1977 01 01 00 00 32.1839345 TDB)
-- Conversion tests
-- ================
-- Check conversions back and forth are consistent. Test around both
-- JD 0 and MJD 0 to make sure we aren't favoring algorithms that are
-- only good around certain dates.
prop_TAI, prop_TT, prop_TCG, prop_TDB, prop_TCB, prop_TCB' :: Double -> Bool
-- These should be exact.
prop_TAI a = let t = jd a TAI in t == conv (conv t :: E TAI Double) -- ^ Conversion back and forth to TAI.
&& let t = mjd a TAI in t == conv (conv t :: E TAI Double) -- ^ Conversion back and forth to TAI.
prop_TT a = let t = jd a TT in t == conv (conv t :: E TAI Double) -- ^ Conversion back and forth to TAI.
&& let t = mjd a TT in t == conv (conv t :: E TAI Double) -- ^ Conversion back and forth to TAI.
-- In the remaining double precision errors come into play.
prop_TCG a = let t = jd a TCG in cmpE dblError t (conv (conv t :: E TAI Double)) -- ^ Conversion back and forth to TAI.
&& let t = mjd a TCG in cmpE dblError t (conv (conv t :: E TAI Double)) -- ^ Conversion back and forth to TAI.
-- Accuracy of TDB|TCB <-> TAI is limited by the accuracy of TDB <-> TAI.
-- However, the reverse conversion appears to cancels the error nicely.
prop_TDB a = let t = jd a TDB in cmpE dblError t (conv (conv t :: E TAI Double)) -- ^ Conversion back and forth to TAI.
&& let t = mjd a TDB in cmpE dblError t (conv (conv t :: E TAI Double)) -- ^ Conversion back and forth to TAI.
prop_TCB a = let t = jd a TCB in cmpE dblError t (conv (conv t :: E TAI Double)) -- ^ Conversion back and forth to TAI.
&& let t = mjd a TCB in cmpE dblError t (conv (conv t :: E TAI Double)) -- ^ Conversion back and forth to TAI.
-- The accuracy of TCB <-> TDB conversions should be good. (This test is mostly redundant given prop_TCB).
prop_TCB' a = let t = jd a TCB in cmpE dblError t (conv (conv t :: E TDB Double)) -- ^ Conversion back and forth to TDB.
&& let t = mjd a TCB in cmpE dblError t (conv (conv t :: E TDB Double)) -- ^ Conversion back and forth to TDB.
-- Tests from literature
-- =====================
-- utc 1990 05 14 10 43 00.000 from [1].
valladoExample = tai == conv tt
&& cmpE tdbError (tai) (conv tdb)
&& cmpE tdbError (tt ) (conv tdb)
where
tai = clock 1990 05 14 16 43 25.000 TAI
tt = clock 1990 05 14 16 43 57.184 TT
tdb = clock 1990 05 14 16 43 57.18527 TDB
-- utc 2004 04 06 07 51 28.386009 from [2].
valladoExample2 = tai == conv tt && conv tai == tt
&& cmpE dblError tai (conv tcg) -- Test conversion from TCG.
&& cmpE dblError (conv tai) tcg -- Test conversion to TCG.
&& cmpE tdbError tai (conv tdb) -- Test conversion from TDB.
&& cmpE tdbError (conv tai) tdb -- Test conversion to TDB.
-- && cmpE dblError (tdbToTCB tdb) tcb -- Test conversion to TCB.
-- && cmpE tdbError (fromTAI $ toTAI tai) tcb -- Test conversion to TCB.
--where
tai = clock 2004 04 06 7 52 00.386009 TAI
tt = clock 2004 04 06 7 52 32.570009 TT
tcg = clock 2004 04 06 7 52 33.1695861742 TCG
tdb = clock 2004 04 06 7 52 32.5716651154 TDB
tcb = clock 2004 04 06 7 52 45.9109901113 TCB -- Incorrect in example, no offset.
-- Driver
-- ======
main = do
-- Start with the faster-running tests.
onceCheck prop_J2000_jd
onceCheck prop_J2000_mjd
onceCheck prop_J2000_clock
onceCheck prop_J2000_TAI
onceCheck prop_TDBTCB_conv
onceCheck prop_TDBTCB_conv'
onceCheck ttConverges
onceCheck tcgConverges
onceCheck tcbConverges
onceCheck tdbConverges
onceCheck valladoExample
onceCheck valladoExample2
quickCheck prop_TAI
quickCheck prop_TT
quickCheck prop_TCG
quickCheck prop_TDB
quickCheck prop_TCB
quickCheck prop_TCB'
|
bjornbm/astro
|
test/Astro/Time/Barycentric/TestAsA2009.hs
|
bsd-3-clause
| 5,810 | 0 | 14 | 1,363 | 1,631 | 819 | 812 | 76 | 1 |
module LGtk.Demos.Maze.Types
where
import Data.Array (Array)
import Data.Vector (Vector)
{-
Common types are presented in this file.
-}
{- Small typedefs -}
type Length = Int
type Coord = Int
type Size = (Length, Length)
type Point = Size
type Dir = Size
type Time = Int
type Fitness = Int
{- The cardinal directions. -}
data Cardinal = N | E | S | W deriving (Eq, Show, Read, Ord, Enum)
{- A cell. The list contains the openings. -}
newtype Cell = C [Cardinal] deriving (Eq, Show, Read)
{- Simple type for maze. -}
type Maze = Array Size Cell
{- A plan is a vector of directions to go, at each time step. -}
type Plan = Vector Cardinal
|
divipp/lgtk
|
lgtkdemo/LGtk/Demos/Maze/Types.hs
|
bsd-3-clause
| 645 | 0 | 6 | 130 | 167 | 104 | 63 | 14 | 0 |
module Main where
import Control.Lens ((%~))
import Control.Monad (foldM_)
import Data.Function ((&))
import SNEK.Check (checkVE, emptyE, eKSs, eTSs, eVSs, runCheck, veT)
import SNEK.Parse (parseVE)
import SNEK.PHP (runPHPGen, ve2PHPM)
import SNEK.Read (readData)
import SNEK.Symbol (KS(..), TS(..), VS(..))
import SNEK.Type ((~->~), K(..), prettyT, T(..))
import System.Directory (makeAbsolute)
import System.Environment (getArgs)
import qualified Data.Map as Map
main :: IO ()
main = do
sourceFiles <- getArgs >>= mapM makeAbsolute
foldM_ go Map.empty sourceFiles
where go ts file = do
text <- readFile file
let [datum] = fromJust $ readData text
let ast = fromRight $ parseVE datum
let tast = fromRight $ check ast
let t = veT tast
putStrLn $ runPHPGen (ve2PHPM tast)
return $ Map.insert file t ts
where check e = runCheck (checkVE e) env
env = emptyE file ts
& eKSs %~ Map.insert "*" (KS TypeK)
& eKSs %~ Map.insert "->" (KS FuncK)
& eTSs %~ Map.insert "bool" (TS BoolT)
& eTSs %~ Map.insert "->" (TS FuncT)
fromRight (Right x) = x
fromRight (Left x) = error (show x)
fromJust (Just x) = x
fromJust _ = error "nein"
|
rightfold/snek
|
app/Main.hs
|
bsd-3-clause
| 1,380 | 0 | 18 | 440 | 520 | 276 | 244 | 35 | 3 |
{-# OPTIONS_GHC -F -pgmF htfpp #-}
module VectorTests.Matrix4x4 where
import Geometry.Space
import Test.Framework
import VectorTests.VectorGenerators ()
prop_inverse :: Matrix4x4 Double -> Bool
prop_inverse a = (abs (det a) <= 1e-15) ||
( (abs (det (prod a (invert a) .- eye)) <= 1e-15)
&& (abs (det (prod (invert a) a .- eye)) <= 1e-15) )
|
achirkin/fgeom
|
test/VectorTests/Matrix4x4.hs
|
bsd-3-clause
| 367 | 0 | 17 | 81 | 140 | 74 | 66 | 9 | 1 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
-- | An implementation of the lambda calculus.
module Language.BLC.Core
( Expr(..)
-- * Construction
, lam
, app
-- * Reduction
, reduce
) where
import Prelude hiding (sequence)
import Bound
import Control.Applicative
import Control.Monad hiding (sequence)
import Data.Foldable (Foldable)
import Data.Traversable
import Prelude.Extras
-- | A lambda calculus expression, parameterized by the type of its variables.
data Expr a
= Var a
| App (Expr a) (Expr a)
| Lam (Scope () Expr a)
deriving (Eq, Ord, Show, Read, Functor, Foldable, Traversable)
instance Eq1 Expr
instance Ord1 Expr
instance Show1 Expr
instance Read1 Expr
instance Applicative Expr where
pure = Var
(<*>) = ap
instance Monad Expr where
return = Var
Var a >>= f = f a
App l r >>= f = App (l >>= f) (r >>= f)
Lam body >>= f = Lam (body >>>= f)
-- | Create a lambda abstraction.
lam :: Eq a => a -> Expr a -> Expr a
lam v b = Lam (abstract1 v b)
-- | Apply a function to a list of arguments.
app :: Expr a -> [Expr a] -> Expr a
app = foldl App
-- | Reduce an expression to beta-eta normal form.
reduce :: Expr a -> Expr a
reduce e@(Var _) = e
reduce (App f a) = beta f a
reduce (Lam s) = eta s
-- | Apply the beta reduction rule, if possible, using a
-- call-by-need evaluation strategy
beta :: Expr a -> Expr a -> Expr a
beta f a = case f' of
Lam b -> reduce (instantiate1 a' b)
_ -> App f' a'
where
(f', a') = (reduce f, reduce a)
-- | Apply eta conversion, if possible.
eta :: Scope () Expr a -> Expr a
eta s = maybe (Lam s) reduce $ case unscope s of
App a (Var (B ())) -> traverse fromVar a
_ -> Nothing
where
fromVar (F (Var a)) = Just a
fromVar _ = Nothing
|
knrafto/blc
|
src/Language/BLC/Core.hs
|
bsd-3-clause
| 1,870 | 0 | 14 | 514 | 661 | 339 | 322 | 49 | 3 |
{-# LANGUAGE FlexibleContexts #-}
module Control.ConstraintClasses.Ap
(
-- * Constraint Apply
CAp (..)
, (<*>:)
) where
import Control.ConstraintClasses.Domain
import Control.ConstraintClasses.Apply
-- base
import Data.Functor.Product
import Data.Functor.Sum
import Data.Functor.Compose
-- vector
import qualified Data.Vector as Vector
--------------------------------------------------------------------------------
-- CLASS
--------------------------------------------------------------------------------
class (DomClosed f, CApply f) => CAp f where
_ap ::
(Dom f a, Dom f b) =>
f (a -> b) -> f a -> f b
infixl 4 <*>:
(<*>:) :: (CAp f, Dom f a, Dom f b) => f (a -> b) -> f a -> f b
(<*>:) = _ap
{-# INLINE (<*>:) #-}
--------------------------------------------------------------------------------
-- INSTANCES
--------------------------------------------------------------------------------
-- base
instance CAp [] where
_ap = (<*>)
instance CAp Maybe where
_ap = (<*>)
-- vector
instance CAp Vector.Vector where
_ap = (<*>)
|
guaraqe/constraint-classes
|
src/Control/ConstraintClasses/Ap.hs
|
bsd-3-clause
| 1,070 | 0 | 11 | 170 | 261 | 156 | 105 | 25 | 1 |
-- | Re-exports of base functionality. Note that this module is just
-- used inside the compiler. It's not compiled to JavaScript.
-- Based on the base-extended package (c) 2013 Simon Meier, licensed as BSD3.
module Fay.Compiler.Prelude
( module Prelude -- Partial
-- * Control modules
, module Control.Applicative
, module Control.Arrow -- Partial
, module Control.Monad
-- * Data modules
, module Data.Char -- Partial
, module Data.Data -- Partial
, module Data.Either
, module Data.Function
, module Data.List -- Partial
, module Data.Maybe
, module Data.Monoid -- Partial
, module Data.Ord
-- * Safe
, module Safe
-- * Additions
, anyM
, for
, io
, readAllFromProcess
) where
import Control.Applicative
import Control.Arrow (first, second, (&&&), (***), (+++), (|||))
import Control.Monad hiding (guard)
import Data.Char hiding (GeneralCategory (..))
import Data.Data (Data (..), Typeable)
import Data.Either
import Data.Function (on)
import Data.List hiding (delete)
import Data.Maybe
import Data.Monoid (Monoid (..), (<>))
import Data.Ord
import Prelude hiding (exp, mod)
import Safe
import Control.Monad.Error
import System.Exit
import System.Process
-- | Alias of liftIO, I hate typing it. Hate reading it.
io :: MonadIO m => IO a -> m a
io = liftIO
-- | Do any of the (monadic) predicates match?
anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool
anyM p l = return . not . null =<< filterM p l
-- | Flip of map.
for :: (Functor f) => f a -> (a -> b) -> f b
for = flip fmap
-- | Read from a process returning both std err and out.
readAllFromProcess :: FilePath -> [String] -> String -> IO (Either (String,String) (String,String))
readAllFromProcess program flags input = do
(code,out,err) <- readProcessWithExitCode program flags input
return $ case code of
ExitFailure 127 -> Left ("cannot find executable " ++ program, "")
ExitFailure _ -> Left (err, out)
ExitSuccess -> Right (err, out)
|
fpco/fay
|
src/Fay/Compiler/Prelude.hs
|
bsd-3-clause
| 2,222 | 0 | 13 | 638 | 556 | 332 | 224 | 47 | 3 |
module Chapter4 where
isPalindrome :: Eq a => [a] -> Bool
isPalindrome xs = xs == reverse xs
myAbs :: Integer -> Integer
myAbs x = if x < 0 then negate x else x
f :: (a, b) -> (c, d) -> ((b, d), (a, c))
f x y = ((snd x, snd y), (fst x, fst y))
|
taojang/haskell-programming-book-exercise
|
src/ch04/chapter4.hs
|
bsd-3-clause
| 247 | 0 | 8 | 62 | 153 | 85 | 68 | 7 | 2 |
module IRTS.Lang where
import Control.Monad.State hiding (lift)
import Core.TT
import Data.List
import Debug.Trace
data LVar = Loc Int | Glob Name
deriving (Show, Eq)
data LExp = LV LVar
| LApp Bool LExp [LExp] -- True = tail call
| LLazyApp Name [LExp] -- True = tail call
| LLazyExp LExp
| LForce LExp -- make sure Exp is evaluted
| LLet Name LExp LExp -- name just for pretty printing
| LLam [Name] LExp -- lambda, lifted out before compiling
| LProj LExp Int -- projection
| LCon Int Name [LExp]
| LCase LExp [LAlt]
| LConst Const
| LForeign FLang FType String [(FType, LExp)]
| LOp PrimFn [LExp]
| LNothing
| LError String
deriving Eq
-- Primitive operators. Backends are not *required* to implement all
-- of these, but should report an error if they are unable
data PrimFn = LPlus ArithTy | LMinus ArithTy | LTimes ArithTy
| LUDiv IntTy | LSDiv ArithTy | LURem IntTy | LSRem ArithTy
| LAnd IntTy | LOr IntTy | LXOr IntTy | LCompl IntTy
| LSHL IntTy | LLSHR IntTy | LASHR IntTy
| LEq ArithTy | LLt IntTy | LLe IntTy | LGt IntTy | LGe IntTy
| LSLt ArithTy | LSLe ArithTy | LSGt ArithTy | LSGe ArithTy
| LSExt IntTy IntTy | LZExt IntTy IntTy | LTrunc IntTy IntTy
| LStrConcat | LStrLt | LStrEq | LStrLen
| LIntFloat IntTy | LFloatInt IntTy | LIntStr IntTy | LStrInt IntTy
| LFloatStr | LStrFloat | LChInt IntTy | LIntCh IntTy
| LPrintNum | LPrintStr | LReadStr
| LBitCast ArithTy ArithTy -- Only for values of equal width
| LFExp | LFLog | LFSin | LFCos | LFTan | LFASin | LFACos | LFATan
| LFSqrt | LFFloor | LFCeil
-- construction element extraction element insertion
| LMkVec NativeTy Int | LIdxVec NativeTy Int | LUpdateVec NativeTy Int
| LStrHead | LStrTail | LStrCons | LStrIndex | LStrRev
| LStdIn | LStdOut | LStdErr
| LFork
| LPar -- evaluate argument anywhere, possibly on another
-- core or another machine. 'id' is a valid implementation
| LVMPtr
| LNoOp
deriving (Show, Eq)
-- Supported target languages for foreign calls
data FCallType = FStatic | FObject | FConstructor
deriving (Show, Eq)
data FLang = LANG_C | LANG_JAVA FCallType
deriving (Show, Eq)
data FType = FArith ArithTy
| FFunction
| FFunctionIO
| FString
| FUnit
| FPtr
| FAny
deriving (Show, Eq)
data LAlt = LConCase Int Name [Name] LExp
| LConstCase Const LExp
| LDefaultCase LExp
deriving (Show, Eq)
data LDecl = LFun [LOpt] Name [Name] LExp -- options, name, arg names, def
| LConstructor Name Int Int -- constructor name, tag, arity
deriving (Show, Eq)
type LDefs = Ctxt LDecl
data LOpt = Inline | NoInline
deriving (Show, Eq)
addTags :: Int -> [(Name, LDecl)] -> (Int, [(Name, LDecl)])
addTags i ds = tag i ds []
where tag i ((n, LConstructor n' (-1) a) : as) acc
= tag (i + 1) as ((n, LConstructor n' i a) : acc)
tag i ((n, LConstructor n' t a) : as) acc
= tag i as ((n, LConstructor n' t a) : acc)
tag i (x : as) acc = tag i as (x : acc)
tag i [] acc = (i, reverse acc)
data LiftState = LS Name Int [(Name, LDecl)]
lname (NS n x) i = NS (lname n i) x
lname (UN n) i = MN i n
lname x i = MN i (show x)
liftAll :: [(Name, LDecl)] -> [(Name, LDecl)]
liftAll xs = concatMap (\ (x, d) -> lambdaLift x d) xs
lambdaLift :: Name -> LDecl -> [(Name, LDecl)]
lambdaLift n (LFun _ _ args e)
= let (e', (LS _ _ decls)) = runState (lift args e) (LS n 0 []) in
(n, LFun [] n args e') : decls
lambdaLift n x = [(n, x)]
getNextName :: State LiftState Name
getNextName = do LS n i ds <- get
put (LS n (i + 1) ds)
return (lname n i)
addFn :: Name -> LDecl -> State LiftState ()
addFn fn d = do LS n i ds <- get
put (LS n i ((fn, d) : ds))
lift :: [Name] -> LExp -> State LiftState LExp
lift env (LV v) = return (LV v) -- Lifting happens before these can exist...
lift env (LApp tc (LV (Glob n)) args) = do args' <- mapM (lift env) args
return (LApp tc (LV (Glob n)) args')
lift env (LApp tc f args) = do f' <- lift env f
fn <- getNextName
addFn fn (LFun [Inline] fn env f')
args' <- mapM (lift env) args
return (LApp tc (LV (Glob fn)) (map (LV . Glob) env ++ args'))
lift env (LLazyApp n args) = do args' <- mapM (lift env) args
return (LLazyApp n args')
lift env (LLazyExp (LConst c)) = return (LConst c)
-- lift env (LLazyExp (LApp tc (LV (Glob f)) args))
-- = lift env (LLazyApp f args)
lift env (LLazyExp e) = do e' <- lift env e
let usedArgs = nub $ usedIn env e'
fn <- getNextName
addFn fn (LFun [NoInline] fn usedArgs e')
return (LLazyApp fn (map (LV . Glob) usedArgs))
lift env (LForce e) = do e' <- lift env e
return (LForce e')
lift env (LLet n v e) = do v' <- lift env v
e' <- lift (env ++ [n]) e
return (LLet n v' e')
lift env (LLam args e) = do e' <- lift (env ++ args) e
let usedArgs = nub $ usedIn env e'
fn <- getNextName
addFn fn (LFun [Inline] fn (usedArgs ++ args) e')
return (LApp False (LV (Glob fn)) (map (LV . Glob) usedArgs))
lift env (LProj t i) = do t' <- lift env t
return (LProj t' i)
lift env (LCon i n args) = do args' <- mapM (lift env) args
return (LCon i n args')
lift env (LCase e alts) = do alts' <- mapM liftA alts
e' <- lift env e
return (LCase e' alts')
where
liftA (LConCase i n args e) = do e' <- lift (env ++ args) e
return (LConCase i n args e')
liftA (LConstCase c e) = do e' <- lift env e
return (LConstCase c e')
liftA (LDefaultCase e) = do e' <- lift env e
return (LDefaultCase e')
lift env (LConst c) = return (LConst c)
lift env (LForeign l t s args) = do args' <- mapM (liftF env) args
return (LForeign l t s args')
where
liftF env (t, e) = do e' <- lift env e
return (t, e')
lift env (LOp f args) = do args' <- mapM (lift env) args
return (LOp f args')
lift env (LError str) = return $ LError str
lift env LNothing = return $ LNothing
-- Return variables in list which are used in the expression
usedArg env n | n `elem` env = [n]
| otherwise = []
usedIn :: [Name] -> LExp -> [Name]
usedIn env (LV (Glob n)) = usedArg env n
usedIn env (LApp _ e args) = usedIn env e ++ concatMap (usedIn env) args
usedIn env (LLazyApp n args) = concatMap (usedIn env) args ++ usedArg env n
usedIn env (LLazyExp e) = usedIn env e
usedIn env (LForce e) = usedIn env e
usedIn env (LLet n v e) = usedIn env v ++ usedIn (env \\ [n]) e
usedIn env (LLam ns e) = usedIn (env \\ ns) e
usedIn env (LCon i n args) = concatMap (usedIn env) args
usedIn env (LProj t i) = usedIn env t
usedIn env (LCase e alts) = usedIn env e ++ concatMap (usedInA env) alts
where usedInA env (LConCase i n ns e) = usedIn env e
usedInA env (LConstCase c e) = usedIn env e
usedInA env (LDefaultCase e) = usedIn env e
usedIn env (LForeign _ _ _ args) = concatMap (usedIn env) (map snd args)
usedIn env (LOp f args) = concatMap (usedIn env) args
usedIn env _ = []
instance Show LExp where
show e = show' [] e where
show' env (LV (Loc i)) = env!!i
show' env (LV (Glob n)) = show n
show' env (LLazyApp e args) = show e ++ "|(" ++
showSep ", " (map (show' env) args) ++")"
show' env (LApp _ e args) = show' env e ++ "(" ++
showSep ", " (map (show' env) args) ++")"
show' env (LLazyExp e) = "%lazy(" ++ show' env e ++ ")"
show' env (LForce e) = "%force(" ++ show' env e ++ ")"
show' env (LLet n v e) = "let " ++ show n ++ " = " ++ show' env v ++ " in " ++
show' (env ++ [show n]) e
show' env (LLam args e) = "\\ " ++ showSep "," (map show args) ++ " => " ++
show' (env ++ (map show args)) e
show' env (LProj t i) = show t ++ "!" ++ show i
show' env (LCon i n args) = show n ++ ")" ++ showSep ", " (map (show' env) args) ++ ")"
show' env (LCase e alts) = "case " ++ show' env e ++ " of {\n\t" ++
showSep "\n\t| " (map (showAlt env) alts)
show' env (LConst c) = show c
show' env (LForeign lang ty n args)
= "foreign " ++ n ++ "(" ++ showSep ", " (map (show' env) (map snd args)) ++ ")"
show' env (LOp f args) = show f ++ "(" ++ showSep ", " (map (show' env) args) ++ ")"
show' env (LError str) = "error " ++ show str
show' env LNothing = "____"
showAlt env (LConCase _ n args e)
= show n ++ "(" ++ showSep ", " (map show args) ++ ") => "
++ show' env e
showAlt env (LConstCase c e) = show c ++ " => " ++ show' env e
showAlt env (LDefaultCase e) = "_ => " ++ show' env e
|
christiaanb/Idris-dev
|
src/IRTS/Lang.hs
|
bsd-3-clause
| 9,844 | 0 | 14 | 3,576 | 3,896 | 1,984 | 1,912 | 190 | 4 |
module Sexy.Instances.Functor () where
import Sexy.Instances.Functor.List ()
import Sexy.Instances.Functor.Maybe ()
import Sexy.Instances.Functor.Either ()
import Sexy.Instances.Functor.Function ()
import Sexy.Instances.Functor.IO ()
|
DanBurton/sexy
|
src/Sexy/Instances/Functor.hs
|
bsd-3-clause
| 235 | 0 | 4 | 20 | 60 | 42 | 18 | 6 | 0 |
module MAAM.Instances.MonadStep where
import FP
import MAAM.Classes.MonadStep
-- ID {{{
instance MonadStep ID where
type SS ID = ID
type SSC ID = Universal
mstep :: (SSC ID a, SSC ID b) => (a -> ID b) -> (SS ID a -> SS ID b)
mstep f = f . runID
munit :: (SSC ID a) => P ID -> a -> SS ID a
munit P = ID
-- }}}
-- State {{{
newtype PairWith s a = PairWith { runPairWith :: (a, s) }
deriving (Eq, Ord, PartialOrder, HasBot, JoinLattice)
mapPairWith :: ((a, s) -> (b, s)) -> PairWith s a -> PairWith s b
mapPairWith f = PairWith . f . runPairWith
mapPairWithM :: (Functor m) => ((a, s) -> m (b, s)) -> PairWith s a -> m (PairWith s b)
mapPairWithM f = map PairWith . f . runPairWith
instance Functor (PairWith s) where
map = mapPairWith . mapFst
instance FunctorM (PairWith s) where
mapM = mapPairWithM . mapFstM
instance (MonadStep m, Functor m, HasBot s) => MonadStep (StateT s m) where
type SS (StateT s m) = SS m :.: PairWith s
type SSC (StateT s m) = SSC m ::.:: PairWith s
mstep :: forall a b. (SSC (StateT s m) a, SSC (StateT s m) b) => (a -> StateT s m b) -> (SS (StateT s m) a -> SS (StateT s m) b)
mstep f = mapCompose $
mstep $ \ (runPairWith -> (a, s)) -> PairWith ^$ unStateT (f a) s
munit :: forall a. (SSC (StateT s m) a) => P (StateT s m) -> a -> SS (StateT s m) a
munit P = Compose . munit (P :: P m) . PairWith . (, bot)
-- }}}
-- Flow Insensitive {{{
instance (MonadStep m, Functor m, Functorial JoinLattice m) => MonadStep (ListSetT m) where
type SS (ListSetT m) = SS m :.: Set
type SSC (ListSetT m) = Ord ::*:: (SSC m ::.:: Set)
mstep :: (SSC (ListSetT m) a, SSC (ListSetT m) b) => (a -> ListSetT m b) -> SS (ListSetT m) a -> SS (ListSetT m) b
mstep f = mapCompose $ mstep $ map sset . runListSetT . msum . map f . toList
munit :: (SSC (ListSetT m) a) => P (ListSetT m) -> a -> SS (ListSetT m) a
munit P = Compose . munit (P :: P m) . cunit
instance (MonadStep m, Functorial JoinLattice m) => MonadStep (SetT m) where
type SS (SetT m) = SS m :.: Set
type SSC (SetT m) = Ord ::*:: (SSC m ::.:: Set)
mstep :: (SSC (SetT m) a, SSC (SetT m) b) => (a -> SetT m b) -> SS (SetT m) a -> SS (SetT m) b
mstep f = mapCompose $ mstep $ runSetT . msum . map f . toList
munit :: (SSC (SetT m) a) => P (SetT m) -> a -> SS (SetT m) a
munit P = Compose . munit (P :: P m) . cunit
-- }}}
-- Flow Sensitive, Path Insensitive {{{
newtype ForkLT m a = ForkLT { runForkLT :: ListSetT m a }
deriving (Unit, Functor)
deriving instance (Monad m, Functorial JoinLattice m) => Applicative (ForkLT m)
deriving instance (Bind m, Functorial JoinLattice m) => Bind (ForkLT m)
deriving instance (Monad m, Functorial JoinLattice m) => Product (ForkLT m)
deriving instance (Monad m, Functorial JoinLattice m) => Monad (ForkLT m)
deriving instance (Monad m, Functorial JoinLattice m) => MonadZero (ForkLT m)
deriving instance (Monad m, Functorial JoinLattice m) => MonadPlus (ForkLT m)
deriving instance (Monad m, Functorial JoinLattice m, MonadStateE s m, JoinLattice s) => MonadStateE s (ForkLT m)
deriving instance (Monad m, Functorial JoinLattice m, MonadStateI s m, JoinLattice s) => MonadStateI s (ForkLT m)
deriving instance (Monad m, Functorial JoinLattice m, MonadState s m, JoinLattice s) => MonadState s (ForkLT m)
instance (MonadStep m, Functorial JoinLattice m, CFunctorM (SSC m) (SS m)) => MonadStep (ForkLT m) where
type SS (ForkLT m) = Set :.: SS m
type SSC (ForkLT m) = (Ord ::.:: SS m) ::*:: SSC m ::*:: (SSC m ::.:: ListSet)
mstep :: forall a b. (SSC (ForkLT m) a, SSC (ForkLT m) b) => (a -> ForkLT m b) -> (SS (ForkLT m) a -> SS (ForkLT m) b)
mstep f = mapCompose $ extend $ fromList . runListSet . csequence . mstep (runListSetT . runForkLT . f)
munit :: (SSC (ForkLT m) a) => P (ForkLT m) -> a -> SS (ForkLT m) a
munit P = Compose . ssingleton . munit (P :: P m)
-- }}}
|
davdar/quals
|
src/MAAM/Instances/MonadStep.hs
|
bsd-3-clause
| 3,861 | 0 | 13 | 851 | 1,953 | 1,009 | 944 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Snooze.Balance.Serial (
balanceTableToText
, balanceTableFromText
, balanceTableParser
, balanceEntryParser
) where
import Data.Attoparsec.Text
import Data.String (String)
import Data.Text as T
import Snooze.Balance.Data
import P
balanceTableToText :: BalanceTable -> Text
balanceTableToText =
T.unlines . fmap balanceEntryToText . balanceTableList
balanceEntryToText :: BalanceEntry -> Text
balanceEntryToText (BalanceEntry (Host h) (Port p)) =
T.intercalate " " [h, T.pack $ show p]
balanceTableFromText :: Text -> Either String BalanceTable
balanceTableFromText =
parseOnly balanceTableParser
balanceTableParser :: Parser BalanceTable
balanceTableParser =
BalanceTable <$> balanceEntryParser `sepBy` (char '\n')
balanceEntryParser :: Parser BalanceEntry
balanceEntryParser = do
h <- T.pack <$> manyTill anyChar (char ' ')
p <- many' digit >>= fromMaybeM (fail "Invalid port") . readMaybe
pure $ BalanceEntry (Host h) (Port p)
|
ambiata/snooze
|
src/Snooze/Balance/Serial.hs
|
bsd-3-clause
| 1,091 | 0 | 12 | 208 | 280 | 149 | 131 | 29 | 1 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
module Graphics.Gloss.Internals.Interface.ViewState.Motion
(callback_viewState_motion)
where
import Graphics.Gloss.Data.ViewState
import Graphics.Gloss.Internals.Interface.Callback
import Graphics.Gloss.Internals.Interface.Backend
import Graphics.Gloss.Internals.Interface.Event
import Data.IORef
-- | Callback to handle keyboard and mouse button events
-- for controlling the viewport.
callback_viewState_motion
:: IORef ViewState
-> Callback
callback_viewState_motion portRef
= Motion (viewState_motion portRef)
viewState_motion :: IORef ViewState -> MotionCallback
viewState_motion viewStateRef stateRef pos
= do viewState <- readIORef viewStateRef
ev <- motionEvent stateRef pos
case updateViewStateWithEventMaybe ev viewState of
Nothing -> return ()
Just viewState'
-> do viewStateRef `writeIORef` viewState'
postRedisplay stateRef
|
ardumont/snake
|
deps/gloss/Graphics/Gloss/Internals/Interface/ViewState/Motion.hs
|
bsd-3-clause
| 1,062 | 0 | 12 | 236 | 177 | 97 | 80 | 23 | 2 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Tree.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Tree
-- Copyright : (c) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Multi-way trees (/aka/ rose trees) and forests.
--
-----------------------------------------------------------------------------
module Data.Tree(
Tree(..), Forest,
-- * Two-dimensional drawing
drawTree, drawForest,
-- * Extraction
flatten, levels,
-- * Building trees
unfoldTree, unfoldForest,
unfoldTreeM, unfoldForestM,
unfoldTreeM_BF, unfoldForestM_BF,
) where
import Control.Applicative (Applicative(..), (<$>))
import Data.Foldable (Foldable(foldMap), toList)
import Data.Monoid (Monoid(..))
import Data.Traversable (Traversable(traverse))
import Control.Monad (liftM)
import Data.Sequence (Seq, empty, singleton, (<|), (|>), fromList,
ViewL(..), ViewR(..), viewl, viewr)
import Data.Typeable
import Control.DeepSeq (NFData(rnf))
import Data.Data (Data)
-- | Multi-way trees, also known as /rose trees/.
data Tree a = Node {
rootLabel :: a, -- ^ label value
subForest :: Forest a -- ^ zero or more child trees
}
deriving (Eq, Read, Show, Data)
type Forest a = [Tree a]
deriving instance Typeable Tree
instance Functor Tree where
fmap = fmapTree
fmapTree :: (a -> b) -> Tree a -> Tree b
fmapTree f (Node x ts) = Node (f x) (map (fmapTree f) ts)
instance Applicative Tree where
pure x = Node x []
Node f tfs <*> tx@(Node x txs) =
Node (f x) (map (f <$>) txs ++ map (<*> tx) tfs)
instance Monad Tree where
return x = Node x []
Node x ts >>= f = Node x' (ts' ++ map (>>= f) ts)
where Node x' ts' = f x
instance Traversable Tree where
traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts
instance Foldable Tree where
foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts
instance NFData a => NFData (Tree a) where
rnf (Node x ts) = rnf x `seq` rnf ts
-- | Neat 2-dimensional drawing of a tree.
drawTree :: Tree String -> String
drawTree = unlines . draw
-- | Neat 2-dimensional drawing of a forest.
drawForest :: Forest String -> String
drawForest = unlines . map drawTree
draw :: Tree String -> [String]
draw (Node x ts0) = x : drawSubTrees ts0
where
drawSubTrees [] = []
drawSubTrees [t] =
"|" : shift "`- " " " (draw t)
drawSubTrees (t:ts) =
"|" : shift "+- " "| " (draw t) ++ drawSubTrees ts
shift first other = zipWith (++) (first : repeat other)
-- | The elements of a tree in pre-order.
flatten :: Tree a -> [a]
flatten t = squish t []
where squish (Node x ts) xs = x:Prelude.foldr squish xs ts
-- | Lists of nodes at each level of the tree.
levels :: Tree a -> [[a]]
levels t =
map (map rootLabel) $
takeWhile (not . null) $
iterate (concatMap subForest) [t]
-- | Build a tree from a seed value
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
unfoldTree f b = let (a, bs) = f b in Node a (unfoldForest f bs)
-- | Build a forest from a list of seed values
unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
unfoldForest f = map (unfoldTree f)
-- | Monadic tree builder, in depth-first order
unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM f b = do
(a, bs) <- f b
ts <- unfoldForestM f bs
return (Node a ts)
-- | Monadic forest builder, in depth-first order
unfoldForestM :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM f = Prelude.mapM (unfoldTreeM f)
-- | Monadic tree builder, in breadth-first order,
-- using an algorithm adapted from
-- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
-- by Chris Okasaki, /ICFP'00/.
unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b)
where
getElement xs = case viewl xs of
x :< _ -> x
EmptyL -> error "unfoldTreeM_BF"
-- | Monadic forest builder, in breadth-first order,
-- using an algorithm adapted from
-- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
-- by Chris Okasaki, /ICFP'00/.
unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList
-- takes a sequence (queue) of seeds
-- produces a sequence (reversed queue) of trees of the same length
unfoldForestQ :: Monad m => (b -> m (a, [b])) -> Seq b -> m (Seq (Tree a))
unfoldForestQ f aQ = case viewl aQ of
EmptyL -> return empty
a :< aQ' -> do
(b, as) <- f a
tQ <- unfoldForestQ f (Prelude.foldl (|>) aQ' as)
let (tQ', ts) = splitOnto [] as tQ
return (Node b ts <| tQ')
where
splitOnto :: [a'] -> [b'] -> Seq a' -> (Seq a', [a'])
splitOnto as [] q = (q, as)
splitOnto as (_:bs) q = case viewr q of
q' :> a -> splitOnto (a:as) bs q'
EmptyR -> error "unfoldForestQ"
|
phischu/fragnix
|
benchmarks/containers/Data.Tree.hs
|
bsd-3-clause
| 5,675 | 0 | 14 | 1,617 | 1,796 | 956 | 840 | 97 | 4 |
{-# LINE 1 "GHC.IOArray.hs" #-}
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, RoleAnnotations #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IOArray
-- Copyright : (c) The University of Glasgow 2008
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The IOArray type
--
-----------------------------------------------------------------------------
module GHC.IOArray (
IOArray(..),
newIOArray, unsafeReadIOArray, unsafeWriteIOArray,
readIOArray, writeIOArray,
boundsIOArray
) where
import GHC.Base
import GHC.IO
import GHC.Arr
-- ---------------------------------------------------------------------------
-- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
-- The type arguments are as follows:
--
-- * @i@: the index type of the array (should be an instance of 'Ix')
--
-- * @e@: the element type of the array.
--
--
newtype IOArray i e = IOArray (STArray RealWorld i e)
-- index type should have a nominal role due to Ix class. See also #9220.
type role IOArray nominal representational
-- explicit instance because Haddock can't figure out a derived one
instance Eq (IOArray i e) where
IOArray x == IOArray y = x == y
-- |Build a new 'IOArray'
newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
{-# INLINE newIOArray #-}
newIOArray lu initial = stToIO $ do {marr <- newSTArray lu initial; return (IOArray marr)}
-- | Read a value from an 'IOArray'
unsafeReadIOArray :: IOArray i e -> Int -> IO e
{-# INLINE unsafeReadIOArray #-}
unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
-- | Write a new value into an 'IOArray'
unsafeWriteIOArray :: IOArray i e -> Int -> e -> IO ()
{-# INLINE unsafeWriteIOArray #-}
unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
-- | Read a value from an 'IOArray'
readIOArray :: Ix i => IOArray i e -> i -> IO e
readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
-- | Write a new value into an 'IOArray'
writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
{-# INLINE boundsIOArray #-}
boundsIOArray :: IOArray i e -> (i,i)
boundsIOArray (IOArray marr) = boundsSTArray marr
|
phischu/fragnix
|
builtins/base/GHC.IOArray.hs
|
bsd-3-clause
| 2,476 | 0 | 10 | 453 | 492 | 269 | 223 | 32 | 1 |
module Main where
import Control.Exception
import Test.Tasty
import Test.Tasty.HUnit
import Kite.Test.Exception
import Kite.Test.Lexer
import Kite.Test.TypeCheck
import Kite.Test.Parser
import Kite.Test.Inference
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Kite Tests"
[
-- truthTests
lexerTests
, typeCheckTests
, inferenceTests
, parserTests
]
truthTests = testGroup "Truth"
[
testCase "Pass" $
assertException DivideByZero (evaluate $ 5 `div` 0)
, testCase "Fail" $
assertException DivideByZero (evaluate $ 5 `div` 1)
]
|
kite-lang/kite
|
tests/Main.hs
|
mit
| 643 | 0 | 11 | 161 | 162 | 94 | 68 | 24 | 1 |
{- |
Module : $Header$
Description : resolve empty conjunctions and other trivial cases
Copyright : (c) Christian Maeder, Uni Bremen 2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Resolve empty conjunctions and other trivial cases
-}
module CASL.Simplify where
import CASL.AS_Basic_CASL
import CASL.Fold
import Common.Id
import Common.Utils (nubOrd)
negateFormula :: FORMULA f -> Maybe (FORMULA f)
negateFormula f = case f of
Sort_gen_ax {} -> Nothing
_ -> Just $ negateForm f nullRange
mkJunction :: Ord f => Junctor -> [FORMULA f] -> Range -> FORMULA f
mkJunction j fs ps = let
(isTop, top, join) = case j of
Con -> (is_False_atom, False, conjunctRange)
Dis -> (is_True_atom, True, disjunctRange)
in case nubOrd $ concatMap (\ f -> case f of
Junction j2 ffs _ | j == j2 -> ffs
Negation (Junction j2 ffs _) p | j /= j2 ->
map (`negateForm` p) ffs
Atom b _ | b /= top -> []
_ -> [f]) fs of
flat -> if any (\ f -> isTop f || elem (mkNeg f) flat) flat
then Atom top ps else join flat ps
mkRelation :: Ord f => FORMULA f -> Relation -> FORMULA f -> Range -> FORMULA f
mkRelation f1 c f2 ps =
let nf1 = negateForm f1 ps
tf = Atom True ps
equiv = c == Equivalence
in case f1 of
Atom b _
| b -> f2
| equiv -> negateForm f2 ps
| otherwise -> tf
_ -> case f2 of
Atom b _
| not b -> nf1
| equiv -> f1
| otherwise -> tf
_ | f1 == f2 -> tf
| nf1 == f2 -> if equiv then Atom False ps else f1
_ -> Relation f1 c f2 ps
mkEquation :: Ord f => TERM f -> Equality -> TERM f -> Range -> FORMULA f
mkEquation t1 e t2 ps =
if e == Strong && t1 == t2 then Atom True ps else Equation t1 e t2 ps
simplifyRecord :: Ord f => (f -> f) -> Record f (FORMULA f) (TERM f)
simplifyRecord mf = (mapRecord mf)
{ foldConditional = \ _ t1 f t2 ps -> case f of
Atom b _ -> if b then t1 else t2
_ -> Conditional t1 f t2 ps
, foldQuantification = \ _ q vs qf ps ->
let nf = Quantification q vs qf ps in
case q of
Unique_existential -> nf
_ -> if null vs then qf else case (qf, q) of
(Atom True _, Universal) -> qf
(Atom False _, Existential) -> qf
_ -> nf
, foldJunction = const mkJunction
, foldRelation = const mkRelation
, foldNegation = const negateForm
, foldEquation = const mkEquation
}
simplifyTerm :: Ord f => (f -> f) -> TERM f -> TERM f
simplifyTerm = foldTerm . simplifyRecord
simplifyFormula :: Ord f => (f -> f) -> FORMULA f -> FORMULA f
simplifyFormula = foldFormula . simplifyRecord
|
keithodulaigh/Hets
|
CASL/Simplify.hs
|
gpl-2.0
| 2,829 | 0 | 18 | 885 | 1,038 | 518 | 520 | 64 | 7 |
module Graphics.Renderable where
import Graphics.Rendering.OpenGL
class Renderable a where
render :: a -> IO ()
renderWith :: a -> (Program -> IO ()) -> IO ()
|
sgillis/HaskHull
|
src/Graphics/Renderable.hs
|
gpl-3.0
| 169 | 0 | 12 | 36 | 65 | 34 | 31 | 5 | 0 |
module EvaluatorBase where
import DataBase
-- Operation for expression evaluation
class Exp x => Evaluate x
where
evaluate :: x -> Int
instance Evaluate Lit
where
evaluate (Lit i) = i
instance (Evaluate l, Evaluate r) => Evaluate (Add l r)
where
evaluate (Add l r) = evaluate l + evaluate r
|
egaburov/funstuff
|
Haskell/tytag/xproblem_src/samples/expressions/Haskell/OpenDatatype2/EvaluatorBase.hs
|
apache-2.0
| 308 | 0 | 8 | 69 | 112 | 57 | 55 | 8 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmm ( codeGen ) where
#include "HsVersions.h"
import StgCmmProf (initCostCentres, ldvEnter)
import StgCmmMonad
import StgCmmEnv
import StgCmmBind
import StgCmmCon
import StgCmmLayout
import StgCmmUtils
import StgCmmClosure
import StgCmmHpc
import StgCmmTicky
import Cmm
import CLabel
import StgSyn
import DynFlags
import HscTypes
import CostCentre
import Id
import IdInfo
import Type
import DataCon
import Name
import TyCon
import Module
import Outputable
import Stream
import BasicTypes
import OrdList
import MkGraph
import Data.IORef
import Control.Monad (when,void)
import Util
codeGen :: DynFlags
-> Module
-> [TyCon]
-> CollectedCCs -- (Local/global) cost-centres needing declaring/registering.
-> [StgBinding] -- Bindings to convert
-> HpcInfo
-> Stream IO CmmGroup () -- Output as a stream, so codegen can
-- be interleaved with output
codeGen dflags this_mod data_tycons
cost_centre_info stg_binds hpc_info
= do { -- cg: run the code generator, and yield the resulting CmmGroup
-- Using an IORef to store the state is a bit crude, but otherwise
-- we would need to add a state monad layer.
; cgref <- liftIO $ newIORef =<< initC
; let cg :: FCode () -> Stream IO CmmGroup ()
cg fcode = do
cmm <- liftIO $ do
st <- readIORef cgref
let (a,st') = runC dflags this_mod st (getCmm fcode)
-- NB. stub-out cgs_tops and cgs_stmts. This fixes
-- a big space leak. DO NOT REMOVE!
writeIORef cgref $! st'{ cgs_tops = nilOL,
cgs_stmts = mkNop }
return a
yield cmm
-- Note [codegen-split-init] the cmm_init block must come
-- FIRST. This is because when -split-objs is on we need to
-- combine this block with its initialisation routines; see
-- Note [pipeline-split-init].
; cg (mkModuleInit cost_centre_info this_mod hpc_info)
; mapM_ (cg . cgTopBinding dflags) stg_binds
-- Put datatype_stuff after code_stuff, because the
-- datatype closure table (for enumeration types) to
-- (say) PrelBase_True_closure, which is defined in
-- code_stuff
; let do_tycon tycon = do
-- Generate a table of static closures for an
-- enumeration type Note that the closure pointers are
-- tagged.
when (isEnumerationTyCon tycon) $ cg (cgEnumerationTyCon tycon)
mapM_ (cg . cgDataCon) (tyConDataCons tycon)
; mapM_ do_tycon data_tycons
}
---------------------------------------------------------------
-- Top-level bindings
---------------------------------------------------------------
{- 'cgTopBinding' is only used for top-level bindings, since they need
to be allocated statically (not in the heap) and need to be labelled.
No unboxed bindings can happen at top level.
In the code below, the static bindings are accumulated in the
@MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
This is so that we can write the top level processing in a compositional
style, with the increasing static environment being plumbed as a state
variable. -}
cgTopBinding :: DynFlags -> StgBinding -> FCode ()
cgTopBinding dflags (StgNonRec id rhs)
= do { id' <- maybeExternaliseId dflags id
; let (info, fcode) = cgTopRhs dflags NonRecursive id' rhs
; fcode
; addBindC info -- Add the *un-externalised* Id to the envt,
-- so we find it when we look up occurrences
}
cgTopBinding dflags (StgRec pairs)
= do { let (bndrs, rhss) = unzip pairs
; bndrs' <- Prelude.mapM (maybeExternaliseId dflags) bndrs
; let pairs' = zip bndrs' rhss
r = unzipWith (cgTopRhs dflags Recursive) pairs'
(infos, fcodes) = unzip r
; addBindsC infos
; sequence_ fcodes
}
cgTopRhs :: DynFlags -> RecFlag -> Id -> StgRhs -> (CgIdInfo, FCode ())
-- The Id is passed along for setting up a binding...
-- It's already been externalised if necessary
cgTopRhs dflags _rec bndr (StgRhsCon _cc con args)
= cgTopRhsCon dflags bndr con args
cgTopRhs dflags rec bndr (StgRhsClosure cc bi fvs upd_flag args body)
= ASSERT(null fvs) -- There should be no free variables
cgTopRhsClosure dflags rec bndr cc bi upd_flag args body
---------------------------------------------------------------
-- Module initialisation code
---------------------------------------------------------------
{- The module initialisation code looks like this, roughly:
FN(__stginit_Foo) {
JMP_(__stginit_Foo_1_p)
}
FN(__stginit_Foo_1_p) {
...
}
We have one version of the init code with a module version and the
'way' attached to it. The version number helps to catch cases
where modules are not compiled in dependency order before being
linked: if a module has been compiled since any modules which depend on
it, then the latter modules will refer to a different version in their
init blocks and a link error will ensue.
The 'way' suffix helps to catch cases where modules compiled in different
ways are linked together (eg. profiled and non-profiled).
We provide a plain, unadorned, version of the module init code
which just jumps to the version with the label and way attached. The
reason for this is that when using foreign exports, the caller of
startupHaskell() must supply the name of the init function for the "top"
module in the program, and we don't want to require that this name
has the version and way info appended to it.
We initialise the module tree by keeping a work-stack,
* pointed to by Sp
* that grows downward
* Sp points to the last occupied slot
-}
mkModuleInit
:: CollectedCCs -- cost centre info
-> Module
-> HpcInfo
-> FCode ()
mkModuleInit cost_centre_info this_mod hpc_info
= do { initHpc this_mod hpc_info
; initCostCentres cost_centre_info
-- For backwards compatibility: user code may refer to this
-- label for calling hs_add_root().
; let lbl = mkPlainModuleInitLabel this_mod
; emitDecl (CmmData (Section Data lbl) (Statics lbl []))
}
---------------------------------------------------------------
-- Generating static stuff for algebraic data types
---------------------------------------------------------------
cgEnumerationTyCon :: TyCon -> FCode ()
cgEnumerationTyCon tycon
= do dflags <- getDynFlags
emitRODataLits (mkLocalClosureTableLabel (tyConName tycon) NoCafRefs)
[ CmmLabelOff (mkLocalClosureLabel (dataConName con) NoCafRefs)
(tagForCon dflags con)
| con <- tyConDataCons tycon]
cgDataCon :: DataCon -> FCode ()
-- Generate the entry code, info tables, and (for niladic constructor)
-- the static closure, for a constructor.
cgDataCon data_con
= do { dflags <- getDynFlags
; let
(tot_wds, -- #ptr_wds + #nonptr_wds
ptr_wds, -- #ptr_wds
arg_things) = mkVirtConstrOffsets dflags arg_reps
nonptr_wds = tot_wds - ptr_wds
sta_info_tbl = mkDataConInfoTable dflags data_con True ptr_wds nonptr_wds
dyn_info_tbl = mkDataConInfoTable dflags data_con False ptr_wds nonptr_wds
emit_info info_tbl ticky_code
= emitClosureAndInfoTable info_tbl NativeDirectCall []
$ mk_code ticky_code
mk_code ticky_code
= -- NB: the closure pointer is assumed *untagged* on
-- entry to a constructor. If the pointer is tagged,
-- then we should not be entering it. This assumption
-- is used in ldvEnter and when tagging the pointer to
-- return it.
-- NB 2: We don't set CC when entering data (WDP 94/06)
do { _ <- ticky_code
; ldvEnter (CmmReg nodeReg)
; tickyReturnOldCon (length arg_things)
; void $ emitReturn [cmmOffsetB dflags (CmmReg nodeReg)
(tagForCon dflags data_con)]
}
-- The case continuation code expects a tagged pointer
arg_reps :: [(PrimRep, UnaryType)]
arg_reps = [(typePrimRep rep_ty, rep_ty) | ty <- dataConRepArgTys data_con, rep_ty <- flattenRepType (repType ty)]
-- Dynamic closure code for non-nullary constructors only
; when (not (isNullaryRepDataCon data_con))
(emit_info dyn_info_tbl tickyEnterDynCon)
-- Dynamic-Closure first, to reduce forward references
; emit_info sta_info_tbl tickyEnterStaticCon }
---------------------------------------------------------------
-- Stuff to support splitting
---------------------------------------------------------------
maybeExternaliseId :: DynFlags -> Id -> FCode Id
maybeExternaliseId dflags id
| gopt Opt_SplitObjs dflags, -- See Note [Externalise when splitting]
-- in StgCmmMonad
isInternalName name = do { mod <- getModuleName
; returnFC (setIdName id (externalise mod)) }
| otherwise = returnFC id
where
externalise mod = mkExternalName uniq mod new_occ loc
name = idName id
uniq = nameUnique name
new_occ = mkLocalOcc uniq (nameOccName name)
loc = nameSrcSpan name
-- We want to conjure up a name that can't clash with any
-- existing name. So we generate
-- Mod_$L243foo
-- where 243 is the unique.
|
vikraman/ghc
|
compiler/codeGen/StgCmm.hs
|
bsd-3-clause
| 10,429 | 1 | 21 | 3,092 | 1,462 | 771 | 691 | 132 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module System.TimeManager (
-- ** Types
Manager
, TimeoutAction
, Handle
-- ** Manager
, initialize
, stopManager
, killManager
, withManager
-- ** Registration
, register
, registerKillThread
-- ** Control
, tickle
, cancel
, pause
, resume
-- ** Exceptions
, TimeoutThread (..)
) where
import Control.Concurrent (myThreadId)
import qualified Control.Exception as E
import Control.Reaper
import Data.Typeable (Typeable)
import Data.IORef (IORef)
import qualified Data.IORef as I
----------------------------------------------------------------
-- | A timeout manager
type Manager = Reaper [Handle] Handle
-- | An action to be performed on timeout.
type TimeoutAction = IO ()
-- | A handle used by 'Manager'
data Handle = Handle !(IORef TimeoutAction) !(IORef State)
data State = Active -- Manager turns it to Inactive.
| Inactive -- Manager removes it with timeout action.
| Paused -- Manager does not change it.
| Canceled -- Manager removes it without timeout action.
----------------------------------------------------------------
-- | Creating timeout manager which works every N micro seconds
-- where N is the first argument.
initialize :: Int -> IO Manager
initialize timeout = mkReaper defaultReaperSettings
{ reaperAction = mkListAction prune
, reaperDelay = timeout
}
where
prune m@(Handle actionRef stateRef) = do
state <- I.atomicModifyIORef' stateRef (\x -> (inactivate x, x))
case state of
Inactive -> do
onTimeout <- I.readIORef actionRef
onTimeout `E.catch` ignoreAll
return Nothing
Canceled -> return Nothing
_ -> return $ Just m
inactivate Active = Inactive
inactivate x = x
----------------------------------------------------------------
-- | Stopping timeout manager with onTimeout fired.
stopManager :: Manager -> IO ()
stopManager mgr = E.mask_ (reaperStop mgr >>= mapM_ fire)
where
fire (Handle actionRef _) = do
onTimeout <- I.readIORef actionRef
onTimeout `E.catch` ignoreAll
ignoreAll :: E.SomeException -> IO ()
ignoreAll _ = return ()
-- | Killing timeout manager immediately without firing onTimeout.
killManager :: Manager -> IO ()
killManager = reaperKill
----------------------------------------------------------------
-- | Registering a timeout action.
register :: Manager -> TimeoutAction -> IO Handle
register mgr onTimeout = do
actionRef <- I.newIORef onTimeout
stateRef <- I.newIORef Active
let h = Handle actionRef stateRef
reaperAdd mgr h
return h
-- | Registering a timeout action of killing this thread.
registerKillThread :: Manager -> TimeoutAction -> IO Handle
registerKillThread m onTimeout = do
-- If we hold ThreadId, the stack and data of the thread is leaked.
-- If we hold Weak ThreadId, the stack is released. However, its
-- data is still leaked probably because of a bug of GHC.
-- So, let's just use ThreadId and release ThreadId by
-- overriding the timeout action by "cancel".
tid <- myThreadId
-- First run the timeout action in case the child thread is masked.
register m $ onTimeout `E.finally` E.throwTo tid TimeoutThread
data TimeoutThread = TimeoutThread
deriving Typeable
instance E.Exception TimeoutThread where
toException = E.asyncExceptionToException
fromException = E.asyncExceptionFromException
instance Show TimeoutThread where
show TimeoutThread = "Thread killed by timeout manager"
----------------------------------------------------------------
-- | Setting the state to active.
-- 'Manager' turns active to inactive repeatedly.
tickle :: Handle -> IO ()
tickle (Handle _ stateRef) = I.writeIORef stateRef Active
-- | Setting the state to canceled.
-- 'Manager' eventually removes this without timeout action.
cancel :: Handle -> IO ()
cancel (Handle actionRef stateRef) = do
I.writeIORef actionRef (return ()) -- ensuring to release ThreadId
I.writeIORef stateRef Canceled
-- | Setting the state to paused.
-- 'Manager' does not change the value.
pause :: Handle -> IO ()
pause (Handle _ stateRef) = I.writeIORef stateRef Paused
-- | Setting the paused state to active.
-- This is an alias to 'tickle'.
resume :: Handle -> IO ()
resume = tickle
----------------------------------------------------------------
-- | Call the inner function with a timeout manager.
withManager :: Int -- ^ timeout in microseconds
-> (Manager -> IO a)
-> IO a
withManager timeout f = do
-- FIXME when stopManager is available, use it
man <- initialize timeout
f man
|
kazu-yamamoto/wai
|
time-manager/System/TimeManager.hs
|
mit
| 4,759 | 0 | 16 | 1,039 | 904 | 482 | 422 | 91 | 4 |
module Main where
import Graphics.X11.Turtle
import System.Environment
import Control.Monad
main :: IO ()
main = do
f <- openField
getArgs >>= flip unless (topleft f) . null
t <- newTurtle f
shape t "turtle"
shapesize t 2 2
pensize t 10
pencolor t (0, 127, 0)
onclick f $ \_ x y -> print (x, y) >> goto t x y >> return True
waitField f
putStrLn "end"
|
YoshikuniJujo/wxturtle
|
tests/testOnClick.hs
|
bsd-3-clause
| 363 | 0 | 12 | 80 | 175 | 83 | 92 | 16 | 1 |
-- Copyright 2016 TensorFlow authors.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}
-- | Testing tracing.
module Main where
import Control.Concurrent.MVar (newEmptyMVar, putMVar, tryReadMVar)
import Data.ByteString.Builder (toLazyByteString)
import Data.ByteString.Lazy (isPrefixOf)
import Data.Default (def)
import Lens.Family2 ((&), (.~))
import Test.Framework (defaultMain)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertBool, assertFailure)
import qualified TensorFlow.Core as TF
import qualified TensorFlow.Ops as TF
testTracing :: IO ()
testTracing = do
-- Verifies that tracing happens as a side-effect of graph extension.
loggedValue <- newEmptyMVar
TF.runSessionWithOptions
(def & TF.sessionTracer .~ putMVar loggedValue)
(TF.run_ (TF.scalar (0 :: Float)))
tryReadMVar loggedValue >>=
maybe (assertFailure "Logging never happened") expectedFormat
where expectedFormat x =
let got = toLazyByteString x in
assertBool ("Unexpected log entry " ++ show got)
("Session.extend" `isPrefixOf` got)
main :: IO ()
main = defaultMain
[ testCase "Tracing" testTracing
]
|
judah/tensorflow-haskell
|
tensorflow-ops/tests/TracingTest.hs
|
apache-2.0
| 1,743 | 0 | 12 | 326 | 302 | 177 | 125 | 27 | 1 |
{-# LANGUAGE CPP #-}
module InfoSpec where
import Control.Applicative ((<$>))
import Data.List (isPrefixOf)
import Language.Haskell.GhcMod
import Language.Haskell.GhcMod.Cradle
#if __GLASGOW_HASKELL__ < 706
import System.Environment.Executable (getExecutablePath)
#else
import System.Environment (getExecutablePath)
#endif
import System.Exit
import System.FilePath
import System.Process
import Test.Hspec
import Dir
spec :: Spec
spec = do
describe "typeExpr" $ do
it "shows types of the expression and its outers" $ do
withDirectory_ "test/data/ghc-mod-check" $ do
cradle <- findCradleWithoutSandbox
res <- typeExpr defaultOptions cradle "Data/Foo.hs" "Data.Foo" 9 5
res `shouldBe` "9 5 11 40 \"Int -> a -> a -> a\"\n7 1 11 40 \"Int -> Integer\"\n"
it "works with a module using TemplateHaskell" $ do
withDirectory_ "test/data" $ do
cradle <- findCradleWithoutSandbox
res <- typeExpr defaultOptions cradle "Bar.hs" "Bar" 5 1
res `shouldBe` unlines ["5 1 5 20 \"[Char]\""]
it "works with a module that imports another module using TemplateHaskell" $ do
withDirectory_ "test/data" $ do
cradle <- findCradleWithoutSandbox
res <- typeExpr defaultOptions cradle "Main.hs" "Main" 3 8
res `shouldBe` unlines ["3 8 3 16 \"String -> IO ()\"", "3 8 3 20 \"IO ()\"", "3 1 3 20 \"IO ()\""]
describe "infoExpr" $ do
it "works for non-export functions" $ do
withDirectory_ "test/data" $ do
cradle <- findCradleWithoutSandbox
res <- infoExpr defaultOptions cradle "Info.hs" "Info" "fib"
res `shouldSatisfy` ("fib :: Int -> Int" `isPrefixOf`)
it "works with a module using TemplateHaskell" $ do
withDirectory_ "test/data" $ do
cradle <- findCradleWithoutSandbox
res <- infoExpr defaultOptions cradle "Bar.hs" "Bar" "foo"
res `shouldSatisfy` ("foo :: ExpQ" `isPrefixOf`)
it "works with a module that imports another module using TemplateHaskell" $ do
withDirectory_ "test/data" $ do
cradle <- findCradleWithoutSandbox
res <- infoExpr defaultOptions cradle "Main.hs" "Main" "bar"
res `shouldSatisfy` ("bar :: [Char]" `isPrefixOf`)
it "doesn't fail on unicode output" $ do
dir <- getDistDir
code <- rawSystem (dir </> "build/ghc-mod/ghc-mod") ["info", "test/data/Unicode.hs", "Unicode", "unicode"]
code `shouldSatisfy` (== ExitSuccess)
getDistDir :: IO FilePath
getDistDir = takeDirectory . takeDirectory . takeDirectory <$> getExecutablePath
|
yuga/ghc-mod
|
test/InfoSpec.hs
|
bsd-3-clause
| 2,794 | 0 | 18 | 786 | 559 | 282 | 277 | 52 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
module Opaleye.Internal.Join where
import qualified Opaleye.Internal.Tag as T
import qualified Opaleye.Internal.PackMap as PM
import Opaleye.Internal.Column (Column, Nullable)
import qualified Opaleye.Column as C
import Data.Profunctor (Profunctor, dimap)
import Data.Profunctor.Product (ProductProfunctor, empty, (***!))
import qualified Data.Profunctor.Product.Default as D
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
newtype NullMaker a b = NullMaker (a -> b)
toNullable :: NullMaker a b -> a -> b
toNullable (NullMaker f) = f
extractLeftJoinFields :: Int -> T.Tag -> HPQ.PrimExpr
-> PM.PM [(HPQ.Symbol, HPQ.PrimExpr)] HPQ.PrimExpr
extractLeftJoinFields n = PM.extractAttr ("result" ++ show n ++ "_")
instance D.Default NullMaker (Column a) (Column (Nullable a)) where
def = NullMaker C.unsafeCoerceColumn
instance D.Default NullMaker (Column (Nullable a)) (Column (Nullable a)) where
def = NullMaker C.unsafeCoerceColumn
-- { Boilerplate instances
instance Profunctor NullMaker where
dimap f g (NullMaker h) = NullMaker (dimap f g h)
instance ProductProfunctor NullMaker where
empty = NullMaker empty
NullMaker f ***! NullMaker f' = NullMaker (f ***! f')
--
|
alanz/haskell-opaleye
|
src/Opaleye/Internal/Join.hs
|
bsd-3-clause
| 1,320 | 0 | 11 | 222 | 393 | 221 | 172 | 25 | 1 |
{-| Module describing an NIC.
The NIC data type only holds data about a NIC, but does not provide any
logic.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.HTools.Nic
( Nic(..)
, Mode(..)
, List
, create
) where
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Types as T
-- * Type declarations
data Mode = Bridged | Routed | OpenVSwitch deriving (Show, Eq)
-- | The NIC type.
--
-- It holds the data for a NIC as it is provided via the IAllocator protocol
-- for an instance creation request. All data in those request is optional,
-- that's why all fields are Maybe's.
--
-- TODO: Another name might be more appropriate for this type, as for example
-- RequestedNic. But this type is used as a field in the Instance type, which
-- is not named RequestedInstance, so such a name would be weird. PartialNic
-- already exists in Objects, but doesn't fit the bill here, as it contains
-- a required field (mac). Objects and the types therein are subject to being
-- reworked, so until then this type is left as is.
data Nic = Nic
{ mac :: Maybe String -- ^ MAC address of the NIC
, ip :: Maybe String -- ^ IP address of the NIC
, mode :: Maybe Mode -- ^ the mode the NIC operates in
, link :: Maybe String -- ^ the link of the NIC
, bridge :: Maybe String -- ^ the bridge this NIC is connected to if
-- the mode is Bridged
, network :: Maybe T.NetworkID -- ^ network UUID if this NIC is connected
-- to a network
} deriving (Show, Eq)
-- | A simple name for an instance map.
type List = Container.Container Nic
-- * Initialization
-- | Create a NIC.
--
create :: Maybe String
-> Maybe String
-> Maybe Mode
-> Maybe String
-> Maybe String
-> Maybe T.NetworkID
-> Nic
create mac_init ip_init mode_init link_init bridge_init network_init =
Nic { mac = mac_init
, ip = ip_init
, mode = mode_init
, link = link_init
, bridge = bridge_init
, network = network_init
}
|
vladimir-ipatov/ganeti
|
src/Ganeti/HTools/Nic.hs
|
gpl-2.0
| 2,844 | 0 | 12 | 720 | 290 | 179 | 111 | 31 | 1 |
{-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module T16723 where
import Data.Kind
type D :: forall a. Type
data D
|
sdiehl/ghc
|
testsuite/tests/saks/should_compile/T16723.hs
|
bsd-3-clause
| 178 | 0 | 5 | 28 | 26 | 18 | 8 | -1 | -1 |
module Mod1 where
f1 0 l = take 42 l
f1 n l = take n l
f2 0 l = drop 0 l
f2 n l = drop n l
g = 42
|
kmate/HaRe
|
old/testing/instantiate/Mod1AST.hs
|
bsd-3-clause
| 103 | 0 | 5 | 39 | 69 | 34 | 35 | 6 | 1 |
module PackageTests.Haddock.Check (suite) where
import Control.Monad (unless, when)
import Data.List (isInfixOf)
import System.FilePath ((</>))
import System.Directory (doesDirectoryExist, removeDirectoryRecursive)
import Test.Tasty.HUnit (Assertion, assertFailure)
import Distribution.Simple.Utils (withFileContents)
import PackageTests.PackageTester
(PackageSpec(..), SuiteConfig, assertHaddockSucceeded, cabal_haddock)
this :: String
this = "Haddock"
suite :: SuiteConfig -> Assertion
suite config = do
let dir = "PackageTests" </> this
haddocksDir = dir </> "dist" </> "doc" </> "html" </> "Haddock"
spec = PackageSpec
{ directory = dir
, configOpts = []
, distPref = Nothing
}
haddocksDirExists <- doesDirectoryExist haddocksDir
when haddocksDirExists (removeDirectoryRecursive haddocksDir)
hResult <- cabal_haddock config spec []
assertHaddockSucceeded hResult
let docFiles = map (haddocksDir </>)
["CPP.html", "Literate.html", "NoCPP.html", "Simple.html"]
mapM_ (assertFindInFile "For hiding needles.") docFiles
assertFindInFile :: String -> FilePath -> Assertion
assertFindInFile needle path =
withFileContents path
(\contents ->
unless (needle `isInfixOf` contents)
(assertFailure ("expected: " ++ needle ++ "\n" ++
" in file: " ++ path)))
|
enolan/cabal
|
Cabal/tests/PackageTests/Haddock/Check.hs
|
bsd-3-clause
| 1,497 | 0 | 15 | 392 | 361 | 200 | 161 | 33 | 1 |
{-# LANGUAGE UnboxedTuples #-}
module T9964 where
import GHC.Base
crash :: IO ()
crash = IO (\s ->
let
{-# NOINLINE s' #-}
s' = s
in (# s', () #))
|
urbanslug/ghc
|
testsuite/tests/codeGen/should_compile/T9964.hs
|
bsd-3-clause
| 161 | 0 | 11 | 45 | 55 | 31 | 24 | 9 | 1 |
module Control.Concurrent.STM.TMapSpec ( spec ) where
import Control.Concurrent.STM
import Control.Concurrent.STM.TMap
import Control.Monad
import Prelude hiding (null, lookup)
import Test.Hspec
spec :: Spec
spec = do
describe "newTMap" $
it "creates a new empty TMap" $ do
isEmpty <- atomically $ newTMap >>= null
unless isEmpty $ fail "TMap is not empty."
describe "newTMapIO" $
it "creates a new empty TMap" $ do
isEmpty <- newTMapIO >>= atomically . null
unless isEmpty $ fail "TMap is not empty."
describe "size" $ do
context "when the TMap is empty" $
it "returns 0" $ do
elems <- atomically $ newTMap >>= size
elems `shouldBe` 0
context "when the TMap is not empty" $
it "returns the size" $ do
elems <- atomically $ do
tmap <- newTMap
insert "hello" "world" tmap
insert "goodbye" "world" tmap
size tmap
elems `shouldBe` 2
describe "null" $ do
context "when the TMap is empty" $
it "returns True" $ do
isEmpty <- atomically $ newTMap >>= null
unless isEmpty $ fail "TMap is not empty."
context "when the TMap is not empty" $
it "returns False" $ do
isEmpty <- atomically $ do
tmap <- newTMap
insert 'a' (15 :: Int) tmap
null tmap
when isEmpty $ fail "TMap is empty."
describe "lookup" $ do
context "when the key is not in the TMap" $
it "returns Nothing" $ do
result <- atomically $
(newTMap :: STM (TMap String ())) >>= lookup "key"
result `shouldBe` Nothing
context "when the key is in the TMap" $
it "returns the associated value" $ do
result <- atomically $ do
tmap <- newTMap
insert "test" (15 :: Int) tmap
lookup "test" tmap
result `shouldBe` Just 15
describe "keys" $
it "returns each key in the TMap" $ do
keys' <- atomically $ do
tmap <- newTMap
insert 'a' (1 :: Int) tmap
insert 'b' 2 tmap
insert 'c' 3 tmap
keys tmap
keys' `shouldBe` "abc"
describe "insert" $
it "inserts a value into the TMap" $ do
tmap <- newTMapIO
firstLookup <- atomically $ lookup "15" tmap
atomically $ insert "15" '8' tmap
secondLookup <- atomically $ lookup "15" tmap
firstLookup `shouldBe` Nothing
secondLookup `shouldBe` Just '8'
describe "delete" $ do
context "when the key does not exist in the TMap" $
it "does not modify the TMap" $ do
tmap <- atomically $ do
tmap' <- newTMap
insert "80" 'a' tmap'
insert "alpha" 'x' tmap'
return tmap'
map' <- atomically $ toMap tmap
atomically $ delete "79" tmap
map'' <- atomically $ toMap tmap
map' `shouldBe` map''
context "when the key does exist in the TMap" $
it "does not modify the TMap" $ do
tmap <- atomically $ do
tmap' <- newTMap
insert (10 :: Int) "greetings" tmap'
insert 12 "human" tmap'
return tmap'
result <- atomically $ lookup 10 tmap
atomically $ delete 10 tmap
result' <- atomically $ lookup 10 tmap
result `shouldBe` Just "greetings"
result' `shouldBe` Nothing
describe "fromList" $ do
let input :: [(String, Int)]
input = [ ("alpha", 1)
, ("beta", 2)
]
it "creates a TMap from the given List" $ do
tmap <- atomically $ fromList input
alphaValue <- atomically $ lookup "alpha" tmap
betaValue <- atomically $ lookup "beta" tmap
gammaValue <- atomically $ lookup "gamma" tmap
alphaValue `shouldBe` Just 1
betaValue `shouldBe` Just 2
gammaValue `shouldBe` Nothing
describe "toList" $ do
let expected :: [(Char, Bool)]
expected = [ ('o', False)
, ('y', True)
, ('z', True)
]
it "creates a List from the given TMap" $ do
list <- atomically $ do
tmap <- newTMap
insert 'z' True tmap
insert 'y' True tmap
insert 'o' False tmap
toList tmap
list `shouldBe` expected
|
nahiluhmot/hasqueue
|
spec/Control/Concurrent/STM/TMapSpec.hs
|
mit
| 4,986 | 0 | 20 | 2,177 | 1,256 | 580 | 676 | 120 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.API.Mandrill.Senders where
import Network.API.Mandrill.Response
import Network.API.Mandrill.Types
import Network.API.Mandrill.Utils
-- | Return the senders that have tried to use this account.
list :: (MonadIO m) => MandrillT m (Either ApiError [Sender])
list = performRequest "/senders/list.json" []
-- | Returns the sender domains that have been added to this account.
domains :: (MonadIO m) => MandrillT m (Either ApiError [DomainRecord])
domains = performRequest "/senders/domains.json" []
-- | Adds a sender domain to your account. Sender domains are added
-- automatically as you send, but you can use this call to add them ahead
-- of time.
addDomain :: (MonadIO m) =>
Name ->
MandrillT m (Either ApiError DomainRecord)
addDomain n = performRequest "/senders/add-domain.json" [ "domain" .= n]
-- | Checks the SPF and DKIM settings for a domain. If you haven't already
-- added this domain to your account, it will be added automatically.
checkDomain :: (MonadIO m) =>
Name ->
MandrillT m (Either ApiError DomainRecord)
checkDomain n = performRequest "/senders/check-domain.json" ["domain" .= n]
-- | Sends a verification email in order to verify ownership of a domain.
-- Domain verification is an optional step to confirm ownership of a domain.
-- Once a domain has been verified in a Mandrill account, other accounts may
-- not have their messages signed by that domain unless they also verify the
-- domain. This prevents other Mandrill accounts from sending mail signed by
-- your domain.
verifyDomain :: (MonadIO m) =>
Name ->
Mailbox ->
MandrillT m (Either ApiError DomainState)
verifyDomain n m = performRequest "/senders/verify-domain.json" $
[ "domain" .= n
, "mailbox" .= m ]
-- | Return more detailed information about a single sender, including
-- aggregates of recent stats
info :: (MonadIO m) =>
Email ->
MandrillT m (Either ApiError Stat)
info e = performRequest "/senders/info.json" ["address" .= e]
-- | Return the recent history (hourly stats for the last 30 days) for a sender
timeSeries :: (MonadIO m) =>
Email ->
MandrillT m (Either ApiError [Stat])
timeSeries e = performRequest "/senders/time-series.json" ["address" .= e]
|
krgn/hamdrill
|
src/Network/API/Mandrill/Senders.hs
|
mit
| 2,417 | 0 | 10 | 553 | 403 | 222 | 181 | 32 | 1 |
module Handler.Echo where
import Import
getEchoR :: Text -> Handler Html
getEchoR theText = defaultLayout $(widgetFile "echo")
|
zhy0216/haskell-learning
|
yosog/Handler/Echo.hs
|
mit
| 130 | 0 | 8 | 20 | 39 | 20 | 19 | 4 | 1 |
{-# LANGUAGE RankNTypes, LambdaCase, ScopedTypeVariables #-}
--------------------------------------------------
--------------------------------------------------
module Enumerate.Function.Extra
( module Enumerate.Function.Extra
, module Prelude.Spiros
, module Control.DeepSeq
, module Data.Semigroup
, module Control.Arrow
, module Data.Function
, module Data.List
, module Data.Foldable
, module Data.Data
, module GHC.Generics
) where
--------------------------------------------------
--------------------------------------------------
import "deepseq" Control.DeepSeq (NFData(..), deepseq)
--------------------------------------------------
import "exceptions" Control.Monad.Catch (MonadThrow(..), SomeException(..))
--------------------------------------------------
--------------------------------------------------
import Data.Semigroup (Semigroup)
import System.IO.Unsafe (unsafePerformIO)
import Control.Exception
( Handler(..)
, AsyncException, ArithException, ArrayException, ErrorCall, PatternMatchFail
, catches, throwIO
)
--------------------------------------------------
--------------------------------------------------
import qualified "containers" Data.Set as Set
--------------------------------------------------
--------------------------------------------------
import "base" Control.Arrow ((>>>),(<<<))
import "base" Data.Function ((&))
import "base" Data.List (intercalate)
import "base" Data.Foldable (traverse_)
import "base" Data.Data (Data)
--------------------------------------------------
import qualified "base" Data.List as List
import qualified "base" Data.Ord as Ord
--------------------------------------------------
import "base" GHC.Generics (Generic)
--------------------------------------------------
--------------------------------------------------
import "spiros" Prelude.Spiros
--------------------------------------------------
--------------------------------------------------
{-| @failed = 'throwM' . 'userError'@
-}
failed :: (MonadThrow m) => String -> m a
failed = throwM . userError
--------------------------------------------------
-- | generalize a function that fails with @Nothing@.
maybe2throw :: (a -> Maybe b) -> (forall m. MonadThrow m => a -> m b)
maybe2throw f = f >>> \case
Nothing -> failed "Nothing"
Just x -> return x
--------------------------------------------------
-- | generalize a function that fails with @[]@.
list2throw :: (a -> [b]) -> (forall m. MonadThrow m => a -> m b)
list2throw f = f >>> \case
[] -> failed "[]"
(x:_) -> return x
--------------------------------------------------
-- | generalize a function that fails with @Left@.
either2throw :: (a -> Either SomeException b) -> (forall m. MonadThrow m => a -> m b)
either2throw f = f >>> \case
Left e -> throwM e
Right x -> return x
--------------------------------------------------
{-| specialization -}
throw2maybe :: (forall m. MonadThrow m => a -> m b) -> (a -> Maybe b)
throw2maybe = id
--------------------------------------------------
{-| specialization -}
throw2either :: (forall m. MonadThrow m => a -> m b) -> (a -> Either SomeException b)
throw2either = id
--------------------------------------------------
{-| specialization -}
throw2list :: (forall m. MonadThrow m => a -> m b) -> (a -> [b])
throw2list = id
--------------------------------------------------
--------------------------------------------------
{-| makes an *unsafely*-partial function
(i.e. a function that throws exceptions or
that has inexhaustive pattern matching)
into a *safely*-partial function
(i.e. that explicitly returns in a monad that supports failure).
-}
totalizeFunction :: (NFData b, MonadThrow m) => (a -> b) -> (a -> m b)
totalizeFunction f = g
where g x = spoonWith defaultPartialityHandlers (f x)
--------------------------------------------------
{-| handles the following exceptions:
* 'ArithException'
* 'ArrayException'
* 'ErrorCall'
* 'PatternMatchFail'
* 'SomeException': \[TODO rm]
-}
defaultPartialityHandlers :: (MonadThrow m) => [Handler (m a)]
defaultPartialityHandlers =
[ Handler $ \(e :: AsyncException) -> throwIO e -- TODO I hope they are tried in order
, Handler $ \(e :: ArithException) -> return (throwM e)
, Handler $ \(e :: ArrayException) -> return (throwM e)
, Handler $ \(e :: ErrorCall) -> return (throwM e)
, Handler $ \(e :: PatternMatchFail) -> return (throwM e)
, Handler $ \(e :: SomeException) -> return (throwM e) -- TODO is catchall okay? why is this here?
]
{-# INLINEABLE defaultPartialityHandlers #-}
--------------------------------------------------
{-| Evaluate a value to normal form and 'throwM' any exceptions are thrown
during evaluation. For any error-free value, @spoon = Just@.
(taken from the
<https://hackage.haskell.org/package/spoon-0.3.1/docs/Control-Spoon.html spoon>
package.)
-}
spoonWith :: (NFData a, MonadThrow m) => [Handler (m a)] -> a -> m a
spoonWith handlers a = unsafePerformIO $ do
(a `deepseq` (return `fmap` return a)) `catches` handlers
{-# INLINEABLE spoonWith #-}
--------------------------------------------------
{- | the eliminator as a function and the introducer as a string
helper for declaring Show instances of datatypes without
visible constructors (like @Map@ which is shown as a list).
-}
showsPrecWith :: (Show b) => String -> (a -> b) -> Int -> a -> ShowS
showsPrecWith stringFrom functionInto p x = showParen (p >= 11) $
showString stringFrom . showString " " . shows (functionInto x)
-- showsPrecWith :: (Show a, Show b) => Name -> (a -> b) -> Int -> a -> ShowS
-- showsPrecWith nameFrom functionInto p x = showParen (p > 10) $
-- showString (nameBase nameFrom) . showString " " . shows (functionInto x)
--------------------------------------------------
--------------------------------------------------
{-| The cross-product of two lists.
>>> crossOrderingBoolean = crossProduct [LT,EQ,GT] [False,True]
>>> length crossOrderingBoolean
3
>>> length (Prelude.head crossOrderingBoolean)
2
>>> import Enumerate.Function.Extra (printMappings)
>>> printMappings crossOrderingBoolean
<BLANKLINE>
(LT,False)
(LT,True)
<BLANKLINE>
(EQ,False)
(EQ,True)
<BLANKLINE>
(GT,False)
(GT,True)
(with 'printMappings' defined internally).
The length of the outer list is the size of the first set, and
the length of the inner list is the size of the second set.
-}
crossProduct :: [a] -> [b] -> [[(a,b)]]
crossProduct [] _ = []
crossProduct (aValue:theDomain) theCodomain =
fmap (aValue,) theCodomain : crossProduct theDomain theCodomain
--------------------------------------------------
--------------------------------------------------
-- for doctests:
{-| convert a power set to an isomorphic matrix, sorting the entries.
(for @doctest@)
-}
powerset2matrix :: Set (Set a) -> [[a]]
powerset2matrix = (List.sortBy (Ord.comparing length) . fmap Set.toList . Set.toList)
--------------------------------------------------
{-| (for @doctest@)
-}
printMappings :: (Show a) => [[a]] -> IO ()
printMappings mappings = traverse_ (\mapping -> (putStrLn"") >> (traverse print) mapping) mappings >> return()
--------------------------------------------------
--------------------------------------------------
|
sboosali/enumerate
|
enumerate-function/sources/Enumerate/Function/Extra.hs
|
mit
| 7,283 | 0 | 13 | 1,024 | 1,398 | 798 | 600 | -1 | -1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.ClientNamenodeProtocolProtos.RefreshNodesResponseProto (RefreshNodesResponseProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data RefreshNodesResponseProto = RefreshNodesResponseProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable RefreshNodesResponseProto where
mergeAppend RefreshNodesResponseProto RefreshNodesResponseProto = RefreshNodesResponseProto
instance P'.Default RefreshNodesResponseProto where
defaultValue = RefreshNodesResponseProto
instance P'.Wire RefreshNodesResponseProto where
wireSize ft' self'@(RefreshNodesResponseProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(RefreshNodesResponseProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> RefreshNodesResponseProto) RefreshNodesResponseProto where
getVal m' f' = f' m'
instance P'.GPB RefreshNodesResponseProto
instance P'.ReflectDescriptor RefreshNodesResponseProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.RefreshNodesResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"ClientNamenodeProtocolProtos\"], baseName = MName \"RefreshNodesResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"ClientNamenodeProtocolProtos\",\"RefreshNodesResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType RefreshNodesResponseProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg RefreshNodesResponseProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/ClientNamenodeProtocolProtos/RefreshNodesResponseProto.hs
|
mit
| 2,953 | 1 | 16 | 535 | 554 | 291 | 263 | 53 | 0 |
module System.Mesos.Raw.ResourceUsage where
import System.Mesos.Internal
import System.Mesos.Raw.ExecutorId
import System.Mesos.Raw.FrameworkId
import System.Mesos.Raw.ResourceStatistics
import System.Mesos.Raw.SlaveId
import System.Mesos.Raw.TaskId
type ResourceUsagePtr = Ptr ResourceUsage
foreign import ccall unsafe "ext/types.h toResourceUsage" c_toResourceUsage
:: SlaveIDPtr
-> FrameworkIDPtr
-> ExecutorIDPtr
-> Ptr CChar
-> CInt
-> TaskIDPtr
-> ResourceStatisticsPtr
-> IO ResourceUsagePtr
foreign import ccall unsafe "ext/types.h fromResourceUsage" c_fromResourceUsage
:: ResourceUsagePtr
-> Ptr SlaveIDPtr
-> Ptr FrameworkIDPtr
-> Ptr ExecutorIDPtr
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr TaskIDPtr
-> Ptr ResourceStatisticsPtr
-> IO ()
foreign import ccall unsafe "ext/types.h destroyResourceUsage" c_destroyResourceUsage
:: ResourceUsagePtr
-> IO ()
instance CPPValue ResourceUsage where
marshal (ResourceUsage sid fid eid en tid rs) = do
sidP <- cppValue sid
fidP <- cppValue fid
eidP <- maybe (return nullPtr) cppValue eid
tidP <- maybe (return nullPtr) cppValue tid
rsP <- maybe (return nullPtr) cppValue rs
(enP, enL) <- maybeCString en
liftIO $ c_toResourceUsage sidP fidP eidP enP (fromIntegral enL) tidP rsP
unmarshal up = do
sidPP <- alloc
fidPP <- alloc
eidPP <- alloc
enPP <- alloc
enLP <- alloc
tidPP <- alloc
rsPP <- alloc
poke eidPP nullPtr
poke enPP nullPtr
poke tidPP nullPtr
poke rsPP nullPtr
liftIO $ c_fromResourceUsage up sidPP fidPP eidPP enPP enLP tidPP rsPP
sid <- unmarshal =<< peek sidPP
fid <- unmarshal =<< peek fidPP
eidP <- peek eidPP
eid <- if eidP == nullPtr
then return Nothing
else Just <$> unmarshal eidP
en <- peekMaybeBS enPP enLP
tidP <- peek tidPP
tid <- if tidP == nullPtr
then return Nothing
else Just <$> unmarshal tidP
rsP <- peek rsPP
rs <- if rsP == nullPtr
then return Nothing
else Just <$> unmarshal rsP
return $ ResourceUsage sid fid eid en tid rs
destroy = c_destroyResourceUsage
|
jhedev/hs-mesos
|
src/System/Mesos/Raw/ResourceUsage.hs
|
mit
| 2,241 | 0 | 15 | 584 | 658 | 315 | 343 | 69 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.