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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
--
-- AST for the fragment of AADL we generate.
--
-- (c) 2014 Galois, Inc.
--
module Tower.AADL.AST where
import qualified Ivory.Language.Syntax.Type as I
import qualified Ivory.Tower.AST.Comment as C
----------------------------------------
data System = System
{ systemName :: !Name
, systemComponents :: [Process]
-- ^ For eChronos and seL4, there will be one process per system.
, systemProperties :: [SystemProperty]
} deriving (Show, Eq)
data Process = Process
{ processName :: !Name
, processComponents :: [Thread]
} deriving (Show, Eq)
data SystemProperty =
SystemOS !String
| SystemHW !String
| SystemAddr (Maybe Integer)
deriving (Show, Eq)
data Thread = Thread
{ threadName :: !Name
, threadFeatures :: [Feature]
, threadProperties :: [ThreadProperty]
, threadComments :: [C.Comment]
} deriving (Show, Eq)
data Feature =
InputFeature Input
| OutputFeature Output
| SignalFeature SignalInfo
deriving (Show, Eq, Ord)
-- | Init Channel
-- data InitChan = InitChan
-- { initChanCallback :: [SourcePath]
-- , initChanOutput :: [(Output, Bound)]
-- } deriving (Show, Eq, Ord)
-- | Input channels
data Input = Input
{ inputId :: !ChanId
, inputLabel :: !ChanLabel
, inputType :: !I.Type
, inputCallback :: [SourcePath]
, inputQueue :: Maybe Integer
, inputSendsEvents :: SendsEvents
} deriving (Show, Eq, Ord)
-- | Output channels
data Output = Output
{ outputId :: !ChanId
, outputLabel :: !ChanLabel
, outputType :: !I.Type
, outputEmitter :: FuncSym
} deriving (Show, Eq, Ord)
-- | Path to a .c file and a function symbol in the file. If the funtion symbol
-- is generated (i.e., in external threads), no filepath is given.
type SourcePath = (FilePath, FuncSym)
type SendsEvents = [(ChanLabel, Bound)]
data SourceTexts = SourceTexts [FilePath]
deriving (Show, Eq, Ord)
data ThreadProperty =
DispatchProtocol DispatchProtocol
| ThreadType !ThreadType
| ExecTime (Integer, Integer)
-- ^ Min bound, max bound.
| StackSize Integer
| Priority Int
| EntryPoint [FuncSym]
| SourceText [FilePath]
-- ^ Path to a .c file
| SendEvents SendsEvents
| External
| InitProperty FuncSym
deriving (Show, Eq)
data DispatchProtocol =
Periodic !Integer
| Signal !SignalName !Address
| Aperiodic
| Sporadic
deriving (Show, Eq)
data SignalInfo = SignalInfo
{ signalInfoName :: SignalName
, signalInfoNumber :: SignalNumber
, signalInfoCallback :: [SourcePath]
, signalInfoSendsEvents :: SendsEvents
} deriving (Show, Eq, Ord)
data ThreadType =
Passive
| Active
deriving (Show, Eq)
-- | An AADL variable.
type LocalId = String
-- | An AADL identifier.
type Name = String
-- Unique through the system.
data ChanId =
SynchChanId Integer
| SignalChanId Integer
| PeriodChanId Integer
| InitChanId String
deriving (Show, Read, Eq, Ord)
type ChanLabel = String
-- | Channel bound.
type Bound = Integer
-- | Function symbol.
type FuncSym = String
type SignalName = String
type Address = Integer
type SignalNumber = Int
| GaloisInc/tower | tower-aadl/src/Tower/AADL/AST.hs | bsd-3-clause | 3,161 | 0 | 10 | 710 | 712 | 432 | 280 | 118 | 0 |
{-# LANGUAGE CPP, GADTs #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, (b) the type signatures, and
-- (c) the #if blah_TARGET_ARCH} things, the
-- structure should not be too overwhelming.
module PPC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import CodeGen.Platform
import PPC.Instr
import PPC.Cond
import PPC.Regs
import CPrim
import NCGMonad
import Instruction
import PIC
import Format
import RegClass
import Reg
import TargetReg
import Platform
-- Our intermediate code:
import BlockId
import PprCmm ( pprExpr )
import Cmm
import CmmUtils
import CmmSwitch
import CLabel
import Hoopl
-- The rest:
import OrdList
import Outputable
import Unique
import DynFlags
import Control.Monad ( mapAndUnzipM, when )
import Data.Bits
import Data.Word
import BasicTypes
import FastString
import Util
-- -----------------------------------------------------------------------------
-- Top-level of the instruction selector
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal (pre-order?) yields the insns in the correct
-- order.
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
arch = platformArch $ targetPlatform dflags
case arch of
ArchPPC | os == OSAIX -> return tops
| otherwise -> do
picBaseMb <- getPicBaseMaybeNat
case picBaseMb of
Just picBase -> initializePicBase_ppc arch os picBase tops
Nothing -> return tops
ArchPPC_64 ELF_V1 -> return tops
-- generating function descriptor is handled in
-- pretty printer
ArchPPC_64 ELF_V2 -> return tops
-- generating function prologue is handled in
-- pretty printer
_ -> panic "PPC.cmmTopCodeGen: unknown arch"
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
basicBlockCodeGen
:: Block CmmNode C C
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode format reg src
| target32Bit (targetPlatform dflags) &&
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
| target32Bit (targetPlatform dflags) &&
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"
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Format Reg InstrBlock
| Any Format (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Format -> Register
swizzleRegisterRep (Fixed _ reg code) format = Fixed format reg code
swizzleRegisterRep (Any _ codefn) format = Any format codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> CmmReg -> Reg
getRegisterReg _ (CmmLocal (LocalReg u pk))
= RegVirtual $ mkVirtualReg u (cmmTypeFormat pk)
getRegisterReg platform (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr
mangleIndexTree dflags (CmmRegOff reg off)
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
mangleIndexTree _ _
= panic "PPC.CodeGen.mangleIndexTree: no match"
-- -----------------------------------------------------------------------------
-- Code gen for 64-bit arithmetic on 32-bit platforms
{-
Simple support for generating 64-bit code (ie, 64 bit values and 64
bit assignments) on 32-bit platforms. Unlike the main code generator
we merely shoot for generating working code as simply as possible, and
pay little attention to code quality. Specifically, there is no
attempt to deal cleverly with the fixed-vs-floating register
distinction; all values are generated into (pairs of) floating
registers, even if this would mean some redundant reg-reg moves as a
result. Only one of the VRegUniques is returned, since it will be
of the VRegUniqueLo form, and the upper-half VReg can be determined
by applying getHiVRegFromLo to it.
-}
data ChildCode64 -- a.k.a "Register64"
= ChildCode64
InstrBlock -- code
Reg -- the lower 32-bit temporary which contains the
-- result; use getHiVRegFromLo to find the other
-- VRegUnique. Rules of this simplified insn
-- selection game are therefore that the returned
-- Reg may be modified
-- | Compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock)
getI64Amodes addrTree = do
Amode hi_addr addr_code <- getAmode D addrTree
case addrOffset hi_addr 4 of
Just lo_addr -> return (hi_addr, lo_addr, addr_code)
Nothing -> do (hi_ptr, code) <- getSomeReg addrTree
return (AddrRegImm hi_ptr (ImmInt 0),
AddrRegImm hi_ptr (ImmInt 4),
code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Big-endian store
mov_hi = ST II32 rhi hi_addr
mov_lo = ST II32 rlo lo_addr
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MR r_dst_lo r_src_lo
mov_hi = MR r_dst_hi r_src_hi
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(powerpc): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LD II32 rhi hi_addr
mov_lo = LD II32 rlo lo_addr
return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
half0 = fromIntegral (fromIntegral i :: Word16)
half1 = fromIntegral (fromIntegral (i `shiftR` 16) :: Word16)
half2 = fromIntegral (fromIntegral (i `shiftR` 32) :: Word16)
half3 = fromIntegral (fromIntegral (i `shiftR` 48) :: Word16)
code = toOL [
LIS rlo (ImmInt half1),
OR rlo rlo (RIImm $ ImmInt half0),
LIS rhi (ImmInt half3),
OR rhi rhi (RIImm $ ImmInt half2)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ ADDC rlo r1lo r2lo,
ADDE rhi r1hi r2hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Sub _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ SUBFC rlo r2lo r1lo,
SUBFE rhi r2hi r1hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv W32 W64) [expr]) = do
(expr_reg,expr_code) <- getSomeReg expr
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LI rhi (ImmInt 0)
mov_lo = MR rlo expr_reg
return $ ChildCode64 (expr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 expr
= pprPanic "iselExpr64(powerpc)" (pprExpr expr)
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
getRegister' dflags e
getRegister' :: DynFlags -> CmmExpr -> NatM Register
getRegister' dflags (CmmReg (CmmGlobal PicBaseReg))
| OSAIX <- platformOS (targetPlatform dflags) = do
let code dst = toOL [ LD II32 dst tocAddr ]
tocAddr = AddrRegImm toc (ImmLit (text "ghc_toc_table[TC]"))
return (Any II32 code)
| target32Bit (targetPlatform dflags) = do
reg <- getPicBaseNat $ archWordFormat (target32Bit (targetPlatform dflags))
return (Fixed (archWordFormat (target32Bit (targetPlatform dflags)))
reg nilOL)
| otherwise = return (Fixed II64 toc nilOL)
getRegister' dflags (CmmReg reg)
= return (Fixed (cmmTypeFormat (cmmRegType dflags reg))
(getRegisterReg (targetPlatform dflags) reg) nilOL)
getRegister' dflags tree@(CmmRegOff _ _)
= getRegister' dflags (mangleIndexTree dflags tree)
-- for 32-bit architectuers, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmLoad mem pk)
| not (isWord64 pk) = do
let platform = targetPlatform dflags
Amode addr addr_code <- getAmode D mem
let code dst = ASSERT((targetClassOfReg platform dst == RcDouble) == isFloatType pk)
addr_code `snocOL` LD format dst addr
return (Any format code)
| not (target32Bit (targetPlatform dflags)) = do
Amode addr addr_code <- getAmode DS mem
let code dst = addr_code `snocOL` LD II64 dst addr
return (Any II64 code)
where format = cmmTypeFormat pk
-- catch simple cases of zero- or sign-extended load
getRegister' _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II8 dst addr))
-- Note: there is no Load Byte Arithmetic instruction, so no signed case here
getRegister' _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LD II16 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LA II16 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II16 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LA II16 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II32 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LA II32 dst addr))
getRegister' dflags (CmmMachOp mop [x]) -- unary MachOps
= case mop of
MO_Not rep -> triv_ucode_int rep NOT
MO_F_Neg w -> triv_ucode_float w FNEG
MO_S_Neg w -> triv_ucode_int w NEG
MO_FF_Conv W64 W32 -> trivialUCode FF32 FRSP x
MO_FF_Conv W32 W64 -> conversionNop FF64 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_SS_Conv from to
| from == to -> conversionNop (intFormat to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_SS_Conv W64 to
| arch32 -> panic "PPC.CodeGen.getRegister no 64 bit int register"
| otherwise -> conversionNop (intFormat to) x
MO_SS_Conv W32 to
| arch32 -> conversionNop (intFormat to) x
| otherwise -> case to of
W64 -> triv_ucode_int to (EXTS II32)
W16 -> conversionNop II16 x
W8 -> conversionNop II8 x
_ -> panic "PPC.CodeGen.getRegister: no match"
MO_SS_Conv W16 W8 -> conversionNop II8 x
MO_SS_Conv W8 to -> triv_ucode_int to (EXTS II8)
MO_SS_Conv W16 to -> triv_ucode_int to (EXTS II16)
MO_UU_Conv from to
| from == to -> conversionNop (intFormat to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_UU_Conv W64 to
| arch32 -> panic "PPC.CodeGen.getRegister no 64 bit target"
| otherwise -> conversionNop (intFormat to) x
MO_UU_Conv W32 to
| arch32 -> conversionNop (intFormat to) x
| otherwise ->
case to of
W64 -> trivialCode to False AND x (CmmLit (CmmInt 4294967295 W64))
W16 -> conversionNop II16 x
W8 -> conversionNop II8 x
_ -> panic "PPC.CodeGen.getRegister: no match"
MO_UU_Conv W16 W8 -> conversionNop II8 x
MO_UU_Conv W8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 W32))
MO_UU_Conv W16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 W32))
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_ucode_int width instr = trivialUCode (intFormat width) instr x
triv_ucode_float width instr = trivialUCode (floatFormat width) instr x
conversionNop new_format expr
= do e_code <- getRegister' dflags expr
return (swizzleRegisterRep e_code new_format)
arch32 = target32Bit $ targetPlatform dflags
getRegister' dflags (CmmMachOp mop [x, y]) -- dyadic PrimOps
= case mop of
MO_F_Eq _ -> condFltReg EQQ x y
MO_F_Ne _ -> condFltReg NE x y
MO_F_Gt _ -> condFltReg GTT x y
MO_F_Ge _ -> condFltReg GE x y
MO_F_Lt _ -> condFltReg LTT x y
MO_F_Le _ -> condFltReg LE x y
MO_Eq rep -> condIntReg EQQ (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_Ne rep -> condIntReg NE (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_S_Gt rep -> condIntReg GTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Ge rep -> condIntReg GE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Lt rep -> condIntReg LTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Le rep -> condIntReg LE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Gt rep -> condIntReg GU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Ge rep -> condIntReg GEU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Lt rep -> condIntReg LU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Le rep -> condIntReg LEU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_F_Add w -> triv_float w FADD
MO_F_Sub w -> triv_float w FSUB
MO_F_Mul w -> triv_float w FMUL
MO_F_Quot w -> triv_float w FDIV
-- optimize addition with 32-bit immediate
-- (needed for PIC)
MO_Add W32 ->
case y of
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate W32 True (-imm)
-> trivialCode W32 True ADD x (CmmLit $ CmmInt imm immrep)
CmmLit lit
-> do
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
code dst = srcCode `appOL` toOL [
ADDIS dst src (HA imm),
ADD dst dst (RIImm (LO imm))
]
return (Any II32 code)
_ -> trivialCode W32 True ADD x y
MO_Add rep -> trivialCode rep True ADD x y
MO_Sub rep ->
case y of -- subfi ('substract from' with immediate) doesn't exist
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm)
-> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep)
_ -> trivialCodeNoImm' (intFormat rep) SUBF y x
MO_Mul rep
| arch32 -> trivialCode rep True MULLW x y
| otherwise -> trivialCode rep True MULLD x y
MO_S_MulMayOflo W32 -> trivialCodeNoImm' II32 MULLW_MayOflo x y
MO_S_MulMayOflo W64 -> trivialCodeNoImm' II64 MULLD_MayOflo x y
MO_S_MulMayOflo _ -> panic "S_MulMayOflo: (II8/16) not implemented"
MO_U_MulMayOflo _ -> panic "U_MulMayOflo: not implemented"
MO_S_Quot rep
| arch32 -> trivialCodeNoImm' (intFormat rep) DIVW
(extendSExpr dflags rep x) (extendSExpr dflags rep y)
| otherwise -> trivialCodeNoImm' (intFormat rep) DIVD
(extendSExpr dflags rep x) (extendSExpr dflags rep y)
MO_U_Quot rep
| arch32 -> trivialCodeNoImm' (intFormat rep) DIVWU
(extendUExpr dflags rep x) (extendUExpr dflags rep y)
| otherwise -> trivialCodeNoImm' (intFormat rep) DIVDU
(extendUExpr dflags rep x) (extendUExpr dflags rep y)
MO_S_Rem rep
| arch32 -> remainderCode rep DIVW (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
| otherwise -> remainderCode rep DIVD (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Rem rep
| arch32 -> remainderCode rep DIVWU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
| otherwise -> remainderCode rep DIVDU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_And rep -> trivialCode rep False AND x y
MO_Or rep -> trivialCode rep False OR x y
MO_Xor rep -> trivialCode rep False XOR x y
MO_Shl rep -> shiftCode rep SL x y
MO_S_Shr rep -> shiftCode rep SRA (extendSExpr dflags rep x) y
MO_U_Shr rep -> shiftCode rep SR (extendUExpr dflags rep x) y
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_float :: Width -> (Format -> Reg -> Reg -> Reg -> Instr) -> NatM Register
triv_float width instr = trivialCodeNoImm (floatFormat width) instr x y
arch32 = target32Bit $ targetPlatform dflags
getRegister' _ (CmmLit (CmmInt i rep))
| Just imm <- makeImmediate rep True i
= let
code dst = unitOL (LI dst imm)
in
return (Any (intFormat rep) code)
getRegister' _ (CmmLit (CmmFloat f frep)) = do
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let format = floatFormat frep
code dst =
LDATA (Section ReadOnlyData lbl)
(Statics lbl [CmmStaticLit (CmmFloat f frep)])
`consOL` (addr_code `snocOL` LD format dst addr)
return (Any format code)
getRegister' dflags (CmmLit lit)
| target32Bit (targetPlatform dflags)
= let rep = cmmLitType dflags lit
imm = litToImm lit
code dst = toOL [
LIS dst (HA imm),
ADD dst dst (RIImm (LO imm))
]
in return (Any (cmmTypeFormat rep) code)
| otherwise
= do lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let rep = cmmLitType dflags lit
format = cmmTypeFormat rep
code dst =
LDATA (Section ReadOnlyData lbl) (Statics lbl [CmmStaticLit lit])
`consOL` (addr_code `snocOL` LD format dst addr)
return (Any format code)
getRegister' _ other = pprPanic "getRegister(ppc)" (pprExpr other)
-- extend?Rep: wrap integer expression of type rep
-- in a conversion to II32 or II64 resp.
extendSExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr
extendSExpr dflags W32 x
| target32Bit (targetPlatform dflags) = x
extendSExpr dflags W64 x
| not (target32Bit (targetPlatform dflags)) = x
extendSExpr dflags rep x =
let size = if target32Bit $ targetPlatform dflags
then W32
else W64
in CmmMachOp (MO_SS_Conv rep size) [x]
extendUExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr
extendUExpr dflags W32 x
| target32Bit (targetPlatform dflags) = x
extendUExpr dflags W64 x
| not (target32Bit (targetPlatform dflags)) = x
extendUExpr dflags rep x =
let size = if target32Bit $ targetPlatform dflags
then W32
else W64
in CmmMachOp (MO_UU_Conv rep size) [x]
-- -----------------------------------------------------------------------------
-- The 'Amode' type: Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
data InstrForm = D | DS
getAmode :: InstrForm -> CmmExpr -> NatM Amode
getAmode inf tree@(CmmRegOff _ _)
= do dflags <- getDynFlags
getAmode inf (mangleIndexTree dflags tree)
getAmode _ (CmmMachOp (MO_Sub W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True (-i)
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True i
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode D (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True (-i)
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode D (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True i
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode DS (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True (-i)
= do
(reg, code) <- getSomeReg x
(reg', off', code') <-
if i `mod` 4 == 0
then do return (reg, off, code)
else do
tmp <- getNewRegNat II64
return (tmp, ImmInt 0,
code `snocOL` ADD tmp reg (RIImm off))
return (Amode (AddrRegImm reg' off') code')
getAmode DS (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True i
= do
(reg, code) <- getSomeReg x
(reg', off', code') <-
if i `mod` 4 == 0
then do return (reg, off, code)
else do
tmp <- getNewRegNat II64
return (tmp, ImmInt 0,
code `snocOL` ADD tmp reg (RIImm off))
return (Amode (AddrRegImm reg' off') code')
-- optimize addition with 32-bit immediate
-- (needed for PIC)
getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit lit])
= do
dflags <- getDynFlags
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
case () of
_ | OSAIX <- platformOS (targetPlatform dflags)
, isCmmLabelType lit ->
-- HA16/LO16 relocations on labels not supported on AIX
return (Amode (AddrRegImm src imm) srcCode)
| otherwise -> do
tmp <- getNewRegNat II32
let code = srcCode `snocOL` ADDIS tmp src (HA imm)
return (Amode (AddrRegImm tmp (LO imm)) code)
where
isCmmLabelType (CmmLabel {}) = True
isCmmLabelType (CmmLabelOff {}) = True
isCmmLabelType (CmmLabelDiffOff {}) = True
isCmmLabelType _ = False
getAmode _ (CmmLit lit)
= do
dflags <- getDynFlags
case platformArch $ targetPlatform dflags of
ArchPPC -> do
tmp <- getNewRegNat II32
let imm = litToImm lit
code = unitOL (LIS tmp (HA imm))
return (Amode (AddrRegImm tmp (LO imm)) code)
_ -> do -- TODO: Load from TOC,
-- see getRegister' _ (CmmLit lit)
tmp <- getNewRegNat II64
let imm = litToImm lit
code = toOL [
LIS tmp (HIGHESTA imm),
OR tmp tmp (RIImm (HIGHERA imm)),
SL II64 tmp tmp (RIImm (ImmInt 32)),
ORIS tmp tmp (HA imm)
]
return (Amode (AddrRegImm tmp (LO imm)) code)
getAmode _ (CmmMachOp (MO_Add W32) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmode _ (CmmMachOp (MO_Add W64) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmode _ other
= do
(reg, code) <- getSomeReg other
let
off = ImmInt 0
return (Amode (AddrRegImm reg off) code)
-- The 'CondCode' type: Condition codes passed up the tree.
data CondCode
= CondCode Bool Cond InstrBlock
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- almost the same as everywhere else - but we need to
-- extend small integers to 32 bit or 64 bit first
getCondCode (CmmMachOp mop [x, y])
= do
dflags <- getDynFlags
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq rep -> condIntCode EQQ (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_Ne rep -> condIntCode NE (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_S_Gt rep -> condIntCode GTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Ge rep -> condIntCode GE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Lt rep -> condIntCode LTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Le rep -> condIntCode LE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Gt rep -> condIntCode GU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Ge rep -> condIntCode GEU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Lt rep -> condIntCode LU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Le rep -> condIntCode LEU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
_ -> pprPanic "getCondCode(powerpc)" (pprMachOp mop)
getCondCode _ = panic "getCondCode(2)(powerpc)"
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- ###FIXME: I16 and I8!
-- TODO: Is this still an issue? All arguments are extend?Expr'd.
condIntCode cond x (CmmLit (CmmInt y rep))
| Just src2 <- makeImmediate rep (not $ condUnsigned cond) y
= do
(src1, code) <- getSomeReg x
dflags <- getDynFlags
let format = archWordFormat $ target32Bit $ targetPlatform dflags
code' = code `snocOL`
(if condUnsigned cond then CMPL else CMP) format src1 (RIImm src2)
return (CondCode False cond code')
condIntCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
dflags <- getDynFlags
let format = archWordFormat $ target32Bit $ targetPlatform dflags
code' = code1 `appOL` code2 `snocOL`
(if condUnsigned cond then CMPL else CMP) format src1 (RIReg src2)
return (CondCode False cond code')
condFltCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
code' = code1 `appOL` code2 `snocOL` FCMP src1 src2
code'' = case cond of -- twiddle CR to handle unordered case
GE -> code' `snocOL` CRNOR ltbit eqbit gtbit
LE -> code' `snocOL` CRNOR gtbit eqbit ltbit
_ -> code'
where
ltbit = 0 ; eqbit = 2 ; gtbit = 1
return (CondCode True cond code'')
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_IntCode pk addr src = do
(srcReg, code) <- getSomeReg src
Amode dstAddr addr_code <- case pk of
II64 -> getAmode DS addr
_ -> getAmode D addr
return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src
= do
dflags <- getDynFlags
let dst = getRegisterReg (targetPlatform dflags) reg
r <- getRegister src
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` MR dst freg
-- Easy, isn't it?
assignMem_FltCode = assignMem_IntCode
assignReg_FltCode = assignReg_IntCode
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (unitOL $ JMP lbl)
genJump tree
= do
dflags <- getDynFlags
genJump' tree (platformToGCP (targetPlatform dflags))
genJump' :: CmmExpr -> GenCCallPlatform -> NatM InstrBlock
genJump' tree (GCPLinux64ELF 1)
= do
(target,code) <- getSomeReg tree
return (code
`snocOL` LD II64 r11 (AddrRegImm target (ImmInt 0))
`snocOL` LD II64 toc (AddrRegImm target (ImmInt 8))
`snocOL` MTCTR r11
`snocOL` LD II64 r11 (AddrRegImm target (ImmInt 16))
`snocOL` BCTR [] Nothing)
genJump' tree (GCPLinux64ELF 2)
= do
(target,code) <- getSomeReg tree
return (code
`snocOL` MR r12 target
`snocOL` MTCTR r12
`snocOL` BCTR [] Nothing)
genJump' tree _
= do
(target,code) <- getSomeReg tree
return (code `snocOL` MTCTR target `snocOL` BCTR [] Nothing)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump id bool = do
CondCode _ cond code <- getCondCode bool
return (code `snocOL` BCC cond id)
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
genCCall :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall target dest_regs argsAndHints
= do dflags <- getDynFlags
genCCall' dflags (platformToGCP (targetPlatform dflags))
target dest_regs argsAndHints
-- TODO: replace 'Int' by an enum such as 'PPC_64ABI'
data GenCCallPlatform = GCPLinux | GCPDarwin | GCPLinux64ELF !Int | GCPAIX
deriving Eq
platformToGCP :: Platform -> GenCCallPlatform
platformToGCP platform = case platformOS platform of
OSLinux -> case platformArch platform of
ArchPPC -> GCPLinux
ArchPPC_64 ELF_V1 -> GCPLinux64ELF 1
ArchPPC_64 ELF_V2 -> GCPLinux64ELF 2
_ -> panic "PPC.CodeGen.platformToGCP: Unknown Linux"
OSAIX -> GCPAIX
OSDarwin -> GCPDarwin
_ -> panic "PPC.CodeGen.platformToGCP: not defined for this OS"
genCCall'
:: DynFlags
-> GenCCallPlatform
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
{-
The PowerPC calling convention for Darwin/Mac OS X
is described in Apple's document
"Inside Mac OS X - Mach-O Runtime Architecture".
PowerPC Linux uses the System V Release 4 Calling Convention
for PowerPC. It is described in the
"System V Application Binary Interface PowerPC Processor Supplement".
Both conventions are similar:
Parameters may be passed in general-purpose registers starting at r3, in
floating point registers starting at f1, or on the stack.
But there are substantial differences:
* The number of registers used for parameter passing and the exact set of
nonvolatile registers differs (see MachRegs.hs).
* On Darwin, stack space is always reserved for parameters, even if they are
passed in registers. The called routine may choose to save parameters from
registers to the corresponding space on the stack.
* On Darwin, a corresponding amount of GPRs is skipped when a floating point
parameter is passed in an FPR.
* SysV insists on either passing I64 arguments on the stack, or in two GPRs,
starting with an odd-numbered GPR. It may skip a GPR to achieve this.
Darwin just treats an I64 like two separate II32s (high word first).
* I64 and FF64 arguments are 8-byte aligned on the stack for SysV, but only
4-byte aligned like everything else on Darwin.
* The SysV spec claims that FF32 is represented as FF64 on the stack. GCC on
PowerPC Linux does not agree, so neither do we.
PowerPC 64 Linux uses the System V Release 4 Calling Convention for
64-bit PowerPC. It is specified in
"64-bit PowerPC ELF Application Binary Interface Supplement 1.9".
According to all conventions, the parameter area should be part of the
caller's stack frame, allocated in the caller's prologue code (large enough
to hold the parameter lists for all called routines). The NCG already
uses the stack for register spilling, leaving 64 bytes free at the top.
If we need a larger parameter area than that, we just allocate a new stack
frame just before ccalling.
-}
genCCall' _ _ (PrimTarget MO_WriteBarrier) _ _
= return $ unitOL LWSYNC
genCCall' _ _ (PrimTarget MO_Touch) _ _
= return $ nilOL
genCCall' _ _ (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall' dflags gcp target dest_regs args
= ASSERT(not $ any (`elem` [II16]) $ map cmmTypeFormat argReps)
-- we rely on argument promotion in the codeGen
do
(finalStack,passArgumentsCode,usedRegs) <- passArguments
(zip args argReps)
allArgRegs
(allFPArgRegs platform)
initialStackOffset
(toOL []) []
(labelOrExpr, reduceToFF32) <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do
uses_pic_base_implicitly
return (Left lbl, False)
ForeignTarget expr _ -> do
uses_pic_base_implicitly
return (Right expr, False)
PrimTarget mop -> outOfLineMachOp mop
let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode
`appOL` toc_before
codeAfter = toc_after labelOrExpr `appOL` move_sp_up finalStack
`appOL` moveResult reduceToFF32
case labelOrExpr of
Left lbl -> do -- the linker does all the work for us
return ( codeBefore
`snocOL` BL lbl usedRegs
`appOL` codeAfter)
Right dyn -> do -- implement call through function pointer
(dynReg, dynCode) <- getSomeReg dyn
case gcp of
GCPLinux64ELF 1 -> return ( dynCode
`appOL` codeBefore
`snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 0))
`snocOL` LD II64 toc (AddrRegImm dynReg (ImmInt 8))
`snocOL` MTCTR r11
`snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 16))
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
GCPLinux64ELF 2 -> return ( dynCode
`appOL` codeBefore
`snocOL` MR r12 dynReg
`snocOL` MTCTR r12
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
GCPAIX -> return ( dynCode
-- AIX/XCOFF follows the PowerOPEN ABI
-- which is quite similiar to LinuxPPC64/ELFv1
`appOL` codeBefore
`snocOL` LD II32 r11 (AddrRegImm dynReg (ImmInt 0))
`snocOL` LD II32 toc (AddrRegImm dynReg (ImmInt 4))
`snocOL` MTCTR r11
`snocOL` LD II32 r11 (AddrRegImm dynReg (ImmInt 8))
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
_ -> return ( dynCode
`snocOL` MTCTR dynReg
`appOL` codeBefore
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
where
platform = targetPlatform dflags
uses_pic_base_implicitly = do
-- See Note [implicit register in PPC PIC code]
-- on why we claim to use PIC register here
when (gopt Opt_PIC dflags && target32Bit platform) $ do
_ <- getPicBaseNat $ archWordFormat True
return ()
initialStackOffset = case gcp of
GCPAIX -> 24
GCPDarwin -> 24
GCPLinux -> 8
GCPLinux64ELF 1 -> 48
GCPLinux64ELF 2 -> 32
_ -> panic "genCall': unknown calling convention"
-- size of linkage area + size of arguments, in bytes
stackDelta finalStack = case gcp of
GCPAIX ->
roundTo 16 $ (24 +) $ max 32 $ sum $
map (widthInBytes . typeWidth) argReps
GCPDarwin ->
roundTo 16 $ (24 +) $ max 32 $ sum $
map (widthInBytes . typeWidth) argReps
GCPLinux -> roundTo 16 finalStack
GCPLinux64ELF 1 ->
roundTo 16 $ (48 +) $ max 64 $ sum $
map (widthInBytes . typeWidth) argReps
GCPLinux64ELF 2 ->
roundTo 16 $ (32 +) $ max 64 $ sum $
map (widthInBytes . typeWidth) argReps
_ -> panic "genCall': unknown calling conv."
argReps = map (cmmExprType dflags) args
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
spFormat = if target32Bit platform then II32 else II64
move_sp_down finalStack
| delta > 64 =
toOL [STU spFormat sp (AddrRegImm sp (ImmInt (-delta))),
DELTA (-delta)]
| otherwise = nilOL
where delta = stackDelta finalStack
toc_before = case gcp of
GCPLinux64ELF 1 -> unitOL $ ST spFormat toc (AddrRegImm sp (ImmInt 40))
GCPLinux64ELF 2 -> unitOL $ ST spFormat toc (AddrRegImm sp (ImmInt 24))
GCPAIX -> unitOL $ ST spFormat toc (AddrRegImm sp (ImmInt 20))
_ -> nilOL
toc_after labelOrExpr = case gcp of
GCPLinux64ELF 1 -> case labelOrExpr of
Left _ -> toOL [ NOP ]
Right _ -> toOL [ LD spFormat toc
(AddrRegImm sp
(ImmInt 40))
]
GCPLinux64ELF 2 -> case labelOrExpr of
Left _ -> toOL [ NOP ]
Right _ -> toOL [ LD spFormat toc
(AddrRegImm sp
(ImmInt 24))
]
GCPAIX -> case labelOrExpr of
Left _ -> unitOL NOP
Right _ -> unitOL (LD spFormat toc
(AddrRegImm sp
(ImmInt 20)))
_ -> nilOL
move_sp_up finalStack
| delta > 64 = -- TODO: fix-up stack back-chain
toOL [ADD sp sp (RIImm (ImmInt delta)),
DELTA 0]
| otherwise = nilOL
where delta = stackDelta finalStack
passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed)
passArguments ((arg,arg_ty):args) gprs fprs stackOffset
accumCode accumUsed | isWord64 arg_ty
&& target32Bit (targetPlatform dflags) =
do
ChildCode64 code vr_lo <- iselExpr64 arg
let vr_hi = getHiVRegFromLo vr_lo
case gcp of
GCPAIX -> -- same as for Darwin
do let storeWord vr (gpr:_) _ = MR gpr vr
storeWord vr [] offset
= ST II32 vr (AddrRegImm sp (ImmInt offset))
passArguments args
(drop 2 gprs)
fprs
(stackOffset+8)
(accumCode `appOL` code
`snocOL` storeWord vr_hi gprs stackOffset
`snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
((take 2 gprs) ++ accumUsed)
GCPDarwin ->
do let storeWord vr (gpr:_) _ = MR gpr vr
storeWord vr [] offset
= ST II32 vr (AddrRegImm sp (ImmInt offset))
passArguments args
(drop 2 gprs)
fprs
(stackOffset+8)
(accumCode `appOL` code
`snocOL` storeWord vr_hi gprs stackOffset
`snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
((take 2 gprs) ++ accumUsed)
GCPLinux ->
do let stackOffset' = roundTo 8 stackOffset
stackCode = accumCode `appOL` code
`snocOL` ST II32 vr_hi (AddrRegImm sp (ImmInt stackOffset'))
`snocOL` ST II32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4)))
regCode hireg loreg =
accumCode `appOL` code
`snocOL` MR hireg vr_hi
`snocOL` MR loreg vr_lo
case gprs of
hireg : loreg : regs | even (length gprs) ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_skipped : hireg : loreg : regs ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_ -> -- only one or no regs left
passArguments args [] fprs (stackOffset'+8)
stackCode accumUsed
GCPLinux64ELF _ -> panic "passArguments: 32 bit code"
passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed
| reg : _ <- regs = do
register <- getRegister arg
let code = case register of
Fixed _ freg fcode -> fcode `snocOL` MR reg freg
Any _ acode -> acode reg
stackOffsetRes = case gcp of
-- The Darwin ABI requires that we reserve
-- stack slots for register parameters
GCPDarwin -> stackOffset + stackBytes
-- ... so does the PowerOpen ABI.
GCPAIX -> stackOffset + stackBytes
-- ... the SysV ABI 32-bit doesn't.
GCPLinux -> stackOffset
-- ... but SysV ABI 64-bit does.
GCPLinux64ELF _ -> stackOffset + stackBytes
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
stackOffsetRes
(accumCode `appOL` code)
(reg : accumUsed)
| otherwise = do
(vr, code) <- getSomeReg arg
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
(stackOffset' + stackBytes)
(accumCode `appOL` code `snocOL` ST (cmmTypeFormat rep) vr stackSlot)
accumUsed
where
stackOffset' = case gcp of
GCPDarwin ->
-- stackOffset is at least 4-byte aligned
-- The Darwin ABI is happy with that.
stackOffset
GCPAIX ->
-- The 32bit PowerOPEN ABI is happy with
-- 32bit-alignment as well...
stackOffset
GCPLinux
-- ... the SysV ABI requires 8-byte
-- alignment for doubles.
| isFloatType rep && typeWidth rep == W64 ->
roundTo 8 stackOffset
| otherwise ->
stackOffset
GCPLinux64ELF _ ->
-- everything on the stack is 8-byte
-- aligned on a 64 bit system
-- (except vector status, not used now)
stackOffset
stackSlot = AddrRegImm sp (ImmInt stackOffset')
(nGprs, nFprs, stackBytes, regs)
= case gcp of
GCPAIX ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- The PowerOpen ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
--
-- E.g. for a `double` two GPRs are skipped,
-- whereas for a `float` one GPR is skipped
-- when parameters are assigned to
-- registers.
--
-- The PowerOpen ABI specification can be found at
-- ftp://www.sourceware.org/pub/binutils/ppc-docs/ppc-poweropen/
FF32 -> (1, 1, 4, fprs)
FF64 -> (2, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPDarwin ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- The Darwin ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
FF32 -> (1, 1, 4, fprs)
FF64 -> (2, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPLinux ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- ... the SysV ABI doesn't.
FF32 -> (0, 1, 4, fprs)
FF64 -> (0, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPLinux64ELF _ ->
case cmmTypeFormat rep of
II8 -> (1, 0, 8, gprs)
II16 -> (1, 0, 8, gprs)
II32 -> (1, 0, 8, gprs)
II64 -> (1, 0, 8, gprs)
-- The ELFv1 ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
FF32 -> (1, 1, 8, fprs)
FF64 -> (1, 1, 8, fprs)
FF80 -> panic "genCCall' passArguments FF80"
moveResult reduceToFF32 =
case dest_regs of
[] -> nilOL
[dest]
| reduceToFF32 && isFloat32 rep -> unitOL (FRSP r_dest f1)
| isFloat32 rep || isFloat64 rep -> unitOL (MR r_dest f1)
| isWord64 rep && target32Bit (targetPlatform dflags)
-> toOL [MR (getHiVRegFromLo r_dest) r3,
MR r_dest r4]
| otherwise -> unitOL (MR r_dest r3)
where rep = cmmRegType dflags (CmmLocal dest)
r_dest = getRegisterReg platform (CmmLocal dest)
_ -> panic "genCCall' moveResult: Bad dest_regs"
outOfLineMachOp mop =
do
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference $
mkForeignLabel functionName Nothing ForeignLabelInThisPackage IsFunction
let mopLabelOrExpr = case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return (mopLabelOrExpr, reduce)
where
(functionName, reduce) = case mop of
MO_F32_Exp -> (fsLit "exp", True)
MO_F32_Log -> (fsLit "log", True)
MO_F32_Sqrt -> (fsLit "sqrt", True)
MO_F32_Sin -> (fsLit "sin", True)
MO_F32_Cos -> (fsLit "cos", True)
MO_F32_Tan -> (fsLit "tan", True)
MO_F32_Asin -> (fsLit "asin", True)
MO_F32_Acos -> (fsLit "acos", True)
MO_F32_Atan -> (fsLit "atan", True)
MO_F32_Sinh -> (fsLit "sinh", True)
MO_F32_Cosh -> (fsLit "cosh", True)
MO_F32_Tanh -> (fsLit "tanh", True)
MO_F32_Pwr -> (fsLit "pow", True)
MO_F64_Exp -> (fsLit "exp", False)
MO_F64_Log -> (fsLit "log", False)
MO_F64_Sqrt -> (fsLit "sqrt", False)
MO_F64_Sin -> (fsLit "sin", False)
MO_F64_Cos -> (fsLit "cos", False)
MO_F64_Tan -> (fsLit "tan", False)
MO_F64_Asin -> (fsLit "asin", False)
MO_F64_Acos -> (fsLit "acos", False)
MO_F64_Atan -> (fsLit "atan", False)
MO_F64_Sinh -> (fsLit "sinh", False)
MO_F64_Cosh -> (fsLit "cosh", False)
MO_F64_Tanh -> (fsLit "tanh", False)
MO_F64_Pwr -> (fsLit "pow", False)
MO_UF_Conv w -> (fsLit $ word2FloatLabel w, False)
MO_Memcpy _ -> (fsLit "memcpy", False)
MO_Memset _ -> (fsLit "memset", False)
MO_Memmove _ -> (fsLit "memmove", False)
MO_BSwap w -> (fsLit $ bSwapLabel w, False)
MO_PopCnt w -> (fsLit $ popCntLabel w, False)
MO_Clz w -> (fsLit $ clzLabel w, False)
MO_Ctz w -> (fsLit $ ctzLabel w, False)
MO_AtomicRMW w amop -> (fsLit $ atomicRMWLabel w amop, False)
MO_Cmpxchg w -> (fsLit $ cmpxchgLabel w, False)
MO_AtomicRead w -> (fsLit $ atomicReadLabel w, False)
MO_AtomicWrite w -> (fsLit $ atomicWriteLabel w, False)
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_SubWordC {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| OSAIX <- platformOS (targetPlatform dflags)
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let code = e_code `appOL` t_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
LD fmt tmp (AddrRegReg tableReg tmp),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
| (gopt Opt_PIC dflags) || (not $ target32Bit $ targetPlatform dflags)
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let code = e_code `appOL` t_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
LD fmt tmp (AddrRegReg tableReg tmp),
ADD tmp tmp (RIReg tableReg),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
| otherwise
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
let code = e_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
ADDIS tmp tmp (HA (ImmCLbl lbl)),
LD fmt tmp (AddrRegImm tmp (LO (ImmCLbl lbl))),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (BCTR ids (Just lbl)) =
let jumpTable
| (gopt Opt_PIC dflags)
|| (not $ target32Bit $ targetPlatform dflags)
= map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
where jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
where blockLabel = mkAsmTempLabel (getUnique blockid)
in Just (CmmData (Section ReadOnlyData lbl) (Statics lbl jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condReg :: NatM CondCode -> NatM Register
condReg getCond = do
CondCode _ cond cond_code <- getCond
dflags <- getDynFlags
let
code dst = cond_code
`appOL` negate_code
`appOL` toOL [
MFCR dst,
RLWINM dst dst (bit + 1) 31 31
]
negate_code | do_negate = unitOL (CRNOR bit bit bit)
| otherwise = nilOL
(bit, do_negate) = case cond of
LTT -> (0, False)
LE -> (1, True)
EQQ -> (2, False)
GE -> (0, True)
GTT -> (1, False)
NE -> (2, True)
LU -> (0, False)
LEU -> (1, True)
GEU -> (0, True)
GU -> (1, False)
_ -> panic "PPC.CodeGen.codeReg: no match"
format = archWordFormat $ target32Bit $ targetPlatform dflags
return (Any format code)
condIntReg cond x y = condReg (condIntCode cond x y)
condFltReg cond x y = condReg (condFltCode cond x y)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
Wolfgang's PowerPC version of The Rules:
A slightly modified version of The Rules to take advantage of the fact
that PowerPC instructions work on all registers and don't implicitly
clobber any fixed registers.
* The only expression for which getRegister returns Fixed is (CmmReg reg).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
It may *not* modify global registers, unless the global
register happens to be the destination register.
It may not clobber any other registers. In fact, only ccalls clobber any
fixed registers.
Also, it may not modify the counter register (used by genCCall).
Corollary: If a getRegister for a subexpression returns Fixed, you need
not move it to a fresh temporary before evaluating the next subexpression.
The Fixed register won't be modified.
Therefore, we don't need a counterpart for the x86's getStableReg on PPC.
* SDM's First Rule is valid for PowerPC, too: subexpressions can depend on
the value of the destination register.
-}
trivialCode
:: Width
-> Bool
-> (Reg -> Reg -> RI -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
trivialCode rep signed instr x (CmmLit (CmmInt y _))
| Just imm <- makeImmediate rep signed y
= do
(src1, code1) <- getSomeReg x
let code dst = code1 `snocOL` instr dst src1 (RIImm imm)
return (Any (intFormat rep) code)
trivialCode rep _ instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2)
return (Any (intFormat rep) code)
shiftCode
:: Width
-> (Format-> Reg -> Reg -> RI -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
shiftCode width instr x (CmmLit (CmmInt y _))
| Just imm <- makeImmediate width False y
= do
(src1, code1) <- getSomeReg x
let format = intFormat width
let code dst = code1 `snocOL` instr format dst src1 (RIImm imm)
return (Any format code)
shiftCode width instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let format = intFormat width
let code dst = code1 `appOL` code2 `snocOL` instr format dst src1 (RIReg src2)
return (Any format code)
trivialCodeNoImm' :: Format -> (Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm' format instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2
return (Any format code)
trivialCodeNoImm :: Format -> (Format -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm format instr x y = trivialCodeNoImm' format (instr format) x y
trivialUCode
:: Format
-> (Reg -> Reg -> Instr)
-> CmmExpr
-> NatM Register
trivialUCode rep instr x = do
(src, code) <- getSomeReg x
let code' dst = code `snocOL` instr dst src
return (Any rep code')
-- There is no "remainder" instruction on the PPC, so we have to do
-- it the hard way.
-- The "div" parameter is the division instruction to use (DIVW or DIVWU)
remainderCode :: Width -> (Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
remainderCode rep div x y = do
dflags <- getDynFlags
let mull_instr = if target32Bit $ targetPlatform dflags then MULLW
else MULLD
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `appOL` toOL [
div dst src1 src2,
mull_instr dst dst (RIReg src2),
SUBF dst dst src1
]
return (Any (intFormat rep) code)
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP fromRep toRep x = do
dflags <- getDynFlags
let arch = platformArch $ targetPlatform dflags
coerceInt2FP' arch fromRep toRep x
coerceInt2FP' :: Arch -> Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP' ArchPPC fromRep toRep x = do
(src, code) <- getSomeReg x
lbl <- getNewLabelNat
itmp <- getNewRegNat II32
ftmp <- getNewRegNat FF64
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let
code' dst = code `appOL` maybe_exts `appOL` toOL [
LDATA (Section ReadOnlyData lbl) $ Statics lbl
[CmmStaticLit (CmmInt 0x43300000 W32),
CmmStaticLit (CmmInt 0x80000000 W32)],
XORIS itmp src (ImmInt 0x8000),
ST II32 itmp (spRel dflags 3),
LIS itmp (ImmInt 0x4330),
ST II32 itmp (spRel dflags 2),
LD FF64 ftmp (spRel dflags 2)
] `appOL` addr_code `appOL` toOL [
LD FF64 dst addr,
FSUB FF64 dst ftmp dst
] `appOL` maybe_frsp dst
maybe_exts = case fromRep of
W8 -> unitOL $ EXTS II8 src src
W16 -> unitOL $ EXTS II16 src src
W32 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
maybe_frsp dst
= case toRep of
W32 -> unitOL $ FRSP dst dst
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
return (Any (floatFormat toRep) code')
-- On an ELF v1 Linux we use the compiler doubleword in the stack frame
-- this is the TOC pointer doubleword on ELF v2 Linux. The latter is only
-- set right before a call and restored right after return from the call.
-- So it is fine.
coerceInt2FP' (ArchPPC_64 _) fromRep toRep x = do
(src, code) <- getSomeReg x
dflags <- getDynFlags
let
code' dst = code `appOL` maybe_exts `appOL` toOL [
ST II64 src (spRel dflags 3),
LD FF64 dst (spRel dflags 3),
FCFID dst dst
] `appOL` maybe_frsp dst
maybe_exts = case fromRep of
W8 -> unitOL $ EXTS II8 src src
W16 -> unitOL $ EXTS II16 src src
W32 -> unitOL $ EXTS II32 src src
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
maybe_frsp dst
= case toRep of
W32 -> unitOL $ FRSP dst dst
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
return (Any (floatFormat toRep) code')
coerceInt2FP' _ _ _ _ = panic "PPC.CodeGen.coerceInt2FP: unknown arch"
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int fromRep toRep x = do
dflags <- getDynFlags
let arch = platformArch $ targetPlatform dflags
coerceFP2Int' arch fromRep toRep x
coerceFP2Int' :: Arch -> Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int' ArchPPC _ toRep x = do
dflags <- getDynFlags
-- the reps don't really matter: F*->FF64 and II32->I* are no-ops
(src, code) <- getSomeReg x
tmp <- getNewRegNat FF64
let
code' dst = code `appOL` toOL [
-- convert to int in FP reg
FCTIWZ tmp src,
-- store value (64bit) from FP to stack
ST FF64 tmp (spRel dflags 2),
-- read low word of value (high word is undefined)
LD II32 dst (spRel dflags 3)]
return (Any (intFormat toRep) code')
coerceFP2Int' (ArchPPC_64 _) _ toRep x = do
dflags <- getDynFlags
-- the reps don't really matter: F*->FF64 and II64->I* are no-ops
(src, code) <- getSomeReg x
tmp <- getNewRegNat FF64
let
code' dst = code `appOL` toOL [
-- convert to int in FP reg
FCTIDZ tmp src,
-- store value (64bit) from FP to compiler word on stack
ST FF64 tmp (spRel dflags 3),
LD II64 dst (spRel dflags 3)]
return (Any (intFormat toRep) code')
coerceFP2Int' _ _ _ _ = panic "PPC.CodeGen.coerceFP2Int: unknown arch"
-- Note [.LCTOC1 in PPC PIC code]
-- The .LCTOC1 label is defined to point 32768 bytes into the GOT table
-- to make the most of the PPC's 16-bit displacements.
-- As 16-bit signed offset is used (usually via addi/lwz instructions)
-- first element will have '-32768' offset against .LCTOC1.
-- Note [implicit register in PPC PIC code]
-- PPC generates calls by labels in assembly
-- in form of:
-- bl puts+32768@plt
-- in this form it's not seen directly (by GHC NCG)
-- that r30 (PicBaseReg) is used,
-- but r30 is a required part of PLT code setup:
-- puts+32768@plt:
-- lwz r11,-30484(r30) ; offset in .LCTOC1
-- mtctr r11
-- bctr
| tjakway/ghcjvm | compiler/nativeGen/PPC/CodeGen.hs | bsd-3-clause | 78,416 | 0 | 28 | 28,521 | 19,443 | 9,622 | 9,821 | -1 | -1 |
module QACG.CircGen.Add.SimpleRipple
( simpleRipple
,simpleModRipple
,simpleCtrlRipple
,mkSimpleRipple
,mkSimpleModRipple
,mkSimpleSubtract
,mkSimpleCtrlRipple
,simpleSubtract
,simpleCtrlSub
) where
import QACG.CircUtils.Circuit
import QACG.CircUtils.CircuitState
import Control.Monad.State
import Control.Exception(assert)
import Debug.Trace
import QACG.CircGen.Bit.Toffoli
-- |Generates the addition circuit in <http://arxiv.org/abs/quant-ph/0410184> and returns it as a circuit
mkSimpleRipple :: [String] -> [String] -> String -> Circuit
mkSimpleRipple aLns bLns carry = circ
where (_,(_,_,circ)) = runState go ([], ['c':show x|x<-[0::Int .. 10]] , Circuit (LineInfo [] [] [] []) [] [])
go = do (aOut,bOut) <- simpleRipple aLns bLns carry
_ <- initLines aLns
_ <- initLines bLns
_ <- initLines [carry]
setOutputs $ aOut ++ bOut ++ [carry]
mkSimpleModRipple :: [String] -> [String] -> Circuit
mkSimpleModRipple aLns bLns = circ
where (_,(_,_,circ)) = runState go ([], ['c':show x|x<-[0::Int .. 10]] , Circuit (LineInfo [] [] [] []) [] [])
go = do (aOut,bOut) <- simpleModRipple aLns bLns
_ <- initLines aLns
_ <- initLines bLns
setOutputs $ aOut ++ bOut
mkSimpleSubtract :: [String] -> [String] -> Circuit
mkSimpleSubtract aLns bLns = circ
where (_,(_,_,circ)) = runState go ([], ['c':show x|x<-[0::Int .. 10]] , Circuit (LineInfo [] [] [] []) [] [])
go = do (aOut,bOut) <- simpleSubtract aLns bLns
_ <- initLines aLns
_ <- initLines bLns
setOutputs $ aOut ++ bOut
mkSimpleCtrlRipple :: String -> [String] -> [String] -> String -> Circuit
mkSimpleCtrlRipple ctrl aLns bLns carry = circ
where (_,(_,_,circ)) = runState go ([], ['c':show x|x<-[0::Int .. 10]] , Circuit (LineInfo [] [] [] []) [] [])
go = do (aOut,bOut) <- simpleCtrlRipple ctrl aLns bLns carry
_ <- initLines aLns
_ <- initLines bLns
_ <- initLines [carry]
_ <- initLines [ctrl]
setOutputs $ aOut ++ bOut ++ [carry]
-- |Used to pad inputs that need to be equal length.
-- In the case of these adders the a input is returned and the result is stored in b.
-- This means that padding bits may be freed in the case where they are added to a but not b
padInputs :: [String] -> [String] -> ([String]->[String]->CircuitState a) -> CircuitState (([String],[String]) , a)
padInputs a b f
| length a > length b = do padding <- getConst $ length a - length b
r <- f a (b++padding)
return ((a,b),r)
| length a < length b = do padding <- getConst $ length b - length a
r <- f (a++padding) b
freeConst padding
return ((a,b),r)
| otherwise = do r <- f a b
return ((a,b),r)
maj :: String -> String -> String -> CircuitState ()
maj x y z
= do cnot z y
cnot z x
leftTof x y z
uma :: String -> String -> String -> CircuitState ()
uma x y z
= do rightTof x y z
cnot z x
cnot x y
simpleModRipple :: [String] -> [String] -> CircuitState ([String], [String])
simpleModRipple a b = assert (trace ("rip("++(show.length) a++","++(show.length) b++")") $ length a == length b) $ do
cs <- getConst 1
applyRipple (head cs:a) b
freeConst [head cs]
return (a, b)
where applyRipple (a0:a1:[]) (b0:[])
= do cnot a1 b0
cnot a0 b0
applyRipple (a0:a1:as) (b0:bs)
= do maj a0 b0 a1
applyRipple (a1:as) bs
uma a0 b0 a1
applyRipple _ _ = assert False $ return () --Should never happen!
simpleRipple :: [String] -> [String] -> String -> CircuitState ([String], [String])
simpleRipple a b carry = assert (trace ("rip("++(show.length) a++","++(show.length) b++")") $ length a == length b) $ do
cs <- getConst 1
applyRipple (head cs:a) b carry
freeConst [head cs]
return (a, b ++ [carry])
where applyRipple (a0:[]) [] z = cnot a0 z
applyRipple (a0:a1:as) (b0:bs) z
= do maj a0 b0 a1
applyRipple (a1:as) bs z
uma a0 b0 a1
applyRipple _ _ _ = assert False $ return () --Should never happen!
simpleSubtract :: [String] -> [String] -> CircuitState ([String], [String])
simpleSubtract a b = assert (trace ("sub("++(show.length) a++","++(show.length) b++")") $ length a == length b) $ do
cs <- getConst 2
applyRippleSub (head cs:a) b (cs!!1)
freeConst [head cs]
return (a, b ++ [cs!!1])
where applyRippleSub (a0:[]) [] z = cnot a0 z
applyRippleSub (a0:a1:as) (b0:bs) z
= do uma a0 b0 a1
applyRippleSub (a1:as) bs z
maj a0 b0 a1
applyRippleSub _ _ _ = assert False $ return () --Should never happen!
simpleCtrlRipple :: String -> [String] -> [String] -> String -> CircuitState ([String], [String])
simpleCtrlRipple ctrl a b carry = assert (trace ("RipCon("++(show.length) a++","++(show.length) b++")") $ length a == length b) $ do
cs <- getConst 1
applyRippleC (head cs:a) b carry
freeConst [head cs]
return (a, b++[carry])
where applyRippleC (a0:[]) [] z = cnot a0 z
applyRippleC (a0:a1:as) (b0:bs) z
= do majC a0 b0 a1
applyRippleC (a1:as) bs z
umaC a0 b0 a1
applyRippleC _ _ _ = assert False $ return () --Should never happen!
majC x y z
= do tof ctrl z y
cnot z x
tof x y z
umaC x y z
= do tof x y z
cnot z x
tof ctrl x y
simpleCtrlSub :: String -> [String] -> [String] -> String -> CircuitState ([String], [String])
simpleCtrlSub ctrl a b carry = assert (trace ("RipCon("++(show.length) a++","++(show.length) b++")") $ length a == length b) $ do
cs <- getConst 1
applyRippleC (head cs:a) b carry
freeConst [head cs]
return (a, b )
where applyRippleC (a0:[]) [] z = cnot a0 z
applyRippleC (a0:a1:as) (b0:bs) z
= do umaC a0 b0 a1
applyRippleC (a1:as) bs z
majC a0 b0 a1
applyRippleC _ _ _ = assert False $ return () --Should never happen!
majC x y z
= do tof ctrl z y
cnot z x
tof x y z
umaC x y z
= do tof x y z
cnot z x
tof ctrl x y
| aparent/qacg | src/QACG/CircGen/Add/SimpleRipple.hs | bsd-3-clause | 6,906 | 0 | 18 | 2,400 | 2,914 | 1,453 | 1,461 | 146 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Examples.CodeGeneration.AddSub
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Simple code generation example.
-----------------------------------------------------------------------------
module Data.SBV.Examples.CodeGeneration.AddSub where
import Data.SBV
-- | Simple function that returns add/sum of args
addSub :: SWord8 -> SWord8 -> (SWord8, SWord8)
addSub x y = (x+y, x-y)
-- | Generate C code for addSub. Here's the output showing the generated C code:
--
-- >>> genAddSub
-- == BEGIN: "Makefile" ================
-- # Makefile for addSub. Automatically generated by SBV. Do not edit!
-- <BLANKLINE>
-- # include any user-defined .mk file in the current directory.
-- -include *.mk
-- <BLANKLINE>
-- CC=gcc
-- CCFLAGS?=-Wall -O3 -DNDEBUG -fomit-frame-pointer
-- <BLANKLINE>
-- all: addSub_driver
-- <BLANKLINE>
-- addSub.o: addSub.c addSub.h
-- ${CC} ${CCFLAGS} -c $< -o $@
-- <BLANKLINE>
-- addSub_driver.o: addSub_driver.c
-- ${CC} ${CCFLAGS} -c $< -o $@
-- <BLANKLINE>
-- addSub_driver: addSub.o addSub_driver.o
-- ${CC} ${CCFLAGS} $^ -o $@
-- <BLANKLINE>
-- clean:
-- rm -f *.o
-- <BLANKLINE>
-- veryclean: clean
-- rm -f addSub_driver
-- == END: "Makefile" ==================
-- == BEGIN: "addSub.h" ================
-- /* Header file for addSub. Automatically generated by SBV. Do not edit! */
-- <BLANKLINE>
-- #ifndef __addSub__HEADER_INCLUDED__
-- #define __addSub__HEADER_INCLUDED__
-- <BLANKLINE>
-- #include <inttypes.h>
-- #include <stdint.h>
-- #include <stdbool.h>
-- #include <math.h>
-- <BLANKLINE>
-- /* The boolean type */
-- typedef bool SBool;
-- <BLANKLINE>
-- /* The float type */
-- typedef float SFloat;
-- <BLANKLINE>
-- /* The double type */
-- typedef double SDouble;
-- <BLANKLINE>
-- /* Unsigned bit-vectors */
-- typedef uint8_t SWord8 ;
-- typedef uint16_t SWord16;
-- typedef uint32_t SWord32;
-- typedef uint64_t SWord64;
-- <BLANKLINE>
-- /* Signed bit-vectors */
-- typedef int8_t SInt8 ;
-- typedef int16_t SInt16;
-- typedef int32_t SInt32;
-- typedef int64_t SInt64;
-- <BLANKLINE>
-- /* Entry point prototype: */
-- void addSub(const SWord8 x, const SWord8 y, SWord8 *sum,
-- SWord8 *dif);
-- <BLANKLINE>
-- #endif /* __addSub__HEADER_INCLUDED__ */
-- == END: "addSub.h" ==================
-- == BEGIN: "addSub_driver.c" ================
-- /* Example driver program for addSub. */
-- /* Automatically generated by SBV. Edit as you see fit! */
-- <BLANKLINE>
-- #include <inttypes.h>
-- #include <stdint.h>
-- #include <stdbool.h>
-- #include <math.h>
-- #include <stdio.h>
-- #include "addSub.h"
-- <BLANKLINE>
-- int main(void)
-- {
-- SWord8 sum;
-- SWord8 dif;
-- <BLANKLINE>
-- addSub(132, 241, &sum, &dif);
-- <BLANKLINE>
-- printf("addSub(132, 241, &sum, &dif) ->\n");
-- printf(" sum = %"PRIu8"\n", sum);
-- printf(" dif = %"PRIu8"\n", dif);
-- <BLANKLINE>
-- return 0;
-- }
-- == END: "addSub_driver.c" ==================
-- == BEGIN: "addSub.c" ================
-- /* File: "addSub.c". Automatically generated by SBV. Do not edit! */
-- <BLANKLINE>
-- #include <inttypes.h>
-- #include <stdint.h>
-- #include <stdbool.h>
-- #include <math.h>
-- #include "addSub.h"
-- <BLANKLINE>
-- void addSub(const SWord8 x, const SWord8 y, SWord8 *sum,
-- SWord8 *dif)
-- {
-- const SWord8 s0 = x;
-- const SWord8 s1 = y;
-- const SWord8 s2 = s0 + s1;
-- const SWord8 s3 = s0 - s1;
-- <BLANKLINE>
-- *sum = s2;
-- *dif = s3;
-- }
-- == END: "addSub.c" ==================
--
genAddSub :: IO ()
genAddSub = compileToC outDir "addSub" "" $ do
x <- cgInput "x"
y <- cgInput "y"
-- leave the cgDriverVals call out for generating a driver with random values
cgSetDriverValues [132, 241]
let (s, d) = addSub x y
cgOutput "sum" s
cgOutput "dif" d
where -- use Just "dirName" for putting the output to the named directory
-- otherwise, it'll go to standard output
outDir = Nothing
| Copilot-Language/sbv-for-copilot | Data/SBV/Examples/CodeGeneration/AddSub.hs | bsd-3-clause | 4,142 | 0 | 11 | 762 | 287 | 209 | 78 | 13 | 1 |
{-# LANGUAGE CPP, DeriveDataTypeable,
DeriveGeneric, FlexibleInstances, DefaultSignatures,
RankNTypes, RoleAnnotations, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-inline-rule-shadowing #-}
#if MIN_VERSION_base(4,9,0)
# define HAS_MONADFAIL 1
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Language.Haskell.Syntax
-- Copyright : (c) The University of Glasgow 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Abstract syntax definitions for Template Haskell.
--
-----------------------------------------------------------------------------
module Language.Haskell.TH.Syntax
( module Language.Haskell.TH.Syntax
-- * Language extensions
, module Language.Haskell.TH.LanguageExtensions
) where
import Data.Data hiding (Fixity(..))
import Data.IORef
import System.IO.Unsafe ( unsafePerformIO )
import Control.Monad (liftM)
import System.IO ( hPutStrLn, stderr )
import Data.Char ( isAlpha, isAlphaNum, isUpper )
import Data.Int
import Data.Word
import Data.Ratio
import GHC.Generics ( Generic )
import GHC.Lexeme ( startsVarSym, startsVarId )
import Language.Haskell.TH.LanguageExtensions
import Numeric.Natural
#if HAS_MONADFAIL
import qualified Control.Monad.Fail as Fail
#endif
-----------------------------------------------------
--
-- The Quasi class
--
-----------------------------------------------------
#if HAS_MONADFAIL
class Fail.MonadFail m => Quasi m where
#else
class Monad m => Quasi m where
#endif
qNewName :: String -> m Name
-- ^ Fresh names
-- Error reporting and recovery
qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False)
-- ...but carry on; use 'fail' to stop
qRecover :: m a -- ^ the error handler
-> m a -- ^ action which may fail
-> m a -- ^ Recover from the monadic 'fail'
-- Inspect the type-checker's environment
qLookupName :: Bool -> String -> m (Maybe Name)
-- True <=> type namespace, False <=> value namespace
qReify :: Name -> m Info
qReifyFixity :: Name -> m (Maybe Fixity)
qReifyInstances :: Name -> [Type] -> m [Dec]
-- Is (n tys) an instance?
-- Returns list of matching instance Decs
-- (with empty sub-Decs)
-- Works for classes and type functions
qReifyRoles :: Name -> m [Role]
qReifyAnnotations :: Data a => AnnLookup -> m [a]
qReifyModule :: Module -> m ModuleInfo
qReifyConStrictness :: Name -> m [DecidedStrictness]
qLocation :: m Loc
qRunIO :: IO a -> m a
-- ^ Input/output (dangerous)
qAddDependentFile :: FilePath -> m ()
qAddTopDecls :: [Dec] -> m ()
qAddModFinalizer :: Q () -> m ()
qGetQ :: Typeable a => m (Maybe a)
qPutQ :: Typeable a => a -> m ()
qIsExtEnabled :: Extension -> m Bool
qExtsEnabled :: m [Extension]
-----------------------------------------------------
-- The IO instance of Quasi
--
-- This instance is used only when running a Q
-- computation in the IO monad, usually just to
-- print the result. There is no interesting
-- type environment, so reification isn't going to
-- work.
--
-----------------------------------------------------
instance Quasi IO where
qNewName s = do { n <- readIORef counter
; writeIORef counter (n+1)
; return (mkNameU s n) }
qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
qLookupName _ _ = badIO "lookupName"
qReify _ = badIO "reify"
qReifyFixity _ = badIO "reifyFixity"
qReifyInstances _ _ = badIO "reifyInstances"
qReifyRoles _ = badIO "reifyRoles"
qReifyAnnotations _ = badIO "reifyAnnotations"
qReifyModule _ = badIO "reifyModule"
qReifyConStrictness _ = badIO "reifyConStrictness"
qLocation = badIO "currentLocation"
qRecover _ _ = badIO "recover" -- Maybe we could fix this?
qAddDependentFile _ = badIO "addDependentFile"
qAddTopDecls _ = badIO "addTopDecls"
qAddModFinalizer _ = badIO "addModFinalizer"
qGetQ = badIO "getQ"
qPutQ _ = badIO "putQ"
qIsExtEnabled _ = badIO "isExtEnabled"
qExtsEnabled = badIO "extsEnabled"
qRunIO m = m
badIO :: String -> IO a
badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
; fail "Template Haskell failure" }
-- Global variable to generate unique symbols
counter :: IORef Int
{-# NOINLINE counter #-}
counter = unsafePerformIO (newIORef 0)
-----------------------------------------------------
--
-- The Q monad
--
-----------------------------------------------------
newtype Q a = Q { unQ :: forall m. Quasi m => m a }
-- \"Runs\" the 'Q' monad. Normal users of Template Haskell
-- should not need this function, as the splice brackets @$( ... )@
-- are the usual way of running a 'Q' computation.
--
-- This function is primarily used in GHC internals, and for debugging
-- splices by running them in 'IO'.
--
-- Note that many functions in 'Q', such as 'reify' and other compiler
-- queries, are not supported when running 'Q' in 'IO'; these operations
-- simply fail at runtime. Indeed, the only operations guaranteed to succeed
-- are 'newName', 'runIO', 'reportError' and 'reportWarning'.
runQ :: Quasi m => Q a -> m a
runQ (Q m) = m
instance Monad Q where
Q m >>= k = Q (m >>= \x -> unQ (k x))
(>>) = (*>)
#if !HAS_MONADFAIL
fail s = report True s >> Q (fail "Q monad failure")
#else
fail = Fail.fail
instance Fail.MonadFail Q where
fail s = report True s >> Q (Fail.fail "Q monad failure")
#endif
instance Functor Q where
fmap f (Q x) = Q (fmap f x)
instance Applicative Q where
pure x = Q (pure x)
Q f <*> Q x = Q (f <*> x)
Q m *> Q n = Q (m *> n)
-----------------------------------------------------
--
-- The TExp type
--
-----------------------------------------------------
type role TExp nominal -- See Note [Role of TExp]
newtype TExp a = TExp { unType :: Exp }
unTypeQ :: Q (TExp a) -> Q Exp
unTypeQ m = do { TExp e <- m
; return e }
unsafeTExpCoerce :: Q Exp -> Q (TExp a)
unsafeTExpCoerce m = do { e <- m
; return (TExp e) }
{- Note [Role of TExp]
~~~~~~~~~~~~~~~~~~~~~~
TExp's argument must have a nominal role, not phantom as would
be inferred (Trac #8459). Consider
e :: TExp Age
e = MkAge 3
foo = $(coerce e) + 4::Int
The splice will evaluate to (MkAge 3) and you can't add that to
4::Int. So you can't coerce a (TExp Age) to a (TExp Int). -}
----------------------------------------------------
-- Packaged versions for the programmer, hiding the Quasi-ness
{- |
Generate a fresh name, which cannot be captured.
For example, this:
@f = $(do
nm1 <- newName \"x\"
let nm2 = 'mkName' \"x\"
return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1)))
)@
will produce the splice
>f = \x0 -> \x -> x0
In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@,
and is not captured by the binding @VarP nm2@.
Although names generated by @newName@ cannot /be captured/, they can
/capture/ other names. For example, this:
>g = $(do
> nm1 <- newName "x"
> let nm2 = mkName "x"
> return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))
> )
will produce the splice
>g = \x -> \x0 -> x0
since the occurrence @VarE nm2@ is captured by the innermost binding
of @x@, namely @VarP nm1@.
-}
newName :: String -> Q Name
newName s = Q (qNewName s)
-- | Report an error (True) or warning (False),
-- but carry on; use 'fail' to stop.
report :: Bool -> String -> Q ()
report b s = Q (qReport b s)
{-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6
-- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'.
reportError :: String -> Q ()
reportError = report True
-- | Report a warning to the user, and carry on.
reportWarning :: String -> Q ()
reportWarning = report False
-- | Recover from errors raised by 'reportError' or 'fail'.
recover :: Q a -- ^ handler to invoke on failure
-> Q a -- ^ computation to run
-> Q a
recover (Q r) (Q m) = Q (qRecover r m)
-- We don't export lookupName; the Bool isn't a great API
-- Instead we export lookupTypeName, lookupValueName
lookupName :: Bool -> String -> Q (Maybe Name)
lookupName ns s = Q (qLookupName ns s)
-- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupTypeName :: String -> Q (Maybe Name)
lookupTypeName s = Q (qLookupName True s)
-- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupValueName :: String -> Q (Maybe Name)
lookupValueName s = Q (qLookupName False s)
{-
Note [Name lookup]
~~~~~~~~~~~~~~~~~~
-}
{- $namelookup #namelookup#
The functions 'lookupTypeName' and 'lookupValueName' provide
a way to query the current splice's context for what names
are in scope. The function 'lookupTypeName' queries the type
namespace, whereas 'lookupValueName' queries the value namespace,
but the functions are otherwise identical.
A call @lookupValueName s@ will check if there is a value
with name @s@ in scope at the current splice's location. If
there is, the @Name@ of this value is returned;
if not, then @Nothing@ is returned.
The returned name cannot be \"captured\".
For example:
> f = "global"
> g = $( do
> Just nm <- lookupValueName "f"
> [| let f = "local" in $( varE nm ) |]
In this case, @g = \"global\"@; the call to @lookupValueName@
returned the global @f@, and this name was /not/ captured by
the local definition of @f@.
The lookup is performed in the context of the /top-level/ splice
being run. For example:
> f = "global"
> g = $( [| let f = "local" in
> $(do
> Just nm <- lookupValueName "f"
> varE nm
> ) |] )
Again in this example, @g = \"global\"@, because the call to
@lookupValueName@ queries the context of the outer-most @$(...)@.
Operators should be queried without any surrounding parentheses, like so:
> lookupValueName "+"
Qualified names are also supported, like so:
> lookupValueName "Prelude.+"
> lookupValueName "Prelude.map"
-}
{- | 'reify' looks up information about the 'Name'.
It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName'
to ensure that we are reifying from the right namespace. For instance, in this context:
> data D = D
which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.)
To ensure we get information about @D@-the-value, use 'lookupValueName':
> do
> Just nm <- lookupValueName "D"
> reify nm
and to get information about @D@-the-type, use 'lookupTypeName'.
-}
reify :: Name -> Q Info
reify v = Q (qReify v)
{- | @reifyFixity nm@ attempts to find a fixity declaration for @nm@. For
example, if the function @foo@ has the fixity declaration @infixr 7 foo@, then
@reifyFixity 'foo@ would return @'Just' ('Fixity' 7 'InfixR')@. If the function
@bar@ does not have a fixity declaration, then @reifyFixity 'bar@ returns
'Nothing', so you may assume @bar@ has 'defaultFixity'.
-}
reifyFixity :: Name -> Q (Maybe Fixity)
reifyFixity nm = Q (qReifyFixity nm)
{- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is,
if @nm@ is the name of a type class, then all instances of this class at the types @tys@
are returned. Alternatively, if @nm@ is the name of a data family or type family,
all instances of this family at the types @tys@ are returned.
-}
reifyInstances :: Name -> [Type] -> Q [InstanceDec]
reifyInstances cls tys = Q (qReifyInstances cls tys)
{- | @reifyRoles nm@ returns the list of roles associated with the parameters of
the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon.
The returned list should never contain 'InferR'.
-}
reifyRoles :: Name -> Q [Role]
reifyRoles nm = Q (qReifyRoles nm)
-- | @reifyAnnotations target@ returns the list of annotations
-- associated with @target@. Only the annotations that are
-- appropriately typed is returned. So if you have @Int@ and @String@
-- annotations for the same target, you have to call this function twice.
reifyAnnotations :: Data a => AnnLookup -> Q [a]
reifyAnnotations an = Q (qReifyAnnotations an)
-- | @reifyModule mod@ looks up information about module @mod@. To
-- look up the current module, call this function with the return
-- value of @thisModule@.
reifyModule :: Module -> Q ModuleInfo
reifyModule m = Q (qReifyModule m)
-- | @reifyConStrictness nm@ looks up the strictness information for the fields
-- of the constructor with the name @nm@. Note that the strictness information
-- that 'reifyConStrictness' returns may not correspond to what is written in
-- the source code. For example, in the following data declaration:
--
-- @
-- data Pair a = Pair a a
-- @
--
-- 'reifyConStrictness' would return @['DecidedLazy', DecidedLazy]@ under most
-- circumstances, but it would return @['DecidedStrict', DecidedStrict]@ if the
-- @-XStrictData@ language extension was enabled.
reifyConStrictness :: Name -> Q [DecidedStrictness]
reifyConStrictness n = Q (qReifyConStrictness n)
-- | Is the list of instances returned by 'reifyInstances' nonempty?
isInstance :: Name -> [Type] -> Q Bool
isInstance nm tys = do { decs <- reifyInstances nm tys
; return (not (null decs)) }
-- | The location at which this computation is spliced.
location :: Q Loc
location = Q qLocation
-- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
-- Take care: you are guaranteed the ordering of calls to 'runIO' within
-- a single 'Q' computation, but not about the order in which splices are run.
--
-- Note: for various murky reasons, stdout and stderr handles are not
-- necessarily flushed when the compiler finishes running, so you should
-- flush them yourself.
runIO :: IO a -> Q a
runIO m = Q (qRunIO m)
-- | Record external files that runIO is using (dependent upon).
-- The compiler can then recognize that it should re-compile the Haskell file
-- when an external file changes.
--
-- Expects an absolute file path.
--
-- Notes:
--
-- * ghc -M does not know about these dependencies - it does not execute TH.
--
-- * The dependency is based on file content, not a modification time
addDependentFile :: FilePath -> Q ()
addDependentFile fp = Q (qAddDependentFile fp)
-- | Add additional top-level declarations. The added declarations will be type
-- checked along with the current declaration group.
addTopDecls :: [Dec] -> Q ()
addTopDecls ds = Q (qAddTopDecls ds)
-- | Add a finalizer that will run in the Q monad after the current module has
-- been type checked. This only makes sense when run within a top-level splice.
addModFinalizer :: Q () -> Q ()
addModFinalizer act = Q (qAddModFinalizer (unQ act))
-- | Get state from the 'Q' monad.
getQ :: Typeable a => Q (Maybe a)
getQ = Q qGetQ
-- | Replace the state in the 'Q' monad.
putQ :: Typeable a => a -> Q ()
putQ x = Q (qPutQ x)
-- | Determine whether the given language extension is enabled in the 'Q' monad.
isExtEnabled :: Extension -> Q Bool
isExtEnabled ext = Q (qIsExtEnabled ext)
-- | List all enabled language extensions.
extsEnabled :: Q [Extension]
extsEnabled = Q qExtsEnabled
instance Quasi Q where
qNewName = newName
qReport = report
qRecover = recover
qReify = reify
qReifyFixity = reifyFixity
qReifyInstances = reifyInstances
qReifyRoles = reifyRoles
qReifyAnnotations = reifyAnnotations
qReifyModule = reifyModule
qReifyConStrictness = reifyConStrictness
qLookupName = lookupName
qLocation = location
qRunIO = runIO
qAddDependentFile = addDependentFile
qAddTopDecls = addTopDecls
qAddModFinalizer = addModFinalizer
qGetQ = getQ
qPutQ = putQ
qIsExtEnabled = isExtEnabled
qExtsEnabled = extsEnabled
----------------------------------------------------
-- The following operations are used solely in DsMeta when desugaring brackets
-- They are not necessary for the user, who can use ordinary return and (>>=) etc
returnQ :: a -> Q a
returnQ = return
bindQ :: Q a -> (a -> Q b) -> Q b
bindQ = (>>=)
sequenceQ :: [Q a] -> Q [a]
sequenceQ = sequence
-----------------------------------------------------
--
-- The Lift class
--
-----------------------------------------------------
-- | A 'Lift' instance can have any of its values turned into a Template
-- Haskell expression. This is needed when a value used within a Template
-- Haskell quotation is bound outside the Oxford brackets (@[| ... |]@) but not
-- at the top level. As an example:
--
-- > add1 :: Int -> Q Exp
-- > add1 x = [| x + 1 |]
--
-- Template Haskell has no way of knowing what value @x@ will take on at
-- splice-time, so it requires the type of @x@ to be an instance of 'Lift'.
--
-- 'Lift' instances can be derived automatically by use of the @-XDeriveLift@
-- GHC language extension:
--
-- > {-# LANGUAGE DeriveLift #-}
-- > module Foo where
-- >
-- > import Language.Haskell.TH.Syntax
-- >
-- > data Bar a = Bar1 a (Bar a) | Bar2 String
-- > deriving Lift
class Lift t where
-- | Turn a value into a Template Haskell expression, suitable for use in
-- a splice.
lift :: t -> Q Exp
default lift :: Data t => t -> Q Exp
lift = liftData
-- If you add any instances here, consider updating test th/TH_Lift
instance Lift Integer where
lift x = return (LitE (IntegerL x))
instance Lift Int where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Int8 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Int16 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Int32 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Int64 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Word where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Word8 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Word16 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Word32 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Word64 where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Lift Natural where
lift x = return (LitE (IntegerL (fromIntegral x)))
instance Integral a => Lift (Ratio a) where
lift x = return (LitE (RationalL (toRational x)))
instance Lift Float where
lift x = return (LitE (RationalL (toRational x)))
instance Lift Double where
lift x = return (LitE (RationalL (toRational x)))
instance Lift Char where
lift x = return (LitE (CharL x))
instance Lift Bool where
lift True = return (ConE trueName)
lift False = return (ConE falseName)
instance Lift a => Lift (Maybe a) where
lift Nothing = return (ConE nothingName)
lift (Just x) = liftM (ConE justName `AppE`) (lift x)
instance (Lift a, Lift b) => Lift (Either a b) where
lift (Left x) = liftM (ConE leftName `AppE`) (lift x)
lift (Right y) = liftM (ConE rightName `AppE`) (lift y)
instance Lift a => Lift [a] where
lift xs = do { xs' <- mapM lift xs; return (ListE xs') }
liftString :: String -> Q Exp
-- Used in TcExpr to short-circuit the lifting for strings
liftString s = return (LitE (StringL s))
instance Lift () where
lift () = return (ConE (tupleDataName 0))
instance (Lift a, Lift b) => Lift (a, b) where
lift (a, b)
= liftM TupE $ sequence [lift a, lift b]
instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
lift (a, b, c)
= liftM TupE $ sequence [lift a, lift b, lift c]
instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
lift (a, b, c, d)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d]
instance (Lift a, Lift b, Lift c, Lift d, Lift e)
=> Lift (a, b, c, d, e) where
lift (a, b, c, d, e)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]
instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
=> Lift (a, b, c, d, e, f) where
lift (a, b, c, d, e, f)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]
instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
=> Lift (a, b, c, d, e, f, g) where
lift (a, b, c, d, e, f, g)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]
-- TH has a special form for literal strings,
-- which we should take advantage of.
-- NB: the lhs of the rule has no args, so that
-- the rule will apply to a 'lift' all on its own
-- which happens to be the way the type checker
-- creates it.
{-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}
trueName, falseName :: Name
trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True"
falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
nothingName, justName :: Name
nothingName = mkNameG DataName "base" "GHC.Base" "Nothing"
justName = mkNameG DataName "base" "GHC.Base" "Just"
leftName, rightName :: Name
leftName = mkNameG DataName "base" "Data.Either" "Left"
rightName = mkNameG DataName "base" "Data.Either" "Right"
-----------------------------------------------------
--
-- Generic Lift implementations
--
-----------------------------------------------------
-- | 'dataToQa' is an internal utility function for constructing generic
-- conversion functions from types with 'Data' instances to various
-- quasi-quoting representations. See the source of 'dataToExpQ' and
-- 'dataToPatQ' for two example usages: @mkCon@, @mkLit@
-- and @appQ@ are overloadable to account for different syntax for
-- expressions and patterns; @antiQ@ allows you to override type-specific
-- cases, a common usage is just @const Nothing@, which results in
-- no overloading.
dataToQa :: forall a k q. Data a
=> (Name -> k)
-> (Lit -> Q q)
-> (k -> [Q q] -> Q q)
-> (forall b . Data b => b -> Maybe (Q q))
-> a
-> Q q
dataToQa mkCon mkLit appCon antiQ t =
case antiQ t of
Nothing ->
case constrRep constr of
AlgConstr _ ->
appCon (mkCon funOrConName) conArgs
where
funOrConName :: Name
funOrConName =
case showConstr constr of
"(:)" -> Name (mkOccName ":")
(NameG DataName
(mkPkgName "ghc-prim")
(mkModName "GHC.Types"))
con@"[]" -> Name (mkOccName con)
(NameG DataName
(mkPkgName "ghc-prim")
(mkModName "GHC.Types"))
con@('(':_) -> Name (mkOccName con)
(NameG DataName
(mkPkgName "ghc-prim")
(mkModName "GHC.Tuple"))
-- It is possible for a Data instance to be defined such
-- that toConstr uses a Constr defined using a function,
-- not a data constructor. In such a case, we must take
-- care to build the Name using mkNameG_v (for values),
-- not mkNameG_d (for data constructors).
-- See Trac #10796.
fun@(x:_) | startsVarSym x || startsVarId x
-> mkNameG_v tyconPkg tyconMod fun
con -> mkNameG_d tyconPkg tyconMod con
where
tycon :: TyCon
tycon = (typeRepTyCon . typeOf) t
tyconPkg, tyconMod :: String
tyconPkg = tyConPackage tycon
tyconMod = tyConModule tycon
conArgs :: [Q q]
conArgs = gmapQ (dataToQa mkCon mkLit appCon antiQ) t
IntConstr n ->
mkLit $ IntegerL n
FloatConstr n ->
mkLit $ RationalL n
CharConstr c ->
mkLit $ CharL c
where
constr :: Constr
constr = toConstr t
Just y -> y
-- | 'dataToExpQ' converts a value to a 'Q Exp' representation of the
-- same value, in the SYB style. It is generalized to take a function
-- override type-specific cases; see 'liftData' for a more commonly
-- used variant.
dataToExpQ :: Data a
=> (forall b . Data b => b -> Maybe (Q Exp))
-> a
-> Q Exp
dataToExpQ = dataToQa varOrConE litE (foldl appE)
where
-- Make sure that VarE is used if the Constr value relies on a
-- function underneath the surface (instead of a constructor).
-- See Trac #10796.
varOrConE s =
case nameSpace s of
Just VarName -> return (VarE s)
Just DataName -> return (ConE s)
_ -> fail $ "Can't construct an expression from name "
++ showName s
appE x y = do { a <- x; b <- y; return (AppE a b)}
litE c = return (LitE c)
-- | 'liftData' is a variant of 'lift' in the 'Lift' type class which
-- works for any type with a 'Data' instance.
liftData :: Data a => a -> Q Exp
liftData = dataToExpQ (const Nothing)
-- | 'dataToPatQ' converts a value to a 'Q Pat' representation of the same
-- value, in the SYB style. It takes a function to handle type-specific cases,
-- alternatively, pass @const Nothing@ to get default behavior.
dataToPatQ :: Data a
=> (forall b . Data b => b -> Maybe (Q Pat))
-> a
-> Q Pat
dataToPatQ = dataToQa id litP conP
where litP l = return (LitP l)
conP n ps =
case nameSpace n of
Just DataName -> do
ps' <- sequence ps
return (ConP n ps')
_ -> fail $ "Can't construct a pattern from name "
++ showName n
-----------------------------------------------------
-- Names and uniques
-----------------------------------------------------
newtype ModName = ModName String -- Module name
deriving (Show,Eq,Ord,Typeable,Data,Generic)
newtype PkgName = PkgName String -- package name
deriving (Show,Eq,Ord,Typeable,Data,Generic)
-- | Obtained from 'reifyModule' and 'thisModule'.
data Module = Module PkgName ModName -- package qualified module name
deriving (Show,Eq,Ord,Typeable,Data,Generic)
newtype OccName = OccName String
deriving (Show,Eq,Ord,Typeable,Data,Generic)
mkModName :: String -> ModName
mkModName s = ModName s
modString :: ModName -> String
modString (ModName m) = m
mkPkgName :: String -> PkgName
mkPkgName s = PkgName s
pkgString :: PkgName -> String
pkgString (PkgName m) = m
-----------------------------------------------------
-- OccName
-----------------------------------------------------
mkOccName :: String -> OccName
mkOccName s = OccName s
occString :: OccName -> String
occString (OccName occ) = occ
-----------------------------------------------------
-- Names
-----------------------------------------------------
--
-- For "global" names ('NameG') we need a totally unique name,
-- so we must include the name-space of the thing
--
-- For unique-numbered things ('NameU'), we've got a unique reference
-- anyway, so no need for name space
--
-- For dynamically bound thing ('NameS') we probably want them to
-- in a context-dependent way, so again we don't want the name
-- space. For example:
--
-- > let v = mkName "T" in [| data $v = $v |]
--
-- Here we use the same Name for both type constructor and data constructor
--
--
-- NameL and NameG are bound *outside* the TH syntax tree
-- either globally (NameG) or locally (NameL). Ex:
--
-- > f x = $(h [| (map, x) |])
--
-- The 'map' will be a NameG, and 'x' wil be a NameL
--
-- These Names should never appear in a binding position in a TH syntax tree
{- $namecapture #namecapture#
Much of 'Name' API is concerned with the problem of /name capture/, which
can be seen in the following example.
> f expr = [| let x = 0 in $expr |]
> ...
> g x = $( f [| x |] )
> h y = $( f [| y |] )
A naive desugaring of this would yield:
> g x = let x = 0 in x
> h y = let x = 0 in y
All of a sudden, @g@ and @h@ have different meanings! In this case,
we say that the @x@ in the RHS of @g@ has been /captured/
by the binding of @x@ in @f@.
What we actually want is for the @x@ in @f@ to be distinct from the
@x@ in @g@, so we get the following desugaring:
> g x = let x' = 0 in x
> h y = let x' = 0 in y
which avoids name capture as desired.
In the general case, we say that a @Name@ can be captured if
the thing it refers to can be changed by adding new declarations.
-}
{- |
An abstract type representing names in the syntax tree.
'Name's can be constructed in several ways, which come with different
name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for
an explanation of name capture):
* the built-in syntax @'f@ and @''T@ can be used to construct names,
The expression @'f@ gives a @Name@ which refers to the value @f@
currently in scope, and @''T@ gives a @Name@ which refers to the
type @T@ currently in scope. These names can never be captured.
* 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and
@''T@ respectively, but the @Name@s are looked up at the point
where the current splice is being run. These names can never be
captured.
* 'newName' monadically generates a new name, which can never
be captured.
* 'mkName' generates a capturable name.
Names constructed using @newName@ and @mkName@ may be used in bindings
(such as @let x = ...@ or @\x -> ...@), but names constructed using
@lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not.
-}
data Name = Name OccName NameFlavour deriving (Typeable, Data, Eq, Generic)
instance Ord Name where
-- check if unique is different before looking at strings
(Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp`
(o1 `compare` o2)
data NameFlavour
= NameS -- ^ An unqualified name; dynamically bound
| NameQ ModName -- ^ A qualified name; dynamically bound
| NameU !Int -- ^ A unique local name
| NameL !Int -- ^ Local name bound outside of the TH AST
| NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
-- An original name (occurrences only, not binders)
-- Need the namespace too to be sure which
-- thing we are naming
deriving ( Typeable, Data, Eq, Ord, Show, Generic )
data NameSpace = VarName -- ^ Variables
| DataName -- ^ Data constructors
| TcClsName -- ^ Type constructors and classes; Haskell has them
-- in the same name space for now.
deriving( Eq, Ord, Show, Data, Typeable, Generic )
type Uniq = Int
-- | The name without its module prefix.
--
-- ==== __Examples__
--
-- >>> nameBase ''Data.Either.Either
-- "Either"
-- >>> nameBase (mkName "foo")
-- "foo"
-- >>> nameBase (mkName "Module.foo")
-- "foo"
nameBase :: Name -> String
nameBase (Name occ _) = occString occ
-- | Module prefix of a name, if it exists.
--
-- ==== __Examples__
--
-- >>> nameModule ''Data.Either.Either
-- Just "Data.Either"
-- >>> nameModule (mkName "foo")
-- Nothing
-- >>> nameModule (mkName "Module.foo")
-- Just "Module"
nameModule :: Name -> Maybe String
nameModule (Name _ (NameQ m)) = Just (modString m)
nameModule (Name _ (NameG _ _ m)) = Just (modString m)
nameModule _ = Nothing
-- | A name's package, if it exists.
--
-- ==== __Examples__
--
-- >>> namePackage ''Data.Either.Either
-- Just "base"
-- >>> namePackage (mkName "foo")
-- Nothing
-- >>> namePackage (mkName "Module.foo")
-- Nothing
namePackage :: Name -> Maybe String
namePackage (Name _ (NameG _ p _)) = Just (pkgString p)
namePackage _ = Nothing
-- | Returns whether a name represents an occurrence of a top-level variable
-- ('VarName'), data constructor ('DataName'), type constructor, or type class
-- ('TcClsName'). If we can't be sure, it returns 'Nothing'.
--
-- ==== __Examples__
--
-- >>> nameSpace 'Prelude.id
-- Just VarName
-- >>> nameSpace (mkName "id")
-- Nothing -- only works for top-level variable names
-- >>> nameSpace 'Data.Maybe.Just
-- Just DataName
-- >>> nameSpace ''Data.Maybe.Maybe
-- Just TcClsName
-- >>> nameSpace ''Data.Ord.Ord
-- Just TcClsName
nameSpace :: Name -> Maybe NameSpace
nameSpace (Name _ (NameG ns _ _)) = Just ns
nameSpace _ = Nothing
{- |
Generate a capturable name. Occurrences of such names will be
resolved according to the Haskell scoping rules at the occurrence
site.
For example:
> f = [| pi + $(varE (mkName "pi")) |]
> ...
> g = let pi = 3 in $f
In this case, @g@ is desugared to
> g = Prelude.pi + 3
Note that @mkName@ may be used with qualified names:
> mkName "Prelude.pi"
See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could
be rewritten using 'dyn' as
> f = [| pi + $(dyn "pi") |]
-}
mkName :: String -> Name
-- The string can have a '.', thus "Foo.baz",
-- giving a dynamically-bound qualified name,
-- in which case we want to generate a NameQ
--
-- Parse the string to see if it has a "." in it
-- so we know whether to generate a qualified or unqualified name
-- It's a bit tricky because we need to parse
--
-- > Foo.Baz.x as Qual Foo.Baz x
--
-- So we parse it from back to front
mkName str
= split [] (reverse str)
where
split occ [] = Name (mkOccName occ) NameS
split occ ('.':rev) | not (null occ)
, is_rev_mod_name rev
= Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
-- The 'not (null occ)' guard ensures that
-- mkName "&." = Name "&." NameS
-- The 'is_rev_mod' guards ensure that
-- mkName ".&" = Name ".&" NameS
-- mkName "^.." = Name "^.." NameS -- Trac #8633
-- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
-- This rather bizarre case actually happened; (.&.) is in Data.Bits
split occ (c:rev) = split (c:occ) rev
-- Recognises a reversed module name xA.yB.C,
-- with at least one component,
-- and each component looks like a module name
-- (i.e. non-empty, starts with capital, all alpha)
is_rev_mod_name rev_mod_str
| (compt, rest) <- break (== '.') rev_mod_str
, not (null compt), isUpper (last compt), all is_mod_char compt
= case rest of
[] -> True
(_dot : rest') -> is_rev_mod_name rest'
| otherwise
= False
is_mod_char c = isAlphaNum c || c == '_' || c == '\''
-- | Only used internally
mkNameU :: String -> Uniq -> Name
mkNameU s u = Name (mkOccName s) (NameU u)
-- | Only used internally
mkNameL :: String -> Uniq -> Name
mkNameL s u = Name (mkOccName s) (NameL u)
-- | Used for 'x etc, but not available to the programmer
mkNameG :: NameSpace -> String -> String -> String -> Name
mkNameG ns pkg modu occ
= Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
mkNameS :: String -> Name
mkNameS n = Name (mkOccName n) NameS
mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
mkNameG_v = mkNameG VarName
mkNameG_tc = mkNameG TcClsName
mkNameG_d = mkNameG DataName
data NameIs = Alone | Applied | Infix
showName :: Name -> String
showName = showName' Alone
showName' :: NameIs -> Name -> String
showName' ni nm
= case ni of
Alone -> nms
Applied
| pnam -> nms
| otherwise -> "(" ++ nms ++ ")"
Infix
| pnam -> "`" ++ nms ++ "`"
| otherwise -> nms
where
-- For now, we make the NameQ and NameG print the same, even though
-- NameQ is a qualified name (so what it means depends on what the
-- current scope is), and NameG is an original name (so its meaning
-- should be independent of what's in scope.
-- We may well want to distinguish them in the end.
-- Ditto NameU and NameL
nms = case nm of
Name occ NameS -> occString occ
Name occ (NameQ m) -> modString m ++ "." ++ occString occ
Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
Name occ (NameU u) -> occString occ ++ "_" ++ show u
Name occ (NameL u) -> occString occ ++ "_" ++ show u
pnam = classify nms
-- True if we are function style, e.g. f, [], (,)
-- False if we are operator style, e.g. +, :+
classify "" = False -- shouldn't happen; . operator is handled below
classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
case dropWhile (/='.') xs of
(_:xs') -> classify xs'
[] -> True
| otherwise = False
instance Show Name where
show = showName
-- Tuple data and type constructors
-- | Tuple data constructor
tupleDataName :: Int -> Name
-- | Tuple type constructor
tupleTypeName :: Int -> Name
tupleDataName 0 = mk_tup_name 0 DataName
tupleDataName 1 = error "tupleDataName 1"
tupleDataName n = mk_tup_name (n-1) DataName
tupleTypeName 0 = mk_tup_name 0 TcClsName
tupleTypeName 1 = error "tupleTypeName 1"
tupleTypeName n = mk_tup_name (n-1) TcClsName
mk_tup_name :: Int -> NameSpace -> Name
mk_tup_name n_commas space
= Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
where
occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
tup_mod = mkModName "GHC.Tuple"
-- Unboxed tuple data and type constructors
-- | Unboxed tuple data constructor
unboxedTupleDataName :: Int -> Name
-- | Unboxed tuple type constructor
unboxedTupleTypeName :: Int -> Name
unboxedTupleDataName 0 = error "unboxedTupleDataName 0"
unboxedTupleDataName 1 = error "unboxedTupleDataName 1"
unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName
unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0"
unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1"
unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName
mk_unboxed_tup_name :: Int -> NameSpace -> Name
mk_unboxed_tup_name n_commas space
= Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
where
occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)")
tup_mod = mkModName "GHC.Tuple"
-----------------------------------------------------
-- Locations
-----------------------------------------------------
data Loc
= Loc { loc_filename :: String
, loc_package :: String
, loc_module :: String
, loc_start :: CharPos
, loc_end :: CharPos }
deriving( Show, Eq, Ord, Data, Typeable, Generic )
type CharPos = (Int, Int) -- ^ Line and character position
-----------------------------------------------------
--
-- The Info returned by reification
--
-----------------------------------------------------
-- | Obtained from 'reify' in the 'Q' Monad.
data Info
=
-- | A class, with a list of its visible instances
ClassI
Dec
[InstanceDec]
-- | A class method
| ClassOpI
Name
Type
ParentName
-- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate
| TyConI
Dec
-- | A type or data family, with a list of its visible instances. A closed
-- type family is returned with 0 instances.
| FamilyI
Dec
[InstanceDec]
-- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@.
| PrimTyConI
Name
Arity
Unlifted
-- | A data constructor
| DataConI
Name
Type
ParentName
{- |
A \"value\" variable (as opposed to a type variable, see 'TyVarI').
The @Maybe Dec@ field contains @Just@ the declaration which
defined the variable -- including the RHS of the declaration --
or else @Nothing@, in the case where the RHS is unavailable to
the compiler. At present, this value is _always_ @Nothing@:
returning the RHS has not yet been implemented because of
lack of interest.
-}
| VarI
Name
Type
(Maybe Dec)
{- |
A type variable.
The @Type@ field contains the type which underlies the variable.
At present, this is always @'VarT' theName@, but future changes
may permit refinement of this.
-}
| TyVarI -- Scoped type variable
Name
Type -- What it is bound to
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | Obtained from 'reifyModule' in the 'Q' Monad.
data ModuleInfo =
-- | Contains the import list of the module.
ModuleInfo [Module]
deriving( Show, Eq, Ord, Data, Typeable, Generic )
{- |
In 'ClassOpI' and 'DataConI', name of the parent class or type
-}
type ParentName = Name
-- | In 'PrimTyConI', arity of the type constructor
type Arity = Int
-- | In 'PrimTyConI', is the type constructor unlifted?
type Unlifted = Bool
-- | 'InstanceDec' desribes a single instance of a class or type function.
-- It is just a 'Dec', but guaranteed to be one of the following:
--
-- * 'InstanceD' (with empty @['Dec']@)
--
-- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@)
--
-- * 'TySynInstD'
type InstanceDec = Dec
data Fixity = Fixity Int FixityDirection
deriving( Eq, Ord, Show, Data, Typeable, Generic )
data FixityDirection = InfixL | InfixR | InfixN
deriving( Eq, Ord, Show, Data, Typeable, Generic )
-- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9)
maxPrecedence :: Int
maxPrecedence = (9::Int)
-- | Default fixity: @infixl 9@
defaultFixity :: Fixity
defaultFixity = Fixity maxPrecedence InfixL
{-
Note [Unresolved infix]
~~~~~~~~~~~~~~~~~~~~~~~
-}
{- $infix #infix#
When implementing antiquotation for quasiquoters, one often wants
to parse strings into expressions:
> parse :: String -> Maybe Exp
But how should we parse @a + b * c@? If we don't know the fixities of
@+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
+ b) * c@.
In cases like this, use 'UInfixE', 'UInfixP', or 'UInfixT', which stand for
\"unresolved infix expression/pattern/type\", respectively. When the compiler
is given a splice containing a tree of @UInfixE@ applications such as
> UInfixE
> (UInfixE e1 op1 e2)
> op2
> (UInfixE e3 op3 e4)
it will look up and the fixities of the relevant operators and
reassociate the tree as necessary.
* trees will not be reassociated across 'ParensE', 'ParensP', or 'ParensT',
which are of use for parsing expressions like
> (a + b * c) + d * e
* 'InfixE', 'InfixP', and 'InfixT' expressions are never reassociated.
* The 'UInfixE' constructor doesn't support sections. Sections
such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
outer-most section, and use 'UInfixE' constructors for all
other operators:
> InfixE
> Just (UInfixE ...a + b * c...)
> op
> Nothing
Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
into 'Exp's differently:
> (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
> -- will result in a fixity error if (+) is left-infix
> (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
> -- no fixity errors
* Quoted expressions such as
> [| a * b + c |] :: Q Exp
> [p| a : b : c |] :: Q Pat
> [t| T + T |] :: Q Type
will never contain 'UInfixE', 'UInfixP', 'UInfixT', 'InfixT', 'ParensE',
'ParensP', or 'ParensT' constructors.
-}
-----------------------------------------------------
--
-- The main syntax data types
--
-----------------------------------------------------
data Lit = CharL Char
| StringL String
| IntegerL Integer -- ^ Used for overloaded and non-overloaded
-- literals. We don't have a good way to
-- represent non-overloaded literals at
-- the moment. Maybe that doesn't matter?
| RationalL Rational -- Ditto
| IntPrimL Integer
| WordPrimL Integer
| FloatPrimL Rational
| DoublePrimL Rational
| StringPrimL [Word8] -- ^ A primitive C-style string, type Addr#
| CharPrimL Char
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- We could add Int, Float, Double etc, as we do in HsLit,
-- but that could complicate the
-- supposedly-simple TH.Syntax literal type
-- | Pattern in Haskell given in @{}@
data Pat
= LitP Lit -- ^ @{ 5 or \'c\' }@
| VarP Name -- ^ @{ x }@
| TupP [Pat] -- ^ @{ (p1,p2) }@
| UnboxedTupP [Pat] -- ^ @{ (\# p1,p2 \#) }@
| ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
| InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
| UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
--
-- See "Language.Haskell.TH.Syntax#infix"
| ParensP Pat -- ^ @{(p)}@
--
-- See "Language.Haskell.TH.Syntax#infix"
| TildeP Pat -- ^ @{ ~p }@
| BangP Pat -- ^ @{ !p }@
| AsP Name Pat -- ^ @{ x \@ p }@
| WildP -- ^ @{ _ }@
| RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
| ListP [ Pat ] -- ^ @{ [1,2,3] }@
| SigP Pat Type -- ^ @{ p :: t }@
| ViewP Exp Pat -- ^ @{ e -> p }@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
type FieldPat = (Name,Pat)
data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Clause = Clause [Pat] Body [Dec]
-- ^ @f { p1 p2 = body where decs }@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Exp
= VarE Name -- ^ @{ x }@
| ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
| LitE Lit -- ^ @{ 5 or \'c\'}@
| AppE Exp Exp -- ^ @{ f x }@
| InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
-- It's a bit gruesome to use an Exp as the
-- operator, but how else can we distinguish
-- constructors from non-constructors?
-- Maybe there should be a var-or-con type?
-- Or maybe we should leave it to the String itself?
| UInfixE Exp Exp Exp -- ^ @{x + y}@
--
-- See "Language.Haskell.TH.Syntax#infix"
| ParensE Exp -- ^ @{ (e) }@
--
-- See "Language.Haskell.TH.Syntax#infix"
| LamE [Pat] Exp -- ^ @{ \\ p1 p2 -> e }@
| LamCaseE [Match] -- ^ @{ \\case m1; m2 }@
| TupE [Exp] -- ^ @{ (e1,e2) } @
| UnboxedTupE [Exp] -- ^ @{ (\# e1,e2 \#) } @
| CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
| MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@
| LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
| CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
| DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
| CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
--
-- The result expression of the comprehension is
-- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'.
--
-- E.g. translation:
--
-- > [ f x | x <- xs ]
--
-- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
| ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
| ListE [ Exp ] -- ^ @{ [1,2,3] }@
| SigE Exp Type -- ^ @{ e :: t }@
| RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
| RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
| StaticE Exp -- ^ @{ static e }@
| UnboundVarE Name -- ^ @{ _x }@ (hole)
deriving( Show, Eq, Ord, Data, Typeable, Generic )
type FieldExp = (Name,Exp)
-- Omitted: implicit parameters
data Body
= GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2
-- | e3 = e4 }
-- where ds@
| NormalB Exp -- ^ @f p { = e } where ds@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Guard
= NormalG Exp -- ^ @f x { | odd x } = x@
| PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Stmt
= BindS Pat Exp
| LetS [ Dec ]
| NoBindS Exp
| ParS [[Stmt]]
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Range = FromR Exp | FromThenR Exp Exp
| FromToR Exp Exp | FromThenToR Exp Exp Exp
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Dec
= FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
| ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
| DataD Cxt Name [TyVarBndr]
(Maybe Kind) -- Kind signature (allowed only for GADTs)
[Con] Cxt
-- ^ @{ data Cxt x => T x = A x | B (T x)
-- deriving (Z,W)}@
| NewtypeD Cxt Name [TyVarBndr]
(Maybe Kind) -- Kind signature
Con Cxt -- ^ @{ newtype Cxt x => T x = A (B x)
-- deriving (Z,W Q)}@
| TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
| ClassD Cxt Name [TyVarBndr]
[FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
| InstanceD (Maybe Overlap) Cxt Type [Dec]
-- ^ @{ instance {\-\# OVERLAPS \#-\}
-- Show w => Show [w] where ds }@
| SigD Name Type -- ^ @{ length :: [a] -> Int }@
| ForeignD Foreign -- ^ @{ foreign import ... }
--{ foreign export ... }@
| InfixD Fixity Name -- ^ @{ infix 3 foo }@
-- | pragmas
| PragmaD Pragma -- ^ @{ {\-\# INLINE [1] foo \#-\} }@
-- | data families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
| DataFamilyD Name [TyVarBndr]
(Maybe Kind)
-- ^ @{ data family T a b c :: * }@
| DataInstD Cxt Name [Type]
(Maybe Kind) -- Kind signature
[Con] Cxt -- ^ @{ data instance Cxt x => T [x]
-- = A x | B (T x) deriving (Z,W)}@
| NewtypeInstD Cxt Name [Type]
(Maybe Kind) -- Kind signature
Con Cxt -- ^ @{ newtype instance Cxt x => T [x]
-- = A (B x) deriving (Z,W)}@
| TySynInstD Name TySynEqn -- ^ @{ type instance ... }@
-- | open type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
| OpenTypeFamilyD TypeFamilyHead
-- ^ @{ type family T a b c = (r :: *) | r -> a b }@
| ClosedTypeFamilyD TypeFamilyHead [TySynEqn]
-- ^ @{ type family F a b = (r :: *) | r -> a where ... }@
| RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@
| StandaloneDerivD Cxt Type -- ^ @{ deriving instance Ord a => Ord (Foo a) }@
| DefaultSigD Name Type -- ^ @{ default size :: Data a => a -> Int }@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | Varieties of allowed instance overlap.
data Overlap = Overlappable -- ^ May be overlapped by more specific instances
| Overlapping -- ^ May overlap a more general instance
| Overlaps -- ^ Both 'Overlapping' and 'Overlappable'
| Incoherent -- ^ Both 'Overlappable' and 'Overlappable', and
-- pick an arbitrary one if multiple choices are
-- available.
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | Common elements of 'OpenTypeFamilyD' and 'ClosedTypeFamilyD'.
-- By analogy with with "head" for type classes and type class instances as
-- defined in /Type classes: an exploration of the design space/, the
-- @TypeFamilyHead@ is defined to be the elements of the declaration between
-- @type family@ and @where@.
data TypeFamilyHead =
TypeFamilyHead Name [TyVarBndr] FamilyResultSig (Maybe InjectivityAnn)
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | One equation of a type family instance or closed type family. The
-- arguments are the left-hand-side type patterns and the right-hand-side
-- result.
data TySynEqn = TySynEqn [Type] Type
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data FunDep = FunDep [Name] [Name]
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data FamFlavour = TypeFam | DataFam
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Foreign = ImportF Callconv Safety String Name Type
| ExportF Callconv String Name Type
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- keep Callconv in sync with module ForeignCall in ghc/compiler/prelude/ForeignCall.hs
data Callconv = CCall | StdCall | CApi | Prim | JavaScript
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Safety = Unsafe | Safe | Interruptible
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Pragma = InlineP Name Inline RuleMatch Phases
| SpecialiseP Name Type (Maybe Inline) Phases
| SpecialiseInstP Type
| RuleP String [RuleBndr] Exp Exp Phases
| AnnP AnnTarget Exp
| LineP Int String
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data Inline = NoInline
| Inline
| Inlinable
deriving (Show, Eq, Ord, Data, Typeable, Generic)
data RuleMatch = ConLike
| FunLike
deriving (Show, Eq, Ord, Data, Typeable, Generic)
data Phases = AllPhases
| FromPhase Int
| BeforePhase Int
deriving (Show, Eq, Ord, Data, Typeable, Generic)
data RuleBndr = RuleVar Name
| TypedRuleVar Name Type
deriving (Show, Eq, Ord, Data, Typeable, Generic)
data AnnTarget = ModuleAnnotation
| TypeAnnotation Name
| ValueAnnotation Name
deriving (Show, Eq, Ord, Data, Typeable, Generic)
type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
-- | Since the advent of @ConstraintKinds@, constraints are really just types.
-- Equality constraints use the 'EqualityT' constructor. Constraints may also
-- be tuples of other constraints.
type Pred = Type
data SourceUnpackedness
= NoSourceUnpackedness -- ^ @C a@
| SourceNoUnpack -- ^ @C { {\-\# NOUNPACK \#-\} } a@
| SourceUnpack -- ^ @C { {\-\# UNPACK \#-\} } a@
deriving (Show, Eq, Ord, Data, Typeable, Generic)
data SourceStrictness = NoSourceStrictness -- ^ @C a@
| SourceLazy -- ^ @C {~}a@
| SourceStrict -- ^ @C {!}a@
deriving (Show, Eq, Ord, Data, Typeable, Generic)
-- | Unlike 'SourceStrictness' and 'SourceUnpackedness', 'DecidedStrictness'
-- refers to the strictness that the compiler chooses for a data constructor
-- field, which may be different from what is written in source code. See
-- 'reifyConStrictness' for more information.
data DecidedStrictness = DecidedLazy
| DecidedStrict
| DecidedUnpack
deriving (Show, Eq, Ord, Data, Typeable, Generic)
data Con = NormalC Name [BangType] -- ^ @C Int a@
| RecC Name [VarBangType] -- ^ @C { v :: Int, w :: a }@
| InfixC BangType Name BangType -- ^ @Int :+ a@
| ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
| GadtC [Name] [BangType]
Type -- See Note [GADT return type]
-- ^ @C :: a -> b -> T b Int@
| RecGadtC [Name] [VarBangType]
Type -- See Note [GADT return type]
-- ^ @C :: { v :: Int } -> T b Int@
deriving (Show, Eq, Ord, Data, Typeable, Generic)
-- Note [GADT return type]
-- ~~~~~~~~~~~~~~~~~~~~~~~
--
-- The return type of a GADT constructor does not necessarily match the name of
-- the data type:
--
-- type S = T
--
-- data T a where
-- MkT :: S Int
--
--
-- type S a = T
--
-- data T a where
-- MkT :: S Char Int
--
--
-- type Id a = a
-- type S a = T
--
-- data T a where
-- MkT :: Id (S Char Int)
--
--
-- That is why we allow the return type stored by a constructor to be an
-- arbitrary type. See also #11341
data Bang = Bang SourceUnpackedness SourceStrictness
-- ^ @C { {\-\# UNPACK \#-\} !}a@
deriving (Show, Eq, Ord, Data, Typeable, Generic)
type BangType = (Bang, Type)
type VarBangType = (Name, Bang, Type)
-- | As of @template-haskell-2.11.0.0@, 'Strict' has been replaced by 'Bang'.
type Strict = Bang
-- | As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by
-- 'BangType'.
type StrictType = BangType
-- | As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by
-- 'VarBangType'.
type VarStrictType = VarBangType
data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@
| AppT Type Type -- ^ @T a b@
| SigT Type Kind -- ^ @t :: k@
| VarT Name -- ^ @a@
| ConT Name -- ^ @T@
| PromotedT Name -- ^ @'T@
| InfixT Type Name Type -- ^ @T + T@
| UInfixT Type Name Type -- ^ @T + T@
--
-- See "Language.Haskell.TH.Syntax#infix"
| ParensT Type -- ^ @(T)@
-- See Note [Representing concrete syntax in types]
| TupleT Int -- ^ @(,), (,,), etc.@
| UnboxedTupleT Int -- ^ @(\#,\#), (\#,,\#), etc.@
| ArrowT -- ^ @->@
| EqualityT -- ^ @~@
| ListT -- ^ @[]@
| PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
| PromotedNilT -- ^ @'[]@
| PromotedConsT -- ^ @(':)@
| StarT -- ^ @*@
| ConstraintT -- ^ @Constraint@
| LitT TyLit -- ^ @0,1,2, etc.@
| WildCardT -- ^ @_,
deriving( Show, Eq, Ord, Data, Typeable, Generic )
data TyVarBndr = PlainTV Name -- ^ @a@
| KindedTV Name Kind -- ^ @(a :: k)@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | Type family result signature
data FamilyResultSig = NoSig -- ^ no signature
| KindSig Kind -- ^ @k@
| TyVarSig TyVarBndr -- ^ @= r, = (r :: k)@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | Injectivity annotation
data InjectivityAnn = InjectivityAnn Name [Name]
deriving ( Show, Eq, Ord, Data, Typeable, Generic )
data TyLit = NumTyLit Integer -- ^ @2@
| StrTyLit String -- ^ @"Hello"@
deriving ( Show, Eq, Ord, Data, Typeable, Generic )
-- | Role annotations
data Role = NominalR -- ^ @nominal@
| RepresentationalR -- ^ @representational@
| PhantomR -- ^ @phantom@
| InferR -- ^ @_@
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | Annotation target for reifyAnnotations
data AnnLookup = AnnLookupModule Module
| AnnLookupName Name
deriving( Show, Eq, Ord, Data, Typeable, Generic )
-- | To avoid duplication between kinds and types, they
-- are defined to be the same. Naturally, you would never
-- have a type be 'StarT' and you would never have a kind
-- be 'SigT', but many of the other constructors are shared.
-- Note that the kind @Bool@ is denoted with 'ConT', not
-- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
-- not 'PromotedTupleT'.
type Kind = Type
{- Note [Representing concrete syntax in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Haskell has a rich concrete syntax for types, including
t1 -> t2, (t1,t2), [t], and so on
In TH we represent all of this using AppT, with a distinguished
type constructor at the head. So,
Type TH representation
-----------------------------------------------
t1 -> t2 ArrowT `AppT` t2 `AppT` t2
[t] ListT `AppT` t
(t1,t2) TupleT 2 `AppT` t1 `AppT` t2
'(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
But if the original HsSyn used prefix application, we won't use
these special TH constructors. For example
[] t ConT "[]" `AppT` t
(->) t ConT "->" `AppT` t
In this way we can faithfully represent in TH whether the original
HsType used concrete syntax or not.
The one case that doesn't fit this pattern is that of promoted lists
'[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
but it's very smelly because there really is no type constructor
corresponding to PromotedListT. So we encode HsExplicitListTy with
PromotedConsT and PromotedNilT (which *do* have underlying type
constructors):
'[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
(PromotedConsT `AppT` IO `AppT` PromotedNilT)
-}
-----------------------------------------------------
-- Internal helper functions
-----------------------------------------------------
cmpEq :: Ordering -> Bool
cmpEq EQ = True
cmpEq _ = False
thenCmp :: Ordering -> Ordering -> Ordering
thenCmp EQ o2 = o2
thenCmp o1 _ = o1
| tjakway/ghcjvm | libraries/template-haskell/Language/Haskell/TH/Syntax.hs | bsd-3-clause | 63,778 | 0 | 20 | 18,448 | 10,375 | 5,715 | 4,660 | 756 | 9 |
module AI.Neuron
( Neuron(..)
, ActivationFunction
, ActivationFunction'
, sigmoidNeuron
, tanhNeuron
, recluNeuron
, l2Neuron
, sigmoid
, sigmoid'
, tanh
, tanh'
, reclu
, reclu'
) where
-- | Using this structure allows users of the library to create their own
-- neurons by creating two functions - an activation function and its
-- derivative - and packaging them up into a neuron type.
data Neuron = Neuron { activation :: ActivationFunction
, activation' :: ActivationFunction'
, description :: String
}
instance Show Neuron where
show = description
type ActivationFunction = Double -> Double
type ActivationFunction' = Double -> Double
-- | Our provided neuron types: sigmoid, tanh, reclu
sigmoidNeuron :: Neuron
sigmoidNeuron = Neuron sigmoid sigmoid' "sigmoid"
tanhNeuron :: Neuron
tanhNeuron = Neuron tanh tanh' "tanh"
recluNeuron :: Neuron
recluNeuron = Neuron reclu reclu' "reclu"
l2Neuron :: Neuron
l2Neuron = Neuron (^2) id "L2"
-- | The sigmoid activation function, a standard activation function defined
-- on the range (0, 1).
sigmoid :: Double -> Double
sigmoid t = 1 / (1 + exp (-1 * t))
-- | The derivative of the sigmoid function conveniently can be computed in
-- terms of the sigmoid function.
sigmoid' :: Double -> Double
sigmoid' t = s * (1 - s)
where s = sigmoid t
-- | The hyperbolic tangent activation function is provided in Prelude. Here
-- we provide the derivative. As with the sigmoid function, the derivative
-- of tanh can be computed in terms of tanh.
tanh' :: Double -> Double
tanh' t = 1 - s ^ 2
where s = tanh t
-- | The rectified linear activation function. This is a more "biologically
-- accurate" activation function that still retains differentiability.
reclu :: Double -> Double
reclu t = log (1 + exp t)
-- | The derivative of the rectified linear activation function is just the
-- sigmoid.
reclu' :: Double -> Double
reclu' = sigmoid
| jbarrow/LambdaNet | AI/Neuron.hs | mit | 2,079 | 0 | 11 | 524 | 355 | 206 | 149 | 41 | 1 |
{-# LANGUAGE RelaxedPolyRec, FlexibleInstances, TypeSynonymInstances #-}
-- RelaxedPolyRec needed for inlinesBetween on GHC < 7
{-
Copyright (C) 2012-2015 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Readers.MediaWiki
Copyright : Copyright (C) 2012-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of mediawiki text to 'Pandoc' document.
-}
{-
TODO:
_ correctly handle tables within tables
_ parse templates?
-}
module Text.Pandoc.Readers.MediaWiki ( readMediaWiki ) where
import Text.Pandoc.Definition
import qualified Text.Pandoc.Builder as B
import Text.Pandoc.Builder (Inlines, Blocks, trimInlines)
import Text.Pandoc.Compat.Monoid ((<>))
import Text.Pandoc.Options
import Text.Pandoc.Readers.HTML ( htmlTag, isBlockTag, isCommentTag )
import Text.Pandoc.XML ( fromEntities )
import Text.Pandoc.Parsing hiding ( nested )
import Text.Pandoc.Walk ( walk )
import Text.Pandoc.Shared ( stripTrailingNewlines, safeRead, stringify, trim )
import Control.Monad
import Data.List (intersperse, intercalate, isPrefixOf )
import Text.HTML.TagSoup
import Data.Sequence (viewl, ViewL(..), (<|))
import qualified Data.Foldable as F
import qualified Data.Map as M
import qualified Data.Set as Set
import Data.Char (isDigit, isSpace)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
import Debug.Trace (trace)
import Text.Pandoc.Error
-- | Read mediawiki from an input string and return a Pandoc document.
readMediaWiki :: ReaderOptions -- ^ Reader options
-> String -- ^ String to parse (assuming @'\n'@ line endings)
-> Either PandocError Pandoc
readMediaWiki opts s =
readWith parseMediaWiki MWState{ mwOptions = opts
, mwMaxNestingLevel = 4
, mwNextLinkNumber = 1
, mwCategoryLinks = []
, mwHeaderMap = M.empty
, mwIdentifierList = Set.empty
}
(s ++ "\n")
data MWState = MWState { mwOptions :: ReaderOptions
, mwMaxNestingLevel :: Int
, mwNextLinkNumber :: Int
, mwCategoryLinks :: [Inlines]
, mwHeaderMap :: M.Map Inlines String
, mwIdentifierList :: Set.Set String
}
type MWParser = Parser [Char] MWState
instance HasReaderOptions MWState where
extractReaderOptions = mwOptions
instance HasHeaderMap MWState where
extractHeaderMap = mwHeaderMap
updateHeaderMap f st = st{ mwHeaderMap = f $ mwHeaderMap st }
instance HasIdentifierList MWState where
extractIdentifierList = mwIdentifierList
updateIdentifierList f st = st{ mwIdentifierList = f $ mwIdentifierList st }
--
-- auxiliary functions
--
-- This is used to prevent exponential blowups for things like:
-- ''a'''a''a'''a''a'''a''a'''a
nested :: MWParser a -> MWParser a
nested p = do
nestlevel <- mwMaxNestingLevel `fmap` getState
guard $ nestlevel > 0
updateState $ \st -> st{ mwMaxNestingLevel = mwMaxNestingLevel st - 1 }
res <- p
updateState $ \st -> st{ mwMaxNestingLevel = nestlevel }
return res
specialChars :: [Char]
specialChars = "'[]<=&*{}|\":\\"
spaceChars :: [Char]
spaceChars = " \n\t"
sym :: String -> MWParser ()
sym s = () <$ try (string s)
newBlockTags :: [String]
newBlockTags = ["haskell","syntaxhighlight","source","gallery","references"]
isBlockTag' :: Tag String -> Bool
isBlockTag' tag@(TagOpen t _) = (isBlockTag tag || t `elem` newBlockTags) &&
t `notElem` eitherBlockOrInline
isBlockTag' tag@(TagClose t) = (isBlockTag tag || t `elem` newBlockTags) &&
t `notElem` eitherBlockOrInline
isBlockTag' tag = isBlockTag tag
isInlineTag' :: Tag String -> Bool
isInlineTag' (TagComment _) = True
isInlineTag' t = not (isBlockTag' t)
eitherBlockOrInline :: [String]
eitherBlockOrInline = ["applet", "button", "del", "iframe", "ins",
"map", "area", "object"]
htmlComment :: MWParser ()
htmlComment = () <$ htmlTag isCommentTag
inlinesInTags :: String -> MWParser Inlines
inlinesInTags tag = try $ do
(_,raw) <- htmlTag (~== TagOpen tag [])
if '/' `elem` raw -- self-closing tag
then return mempty
else trimInlines . mconcat <$>
manyTill inline (htmlTag (~== TagClose tag))
blocksInTags :: String -> MWParser Blocks
blocksInTags tag = try $ do
(_,raw) <- htmlTag (~== TagOpen tag [])
let closer = if tag == "li"
then htmlTag (~== TagClose "li")
<|> lookAhead (
htmlTag (~== TagOpen "li" [])
<|> htmlTag (~== TagClose "ol")
<|> htmlTag (~== TagClose "ul"))
else htmlTag (~== TagClose tag)
if '/' `elem` raw -- self-closing tag
then return mempty
else mconcat <$> manyTill block closer
charsInTags :: String -> MWParser [Char]
charsInTags tag = try $ do
(_,raw) <- htmlTag (~== TagOpen tag [])
if '/' `elem` raw -- self-closing tag
then return ""
else manyTill anyChar (htmlTag (~== TagClose tag))
--
-- main parser
--
parseMediaWiki :: MWParser Pandoc
parseMediaWiki = do
bs <- mconcat <$> many block
spaces
eof
categoryLinks <- reverse . mwCategoryLinks <$> getState
let categories = if null categoryLinks
then mempty
else B.para $ mconcat $ intersperse B.space categoryLinks
return $ B.doc $ bs <> categories
--
-- block parsers
--
block :: MWParser Blocks
block = do
tr <- getOption readerTrace
pos <- getPosition
res <- mempty <$ skipMany1 blankline
<|> table
<|> header
<|> hrule
<|> orderedList
<|> bulletList
<|> definitionList
<|> mempty <$ try (spaces *> htmlComment)
<|> preformatted
<|> blockTag
<|> (B.rawBlock "mediawiki" <$> template)
<|> para
when tr $
trace (printf "line %d: %s" (sourceLine pos)
(take 60 $ show $ B.toList res)) (return ())
return res
para :: MWParser Blocks
para = do
contents <- trimInlines . mconcat <$> many1 inline
if F.all (==Space) contents
then return mempty
else return $ B.para contents
table :: MWParser Blocks
table = do
tableStart
styles <- option [] parseAttrs <* blankline
let tableWidth = case lookup "width" styles of
Just w -> fromMaybe 1.0 $ parseWidth w
Nothing -> 1.0
caption <- option mempty tableCaption
optional rowsep
hasheader <- option False $ True <$ (lookAhead (skipSpaces *> char '!'))
(cellspecs',hdr) <- unzip <$> tableRow
let widths = map ((tableWidth *) . snd) cellspecs'
let restwidth = tableWidth - sum widths
let zerocols = length $ filter (==0.0) widths
let defaultwidth = if zerocols == 0 || zerocols == length widths
then 0.0
else restwidth / fromIntegral zerocols
let widths' = map (\w -> if w == 0 then defaultwidth else w) widths
let cellspecs = zip (map fst cellspecs') widths'
rows' <- many $ try $ rowsep *> (map snd <$> tableRow)
optional blanklines
tableEnd
let cols = length hdr
let (headers,rows) = if hasheader
then (hdr, rows')
else (replicate cols mempty, hdr:rows')
return $ B.table caption cellspecs headers rows
parseAttrs :: MWParser [(String,String)]
parseAttrs = many1 parseAttr
parseAttr :: MWParser (String, String)
parseAttr = try $ do
skipMany spaceChar
k <- many1 letter
char '='
v <- (char '"' >> many1Till (satisfy (/='\n')) (char '"'))
<|> many1 nonspaceChar
return (k,v)
tableStart :: MWParser ()
tableStart = try $ guardColumnOne *> skipSpaces *> sym "{|"
tableEnd :: MWParser ()
tableEnd = try $ guardColumnOne *> skipSpaces *> sym "|}"
rowsep :: MWParser ()
rowsep = try $ guardColumnOne *> skipSpaces *> sym "|-" <*
optional parseAttr <* blanklines
cellsep :: MWParser ()
cellsep = try $
(guardColumnOne *> skipSpaces <*
( (char '|' <* notFollowedBy (oneOf "-}+"))
<|> (char '!')
)
)
<|> (() <$ try (string "||"))
<|> (() <$ try (string "!!"))
tableCaption :: MWParser Inlines
tableCaption = try $ do
guardColumnOne
skipSpaces
sym "|+"
optional (try $ parseAttr *> skipSpaces *> char '|' *> skipSpaces)
(trimInlines . mconcat) <$> many (notFollowedBy (cellsep <|> rowsep) *> inline)
tableRow :: MWParser [((Alignment, Double), Blocks)]
tableRow = try $ skipMany htmlComment *> many tableCell
tableCell :: MWParser ((Alignment, Double), Blocks)
tableCell = try $ do
cellsep
skipMany spaceChar
attrs <- option [] $ try $ parseAttrs <* skipSpaces <* char '|' <*
notFollowedBy (char '|')
skipMany spaceChar
ls <- concat <$> many (notFollowedBy (cellsep <|> rowsep <|> tableEnd) *>
((snd <$> withRaw table) <|> count 1 anyChar))
bs <- parseFromString (mconcat <$> many block) ls
let align = case lookup "align" attrs of
Just "left" -> AlignLeft
Just "right" -> AlignRight
Just "center" -> AlignCenter
_ -> AlignDefault
let width = case lookup "width" attrs of
Just xs -> fromMaybe 0.0 $ parseWidth xs
Nothing -> 0.0
return ((align, width), bs)
parseWidth :: String -> Maybe Double
parseWidth s =
case reverse s of
('%':ds) | all isDigit ds -> safeRead ('0':'.':reverse ds)
_ -> Nothing
template :: MWParser String
template = try $ do
string "{{"
notFollowedBy (char '{')
lookAhead $ letter <|> digit <|> char ':'
let chunk = template <|> variable <|> many1 (noneOf "{}") <|> count 1 anyChar
contents <- manyTill chunk (try $ string "}}")
return $ "{{" ++ concat contents ++ "}}"
blockTag :: MWParser Blocks
blockTag = do
(tag, _) <- lookAhead $ htmlTag isBlockTag'
case tag of
TagOpen "blockquote" _ -> B.blockQuote <$> blocksInTags "blockquote"
TagOpen "pre" _ -> B.codeBlock . trimCode <$> charsInTags "pre"
TagOpen "syntaxhighlight" attrs -> syntaxhighlight "syntaxhighlight" attrs
TagOpen "source" attrs -> syntaxhighlight "source" attrs
TagOpen "haskell" _ -> B.codeBlockWith ("",["haskell"],[]) . trimCode <$>
charsInTags "haskell"
TagOpen "gallery" _ -> blocksInTags "gallery"
TagOpen "p" _ -> mempty <$ htmlTag (~== tag)
TagClose "p" -> mempty <$ htmlTag (~== tag)
_ -> B.rawBlock "html" . snd <$> htmlTag (~== tag)
trimCode :: String -> String
trimCode ('\n':xs) = stripTrailingNewlines xs
trimCode xs = stripTrailingNewlines xs
syntaxhighlight :: String -> [Attribute String] -> MWParser Blocks
syntaxhighlight tag attrs = try $ do
let mblang = lookup "lang" attrs
let mbstart = lookup "start" attrs
let mbline = lookup "line" attrs
let classes = maybe [] (:[]) mblang ++ maybe [] (const ["numberLines"]) mbline
let kvs = maybe [] (\x -> [("startFrom",x)]) mbstart
contents <- charsInTags tag
return $ B.codeBlockWith ("",classes,kvs) $ trimCode contents
hrule :: MWParser Blocks
hrule = B.horizontalRule <$ try (string "----" *> many (char '-') *> newline)
guardColumnOne :: MWParser ()
guardColumnOne = getPosition >>= \pos -> guard (sourceColumn pos == 1)
preformatted :: MWParser Blocks
preformatted = try $ do
guardColumnOne
char ' '
let endline' = B.linebreak <$ (try $ newline <* char ' ')
let whitespace' = B.str <$> many1 ('\160' <$ spaceChar)
let spToNbsp ' ' = '\160'
spToNbsp x = x
let nowiki' = mconcat . intersperse B.linebreak . map B.str .
lines . fromEntities . map spToNbsp <$> try
(htmlTag (~== TagOpen "nowiki" []) *>
manyTill anyChar (htmlTag (~== TagClose "nowiki")))
let inline' = whitespace' <|> endline' <|> nowiki'
<|> (try $ notFollowedBy newline *> inline)
contents <- mconcat <$> many1 inline'
let spacesStr (Str xs) = all isSpace xs
spacesStr _ = False
if F.all spacesStr contents
then return mempty
else return $ B.para $ walk strToCode contents
strToCode :: Inline -> Inline
strToCode (Str s) = Code ("",[],[]) s
strToCode x = x
header :: MWParser Blocks
header = try $ do
guardColumnOne
eqs <- many1 (char '=')
let lev = length eqs
guard $ lev <= 6
contents <- trimInlines . mconcat <$> manyTill inline (count lev $ char '=')
attr <- registerHeader nullAttr contents
return $ B.headerWith attr lev contents
bulletList :: MWParser Blocks
bulletList = B.bulletList <$>
( many1 (listItem '*')
<|> (htmlTag (~== TagOpen "ul" []) *> spaces *> many (listItem '*' <|> li) <*
optional (htmlTag (~== TagClose "ul"))) )
orderedList :: MWParser Blocks
orderedList =
(B.orderedList <$> many1 (listItem '#'))
<|> try
(do (tag,_) <- htmlTag (~== TagOpen "ol" [])
spaces
items <- many (listItem '#' <|> li)
optional (htmlTag (~== TagClose "ol"))
let start = fromMaybe 1 $ safeRead $ fromAttrib "start" tag
return $ B.orderedListWith (start, DefaultStyle, DefaultDelim) items)
definitionList :: MWParser Blocks
definitionList = B.definitionList <$> many1 defListItem
defListItem :: MWParser (Inlines, [Blocks])
defListItem = try $ do
terms <- mconcat . intersperse B.linebreak <$> many defListTerm
-- we allow dd with no dt, or dt with no dd
defs <- if B.isNull terms
then notFollowedBy (try $ string ":<math>") *>
many1 (listItem ':')
else many (listItem ':')
return (terms, defs)
defListTerm :: MWParser Inlines
defListTerm = char ';' >> skipMany spaceChar >> anyLine >>=
parseFromString (trimInlines . mconcat <$> many inline)
listStart :: Char -> MWParser ()
listStart c = char c *> notFollowedBy listStartChar
listStartChar :: MWParser Char
listStartChar = oneOf "*#;:"
anyListStart :: MWParser Char
anyListStart = char '*'
<|> char '#'
<|> char ':'
<|> char ';'
li :: MWParser Blocks
li = lookAhead (htmlTag (~== TagOpen "li" [])) *>
(firstParaToPlain <$> blocksInTags "li") <* spaces
listItem :: Char -> MWParser Blocks
listItem c = try $ do
extras <- many (try $ char c <* lookAhead listStartChar)
if null extras
then listItem' c
else do
skipMany spaceChar
first <- concat <$> manyTill listChunk newline
rest <- many
(try $ string extras *> lookAhead listStartChar *>
(concat <$> manyTill listChunk newline))
contents <- parseFromString (many1 $ listItem' c)
(unlines (first : rest))
case c of
'*' -> return $ B.bulletList contents
'#' -> return $ B.orderedList contents
':' -> return $ B.definitionList [(mempty, contents)]
_ -> mzero
-- The point of this is to handle stuff like
-- * {{cite book
-- | blah
-- | blah
-- }}
-- * next list item
-- which seems to be valid mediawiki.
listChunk :: MWParser String
listChunk = template <|> count 1 anyChar
listItem' :: Char -> MWParser Blocks
listItem' c = try $ do
listStart c
skipMany spaceChar
first <- concat <$> manyTill listChunk newline
rest <- many (try $ char c *> lookAhead listStartChar *>
(concat <$> manyTill listChunk newline))
parseFromString (firstParaToPlain . mconcat <$> many1 block)
$ unlines $ first : rest
firstParaToPlain :: Blocks -> Blocks
firstParaToPlain contents =
case viewl (B.unMany contents) of
(Para xs) :< ys -> B.Many $ (Plain xs) <| ys
_ -> contents
--
-- inline parsers
--
inline :: MWParser Inlines
inline = whitespace
<|> url
<|> str
<|> doubleQuotes
<|> strong
<|> emph
<|> image
<|> internalLink
<|> externalLink
<|> math
<|> inlineTag
<|> B.singleton <$> charRef
<|> inlineHtml
<|> (B.rawInline "mediawiki" <$> variable)
<|> (B.rawInline "mediawiki" <$> template)
<|> special
str :: MWParser Inlines
str = B.str <$> many1 (noneOf $ specialChars ++ spaceChars)
math :: MWParser Inlines
math = (B.displayMath . trim <$> try (char ':' >> charsInTags "math"))
<|> (B.math . trim <$> charsInTags "math")
<|> (B.displayMath . trim <$> try (dmStart *> manyTill anyChar dmEnd))
<|> (B.math . trim <$> try (mStart *> manyTill (satisfy (/='\n')) mEnd))
where dmStart = string "\\["
dmEnd = try (string "\\]")
mStart = string "\\("
mEnd = try (string "\\)")
variable :: MWParser String
variable = try $ do
string "{{{"
contents <- manyTill anyChar (try $ string "}}}")
return $ "{{{" ++ contents ++ "}}}"
inlineTag :: MWParser Inlines
inlineTag = do
(tag, _) <- lookAhead $ htmlTag isInlineTag'
case tag of
TagOpen "ref" _ -> B.note . B.plain <$> inlinesInTags "ref"
TagOpen "nowiki" _ -> try $ do
(_,raw) <- htmlTag (~== tag)
if '/' `elem` raw
then return mempty
else B.text . fromEntities <$>
manyTill anyChar (htmlTag (~== TagClose "nowiki"))
TagOpen "br" _ -> B.linebreak <$ (htmlTag (~== TagOpen "br" []) -- will get /> too
*> optional blankline)
TagOpen "strike" _ -> B.strikeout <$> inlinesInTags "strike"
TagOpen "del" _ -> B.strikeout <$> inlinesInTags "del"
TagOpen "sub" _ -> B.subscript <$> inlinesInTags "sub"
TagOpen "sup" _ -> B.superscript <$> inlinesInTags "sup"
TagOpen "code" _ -> walk strToCode <$> inlinesInTags "code"
TagOpen "tt" _ -> walk strToCode <$> inlinesInTags "tt"
TagOpen "hask" _ -> B.codeWith ("",["haskell"],[]) <$> charsInTags "hask"
_ -> B.rawInline "html" . snd <$> htmlTag (~== tag)
special :: MWParser Inlines
special = B.str <$> count 1 (notFollowedBy' (htmlTag isBlockTag') *>
oneOf specialChars)
inlineHtml :: MWParser Inlines
inlineHtml = B.rawInline "html" . snd <$> htmlTag isInlineTag'
whitespace :: MWParser Inlines
whitespace = B.space <$ (skipMany1 spaceChar <|> htmlComment)
<|> B.softbreak <$ endline
endline :: MWParser ()
endline = () <$ try (newline <*
notFollowedBy spaceChar <*
notFollowedBy newline <*
notFollowedBy' hrule <*
notFollowedBy tableStart <*
notFollowedBy' header <*
notFollowedBy anyListStart)
imageIdentifiers :: [MWParser ()]
imageIdentifiers = [sym (identifier ++ ":") | identifier <- identifiers]
where identifiers = ["File", "Image", "Archivo", "Datei", "Fichier",
"Bild"]
image :: MWParser Inlines
image = try $ do
sym "[["
choice imageIdentifiers
fname <- many1 (noneOf "|]")
_ <- many imageOption
dims <- try (char '|' *> (sepBy (many digit) (char 'x')) <* string "px")
<|> return []
_ <- many imageOption
let kvs = case dims of
w:[] -> [("width", w)]
w:(h:[]) -> [("width", w), ("height", h)]
_ -> []
let attr = ("", [], kvs)
caption <- (B.str fname <$ sym "]]")
<|> try (char '|' *> (mconcat <$> manyTill inline (sym "]]")))
return $ B.imageWith attr fname ("fig:" ++ stringify caption) caption
imageOption :: MWParser String
imageOption = try $ char '|' *> opt
where
opt = try (oneOfStrings [ "border", "thumbnail", "frameless"
, "thumb", "upright", "left", "right"
, "center", "none", "baseline", "sub"
, "super", "top", "text-top", "middle"
, "bottom", "text-bottom" ])
<|> try (string "frame")
<|> try (oneOfStrings ["link=","alt=","page=","class="] <* many (noneOf "|]"))
collapseUnderscores :: String -> String
collapseUnderscores [] = []
collapseUnderscores ('_':'_':xs) = collapseUnderscores ('_':xs)
collapseUnderscores (x:xs) = x : collapseUnderscores xs
addUnderscores :: String -> String
addUnderscores = collapseUnderscores . intercalate "_" . words
internalLink :: MWParser Inlines
internalLink = try $ do
sym "[["
pagename <- unwords . words <$> many (noneOf "|]")
label <- option (B.text pagename) $ char '|' *>
( (mconcat <$> many1 (notFollowedBy (char ']') *> inline))
-- the "pipe trick"
-- [[Help:Contents|] -> "Contents"
<|> (return $ B.text $ drop 1 $ dropWhile (/=':') pagename) )
sym "]]"
linktrail <- B.text <$> many letter
let link = B.link (addUnderscores pagename) "wikilink" (label <> linktrail)
if "Category:" `isPrefixOf` pagename
then do
updateState $ \st -> st{ mwCategoryLinks = link : mwCategoryLinks st }
return mempty
else return link
externalLink :: MWParser Inlines
externalLink = try $ do
char '['
(_, src) <- uri
lab <- try (trimInlines . mconcat <$>
(skipMany1 spaceChar *> manyTill inline (char ']')))
<|> do char ']'
num <- mwNextLinkNumber <$> getState
updateState $ \st -> st{ mwNextLinkNumber = num + 1 }
return $ B.str $ show num
return $ B.link src "" lab
url :: MWParser Inlines
url = do
(orig, src) <- uri
return $ B.link src "" (B.str orig)
-- | Parses a list of inlines between start and end delimiters.
inlinesBetween :: (Show b) => MWParser a -> MWParser b -> MWParser Inlines
inlinesBetween start end =
(trimInlines . mconcat) <$> try (start >> many1Till inner end)
where inner = innerSpace <|> (notFollowedBy' (() <$ whitespace) >> inline)
innerSpace = try $ whitespace <* notFollowedBy' end
emph :: MWParser Inlines
emph = B.emph <$> nested (inlinesBetween start end)
where start = sym "''" >> lookAhead nonspaceChar
end = try $ notFollowedBy' (() <$ strong) >> sym "''"
strong :: MWParser Inlines
strong = B.strong <$> nested (inlinesBetween start end)
where start = sym "'''" >> lookAhead nonspaceChar
end = try $ sym "'''"
doubleQuotes :: MWParser Inlines
doubleQuotes = B.doubleQuoted . trimInlines . mconcat <$> try
((getState >>= guard . readerSmart . mwOptions) *>
openDoubleQuote *> manyTill inline closeDoubleQuote )
where openDoubleQuote = char '"' <* lookAhead alphaNum
closeDoubleQuote = char '"' <* notFollowedBy alphaNum
| janschulz/pandoc | src/Text/Pandoc/Readers/MediaWiki.hs | gpl-2.0 | 23,551 | 0 | 21 | 6,378 | 7,416 | 3,728 | 3,688 | 525 | 12 |
test x = [x, "hello", 13, x]
| roberth/uu-helium | test/typeerrors/Heuristics/UnifierList.hs | gpl-3.0 | 29 | 0 | 5 | 7 | 21 | 12 | 9 | 1 | 1 |
module ExprCompUndefVar where
main = [ 1 | x ] | roberth/uu-helium | test/staticerrors/ExprCompUndefVar.hs | gpl-3.0 | 49 | 0 | 6 | 12 | 16 | 10 | 6 | 2 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
-- | Construct a @Plan@ for how to build
module Stack.Build.ConstructPlan
( constructPlan
) where
import Control.Arrow ((&&&))
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.RWS.Strict
import Control.Monad.Trans.Resource
import Data.Either
import Data.Function
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Typeable
import qualified Distribution.Package as Cabal
import qualified Distribution.Text as Cabal
import qualified Distribution.Version as Cabal
import GHC.Generics (Generic)
import Generics.Deriving.Monoid (memptydefault, mappenddefault)
import Lens.Micro (lens)
import Path
import Prelude hiding (pi, writeFile)
import Stack.Build.Cache
import Stack.Build.Haddock
import Stack.Build.Installed
import Stack.Build.Source
import Stack.BuildPlan
import Stack.Constants
import Stack.Package
import Stack.PackageDump
import Stack.PackageIndex
import Stack.PrettyPrint
import Stack.Types.Build
import Stack.Types.Compiler
import Stack.Types.Config
import Stack.Types.FlagName
import Stack.Types.GhcPkgId
import Stack.Types.Package
import Stack.Types.PackageIdentifier
import Stack.Types.PackageName
import Stack.Types.StackT (StackM)
import Stack.Types.Version
import System.Process.Read (findExecutable)
data PackageInfo
= PIOnlyInstalled InstallLocation Installed
| PIOnlySource PackageSource
| PIBoth PackageSource Installed
deriving (Show)
combineSourceInstalled :: PackageSource
-> (InstallLocation, Installed)
-> PackageInfo
combineSourceInstalled ps (location, installed) =
assert (piiVersion ps == installedVersion installed) $
assert (piiLocation ps == location) $
case location of
-- Always trust something in the snapshot
Snap -> PIOnlyInstalled location installed
Local -> PIBoth ps installed
type CombinedMap = Map PackageName PackageInfo
combineMap :: SourceMap -> InstalledMap -> CombinedMap
combineMap = Map.mergeWithKey
(\_ s i -> Just $ combineSourceInstalled s i)
(fmap PIOnlySource)
(fmap (uncurry PIOnlyInstalled))
data AddDepRes
= ADRToInstall Task
| ADRFound InstallLocation Installed
deriving Show
type ParentMap = MonoidMap PackageName (First Version, [(PackageIdentifier, VersionRange)])
data W = W
{ wFinals :: !(Map PackageName (Either ConstructPlanException Task))
, wInstall :: !(Map Text InstallLocation)
-- ^ executable to be installed, and location where the binary is placed
, wDirty :: !(Map PackageName Text)
-- ^ why a local package is considered dirty
, wDeps :: !(Set PackageName)
-- ^ Packages which count as dependencies
, wWarnings :: !([Text] -> [Text])
-- ^ Warnings
, wParents :: !ParentMap
-- ^ Which packages a given package depends on, along with the package's version
} deriving Generic
instance Monoid W where
mempty = memptydefault
mappend = mappenddefault
type M = RWST
Ctx
W
(Map PackageName (Either ConstructPlanException AddDepRes))
IO
data Ctx = Ctx
{ mbp :: !MiniBuildPlan
, baseConfigOpts :: !BaseConfigOpts
, loadPackage :: !(PackageName -> Version -> Map FlagName Bool -> [Text] -> IO Package)
, combinedMap :: !CombinedMap
, toolToPackages :: !(Cabal.Dependency -> Map PackageName VersionRange)
, ctxEnvConfig :: !EnvConfig
, callStack :: ![PackageName]
, extraToBuild :: !(Set PackageName)
, getVersions :: !(PackageName -> IO (Set Version))
, wanted :: !(Set PackageName)
, localNames :: !(Set PackageName)
, logFunc :: Loc -> LogSource -> LogLevel -> LogStr -> IO ()
}
instance HasPlatform Ctx
instance HasGHCVariant Ctx
instance HasConfig Ctx
instance HasBuildConfigNoLocal Ctx
instance HasBuildConfig Ctx
instance HasEnvConfigNoLocal Ctx where
envConfigNoLocalL = envConfigL.envConfigNoLocalL
instance HasEnvConfig Ctx where
envConfigL = lens ctxEnvConfig (\x y -> x { ctxEnvConfig = y })
constructPlan :: forall env m. (StackM env m, HasEnvConfig env)
=> MiniBuildPlan
-> BaseConfigOpts
-> [LocalPackage]
-> Set PackageName -- ^ additional packages that must be built
-> [DumpPackage () () ()] -- ^ locally registered
-> (PackageName -> Version -> Map FlagName Bool -> [Text] -> IO Package) -- ^ load upstream package
-> SourceMap
-> InstalledMap
-> m Plan
constructPlan mbp0 baseConfigOpts0 locals extraToBuild0 localDumpPkgs loadPackage0 sourceMap installedMap = do
$logDebug "Constructing the build plan"
let locallyRegistered = Map.fromList $ map (dpGhcPkgId &&& dpPackageIdent) localDumpPkgs
getVersions0 <- getPackageVersionsIO
econfig <- view envConfigL
let onWanted = void . addDep False . packageName . lpPackage
let inner = do
mapM_ onWanted $ filter lpWanted locals
mapM_ (addDep False) $ Set.toList extraToBuild0
lf <- askLoggerIO
((), m, W efinals installExes dirtyReason deps warnings parents) <-
liftIO $ runRWST inner (ctx econfig getVersions0 lf) M.empty
mapM_ $logWarn (warnings [])
let toEither (_, Left e) = Left e
toEither (k, Right v) = Right (k, v)
(errlibs, adrs) = partitionEithers $ map toEither $ M.toList m
(errfinals, finals) = partitionEithers $ map toEither $ M.toList efinals
errs = errlibs ++ errfinals
if null errs
then do
let toTask (_, ADRFound _ _) = Nothing
toTask (name, ADRToInstall task) = Just (name, task)
tasks = M.fromList $ mapMaybe toTask adrs
takeSubset =
case boptsCLIBuildSubset $ bcoBuildOptsCLI baseConfigOpts0 of
BSAll -> id
BSOnlySnapshot -> stripLocals
BSOnlyDependencies -> stripNonDeps deps
return $ takeSubset Plan
{ planTasks = tasks
, planFinals = M.fromList finals
, planUnregisterLocal = mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap
, planInstallExes =
if boptsInstallExes $ bcoBuildOpts baseConfigOpts0
then installExes
else Map.empty
}
else do
planDebug $ show errs
stackYaml <- view stackYamlL
$prettyError $ pprintExceptions errs stackYaml parents (wantedLocalPackages locals)
throwM $ ConstructPlanFailed "Plan construction failed."
where
ctx econfig getVersions0 lf = Ctx
{ mbp = mbp0
, baseConfigOpts = baseConfigOpts0
, loadPackage = loadPackage0
, combinedMap = combineMap sourceMap installedMap
, toolToPackages = \(Cabal.Dependency name _) ->
maybe Map.empty (Map.fromSet (const Cabal.anyVersion)) $
Map.lookup (T.pack . packageNameString . fromCabalPackageName $ name) toolMap
, ctxEnvConfig = econfig
, callStack = []
, extraToBuild = extraToBuild0
, getVersions = getVersions0
, wanted = wantedLocalPackages locals
, localNames = Set.fromList $ map (packageName . lpPackage) locals
, logFunc = lf
}
-- TODO Currently, this will only consider and install tools from the
-- snapshot. It will not automatically install build tools from extra-deps
-- or local packages.
toolMap = getToolMap mbp0
-- | Determine which packages to unregister based on the given tasks and
-- already registered local packages
mkUnregisterLocal :: Map PackageName Task
-> Map PackageName Text
-> Map GhcPkgId PackageIdentifier
-> SourceMap
-> Map GhcPkgId (PackageIdentifier, Maybe Text)
mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap =
Map.unions $ map toUnregisterMap $ Map.toList locallyRegistered
where
toUnregisterMap (gid, ident) =
case M.lookup name tasks of
Nothing ->
case M.lookup name sourceMap of
Just (PSUpstream _ Snap _ _ _) -> Map.singleton gid
( ident
, Just "Switching to snapshot installed package"
)
_ -> Map.empty
Just _ -> Map.singleton gid
( ident
, Map.lookup name dirtyReason
)
where
name = packageIdentifierName ident
addFinal :: LocalPackage -> Package -> Bool -> M ()
addFinal lp package isAllInOne = do
depsRes <- addPackageDeps False package
res <- case depsRes of
Left e -> return $ Left e
Right (missing, present, _minLoc) -> do
ctx <- ask
return $ Right Task
{ taskProvides = PackageIdentifier
(packageName package)
(packageVersion package)
, taskConfigOpts = TaskConfigOpts missing $ \missing' ->
let allDeps = Map.union present missing'
in configureOpts
(view envConfigL ctx)
(baseConfigOpts ctx)
allDeps
True -- local
Local
package
, taskPresent = present
, taskType = TTLocal lp
, taskAllInOne = isAllInOne
}
tell mempty { wFinals = Map.singleton (packageName package) res }
addDep :: Bool -- ^ is this being used by a dependency?
-> PackageName
-> M (Either ConstructPlanException AddDepRes)
addDep treatAsDep' name = do
ctx <- ask
let treatAsDep = treatAsDep' || name `Set.notMember` wanted ctx
when treatAsDep $ markAsDep name
m <- get
case Map.lookup name m of
Just res -> do
planDebug $ "addDep: Using cached result for " ++ show name ++ ": " ++ show res
return res
Nothing -> do
res <- if name `elem` callStack ctx
then do
planDebug $ "addDep: Detected cycle " ++ show name ++ ": " ++ show (callStack ctx)
return $ Left $ DependencyCycleDetected $ name : callStack ctx
else local (\ctx' -> ctx' { callStack = name : callStack ctx' }) $ do
let mpackageInfo = Map.lookup name $ combinedMap ctx
planDebug $ "addDep: Package info for " ++ show name ++ ": " ++ show mpackageInfo
case mpackageInfo of
-- TODO look up in the package index and see if there's a
-- recommendation available
Nothing -> return $ Left $ UnknownPackage name
Just (PIOnlyInstalled loc installed) -> do
-- slightly hacky, no flags since they likely won't affect executable names
tellExecutablesUpstream name (installedVersion installed) loc Map.empty
return $ Right $ ADRFound loc installed
Just (PIOnlySource ps) -> do
tellExecutables name ps
installPackage treatAsDep name ps Nothing
Just (PIBoth ps installed) -> do
tellExecutables name ps
installPackage treatAsDep name ps (Just installed)
updateLibMap name res
return res
tellExecutables :: PackageName -> PackageSource -> M ()
tellExecutables _ (PSLocal lp)
| lpWanted lp = tellExecutablesPackage Local $ lpPackage lp
| otherwise = return ()
-- Ignores ghcOptions because they don't matter for enumerating
-- executables.
tellExecutables name (PSUpstream version loc flags _ghcOptions _gitSha) =
tellExecutablesUpstream name version loc flags
tellExecutablesUpstream :: PackageName -> Version -> InstallLocation -> Map FlagName Bool -> M ()
tellExecutablesUpstream name version loc flags = do
ctx <- ask
when (name `Set.member` extraToBuild ctx) $ do
p <- liftIO $ loadPackage ctx name version flags []
tellExecutablesPackage loc p
tellExecutablesPackage :: InstallLocation -> Package -> M ()
tellExecutablesPackage loc p = do
cm <- asks combinedMap
-- Determine which components are enabled so we know which ones to copy
let myComps =
case Map.lookup (packageName p) cm of
Nothing -> assert False Set.empty
Just (PIOnlyInstalled _ _) -> Set.empty
Just (PIOnlySource ps) -> goSource ps
Just (PIBoth ps _) -> goSource ps
goSource (PSLocal lp)
| lpWanted lp = exeComponents (lpComponents lp)
| otherwise = Set.empty
goSource PSUpstream{} = Set.empty
tell mempty { wInstall = Map.fromList $ map (, loc) $ Set.toList $ filterComps myComps $ packageExes p }
where
filterComps myComps x
| Set.null myComps = x
| otherwise = Set.intersection x myComps
installPackage :: Bool -- ^ is this being used by a dependency?
-> PackageName
-> PackageSource
-> Maybe Installed
-> M (Either ConstructPlanException AddDepRes)
installPackage treatAsDep name ps minstalled = do
ctx <- ask
case ps of
PSUpstream version _ flags ghcOptions _ -> do
planDebug $ "installPackage: Doing all-in-one build for upstream package " ++ show name
package <- liftIO $ loadPackage ctx name version flags ghcOptions
resolveDepsAndInstall True treatAsDep ps package minstalled
PSLocal lp ->
case lpTestBench lp of
Nothing -> do
planDebug $ "installPackage: No test / bench component for " ++ show name ++ " so doing an all-in-one build."
resolveDepsAndInstall True treatAsDep ps (lpPackage lp) minstalled
Just tb -> do
-- Attempt to find a plan which performs an all-in-one
-- build. Ignore the writer action + reset the state if
-- it fails.
s <- get
res <- pass $ do
res <- addPackageDeps treatAsDep tb
let writerFunc w = case res of
Left _ -> mempty
_ -> w
return (res, writerFunc)
case res of
Right deps -> do
planDebug $ "installPackage: For " ++ show name ++ ", successfully added package deps"
adr <- installPackageGivenDeps True ps tb minstalled deps
-- FIXME: this redundantly adds the deps (but
-- they'll all just get looked up in the map)
addFinal lp tb True
return $ Right adr
Left _ -> do
-- Reset the state to how it was before
-- attempting to find an all-in-one build
-- plan.
planDebug $ "installPackage: Before trying cyclic plan, resetting lib result map to " ++ show s
put s
-- Otherwise, fall back on building the
-- tests / benchmarks in a separate step.
res' <- resolveDepsAndInstall False treatAsDep ps (lpPackage lp) minstalled
when (isRight res') $ do
-- Insert it into the map so that it's
-- available for addFinal.
updateLibMap name res'
addFinal lp tb False
return res'
resolveDepsAndInstall :: Bool
-> Bool
-> PackageSource
-> Package
-> Maybe Installed
-> M (Either ConstructPlanException AddDepRes)
resolveDepsAndInstall isAllInOne treatAsDep ps package minstalled = do
res <- addPackageDeps treatAsDep package
case res of
Left err -> return $ Left err
Right deps -> liftM Right $ installPackageGivenDeps isAllInOne ps package minstalled deps
installPackageGivenDeps :: Bool
-> PackageSource
-> Package
-> Maybe Installed
-> ( Set PackageIdentifier
, Map PackageIdentifier GhcPkgId
, InstallLocation )
-> M AddDepRes
installPackageGivenDeps isAllInOne ps package minstalled (missing, present, minLoc) = do
let name = packageName package
ctx <- ask
mRightVersionInstalled <- case (minstalled, Set.null missing) of
(Just installed, True) -> do
shouldInstall <- checkDirtiness ps installed package present (wanted ctx)
return $ if shouldInstall then Nothing else Just installed
(Just _, False) -> do
let t = T.intercalate ", " $ map (T.pack . packageNameString . packageIdentifierName) (Set.toList missing)
tell mempty { wDirty = Map.singleton name $ "missing dependencies: " <> addEllipsis t }
return Nothing
(Nothing, _) -> return Nothing
return $ case mRightVersionInstalled of
Just installed -> ADRFound (piiLocation ps) installed
Nothing -> ADRToInstall Task
{ taskProvides = PackageIdentifier
(packageName package)
(packageVersion package)
, taskConfigOpts = TaskConfigOpts missing $ \missing' ->
let allDeps = Map.union present missing'
destLoc = piiLocation ps <> minLoc
in configureOpts
(view envConfigL ctx)
(baseConfigOpts ctx)
allDeps
(psLocal ps)
-- An assertion to check for a recurrence of
-- https://github.com/commercialhaskell/stack/issues/345
(assert (destLoc == piiLocation ps) destLoc)
package
, taskPresent = present
, taskType =
case ps of
PSLocal lp -> TTLocal lp
PSUpstream _ loc _ _ sha -> TTUpstream package (loc <> minLoc) sha
, taskAllInOne = isAllInOne
}
-- Update response in the lib map. If it is an error, and there's
-- already an error about cyclic dependencies, prefer the cyclic error.
updateLibMap :: PackageName -> Either ConstructPlanException AddDepRes -> M ()
updateLibMap name val = modify $ \mp ->
case (M.lookup name mp, val) of
(Just (Left DependencyCycleDetected{}), Left _) -> mp
_ -> M.insert name val mp
addEllipsis :: Text -> Text
addEllipsis t
| T.length t < 100 = t
| otherwise = T.take 97 t <> "..."
addPackageDeps :: Bool -- ^ is this being used by a dependency?
-> Package -> M (Either ConstructPlanException (Set PackageIdentifier, Map PackageIdentifier GhcPkgId, InstallLocation))
addPackageDeps treatAsDep package = do
ctx <- ask
deps' <- packageDepsWithTools package
deps <- forM (Map.toList deps') $ \(depname, range) -> do
eres <- addDep treatAsDep depname
let getLatestApplicable = do
vs <- liftIO $ getVersions ctx depname
return (latestApplicableVersion range vs)
case eres of
Left e -> do
addParent depname range Nothing
let bd =
case e of
UnknownPackage name -> assert (name == depname) NotInBuildPlan
_ -> Couldn'tResolveItsDependencies (packageVersion package)
mlatestApplicable <- getLatestApplicable
return $ Left (depname, (range, mlatestApplicable, bd))
Right adr -> do
addParent depname range Nothing
inRange <- if adrVersion adr `withinRange` range
then return True
else do
let warn_ reason =
tell mempty { wWarnings = (msg:) }
where
msg = T.concat
[ "WARNING: Ignoring out of range dependency"
, reason
, ": "
, T.pack $ packageIdentifierString $ PackageIdentifier depname (adrVersion adr)
, ". "
, T.pack $ packageNameString $ packageName package
, " requires: "
, versionRangeText range
]
allowNewer <- view $ configL.to configAllowNewer
if allowNewer
then do
warn_ " (allow-newer enabled)"
return True
else do
x <- inSnapshot (packageName package) (packageVersion package)
y <- inSnapshot depname (adrVersion adr)
if x && y
then do
warn_ " (trusting snapshot over Hackage revisions)"
return True
else return False
if inRange
then case adr of
ADRToInstall task -> return $ Right
(Set.singleton $ taskProvides task, Map.empty, taskLocation task)
ADRFound loc (Executable _) -> return $ Right
(Set.empty, Map.empty, loc)
ADRFound loc (Library ident gid) -> return $ Right
(Set.empty, Map.singleton ident gid, loc)
else do
mlatestApplicable <- getLatestApplicable
return $ Left (depname, (range, mlatestApplicable, DependencyMismatch $ adrVersion adr))
case partitionEithers deps of
([], pairs) -> return $ Right $ mconcat pairs
(errs, _) -> return $ Left $ DependencyPlanFailures
package
(Map.fromList errs)
where
adrVersion (ADRToInstall task) = packageIdentifierVersion $ taskProvides task
adrVersion (ADRFound _ installed) = installedVersion installed
addParent depname range mversion = tell mempty { wParents = MonoidMap $ M.singleton depname val }
where
val = (First mversion, [(packageIdentifier package, range)])
checkDirtiness :: PackageSource
-> Installed
-> Package
-> Map PackageIdentifier GhcPkgId
-> Set PackageName
-> M Bool
checkDirtiness ps installed package present wanted = do
ctx <- ask
moldOpts <- flip runLoggingT (logFunc ctx) $ tryGetFlagCache installed
let configOpts = configureOpts
(view envConfigL ctx)
(baseConfigOpts ctx)
present
(psLocal ps)
(piiLocation ps) -- should be Local always
package
buildOpts = bcoBuildOpts (baseConfigOpts ctx)
wantConfigCache = ConfigCache
{ configCacheOpts = configOpts
, configCacheDeps = Set.fromList $ Map.elems present
, configCacheComponents =
case ps of
PSLocal lp -> Set.map renderComponent $ lpComponents lp
PSUpstream{} -> Set.empty
, configCacheHaddock =
shouldHaddockPackage buildOpts wanted (packageName package) ||
-- Disabling haddocks when old config had haddocks doesn't make dirty.
maybe False configCacheHaddock moldOpts
}
let mreason =
case moldOpts of
Nothing -> Just "old configure information not found"
Just oldOpts
| Just reason <- describeConfigDiff config oldOpts wantConfigCache -> Just reason
| True <- psForceDirty ps -> Just "--force-dirty specified"
| Just files <- psDirty ps -> Just $ "local file changes: " <>
addEllipsis (T.pack $ unwords $ Set.toList files)
| otherwise -> Nothing
config = view configL ctx
case mreason of
Nothing -> return False
Just reason -> do
tell mempty { wDirty = Map.singleton (packageName package) reason }
return True
describeConfigDiff :: Config -> ConfigCache -> ConfigCache -> Maybe Text
describeConfigDiff config old new
| not (configCacheDeps new `Set.isSubsetOf` configCacheDeps old) = Just "dependencies changed"
| not $ Set.null newComponents =
Just $ "components added: " `T.append` T.intercalate ", "
(map (decodeUtf8With lenientDecode) (Set.toList newComponents))
| not (configCacheHaddock old) && configCacheHaddock new = Just "rebuilding with haddocks"
| oldOpts /= newOpts = Just $ T.pack $ concat
[ "flags changed from "
, show oldOpts
, " to "
, show newOpts
]
| otherwise = Nothing
where
stripGhcOptions =
go
where
go [] = []
go ("--ghc-option":x:xs) = go' Ghc x xs
go ("--ghc-options":x:xs) = go' Ghc x xs
go ((T.stripPrefix "--ghc-option=" -> Just x):xs) = go' Ghc x xs
go ((T.stripPrefix "--ghc-options=" -> Just x):xs) = go' Ghc x xs
go ("--ghcjs-option":x:xs) = go' Ghcjs x xs
go ("--ghcjs-options":x:xs) = go' Ghcjs x xs
go ((T.stripPrefix "--ghcjs-option=" -> Just x):xs) = go' Ghcjs x xs
go ((T.stripPrefix "--ghcjs-options=" -> Just x):xs) = go' Ghcjs x xs
go (x:xs) = x : go xs
go' wc x xs = checkKeepers wc x $ go xs
checkKeepers wc x xs =
case filter isKeeper $ T.words x of
[] -> xs
keepers -> T.pack (compilerOptionsCabalFlag wc) : T.unwords keepers : xs
-- GHC options which affect build results and therefore should always
-- force a rebuild
--
-- For the most part, we only care about options generated by Stack
-- itself
isKeeper = (== "-fhpc") -- more to be added later
userOpts = filter (not . isStackOpt)
. (if configRebuildGhcOptions config
then id
else stripGhcOptions)
. map T.pack
. (\(ConfigureOpts x y) -> x ++ y)
. configCacheOpts
(oldOpts, newOpts) = removeMatching (userOpts old) (userOpts new)
removeMatching (x:xs) (y:ys)
| x == y = removeMatching xs ys
removeMatching xs ys = (xs, ys)
newComponents = configCacheComponents new `Set.difference` configCacheComponents old
psForceDirty :: PackageSource -> Bool
psForceDirty (PSLocal lp) = lpForceDirty lp
psForceDirty PSUpstream{} = False
psDirty :: PackageSource -> Maybe (Set FilePath)
psDirty (PSLocal lp) = lpDirtyFiles lp
psDirty PSUpstream{} = Nothing -- files never change in an upstream package
psLocal :: PackageSource -> Bool
psLocal (PSLocal _) = True
psLocal PSUpstream{} = False
-- | Get all of the dependencies for a given package, including guessed build
-- tool dependencies.
packageDepsWithTools :: Package -> M (Map PackageName VersionRange)
packageDepsWithTools p = do
ctx <- ask
-- TODO: it would be cool to defer these warnings until there's an
-- actual issue building the package.
let toEither (Cabal.Dependency (Cabal.PackageName name) _) mp =
case Map.toList mp of
[] -> Left (NoToolFound name (packageName p))
[_] -> Right mp
xs -> Left (AmbiguousToolsFound name (packageName p) (map fst xs))
(warnings0, toolDeps) =
partitionEithers $
map (\dep -> toEither dep (toolToPackages ctx dep)) (packageTools p)
-- Check whether the tool is on the PATH before warning about it.
warnings <- fmap catMaybes $ forM warnings0 $ \warning -> do
let toolName = case warning of
NoToolFound tool _ -> tool
AmbiguousToolsFound tool _ _ -> tool
config <- view configL
menv <- liftIO $ configEnvOverride config minimalEnvSettings { esIncludeLocals = True }
mfound <- findExecutable menv toolName
case mfound of
Nothing -> return (Just warning)
Just _ -> return Nothing
tell mempty { wWarnings = (map toolWarningText warnings ++) }
when (any isNoToolFound warnings) $ do
let msg = T.unlines
[ "Missing build-tools may be caused by dependencies of the build-tool being overridden by extra-deps."
, "This should be fixed soon - see this issue https://github.com/commercialhaskell/stack/issues/595"
]
tell mempty { wWarnings = (msg:) }
return $ Map.unionsWith intersectVersionRanges
$ packageDeps p
: toolDeps
data ToolWarning
= NoToolFound String PackageName
| AmbiguousToolsFound String PackageName [PackageName]
isNoToolFound :: ToolWarning -> Bool
isNoToolFound NoToolFound{} = True
isNoToolFound _ = False
toolWarningText :: ToolWarning -> Text
toolWarningText (NoToolFound toolName pkgName) =
"No packages found in snapshot which provide a " <>
T.pack (show toolName) <>
" executable, which is a build-tool dependency of " <>
T.pack (show (packageNameString pkgName))
toolWarningText (AmbiguousToolsFound toolName pkgName options) =
"Multiple packages found in snapshot which provide a " <>
T.pack (show toolName) <>
" exeuctable, which is a build-tool dependency of " <>
T.pack (show (packageNameString pkgName)) <>
", so none will be installed.\n" <>
"Here's the list of packages which provide it: " <>
T.intercalate ", " (map packageNameText options) <>
"\nSince there's no good way to choose, you may need to install it manually."
-- | Strip out anything from the @Plan@ intended for the local database
stripLocals :: Plan -> Plan
stripLocals plan = plan
{ planTasks = Map.filter checkTask $ planTasks plan
, planFinals = Map.empty
, planUnregisterLocal = Map.empty
, planInstallExes = Map.filter (/= Local) $ planInstallExes plan
}
where
checkTask task =
case taskType task of
TTLocal _ -> False
TTUpstream _ Local _ -> False
TTUpstream _ Snap _ -> True
stripNonDeps :: Set PackageName -> Plan -> Plan
stripNonDeps deps plan = plan
{ planTasks = Map.filter checkTask $ planTasks plan
, planFinals = Map.empty
, planInstallExes = Map.empty -- TODO maybe don't disable this?
}
where
checkTask task = packageIdentifierName (taskProvides task) `Set.member` deps
markAsDep :: PackageName -> M ()
markAsDep name = tell mempty { wDeps = Set.singleton name }
-- | Is the given package/version combo defined in the snapshot?
inSnapshot :: PackageName -> Version -> M Bool
inSnapshot name version = do
p <- asks mbp
ls <- asks localNames
return $ fromMaybe False $ do
guard $ not $ name `Set.member` ls
mpi <- Map.lookup name (mbpPackages p)
return $ mpiVersion mpi == version
data ConstructPlanException
= DependencyCycleDetected [PackageName]
| DependencyPlanFailures Package (Map PackageName (VersionRange, LatestApplicableVersion, BadDependency))
| UnknownPackage PackageName -- TODO perhaps this constructor will be removed, and BadDependency will handle it all
-- ^ Recommend adding to extra-deps, give a helpful version number?
deriving (Typeable, Eq, Show)
-- | For display purposes only, Nothing if package not found
type LatestApplicableVersion = Maybe Version
-- | Reason why a dependency was not used
data BadDependency
= NotInBuildPlan
| Couldn'tResolveItsDependencies Version
| DependencyMismatch Version
deriving (Typeable, Eq, Show)
-- TODO: Consider intersecting version ranges for multiple deps on a
-- package. This is why VersionRange is in the parent map.
pprintExceptions
:: [ConstructPlanException]
-> Path Abs File
-> ParentMap
-> Set PackageName
-> AnsiDoc
pprintExceptions exceptions stackYaml parentMap wanted =
"While constructing the build plan, the following exceptions were encountered:" <> line <> line <>
mconcat (intersperse (line <> line) (mapMaybe pprintException exceptions')) <> line <>
if Map.null extras then "" else
line <>
"Recommended action: try adding the following to your extra-deps in" <+>
toAnsiDoc (display stackYaml) <> ":" <>
line <>
vsep (map pprintExtra (Map.toList extras)) <>
line <>
line <>
"You may also want to try the 'stack solver' command"
where
exceptions' = nub exceptions
extras = Map.unions $ map getExtras exceptions'
getExtras (DependencyCycleDetected _) = Map.empty
getExtras (UnknownPackage _) = Map.empty
getExtras (DependencyPlanFailures _ m) =
Map.unions $ map go $ Map.toList m
where
go (name, (_range, Just version, NotInBuildPlan)) =
Map.singleton name version
go _ = Map.empty
pprintExtra (name, version) =
fromString (concat ["- ", packageNameString name, "-", versionString version])
pprintException (DependencyCycleDetected pNames) = Just $
"Dependency cycle detected in packages:" <> line <>
indent 4 (encloseSep "[" "]" "," (map (errorRed . fromString . packageNameString) pNames))
pprintException (DependencyPlanFailures pkg (Map.toList -> pDeps)) =
case mapMaybe pprintDep pDeps of
[] -> Nothing
depErrors -> Just $
"In the dependencies for" <+> pkgIdent <>
pprintFlags (packageFlags pkg) <> ":" <> line <>
indent 4 (vsep depErrors) <>
case getShortestDepsPath parentMap wanted (packageName pkg) of
[] -> mempty
[target,_] -> line <> "needed since" <+> displayTargetPkgId target <+> "is a build target."
(target:path) -> line <> "needed due to " <> encloseSep "" "" " -> " pathElems
where
pathElems =
[displayTargetPkgId target] ++
map display path ++
[pkgIdent]
where
pkgIdent = displayCurrentPkgId (packageIdentifier pkg)
-- TODO: optionally show these?
-- Skip these because they are redundant with 'NotInBuildPlan' info.
pprintException (UnknownPackage _) = Nothing
pprintFlags flags
| Map.null flags = ""
| otherwise = parens $ sep $ map pprintFlag $ Map.toList flags
pprintFlag (name, True) = "+" <> fromString (show name)
pprintFlag (name, False) = "-" <> fromString (show name)
pprintDep (name, (range, mlatestApplicable, badDep)) = case badDep of
NotInBuildPlan -> Just $
errorRed (display name) <+>
align ("must match" <+> goodRange <> "," <> softline <>
"but the stack configuration has no specified version" <>
latestApplicable Nothing)
-- TODO: For local packages, suggest editing constraints
DependencyMismatch version -> Just $
displayErrorPkgId (PackageIdentifier name version) <+>
align ("must match" <+> goodRange <>
latestApplicable (Just version))
-- I think the main useful info is these explain why missing
-- packages are needed. Instead lets give the user the shortest
-- path from a target to the package.
Couldn'tResolveItsDependencies _version -> Nothing
where
goodRange = goodGreen (fromString (Cabal.display range))
latestApplicable mversion =
case mlatestApplicable of
Nothing -> ""
Just la
| mlatestApplicable == mversion -> softline <>
"(latest applicable is specified)"
| otherwise -> softline <>
"(latest applicable is " <> goodGreen (display la) <> ")"
-- | Get the shortest reason for the package to be in the build plan. In
-- other words, trace the parent dependencies back to a 'wanted'
-- package.
getShortestDepsPath
:: ParentMap
-> Set PackageName
-> PackageName
-> [PackageIdentifier]
getShortestDepsPath (MonoidMap parentsMap) wanted name =
case M.lookup name parentsMap of
Nothing -> []
Just (_, parents) -> findShortest 256 paths0
where
paths0 = M.fromList $ map (\(ident, _) -> (packageIdentifierName ident, startDepsPath ident)) parents
where
-- The 'paths' map is a map from PackageName to the shortest path
-- found to get there. It is the frontier of our breadth-first
-- search of dependencies.
findShortest :: Int -> Map PackageName DepsPath -> [PackageIdentifier]
findShortest fuel _ | fuel <= 0 =
[PackageIdentifier $(mkPackageName "stack-ran-out-of-jet-fuel") $(mkVersion "0")]
findShortest _ paths | M.null paths = []
findShortest fuel paths =
case targets of
[] -> findShortest (fuel - 1) $ M.fromListWith chooseBest $ concatMap extendPath recurses
_ -> let (DepsPath _ _ path) = minimum (map snd targets) in path
where
(targets, recurses) = partition (\(n, _) -> n `Set.member` wanted) (M.toList paths)
chooseBest :: DepsPath -> DepsPath -> DepsPath
chooseBest x y = if x > y then x else y
-- Extend a path to all its parents.
extendPath :: (PackageName, DepsPath) -> [(PackageName, DepsPath)]
extendPath (n, dp) =
case M.lookup n parentsMap of
Nothing -> []
Just (_, parents) -> map (\(pkgId, _) -> (packageIdentifierName pkgId, extendDepsPath pkgId dp)) parents
data DepsPath = DepsPath
{ dpLength :: Int -- ^ Length of dpPath
, dpNameLength :: Int -- ^ Length of package names combined
, dpPath :: [PackageIdentifier] -- ^ A path where the packages later
-- in the list depend on those that
-- come earlier
}
deriving (Eq, Ord, Show)
startDepsPath :: PackageIdentifier -> DepsPath
startDepsPath ident = DepsPath
{ dpLength = 1
, dpNameLength = T.length (packageNameText (packageIdentifierName ident))
, dpPath = [ident]
}
extendDepsPath :: PackageIdentifier -> DepsPath -> DepsPath
extendDepsPath ident dp = DepsPath
{ dpLength = dpLength dp + 1
, dpNameLength = dpNameLength dp + T.length (packageNameText (packageIdentifierName ident))
, dpPath = [ident]
}
-- Utility newtype wrapper to make make Map's Monoid also use the
-- element's Monoid.
newtype MonoidMap k a = MonoidMap (Map k a)
deriving (Eq, Ord, Read, Show, Generic, Functor)
instance (Ord k, Monoid a) => Monoid (MonoidMap k a) where
mappend (MonoidMap mp1) (MonoidMap mp2) = MonoidMap (M.unionWith mappend mp1 mp2)
mempty = MonoidMap mempty
-- Switch this to 'True' to enable some debugging putStrLn in this module
planDebug :: MonadIO m => String -> m ()
planDebug = if False then liftIO . putStrLn else \_ -> return ()
| AndreasPK/stack | src/Stack/Build/ConstructPlan.hs | bsd-3-clause | 41,493 | 0 | 32 | 14,002 | 9,797 | 4,942 | 4,855 | 808 | 14 |
module SubHask.Category.Trans.Monotonic
( Mon
, unsafeProveMon
-- * The MonT transformer
, MonT (..)
, unsafeProveMonT
)
where
import SubHask.Category
import SubHask.Algebra
import SubHask.SubType
data IncreasingT cat (a :: *) (b :: *) where
IncreasingT :: (Ord_ a, Ord_ b) => cat a b -> IncreasingT cat a b
mkMutable [t| forall cat a b. IncreasingT cat a b |]
instance Category cat => Category (IncreasingT cat) where
type ValidCategory (IncreasingT cat) a = (ValidCategory cat a, Ord_ a)
id = IncreasingT id
(IncreasingT f).(IncreasingT g) = IncreasingT $ f.g
instance Sup a b c => Sup (IncreasingT a) b c
instance Sup b a c => Sup a (IncreasingT b) c
instance (subcat <: cat) => IncreasingT subcat <: cat where
embedType_ = Embed2 (\ (IncreasingT f) -> embedType2 f)
instance Semigroup (cat a b) => Semigroup (IncreasingT cat a b) where
(IncreasingT f)+(IncreasingT g) = IncreasingT $ f+g
instance Abelian (cat a b) => Abelian (IncreasingT cat a b) where
instance Provable (IncreasingT Hask) where
f $$ a = ProofOf $ (f $ unProofOf a)
newtype instance ProofOf (IncreasingT cat) a = ProofOf { unProofOf :: ProofOf_ cat a }
mkMutable [t| forall a cat. ProofOf (IncreasingT cat) a |]
instance Semigroup (ProofOf_ cat a) => Semigroup (ProofOf (IncreasingT cat) a) where
(ProofOf a1)+(ProofOf a2) = ProofOf (a1+a2)
instance Abelian (ProofOf_ cat a) => Abelian (ProofOf (IncreasingT cat) a)
type Increasing a = Increasing_ a
type family Increasing_ a where
Increasing_ ( (cat :: * -> * -> *) a b) = IncreasingT cat a b
proveIncreasing ::
( Ord_ a
, Ord_ b
) => (ProofOf (IncreasingT Hask) a -> ProofOf (IncreasingT Hask) b) -> Increasing (a -> b)
proveIncreasing f = unsafeProveIncreasing $ \a -> unProofOf $ f $ ProofOf a
instance (Ord_ a, Ord_ b) => Hask (ProofOf (IncreasingT Hask) a) (ProofOf (IncreasingT Hask) b) <: (IncreasingT Hask) a b where
embedType_ = Embed0 proveIncreasing
unsafeProveIncreasing ::
( Ord_ a
, Ord_ b
) => (a -> b) -> Increasing (a -> b)
unsafeProveIncreasing = IncreasingT
-- | A convenient specialization of "MonT" and "Hask"
type Mon = MonT Hask
type ValidMon a = Ord a
data MonT cat (a :: *) (b :: *) where
MonT :: (ValidMon a, ValidMon b) => cat a b -> MonT cat a b
unsafeProveMonT :: (ValidMon a, ValidMon b) => cat a b -> MonT cat a b
unsafeProveMonT = MonT
unsafeProveMon :: (ValidMon a, ValidMon b) => cat a b -> MonT cat a b
unsafeProveMon = MonT
instance Category cat => Category (MonT cat) where
type ValidCategory (MonT cat) a = (ValidCategory cat a, ValidMon a)
id = MonT id
(MonT f).(MonT g) = MonT $ f.g
instance Sup a b c => Sup (MonT a) b c
instance Sup b a c => Sup a (MonT b) c
instance (subcat <: cat) => MonT subcat <: cat where
embedType_ = Embed2 (\ (MonT f) -> embedType2 f)
| Drezil/subhask | src/SubHask/Category/Trans/Monotonic.hs | bsd-3-clause | 2,870 | 47 | 14 | 637 | 1,143 | 604 | 539 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
module Example where
import Data.Yaml.Union
import Data.Yaml
import Data.Maybe
readEx :: [FilePath] -> IO Object
readEx fs = fmap fromJust (decodeFiles fs)
main :: IO ()
main =
do en <- readEx ["example/en.yaml"]
de <- readEx ["example/en.yaml", "example/de.yaml"]
print en
print de
| michelk/yaml-overrides.hs | tests/Example.hs | bsd-3-clause | 334 | 0 | 9 | 66 | 111 | 57 | 54 | 13 | 1 |
{-
%
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
TcGenDeriv: Generating derived instance declarations
This module is nominally ``subordinate'' to @TcDeriv@, which is the
``official'' interface to deriving-related things.
This is where we do all the grimy bindings' generation.
-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module TcGenDeriv (
BagDerivStuff, DerivStuff(..),
gen_Eq_binds,
gen_Ord_binds,
gen_Enum_binds,
gen_Bounded_binds,
gen_Ix_binds,
gen_Show_binds,
gen_Read_binds,
gen_Data_binds,
gen_Lift_binds,
gen_Newtype_binds,
mkCoerceClassMethEqn,
genAuxBinds,
ordOpTbl, boxConTbl, litConTbl,
mkRdrFunBind, mkRdrFunBindEC, mkRdrFunBindSE, error_Expr
) where
#include "HsVersions.h"
import GhcPrelude
import TcRnMonad
import HsSyn
import RdrName
import BasicTypes
import DataCon
import Name
import Fingerprint
import Encoding
import DynFlags
import PrelInfo
import FamInst
import FamInstEnv
import PrelNames
import THNames
import Module ( moduleName, moduleNameString
, moduleUnitId, unitIdString )
import MkId ( coerceId )
import PrimOp
import SrcLoc
import TyCon
import TcEnv
import TcType
import TcValidity ( checkValidTyFamEqn )
import TysPrim
import TysWiredIn
import Type
import Class
import VarSet
import VarEnv
import Util
import Var
import Outputable
import Lexeme
import FastString
import Pair
import Bag
import Data.List ( partition, intersperse )
type BagDerivStuff = Bag DerivStuff
data AuxBindSpec
= DerivCon2Tag TyCon -- The con2Tag for given TyCon
| DerivTag2Con TyCon -- ...ditto tag2Con
| DerivMaxTag TyCon -- ...and maxTag
deriving( Eq )
-- All these generate ZERO-BASED tag operations
-- I.e first constructor has tag 0
data DerivStuff -- Please add this auxiliary stuff
= DerivAuxBind AuxBindSpec
-- Generics and DeriveAnyClass
| DerivFamInst FamInst -- New type family instances
-- New top-level auxiliary bindings
| DerivHsBind (LHsBind GhcPs, LSig GhcPs) -- Also used for SYB
{-
************************************************************************
* *
Eq instances
* *
************************************************************************
Here are the heuristics for the code we generate for @Eq@. Let's
assume we have a data type with some (possibly zero) nullary data
constructors and some ordinary, non-nullary ones (the rest, also
possibly zero of them). Here's an example, with both \tr{N}ullary and
\tr{O}rdinary data cons.
data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ...
* For the ordinary constructors (if any), we emit clauses to do The
Usual Thing, e.g.,:
(==) (O1 a1 b1) (O1 a2 b2) = a1 == a2 && b1 == b2
(==) (O2 a1) (O2 a2) = a1 == a2
(==) (O3 a1 b1 c1) (O3 a2 b2 c2) = a1 == a2 && b1 == b2 && c1 == c2
Note: if we're comparing unlifted things, e.g., if 'a1' and
'a2' are Float#s, then we have to generate
case (a1 `eqFloat#` a2) of r -> r
for that particular test.
* If there are a lot of (more than ten) nullary constructors, we emit a
catch-all clause of the form:
(==) a b = case (con2tag_Foo a) of { a# ->
case (con2tag_Foo b) of { b# ->
case (a# ==# b#) of {
r -> r }}}
If con2tag gets inlined this leads to join point stuff, so
it's better to use regular pattern matching if there aren't too
many nullary constructors. "Ten" is arbitrary, of course
* If there aren't any nullary constructors, we emit a simpler
catch-all:
(==) a b = False
* For the @(/=)@ method, we normally just use the default method.
If the type is an enumeration type, we could/may/should? generate
special code that calls @con2tag_Foo@, much like for @(==)@ shown
above.
We thought about doing this: If we're also deriving 'Ord' for this
tycon, we generate:
instance ... Eq (Foo ...) where
(==) a b = case (compare a b) of { _LT -> False; _EQ -> True ; _GT -> False}
(/=) a b = case (compare a b) of { _LT -> True ; _EQ -> False; _GT -> True }
However, that requires that (Ord <whatever>) was put in the context
for the instance decl, which it probably wasn't, so the decls
produced don't get through the typechecker.
-}
gen_Eq_binds :: SrcSpan -> TyCon -> TcM (LHsBinds GhcPs, BagDerivStuff)
gen_Eq_binds loc tycon = do
dflags <- getDynFlags
return (method_binds dflags, aux_binds)
where
all_cons = tyConDataCons tycon
(nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon all_cons
-- If there are ten or more (arbitrary number) nullary constructors,
-- use the con2tag stuff. For small types it's better to use
-- ordinary pattern matching.
(tag_match_cons, pat_match_cons)
| nullary_cons `lengthExceeds` 10 = (nullary_cons, non_nullary_cons)
| otherwise = ([], all_cons)
no_tag_match_cons = null tag_match_cons
fall_through_eqn dflags
| no_tag_match_cons -- All constructors have arguments
= case pat_match_cons of
[] -> [] -- No constructors; no fall-though case
[_] -> [] -- One constructor; no fall-though case
_ -> -- Two or more constructors; add fall-through of
-- (==) _ _ = False
[([nlWildPat, nlWildPat], false_Expr)]
| otherwise -- One or more tag_match cons; add fall-through of
-- extract tags compare for equality
= [([a_Pat, b_Pat],
untag_Expr dflags tycon [(a_RDR,ah_RDR), (b_RDR,bh_RDR)]
(genPrimOpApp (nlHsVar ah_RDR) eqInt_RDR (nlHsVar bh_RDR)))]
aux_binds | no_tag_match_cons = emptyBag
| otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon
method_binds dflags = unitBag (eq_bind dflags)
eq_bind dflags = mkFunBindEC 2 loc eq_RDR (const true_Expr)
(map pats_etc pat_match_cons
++ fall_through_eqn dflags)
------------------------------------------------------------------
pats_etc data_con
= let
con1_pat = nlParPat $ nlConVarPat data_con_RDR as_needed
con2_pat = nlParPat $ nlConVarPat data_con_RDR bs_needed
data_con_RDR = getRdrName data_con
con_arity = length tys_needed
as_needed = take con_arity as_RDRs
bs_needed = take con_arity bs_RDRs
tys_needed = dataConOrigArgTys data_con
in
([con1_pat, con2_pat], nested_eq_expr tys_needed as_needed bs_needed)
where
nested_eq_expr [] [] [] = true_Expr
nested_eq_expr tys as bs
= foldl1 and_Expr (zipWith3Equal "nested_eq" nested_eq tys as bs)
where
nested_eq ty a b = nlHsPar (eq_Expr tycon ty (nlHsVar a) (nlHsVar b))
{-
************************************************************************
* *
Ord instances
* *
************************************************************************
Note [Generating Ord instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose constructors are K1..Kn, and some are nullary.
The general form we generate is:
* Do case on first argument
case a of
K1 ... -> rhs_1
K2 ... -> rhs_2
...
Kn ... -> rhs_n
_ -> nullary_rhs
* To make rhs_i
If i = 1, 2, n-1, n, generate a single case.
rhs_2 case b of
K1 {} -> LT
K2 ... -> ...eq_rhs(K2)...
_ -> GT
Otherwise do a tag compare against the bigger range
(because this is the one most likely to succeed)
rhs_3 case tag b of tb ->
if 3 <# tg then GT
else case b of
K3 ... -> ...eq_rhs(K3)....
_ -> LT
* To make eq_rhs(K), which knows that
a = K a1 .. av
b = K b1 .. bv
we just want to compare (a1,b1) then (a2,b2) etc.
Take care on the last field to tail-call into comparing av,bv
* To make nullary_rhs generate this
case con2tag a of a# ->
case con2tag b of ->
a# `compare` b#
Several special cases:
* Two or fewer nullary constructors: don't generate nullary_rhs
* Be careful about unlifted comparisons. When comparing unboxed
values we can't call the overloaded functions.
See function unliftedOrdOp
Note [Game plan for deriving Ord]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's a bad idea to define only 'compare', and build the other binary
comparisons on top of it; see Trac #2130, #4019. Reason: we don't
want to laboriously make a three-way comparison, only to extract a
binary result, something like this:
(>) (I# x) (I# y) = case <# x y of
True -> False
False -> case ==# x y of
True -> False
False -> True
This being said, we can get away with generating full code only for
'compare' and '<' thus saving us generation of other three operators.
Other operators can be cheaply expressed through '<':
a <= b = not $ b < a
a > b = b < a
a >= b = not $ a < b
So for sufficiently small types (few constructors, or all nullary)
we generate all methods; for large ones we just use 'compare'.
-}
data OrdOp = OrdCompare | OrdLT | OrdLE | OrdGE | OrdGT
------------
ordMethRdr :: OrdOp -> RdrName
ordMethRdr op
= case op of
OrdCompare -> compare_RDR
OrdLT -> lt_RDR
OrdLE -> le_RDR
OrdGE -> ge_RDR
OrdGT -> gt_RDR
------------
ltResult :: OrdOp -> LHsExpr GhcPs
-- Knowing a<b, what is the result for a `op` b?
ltResult OrdCompare = ltTag_Expr
ltResult OrdLT = true_Expr
ltResult OrdLE = true_Expr
ltResult OrdGE = false_Expr
ltResult OrdGT = false_Expr
------------
eqResult :: OrdOp -> LHsExpr GhcPs
-- Knowing a=b, what is the result for a `op` b?
eqResult OrdCompare = eqTag_Expr
eqResult OrdLT = false_Expr
eqResult OrdLE = true_Expr
eqResult OrdGE = true_Expr
eqResult OrdGT = false_Expr
------------
gtResult :: OrdOp -> LHsExpr GhcPs
-- Knowing a>b, what is the result for a `op` b?
gtResult OrdCompare = gtTag_Expr
gtResult OrdLT = false_Expr
gtResult OrdLE = false_Expr
gtResult OrdGE = true_Expr
gtResult OrdGT = true_Expr
------------
gen_Ord_binds :: SrcSpan -> TyCon -> TcM (LHsBinds GhcPs, BagDerivStuff)
gen_Ord_binds loc tycon = do
dflags <- getDynFlags
return $ if null tycon_data_cons -- No data-cons => invoke bale-out case
then ( unitBag $ mkFunBindEC 2 loc compare_RDR (const eqTag_Expr) []
, emptyBag)
else ( unitBag (mkOrdOp dflags OrdCompare) `unionBags` other_ops dflags
, aux_binds)
where
aux_binds | single_con_type = emptyBag
| otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon
-- Note [Game plan for deriving Ord]
other_ops dflags
| (last_tag - first_tag) <= 2 -- 1-3 constructors
|| null non_nullary_cons -- Or it's an enumeration
= listToBag [mkOrdOp dflags OrdLT, lE, gT, gE]
| otherwise
= emptyBag
negate_expr = nlHsApp (nlHsVar not_RDR)
lE = mk_easy_FunBind loc le_RDR [a_Pat, b_Pat] $
negate_expr (nlHsApp (nlHsApp (nlHsVar lt_RDR) b_Expr) a_Expr)
gT = mk_easy_FunBind loc gt_RDR [a_Pat, b_Pat] $
nlHsApp (nlHsApp (nlHsVar lt_RDR) b_Expr) a_Expr
gE = mk_easy_FunBind loc ge_RDR [a_Pat, b_Pat] $
negate_expr (nlHsApp (nlHsApp (nlHsVar lt_RDR) a_Expr) b_Expr)
get_tag con = dataConTag con - fIRST_TAG
-- We want *zero-based* tags, because that's what
-- con2Tag returns (generated by untag_Expr)!
tycon_data_cons = tyConDataCons tycon
single_con_type = isSingleton tycon_data_cons
(first_con : _) = tycon_data_cons
(last_con : _) = reverse tycon_data_cons
first_tag = get_tag first_con
last_tag = get_tag last_con
(nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon tycon_data_cons
mkOrdOp :: DynFlags -> OrdOp -> LHsBind GhcPs
-- Returns a binding op a b = ... compares a and b according to op ....
mkOrdOp dflags op = mk_easy_FunBind loc (ordMethRdr op) [a_Pat, b_Pat]
(mkOrdOpRhs dflags op)
mkOrdOpRhs :: DynFlags -> OrdOp -> LHsExpr GhcPs
mkOrdOpRhs dflags op -- RHS for comparing 'a' and 'b' according to op
| nullary_cons `lengthAtMost` 2 -- Two nullary or fewer, so use cases
= nlHsCase (nlHsVar a_RDR) $
map (mkOrdOpAlt dflags op) tycon_data_cons
-- i.e. case a of { C1 x y -> case b of C1 x y -> ....compare x,y...
-- C2 x -> case b of C2 x -> ....comopare x.... }
| null non_nullary_cons -- All nullary, so go straight to comparing tags
= mkTagCmp dflags op
| otherwise -- Mixed nullary and non-nullary
= nlHsCase (nlHsVar a_RDR) $
(map (mkOrdOpAlt dflags op) non_nullary_cons
++ [mkHsCaseAlt nlWildPat (mkTagCmp dflags op)])
mkOrdOpAlt :: DynFlags -> OrdOp -> DataCon
-> LMatch GhcPs (LHsExpr GhcPs)
-- Make the alternative (Ki a1 a2 .. av ->
mkOrdOpAlt dflags op data_con
= mkHsCaseAlt (nlConVarPat data_con_RDR as_needed)
(mkInnerRhs dflags op data_con)
where
as_needed = take (dataConSourceArity data_con) as_RDRs
data_con_RDR = getRdrName data_con
mkInnerRhs dflags op data_con
| single_con_type
= nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con ]
| tag == first_tag
= nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con
, mkHsCaseAlt nlWildPat (ltResult op) ]
| tag == last_tag
= nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con
, mkHsCaseAlt nlWildPat (gtResult op) ]
| tag == first_tag + 1
= nlHsCase (nlHsVar b_RDR) [ mkHsCaseAlt (nlConWildPat first_con)
(gtResult op)
, mkInnerEqAlt op data_con
, mkHsCaseAlt nlWildPat (ltResult op) ]
| tag == last_tag - 1
= nlHsCase (nlHsVar b_RDR) [ mkHsCaseAlt (nlConWildPat last_con)
(ltResult op)
, mkInnerEqAlt op data_con
, mkHsCaseAlt nlWildPat (gtResult op) ]
| tag > last_tag `div` 2 -- lower range is larger
= untag_Expr dflags tycon [(b_RDR, bh_RDR)] $
nlHsIf (genPrimOpApp (nlHsVar bh_RDR) ltInt_RDR tag_lit)
(gtResult op) $ -- Definitely GT
nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con
, mkHsCaseAlt nlWildPat (ltResult op) ]
| otherwise -- upper range is larger
= untag_Expr dflags tycon [(b_RDR, bh_RDR)] $
nlHsIf (genPrimOpApp (nlHsVar bh_RDR) gtInt_RDR tag_lit)
(ltResult op) $ -- Definitely LT
nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con
, mkHsCaseAlt nlWildPat (gtResult op) ]
where
tag = get_tag data_con
tag_lit = noLoc (HsLit (HsIntPrim NoSourceText (toInteger tag)))
mkInnerEqAlt :: OrdOp -> DataCon -> LMatch GhcPs (LHsExpr GhcPs)
-- First argument 'a' known to be built with K
-- Returns a case alternative Ki b1 b2 ... bv -> compare (a1,a2,...) with (b1,b2,...)
mkInnerEqAlt op data_con
= mkHsCaseAlt (nlConVarPat data_con_RDR bs_needed) $
mkCompareFields tycon op (dataConOrigArgTys data_con)
where
data_con_RDR = getRdrName data_con
bs_needed = take (dataConSourceArity data_con) bs_RDRs
mkTagCmp :: DynFlags -> OrdOp -> LHsExpr GhcPs
-- Both constructors known to be nullary
-- generates (case data2Tag a of a# -> case data2Tag b of b# -> a# `op` b#
mkTagCmp dflags op =
untag_Expr dflags tycon[(a_RDR, ah_RDR),(b_RDR, bh_RDR)] $
unliftedOrdOp tycon intPrimTy op ah_RDR bh_RDR
mkCompareFields :: TyCon -> OrdOp -> [Type] -> LHsExpr GhcPs
-- Generates nested comparisons for (a1,a2...) against (b1,b2,...)
-- where the ai,bi have the given types
mkCompareFields tycon op tys
= go tys as_RDRs bs_RDRs
where
go [] _ _ = eqResult op
go [ty] (a:_) (b:_)
| isUnliftedType ty = unliftedOrdOp tycon ty op a b
| otherwise = genOpApp (nlHsVar a) (ordMethRdr op) (nlHsVar b)
go (ty:tys) (a:as) (b:bs) = mk_compare ty a b
(ltResult op)
(go tys as bs)
(gtResult op)
go _ _ _ = panic "mkCompareFields"
-- (mk_compare ty a b) generates
-- (case (compare a b) of { LT -> <lt>; EQ -> <eq>; GT -> <bt> })
-- but with suitable special cases for
mk_compare ty a b lt eq gt
| isUnliftedType ty
= unliftedCompare lt_op eq_op a_expr b_expr lt eq gt
| otherwise
= nlHsCase (nlHsPar (nlHsApp (nlHsApp (nlHsVar compare_RDR) a_expr) b_expr))
[mkHsCaseAlt (nlNullaryConPat ltTag_RDR) lt,
mkHsCaseAlt (nlNullaryConPat eqTag_RDR) eq,
mkHsCaseAlt (nlNullaryConPat gtTag_RDR) gt]
where
a_expr = nlHsVar a
b_expr = nlHsVar b
(lt_op, _, eq_op, _, _) = primOrdOps "Ord" tycon ty
unliftedOrdOp :: TyCon -> Type -> OrdOp -> RdrName -> RdrName -> LHsExpr GhcPs
unliftedOrdOp tycon ty op a b
= case op of
OrdCompare -> unliftedCompare lt_op eq_op a_expr b_expr
ltTag_Expr eqTag_Expr gtTag_Expr
OrdLT -> wrap lt_op
OrdLE -> wrap le_op
OrdGE -> wrap ge_op
OrdGT -> wrap gt_op
where
(lt_op, le_op, eq_op, ge_op, gt_op) = primOrdOps "Ord" tycon ty
wrap prim_op = genPrimOpApp a_expr prim_op b_expr
a_expr = nlHsVar a
b_expr = nlHsVar b
unliftedCompare :: RdrName -> RdrName
-> LHsExpr GhcPs -> LHsExpr GhcPs -- What to cmpare
-> LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
-- Three results
-> LHsExpr GhcPs
-- Return (if a < b then lt else if a == b then eq else gt)
unliftedCompare lt_op eq_op a_expr b_expr lt eq gt
= nlHsIf (ascribeBool $ genPrimOpApp a_expr lt_op b_expr) lt $
-- Test (<) first, not (==), because the latter
-- is true less often, so putting it first would
-- mean more tests (dynamically)
nlHsIf (ascribeBool $ genPrimOpApp a_expr eq_op b_expr) eq gt
where
ascribeBool e = nlExprWithTySig e boolTy
nlConWildPat :: DataCon -> LPat GhcPs
-- The pattern (K {})
nlConWildPat con = noLoc (ConPatIn (noLoc (getRdrName con))
(RecCon (HsRecFields { rec_flds = []
, rec_dotdot = Nothing })))
{-
************************************************************************
* *
Enum instances
* *
************************************************************************
@Enum@ can only be derived for enumeration types. For a type
\begin{verbatim}
data Foo ... = N1 | N2 | ... | Nn
\end{verbatim}
we use both @con2tag_Foo@ and @tag2con_Foo@ functions, as well as a
@maxtag_Foo@ variable (all generated by @gen_tag_n_con_binds@).
\begin{verbatim}
instance ... Enum (Foo ...) where
succ x = toEnum (1 + fromEnum x)
pred x = toEnum (fromEnum x - 1)
toEnum i = tag2con_Foo i
enumFrom a = map tag2con_Foo [con2tag_Foo a .. maxtag_Foo]
-- or, really...
enumFrom a
= case con2tag_Foo a of
a# -> map tag2con_Foo (enumFromTo (I# a#) maxtag_Foo)
enumFromThen a b
= map tag2con_Foo [con2tag_Foo a, con2tag_Foo b .. maxtag_Foo]
-- or, really...
enumFromThen a b
= case con2tag_Foo a of { a# ->
case con2tag_Foo b of { b# ->
map tag2con_Foo (enumFromThenTo (I# a#) (I# b#) maxtag_Foo)
}}
\end{verbatim}
For @enumFromTo@ and @enumFromThenTo@, we use the default methods.
-}
gen_Enum_binds :: SrcSpan -> TyCon -> TcM (LHsBinds GhcPs, BagDerivStuff)
gen_Enum_binds loc tycon = do
dflags <- getDynFlags
return (method_binds dflags, aux_binds)
where
method_binds dflags = listToBag
[ succ_enum dflags
, pred_enum dflags
, to_enum dflags
, enum_from dflags
, enum_from_then dflags
, from_enum dflags
]
aux_binds = listToBag $ map DerivAuxBind
[DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon]
occ_nm = getOccString tycon
succ_enum dflags
= mk_easy_FunBind loc succ_RDR [a_Pat] $
untag_Expr dflags tycon [(a_RDR, ah_RDR)] $
nlHsIf (nlHsApps eq_RDR [nlHsVar (maxtag_RDR dflags tycon),
nlHsVarApps intDataCon_RDR [ah_RDR]])
(illegal_Expr "succ" occ_nm "tried to take `succ' of last tag in enumeration")
(nlHsApp (nlHsVar (tag2con_RDR dflags tycon))
(nlHsApps plus_RDR [nlHsVarApps intDataCon_RDR [ah_RDR],
nlHsIntLit 1]))
pred_enum dflags
= mk_easy_FunBind loc pred_RDR [a_Pat] $
untag_Expr dflags tycon [(a_RDR, ah_RDR)] $
nlHsIf (nlHsApps eq_RDR [nlHsIntLit 0,
nlHsVarApps intDataCon_RDR [ah_RDR]])
(illegal_Expr "pred" occ_nm "tried to take `pred' of first tag in enumeration")
(nlHsApp (nlHsVar (tag2con_RDR dflags tycon))
(nlHsApps plus_RDR
[ nlHsVarApps intDataCon_RDR [ah_RDR]
, nlHsLit (HsInt def (mkIntegralLit (-1 :: Int)))]))
to_enum dflags
= mk_easy_FunBind loc toEnum_RDR [a_Pat] $
nlHsIf (nlHsApps and_RDR
[nlHsApps ge_RDR [nlHsVar a_RDR, nlHsIntLit 0],
nlHsApps le_RDR [ nlHsVar a_RDR
, nlHsVar (maxtag_RDR dflags tycon)]])
(nlHsVarApps (tag2con_RDR dflags tycon) [a_RDR])
(illegal_toEnum_tag occ_nm (maxtag_RDR dflags tycon))
enum_from dflags
= mk_easy_FunBind loc enumFrom_RDR [a_Pat] $
untag_Expr dflags tycon [(a_RDR, ah_RDR)] $
nlHsApps map_RDR
[nlHsVar (tag2con_RDR dflags tycon),
nlHsPar (enum_from_to_Expr
(nlHsVarApps intDataCon_RDR [ah_RDR])
(nlHsVar (maxtag_RDR dflags tycon)))]
enum_from_then dflags
= mk_easy_FunBind loc enumFromThen_RDR [a_Pat, b_Pat] $
untag_Expr dflags tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)] $
nlHsApp (nlHsVarApps map_RDR [tag2con_RDR dflags tycon]) $
nlHsPar (enum_from_then_to_Expr
(nlHsVarApps intDataCon_RDR [ah_RDR])
(nlHsVarApps intDataCon_RDR [bh_RDR])
(nlHsIf (nlHsApps gt_RDR [nlHsVarApps intDataCon_RDR [ah_RDR],
nlHsVarApps intDataCon_RDR [bh_RDR]])
(nlHsIntLit 0)
(nlHsVar (maxtag_RDR dflags tycon))
))
from_enum dflags
= mk_easy_FunBind loc fromEnum_RDR [a_Pat] $
untag_Expr dflags tycon [(a_RDR, ah_RDR)] $
(nlHsVarApps intDataCon_RDR [ah_RDR])
{-
************************************************************************
* *
Bounded instances
* *
************************************************************************
-}
gen_Bounded_binds :: SrcSpan -> TyCon -> (LHsBinds GhcPs, BagDerivStuff)
gen_Bounded_binds loc tycon
| isEnumerationTyCon tycon
= (listToBag [ min_bound_enum, max_bound_enum ], emptyBag)
| otherwise
= ASSERT(isSingleton data_cons)
(listToBag [ min_bound_1con, max_bound_1con ], emptyBag)
where
data_cons = tyConDataCons tycon
----- enum-flavored: ---------------------------
min_bound_enum = mkHsVarBind loc minBound_RDR (nlHsVar data_con_1_RDR)
max_bound_enum = mkHsVarBind loc maxBound_RDR (nlHsVar data_con_N_RDR)
data_con_1 = head data_cons
data_con_N = last data_cons
data_con_1_RDR = getRdrName data_con_1
data_con_N_RDR = getRdrName data_con_N
----- single-constructor-flavored: -------------
arity = dataConSourceArity data_con_1
min_bound_1con = mkHsVarBind loc minBound_RDR $
nlHsVarApps data_con_1_RDR (nOfThem arity minBound_RDR)
max_bound_1con = mkHsVarBind loc maxBound_RDR $
nlHsVarApps data_con_1_RDR (nOfThem arity maxBound_RDR)
{-
************************************************************************
* *
Ix instances
* *
************************************************************************
Deriving @Ix@ is only possible for enumeration types and
single-constructor types. We deal with them in turn.
For an enumeration type, e.g.,
\begin{verbatim}
data Foo ... = N1 | N2 | ... | Nn
\end{verbatim}
things go not too differently from @Enum@:
\begin{verbatim}
instance ... Ix (Foo ...) where
range (a, b)
= map tag2con_Foo [con2tag_Foo a .. con2tag_Foo b]
-- or, really...
range (a, b)
= case (con2tag_Foo a) of { a# ->
case (con2tag_Foo b) of { b# ->
map tag2con_Foo (enumFromTo (I# a#) (I# b#))
}}
-- Generate code for unsafeIndex, because using index leads
-- to lots of redundant range tests
unsafeIndex c@(a, b) d
= case (con2tag_Foo d -# con2tag_Foo a) of
r# -> I# r#
inRange (a, b) c
= let
p_tag = con2tag_Foo c
in
p_tag >= con2tag_Foo a && p_tag <= con2tag_Foo b
-- or, really...
inRange (a, b) c
= case (con2tag_Foo a) of { a_tag ->
case (con2tag_Foo b) of { b_tag ->
case (con2tag_Foo c) of { c_tag ->
if (c_tag >=# a_tag) then
c_tag <=# b_tag
else
False
}}}
\end{verbatim}
(modulo suitable case-ification to handle the unlifted tags)
For a single-constructor type (NB: this includes all tuples), e.g.,
\begin{verbatim}
data Foo ... = MkFoo a b Int Double c c
\end{verbatim}
we follow the scheme given in Figure~19 of the Haskell~1.2 report
(p.~147).
-}
gen_Ix_binds :: SrcSpan -> TyCon -> TcM (LHsBinds GhcPs, BagDerivStuff)
gen_Ix_binds loc tycon = do
dflags <- getDynFlags
return $ if isEnumerationTyCon tycon
then (enum_ixes dflags, listToBag $ map DerivAuxBind
[DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon])
else (single_con_ixes, unitBag (DerivAuxBind (DerivCon2Tag tycon)))
where
--------------------------------------------------------------
enum_ixes dflags = listToBag
[ enum_range dflags
, enum_index dflags
, enum_inRange dflags
]
enum_range dflags
= mk_easy_FunBind loc range_RDR [nlTuplePat [a_Pat, b_Pat] Boxed] $
untag_Expr dflags tycon [(a_RDR, ah_RDR)] $
untag_Expr dflags tycon [(b_RDR, bh_RDR)] $
nlHsApp (nlHsVarApps map_RDR [tag2con_RDR dflags tycon]) $
nlHsPar (enum_from_to_Expr
(nlHsVarApps intDataCon_RDR [ah_RDR])
(nlHsVarApps intDataCon_RDR [bh_RDR]))
enum_index dflags
= mk_easy_FunBind loc unsafeIndex_RDR
[noLoc (AsPat (noLoc c_RDR)
(nlTuplePat [a_Pat, nlWildPat] Boxed)),
d_Pat] (
untag_Expr dflags tycon [(a_RDR, ah_RDR)] (
untag_Expr dflags tycon [(d_RDR, dh_RDR)] (
let
rhs = nlHsVarApps intDataCon_RDR [c_RDR]
in
nlHsCase
(genOpApp (nlHsVar dh_RDR) minusInt_RDR (nlHsVar ah_RDR))
[mkHsCaseAlt (nlVarPat c_RDR) rhs]
))
)
-- This produces something like `(ch >= ah) && (ch <= bh)`
enum_inRange dflags
= mk_easy_FunBind loc inRange_RDR [nlTuplePat [a_Pat, b_Pat] Boxed, c_Pat] $
untag_Expr dflags tycon [(a_RDR, ah_RDR)] (
untag_Expr dflags tycon [(b_RDR, bh_RDR)] (
untag_Expr dflags tycon [(c_RDR, ch_RDR)] (
-- This used to use `if`, which interacts badly with RebindableSyntax.
-- See #11396.
nlHsApps and_RDR
[ genPrimOpApp (nlHsVar ch_RDR) geInt_RDR (nlHsVar ah_RDR)
, genPrimOpApp (nlHsVar ch_RDR) leInt_RDR (nlHsVar bh_RDR)
]
)))
--------------------------------------------------------------
single_con_ixes
= listToBag [single_con_range, single_con_index, single_con_inRange]
data_con
= case tyConSingleDataCon_maybe tycon of -- just checking...
Nothing -> panic "get_Ix_binds"
Just dc -> dc
con_arity = dataConSourceArity data_con
data_con_RDR = getRdrName data_con
as_needed = take con_arity as_RDRs
bs_needed = take con_arity bs_RDRs
cs_needed = take con_arity cs_RDRs
con_pat xs = nlConVarPat data_con_RDR xs
con_expr = nlHsVarApps data_con_RDR cs_needed
--------------------------------------------------------------
single_con_range
= mk_easy_FunBind loc range_RDR
[nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed] $
noLoc (mkHsComp ListComp stmts con_expr)
where
stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed
mk_qual a b c = noLoc $ mkBindStmt (nlVarPat c)
(nlHsApp (nlHsVar range_RDR)
(mkLHsVarTuple [a,b]))
----------------
single_con_index
= mk_easy_FunBind loc unsafeIndex_RDR
[nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed,
con_pat cs_needed]
-- We need to reverse the order we consider the components in
-- so that
-- range (l,u) !! index (l,u) i == i -- when i is in range
-- (from http://haskell.org/onlinereport/ix.html) holds.
(mk_index (reverse $ zip3 as_needed bs_needed cs_needed))
where
-- index (l1,u1) i1 + rangeSize (l1,u1) * (index (l2,u2) i2 + ...)
mk_index [] = nlHsIntLit 0
mk_index [(l,u,i)] = mk_one l u i
mk_index ((l,u,i) : rest)
= genOpApp (
mk_one l u i
) plus_RDR (
genOpApp (
(nlHsApp (nlHsVar unsafeRangeSize_RDR)
(mkLHsVarTuple [l,u]))
) times_RDR (mk_index rest)
)
mk_one l u i
= nlHsApps unsafeIndex_RDR [mkLHsVarTuple [l,u], nlHsVar i]
------------------
single_con_inRange
= mk_easy_FunBind loc inRange_RDR
[nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed,
con_pat cs_needed] $
if con_arity == 0
-- If the product type has no fields, inRange is trivially true
-- (see Trac #12853).
then true_Expr
else foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range
as_needed bs_needed cs_needed)
where
in_range a b c = nlHsApps inRange_RDR [mkLHsVarTuple [a,b], nlHsVar c]
{-
************************************************************************
* *
Read instances
* *
************************************************************************
Example
infix 4 %%
data T = Int %% Int
| T1 { f1 :: Int }
| T2 T
instance Read T where
readPrec =
parens
( prec 4 (
do x <- ReadP.step Read.readPrec
expectP (Symbol "%%")
y <- ReadP.step Read.readPrec
return (x %% y))
+++
prec (appPrec+1) (
-- Note the "+1" part; "T2 T1 {f1=3}" should parse ok
-- Record construction binds even more tightly than application
do expectP (Ident "T1")
expectP (Punc '{')
x <- Read.readField "f1" (ReadP.reset readPrec)
expectP (Punc '}')
return (T1 { f1 = x }))
+++
prec appPrec (
do expectP (Ident "T2")
x <- ReadP.step Read.readPrec
return (T2 x))
)
readListPrec = readListPrecDefault
readList = readListDefault
Note [Use expectP]
~~~~~~~~~~~~~~~~~~
Note that we use
expectP (Ident "T1")
rather than
Ident "T1" <- lexP
The latter desugares to inline code for matching the Ident and the
string, and this can be very voluminous. The former is much more
compact. Cf Trac #7258, although that also concerned non-linearity in
the occurrence analyser, a separate issue.
Note [Read for empty data types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What should we get for this? (Trac #7931)
data Emp deriving( Read ) -- No data constructors
Here we want
read "[]" :: [Emp] to succeed, returning []
So we do NOT want
instance Read Emp where
readPrec = error "urk"
Rather we want
instance Read Emp where
readPred = pfail -- Same as choose []
Because 'pfail' allows the parser to backtrack, but 'error' doesn't.
These instances are also useful for Read (Either Int Emp), where
we want to be able to parse (Left 3) just fine.
-}
gen_Read_binds :: (Name -> Fixity) -> SrcSpan -> TyCon
-> (LHsBinds GhcPs, BagDerivStuff)
gen_Read_binds get_fixity loc tycon
= (listToBag [read_prec, default_readlist, default_readlistprec], emptyBag)
where
-----------------------------------------------------------------------
default_readlist
= mkHsVarBind loc readList_RDR (nlHsVar readListDefault_RDR)
default_readlistprec
= mkHsVarBind loc readListPrec_RDR (nlHsVar readListPrecDefault_RDR)
-----------------------------------------------------------------------
data_cons = tyConDataCons tycon
(nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon data_cons
read_prec = mkHsVarBind loc readPrec_RDR rhs
where
rhs | null data_cons -- See Note [Read for empty data types]
= nlHsVar pfail_RDR
| otherwise
= nlHsApp (nlHsVar parens_RDR)
(foldr1 mk_alt (read_nullary_cons ++
read_non_nullary_cons))
read_non_nullary_cons = map read_non_nullary_con non_nullary_cons
read_nullary_cons
= case nullary_cons of
[] -> []
[con] -> [nlHsDo DoExpr (match_con con ++ [noLoc $ mkLastStmt (result_expr con [])])]
_ -> [nlHsApp (nlHsVar choose_RDR)
(nlList (map mk_pair nullary_cons))]
-- NB For operators the parens around (:=:) are matched by the
-- enclosing "parens" call, so here we must match the naked
-- data_con_str con
match_con con | isSym con_str = [symbol_pat con_str]
| otherwise = ident_h_pat con_str
where
con_str = data_con_str con
-- For nullary constructors we must match Ident s for normal constrs
-- and Symbol s for operators
mk_pair con = mkLHsTupleExpr [nlHsLit (mkHsString (data_con_str con)),
result_expr con []]
read_non_nullary_con data_con
| is_infix = mk_parser infix_prec infix_stmts body
| is_record = mk_parser record_prec record_stmts body
-- Using these two lines instead allows the derived
-- read for infix and record bindings to read the prefix form
-- | is_infix = mk_alt prefix_parser (mk_parser infix_prec infix_stmts body)
-- | is_record = mk_alt prefix_parser (mk_parser record_prec record_stmts body)
| otherwise = prefix_parser
where
body = result_expr data_con as_needed
con_str = data_con_str data_con
prefix_parser = mk_parser prefix_prec prefix_stmts body
read_prefix_con
| isSym con_str = [read_punc "(", symbol_pat con_str, read_punc ")"]
| otherwise = ident_h_pat con_str
read_infix_con
| isSym con_str = [symbol_pat con_str]
| otherwise = [read_punc "`"] ++ ident_h_pat con_str ++ [read_punc "`"]
prefix_stmts -- T a b c
= read_prefix_con ++ read_args
infix_stmts -- a %% b, or a `T` b
= [read_a1]
++ read_infix_con
++ [read_a2]
record_stmts -- T { f1 = a, f2 = b }
= read_prefix_con
++ [read_punc "{"]
++ concat (intersperse [read_punc ","] field_stmts)
++ [read_punc "}"]
field_stmts = zipWithEqual "lbl_stmts" read_field labels as_needed
con_arity = dataConSourceArity data_con
labels = map flLabel $ dataConFieldLabels data_con
dc_nm = getName data_con
is_infix = dataConIsInfix data_con
is_record = labels `lengthExceeds` 0
as_needed = take con_arity as_RDRs
read_args = zipWithEqual "gen_Read_binds" read_arg as_needed (dataConOrigArgTys data_con)
(read_a1:read_a2:_) = read_args
prefix_prec = appPrecedence
infix_prec = getPrecedence get_fixity dc_nm
record_prec = appPrecedence + 1 -- Record construction binds even more tightly
-- than application; e.g. T2 T1 {x=2} means T2 (T1 {x=2})
------------------------------------------------------------------------
-- Helpers
------------------------------------------------------------------------
mk_alt e1 e2 = genOpApp e1 alt_RDR e2 -- e1 +++ e2
mk_parser p ss b = nlHsApps prec_RDR [nlHsIntLit p -- prec p (do { ss ; b })
, nlHsDo DoExpr (ss ++ [noLoc $ mkLastStmt b])]
con_app con as = nlHsVarApps (getRdrName con) as -- con as
result_expr con as = nlHsApp (nlHsVar returnM_RDR) (con_app con as) -- return (con as)
-- For constructors and field labels ending in '#', we hackily
-- let the lexer generate two tokens, and look for both in sequence
-- Thus [Ident "I"; Symbol "#"]. See Trac #5041
ident_h_pat s | Just (ss, '#') <- snocView s = [ ident_pat ss, symbol_pat "#" ]
| otherwise = [ ident_pat s ]
bindLex pat = noLoc (mkBodyStmt (nlHsApp (nlHsVar expectP_RDR) pat)) -- expectP p
-- See Note [Use expectP]
ident_pat s = bindLex $ nlHsApps ident_RDR [nlHsLit (mkHsString s)] -- expectP (Ident "foo")
symbol_pat s = bindLex $ nlHsApps symbol_RDR [nlHsLit (mkHsString s)] -- expectP (Symbol ">>")
read_punc c = bindLex $ nlHsApps punc_RDR [nlHsLit (mkHsString c)] -- expectP (Punc "<")
data_con_str con = occNameString (getOccName con)
read_arg a ty = ASSERT( not (isUnliftedType ty) )
noLoc (mkBindStmt (nlVarPat a) (nlHsVarApps step_RDR [readPrec_RDR]))
-- When reading field labels we might encounter
-- a = 3
-- _a = 3
-- or (#) = 4
-- Note the parens!
read_field lbl a =
[noLoc
(mkBindStmt
(nlVarPat a)
(nlHsApps
read_field
[ nlHsLit (mkHsString lbl_str)
, nlHsVarApps reset_RDR [readPrec_RDR]
]
)
)
]
where
lbl_str = unpackFS lbl
read_field
| isSym lbl_str = readSymField_RDR
| otherwise = readField_RDR
{-
************************************************************************
* *
Show instances
* *
************************************************************************
Example
infixr 5 :^:
data Tree a = Leaf a | Tree a :^: Tree a
instance (Show a) => Show (Tree a) where
showsPrec d (Leaf m) = showParen (d > app_prec) showStr
where
showStr = showString "Leaf " . showsPrec (app_prec+1) m
showsPrec d (u :^: v) = showParen (d > up_prec) showStr
where
showStr = showsPrec (up_prec+1) u .
showString " :^: " .
showsPrec (up_prec+1) v
-- Note: right-associativity of :^: ignored
up_prec = 5 -- Precedence of :^:
app_prec = 10 -- Application has precedence one more than
-- the most tightly-binding operator
-}
gen_Show_binds :: (Name -> Fixity) -> SrcSpan -> TyCon
-> (LHsBinds GhcPs, BagDerivStuff)
gen_Show_binds get_fixity loc tycon
= (unitBag shows_prec, emptyBag)
where
data_cons = tyConDataCons tycon
shows_prec = mkFunBindEC 2 loc showsPrec_RDR id (map pats_etc data_cons)
comma_space = nlHsVar showCommaSpace_RDR
pats_etc data_con
| nullary_con = -- skip the showParen junk...
ASSERT(null bs_needed)
([nlWildPat, con_pat], mk_showString_app op_con_str)
| otherwise =
([a_Pat, con_pat],
showParen_Expr (genOpApp a_Expr ge_RDR (nlHsLit
(HsInt def (mkIntegralLit con_prec_plus_one))))
(nlHsPar (nested_compose_Expr show_thingies)))
where
data_con_RDR = getRdrName data_con
con_arity = dataConSourceArity data_con
bs_needed = take con_arity bs_RDRs
arg_tys = dataConOrigArgTys data_con -- Correspond 1-1 with bs_needed
con_pat = nlConVarPat data_con_RDR bs_needed
nullary_con = con_arity == 0
labels = map flLabel $ dataConFieldLabels data_con
lab_fields = length labels
record_syntax = lab_fields > 0
dc_nm = getName data_con
dc_occ_nm = getOccName data_con
con_str = occNameString dc_occ_nm
op_con_str = wrapOpParens con_str
backquote_str = wrapOpBackquotes con_str
show_thingies
| is_infix = [show_arg1, mk_showString_app (" " ++ backquote_str ++ " "), show_arg2]
| record_syntax = mk_showString_app (op_con_str ++ " {") :
show_record_args ++ [mk_showString_app "}"]
| otherwise = mk_showString_app (op_con_str ++ " ") : show_prefix_args
show_label l = mk_showString_app (nm ++ " = ")
-- Note the spaces around the "=" sign. If we
-- don't have them then we get Foo { x=-1 } and
-- the "=-" parses as a single lexeme. Only the
-- space after the '=' is necessary, but it
-- seems tidier to have them both sides.
where
nm = wrapOpParens (unpackFS l)
show_args = zipWith show_arg bs_needed arg_tys
(show_arg1:show_arg2:_) = show_args
show_prefix_args = intersperse (nlHsVar showSpace_RDR) show_args
-- Assumption for record syntax: no of fields == no of
-- labelled fields (and in same order)
show_record_args = concat $
intersperse [comma_space] $
[ [show_label lbl, arg]
| (lbl,arg) <- zipEqual "gen_Show_binds"
labels show_args ]
show_arg :: RdrName -> Type -> LHsExpr GhcPs
show_arg b arg_ty
| isUnliftedType arg_ty
-- See Note [Deriving and unboxed types] in TcDeriv
= nlHsApps compose_RDR [mk_shows_app boxed_arg,
mk_showString_app postfixMod]
| otherwise
= mk_showsPrec_app arg_prec arg
where
arg = nlHsVar b
boxed_arg = box "Show" tycon arg arg_ty
postfixMod = assoc_ty_id "Show" tycon postfixModTbl arg_ty
-- Fixity stuff
is_infix = dataConIsInfix data_con
con_prec_plus_one = 1 + getPrec is_infix get_fixity dc_nm
arg_prec | record_syntax = 0 -- Record fields don't need parens
| otherwise = con_prec_plus_one
wrapOpParens :: String -> String
wrapOpParens s | isSym s = '(' : s ++ ")"
| otherwise = s
wrapOpBackquotes :: String -> String
wrapOpBackquotes s | isSym s = s
| otherwise = '`' : s ++ "`"
isSym :: String -> Bool
isSym "" = False
isSym (c : _) = startsVarSym c || startsConSym c
-- | showString :: String -> ShowS
mk_showString_app :: String -> LHsExpr GhcPs
mk_showString_app str = nlHsApp (nlHsVar showString_RDR) (nlHsLit (mkHsString str))
-- | showsPrec :: Show a => Int -> a -> ShowS
mk_showsPrec_app :: Integer -> LHsExpr GhcPs -> LHsExpr GhcPs
mk_showsPrec_app p x
= nlHsApps showsPrec_RDR [nlHsLit (HsInt def (mkIntegralLit p)), x]
-- | shows :: Show a => a -> ShowS
mk_shows_app :: LHsExpr GhcPs -> LHsExpr GhcPs
mk_shows_app x = nlHsApp (nlHsVar shows_RDR) x
getPrec :: Bool -> (Name -> Fixity) -> Name -> Integer
getPrec is_infix get_fixity nm
| not is_infix = appPrecedence
| otherwise = getPrecedence get_fixity nm
appPrecedence :: Integer
appPrecedence = fromIntegral maxPrecedence + 1
-- One more than the precedence of the most
-- tightly-binding operator
getPrecedence :: (Name -> Fixity) -> Name -> Integer
getPrecedence get_fixity nm
= case get_fixity nm of
Fixity _ x _assoc -> fromIntegral x
-- NB: the Report says that associativity is not taken
-- into account for either Read or Show; hence we
-- ignore associativity here
{-
************************************************************************
* *
Data instances
* *
************************************************************************
From the data type
data T a b = T1 a b | T2
we generate
$cT1 = mkDataCon $dT "T1" Prefix
$cT2 = mkDataCon $dT "T2" Prefix
$dT = mkDataType "Module.T" [] [$con_T1, $con_T2]
-- the [] is for field labels.
instance (Data a, Data b) => Data (T a b) where
gfoldl k z (T1 a b) = z T `k` a `k` b
gfoldl k z T2 = z T2
-- ToDo: add gmapT,Q,M, gfoldr
gunfold k z c = case conIndex c of
I# 1# -> k (k (z T1))
I# 2# -> z T2
toConstr (T1 _ _) = $cT1
toConstr T2 = $cT2
dataTypeOf _ = $dT
dataCast1 = gcast1 -- If T :: * -> *
dataCast2 = gcast2 -- if T :: * -> * -> *
-}
gen_Data_binds :: SrcSpan
-> TyCon -- For data families, this is the
-- *representation* TyCon
-> TcM (LHsBinds GhcPs, -- The method bindings
BagDerivStuff) -- Auxiliary bindings
gen_Data_binds loc rep_tc
= do { dflags <- getDynFlags
-- Make unique names for the data type and constructor
-- auxiliary bindings. Start with the name of the TyCon/DataCon
-- but that might not be unique: see Trac #12245.
; dt_occ <- chooseUniqueOccTc (mkDataTOcc (getOccName rep_tc))
; dc_occs <- mapM (chooseUniqueOccTc . mkDataCOcc . getOccName)
(tyConDataCons rep_tc)
; let dt_rdr = mkRdrUnqual dt_occ
dc_rdrs = map mkRdrUnqual dc_occs
-- OK, now do the work
; return (gen_data dflags dt_rdr dc_rdrs loc rep_tc) }
gen_data :: DynFlags -> RdrName -> [RdrName]
-> SrcSpan -> TyCon
-> (LHsBinds GhcPs, -- The method bindings
BagDerivStuff) -- Auxiliary bindings
gen_data dflags data_type_name constr_names loc rep_tc
= (listToBag [gfoldl_bind, gunfold_bind, toCon_bind, dataTypeOf_bind]
`unionBags` gcast_binds,
-- Auxiliary definitions: the data type and constructors
listToBag ( genDataTyCon
: zipWith genDataDataCon data_cons constr_names ) )
where
data_cons = tyConDataCons rep_tc
n_cons = length data_cons
one_constr = n_cons == 1
genDataTyCon :: DerivStuff
genDataTyCon -- $dT
= DerivHsBind (mkHsVarBind loc data_type_name rhs,
L loc (TypeSig [L loc data_type_name] sig_ty))
sig_ty = mkLHsSigWcType (nlHsTyVar dataType_RDR)
rhs = nlHsVar mkDataType_RDR
`nlHsApp` nlHsLit (mkHsString (showSDocOneLine dflags (ppr rep_tc)))
`nlHsApp` nlList (map nlHsVar constr_names)
genDataDataCon :: DataCon -> RdrName -> DerivStuff
genDataDataCon dc constr_name -- $cT1 etc
= DerivHsBind (mkHsVarBind loc constr_name rhs,
L loc (TypeSig [L loc constr_name] sig_ty))
where
sig_ty = mkLHsSigWcType (nlHsTyVar constr_RDR)
rhs = nlHsApps mkConstr_RDR constr_args
constr_args
= [ -- nlHsIntLit (toInteger (dataConTag dc)), -- Tag
nlHsVar (data_type_name) -- DataType
, nlHsLit (mkHsString (occNameString dc_occ)) -- String name
, nlList labels -- Field labels
, nlHsVar fixity ] -- Fixity
labels = map (nlHsLit . mkHsString . unpackFS . flLabel)
(dataConFieldLabels dc)
dc_occ = getOccName dc
is_infix = isDataSymOcc dc_occ
fixity | is_infix = infix_RDR
| otherwise = prefix_RDR
------------ gfoldl
gfoldl_bind = mkFunBindEC 3 loc gfoldl_RDR id (map gfoldl_eqn data_cons)
gfoldl_eqn con
= ([nlVarPat k_RDR, z_Pat, nlConVarPat con_name as_needed],
foldl mk_k_app (z_Expr `nlHsApp` nlHsVar con_name) as_needed)
where
con_name :: RdrName
con_name = getRdrName con
as_needed = take (dataConSourceArity con) as_RDRs
mk_k_app e v = nlHsPar (nlHsOpApp e k_RDR (nlHsVar v))
------------ gunfold
gunfold_bind = mk_easy_FunBind loc
gunfold_RDR
[k_Pat, z_Pat, if one_constr then nlWildPat else c_Pat]
gunfold_rhs
gunfold_rhs
| one_constr = mk_unfold_rhs (head data_cons) -- No need for case
| otherwise = nlHsCase (nlHsVar conIndex_RDR `nlHsApp` c_Expr)
(map gunfold_alt data_cons)
gunfold_alt dc = mkHsCaseAlt (mk_unfold_pat dc) (mk_unfold_rhs dc)
mk_unfold_rhs dc = foldr nlHsApp
(z_Expr `nlHsApp` nlHsVar (getRdrName dc))
(replicate (dataConSourceArity dc) (nlHsVar k_RDR))
mk_unfold_pat dc -- Last one is a wild-pat, to avoid
-- redundant test, and annoying warning
| tag-fIRST_TAG == n_cons-1 = nlWildPat -- Last constructor
| otherwise = nlConPat intDataCon_RDR
[nlLitPat (HsIntPrim NoSourceText (toInteger tag))]
where
tag = dataConTag dc
------------ toConstr
toCon_bind = mkFunBindEC 1 loc toConstr_RDR id
(zipWith to_con_eqn data_cons constr_names)
to_con_eqn dc con_name = ([nlWildConPat dc], nlHsVar con_name)
------------ dataTypeOf
dataTypeOf_bind = mk_easy_FunBind
loc
dataTypeOf_RDR
[nlWildPat]
(nlHsVar data_type_name)
------------ gcast1/2
-- Make the binding dataCast1 x = gcast1 x -- if T :: * -> *
-- or dataCast2 x = gcast2 s -- if T :: * -> * -> *
-- (or nothing if T has neither of these two types)
-- But care is needed for data families:
-- If we have data family D a
-- data instance D (a,b,c) = A | B deriving( Data )
-- and we want instance ... => Data (D [(a,b,c)]) where ...
-- then we need dataCast1 x = gcast1 x
-- because D :: * -> *
-- even though rep_tc has kind * -> * -> * -> *
-- Hence looking for the kind of fam_tc not rep_tc
-- See Trac #4896
tycon_kind = case tyConFamInst_maybe rep_tc of
Just (fam_tc, _) -> tyConKind fam_tc
Nothing -> tyConKind rep_tc
gcast_binds | tycon_kind `tcEqKind` kind1 = mk_gcast dataCast1_RDR gcast1_RDR
| tycon_kind `tcEqKind` kind2 = mk_gcast dataCast2_RDR gcast2_RDR
| otherwise = emptyBag
mk_gcast dataCast_RDR gcast_RDR
= unitBag (mk_easy_FunBind loc dataCast_RDR [nlVarPat f_RDR]
(nlHsVar gcast_RDR `nlHsApp` nlHsVar f_RDR))
kind1, kind2 :: Kind
kind1 = liftedTypeKind `mkFunTy` liftedTypeKind
kind2 = liftedTypeKind `mkFunTy` kind1
gfoldl_RDR, gunfold_RDR, toConstr_RDR, dataTypeOf_RDR, mkConstr_RDR,
mkDataType_RDR, conIndex_RDR, prefix_RDR, infix_RDR,
dataCast1_RDR, dataCast2_RDR, gcast1_RDR, gcast2_RDR,
constr_RDR, dataType_RDR,
eqChar_RDR , ltChar_RDR , geChar_RDR , gtChar_RDR , leChar_RDR ,
eqInt_RDR , ltInt_RDR , geInt_RDR , gtInt_RDR , leInt_RDR ,
eqWord_RDR , ltWord_RDR , geWord_RDR , gtWord_RDR , leWord_RDR ,
eqAddr_RDR , ltAddr_RDR , geAddr_RDR , gtAddr_RDR , leAddr_RDR ,
eqFloat_RDR , ltFloat_RDR , geFloat_RDR , gtFloat_RDR , leFloat_RDR ,
eqDouble_RDR, ltDouble_RDR, geDouble_RDR, gtDouble_RDR, leDouble_RDR :: RdrName
gfoldl_RDR = varQual_RDR gENERICS (fsLit "gfoldl")
gunfold_RDR = varQual_RDR gENERICS (fsLit "gunfold")
toConstr_RDR = varQual_RDR gENERICS (fsLit "toConstr")
dataTypeOf_RDR = varQual_RDR gENERICS (fsLit "dataTypeOf")
dataCast1_RDR = varQual_RDR gENERICS (fsLit "dataCast1")
dataCast2_RDR = varQual_RDR gENERICS (fsLit "dataCast2")
gcast1_RDR = varQual_RDR tYPEABLE (fsLit "gcast1")
gcast2_RDR = varQual_RDR tYPEABLE (fsLit "gcast2")
mkConstr_RDR = varQual_RDR gENERICS (fsLit "mkConstr")
constr_RDR = tcQual_RDR gENERICS (fsLit "Constr")
mkDataType_RDR = varQual_RDR gENERICS (fsLit "mkDataType")
dataType_RDR = tcQual_RDR gENERICS (fsLit "DataType")
conIndex_RDR = varQual_RDR gENERICS (fsLit "constrIndex")
prefix_RDR = dataQual_RDR gENERICS (fsLit "Prefix")
infix_RDR = dataQual_RDR gENERICS (fsLit "Infix")
eqChar_RDR = varQual_RDR gHC_PRIM (fsLit "eqChar#")
ltChar_RDR = varQual_RDR gHC_PRIM (fsLit "ltChar#")
leChar_RDR = varQual_RDR gHC_PRIM (fsLit "leChar#")
gtChar_RDR = varQual_RDR gHC_PRIM (fsLit "gtChar#")
geChar_RDR = varQual_RDR gHC_PRIM (fsLit "geChar#")
eqInt_RDR = varQual_RDR gHC_PRIM (fsLit "==#")
ltInt_RDR = varQual_RDR gHC_PRIM (fsLit "<#" )
leInt_RDR = varQual_RDR gHC_PRIM (fsLit "<=#")
gtInt_RDR = varQual_RDR gHC_PRIM (fsLit ">#" )
geInt_RDR = varQual_RDR gHC_PRIM (fsLit ">=#")
eqWord_RDR = varQual_RDR gHC_PRIM (fsLit "eqWord#")
ltWord_RDR = varQual_RDR gHC_PRIM (fsLit "ltWord#")
leWord_RDR = varQual_RDR gHC_PRIM (fsLit "leWord#")
gtWord_RDR = varQual_RDR gHC_PRIM (fsLit "gtWord#")
geWord_RDR = varQual_RDR gHC_PRIM (fsLit "geWord#")
eqAddr_RDR = varQual_RDR gHC_PRIM (fsLit "eqAddr#")
ltAddr_RDR = varQual_RDR gHC_PRIM (fsLit "ltAddr#")
leAddr_RDR = varQual_RDR gHC_PRIM (fsLit "leAddr#")
gtAddr_RDR = varQual_RDR gHC_PRIM (fsLit "gtAddr#")
geAddr_RDR = varQual_RDR gHC_PRIM (fsLit "geAddr#")
eqFloat_RDR = varQual_RDR gHC_PRIM (fsLit "eqFloat#")
ltFloat_RDR = varQual_RDR gHC_PRIM (fsLit "ltFloat#")
leFloat_RDR = varQual_RDR gHC_PRIM (fsLit "leFloat#")
gtFloat_RDR = varQual_RDR gHC_PRIM (fsLit "gtFloat#")
geFloat_RDR = varQual_RDR gHC_PRIM (fsLit "geFloat#")
eqDouble_RDR = varQual_RDR gHC_PRIM (fsLit "==##")
ltDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<##" )
leDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<=##")
gtDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">##" )
geDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">=##")
{-
************************************************************************
* *
Lift instances
* *
************************************************************************
Example:
data Foo a = Foo a | a :^: a deriving Lift
==>
instance (Lift a) => Lift (Foo a) where
lift (Foo a)
= appE
(conE
(mkNameG_d "package-name" "ModuleName" "Foo"))
(lift a)
lift (u :^: v)
= infixApp
(lift u)
(conE
(mkNameG_d "package-name" "ModuleName" ":^:"))
(lift v)
Note that (mkNameG_d "package-name" "ModuleName" "Foo") is equivalent to what
'Foo would be when using the -XTemplateHaskell extension. To make sure that
-XDeriveLift can be used on stage-1 compilers, however, we explicitly invoke
makeG_d.
-}
gen_Lift_binds :: SrcSpan -> TyCon -> (LHsBinds GhcPs, BagDerivStuff)
gen_Lift_binds loc tycon = (unitBag lift_bind, emptyBag)
where
lift_bind = mkFunBindEC 1 loc lift_RDR (nlHsApp pure_Expr)
(map pats_etc data_cons)
data_cons = tyConDataCons tycon
pats_etc data_con
= ([con_pat], lift_Expr)
where
con_pat = nlConVarPat data_con_RDR as_needed
data_con_RDR = getRdrName data_con
con_arity = dataConSourceArity data_con
as_needed = take con_arity as_RDRs
lifted_as = zipWithEqual "mk_lift_app" mk_lift_app
tys_needed as_needed
tycon_name = tyConName tycon
is_infix = dataConIsInfix data_con
tys_needed = dataConOrigArgTys data_con
mk_lift_app ty a
| not (isUnliftedType ty) = nlHsApp (nlHsVar lift_RDR)
(nlHsVar a)
| otherwise = nlHsApp (nlHsVar litE_RDR)
(primLitOp (mkBoxExp (nlHsVar a)))
where (primLitOp, mkBoxExp) = primLitOps "Lift" tycon ty
pkg_name = unitIdString . moduleUnitId
. nameModule $ tycon_name
mod_name = moduleNameString . moduleName . nameModule $ tycon_name
con_name = occNameString . nameOccName . dataConName $ data_con
conE_Expr = nlHsApp (nlHsVar conE_RDR)
(nlHsApps mkNameG_dRDR
(map (nlHsLit . mkHsString)
[pkg_name, mod_name, con_name]))
lift_Expr
| is_infix = nlHsApps infixApp_RDR [a1, conE_Expr, a2]
| otherwise = foldl mk_appE_app conE_Expr lifted_as
(a1:a2:_) = lifted_as
mk_appE_app :: LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
mk_appE_app a b = nlHsApps appE_RDR [a, b]
{-
************************************************************************
* *
Newtype-deriving instances
* *
************************************************************************
Note [Newtype-deriving instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We take every method in the original instance and `coerce` it to fit
into the derived instance. We need a type annotation on the argument
to `coerce` to make it obvious what instantiation of the method we're
coercing from. So from, say,
class C a b where
op :: a -> [b] -> Int
newtype T x = MkT <rep-ty>
instance C a <rep-ty> => C a (T x) where
op = coerce @ (a -> [<rep-ty>] -> Int)
@ (a -> [T x] -> Int)
op
Notice that we give the 'coerce' two explicitly-visible type arguments
to say how it should be instantiated. Recall
coerce :: Coeercible a b => a -> b
By giving it explicit type arguments we deal with the case where
'op' has a higher rank type, and so we must instantiate 'coerce' with
a polytype. E.g.
class C a where op :: forall b. a -> b -> b
newtype T x = MkT <rep-ty>
instance C <rep-ty> => C (T x) where
op = coerce @ (forall b. <rep-ty> -> b -> b)
@ (forall b. T x -> b -> b)
op
The type checker checks this code, and it currently requires
-XImpredicativeTypes to permit that polymorphic type instantiation,
so we have to switch that flag on locally in TcDeriv.genInst.
See #8503 for more discussion.
Note [Newtype-deriving trickiness]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (Trac #12768):
class C a where { op :: D a => a -> a }
instance C a => C [a] where { op = opList }
opList :: (C a, D [a]) => [a] -> [a]
opList = ...
Now suppose we try GND on this:
newtype N a = MkN [a] deriving( C )
The GND is expecting to get an implementation of op for N by
coercing opList, thus:
instance C a => C (N a) where { op = opN }
opN :: (C a, D (N a)) => N a -> N a
opN = coerce @(D [a] => [a] -> [a])
@(D (N a) => [N a] -> [N a]
opList
But there is no reason to suppose that (D [a]) and (D (N a))
are inter-coercible; these instances might completely different.
So GHC rightly rejects this code.
-}
gen_Newtype_binds :: SrcSpan
-> Class -- the class being derived
-> [TyVar] -- the tvs in the instance head (this includes
-- the tvs from both the class types and the
-- newtype itself)
-> [Type] -- instance head parameters (incl. newtype)
-> Type -- the representation type
-> TcM (LHsBinds GhcPs, BagDerivStuff)
-- See Note [Newtype-deriving instances]
gen_Newtype_binds loc cls inst_tvs inst_tys rhs_ty
= do let ats = classATs cls
atf_insts <- ASSERT( all (not . isDataFamilyTyCon) ats )
mapM mk_atf_inst ats
return ( listToBag $ map mk_bind (classMethods cls)
, listToBag $ map DerivFamInst atf_insts )
where
mk_bind :: Id -> LHsBind GhcPs
mk_bind meth_id
= mkRdrFunBind (L loc meth_RDR) [mkSimpleMatch
(mkPrefixFunRhs (L loc meth_RDR))
[] rhs_expr]
where
Pair from_ty to_ty = mkCoerceClassMethEqn cls inst_tvs inst_tys rhs_ty meth_id
meth_RDR = getRdrName meth_id
rhs_expr = nlHsVar (getRdrName coerceId)
`nlHsAppType` from_ty
`nlHsAppType` to_ty
`nlHsApp` nlHsVar meth_RDR
mk_atf_inst :: TyCon -> TcM FamInst
mk_atf_inst fam_tc = do
rep_tc_name <- newFamInstTyConName (L loc (tyConName fam_tc))
rep_lhs_tys
let axiom = mkSingleCoAxiom Nominal rep_tc_name rep_tvs' rep_cvs'
fam_tc rep_lhs_tys rep_rhs_ty
-- Check (c) from Note [GND and associated type families] in TcDeriv
checkValidTyFamEqn (Just (cls, cls_tvs, lhs_env)) fam_tc rep_tvs'
rep_cvs' rep_lhs_tys rep_rhs_ty pp_lhs loc
newFamInst SynFamilyInst axiom
where
cls_tvs = classTyVars cls
in_scope = mkInScopeSet $ mkVarSet inst_tvs
lhs_env = zipTyEnv cls_tvs inst_tys
lhs_subst = mkTvSubst in_scope lhs_env
rhs_env = zipTyEnv cls_tvs $ changeLast inst_tys rhs_ty
rhs_subst = mkTvSubst in_scope rhs_env
fam_tvs = tyConTyVars fam_tc
rep_lhs_tys = substTyVars lhs_subst fam_tvs
rep_rhs_tys = substTyVars rhs_subst fam_tvs
rep_rhs_ty = mkTyConApp fam_tc rep_rhs_tys
rep_tcvs = tyCoVarsOfTypesList rep_lhs_tys
(rep_tvs, rep_cvs) = partition isTyVar rep_tcvs
rep_tvs' = toposortTyVars rep_tvs
rep_cvs' = toposortTyVars rep_cvs
pp_lhs = ppr (mkTyConApp fam_tc rep_lhs_tys)
nlHsAppType :: LHsExpr GhcPs -> Type -> LHsExpr GhcPs
nlHsAppType e s = noLoc (e `HsAppType` hs_ty)
where
hs_ty = mkHsWildCardBndrs $ nlHsParTy (typeToLHsType s)
nlExprWithTySig :: LHsExpr GhcPs -> Type -> LHsExpr GhcPs
nlExprWithTySig e s = noLoc (e `ExprWithTySig` hs_ty)
where
hs_ty = mkLHsSigWcType (typeToLHsType s)
mkCoerceClassMethEqn :: Class -- the class being derived
-> [TyVar] -- the tvs in the instance head (this includes
-- the tvs from both the class types and the
-- newtype itself)
-> [Type] -- instance head parameters (incl. newtype)
-> Type -- the representation type
-> Id -- the method to look at
-> Pair Type
-- See Note [Newtype-deriving instances]
-- See also Note [Newtype-deriving trickiness]
-- The pair is the (from_type, to_type), where to_type is
-- the type of the method we are tyrying to get
mkCoerceClassMethEqn cls inst_tvs inst_tys rhs_ty id
= Pair (substTy rhs_subst user_meth_ty)
(substTy lhs_subst user_meth_ty)
where
cls_tvs = classTyVars cls
in_scope = mkInScopeSet $ mkVarSet inst_tvs
lhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs inst_tys)
rhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs (changeLast inst_tys rhs_ty))
(_class_tvs, _class_constraint, user_meth_ty)
= tcSplitMethodTy (varType id)
{-
************************************************************************
* *
\subsection{Generating extra binds (@con2tag@ and @tag2con@)}
* *
************************************************************************
\begin{verbatim}
data Foo ... = ...
con2tag_Foo :: Foo ... -> Int#
tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
maxtag_Foo :: Int -- ditto (NB: not unlifted)
\end{verbatim}
The `tags' here start at zero, hence the @fIRST_TAG@ (currently one)
fiddling around.
-}
genAuxBindSpec :: DynFlags -> SrcSpan -> AuxBindSpec
-> (LHsBind GhcPs, LSig GhcPs)
genAuxBindSpec dflags loc (DerivCon2Tag tycon)
= (mkFunBindSE 0 loc rdr_name eqns,
L loc (TypeSig [L loc rdr_name] sig_ty))
where
rdr_name = con2tag_RDR dflags tycon
sig_ty = mkLHsSigWcType $ L loc $ HsCoreTy $
mkSpecSigmaTy (tyConTyVars tycon) (tyConStupidTheta tycon) $
mkParentType tycon `mkFunTy` intPrimTy
lots_of_constructors = tyConFamilySize tycon > 8
-- was: mAX_FAMILY_SIZE_FOR_VEC_RETURNS
-- but we don't do vectored returns any more.
eqns | lots_of_constructors = [get_tag_eqn]
| otherwise = map mk_eqn (tyConDataCons tycon)
get_tag_eqn = ([nlVarPat a_RDR], nlHsApp (nlHsVar getTag_RDR) a_Expr)
mk_eqn :: DataCon -> ([LPat GhcPs], LHsExpr GhcPs)
mk_eqn con = ([nlWildConPat con],
nlHsLit (HsIntPrim NoSourceText
(toInteger ((dataConTag con) - fIRST_TAG))))
genAuxBindSpec dflags loc (DerivTag2Con tycon)
= (mkFunBindSE 0 loc rdr_name
[([nlConVarPat intDataCon_RDR [a_RDR]],
nlHsApp (nlHsVar tagToEnum_RDR) a_Expr)],
L loc (TypeSig [L loc rdr_name] sig_ty))
where
sig_ty = mkLHsSigWcType $ L loc $
HsCoreTy $ mkSpecForAllTys (tyConTyVars tycon) $
intTy `mkFunTy` mkParentType tycon
rdr_name = tag2con_RDR dflags tycon
genAuxBindSpec dflags loc (DerivMaxTag tycon)
= (mkHsVarBind loc rdr_name rhs,
L loc (TypeSig [L loc rdr_name] sig_ty))
where
rdr_name = maxtag_RDR dflags tycon
sig_ty = mkLHsSigWcType (L loc (HsCoreTy intTy))
rhs = nlHsApp (nlHsVar intDataCon_RDR)
(nlHsLit (HsIntPrim NoSourceText max_tag))
max_tag = case (tyConDataCons tycon) of
data_cons -> toInteger ((length data_cons) - fIRST_TAG)
type SeparateBagsDerivStuff =
-- AuxBinds and SYB bindings
( Bag (LHsBind GhcPs, LSig GhcPs)
-- Extra family instances (used by Generic and DeriveAnyClass)
, Bag (FamInst) )
genAuxBinds :: DynFlags -> SrcSpan -> BagDerivStuff -> SeparateBagsDerivStuff
genAuxBinds dflags loc b = genAuxBinds' b2 where
(b1,b2) = partitionBagWith splitDerivAuxBind b
splitDerivAuxBind (DerivAuxBind x) = Left x
splitDerivAuxBind x = Right x
rm_dups = foldrBag dup_check emptyBag
dup_check a b = if anyBag (== a) b then b else consBag a b
genAuxBinds' :: BagDerivStuff -> SeparateBagsDerivStuff
genAuxBinds' = foldrBag f ( mapBag (genAuxBindSpec dflags loc) (rm_dups b1)
, emptyBag )
f :: DerivStuff -> SeparateBagsDerivStuff -> SeparateBagsDerivStuff
f (DerivAuxBind _) = panic "genAuxBinds'" -- We have removed these before
f (DerivHsBind b) = add1 b
f (DerivFamInst t) = add2 t
add1 x (a,b) = (x `consBag` a,b)
add2 x (a,b) = (a,x `consBag` b)
mkParentType :: TyCon -> Type
-- Turn the representation tycon of a family into
-- a use of its family constructor
mkParentType tc
= case tyConFamInst_maybe tc of
Nothing -> mkTyConApp tc (mkTyVarTys (tyConTyVars tc))
Just (fam_tc,tys) -> mkTyConApp fam_tc tys
{-
************************************************************************
* *
\subsection{Utility bits for generating bindings}
* *
************************************************************************
-}
-- | Make a function binding. If no equations are given, produce a function
-- with the given arity that produces a stock error.
mkFunBindSE :: Arity -> SrcSpan -> RdrName
-> [([LPat GhcPs], LHsExpr GhcPs)]
-> LHsBind GhcPs
mkFunBindSE arity loc fun pats_and_exprs
= mkRdrFunBindSE arity (L loc fun) matches
where
matches = [mkMatch (mkPrefixFunRhs (L loc fun))
(map parenthesizeCompoundPat p) e
(noLoc emptyLocalBinds)
| (p,e) <-pats_and_exprs]
mkRdrFunBind :: Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)]
-> LHsBind GhcPs
mkRdrFunBind fun@(L loc _fun_rdr) matches
= L loc (mkFunBind fun matches)
-- | Make a function binding. If no equations are given, produce a function
-- with the given arity that uses an empty case expression for the last
-- argument that is passes to the given function to produce the right-hand
-- side.
mkFunBindEC :: Arity -> SrcSpan -> RdrName
-> (LHsExpr GhcPs -> LHsExpr GhcPs)
-> [([LPat GhcPs], LHsExpr GhcPs)]
-> LHsBind GhcPs
mkFunBindEC arity loc fun catch_all pats_and_exprs
= mkRdrFunBindEC arity catch_all (L loc fun) matches
where
matches = [ mkMatch (mkPrefixFunRhs (L loc fun))
(map parenthesizeCompoundPat p) e
(noLoc emptyLocalBinds)
| (p,e) <- pats_and_exprs ]
-- | Produces a function binding. When no equations are given, it generates
-- a binding of the given arity and an empty case expression
-- for the last argument that it passes to the given function to produce
-- the right-hand side.
mkRdrFunBindEC :: Arity
-> (LHsExpr GhcPs -> LHsExpr GhcPs)
-> Located RdrName
-> [LMatch GhcPs (LHsExpr GhcPs)]
-> LHsBind GhcPs
mkRdrFunBindEC arity catch_all
fun@(L loc _fun_rdr) matches = L loc (mkFunBind fun matches')
where
-- Catch-all eqn looks like
-- fmap _ z = case z of {}
-- or
-- traverse _ z = pure (case z of)
-- or
-- foldMap _ z = mempty
-- It's needed if there no data cons at all,
-- which can happen with -XEmptyDataDecls
-- See Trac #4302
matches' = if null matches
then [mkMatch (mkPrefixFunRhs fun)
(replicate (arity - 1) nlWildPat ++ [z_Pat])
(catch_all $ nlHsCase z_Expr [])
(noLoc emptyLocalBinds)]
else matches
-- | Produces a function binding. When there are no equations, it generates
-- a binding with the given arity that produces an error based on the name of
-- the type of the last argument.
mkRdrFunBindSE :: Arity -> Located RdrName ->
[LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs
mkRdrFunBindSE arity
fun@(L loc fun_rdr) matches = L loc (mkFunBind fun matches')
where
-- Catch-all eqn looks like
-- compare _ _ = error "Void compare"
-- It's needed if there no data cons at all,
-- which can happen with -XEmptyDataDecls
-- See Trac #4302
matches' = if null matches
then [mkMatch (mkPrefixFunRhs fun)
(replicate arity nlWildPat)
(error_Expr str) (noLoc emptyLocalBinds)]
else matches
str = "Void " ++ occNameString (rdrNameOcc fun_rdr)
box :: String -- The class involved
-> TyCon -- The tycon involved
-> LHsExpr GhcPs -- The argument
-> Type -- The argument type
-> LHsExpr GhcPs -- Boxed version of the arg
-- See Note [Deriving and unboxed types] in TcDeriv
box cls_str tycon arg arg_ty = nlHsApp (nlHsVar box_con) arg
where
box_con = assoc_ty_id cls_str tycon boxConTbl arg_ty
---------------------
primOrdOps :: String -- The class involved
-> TyCon -- The tycon involved
-> Type -- The type
-> (RdrName, RdrName, RdrName, RdrName, RdrName) -- (lt,le,eq,ge,gt)
-- See Note [Deriving and unboxed types] in TcDeriv
primOrdOps str tycon ty = assoc_ty_id str tycon ordOpTbl ty
primLitOps :: String -- The class involved
-> TyCon -- The tycon involved
-> Type -- The type
-> ( LHsExpr GhcPs -> LHsExpr GhcPs -- Constructs a Q Exp value
, LHsExpr GhcPs -> LHsExpr GhcPs -- Constructs a boxed value
)
primLitOps str tycon ty = ( assoc_ty_id str tycon litConTbl ty
, \v -> nlHsVar boxRDR `nlHsApp` v
)
where
boxRDR
| ty `eqType` addrPrimTy = unpackCString_RDR
| otherwise = assoc_ty_id str tycon boxConTbl ty
ordOpTbl :: [(Type, (RdrName, RdrName, RdrName, RdrName, RdrName))]
ordOpTbl
= [(charPrimTy , (ltChar_RDR , leChar_RDR , eqChar_RDR , geChar_RDR , gtChar_RDR ))
,(intPrimTy , (ltInt_RDR , leInt_RDR , eqInt_RDR , geInt_RDR , gtInt_RDR ))
,(wordPrimTy , (ltWord_RDR , leWord_RDR , eqWord_RDR , geWord_RDR , gtWord_RDR ))
,(addrPrimTy , (ltAddr_RDR , leAddr_RDR , eqAddr_RDR , geAddr_RDR , gtAddr_RDR ))
,(floatPrimTy , (ltFloat_RDR , leFloat_RDR , eqFloat_RDR , geFloat_RDR , gtFloat_RDR ))
,(doublePrimTy, (ltDouble_RDR, leDouble_RDR, eqDouble_RDR, geDouble_RDR, gtDouble_RDR)) ]
boxConTbl :: [(Type, RdrName)]
boxConTbl
= [(charPrimTy , getRdrName charDataCon )
,(intPrimTy , getRdrName intDataCon )
,(wordPrimTy , getRdrName wordDataCon )
,(floatPrimTy , getRdrName floatDataCon )
,(doublePrimTy, getRdrName doubleDataCon)
]
-- | A table of postfix modifiers for unboxed values.
postfixModTbl :: [(Type, String)]
postfixModTbl
= [(charPrimTy , "#" )
,(intPrimTy , "#" )
,(wordPrimTy , "##")
,(floatPrimTy , "#" )
,(doublePrimTy, "##")
]
litConTbl :: [(Type, LHsExpr GhcPs -> LHsExpr GhcPs)]
litConTbl
= [(charPrimTy , nlHsApp (nlHsVar charPrimL_RDR))
,(intPrimTy , nlHsApp (nlHsVar intPrimL_RDR)
. nlHsApp (nlHsVar toInteger_RDR))
,(wordPrimTy , nlHsApp (nlHsVar wordPrimL_RDR)
. nlHsApp (nlHsVar toInteger_RDR))
,(addrPrimTy , nlHsApp (nlHsVar stringPrimL_RDR)
. nlHsApp (nlHsApp
(nlHsVar map_RDR)
(compose_RDR `nlHsApps`
[ nlHsVar fromIntegral_RDR
, nlHsVar fromEnum_RDR
])))
,(floatPrimTy , nlHsApp (nlHsVar floatPrimL_RDR)
. nlHsApp (nlHsVar toRational_RDR))
,(doublePrimTy, nlHsApp (nlHsVar doublePrimL_RDR)
. nlHsApp (nlHsVar toRational_RDR))
]
-- | Lookup `Type` in an association list.
assoc_ty_id :: String -- The class involved
-> TyCon -- The tycon involved
-> [(Type,a)] -- The table
-> Type -- The type
-> a -- The result of the lookup
assoc_ty_id cls_str _ tbl ty
| null res = pprPanic "Error in deriving:" (text "Can't derive" <+> text cls_str <+>
text "for primitive type" <+> ppr ty)
| otherwise = head res
where
res = [id | (ty',id) <- tbl, ty `eqType` ty']
-----------------------------------------------------------------------
and_Expr :: LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
and_Expr a b = genOpApp a and_RDR b
-----------------------------------------------------------------------
eq_Expr :: TyCon -> Type -> LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
eq_Expr tycon ty a b
| not (isUnliftedType ty) = genOpApp a eq_RDR b
| otherwise = genPrimOpApp a prim_eq b
where
(_, _, prim_eq, _, _) = primOrdOps "Eq" tycon ty
untag_Expr :: DynFlags -> TyCon -> [( RdrName, RdrName)]
-> LHsExpr GhcPs -> LHsExpr GhcPs
untag_Expr _ _ [] expr = expr
untag_Expr dflags tycon ((untag_this, put_tag_here) : more) expr
= nlHsCase (nlHsPar (nlHsVarApps (con2tag_RDR dflags tycon)
[untag_this])) {-of-}
[mkHsCaseAlt (nlVarPat put_tag_here) (untag_Expr dflags tycon more expr)]
enum_from_to_Expr
:: LHsExpr GhcPs -> LHsExpr GhcPs
-> LHsExpr GhcPs
enum_from_then_to_Expr
:: LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
-> LHsExpr GhcPs
enum_from_to_Expr f t2 = nlHsApp (nlHsApp (nlHsVar enumFromTo_RDR) f) t2
enum_from_then_to_Expr f t t2 = nlHsApp (nlHsApp (nlHsApp (nlHsVar enumFromThenTo_RDR) f) t) t2
showParen_Expr
:: LHsExpr GhcPs -> LHsExpr GhcPs
-> LHsExpr GhcPs
showParen_Expr e1 e2 = nlHsApp (nlHsApp (nlHsVar showParen_RDR) e1) e2
nested_compose_Expr :: [LHsExpr GhcPs] -> LHsExpr GhcPs
nested_compose_Expr [] = panic "nested_compose_expr" -- Arg is always non-empty
nested_compose_Expr [e] = parenify e
nested_compose_Expr (e:es)
= nlHsApp (nlHsApp (nlHsVar compose_RDR) (parenify e)) (nested_compose_Expr es)
-- impossible_Expr is used in case RHSs that should never happen.
-- We generate these to keep the desugarer from complaining that they *might* happen!
error_Expr :: String -> LHsExpr GhcPs
error_Expr string = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString string))
-- illegal_Expr is used when signalling error conditions in the RHS of a derived
-- method. It is currently only used by Enum.{succ,pred}
illegal_Expr :: String -> String -> String -> LHsExpr GhcPs
illegal_Expr meth tp msg =
nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString (meth ++ '{':tp ++ "}: " ++ msg)))
-- illegal_toEnum_tag is an extended version of illegal_Expr, which also allows you
-- to include the value of a_RDR in the error string.
illegal_toEnum_tag :: String -> RdrName -> LHsExpr GhcPs
illegal_toEnum_tag tp maxtag =
nlHsApp (nlHsVar error_RDR)
(nlHsApp (nlHsApp (nlHsVar append_RDR)
(nlHsLit (mkHsString ("toEnum{" ++ tp ++ "}: tag ("))))
(nlHsApp (nlHsApp (nlHsApp
(nlHsVar showsPrec_RDR)
(nlHsIntLit 0))
(nlHsVar a_RDR))
(nlHsApp (nlHsApp
(nlHsVar append_RDR)
(nlHsLit (mkHsString ") is outside of enumeration's range (0,")))
(nlHsApp (nlHsApp (nlHsApp
(nlHsVar showsPrec_RDR)
(nlHsIntLit 0))
(nlHsVar maxtag))
(nlHsLit (mkHsString ")"))))))
parenify :: LHsExpr GhcPs -> LHsExpr GhcPs
parenify e@(L _ (HsVar _)) = e
parenify e = mkHsPar e
-- genOpApp wraps brackets round the operator application, so that the
-- renamer won't subsequently try to re-associate it.
genOpApp :: LHsExpr GhcPs -> RdrName -> LHsExpr GhcPs -> LHsExpr GhcPs
genOpApp e1 op e2 = nlHsPar (nlHsOpApp e1 op e2)
genPrimOpApp :: LHsExpr GhcPs -> RdrName -> LHsExpr GhcPs -> LHsExpr GhcPs
genPrimOpApp e1 op e2 = nlHsPar (nlHsApp (nlHsVar tagToEnum_RDR) (nlHsOpApp e1 op e2))
a_RDR, b_RDR, c_RDR, d_RDR, f_RDR, k_RDR, z_RDR, ah_RDR, bh_RDR, ch_RDR, dh_RDR
:: RdrName
a_RDR = mkVarUnqual (fsLit "a")
b_RDR = mkVarUnqual (fsLit "b")
c_RDR = mkVarUnqual (fsLit "c")
d_RDR = mkVarUnqual (fsLit "d")
f_RDR = mkVarUnqual (fsLit "f")
k_RDR = mkVarUnqual (fsLit "k")
z_RDR = mkVarUnqual (fsLit "z")
ah_RDR = mkVarUnqual (fsLit "a#")
bh_RDR = mkVarUnqual (fsLit "b#")
ch_RDR = mkVarUnqual (fsLit "c#")
dh_RDR = mkVarUnqual (fsLit "d#")
as_RDRs, bs_RDRs, cs_RDRs :: [RdrName]
as_RDRs = [ mkVarUnqual (mkFastString ("a"++show i)) | i <- [(1::Int) .. ] ]
bs_RDRs = [ mkVarUnqual (mkFastString ("b"++show i)) | i <- [(1::Int) .. ] ]
cs_RDRs = [ mkVarUnqual (mkFastString ("c"++show i)) | i <- [(1::Int) .. ] ]
a_Expr, b_Expr, c_Expr, z_Expr, ltTag_Expr, eqTag_Expr, gtTag_Expr, false_Expr,
true_Expr, pure_Expr :: LHsExpr GhcPs
a_Expr = nlHsVar a_RDR
b_Expr = nlHsVar b_RDR
c_Expr = nlHsVar c_RDR
z_Expr = nlHsVar z_RDR
ltTag_Expr = nlHsVar ltTag_RDR
eqTag_Expr = nlHsVar eqTag_RDR
gtTag_Expr = nlHsVar gtTag_RDR
false_Expr = nlHsVar false_RDR
true_Expr = nlHsVar true_RDR
pure_Expr = nlHsVar pure_RDR
a_Pat, b_Pat, c_Pat, d_Pat, k_Pat, z_Pat :: LPat GhcPs
a_Pat = nlVarPat a_RDR
b_Pat = nlVarPat b_RDR
c_Pat = nlVarPat c_RDR
d_Pat = nlVarPat d_RDR
k_Pat = nlVarPat k_RDR
z_Pat = nlVarPat z_RDR
minusInt_RDR, tagToEnum_RDR :: RdrName
minusInt_RDR = getRdrName (primOpId IntSubOp )
tagToEnum_RDR = getRdrName (primOpId TagToEnumOp)
con2tag_RDR, tag2con_RDR, maxtag_RDR :: DynFlags -> TyCon -> RdrName
-- Generates Orig s RdrName, for the binding positions
con2tag_RDR dflags tycon = mk_tc_deriv_name dflags tycon mkCon2TagOcc
tag2con_RDR dflags tycon = mk_tc_deriv_name dflags tycon mkTag2ConOcc
maxtag_RDR dflags tycon = mk_tc_deriv_name dflags tycon mkMaxTagOcc
mk_tc_deriv_name :: DynFlags -> TyCon -> (OccName -> OccName) -> RdrName
mk_tc_deriv_name dflags tycon occ_fun =
mkAuxBinderName dflags (tyConName tycon) occ_fun
mkAuxBinderName :: DynFlags -> Name -> (OccName -> OccName) -> RdrName
-- ^ Make a top-level binder name for an auxiliary binding for a parent name
-- See Note [Auxiliary binders]
mkAuxBinderName dflags parent occ_fun
= mkRdrUnqual (occ_fun stable_parent_occ)
where
stable_parent_occ = mkOccName (occNameSpace parent_occ) stable_string
stable_string
| hasPprDebug dflags = parent_stable
| otherwise = parent_stable_hash
parent_stable = nameStableString parent
parent_stable_hash =
let Fingerprint high low = fingerprintString parent_stable
in toBase62 high ++ toBase62Padded low
-- See Note [Base 62 encoding 128-bit integers] in Encoding
parent_occ = nameOccName parent
{-
Note [Auxiliary binders]
~~~~~~~~~~~~~~~~~~~~~~~~
We often want to make a top-level auxiliary binding. E.g. for comparison we haev
instance Ord T where
compare a b = $con2tag a `compare` $con2tag b
$con2tag :: T -> Int
$con2tag = ...code....
Of course these top-level bindings should all have distinct name, and we are
generating RdrNames here. We can't just use the TyCon or DataCon to distinguish
because with standalone deriving two imported TyCons might both be called T!
(See Trac #7947.)
So we use package name, module name and the name of the parent
(T in this example) as part of the OccName we generate for the new binding.
To make the symbol names short we take a base62 hash of the full name.
In the past we used the *unique* from the parent, but that's not stable across
recompilations as uniques are nondeterministic.
-}
| shlevy/ghc | compiler/typecheck/TcGenDeriv.hs | bsd-3-clause | 87,178 | 0 | 20 | 27,803 | 15,778 | 8,238 | 7,540 | 1,171 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module Stack.Options.BenchParser where
import Data.Monoid.Extra
import Options.Applicative
import Options.Applicative.Builder.Extra
import Stack.Options.Utils
import Stack.Types.Config
-- | Parser for bench arguments.
-- FIXME hiding options
benchOptsParser :: Bool -> Parser BenchmarkOptsMonoid
benchOptsParser hide0 = BenchmarkOptsMonoid
<$> optionalFirst (strOption (long "benchmark-arguments" <>
long "ba" <>
metavar "BENCH_ARGS" <>
help ("Forward BENCH_ARGS to the benchmark suite. " <>
"Supports templates from `cabal bench`") <>
hide))
<*> optionalFirst (switch (long "no-run-benchmarks" <>
help "Disable running of benchmarks. (Benchmarks will still be built.)" <>
hide))
where hide = hideMods hide0
| mrkkrp/stack | src/Stack/Options/BenchParser.hs | bsd-3-clause | 1,046 | 0 | 15 | 391 | 151 | 81 | 70 | 19 | 1 |
{- |
Module : $Header$
Description : Some additional helper functions
Copyright : (c) Dominik Luecke, Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : luecke@informatik.uni-bremen.de
Stability : experimental
Portability : non-portable (imports Logic.Logic)
Some helper functions for Propositional Logic
-}
{-
Ref.
http://en.wikipedia.org/wiki/Propositional_logic
Till Mossakowski, Joseph Goguen, Razvan Diaconescu, Andrzej Tarlecki.
What is a Logic?.
In Jean-Yves Beziau (Ed.), Logica Universalis, pp. 113-@133. Birkhaeuser.
2005.
-}
module Propositional.Tools
( flatten -- "flattening" of specs
, flattenDis -- "flattening" of disjunctions
) where
import Propositional.AS_BASIC_Propositional
{- | the flatten functions use associtivity to "flatten" the syntax
tree of the formulae.
flatten \"flattens\" formulae under the assumption of the
semantics of basic specs, this means that we put each
\"clause\" into a single formula for CNF we really will obtain
clauses. -}
flatten :: FORMULA -> [FORMULA]
flatten f = case f of
Conjunction fs _ -> concatMap flatten fs
_ -> [f]
-- | "flattening" for disjunctions
flattenDis :: FORMULA -> [FORMULA]
flattenDis f = case f of
Disjunction fs _ -> concatMap flattenDis fs
_ -> [f]
| mariefarrell/Hets | Propositional/Tools.hs | gpl-2.0 | 1,356 | 0 | 8 | 292 | 123 | 68 | 55 | 12 | 2 |
{-# LANGUAGE DerivingStrategies #-}
{-# OPTIONS_GHC -Wmissing-deriving-strategies #-}
module T15798a () where
data Foo a = Foo a
deriving stock (Eq)
data Bar a = Bar a
deriving (Eq, Show)
deriving stock (Ord)
| sdiehl/ghc | testsuite/tests/rename/should_compile/T15798a.hs | bsd-3-clause | 219 | 0 | 6 | 43 | 58 | 35 | 23 | 8 | 0 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
import Distribution.Simple
main = defaultMain
| Ye-Yong-Chi/codeworld | codeworld-server/Setup.hs | apache-2.0 | 646 | 0 | 4 | 120 | 12 | 7 | 5 | 2 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Code generation for foreign calls.
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmForeign (
cgForeignCall,
emitPrimCall, emitCCall,
emitForeignCall, -- For CmmParse
emitSaveThreadState,
saveThreadState,
emitLoadThreadState,
loadThreadState,
emitOpenNursery,
emitCloseNursery,
) where
#include "HsVersions.h"
import StgSyn
import StgCmmProf (storeCurCCS, ccsType, curCCS)
import StgCmmEnv
import StgCmmMonad
import StgCmmUtils
import StgCmmClosure
import StgCmmLayout
import Cmm
import CmmUtils
import MkGraph
import Type
import TysPrim
import CLabel
import SMRep
import ForeignCall
import DynFlags
import Maybes
import Outputable
import BasicTypes
import Control.Monad
#if __GLASGOW_HASKELL__ >= 709
import Prelude hiding( succ, (<*>) )
#else
import Prelude hiding( succ )
#endif
-----------------------------------------------------------------------------
-- Code generation for Foreign Calls
-----------------------------------------------------------------------------
-- | emit code for a foreign call, and return the results to the sequel.
--
cgForeignCall :: ForeignCall -- the op
-> [StgArg] -- x,y arguments
-> Type -- result type
-> FCode ReturnKind
cgForeignCall (CCall (CCallSpec target cconv safety)) stg_args res_ty
= do { dflags <- getDynFlags
; let -- in the stdcall calling convention, the symbol needs @size appended
-- to it, where size is the total number of bytes of arguments. We
-- attach this info to the CLabel here, and the CLabel pretty printer
-- will generate the suffix when the label is printed.
call_size args
| StdCallConv <- cconv = Just (sum (map arg_size args))
| otherwise = Nothing
-- ToDo: this might not be correct for 64-bit API
arg_size (arg, _) = max (widthInBytes $ typeWidth $ cmmExprType dflags arg)
(wORD_SIZE dflags)
; cmm_args <- getFCallArgs stg_args
; (res_regs, res_hints) <- newUnboxedTupleRegs res_ty
; let ((call_args, arg_hints), cmm_target)
= case target of
StaticTarget _ _ False ->
panic "cgForeignCall: unexpected FFI value import"
StaticTarget lbl mPkgId True
-> let labelSource
= case mPkgId of
Nothing -> ForeignLabelInThisPackage
Just pkgId -> ForeignLabelInPackage pkgId
size = call_size cmm_args
in ( unzip cmm_args
, CmmLit (CmmLabel
(mkForeignLabel lbl size labelSource IsFunction)))
DynamicTarget -> case cmm_args of
(fn,_):rest -> (unzip rest, fn)
[] -> panic "cgForeignCall []"
fc = ForeignConvention cconv arg_hints res_hints CmmMayReturn
call_target = ForeignTarget cmm_target fc
-- we want to emit code for the call, and then emitReturn.
-- However, if the sequel is AssignTo, we shortcut a little
-- and generate a foreign call that assigns the results
-- directly. Otherwise we end up generating a bunch of
-- useless "r = r" assignments, which are not merely annoying:
-- they prevent the common block elimination from working correctly
-- in the case of a safe foreign call.
-- See Note [safe foreign call convention]
--
; sequel <- getSequel
; case sequel of
AssignTo assign_to_these _ ->
emitForeignCall safety assign_to_these call_target call_args
_something_else ->
do { _ <- emitForeignCall safety res_regs call_target call_args
; emitReturn (map (CmmReg . CmmLocal) res_regs)
}
}
{- Note [safe foreign call convention]
The simple thing to do for a safe foreign call would be the same as an
unsafe one: just
emitForeignCall ...
emitReturn ...
but consider what happens in this case
case foo x y z of
(# s, r #) -> ...
The sequel is AssignTo [r]. The call to newUnboxedTupleRegs picks [r]
as the result reg, and we generate
r = foo(x,y,z) returns to L1 -- emitForeignCall
L1:
r = r -- emitReturn
goto L2
L2:
...
Now L1 is a proc point (by definition, it is the continuation of the
safe foreign call). If L2 does a heap check, then L2 will also be a
proc point.
Furthermore, the stack layout algorithm has to arrange to save r
somewhere between the call and the jump to L1, which is annoying: we
would have to treat r differently from the other live variables, which
have to be saved *before* the call.
So we adopt a special convention for safe foreign calls: the results
are copied out according to the NativeReturn convention by the call,
and the continuation of the call should copyIn the results. (The
copyOut code is actually inserted when the safe foreign call is
lowered later). The result regs attached to the safe foreign call are
only used temporarily to hold the results before they are copied out.
We will now generate this:
r = foo(x,y,z) returns to L1
L1:
r = R1 -- copyIn, inserted by mkSafeCall
goto L2
L2:
... r ...
And when the safe foreign call is lowered later (see Note [lower safe
foreign calls]) we get this:
suspendThread()
r = foo(x,y,z)
resumeThread()
R1 = r -- copyOut, inserted by lowerSafeForeignCall
jump L1
L1:
r = R1 -- copyIn, inserted by mkSafeCall
goto L2
L2:
... r ...
Now consider what happens if L2 does a heap check: the Adams
optimisation kicks in and commons up L1 with the heap-check
continuation, resulting in just one proc point instead of two. Yay!
-}
emitCCall :: [(CmmFormal,ForeignHint)]
-> CmmExpr
-> [(CmmActual,ForeignHint)]
-> FCode ()
emitCCall hinted_results fn hinted_args
= void $ emitForeignCall PlayRisky results target args
where
(args, arg_hints) = unzip hinted_args
(results, result_hints) = unzip hinted_results
target = ForeignTarget fn fc
fc = ForeignConvention CCallConv arg_hints result_hints CmmMayReturn
emitPrimCall :: [CmmFormal] -> CallishMachOp -> [CmmActual] -> FCode ()
emitPrimCall res op args
= void $ emitForeignCall PlayRisky res (PrimTarget op) args
-- alternative entry point, used by CmmParse
emitForeignCall
:: Safety
-> [CmmFormal] -- where to put the results
-> ForeignTarget -- the op
-> [CmmActual] -- arguments
-> FCode ReturnKind
emitForeignCall safety results target args
| not (playSafe safety) = do
dflags <- getDynFlags
let (caller_save, caller_load) = callerSaveVolatileRegs dflags
emit caller_save
target' <- load_target_into_temp target
args' <- mapM maybe_assign_temp args
emit $ mkUnsafeCall target' results args'
emit caller_load
return AssignedDirectly
| otherwise = do
dflags <- getDynFlags
updfr_off <- getUpdFrameOff
target' <- load_target_into_temp target
args' <- mapM maybe_assign_temp args
k <- newLabelC
let (off, _, copyout) = copyInOflow dflags NativeReturn (Young k) results []
-- see Note [safe foreign call convention]
tscope <- getTickScope
emit $
( mkStore (CmmStackSlot (Young k) (widthInBytes (wordWidth dflags)))
(CmmLit (CmmBlock k))
<*> mkLast (CmmForeignCall { tgt = target'
, res = results
, args = args'
, succ = k
, ret_args = off
, ret_off = updfr_off
, intrbl = playInterruptible safety })
<*> mkLabel k tscope
<*> copyout
)
return (ReturnedTo k off)
load_target_into_temp :: ForeignTarget -> FCode ForeignTarget
load_target_into_temp (ForeignTarget expr conv) = do
tmp <- maybe_assign_temp expr
return (ForeignTarget tmp conv)
load_target_into_temp other_target@(PrimTarget _) =
return other_target
-- What we want to do here is create a new temporary for the foreign
-- call argument if it is not safe to use the expression directly,
-- because the expression mentions caller-saves GlobalRegs (see
-- Note [Register Parameter Passing]).
--
-- However, we can't pattern-match on the expression here, because
-- this is used in a loop by CmmParse, and testing the expression
-- results in a black hole. So we always create a temporary, and rely
-- on CmmSink to clean it up later. (Yuck, ToDo). The generated code
-- ends up being the same, at least for the RTS .cmm code.
--
maybe_assign_temp :: CmmExpr -> FCode CmmExpr
maybe_assign_temp e = do
dflags <- getDynFlags
reg <- newTemp (cmmExprType dflags e)
emitAssign (CmmLocal reg) e
return (CmmReg (CmmLocal reg))
-- -----------------------------------------------------------------------------
-- Save/restore the thread state in the TSO
-- This stuff can't be done in suspendThread/resumeThread, because it
-- refers to global registers which aren't available in the C world.
emitSaveThreadState :: FCode ()
emitSaveThreadState = do
dflags <- getDynFlags
tso <- newTemp (gcWord dflags)
cn <- newTemp (bWord dflags)
emit $ saveThreadState dflags tso cn
-- saveThreadState must be usable from the stack layout pass, where we
-- don't have FCode. Therefore it takes LocalRegs as arguments, so
-- the caller can create these.
saveThreadState :: DynFlags -> LocalReg -> LocalReg -> CmmAGraph
saveThreadState dflags tso cn =
catAGraphs [
-- tso = CurrentTSO;
mkAssign (CmmLocal tso) stgCurrentTSO,
-- tso->stackobj->sp = Sp;
mkStore (cmmOffset dflags (CmmLoad (cmmOffset dflags (CmmReg (CmmLocal tso)) (tso_stackobj dflags)) (bWord dflags)) (stack_SP dflags)) stgSp,
closeNursery dflags tso cn,
-- and save the current cost centre stack in the TSO when profiling:
if gopt Opt_SccProfilingOn dflags then
mkStore (cmmOffset dflags (CmmReg (CmmLocal tso)) (tso_CCCS dflags)) curCCS
else mkNop
]
emitCloseNursery :: FCode ()
emitCloseNursery = do
dflags <- getDynFlags
tso <- newTemp (gcWord dflags)
cn <- newTemp (bWord dflags)
emit $ mkAssign (CmmLocal tso) stgCurrentTSO <*>
closeNursery dflags tso cn
{-
Closing the nursery corresponds to the following code:
tso = CurrentTSO;
cn = CurrentNuresry;
// Update the allocation limit for the current thread. We don't
// check to see whether it has overflowed at this point, that check is
// made when we run out of space in the current heap block (stg_gc_noregs)
// and in the scheduler when context switching (schedulePostRunThread).
tso->alloc_limit -= Hp + WDS(1) - cn->start;
// Set cn->free to the next unoccupied word in the block
cn->free = Hp + WDS(1);
-}
closeNursery :: DynFlags -> LocalReg -> LocalReg -> CmmAGraph
closeNursery df tso cn =
let
tsoreg = CmmLocal tso
cnreg = CmmLocal cn
in
catAGraphs [
mkAssign cnreg stgCurrentNursery,
-- CurrentNursery->free = Hp+1;
mkStore (nursery_bdescr_free df cnreg) (cmmOffsetW df stgHp 1),
let alloc =
CmmMachOp (mo_wordSub df)
[ cmmOffsetW df stgHp 1
, CmmLoad (nursery_bdescr_start df cnreg) (bWord df)
]
alloc_limit = cmmOffset df (CmmReg tsoreg) (tso_alloc_limit df)
in
-- tso->alloc_limit += alloc
mkStore alloc_limit (CmmMachOp (MO_Sub W64)
[ CmmLoad alloc_limit b64
, CmmMachOp (mo_WordTo64 df) [alloc] ])
]
emitLoadThreadState :: FCode ()
emitLoadThreadState = do
dflags <- getDynFlags
tso <- newTemp (gcWord dflags)
stack <- newTemp (gcWord dflags)
cn <- newTemp (bWord dflags)
bdfree <- newTemp (bWord dflags)
bdstart <- newTemp (bWord dflags)
emit $ loadThreadState dflags tso stack cn bdfree bdstart
-- loadThreadState must be usable from the stack layout pass, where we
-- don't have FCode. Therefore it takes LocalRegs as arguments, so
-- the caller can create these.
loadThreadState :: DynFlags
-> LocalReg -> LocalReg -> LocalReg -> LocalReg -> LocalReg
-> CmmAGraph
loadThreadState dflags tso stack cn bdfree bdstart =
catAGraphs [
-- tso = CurrentTSO;
mkAssign (CmmLocal tso) stgCurrentTSO,
-- stack = tso->stackobj;
mkAssign (CmmLocal stack) (CmmLoad (cmmOffset dflags (CmmReg (CmmLocal tso)) (tso_stackobj dflags)) (bWord dflags)),
-- Sp = stack->sp;
mkAssign sp (CmmLoad (cmmOffset dflags (CmmReg (CmmLocal stack)) (stack_SP dflags)) (bWord dflags)),
-- SpLim = stack->stack + RESERVED_STACK_WORDS;
mkAssign spLim (cmmOffsetW dflags (cmmOffset dflags (CmmReg (CmmLocal stack)) (stack_STACK dflags))
(rESERVED_STACK_WORDS dflags)),
-- HpAlloc = 0;
-- HpAlloc is assumed to be set to non-zero only by a failed
-- a heap check, see HeapStackCheck.cmm:GC_GENERIC
mkAssign hpAlloc (zeroExpr dflags),
openNursery dflags tso cn bdfree bdstart,
-- and load the current cost centre stack from the TSO when profiling:
if gopt Opt_SccProfilingOn dflags
then storeCurCCS
(CmmLoad (cmmOffset dflags (CmmReg (CmmLocal tso))
(tso_CCCS dflags)) (ccsType dflags))
else mkNop
]
emitOpenNursery :: FCode ()
emitOpenNursery = do
dflags <- getDynFlags
tso <- newTemp (gcWord dflags)
cn <- newTemp (bWord dflags)
bdfree <- newTemp (bWord dflags)
bdstart <- newTemp (bWord dflags)
emit $ mkAssign (CmmLocal tso) stgCurrentTSO <*>
openNursery dflags tso cn bdfree bdstart
{-
Opening the nursery corresponds to the following code:
tso = CurrentTSO;
cn = CurrentNursery;
bdfree = CurrentNuresry->free;
bdstart = CurrentNuresry->start;
// We *add* the currently occupied portion of the nursery block to
// the allocation limit, because we will subtract it again in
// closeNursery.
tso->alloc_limit += bdfree - bdstart;
// Set Hp to the last occupied word of the heap block. Why not the
// next unocupied word? Doing it this way means that we get to use
// an offset of zero more often, which might lead to slightly smaller
// code on some architectures.
Hp = bdfree - WDS(1);
// Set HpLim to the end of the current nursery block (note that this block
// might be a block group, consisting of several adjacent blocks.
HpLim = bdstart + CurrentNursery->blocks*BLOCK_SIZE_W - 1;
-}
openNursery :: DynFlags
-> LocalReg -> LocalReg -> LocalReg -> LocalReg
-> CmmAGraph
openNursery df tso cn bdfree bdstart =
let
tsoreg = CmmLocal tso
cnreg = CmmLocal cn
bdfreereg = CmmLocal bdfree
bdstartreg = CmmLocal bdstart
in
-- These assignments are carefully ordered to reduce register
-- pressure and generate not completely awful code on x86. To see
-- what code we generate, look at the assembly for
-- stg_returnToStackTop in rts/StgStartup.cmm.
catAGraphs [
mkAssign cnreg stgCurrentNursery,
mkAssign bdfreereg (CmmLoad (nursery_bdescr_free df cnreg) (bWord df)),
-- Hp = CurrentNursery->free - 1;
mkAssign hp (cmmOffsetW df (CmmReg bdfreereg) (-1)),
mkAssign bdstartreg (CmmLoad (nursery_bdescr_start df cnreg) (bWord df)),
-- HpLim = CurrentNursery->start +
-- CurrentNursery->blocks*BLOCK_SIZE_W - 1;
mkAssign hpLim
(cmmOffsetExpr df
(CmmReg bdstartreg)
(cmmOffset df
(CmmMachOp (mo_wordMul df) [
CmmMachOp (MO_SS_Conv W32 (wordWidth df))
[CmmLoad (nursery_bdescr_blocks df cnreg) b32],
mkIntExpr df (bLOCK_SIZE df)
])
(-1)
)
),
-- alloc = bd->free - bd->start
let alloc =
CmmMachOp (mo_wordSub df) [CmmReg bdfreereg, CmmReg bdstartreg]
alloc_limit = cmmOffset df (CmmReg tsoreg) (tso_alloc_limit df)
in
-- tso->alloc_limit += alloc
mkStore alloc_limit (CmmMachOp (MO_Add W64)
[ CmmLoad alloc_limit b64
, CmmMachOp (mo_WordTo64 df) [alloc] ])
]
nursery_bdescr_free, nursery_bdescr_start, nursery_bdescr_blocks
:: DynFlags -> CmmReg -> CmmExpr
nursery_bdescr_free dflags cn =
cmmOffset dflags (CmmReg cn) (oFFSET_bdescr_free dflags)
nursery_bdescr_start dflags cn =
cmmOffset dflags (CmmReg cn) (oFFSET_bdescr_start dflags)
nursery_bdescr_blocks dflags cn =
cmmOffset dflags (CmmReg cn) (oFFSET_bdescr_blocks dflags)
tso_stackobj, tso_CCCS, tso_alloc_limit, stack_STACK, stack_SP :: DynFlags -> ByteOff
tso_stackobj dflags = closureField dflags (oFFSET_StgTSO_stackobj dflags)
tso_alloc_limit dflags = closureField dflags (oFFSET_StgTSO_alloc_limit dflags)
tso_CCCS dflags = closureField dflags (oFFSET_StgTSO_cccs dflags)
stack_STACK dflags = closureField dflags (oFFSET_StgStack_stack dflags)
stack_SP dflags = closureField dflags (oFFSET_StgStack_sp dflags)
closureField :: DynFlags -> ByteOff -> ByteOff
closureField dflags off = off + fixedHdrSize dflags
stgSp, stgHp, stgCurrentTSO, stgCurrentNursery :: CmmExpr
stgSp = CmmReg sp
stgHp = CmmReg hp
stgCurrentTSO = CmmReg currentTSO
stgCurrentNursery = CmmReg currentNursery
sp, spLim, hp, hpLim, currentTSO, currentNursery, hpAlloc :: CmmReg
sp = CmmGlobal Sp
spLim = CmmGlobal SpLim
hp = CmmGlobal Hp
hpLim = CmmGlobal HpLim
currentTSO = CmmGlobal CurrentTSO
currentNursery = CmmGlobal CurrentNursery
hpAlloc = CmmGlobal HpAlloc
-- -----------------------------------------------------------------------------
-- For certain types passed to foreign calls, we adjust the actual
-- value passed to the call. For ByteArray#/Array# we pass the
-- address of the actual array, not the address of the heap object.
getFCallArgs :: [StgArg] -> FCode [(CmmExpr, ForeignHint)]
-- (a) Drop void args
-- (b) Add foreign-call shim code
-- It's (b) that makes this differ from getNonVoidArgAmodes
getFCallArgs args
= do { mb_cmms <- mapM get args
; return (catMaybes mb_cmms) }
where
get arg | isVoidRep arg_rep
= return Nothing
| otherwise
= do { cmm <- getArgAmode (NonVoid arg)
; dflags <- getDynFlags
; return (Just (add_shim dflags arg_ty cmm, hint)) }
where
arg_ty = stgArgType arg
arg_rep = typePrimRep arg_ty
hint = typeForeignHint arg_ty
add_shim :: DynFlags -> Type -> CmmExpr -> CmmExpr
add_shim dflags arg_ty expr
| tycon == arrayPrimTyCon || tycon == mutableArrayPrimTyCon
= cmmOffsetB dflags expr (arrPtrsHdrSize dflags)
| tycon == smallArrayPrimTyCon || tycon == smallMutableArrayPrimTyCon
= cmmOffsetB dflags expr (smallArrPtrsHdrSize dflags)
| tycon == byteArrayPrimTyCon || tycon == mutableByteArrayPrimTyCon
= cmmOffsetB dflags expr (arrWordsHdrSize dflags)
| otherwise = expr
where
UnaryRep rep_ty = repType arg_ty
tycon = tyConAppTyCon rep_ty
-- should be a tycon app, since this is a foreign call
| forked-upstream-packages-for-ghcjs/ghc | compiler/codeGen/StgCmmForeign.hs | bsd-3-clause | 20,003 | 0 | 21 | 5,426 | 3,542 | 1,816 | 1,726 | 288 | 6 |
module THInSubdir (thFuncC) where
import Language.Haskell.TH
thFuncC :: Q Exp
thFuncC = runIO $ do
readFile "files/file.txt"
return $ LitE (IntegerL 5)
| mrkkrp/stack | test/integration/tests/717-sdist-test/files/subdirs/failing-in-subdir/src/THInSubdir.hs | bsd-3-clause | 158 | 0 | 11 | 28 | 54 | 28 | 26 | 6 | 1 |
import Test.Cabal.Prelude
main = setupAndCabalTest $ do
skipUnless =<< ghcVersionIs (>= mkVersion [8,1])
setup "configure" []
setup "build" []
| mydaum/cabal | cabal-testsuite/PackageTests/Backpack/TemplateHaskell/setup.test.hs | bsd-3-clause | 155 | 0 | 12 | 31 | 59 | 29 | 30 | 5 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- Tests newtype unwrapping for the IO monad itself
-- Notice the RenderM monad, which is used in the
-- type of the callback function
module ShouldCompile where
import Control.Applicative (Applicative)
import Foreign.Ptr
newtype RenderM a = RenderM (IO a) deriving (Functor, Applicative, Monad)
type RenderCallback = Int -> Int -> RenderM ()
foreign import ccall duma_onRender :: FunPtr RenderCallback -> RenderM ()
foreign import ccall "wrapper" mkRenderCallback
:: RenderCallback -> RenderM (FunPtr RenderCallback)
onRender :: RenderCallback -> RenderM ()
onRender f = mkRenderCallback f >>= duma_onRender
| ezyang/ghc | testsuite/tests/ffi/should_compile/ffi-deriv1.hs | bsd-3-clause | 669 | 0 | 9 | 107 | 148 | 81 | 67 | 11 | 1 |
module Dummy2 where
import Distribution.TestSuite (Test)
tests :: IO [Test]
tests = return []
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/tests/PackageTests/BuildTestSuiteDetailedV09/Dummy2.hs | bsd-3-clause | 96 | 0 | 6 | 16 | 35 | 20 | 15 | 4 | 1 |
-- Ordered Count of Characters
-- https://www.codewars.com/kata/57a6633153ba33189e000074
module Kata where
import Data.List (partition)
orderedCount :: String -> [(Char, Int)]
orderedCount [] = []
orderedCount (x:xs) = let (s, d) = partition (== x) xs in (x, succ . length $ s) : orderedCount d
| gafiatulin/codewars | src/7 kyu/OrderedCount.hs | mit | 298 | 0 | 10 | 47 | 109 | 61 | 48 | 5 | 1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.GenericRefreshProtocolProtos.GenericRefreshProtocolService
(GenericRefreshProtocolService, genericRefreshProtocolService, Refresh, refresh) 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'
import qualified Hadoop.Protos.GenericRefreshProtocolProtos.GenericRefreshRequestProto as GenericRefreshProtocolProtos
(GenericRefreshRequestProto)
import qualified Hadoop.Protos.GenericRefreshProtocolProtos.GenericRefreshResponseCollectionProto as GenericRefreshProtocolProtos
(GenericRefreshResponseCollectionProto)
type GenericRefreshProtocolService = P'.Service '[Refresh]
genericRefreshProtocolService :: GenericRefreshProtocolService
genericRefreshProtocolService = P'.Service
type Refresh =
P'.Method ".hadoop.common.GenericRefreshProtocolService.refresh" GenericRefreshProtocolProtos.GenericRefreshRequestProto
GenericRefreshProtocolProtos.GenericRefreshResponseCollectionProto
refresh :: Refresh
refresh = P'.Method | alexbiehl/hoop | hadoop-protos/src/Hadoop/Protos/GenericRefreshProtocolProtos/GenericRefreshProtocolService.hs | mit | 1,280 | 0 | 7 | 119 | 164 | 111 | 53 | 21 | 1 |
data Day = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Show, Eq, Enum, Bounded)
data Month = Jan | Feb | Mar | Apr | May | Jun | July | Aug | Sept | Oct | Nov | Dec deriving (Show, Eq, Enum, Bounded)
next :: (Eq a, Enum a, Bounded a) => a -> a
next d = if d == maxBound then minBound else succ d
back :: (Eq a, Enum a, Bounded a) => a -> a
back d = if d == minBound then maxBound else pred d
applyN:: Int -> (a -> a) -> (a -> a)
applyN n _ | n < 1 = id
applyN n f = (applyN (n-1) f) . f
newtype DayOfMonth = DayOfMonth { intValue :: Int } deriving (Show)
newtype Year = Year { unYear :: Int } deriving (Show, Ord, Eq)
nextYear :: Year -> Year
nextYear (Year i) = Year (i+1)
lastYear :: Year -> Year
lastYear (Year i) = Year (i-1)
data Date = Date { dayOfWeek :: Day, dayOfMonth :: DayOfMonth, year :: Year, month :: Month} deriving (Show)
--- 1 Jan 1900 was a Monday.
--- Thirty days has September, --- April, June and November.
--- All the rest have thirty-one,
--- Saving February alone,
--- Which has twenty-eight, rain or shine.
--- And on leap years, twenty-nine.
--- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
--- How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
daysInMonth :: Month -> Year -> Int
daysInMonth Feb y = if isLeap y then 29 else 28
daysInMonth Jan _ = 31
daysInMonth Mar _ = 31
daysInMonth Apr _ = 30
daysInMonth May _ = 31
daysInMonth Jun _ = 30
daysInMonth July _ = 31
daysInMonth Aug _ = 31
daysInMonth Sept _ = 30
daysInMonth Oct _ = 31
daysInMonth Nov _ = 30
daysInMonth Dec _ = 31
isLeap :: Year -> Bool
isLeap (Year i) = if multOf 400 then True
else and [multOf 4, (not . multOf) 100]
where
multOf :: Int -> Bool
multOf = (== 0) . mod i
nextDate :: Date -> Date
nextDate date = Date { dayOfWeek = next $ dayOfWeek date, dayOfMonth = dm', year = y', month = m' }
where
nextMonth :: Bool
nextMonth = intDm == (daysInMonth (month date) (year date))
intDm = (intValue . dayOfMonth) date
dm' = if nextMonth then DayOfMonth 1 else DayOfMonth (intDm + 1)
m' = ((if nextMonth then next else id) . month) date
isNextYear :: Bool
isNextYear = and [nextMonth, month date == maxBound]
y' = ((if isNextYear then nextYear else id) . year) date
basis :: Date
basis = Date { dayOfWeek = Monday, dayOfMonth = DayOfMonth 1, year = Year 1900, month = Jan }
foreverDates :: [Date]
foreverDates = iterate nextDate basis
numSundays :: Int
numSundays = length $ takeWhile ((< Year 2001) . year) $ filter ((== Sunday) . dayOfWeek) foreverDates
main :: IO ()
main = putStrLn $ "Number of Sundays in 20th Century: " ++ (show numSundays)
| nlim/haskell-playground | src/Euler19.hs | mit | 2,831 | 0 | 11 | 681 | 1,020 | 563 | 457 | 52 | 4 |
{-
Coin sums
Problem 31
In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
-}
coins' 0 _ = 1
coins' value previous = sum [ coins' (value-coin) coin
| coin <- [1,2,5,10,20,50,100,200]
, coin <= value
, coin <= previous
]
coins value = coins' value 200
euler31 = coins 200
--
-- (17.38 secs, 2791918820 bytes)
--2) http://projecteuler.net/overview=031 (A)
coinValues = [ 1, 2, 5, 10, 20, 50, 100 , 200, -1 ]
ways' target avc res
| avc <= 0 = 1
| target > 0 = ways' (target - coinValues !! avc) avc (res + ways' target (avc-1) 0)
| otherwise = res
ways amount = ways' amount 7 0
euler31' = ways 200
-- (0.17 secs, 25812320 bytes)
--3) http://projecteuler.net/overview=031 (B)
euler31fast = looper 0 (coinValues !! 1) (0:1:(replicate 200 0))
coinValues' = [ 0, 1, 2, 5, 10, 20, 50, 100 , 200, -1 ]
looper i j ways
| i > 8 = ways !! 200
| j > 200 = looper (i+1) (coinValues!!(i+1)) ways
| otherwise = looper i (j+1) newWays
where newWays = take j ways ++ [ways!!j + ways!!(j-coinValues!!i)] ++ drop (j+1) ways
-- Not working properly. Some off-by-1 errors in the way | feliposz/project-euler-solutions | haskell/euler31.hs | mit | 1,493 | 0 | 13 | 410 | 478 | 255 | 223 | 21 | 1 |
import Prime
import Test.HUnit
test1 = TestCase(assertEqual "2 should be prime" True (isPrime 2))
test2 = TestCase(assertEqual "4 should not be prime" False (isPrime 4))
test3 = TestCase(assertEqual "7 should be prime" True (isPrime 7))
testList = TestList[ test1, test2, test3 ]
main = do runTestTT testList
| RadoRado/HUnit-Test-Generator | PrimeTests.hs | mit | 310 | 0 | 9 | 48 | 109 | 56 | 53 | 7 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Network.AMQP.Internal.Types
( Connection (..)
, Exchange (..)
, ExchangeName (..)
, Message (..)
, MessageHandler (..)
, Queue (..)
, QueueName (..)
, QueueStatus (..)
, TopicName (..)
, WithConn (..)
) where
import Network.AMQP.Config as Config (RabbitMQConfig (..))
import Control.Monad.Reader
import Data.Text (Text)
import qualified Network.AMQP as AMQP
newtype WithConn a = WithConn { runConn :: ReaderT Connection IO a }
deriving (Functor, Applicative, Monad, MonadReader Connection, MonadIO)
data Connection =
Connection { getConnection :: AMQP.Connection
, getChannel :: AMQP.Channel
, getConfig :: RabbitMQConfig
}
data Exchange =
Exchange { getExchangeName :: Text
, getExchangeType :: Text
, getIsDurable :: Bool
}
data Queue =
Queue { getQueueName :: Text
, getQueueAutoDelete :: Bool
, getQueueIsDurable :: Bool
}
newtype QueueStatus = QueueStatus (Text, MessageCount, ConsumerCount)
deriving (Show, Read, Eq)
type MessageCount = Int
type ConsumerCount = Int
newtype ExchangeName = ExchangeName Text
newtype QueueName = QueueName Text
newtype TopicName = TopicName Text
newtype Message a = Message a
newtype MessageHandler = MessageHandler { processMessage :: (AMQP.Message, AMQP.Envelope) -> IO () }
| gust/feature-creature | amqp-client/src/Network/AMQP/Internal/Types.hs | mit | 1,436 | 0 | 9 | 349 | 362 | 232 | 130 | 39 | 0 |
module Example where
import qualified NLP.Tokenize.Chatter as Tk
| karimamer/talks | haskell talks/nlp in haskell/tokenizeexample.hs | mit | 67 | 0 | 4 | 10 | 13 | 10 | 3 | 2 | 0 |
module Core.Grammar (CoreExpr(..),
Expr(..),
Name,
CoreAlt(..),
Alter(..),
CoreProgram(..),
Program(..),
CoreScDefn(..),
ScDefn(..)) where
-- | AST of the Core language
data Expr a = EVar Name -- ^ a variable
| ENum Int -- ^ an Int
| EConstr Int Int [Expr a] -- ^ a type declaration
| EAp (Expr a) (Expr a) -- ^ function application
| ELet Bool [(a, Expr a)] (Expr a) -- ^ let/letrec expression
| ECase (Expr a) [Alter a] -- ^ case expression
| ELam [a] (Expr a) -- ^ lambda expression (not yet implemented)
deriving (Show, Eq)
-- | A Core expression
type CoreExpr = Expr Name
type Name = String
-- | a case alternative for a given datatype
type Alter a = (Int -- ^ the datatype number
,[a] -- ^ a list of local variable names
, Expr a -- ^ the expression that the case evaluates to
)
-- | a case alternative
type CoreAlt = Alter Name
type Program a = [ScDefn a]
-- | A list of super combinator definitions
type CoreProgram = Program Name
type ScDefn a = (Name -- ^ the name of the function/global
,[a] -- ^ the list of local variable names
, Expr a -- ^ the expression the supercombinator evaluates to
)
-- | A supercombinator definition
type CoreScDefn = ScDefn Name | aneksteind/Core | src/Core/Grammar.hs | mit | 1,521 | 0 | 9 | 573 | 307 | 193 | 114 | 29 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Jira.API.Types.Status where
import Data.Aeson
import qualified Data.CaseInsensitive as CI
data Status = Open
| InProgress
| Resolved
| Closed
| CustomStatus String
deriving (Eq, Ord)
instance Show Status where
show Open = "Open"
show InProgress = "In Progress"
show Resolved = "Resolved"
show Closed = "Closed"
show (CustomStatus s) = s
instance FromJSON Status where
parseJSON = withObject "Expected object" $ \o -> do
statusName <- o .: "name"
return $ case CI.mk statusName of
"Open" -> Open
"In Progress" -> InProgress
"Resolved" -> Resolved
"Closed" -> Closed
_ -> CustomStatus statusName
| dsmatter/jira-api | src/Jira/API/Types/Status.hs | mit | 824 | 0 | 14 | 285 | 193 | 103 | 90 | 25 | 0 |
module Moonbase.Util.Gtk.Widget
(
) where
| felixsch/moonbase-gtk | src/Moonbase/Util/Gtk/Widget.hs | gpl-2.0 | 49 | 0 | 3 | 12 | 11 | 8 | 3 | 2 | 0 |
module Cryptography.ComputationalProblems.Games.BitGuessingProblems.Terms where
import Notes
makeDefs
[ "deterministic bit-guessing problem"
, "probabilistic bit-guessing problem"
, "bit-guessing problem"
, "deterministic bit guesser"
, "probabilistic bit guesser"
, "bit guesser"
, "deterministic bit-guessing game"
, "bit-guessing game"
]
| NorfairKing/the-notes | src/Cryptography/ComputationalProblems/Games/BitGuessingProblems/Terms.hs | gpl-2.0 | 389 | 0 | 6 | 84 | 42 | 27 | 15 | -1 | -1 |
{- Piffle, Copyright (C) 2007, Jaap Weel. This program is free
software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option)
any later version. This program is distributed in the hope that it
will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should
have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -}
-- TRANSFORM C -------------------------------------------------------
{- This module simplifies C code. It does transformations that (you'd
hope) the C compiler will do anyway, but they make the output code
look a lot nicer. This module is actually trickier than I thought
it would be, especially because I want to make sure that all
transformations are valid on C code in general, and not just on C
code that I happen to know comes out of the Piffle compiler. I have
fixed several bugs. Please read K&R carefully before adding a
clever new simplification. -}
module CC where
import Control.Monad (liftM)
import C
-- THE C SIMPLIFIER --------------------------------------------------
{- Simplify a file -}
tFile :: File -> File
tFile (File ds) =
File (map tDef ds)
{- Simplify a definition -}
tDef :: Def -> Def
tDef (Fundef s qt i b) =
Fundef s qt i (tBody b)
tDef (Def s qt i e) =
Def s qt i (tMaybeExp e)
tDef d =
d
{- Simplify a body -}
tBody :: Body -> Body
tBody (Body ds ss) =
case (tDef `map` ds, tStat `concatMap` ss) of
(_, []) ->
Body [] []
(ds, [Block (Body ds' ss)]) ->
Body (ds++ds') ss
(ds, ss) ->
Body ds ss
-- SIMPLIFY STATEMENTS -----------------------------------------------
{- Simplify a statement when a single statement is expected (if the
statement simplifies into a list of staments, we wrap a black
around it. If the statement disappears, we insert a lone
semicolon.) -}
tStat1 :: Stat -> Stat
tStat1 s =
case tStat s of
[] ->
Computation Nothing
[x] ->
x
xs ->
Block (Body [] xs)
{- Simplify a statement where any number of statements can be
accomodated. -}
tStat :: Stat -> [Stat]
{- A lone semicolon can be left out of a list of expressions -}
tStat (Computation Nothing) =
[]
{- A GNU block-with-a-value of which the value is ignored is just a
block. -}
tStat (Computation (Just (GnuBody b))) =
tStat (Block b)
{- A ternary expression of which the value is ignored can be more
idiomatically expressed as an if statement. -}
tStat (Computation (Just (Ternary a b c))) =
tStat (If a (computation b) (computation c))
tStat (Computation e) =
[Computation (tMaybeExp e)]
{- If a block has no declarations, it can be spliced into the rest of a
list of statements that it is part of. -}
tStat (Block (Body [] ss)) =
tStat `concatMap` ss
tStat (Block b) =
[Block (tBody b)]
{- If the condition is a constant integer, we don't need the if
statement. -}
tStat (If a b c) =
case tExp a of
LitInt 0 ->
tStat c
LitInt _ ->
tStat b
a' ->
[If a' (tStat1 b) (tStat1 c)]
{- Returning a GNU block-with-a-value is like executing a regular
block and returning the value of the last thing in it. If the last
thing in it has no value, or there is nothing in it, we must add a
"return;" in order to properly preserve the semantics here. (Piffle
never generates code where this matters, which is why I almost got
this case wrong...) -}
tStat (Return (Just (GnuBody body))) =
tStat (Block (returnify body))
where returnify (Body ds ss) = Body ds (returnify' ss)
returnify' [] = [Return Nothing]
returnify' [Computation x] = [Return x]
returnify' (x:xs) = x:(returnify' xs)
tStat (Return (Just (Ternary a b c))) =
[If a (tStat1 (Return (Just b))) (tStat1 (Return (Just c)))]
{- Trivial cases -}
tStat (Return e) =
[Return (tMaybeExp e)]
tStat (While e s) =
[While (tExp e) (tStat1 s)]
tStat (Dowhile e s) =
[Dowhile (tExp e) (tStat1 s)]
tStat (For a b c s) =
[For (tMaybeExp a) (tMaybeExp b) (tMaybeExp c) (tStat1 s)]
tStat (Case e) =
[Case (tExp e)]
tStat s =
[s]
-- SIMPLIFY AN EXPRESSION --------------------------------------------
{- Simplify an expression -}
tExp :: Exp -> Exp
{- Because !, like the comparison and logical operators, guaranteed to
return 0 or 1, !!x is not the same thing as x. (Did Ritchie read
about constructive logic in his spare time and was he ashamed to
admit it?) -}
{- CAN'T DO THIS: tExp (Unary Not (Unary Not e)) = tExp e -}
{- Negating an integer literal is quite predictable. -}
tExp (Unary Not e) =
case tExp e of
LitInt 0 ->
LitInt 1
LitInt _ ->
LitInt 0
e' ->
Unary Not e'
{- If one of the operands to && is a nonzero integer, or the first
operand is 0, we can predict what'll happen. Unfortunately, if the
second operand is 0, we can't do much of anything, because the
first operand must still be evaluated for its side effects. -}
tExp (Binary And a b) =
case (tExp a, tExp b) of
(a, LitInt i) | i /= 0 ->
a
(LitInt i, b) | i /= 0 ->
b
(LitInt 0, _) ->
LitInt 0
(a,b) ->
Binary And a b
{- Only a computer would write code like ({(x);}), but it does always
reduce to x. -}
tExp (GnuBody (Body [] [Computation (Just e)])) =
tExp e
tExp (GnuBody b) =
GnuBody (tBody b)
{- Trivial cases -}
tExp (Unary o e) =
Unary o (tExp e)
tExp (Binary o x y) =
Binary o (tExp x) (tExp y)
tExp (Ternary x y z) =
Ternary (tExp x) (tExp y) (tExp z)
tExp (Cast t e) =
Cast t (tExp e)
tExp (ESize e) =
ESize (tExp e)
tExp (Index x i) =
Index (tExp x) (tExp i)
tExp (Dot e f) =
Dot (tExp e) f
tExp (Arrow e f) =
Arrow (tExp e) f
tExp e =
e
{- Simplify an object of type Maybe Exp -}
tMaybeExp :: Maybe Exp -> Maybe Exp
tMaybeExp =
liftM tExp
| jaapweel/piffle | src/CC.hs | gpl-2.0 | 6,414 | 0 | 13 | 1,723 | 1,552 | 786 | 766 | 116 | 6 |
module Data.Tree.Binary where
import Prelude hiding (lookup)
data Ord a => BTree a b =
Leaf
| Branch a b (BTree a b) (BTree a b)
deriving (Show)
leaf :: BTree a b
leaf = Leaf
branch :: Ord a => a -> b -> BTree a b -> BTree a b -> BTree a b
branch = Branch
left (Branch _ _ l _) = l
right (Branch _ _ _ r) = r
lookup :: Ord a => a -> BTree a b -> Maybe b
lookup _ Leaf = Nothing
lookup key (Branch k v ltree rtree) | key == k = Just v
| key < k = lookup key ltree
| otherwise = lookup key rtree
insert :: Ord a => (a, b) -> BTree a b -> BTree a b
insert (key, val) Leaf = Branch key val Leaf Leaf
insert p@(key, val) (Branch k v ltree rtree) | key == k = Branch key val ltree rtree
| key < k = Branch k v (insert p ltree) rtree
| otherwise = Branch k v ltree (insert p rtree)
minBranch :: Ord a => BTree a b -> BTree a b
minBranch m@(Branch k v Leaf _) = m
minBranch (Branch _ _ l@(Branch _ _ _ _) _) = minBranch l
minBranch _ = Leaf
delete :: Ord a => a -> BTree a b -> BTree a b
delete _ Leaf = Leaf
delete key (Branch k v ltree Leaf) | key == k = ltree
delete key (Branch k v ltree rtree) | key == k = let mb@(Branch mk mv _ _) = minBranch rtree
in Branch mk mv ltree (delete mk rtree)
| key < k = Branch k v (delete key ltree) rtree
| key > k = Branch k v ltree (delete key ltree)
fromList :: Ord a => [(a, b)] -> BTree a b
fromList = foldr insert Leaf
toList :: Ord key => BTree key value -> [(key, value)]
toList Leaf = []
toList (Branch k v ltree rtree) = ((k, v) : toList ltree) ++ toList rtree | graninas/Haskell-Algorithms | Data/Tree/Binary.hs | gpl-3.0 | 1,654 | 4 | 12 | 506 | 874 | 431 | 443 | 38 | 1 |
{- |
Module : Solver
Description : Solver
Copyright : (c) Frédéric BISSON, 2015
License : GPL-3
Maintainer : zigazou@free.fr
Stability : experimental
Portability : POSIX
The Solver can take a 'Grid' and a 'Dictionary' and searches for all 'DictWord's
that can be constructed in the 'Grid' that appears in the 'Dictionary'.
-}
module Solver.Problem (readCell, readRow, readGrid) where
import Solver.Types (Multiplier (..), Cell (..), Grid, Problem)
import Solver.Helper (translate, readLetter)
import Data.Array
{- |
Read the 'Multiplier' letter in a 'Problem'.
-}
readMultiplier :: Char -> Multiplier
readMultiplier = translate
"dtDT"
[MultiplyLetter 2, MultiplyLetter 3, MultiplyWord 2, MultiplyWord 3]
(MultiplyLetter 1)
{- |
Read a 'Cell' in a 'Problem'. The function eats 2 characters from a 'String'
and returns a tuple composed from the created 'Cell' and the remaining
characters.
-}
readCell :: String -> (Cell, String)
readCell (l : m : remains) =
( Cell { letter = readLetter l, multiplier = readMultiplier m }, remains )
readCell _ = error "Invalid input given to coupleToCell"
{- |
Read a complete row from a 'Problem' and returns a list of 'Cell's.
-}
readRow :: String -> [Cell]
readRow [] = []
readRow string = oneCell : readRow remains
where (oneCell, remains) = readCell string
{- |
Generate a 'Grid' of 'Cell's from a 'Problem'
-}
readGrid :: Problem -> Grid
readGrid = listArray ((0, 0), (3, 3)) . readRow . concat
| Zigazou/RuzzSolver | src/Solver/Problem.hs | gpl-3.0 | 1,487 | 0 | 9 | 284 | 288 | 164 | 124 | 19 | 1 |
f . id == f
id . f == f | hmemcpy/milewski-ctfp-pdf | src/content/1.1/code/haskell/snippet06.hs | gpl-3.0 | 23 | 0 | 6 | 9 | 23 | 10 | 13 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, OverloadedStrings, CPP #-}
{-# OPTIONS_GHC -Wall #-}
module Decommenter (decomment) where
{-
this module exports decomment, which removes:
empty lines
lines beginning with '#'
anything in a line following a '#'
-}
import qualified Data.Text as T (Text, null, lines, unlines,
takeWhile, dropWhile, head)
import qualified Data.Text.IO as TextIO (interact)
import Data.Monoid ((<>))
import Data.String (IsString)
import Data.Char (isSpace)
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>), (<*>))
#endif
main :: IO ()
main = TextIO.interact decomment
decomment :: (Stringy a) => a -> a
decomment = unlines'' . map (dropWhile' isSpace) . removeInlineComments
. removeLines . lines'
removeLines :: (Stringy a) => [a] -> [a]
removeLines = filter $ (&&) <$> (not . null') <*> ((/='#') . head')
removeInlineComments :: (Stringy a) => [a] -> [a]
removeInlineComments = fmap $ takeWhile' (/= ('#'))
class (IsString a, Monoid a) => Stringy a where
head' :: a -> Char
dropWhile' :: (Char -> Bool) -> a -> a
takeWhile' :: (Char -> Bool) -> a -> a
null' :: a -> Bool
lines' :: a -> [a]
-- this is just like the unlines of the Prelude, except no newline at the end
unlines' :: [a] -> a
unlines' [] = ""
unlines' (x:xs) = mconcat $ x : fmap ("\n" <>) xs
-- this unlines has a newline at the end
unlines'' :: [a] -> a
instance Stringy T.Text where
head' = T.head
dropWhile' = T.dropWhile
takeWhile' = T.takeWhile
null' = T.null
lines' = T.lines
unlines'' = T.unlines
instance Stringy [Char] where
head' = head
dropWhile' = dropWhile
takeWhile' = takeWhile
null' = null
lines' = lines
unlines'' = unlines
| ninedotnine/bugfree-computing-machine | src/Decommenter.hs | gpl-3.0 | 1,790 | 0 | 11 | 428 | 535 | 312 | 223 | 43 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Concurrent (forkIO, killThread, threadDelay)
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr,
pgPoolSize, runSqlPool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
import System.Systemd.Daemon (notifyReady, notifyWatchdog)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.List
import Handler.User
import Handler.Subscriptions
import Handler.Events
import Handler.Category
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and return a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applying some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadYamlSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
dog <- forkIO $ handleWatchdog $ appNotifyDelay settings
void $ notifyReady
-- Run the application with Warp
runSettings (warpSettings foundation) app
killThread dog
handleWatchdog :: Int -> IO ()
handleWatchdog delay = forever $ do
threadDelay delay
notifyWatchdog
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerFor App) a -> IO a
db = handler . runDB
| mmarx/minitrue | Application.hs | gpl-3.0 | 7,091 | 0 | 16 | 1,812 | 1,128 | 601 | 527 | -1 | -1 |
module Main where
import Data.Maybe
import ChapterExercises
main :: IO ()
main = do
print $ sequenceA [Just 3, Just 2, Just 1]
print $ sequenceA [x, y]
print $ sequenceA [xs, ys]
print $ summed <$> ((,) <$> xs <*> ys)
print $ fmap summed ((,) <$> xs <*> zs)
print $ bolt 7
print $ fmap bolt z
print $ sequenceA [(>3), (<8), even] 7
print $ foldr (&&) True (sequA 7)
print $ sequA $ fromMaybe 0 s'
print $ bolt $ fromMaybe 0 ys | nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles | Reader/app/Main.hs | gpl-3.0 | 472 | 0 | 12 | 133 | 243 | 122 | 121 | 16 | 1 |
module QHaskell.Expression.Utils.Show.GADTFirstOrder
() where
import QHaskell.MyPrelude
import QHaskell.Expression.GADTFirstOrder as GFO
import QHaskell.Environment.Typed
deriving instance Show (Exp s g a)
instance Show (Env (Exp s g) g') where
show Emp = "Emp"
show (Ext x xs) = "Ext (" ++ show x ++") ("++ show xs ++")"
| shayan-najd/QHaskell | QHaskell/Expression/Utils/Show/GADTFirstOrder.hs | gpl-3.0 | 343 | 0 | 10 | 67 | 119 | 65 | 54 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Instances.GetGuestAttributes
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the specified guest attributes entry.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.getGuestAttributes@.
module Network.Google.Resource.Compute.Instances.GetGuestAttributes
(
-- * REST Resource
InstancesGetGuestAttributesResource
-- * Creating a Request
, instancesGetGuestAttributes
, InstancesGetGuestAttributes
-- * Request Lenses
, iggaProject
, iggaZone
, iggaVariableKey
, iggaQueryPath
, iggaInstance
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instances.getGuestAttributes@ method which the
-- 'InstancesGetGuestAttributes' request conforms to.
type InstancesGetGuestAttributesResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instances" :>
Capture "instance" Text :>
"getGuestAttributes" :>
QueryParam "variableKey" Text :>
QueryParam "queryPath" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GuestAttributes
-- | Returns the specified guest attributes entry.
--
-- /See:/ 'instancesGetGuestAttributes' smart constructor.
data InstancesGetGuestAttributes =
InstancesGetGuestAttributes'
{ _iggaProject :: !Text
, _iggaZone :: !Text
, _iggaVariableKey :: !(Maybe Text)
, _iggaQueryPath :: !(Maybe Text)
, _iggaInstance :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstancesGetGuestAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iggaProject'
--
-- * 'iggaZone'
--
-- * 'iggaVariableKey'
--
-- * 'iggaQueryPath'
--
-- * 'iggaInstance'
instancesGetGuestAttributes
:: Text -- ^ 'iggaProject'
-> Text -- ^ 'iggaZone'
-> Text -- ^ 'iggaInstance'
-> InstancesGetGuestAttributes
instancesGetGuestAttributes pIggaProject_ pIggaZone_ pIggaInstance_ =
InstancesGetGuestAttributes'
{ _iggaProject = pIggaProject_
, _iggaZone = pIggaZone_
, _iggaVariableKey = Nothing
, _iggaQueryPath = Nothing
, _iggaInstance = pIggaInstance_
}
-- | Project ID for this request.
iggaProject :: Lens' InstancesGetGuestAttributes Text
iggaProject
= lens _iggaProject (\ s a -> s{_iggaProject = a})
-- | The name of the zone for this request.
iggaZone :: Lens' InstancesGetGuestAttributes Text
iggaZone = lens _iggaZone (\ s a -> s{_iggaZone = a})
-- | Specifies the key for the guest attributes entry.
iggaVariableKey :: Lens' InstancesGetGuestAttributes (Maybe Text)
iggaVariableKey
= lens _iggaVariableKey
(\ s a -> s{_iggaVariableKey = a})
-- | Specifies the guest attributes path to be queried.
iggaQueryPath :: Lens' InstancesGetGuestAttributes (Maybe Text)
iggaQueryPath
= lens _iggaQueryPath
(\ s a -> s{_iggaQueryPath = a})
-- | Name of the instance scoping this request.
iggaInstance :: Lens' InstancesGetGuestAttributes Text
iggaInstance
= lens _iggaInstance (\ s a -> s{_iggaInstance = a})
instance GoogleRequest InstancesGetGuestAttributes
where
type Rs InstancesGetGuestAttributes = GuestAttributes
type Scopes InstancesGetGuestAttributes =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient InstancesGetGuestAttributes'{..}
= go _iggaProject _iggaZone _iggaInstance
_iggaVariableKey
_iggaQueryPath
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy InstancesGetGuestAttributesResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Instances/GetGuestAttributes.hs | mpl-2.0 | 4,839 | 0 | 19 | 1,152 | 630 | 370 | 260 | 100 | 1 |
module Knight where
import Control.Monad
type KnightPos = (Int, Int)
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c,r) = do
(c', r') <- [(c+2, r-1), (c+2, r+1), (c-2, r-1), (c-2, r+1)
,(c+1, r-2), (c+1, r+2), (c-1, r-2), (c-1, r+2)
]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c', r')
in3 :: KnightPos -> [KnightPos]
in3 start = do
first <- moveKnight start
second <- moveKnight first
moveKnight second
canReachIn3 :: KnightPos -> KnightPos -> Bool
canReachIn3 start end = end `elem` in3 start
inMany :: Int -> KnightPos -> [KnightPos]
--inMany x start = return start >>= foldr (<=<) return (replicate x moveKnight)
--GhcModLint suggests:
inMany x = foldr (<=<) return (replicate x moveKnight)
canReachIn :: Int -> KnightPos -> KnightPos -> Bool
canReachIn x start end = end `elem` inMany x start
| alexliew/learn_you_a_haskell | code/knightmoves.hs | unlicense | 858 | 0 | 12 | 179 | 404 | 225 | 179 | 20 | 1 |
{-# LANGUAGE ViewPatterns #-}
module Language.TAPL.SimplyTyped (evaluate, typecheck) where
{- types -}
data Type = Arr Type Type
| Bool
deriving Eq
instance Show Type where
show (Arr a b) = "(" ++ show a ++ " -> " ++ show b ++ ")"
show Bool = "Bool"
{- terms -}
data Term = Var Int
| Abs String Type Term
| App Term Term
| If Term Term Term
| T
| F
deriving Eq
instance Show Term where
show tm =
let fresh names name
| name `elem` names = fresh names $ name ++ "'"
| otherwise = (name : names, name)
go names (Var index) =
names !! index
go names (Abs name ty body) =
let (names', name') = fresh names name
in "λ" ++ name' ++ ":" ++ show ty ++ "." ++ go names' body
go names (App fn arg) =
"(" ++ go names fn ++ " " ++ go names arg ++ ")"
go names (If pred lhs rhs) =
"{ if " ++ show pred ++ " then " ++ show lhs ++ " else " ++ show rhs ++ " }"
go _ T = "T"
go _ F = "F"
in go [] tm
{- type checking -}
typecheck :: Term -> Maybe Type
typecheck tm =
let typecheck' types tm = go tm where
go (Var index) = Just $ types !! index
go (Abs _ ty (typecheck' $ ty : types -> Just body)) = Just $ Arr ty body
go (App (go -> Just (Arr a b)) (go -> Just arg)) | a == arg = Just b
go (If (go -> Just Bool) (go -> Just lhs) (go -> Just rhs)) | lhs == rhs = Just lhs
go T = Just Bool
go F = Just Bool
go _ = Nothing
in typecheck' [] tm
{- evaluation -}
tweak :: (Int -> Int -> Term) -> Term -> Term
tweak f tm =
let tweak' n tm = go tm where
go (Var index) = f index n
go (Abs name ty body) = Abs name ty $ tweak' (n + 1) body
go (App fn arg) = App (go fn) (go arg)
go (If pred lhs rhs) = If (go pred) (go lhs) (go rhs)
go tm = tm
in tweak' 0 tm
shift :: Int -> Term -> Term
shift distance tm =
let go index cutoff
| index >= cutoff = Var $ index + distance
| otherwise = Var index
in tweak go tm
subst :: Int -> Term -> Term -> Term
subst index substitute tm =
let go index' offset
| index' == index + offset = shift offset substitute
| otherwise = Var index'
in tweak go tm
evaluate :: Term -> Term
evaluate tm =
let go (App (Abs _ _ body) arg@(Abs _ _ _)) = shift (-1) (subst 0 (shift 1 arg) body)
go (App fn@(Abs _ _ _) arg) = App fn (go arg)
go (App fn arg) = App (go fn) arg
go tm = tm
tm' = go tm
in if tm' == tm then tm else evaluate tm'
| mergeconflict/tapl | src/Language/TAPL/SimplyTyped.hs | apache-2.0 | 2,786 | 0 | 18 | 1,081 | 1,231 | 603 | 628 | 72 | 7 |
module Minecraft.A309978Spec (main, spec) where
import Test.Hspec
import Minecraft.A309978 (a309978)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A309978" $
it "correctly computes the first 20 elements" $
take 20 (map a309978 [1..]) `shouldBe` expectedValue where
expectedValue = [0,1,1,2,1,3,1,2,1,3,1,3,1,2,1,2,1,3,1,3]
| peterokagey/haskellOEIS | test/Minecraft/A309978Spec.hs | apache-2.0 | 353 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
module Main where
import Control.Monad (unless)
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Lazy
import qualified Data.ByteString as BS
import Data.Binary.Put
import Network.Simple.TCP
import RL_Glue.Experiment
import RL_Glue.Network
main = runExperiment doExperiments
doExperiments :: (Socket, SockAddr) -> IO ()
doExperiments (sock, addr) =
do
taskSpec <- initExperiment sock
putStrLn ("Sent task spec: " ++ show taskSpec)
putStrLn "\n----------Sending some sample messages----------"
resp <- sendAgentMessageStr sock "what is your name?"
putStrLn ("Agent responded to \"what is your name?\" with: " ++ show resp)
resp <- sendAgentMessageStr sock "If at first you don't succeed; call it version 1.0"
putStrLn ("Agent responded to \"If at first you don't succeed; call it version 1.0?\" with: " ++ show resp)
resp <- sendEnvMessageStr sock "what is your name?"
putStrLn ("Environment responded to \"what is your name?\" with: " ++ show resp)
resp <- sendEnvMessageStr sock "If at first you don't succeed; call it version 1.0"
putStrLn ("Environment responded to \"If at first you don't succeed; call it version 1.0?\" with: " ++ show resp)
putStrLn "\n----------Running a few episodes----------"
evalStateT
(do
prettyRunEpisode sock 100
prettyRunEpisode sock 100
prettyRunEpisode sock 100
prettyRunEpisode sock 100
prettyRunEpisode sock 100
prettyRunEpisode sock 1
-- Run one without a limit
prettyRunEpisode sock 0) 1
cleanupExperiment sock
putStrLn "\n----------Stepping through an episode----------"
taskSpec <- initExperiment sock
-- Start an episode
(Observation (RLAbstractType o _ _), Action (RLAbstractType a _ _)) <- startEpisode sock
putStrLn $ "First observation and action were: " ++ show (head o) ++ " and: " ++ show (head a)
-- Step until episode ends
loopUntil $ do
(_, _, _, terminal) <- stepEpisode sock
return (terminal > 0)
putStrLn "\n----------Summary----------"
totalSteps <- getNumSteps sock
totalReward <- getReturn sock
putStrLn $ "It ran for " ++ show totalSteps ++ " steps, total reward was: " ++ show totalReward
cleanupExperiment sock
prettyRunEpisode :: Socket -> Int -> StateT Int IO ()
prettyRunEpisode sock steps =
do
terminal <- lift $ runEpisode sock steps
totalSteps <- lift $ getNumSteps sock
totalReward <- lift $ getReturn sock
episodeNum <- get
lift $ putStrLn $ "Episode " ++ show episodeNum ++ "\t " ++ show totalSteps ++ " steps \t" ++
show totalReward ++ " total reward\t" ++ show terminal ++ " natural end"
modify (+1)
loopUntil :: IO Bool -> IO ()
loopUntil f = do
x <- f
unless x (loopUntil f)
| rhofour/rlglue-haskell-codec | src/RL_Glue/Example/SkeletonExperiment.hs | apache-2.0 | 2,806 | 0 | 16 | 629 | 715 | 333 | 382 | 61 | 1 |
{-# LANGUAGE TemplateHaskell, FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Player where
import Control.Lens
import Time
import TimeSeries
import TimeSeriesGeometry
import Checkpoint
import Direction
data Player = Player { _timeseries :: TimeSeries (Maybe Turn), _initial :: Checkpoint }
makeLenses ''Player
change :: DTime -> Maybe TurnEvent -> Player -> Player
change dt = maybe (Player.extend dt) happened
happened :: TurnEvent -> Player -> Player
happened trn = over timeseries (insert trn)
-- Extend the player's time series by the amount dt
extend :: DTime -> Player -> Player
extend dt = over timeseries (TimeSeries.extend dt)
player p h = Player (TimeSeries [Event Nothing 0]) (Checkpoint p h)
| epeld/zatacka | old/Player.hs | apache-2.0 | 735 | 0 | 11 | 114 | 209 | 110 | 99 | 18 | 1 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Blog
( getBlogR
, getBlogPostR
, getBlogPostNoDateR
, getBlogFeedR
) where
import Wiki
import Handler.ShowMap (loadTree, showTree)
import Util
import Yesod.Feed
import Data.List (groupBy)
import Data.Function (on)
import Data.Text (pack)
import Control.Arrow ((&&&))
import Handler.Topic (comments)
getBlogR :: Handler ()
getBlogR = do
-- FIXME admin interface when appropriate
posts <- runDB $ selectList [] [Desc BlogPosted, LimitTo 1]
post <-
case posts of
[] -> notFound
(_, post):_ -> return post
redirect RedirectTemporary $ BlogPostR (blogYear post) (blogMonth post) $ blogSlug post
type Archive = [((Int, Int), [AEntry])]
data AEntry = AEntry
{ aeTitle :: Text
, aeLink :: WikiRoute
, aeDate :: Text
}
getBlogPostR :: Int -> Month -> BlogSlugT -> Handler RepHtml
getBlogPostR year month slug = do
let curr = BlogPostR year month slug
blog <- getBlogPost year month slug
archive' <- runDB $ selectList [] [Desc BlogPosted] >>= mapM (\(_, b) -> do
tmap <- get404 $ blogMap b
let y = blogYear b
m = blogMonth b
Month m' = m
return ((y, m'), AEntry (tMapTitle tmap) (BlogPostR y m $ blogSlug b) (pack $ prettyDate $ blogPosted b)))
let archive :: Archive
archive = map (fst . head &&& map snd) $ groupBy ((==) `on` fst) archive'
tmap <- runDB $ get404 $ blogMap blog
user <- runDB $ get404 $ tMapOwner tmap
let tmid = blogMap blog
tree <- loadTree tmid
let showMap = $(widgetFile "show-map")
defaultLayout $ do
comments
addScript $ StaticR jquery_js
addScript $ StaticR jquery_cookie_js
addScript $ StaticR jquery_treeview_js
$(widgetFile "blog")
getBlogPostNoDateR :: BlogSlugT -> Handler ()
getBlogPostNoDateR slug = do
x <- runDB $ selectList [BlogSlug ==. slug] [Desc BlogPosted, LimitTo 1]
case x of
(_, y):_ -> redirect RedirectTemporary $ BlogPostR (blogYear y) (blogMonth y) slug
[] -> notFound
getBlogFeedR :: Handler RepAtomRss
getBlogFeedR = do
x <- runDB $ selectList [] [Desc BlogPosted, LimitTo 10]
updated <-
case x of
[] -> liftIO getCurrentTime
(_, y):_ -> return $ blogPosted y
render <- getUrlRenderParams
let go (_, e) = do
blog <- getBlogPost (blogYear e) (blogMonth e) (blogSlug e)
tmap <- runDB $ get404 $ blogMap blog
let title = tMapTitle tmap
tree <- loadTree $ blogMap blog
return FeedEntry
{ feedEntryLink = BlogPostR (blogYear e) (blogMonth e) (blogSlug e)
, feedEntryUpdated = blogPosted e
, feedEntryTitle = title
, feedEntryContent = showTree 2 tree render
}
entries <- mapM go x
newsFeed Feed
{ feedTitle = "Yesod Web Framework"
, feedLinkSelf = BlogFeedR
, feedLinkHome = RootR
, feedDescription = "Yesod Web Framework"
, feedLanguage = "en"
, feedUpdated = updated
, feedEntries = entries
}
| snoyberg/yesodwiki | Handler/Blog.hs | bsd-2-clause | 3,220 | 0 | 19 | 949 | 1,083 | 547 | 536 | -1 | -1 |
-- | QuickCheck properties for the text library.
{-# LANGUAGE BangPatterns, FlexibleInstances, OverloadedStrings,
ScopedTypeVariables, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-enable-rewrite-rules -fno-warn-missing-signatures #-}
module Tests.Properties
(
tests
) where
import Control.Applicative ((<$>), (<*>))
import Control.Arrow ((***), first, second)
import Data.Bits ((.&.))
import Data.Char (chr, isDigit, isHexDigit, isLower, isSpace, isLetter, isUpper, ord)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Monoid (Monoid(..))
import Data.String (IsString(fromString))
import Data.Text.Encoding.Error
import Data.Text.Foreign
import Data.Text.Internal.Encoding.Utf8
import Data.Text.Internal.Fusion.Size
import Data.Text.Internal.Search (indices)
import Data.Text.Lazy.Read as TL
import Data.Text.Read as T
import Data.Word (Word, Word8, Word16, Word32, Word64)
import Data.Maybe (mapMaybe)
import Numeric (showEFloat, showFFloat, showGFloat, showHex)
import Prelude hiding (replicate)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck hiding ((.&.))
import Test.QuickCheck.Monadic
import Test.QuickCheck.Property (Property(..))
import Test.QuickCheck.Unicode (char)
import Tests.QuickCheckUtils
import Tests.Utils
import Text.Show.Functions ()
import qualified Control.Exception as Exception
import qualified Data.Bits as Bits (shiftL, shiftR)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import qualified Data.Text.IO as T
import qualified Data.Text.Internal.Fusion as S
import qualified Data.Text.Internal.Fusion.Common as S
import qualified Data.Text.Internal.Lazy.Fusion as SL
import qualified Data.Text.Internal.Lazy.Search as S (indices)
import qualified Data.Text.Internal.Unsafe.Shift as U
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TB
import qualified Data.Text.Lazy.Builder.Int as TB
import qualified Data.Text.Lazy.Builder.RealFloat as TB
import qualified Data.Text.Lazy.Encoding as EL
import qualified Data.Text.Lazy.IO as TL
import qualified System.IO as IO
import qualified Tests.Properties.Mul as Mul
import qualified Tests.SlowFunctions as Slow
t_pack_unpack = (T.unpack . T.pack) `eq` id
tl_pack_unpack = (TL.unpack . TL.pack) `eq` id
t_stream_unstream = (S.unstream . S.stream) `eq` id
tl_stream_unstream = (SL.unstream . SL.stream) `eq` id
t_reverse_stream t = (S.reverse . S.reverseStream) t === t
t_singleton c = [c] === (T.unpack . T.singleton) c
tl_singleton c = [c] === (TL.unpack . TL.singleton) c
tl_unstreamChunks x = f 11 x === f 1000 x
where f n = SL.unstreamChunks n . S.streamList
tl_chunk_unchunk = (TL.fromChunks . TL.toChunks) `eq` id
tl_from_to_strict = (TL.fromStrict . TL.toStrict) `eq` id
-- Note: this silently truncates code-points > 255 to 8-bit due to 'B.pack'
encodeL1 :: T.Text -> B.ByteString
encodeL1 = B.pack . map (fromIntegral . fromEnum) . T.unpack
encodeLazyL1 :: TL.Text -> BL.ByteString
encodeLazyL1 = BL.fromChunks . map encodeL1 . TL.toChunks
t_ascii t = E.decodeASCII (E.encodeUtf8 a) === a
where a = T.map (\c -> chr (ord c `mod` 128)) t
tl_ascii t = EL.decodeASCII (EL.encodeUtf8 a) === a
where a = TL.map (\c -> chr (ord c `mod` 128)) t
t_latin1 t = E.decodeLatin1 (encodeL1 a) === a
where a = T.map (\c -> chr (ord c `mod` 256)) t
tl_latin1 t = EL.decodeLatin1 (encodeLazyL1 a) === a
where a = TL.map (\c -> chr (ord c `mod` 256)) t
t_utf8 = forAll genUnicode $ (E.decodeUtf8 . E.encodeUtf8) `eq` id
t_utf8' = forAll genUnicode $ (E.decodeUtf8' . E.encodeUtf8) `eq` (id . Right)
tl_utf8 = forAll genUnicode $ (EL.decodeUtf8 . EL.encodeUtf8) `eq` id
tl_utf8' = forAll genUnicode $ (EL.decodeUtf8' . EL.encodeUtf8) `eq` (id . Right)
t_utf16LE = forAll genUnicode $ (E.decodeUtf16LE . E.encodeUtf16LE) `eq` id
tl_utf16LE = forAll genUnicode $ (EL.decodeUtf16LE . EL.encodeUtf16LE) `eq` id
t_utf16BE = forAll genUnicode $ (E.decodeUtf16BE . E.encodeUtf16BE) `eq` id
tl_utf16BE = forAll genUnicode $ (EL.decodeUtf16BE . EL.encodeUtf16BE) `eq` id
t_utf32LE = forAll genUnicode $ (E.decodeUtf32LE . E.encodeUtf32LE) `eq` id
tl_utf32LE = forAll genUnicode $ (EL.decodeUtf32LE . EL.encodeUtf32LE) `eq` id
t_utf32BE = forAll genUnicode $ (E.decodeUtf32BE . E.encodeUtf32BE) `eq` id
tl_utf32BE = forAll genUnicode $ (EL.decodeUtf32BE . EL.encodeUtf32BE) `eq` id
t_utf8_incr = forAll genUnicode $ \s (Positive n) -> (recode n `eq` id) s
where recode n = T.concat . map fst . feedChunksOf n E.streamDecodeUtf8 .
E.encodeUtf8
feedChunksOf :: Int -> (B.ByteString -> E.Decoding) -> B.ByteString
-> [(T.Text, B.ByteString)]
feedChunksOf n f bs
| B.null bs = []
| otherwise = let (x,y) = B.splitAt n bs
E.Some t b f' = f x
in (t,b) : feedChunksOf n f' y
t_utf8_undecoded = forAll genUnicode $ \t ->
let b = E.encodeUtf8 t
ls = concatMap (leftover . E.encodeUtf8 . T.singleton) . T.unpack $ t
leftover = (++ [B.empty]) . init . tail . B.inits
in (map snd . feedChunksOf 1 E.streamDecodeUtf8) b === ls
data Badness = Solo | Leading | Trailing
deriving (Eq, Show)
instance Arbitrary Badness where
arbitrary = elements [Solo, Leading, Trailing]
t_utf8_err :: Badness -> DecodeErr -> Property
t_utf8_err bad de = do
let gen = case bad of
Solo -> genInvalidUTF8
Leading -> B.append <$> genInvalidUTF8 <*> genUTF8
Trailing -> B.append <$> genUTF8 <*> genInvalidUTF8
genUTF8 = E.encodeUtf8 <$> genUnicode
forAll gen $ \bs -> MkProperty $ do
onErr <- genDecodeErr de
unProperty . monadicIO $ do
l <- run $ let len = T.length (E.decodeUtf8With onErr bs)
in (len `seq` return (Right len)) `Exception.catch`
(\(e::UnicodeException) -> return (Left e))
assert $ case l of
Left err -> length (show err) >= 0
Right _ -> de /= Strict
t_utf8_err' :: B.ByteString -> Property
t_utf8_err' bs = monadicIO . assert $ case E.decodeUtf8' bs of
Left err -> length (show err) >= 0
Right t -> T.length t >= 0
genInvalidUTF8 :: Gen B.ByteString
genInvalidUTF8 = B.pack <$> oneof [
-- invalid leading byte of a 2-byte sequence
(:) <$> choose (0xC0, 0xC1) <*> upTo 1 contByte
-- invalid leading byte of a 4-byte sequence
, (:) <$> choose (0xF5, 0xFF) <*> upTo 3 contByte
-- 4-byte sequence greater than U+10FFFF
, do k <- choose (0x11, 0x13)
let w0 = 0xF0 + (k `Bits.shiftR` 2)
w1 = 0x80 + ((k .&. 3) `Bits.shiftL` 4)
([w0,w1]++) <$> vectorOf 2 contByte
-- continuation bytes without a start byte
, listOf1 contByte
-- short 2-byte sequence
, (:[]) <$> choose (0xC2, 0xDF)
-- short 3-byte sequence
, (:) <$> choose (0xE0, 0xEF) <*> upTo 1 contByte
-- short 4-byte sequence
, (:) <$> choose (0xF0, 0xF4) <*> upTo 2 contByte
-- overlong encoding
, do k <- choose (0,0xFFFF)
let c = chr k
case k of
_ | k < 0x80 -> oneof [ let (w,x) = ord2 c in return [w,x]
, let (w,x,y) = ord3 c in return [w,x,y]
, let (w,x,y,z) = ord4 c in return [w,x,y,z] ]
| k < 0x7FF -> oneof [ let (w,x,y) = ord3 c in return [w,x,y]
, let (w,x,y,z) = ord4 c in return [w,x,y,z] ]
| otherwise -> let (w,x,y,z) = ord4 c in return [w,x,y,z]
]
where
contByte = (0x80 +) <$> choose (0, 0x3f)
upTo n gen = do
k <- choose (0,n)
vectorOf k gen
s_Eq s = (s==) `eq` ((S.streamList s==) . S.streamList)
where _types = s :: String
sf_Eq p s =
((L.filter p s==) . L.filter p) `eq`
(((S.filter p $ S.streamList s)==) . S.filter p . S.streamList)
t_Eq s = (s==) `eq` ((T.pack s==) . T.pack)
tl_Eq s = (s==) `eq` ((TL.pack s==) . TL.pack)
s_Ord s = (compare s) `eq` (compare (S.streamList s) . S.streamList)
where _types = s :: String
sf_Ord p s =
((compare $ L.filter p s) . L.filter p) `eq`
(compare (S.filter p $ S.streamList s) . S.filter p . S.streamList)
t_Ord s = (compare s) `eq` (compare (T.pack s) . T.pack)
tl_Ord s = (compare s) `eq` (compare (TL.pack s) . TL.pack)
t_Read = id `eq` (T.unpack . read . show)
tl_Read = id `eq` (TL.unpack . read . show)
t_Show = show `eq` (show . T.pack)
tl_Show = show `eq` (show . TL.pack)
t_mappend s = mappend s`eqP` (unpackS . mappend (T.pack s))
tl_mappend s = mappend s`eqP` (unpackS . mappend (TL.pack s))
t_mconcat = unsquare $
mconcat `eq` (unpackS . mconcat . L.map T.pack)
tl_mconcat = unsquare $
mconcat `eq` (unpackS . mconcat . L.map TL.pack)
t_mempty = mempty === (unpackS (mempty :: T.Text))
tl_mempty = mempty === (unpackS (mempty :: TL.Text))
t_IsString = fromString `eqP` (T.unpack . fromString)
tl_IsString = fromString `eqP` (TL.unpack . fromString)
s_cons x = (x:) `eqP` (unpackS . S.cons x)
s_cons_s x = (x:) `eqP` (unpackS . S.unstream . S.cons x)
sf_cons p x = ((x:) . L.filter p) `eqP` (unpackS . S.cons x . S.filter p)
t_cons x = (x:) `eqP` (unpackS . T.cons x)
tl_cons x = (x:) `eqP` (unpackS . TL.cons x)
s_snoc x = (++ [x]) `eqP` (unpackS . (flip S.snoc) x)
t_snoc x = (++ [x]) `eqP` (unpackS . (flip T.snoc) x)
tl_snoc x = (++ [x]) `eqP` (unpackS . (flip TL.snoc) x)
s_append s = (s++) `eqP` (unpackS . S.append (S.streamList s))
s_append_s s = (s++) `eqP`
(unpackS . S.unstream . S.append (S.streamList s))
sf_append p s = (L.filter p s++) `eqP`
(unpackS . S.append (S.filter p $ S.streamList s))
t_append s = (s++) `eqP` (unpackS . T.append (packS s))
uncons (x:xs) = Just (x,xs)
uncons _ = Nothing
s_uncons = uncons `eqP` (fmap (second unpackS) . S.uncons)
sf_uncons p = (uncons . L.filter p) `eqP`
(fmap (second unpackS) . S.uncons . S.filter p)
t_uncons = uncons `eqP` (fmap (second unpackS) . T.uncons)
tl_uncons = uncons `eqP` (fmap (second unpackS) . TL.uncons)
unsnoc xs@(_:_) = Just (init xs, last xs)
unsnoc [] = Nothing
t_unsnoc = unsnoc `eqP` (fmap (first unpackS) . T.unsnoc)
tl_unsnoc = unsnoc `eqP` (fmap (first unpackS) . TL.unsnoc)
s_head = head `eqP` S.head
sf_head p = (head . L.filter p) `eqP` (S.head . S.filter p)
t_head = head `eqP` T.head
tl_head = head `eqP` TL.head
s_last = last `eqP` S.last
sf_last p = (last . L.filter p) `eqP` (S.last . S.filter p)
t_last = last `eqP` T.last
tl_last = last `eqP` TL.last
s_tail = tail `eqP` (unpackS . S.tail)
s_tail_s = tail `eqP` (unpackS . S.unstream . S.tail)
sf_tail p = (tail . L.filter p) `eqP` (unpackS . S.tail . S.filter p)
t_tail = tail `eqP` (unpackS . T.tail)
tl_tail = tail `eqP` (unpackS . TL.tail)
s_init = init `eqP` (unpackS . S.init)
s_init_s = init `eqP` (unpackS . S.unstream . S.init)
sf_init p = (init . L.filter p) `eqP` (unpackS . S.init . S.filter p)
t_init = init `eqP` (unpackS . T.init)
tl_init = init `eqP` (unpackS . TL.init)
s_null = null `eqP` S.null
sf_null p = (null . L.filter p) `eqP` (S.null . S.filter p)
t_null = null `eqP` T.null
tl_null = null `eqP` TL.null
s_length = length `eqP` S.length
sf_length p = (length . L.filter p) `eqP` (S.length . S.filter p)
sl_length = (fromIntegral . length) `eqP` SL.length
t_length = length `eqP` T.length
tl_length = L.genericLength `eqP` TL.length
t_compareLength t = (compare (T.length t)) `eq` T.compareLength t
tl_compareLength t= (compare (TL.length t)) `eq` TL.compareLength t
s_map f = map f `eqP` (unpackS . S.map f)
s_map_s f = map f `eqP` (unpackS . S.unstream . S.map f)
sf_map p f = (map f . L.filter p) `eqP` (unpackS . S.map f . S.filter p)
t_map f = map f `eqP` (unpackS . T.map f)
tl_map f = map f `eqP` (unpackS . TL.map f)
s_intercalate c = unsquare $
L.intercalate c `eq`
(unpackS . S.intercalate (packS c) . map packS)
t_intercalate c = unsquare $
L.intercalate c `eq`
(unpackS . T.intercalate (packS c) . map packS)
tl_intercalate c = unsquare $
L.intercalate c `eq`
(unpackS . TL.intercalate (TL.pack c) . map TL.pack)
s_intersperse c = L.intersperse c `eqP`
(unpackS . S.intersperse c)
s_intersperse_s c = L.intersperse c `eqP`
(unpackS . S.unstream . S.intersperse c)
sf_intersperse p c= (L.intersperse c . L.filter p) `eqP`
(unpackS . S.intersperse c . S.filter p)
t_intersperse c = unsquare $
L.intersperse c `eqP` (unpackS . T.intersperse c)
tl_intersperse c = unsquare $
L.intersperse c `eqP` (unpackS . TL.intersperse c)
t_transpose = unsquare $
L.transpose `eq` (map unpackS . T.transpose . map packS)
tl_transpose = unsquare $
L.transpose `eq` (map unpackS . TL.transpose . map TL.pack)
t_reverse = L.reverse `eqP` (unpackS . T.reverse)
tl_reverse = L.reverse `eqP` (unpackS . TL.reverse)
t_reverse_short n = L.reverse `eqP` (unpackS . S.reverse . shorten n . S.stream)
t_replace s d = (L.intercalate d . splitOn s) `eqP`
(unpackS . T.replace (T.pack s) (T.pack d))
tl_replace s d = (L.intercalate d . splitOn s) `eqP`
(unpackS . TL.replace (TL.pack s) (TL.pack d))
splitOn :: (Eq a) => [a] -> [a] -> [[a]]
splitOn pat src0
| l == 0 = error "splitOn: empty"
| otherwise = go src0
where
l = length pat
go src = search 0 src
where
search _ [] = [src]
search !n s@(_:s')
| pat `L.isPrefixOf` s = take n src : go (drop l s)
| otherwise = search (n+1) s'
s_toCaseFold_length xs = S.length (S.toCaseFold s) >= length xs
where s = S.streamList xs
sf_toCaseFold_length p xs =
(S.length . S.toCaseFold . S.filter p $ s) >= (length . L.filter p $ xs)
where s = S.streamList xs
t_toCaseFold_length t = T.length (T.toCaseFold t) >= T.length t
tl_toCaseFold_length t = TL.length (TL.toCaseFold t) >= TL.length t
t_toLower_length t = T.length (T.toLower t) >= T.length t
t_toLower_lower t = p (T.toLower t) >= p t
where p = T.length . T.filter isLower
tl_toLower_lower t = p (TL.toLower t) >= p t
where p = TL.length . TL.filter isLower
t_toUpper_length t = T.length (T.toUpper t) >= T.length t
t_toUpper_upper t = p (T.toUpper t) >= p t
where p = T.length . T.filter isUpper
tl_toUpper_upper t = p (TL.toUpper t) >= p t
where p = TL.length . TL.filter isUpper
t_toTitle_title t = all (<= 1) (caps w)
where caps = fmap (T.length . T.filter isUpper) . T.words . T.toTitle
-- TIL: there exist uppercase-only letters
w = T.filter (\c -> if C.isUpper c then C.toLower c /= c else True) t
t_toTitle_1stNotLower = and . notLow . T.toTitle . T.filter stable
where notLow = mapMaybe (fmap (not . isLower) . (T.find isLetter)) . T.words
-- Surprise! The Spanish/Portuguese ordinal indicators changed
-- from category Ll (letter, lowercase) to Lo (letter, other)
-- in Unicode 7.0
-- Oh, and there exist lowercase-only letters (see previous test)
stable c = if isLower c
then C.toUpper c /= c
else c /= '\170' && c /= '\186'
justifyLeft k c xs = xs ++ L.replicate (k - length xs) c
justifyRight m n xs = L.replicate (m - length xs) n ++ xs
center k c xs
| len >= k = xs
| otherwise = L.replicate l c ++ xs ++ L.replicate r c
where len = length xs
d = k - len
r = d `div` 2
l = d - r
s_justifyLeft k c = justifyLeft j c `eqP` (unpackS . S.justifyLeftI j c)
where j = fromIntegral (k :: Word8)
s_justifyLeft_s k c = justifyLeft j c `eqP`
(unpackS . S.unstream . S.justifyLeftI j c)
where j = fromIntegral (k :: Word8)
sf_justifyLeft p k c = (justifyLeft j c . L.filter p) `eqP`
(unpackS . S.justifyLeftI j c . S.filter p)
where j = fromIntegral (k :: Word8)
t_justifyLeft k c = justifyLeft j c `eqP` (unpackS . T.justifyLeft j c)
where j = fromIntegral (k :: Word8)
tl_justifyLeft k c = justifyLeft j c `eqP`
(unpackS . TL.justifyLeft (fromIntegral j) c)
where j = fromIntegral (k :: Word8)
t_justifyRight k c = justifyRight j c `eqP` (unpackS . T.justifyRight j c)
where j = fromIntegral (k :: Word8)
tl_justifyRight k c = justifyRight j c `eqP`
(unpackS . TL.justifyRight (fromIntegral j) c)
where j = fromIntegral (k :: Word8)
t_center k c = center j c `eqP` (unpackS . T.center j c)
where j = fromIntegral (k :: Word8)
tl_center k c = center j c `eqP` (unpackS . TL.center (fromIntegral j) c)
where j = fromIntegral (k :: Word8)
sf_foldl p f z = (L.foldl f z . L.filter p) `eqP` (S.foldl f z . S.filter p)
where _types = f :: Char -> Char -> Char
t_foldl f z = L.foldl f z `eqP` (T.foldl f z)
where _types = f :: Char -> Char -> Char
tl_foldl f z = L.foldl f z `eqP` (TL.foldl f z)
where _types = f :: Char -> Char -> Char
sf_foldl' p f z = (L.foldl' f z . L.filter p) `eqP`
(S.foldl' f z . S.filter p)
where _types = f :: Char -> Char -> Char
t_foldl' f z = L.foldl' f z `eqP` T.foldl' f z
where _types = f :: Char -> Char -> Char
tl_foldl' f z = L.foldl' f z `eqP` TL.foldl' f z
where _types = f :: Char -> Char -> Char
sf_foldl1 p f = (L.foldl1 f . L.filter p) `eqP` (S.foldl1 f . S.filter p)
t_foldl1 f = L.foldl1 f `eqP` T.foldl1 f
tl_foldl1 f = L.foldl1 f `eqP` TL.foldl1 f
sf_foldl1' p f = (L.foldl1' f . L.filter p) `eqP` (S.foldl1' f . S.filter p)
t_foldl1' f = L.foldl1' f `eqP` T.foldl1' f
tl_foldl1' f = L.foldl1' f `eqP` TL.foldl1' f
sf_foldr p f z = (L.foldr f z . L.filter p) `eqP` (S.foldr f z . S.filter p)
where _types = f :: Char -> Char -> Char
t_foldr f z = L.foldr f z `eqP` T.foldr f z
where _types = f :: Char -> Char -> Char
tl_foldr f z = unsquare $
L.foldr f z `eqP` TL.foldr f z
where _types = f :: Char -> Char -> Char
sf_foldr1 p f = unsquare $
(L.foldr1 f . L.filter p) `eqP` (S.foldr1 f . S.filter p)
t_foldr1 f = L.foldr1 f `eqP` T.foldr1 f
tl_foldr1 f = unsquare $
L.foldr1 f `eqP` TL.foldr1 f
s_concat_s = unsquare $
L.concat `eq` (unpackS . S.unstream . S.concat . map packS)
sf_concat p = unsquare $
(L.concat . map (L.filter p)) `eq`
(unpackS . S.concat . map (S.filter p . packS))
t_concat = unsquare $
L.concat `eq` (unpackS . T.concat . map packS)
tl_concat = unsquare $
L.concat `eq` (unpackS . TL.concat . map TL.pack)
sf_concatMap p f = unsquare $ (L.concatMap f . L.filter p) `eqP`
(unpackS . S.concatMap (packS . f) . S.filter p)
t_concatMap f = unsquare $
L.concatMap f `eqP` (unpackS . T.concatMap (packS . f))
tl_concatMap f = unsquare $
L.concatMap f `eqP` (unpackS . TL.concatMap (TL.pack . f))
sf_any q p = (L.any p . L.filter q) `eqP` (S.any p . S.filter q)
t_any p = L.any p `eqP` T.any p
tl_any p = L.any p `eqP` TL.any p
sf_all q p = (L.all p . L.filter q) `eqP` (S.all p . S.filter q)
t_all p = L.all p `eqP` T.all p
tl_all p = L.all p `eqP` TL.all p
sf_maximum p = (L.maximum . L.filter p) `eqP` (S.maximum . S.filter p)
t_maximum = L.maximum `eqP` T.maximum
tl_maximum = L.maximum `eqP` TL.maximum
sf_minimum p = (L.minimum . L.filter p) `eqP` (S.minimum . S.filter p)
t_minimum = L.minimum `eqP` T.minimum
tl_minimum = L.minimum `eqP` TL.minimum
sf_scanl p f z = (L.scanl f z . L.filter p) `eqP`
(unpackS . S.scanl f z . S.filter p)
t_scanl f z = L.scanl f z `eqP` (unpackS . T.scanl f z)
tl_scanl f z = L.scanl f z `eqP` (unpackS . TL.scanl f z)
t_scanl1 f = L.scanl1 f `eqP` (unpackS . T.scanl1 f)
tl_scanl1 f = L.scanl1 f `eqP` (unpackS . TL.scanl1 f)
t_scanr f z = L.scanr f z `eqP` (unpackS . T.scanr f z)
tl_scanr f z = L.scanr f z `eqP` (unpackS . TL.scanr f z)
t_scanr1 f = L.scanr1 f `eqP` (unpackS . T.scanr1 f)
tl_scanr1 f = L.scanr1 f `eqP` (unpackS . TL.scanr1 f)
t_mapAccumL f z = L.mapAccumL f z `eqP` (second unpackS . T.mapAccumL f z)
where _types = f :: Int -> Char -> (Int,Char)
tl_mapAccumL f z = L.mapAccumL f z `eqP` (second unpackS . TL.mapAccumL f z)
where _types = f :: Int -> Char -> (Int,Char)
t_mapAccumR f z = L.mapAccumR f z `eqP` (second unpackS . T.mapAccumR f z)
where _types = f :: Int -> Char -> (Int,Char)
tl_mapAccumR f z = L.mapAccumR f z `eqP` (second unpackS . TL.mapAccumR f z)
where _types = f :: Int -> Char -> (Int,Char)
tl_repeat n = (L.take m . L.repeat) `eq`
(unpackS . TL.take (fromIntegral m) . TL.repeat)
where m = fromIntegral (n :: Word8)
replicate n l = concat (L.replicate n l)
s_replicate n = replicate m `eq`
(unpackS . S.replicateI (fromIntegral m) . packS)
where m = fromIntegral (n :: Word8)
t_replicate n = replicate m `eq` (unpackS . T.replicate m . packS)
where m = fromIntegral (n :: Word8)
tl_replicate n = replicate m `eq`
(unpackS . TL.replicate (fromIntegral m) . packS)
where m = fromIntegral (n :: Word8)
tl_cycle n = (L.take m . L.cycle) `eq`
(unpackS . TL.take (fromIntegral m) . TL.cycle . packS)
where m = fromIntegral (n :: Word8)
tl_iterate f n = (L.take m . L.iterate f) `eq`
(unpackS . TL.take (fromIntegral m) . TL.iterate f)
where m = fromIntegral (n :: Word8)
unf :: Int -> Char -> Maybe (Char, Char)
unf n c | fromEnum c * 100 > n = Nothing
| otherwise = Just (c, succ c)
t_unfoldr n = L.unfoldr (unf m) `eq` (unpackS . T.unfoldr (unf m))
where m = fromIntegral (n :: Word16)
tl_unfoldr n = L.unfoldr (unf m) `eq` (unpackS . TL.unfoldr (unf m))
where m = fromIntegral (n :: Word16)
t_unfoldrN n m = (L.take i . L.unfoldr (unf j)) `eq`
(unpackS . T.unfoldrN i (unf j))
where i = fromIntegral (n :: Word16)
j = fromIntegral (m :: Word16)
tl_unfoldrN n m = (L.take i . L.unfoldr (unf j)) `eq`
(unpackS . TL.unfoldrN (fromIntegral i) (unf j))
where i = fromIntegral (n :: Word16)
j = fromIntegral (m :: Word16)
unpack2 :: (Stringy s) => (s,s) -> (String,String)
unpack2 = unpackS *** unpackS
s_take n = L.take n `eqP` (unpackS . S.take n)
s_take_s m = L.take n `eqP` (unpackS . S.unstream . S.take n)
where n = small m
sf_take p n = (L.take n . L.filter p) `eqP`
(unpackS . S.take n . S.filter p)
t_take n = L.take n `eqP` (unpackS . T.take n)
t_takeEnd n = (L.reverse . L.take n . L.reverse) `eqP`
(unpackS . T.takeEnd n)
tl_take n = L.take n `eqP` (unpackS . TL.take (fromIntegral n))
tl_takeEnd n = (L.reverse . L.take (fromIntegral n) . L.reverse) `eqP`
(unpackS . TL.takeEnd n)
s_drop n = L.drop n `eqP` (unpackS . S.drop n)
s_drop_s m = L.drop n `eqP` (unpackS . S.unstream . S.drop n)
where n = small m
sf_drop p n = (L.drop n . L.filter p) `eqP`
(unpackS . S.drop n . S.filter p)
t_drop n = L.drop n `eqP` (unpackS . T.drop n)
t_dropEnd n = (L.reverse . L.drop n . L.reverse) `eqP`
(unpackS . T.dropEnd n)
tl_drop n = L.drop n `eqP` (unpackS . TL.drop (fromIntegral n))
tl_dropEnd n = (L.reverse . L.drop n . L.reverse) `eqP`
(unpackS . TL.dropEnd (fromIntegral n))
s_take_drop m = (L.take n . L.drop n) `eqP` (unpackS . S.take n . S.drop n)
where n = small m
s_take_drop_s m = (L.take n . L.drop n) `eqP`
(unpackS . S.unstream . S.take n . S.drop n)
where n = small m
s_takeWhile p = L.takeWhile p `eqP` (unpackS . S.takeWhile p)
s_takeWhile_s p = L.takeWhile p `eqP` (unpackS . S.unstream . S.takeWhile p)
sf_takeWhile q p = (L.takeWhile p . L.filter q) `eqP`
(unpackS . S.takeWhile p . S.filter q)
noMatch = do
c <- char
d <- suchThat char (/= c)
return (c,d)
t_takeWhile p = L.takeWhile p `eqP` (unpackS . T.takeWhile p)
tl_takeWhile p = L.takeWhile p `eqP` (unpackS . TL.takeWhile p)
t_takeWhileEnd p = (L.reverse . L.takeWhile p . L.reverse) `eqP`
(unpackS . T.takeWhileEnd p)
t_takeWhileEnd_null t = forAll noMatch $ \(c,d) -> T.null $
T.takeWhileEnd (==d) (T.snoc t c)
tl_takeWhileEnd p = (L.reverse . L.takeWhile p . L.reverse) `eqP`
(unpackS . TL.takeWhileEnd p)
tl_takeWhileEnd_null t = forAll noMatch $ \(c,d) -> TL.null $
TL.takeWhileEnd (==d) (TL.snoc t c)
s_dropWhile p = L.dropWhile p `eqP` (unpackS . S.dropWhile p)
s_dropWhile_s p = L.dropWhile p `eqP` (unpackS . S.unstream . S.dropWhile p)
sf_dropWhile q p = (L.dropWhile p . L.filter q) `eqP`
(unpackS . S.dropWhile p . S.filter q)
t_dropWhile p = L.dropWhile p `eqP` (unpackS . T.dropWhile p)
tl_dropWhile p = L.dropWhile p `eqP` (unpackS . S.dropWhile p)
t_dropWhileEnd p = (L.reverse . L.dropWhile p . L.reverse) `eqP`
(unpackS . T.dropWhileEnd p)
tl_dropWhileEnd p = (L.reverse . L.dropWhile p . L.reverse) `eqP`
(unpackS . TL.dropWhileEnd p)
t_dropAround p = (L.dropWhile p . L.reverse . L.dropWhile p . L.reverse)
`eqP` (unpackS . T.dropAround p)
tl_dropAround p = (L.dropWhile p . L.reverse . L.dropWhile p . L.reverse)
`eqP` (unpackS . TL.dropAround p)
t_stripStart = T.dropWhile isSpace `eq` T.stripStart
tl_stripStart = TL.dropWhile isSpace `eq` TL.stripStart
t_stripEnd = T.dropWhileEnd isSpace `eq` T.stripEnd
tl_stripEnd = TL.dropWhileEnd isSpace `eq` TL.stripEnd
t_strip = T.dropAround isSpace `eq` T.strip
tl_strip = TL.dropAround isSpace `eq` TL.strip
t_splitAt n = L.splitAt n `eqP` (unpack2 . T.splitAt n)
tl_splitAt n = L.splitAt n `eqP` (unpack2 . TL.splitAt (fromIntegral n))
t_span p = L.span p `eqP` (unpack2 . T.span p)
tl_span p = L.span p `eqP` (unpack2 . TL.span p)
t_breakOn_id s = squid `eq` (uncurry T.append . T.breakOn s)
where squid t | T.null s = error "empty"
| otherwise = t
tl_breakOn_id s = squid `eq` (uncurry TL.append . TL.breakOn s)
where squid t | TL.null s = error "empty"
| otherwise = t
t_breakOn_start (NotEmpty s) t =
let (k,m) = T.breakOn s t
in k `T.isPrefixOf` t && (T.null m || s `T.isPrefixOf` m)
tl_breakOn_start (NotEmpty s) t =
let (k,m) = TL.breakOn s t
in k `TL.isPrefixOf` t && TL.null m || s `TL.isPrefixOf` m
t_breakOnEnd_end (NotEmpty s) t =
let (m,k) = T.breakOnEnd s t
in k `T.isSuffixOf` t && (T.null m || s `T.isSuffixOf` m)
tl_breakOnEnd_end (NotEmpty s) t =
let (m,k) = TL.breakOnEnd s t
in k `TL.isSuffixOf` t && (TL.null m || s `TL.isSuffixOf` m)
t_break p = L.break p `eqP` (unpack2 . T.break p)
tl_break p = L.break p `eqP` (unpack2 . TL.break p)
t_group = L.group `eqP` (map unpackS . T.group)
tl_group = L.group `eqP` (map unpackS . TL.group)
t_groupBy p = L.groupBy p `eqP` (map unpackS . T.groupBy p)
tl_groupBy p = L.groupBy p `eqP` (map unpackS . TL.groupBy p)
t_inits = L.inits `eqP` (map unpackS . T.inits)
tl_inits = L.inits `eqP` (map unpackS . TL.inits)
t_tails = L.tails `eqP` (map unpackS . T.tails)
tl_tails = unsquare $
L.tails `eqP` (map unpackS . TL.tails)
t_findAppendId = unsquare $ \(NotEmpty s) ts ->
let t = T.intercalate s ts
in all (==t) $ map (uncurry T.append) (T.breakOnAll s t)
tl_findAppendId = unsquare $ \(NotEmpty s) ts ->
let t = TL.intercalate s ts
in all (==t) $ map (uncurry TL.append) (TL.breakOnAll s t)
t_findContains = unsquare $ \(NotEmpty s) ->
all (T.isPrefixOf s . snd) . T.breakOnAll s . T.intercalate s
tl_findContains = unsquare $ \(NotEmpty s) -> all (TL.isPrefixOf s . snd) .
TL.breakOnAll s . TL.intercalate s
sl_filterCount c = (L.genericLength . L.filter (==c)) `eqP` SL.countChar c
t_findCount s = (L.length . T.breakOnAll s) `eq` T.count s
tl_findCount s = (L.genericLength . TL.breakOnAll s) `eq` TL.count s
t_splitOn_split s = unsquare $
(T.splitOn s `eq` Slow.splitOn s) . T.intercalate s
tl_splitOn_split s = unsquare $
((TL.splitOn (TL.fromStrict s) . TL.fromStrict) `eq`
(map TL.fromStrict . T.splitOn s)) . T.intercalate s
t_splitOn_i (NotEmpty t) = id `eq` (T.intercalate t . T.splitOn t)
tl_splitOn_i (NotEmpty t) = id `eq` (TL.intercalate t . TL.splitOn t)
t_split p = split p `eqP` (map unpackS . T.split p)
t_split_count c = (L.length . T.split (==c)) `eq`
((1+) . T.count (T.singleton c))
t_split_splitOn c = T.split (==c) `eq` T.splitOn (T.singleton c)
tl_split p = split p `eqP` (map unpackS . TL.split p)
split :: (a -> Bool) -> [a] -> [[a]]
split _ [] = [[]]
split p xs = loop xs
where loop s | null s' = [l]
| otherwise = l : loop (tail s')
where (l, s') = break p s
t_chunksOf_same_lengths k = all ((==k) . T.length) . ini . T.chunksOf k
where ini [] = []
ini xs = init xs
t_chunksOf_length k t = len == T.length t || (k <= 0 && len == 0)
where len = L.sum . L.map T.length $ T.chunksOf k t
tl_chunksOf k = T.chunksOf k `eq` (map (T.concat . TL.toChunks) .
TL.chunksOf (fromIntegral k) . TL.fromStrict)
t_lines = L.lines `eqP` (map unpackS . T.lines)
tl_lines = L.lines `eqP` (map unpackS . TL.lines)
{-
t_lines' = lines' `eqP` (map unpackS . T.lines')
where lines' "" = []
lines' s = let (l, s') = break eol s
in l : case s' of
[] -> []
('\r':'\n':s'') -> lines' s''
(_:s'') -> lines' s''
eol c = c == '\r' || c == '\n'
-}
t_words = L.words `eqP` (map unpackS . T.words)
tl_words = L.words `eqP` (map unpackS . TL.words)
t_unlines = unsquare $
L.unlines `eq` (unpackS . T.unlines . map packS)
tl_unlines = unsquare $
L.unlines `eq` (unpackS . TL.unlines . map packS)
t_unwords = unsquare $
L.unwords `eq` (unpackS . T.unwords . map packS)
tl_unwords = unsquare $
L.unwords `eq` (unpackS . TL.unwords . map packS)
s_isPrefixOf s = L.isPrefixOf s `eqP`
(S.isPrefixOf (S.stream $ packS s) . S.stream)
sf_isPrefixOf p s = (L.isPrefixOf s . L.filter p) `eqP`
(S.isPrefixOf (S.stream $ packS s) . S.filter p . S.stream)
t_isPrefixOf s = L.isPrefixOf s`eqP` T.isPrefixOf (packS s)
tl_isPrefixOf s = L.isPrefixOf s`eqP` TL.isPrefixOf (packS s)
t_isSuffixOf s = L.isSuffixOf s`eqP` T.isSuffixOf (packS s)
tl_isSuffixOf s = L.isSuffixOf s`eqP` TL.isSuffixOf (packS s)
t_isInfixOf s = L.isInfixOf s `eqP` T.isInfixOf (packS s)
tl_isInfixOf s = L.isInfixOf s `eqP` TL.isInfixOf (packS s)
t_stripPrefix s = (fmap packS . L.stripPrefix s) `eqP` T.stripPrefix (packS s)
tl_stripPrefix s = (fmap packS . L.stripPrefix s) `eqP` TL.stripPrefix (packS s)
stripSuffix p t = reverse `fmap` L.stripPrefix (reverse p) (reverse t)
t_stripSuffix s = (fmap packS . stripSuffix s) `eqP` T.stripSuffix (packS s)
tl_stripSuffix s = (fmap packS . stripSuffix s) `eqP` TL.stripSuffix (packS s)
commonPrefixes a0@(_:_) b0@(_:_) = Just (go a0 b0 [])
where go (a:as) (b:bs) ps
| a == b = go as bs (a:ps)
go as bs ps = (reverse ps,as,bs)
commonPrefixes _ _ = Nothing
t_commonPrefixes a b (NonEmpty p)
= commonPrefixes pa pb ==
repack `fmap` T.commonPrefixes (packS pa) (packS pb)
where repack (x,y,z) = (unpackS x,unpackS y,unpackS z)
pa = p ++ a
pb = p ++ b
tl_commonPrefixes a b (NonEmpty p)
= commonPrefixes pa pb ==
repack `fmap` TL.commonPrefixes (packS pa) (packS pb)
where repack (x,y,z) = (unpackS x,unpackS y,unpackS z)
pa = p ++ a
pb = p ++ b
sf_elem p c = (L.elem c . L.filter p) `eqP` (S.elem c . S.filter p)
sf_filter q p = (L.filter p . L.filter q) `eqP`
(unpackS . S.filter p . S.filter q)
t_filter p = L.filter p `eqP` (unpackS . T.filter p)
tl_filter p = L.filter p `eqP` (unpackS . TL.filter p)
sf_findBy q p = (L.find p . L.filter q) `eqP` (S.findBy p . S.filter q)
t_find p = L.find p `eqP` T.find p
tl_find p = L.find p `eqP` TL.find p
t_partition p = L.partition p `eqP` (unpack2 . T.partition p)
tl_partition p = L.partition p `eqP` (unpack2 . TL.partition p)
sf_index p s = forAll (choose (-l,l*2))
((L.filter p s L.!!) `eq` S.index (S.filter p $ packS s))
where l = L.length s
t_index s = forAll (choose (-l,l*2)) ((s L.!!) `eq` T.index (packS s))
where l = L.length s
tl_index s = forAll (choose (-l,l*2))
((s L.!!) `eq` (TL.index (packS s) . fromIntegral))
where l = L.length s
t_findIndex p = L.findIndex p `eqP` T.findIndex p
t_count (NotEmpty t) = (subtract 1 . L.length . T.splitOn t) `eq` T.count t
tl_count (NotEmpty t) = (subtract 1 . L.genericLength . TL.splitOn t) `eq`
TL.count t
t_zip s = L.zip s `eqP` T.zip (packS s)
tl_zip s = L.zip s `eqP` TL.zip (packS s)
sf_zipWith p c s = (L.zipWith c (L.filter p s) . L.filter p) `eqP`
(unpackS . S.zipWith c (S.filter p $ packS s) . S.filter p)
t_zipWith c s = L.zipWith c s `eqP` (unpackS . T.zipWith c (packS s))
tl_zipWith c s = L.zipWith c s `eqP` (unpackS . TL.zipWith c (packS s))
t_indices (NotEmpty s) = Slow.indices s `eq` indices s
tl_indices (NotEmpty s) = lazyIndices s `eq` S.indices s
where lazyIndices ss t = map fromIntegral $ Slow.indices (conc ss) (conc t)
conc = T.concat . TL.toChunks
t_indices_occurs = unsquare $ \(NotEmpty t) ts ->
let s = T.intercalate t ts
in Slow.indices t s === indices t s
-- Bit shifts.
shiftL w = forAll (choose (0,width-1)) $ \k -> Bits.shiftL w k == U.shiftL w k
where width = round (log (fromIntegral m) / log 2 :: Double)
(m,_) = (maxBound, m == w)
shiftR w = forAll (choose (0,width-1)) $ \k -> Bits.shiftR w k == U.shiftR w k
where width = round (log (fromIntegral m) / log 2 :: Double)
(m,_) = (maxBound, m == w)
shiftL_Int = shiftL :: Int -> Property
shiftL_Word16 = shiftL :: Word16 -> Property
shiftL_Word32 = shiftL :: Word32 -> Property
shiftR_Int = shiftR :: Int -> Property
shiftR_Word16 = shiftR :: Word16 -> Property
shiftR_Word32 = shiftR :: Word32 -> Property
-- Builder.
tb_singleton = id `eqP`
(unpackS . TB.toLazyText . mconcat . map TB.singleton)
tb_fromText = L.concat `eq` (unpackS . TB.toLazyText . mconcat .
map (TB.fromText . packS))
tb_associative s1 s2 s3 =
TB.toLazyText (b1 `mappend` (b2 `mappend` b3)) ==
TB.toLazyText ((b1 `mappend` b2) `mappend` b3)
where b1 = TB.fromText (packS s1)
b2 = TB.fromText (packS s2)
b3 = TB.fromText (packS s3)
-- Numeric builder stuff.
tb_decimal :: (Integral a, Show a) => a -> Bool
tb_decimal = (TB.toLazyText . TB.decimal) `eq` (TL.pack . show)
tb_decimal_integer (a::Integer) = tb_decimal a
tb_decimal_integer_big (Big a) = tb_decimal a
tb_decimal_int (a::Int) = tb_decimal a
tb_decimal_int8 (a::Int8) = tb_decimal a
tb_decimal_int16 (a::Int16) = tb_decimal a
tb_decimal_int32 (a::Int32) = tb_decimal a
tb_decimal_int64 (a::Int64) = tb_decimal a
tb_decimal_word (a::Word) = tb_decimal a
tb_decimal_word8 (a::Word8) = tb_decimal a
tb_decimal_word16 (a::Word16) = tb_decimal a
tb_decimal_word32 (a::Word32) = tb_decimal a
tb_decimal_word64 (a::Word64) = tb_decimal a
tb_decimal_big_int (BigBounded (a::Int)) = tb_decimal a
tb_decimal_big_int64 (BigBounded (a::Int64)) = tb_decimal a
tb_decimal_big_word (BigBounded (a::Word)) = tb_decimal a
tb_decimal_big_word64 (BigBounded (a::Word64)) = tb_decimal a
tb_hex :: (Integral a, Show a) => a -> Bool
tb_hex = (TB.toLazyText . TB.hexadecimal) `eq` (TL.pack . flip showHex "")
tb_hexadecimal_integer (a::Integer) = tb_hex a
tb_hexadecimal_int (a::Int) = tb_hex a
tb_hexadecimal_int8 (a::Int8) = tb_hex a
tb_hexadecimal_int16 (a::Int16) = tb_hex a
tb_hexadecimal_int32 (a::Int32) = tb_hex a
tb_hexadecimal_int64 (a::Int64) = tb_hex a
tb_hexadecimal_word (a::Word) = tb_hex a
tb_hexadecimal_word8 (a::Word8) = tb_hex a
tb_hexadecimal_word16 (a::Word16) = tb_hex a
tb_hexadecimal_word32 (a::Word32) = tb_hex a
tb_hexadecimal_word64 (a::Word64) = tb_hex a
tb_realfloat :: (RealFloat a, Show a) => a -> Bool
tb_realfloat = (TB.toLazyText . TB.realFloat) `eq` (TL.pack . show)
tb_realfloat_float (a::Float) = tb_realfloat a
tb_realfloat_double (a::Double) = tb_realfloat a
showFloat :: (RealFloat a) => TB.FPFormat -> Maybe Int -> a -> ShowS
showFloat TB.Exponent = showEFloat
showFloat TB.Fixed = showFFloat
showFloat TB.Generic = showGFloat
tb_formatRealFloat :: (RealFloat a, Show a) =>
a -> TB.FPFormat -> Precision a -> Property
tb_formatRealFloat a fmt prec =
TB.formatRealFloat fmt p a ===
TB.fromString (showFloat fmt p a "")
where p = precision a prec
tb_formatRealFloat_float (a::Float) = tb_formatRealFloat a
tb_formatRealFloat_double (a::Double) = tb_formatRealFloat a
-- Reading.
t_decimal (n::Int) s =
T.signed T.decimal (T.pack (show n) `T.append` t) === Right (n,t)
where t = T.dropWhile isDigit s
tl_decimal (n::Int) s =
TL.signed TL.decimal (TL.pack (show n) `TL.append` t) === Right (n,t)
where t = TL.dropWhile isDigit s
t_hexadecimal m s ox =
T.hexadecimal (T.concat [p, T.pack (showHex n ""), t]) === Right (n,t)
where t = T.dropWhile isHexDigit s
p = if ox then "0x" else ""
n = getPositive m :: Int
tl_hexadecimal m s ox =
TL.hexadecimal (TL.concat [p, TL.pack (showHex n ""), t]) === Right (n,t)
where t = TL.dropWhile isHexDigit s
p = if ox then "0x" else ""
n = getPositive m :: Int
isFloaty c = c `elem` ("+-.0123456789eE" :: String)
t_read_rational p tol (n::Double) s =
case p (T.pack (show n) `T.append` t) of
Left _err -> False
Right (n',t') -> t == t' && abs (n-n') <= tol
where t = T.dropWhile isFloaty s
tl_read_rational p tol (n::Double) s =
case p (TL.pack (show n) `TL.append` t) of
Left _err -> False
Right (n',t') -> t == t' && abs (n-n') <= tol
where t = TL.dropWhile isFloaty s
t_double = t_read_rational T.double 1e-13
tl_double = tl_read_rational TL.double 1e-13
t_rational = t_read_rational T.rational 1e-16
tl_rational = tl_read_rational TL.rational 1e-16
-- Input and output.
t_put_get = write_read T.unlines T.filter put get
where put h = withRedirect h IO.stdout . T.putStr
get h = withRedirect h IO.stdin T.getContents
tl_put_get = write_read TL.unlines TL.filter put get
where put h = withRedirect h IO.stdout . TL.putStr
get h = withRedirect h IO.stdin TL.getContents
t_write_read = write_read T.unlines T.filter T.hPutStr T.hGetContents
tl_write_read = write_read TL.unlines TL.filter TL.hPutStr TL.hGetContents
t_write_read_line e m b t = write_read head T.filter T.hPutStrLn
T.hGetLine e m b [t]
tl_write_read_line e m b t = write_read head TL.filter TL.hPutStrLn
TL.hGetLine e m b [t]
-- Low-level.
t_dropWord8 m t = dropWord8 m t `T.isSuffixOf` t
t_takeWord8 m t = takeWord8 m t `T.isPrefixOf` t
t_take_drop_8 m t = T.append (takeWord8 n t) (dropWord8 n t) == t
where n = small m
t_use_from t = monadicIO $ assert . (==t) =<< run (useAsPtr t fromPtr)
t_copy t = T.copy t === t
-- Regression tests.
s_filter_eq s = S.filter p t == S.streamList (filter p s)
where p = (/= S.last t)
t = S.streamList s
-- Make a stream appear shorter than it really is, to ensure that
-- functions that consume inaccurately sized streams behave
-- themselves.
shorten :: Int -> S.Stream a -> S.Stream a
shorten n t@(S.Stream arr off len)
| n > 0 = S.Stream arr off (smaller (exactSize n) len)
| otherwise = t
tests :: Test
tests =
testGroup "Properties" [
testGroup "creation/elimination" [
testProperty "t_pack_unpack" t_pack_unpack,
testProperty "tl_pack_unpack" tl_pack_unpack,
testProperty "t_stream_unstream" t_stream_unstream,
testProperty "tl_stream_unstream" tl_stream_unstream,
testProperty "t_reverse_stream" t_reverse_stream,
testProperty "t_singleton" t_singleton,
testProperty "tl_singleton" tl_singleton,
testProperty "tl_unstreamChunks" tl_unstreamChunks,
testProperty "tl_chunk_unchunk" tl_chunk_unchunk,
testProperty "tl_from_to_strict" tl_from_to_strict
],
testGroup "transcoding" [
testProperty "t_ascii" t_ascii,
testProperty "tl_ascii" tl_ascii,
testProperty "t_latin1" t_latin1,
testProperty "tl_latin1" tl_latin1,
testProperty "t_utf8" t_utf8,
testProperty "t_utf8'" t_utf8',
testProperty "t_utf8_incr" t_utf8_incr,
testProperty "t_utf8_undecoded" t_utf8_undecoded,
testProperty "tl_utf8" tl_utf8,
testProperty "tl_utf8'" tl_utf8',
testProperty "t_utf16LE" t_utf16LE,
testProperty "tl_utf16LE" tl_utf16LE,
testProperty "t_utf16BE" t_utf16BE,
testProperty "tl_utf16BE" tl_utf16BE,
testProperty "t_utf32LE" t_utf32LE,
testProperty "tl_utf32LE" tl_utf32LE,
testProperty "t_utf32BE" t_utf32BE,
testProperty "tl_utf32BE" tl_utf32BE,
testGroup "errors" [
testProperty "t_utf8_err" t_utf8_err,
testProperty "t_utf8_err'" t_utf8_err'
]
],
testGroup "instances" [
testProperty "s_Eq" s_Eq,
testProperty "sf_Eq" sf_Eq,
testProperty "t_Eq" t_Eq,
testProperty "tl_Eq" tl_Eq,
testProperty "s_Ord" s_Ord,
testProperty "sf_Ord" sf_Ord,
testProperty "t_Ord" t_Ord,
testProperty "tl_Ord" tl_Ord,
testProperty "t_Read" t_Read,
testProperty "tl_Read" tl_Read,
testProperty "t_Show" t_Show,
testProperty "tl_Show" tl_Show,
testProperty "t_mappend" t_mappend,
testProperty "tl_mappend" tl_mappend,
testProperty "t_mconcat" t_mconcat,
testProperty "tl_mconcat" tl_mconcat,
testProperty "t_mempty" t_mempty,
testProperty "tl_mempty" tl_mempty,
testProperty "t_IsString" t_IsString,
testProperty "tl_IsString" tl_IsString
],
testGroup "basics" [
testProperty "s_cons" s_cons,
testProperty "s_cons_s" s_cons_s,
testProperty "sf_cons" sf_cons,
testProperty "t_cons" t_cons,
testProperty "tl_cons" tl_cons,
testProperty "s_snoc" s_snoc,
testProperty "t_snoc" t_snoc,
testProperty "tl_snoc" tl_snoc,
testProperty "s_append" s_append,
testProperty "s_append_s" s_append_s,
testProperty "sf_append" sf_append,
testProperty "t_append" t_append,
testProperty "s_uncons" s_uncons,
testProperty "sf_uncons" sf_uncons,
testProperty "t_uncons" t_uncons,
testProperty "tl_uncons" tl_uncons,
testProperty "t_unsnoc" t_unsnoc,
testProperty "tl_unsnoc" tl_unsnoc,
testProperty "s_head" s_head,
testProperty "sf_head" sf_head,
testProperty "t_head" t_head,
testProperty "tl_head" tl_head,
testProperty "s_last" s_last,
testProperty "sf_last" sf_last,
testProperty "t_last" t_last,
testProperty "tl_last" tl_last,
testProperty "s_tail" s_tail,
testProperty "s_tail_s" s_tail_s,
testProperty "sf_tail" sf_tail,
testProperty "t_tail" t_tail,
testProperty "tl_tail" tl_tail,
testProperty "s_init" s_init,
testProperty "s_init_s" s_init_s,
testProperty "sf_init" sf_init,
testProperty "t_init" t_init,
testProperty "tl_init" tl_init,
testProperty "s_null" s_null,
testProperty "sf_null" sf_null,
testProperty "t_null" t_null,
testProperty "tl_null" tl_null,
testProperty "s_length" s_length,
testProperty "sf_length" sf_length,
testProperty "sl_length" sl_length,
testProperty "t_length" t_length,
testProperty "tl_length" tl_length,
testProperty "t_compareLength" t_compareLength,
testProperty "tl_compareLength" tl_compareLength
],
testGroup "transformations" [
testProperty "s_map" s_map,
testProperty "s_map_s" s_map_s,
testProperty "sf_map" sf_map,
testProperty "t_map" t_map,
testProperty "tl_map" tl_map,
testProperty "s_intercalate" s_intercalate,
testProperty "t_intercalate" t_intercalate,
testProperty "tl_intercalate" tl_intercalate,
testProperty "s_intersperse" s_intersperse,
testProperty "s_intersperse_s" s_intersperse_s,
testProperty "sf_intersperse" sf_intersperse,
testProperty "t_intersperse" t_intersperse,
testProperty "tl_intersperse" tl_intersperse,
testProperty "t_transpose" t_transpose,
testProperty "tl_transpose" tl_transpose,
testProperty "t_reverse" t_reverse,
testProperty "tl_reverse" tl_reverse,
testProperty "t_reverse_short" t_reverse_short,
testProperty "t_replace" t_replace,
testProperty "tl_replace" tl_replace,
testGroup "case conversion" [
testProperty "s_toCaseFold_length" s_toCaseFold_length,
testProperty "sf_toCaseFold_length" sf_toCaseFold_length,
testProperty "t_toCaseFold_length" t_toCaseFold_length,
testProperty "tl_toCaseFold_length" tl_toCaseFold_length,
testProperty "t_toLower_length" t_toLower_length,
testProperty "t_toLower_lower" t_toLower_lower,
testProperty "tl_toLower_lower" tl_toLower_lower,
testProperty "t_toUpper_length" t_toUpper_length,
testProperty "t_toUpper_upper" t_toUpper_upper,
testProperty "tl_toUpper_upper" tl_toUpper_upper,
testProperty "t_toTitle_title" t_toTitle_title,
testProperty "t_toTitle_1stNotLower" t_toTitle_1stNotLower
],
testGroup "justification" [
testProperty "s_justifyLeft" s_justifyLeft,
testProperty "s_justifyLeft_s" s_justifyLeft_s,
testProperty "sf_justifyLeft" sf_justifyLeft,
testProperty "t_justifyLeft" t_justifyLeft,
testProperty "tl_justifyLeft" tl_justifyLeft,
testProperty "t_justifyRight" t_justifyRight,
testProperty "tl_justifyRight" tl_justifyRight,
testProperty "t_center" t_center,
testProperty "tl_center" tl_center
]
],
testGroup "folds" [
testProperty "sf_foldl" sf_foldl,
testProperty "t_foldl" t_foldl,
testProperty "tl_foldl" tl_foldl,
testProperty "sf_foldl'" sf_foldl',
testProperty "t_foldl'" t_foldl',
testProperty "tl_foldl'" tl_foldl',
testProperty "sf_foldl1" sf_foldl1,
testProperty "t_foldl1" t_foldl1,
testProperty "tl_foldl1" tl_foldl1,
testProperty "t_foldl1'" t_foldl1',
testProperty "sf_foldl1'" sf_foldl1',
testProperty "tl_foldl1'" tl_foldl1',
testProperty "sf_foldr" sf_foldr,
testProperty "t_foldr" t_foldr,
testProperty "tl_foldr" tl_foldr,
testProperty "sf_foldr1" sf_foldr1,
testProperty "t_foldr1" t_foldr1,
testProperty "tl_foldr1" tl_foldr1,
testGroup "special" [
testProperty "s_concat_s" s_concat_s,
testProperty "sf_concat" sf_concat,
testProperty "t_concat" t_concat,
testProperty "tl_concat" tl_concat,
testProperty "sf_concatMap" sf_concatMap,
testProperty "t_concatMap" t_concatMap,
testProperty "tl_concatMap" tl_concatMap,
testProperty "sf_any" sf_any,
testProperty "t_any" t_any,
testProperty "tl_any" tl_any,
testProperty "sf_all" sf_all,
testProperty "t_all" t_all,
testProperty "tl_all" tl_all,
testProperty "sf_maximum" sf_maximum,
testProperty "t_maximum" t_maximum,
testProperty "tl_maximum" tl_maximum,
testProperty "sf_minimum" sf_minimum,
testProperty "t_minimum" t_minimum,
testProperty "tl_minimum" tl_minimum
]
],
testGroup "construction" [
testGroup "scans" [
testProperty "sf_scanl" sf_scanl,
testProperty "t_scanl" t_scanl,
testProperty "tl_scanl" tl_scanl,
testProperty "t_scanl1" t_scanl1,
testProperty "tl_scanl1" tl_scanl1,
testProperty "t_scanr" t_scanr,
testProperty "tl_scanr" tl_scanr,
testProperty "t_scanr1" t_scanr1,
testProperty "tl_scanr1" tl_scanr1
],
testGroup "mapAccum" [
testProperty "t_mapAccumL" t_mapAccumL,
testProperty "tl_mapAccumL" tl_mapAccumL,
testProperty "t_mapAccumR" t_mapAccumR,
testProperty "tl_mapAccumR" tl_mapAccumR
],
testGroup "unfolds" [
testProperty "tl_repeat" tl_repeat,
testProperty "s_replicate" s_replicate,
testProperty "t_replicate" t_replicate,
testProperty "tl_replicate" tl_replicate,
testProperty "tl_cycle" tl_cycle,
testProperty "tl_iterate" tl_iterate,
testProperty "t_unfoldr" t_unfoldr,
testProperty "tl_unfoldr" tl_unfoldr,
testProperty "t_unfoldrN" t_unfoldrN,
testProperty "tl_unfoldrN" tl_unfoldrN
]
],
testGroup "substrings" [
testGroup "breaking" [
testProperty "s_take" s_take,
testProperty "s_take_s" s_take_s,
testProperty "sf_take" sf_take,
testProperty "t_take" t_take,
testProperty "t_takeEnd" t_takeEnd,
testProperty "tl_take" tl_take,
testProperty "tl_takeEnd" tl_takeEnd,
testProperty "s_drop" s_drop,
testProperty "s_drop_s" s_drop_s,
testProperty "sf_drop" sf_drop,
testProperty "t_drop" t_drop,
testProperty "t_dropEnd" t_dropEnd,
testProperty "tl_drop" tl_drop,
testProperty "tl_dropEnd" tl_dropEnd,
testProperty "s_take_drop" s_take_drop,
testProperty "s_take_drop_s" s_take_drop_s,
testProperty "s_takeWhile" s_takeWhile,
testProperty "s_takeWhile_s" s_takeWhile_s,
testProperty "sf_takeWhile" sf_takeWhile,
testProperty "t_takeWhile" t_takeWhile,
testProperty "tl_takeWhile" tl_takeWhile,
testProperty "t_takeWhileEnd" t_takeWhileEnd,
testProperty "t_takeWhileEnd_null" t_takeWhileEnd_null,
testProperty "tl_takeWhileEnd" tl_takeWhileEnd,
testProperty "tl_takeWhileEnd_null" tl_takeWhileEnd_null,
testProperty "sf_dropWhile" sf_dropWhile,
testProperty "s_dropWhile" s_dropWhile,
testProperty "s_dropWhile_s" s_dropWhile_s,
testProperty "t_dropWhile" t_dropWhile,
testProperty "tl_dropWhile" tl_dropWhile,
testProperty "t_dropWhileEnd" t_dropWhileEnd,
testProperty "tl_dropWhileEnd" tl_dropWhileEnd,
testProperty "t_dropAround" t_dropAround,
testProperty "tl_dropAround" tl_dropAround,
testProperty "t_stripStart" t_stripStart,
testProperty "tl_stripStart" tl_stripStart,
testProperty "t_stripEnd" t_stripEnd,
testProperty "tl_stripEnd" tl_stripEnd,
testProperty "t_strip" t_strip,
testProperty "tl_strip" tl_strip,
testProperty "t_splitAt" t_splitAt,
testProperty "tl_splitAt" tl_splitAt,
testProperty "t_span" t_span,
testProperty "tl_span" tl_span,
testProperty "t_breakOn_id" t_breakOn_id,
testProperty "tl_breakOn_id" tl_breakOn_id,
testProperty "t_breakOn_start" t_breakOn_start,
testProperty "tl_breakOn_start" tl_breakOn_start,
testProperty "t_breakOnEnd_end" t_breakOnEnd_end,
testProperty "tl_breakOnEnd_end" tl_breakOnEnd_end,
testProperty "t_break" t_break,
testProperty "tl_break" tl_break,
testProperty "t_group" t_group,
testProperty "tl_group" tl_group,
testProperty "t_groupBy" t_groupBy,
testProperty "tl_groupBy" tl_groupBy,
testProperty "t_inits" t_inits,
testProperty "tl_inits" tl_inits,
testProperty "t_tails" t_tails,
testProperty "tl_tails" tl_tails
],
testGroup "breaking many" [
testProperty "t_findAppendId" t_findAppendId,
testProperty "tl_findAppendId" tl_findAppendId,
testProperty "t_findContains" t_findContains,
testProperty "tl_findContains" tl_findContains,
testProperty "sl_filterCount" sl_filterCount,
testProperty "t_findCount" t_findCount,
testProperty "tl_findCount" tl_findCount,
testProperty "t_splitOn_split" t_splitOn_split,
testProperty "tl_splitOn_split" tl_splitOn_split,
testProperty "t_splitOn_i" t_splitOn_i,
testProperty "tl_splitOn_i" tl_splitOn_i,
testProperty "t_split" t_split,
testProperty "t_split_count" t_split_count,
testProperty "t_split_splitOn" t_split_splitOn,
testProperty "tl_split" tl_split,
testProperty "t_chunksOf_same_lengths" t_chunksOf_same_lengths,
testProperty "t_chunksOf_length" t_chunksOf_length,
testProperty "tl_chunksOf" tl_chunksOf
],
testGroup "lines and words" [
testProperty "t_lines" t_lines,
testProperty "tl_lines" tl_lines,
--testProperty "t_lines'" t_lines',
testProperty "t_words" t_words,
testProperty "tl_words" tl_words,
testProperty "t_unlines" t_unlines,
testProperty "tl_unlines" tl_unlines,
testProperty "t_unwords" t_unwords,
testProperty "tl_unwords" tl_unwords
]
],
testGroup "predicates" [
testProperty "s_isPrefixOf" s_isPrefixOf,
testProperty "sf_isPrefixOf" sf_isPrefixOf,
testProperty "t_isPrefixOf" t_isPrefixOf,
testProperty "tl_isPrefixOf" tl_isPrefixOf,
testProperty "t_isSuffixOf" t_isSuffixOf,
testProperty "tl_isSuffixOf" tl_isSuffixOf,
testProperty "t_isInfixOf" t_isInfixOf,
testProperty "tl_isInfixOf" tl_isInfixOf,
testGroup "view" [
testProperty "t_stripPrefix" t_stripPrefix,
testProperty "tl_stripPrefix" tl_stripPrefix,
testProperty "t_stripSuffix" t_stripSuffix,
testProperty "tl_stripSuffix" tl_stripSuffix,
testProperty "t_commonPrefixes" t_commonPrefixes,
testProperty "tl_commonPrefixes" tl_commonPrefixes
]
],
testGroup "searching" [
testProperty "sf_elem" sf_elem,
testProperty "sf_filter" sf_filter,
testProperty "t_filter" t_filter,
testProperty "tl_filter" tl_filter,
testProperty "sf_findBy" sf_findBy,
testProperty "t_find" t_find,
testProperty "tl_find" tl_find,
testProperty "t_partition" t_partition,
testProperty "tl_partition" tl_partition
],
testGroup "indexing" [
testProperty "sf_index" sf_index,
testProperty "t_index" t_index,
testProperty "tl_index" tl_index,
testProperty "t_findIndex" t_findIndex,
testProperty "t_count" t_count,
testProperty "tl_count" tl_count,
testProperty "t_indices" t_indices,
testProperty "tl_indices" tl_indices,
testProperty "t_indices_occurs" t_indices_occurs
],
testGroup "zips" [
testProperty "t_zip" t_zip,
testProperty "tl_zip" tl_zip,
testProperty "sf_zipWith" sf_zipWith,
testProperty "t_zipWith" t_zipWith,
testProperty "tl_zipWith" tl_zipWith
],
testGroup "regressions" [
testProperty "s_filter_eq" s_filter_eq
],
testGroup "shifts" [
testProperty "shiftL_Int" shiftL_Int,
testProperty "shiftL_Word16" shiftL_Word16,
testProperty "shiftL_Word32" shiftL_Word32,
testProperty "shiftR_Int" shiftR_Int,
testProperty "shiftR_Word16" shiftR_Word16,
testProperty "shiftR_Word32" shiftR_Word32
],
testGroup "builder" [
testProperty "tb_associative" tb_associative,
testGroup "decimal" [
testProperty "tb_decimal_int" tb_decimal_int,
testProperty "tb_decimal_int8" tb_decimal_int8,
testProperty "tb_decimal_int16" tb_decimal_int16,
testProperty "tb_decimal_int32" tb_decimal_int32,
testProperty "tb_decimal_int64" tb_decimal_int64,
testProperty "tb_decimal_integer" tb_decimal_integer,
testProperty "tb_decimal_integer_big" tb_decimal_integer_big,
testProperty "tb_decimal_word" tb_decimal_word,
testProperty "tb_decimal_word8" tb_decimal_word8,
testProperty "tb_decimal_word16" tb_decimal_word16,
testProperty "tb_decimal_word32" tb_decimal_word32,
testProperty "tb_decimal_word64" tb_decimal_word64,
testProperty "tb_decimal_big_int" tb_decimal_big_int,
testProperty "tb_decimal_big_word" tb_decimal_big_word,
testProperty "tb_decimal_big_int64" tb_decimal_big_int64,
testProperty "tb_decimal_big_word64" tb_decimal_big_word64
],
testGroup "hexadecimal" [
testProperty "tb_hexadecimal_int" tb_hexadecimal_int,
testProperty "tb_hexadecimal_int8" tb_hexadecimal_int8,
testProperty "tb_hexadecimal_int16" tb_hexadecimal_int16,
testProperty "tb_hexadecimal_int32" tb_hexadecimal_int32,
testProperty "tb_hexadecimal_int64" tb_hexadecimal_int64,
testProperty "tb_hexadecimal_integer" tb_hexadecimal_integer,
testProperty "tb_hexadecimal_word" tb_hexadecimal_word,
testProperty "tb_hexadecimal_word8" tb_hexadecimal_word8,
testProperty "tb_hexadecimal_word16" tb_hexadecimal_word16,
testProperty "tb_hexadecimal_word32" tb_hexadecimal_word32,
testProperty "tb_hexadecimal_word64" tb_hexadecimal_word64
],
testGroup "realfloat" [
testProperty "tb_realfloat_double" tb_realfloat_double,
testProperty "tb_realfloat_float" tb_realfloat_float,
testProperty "tb_formatRealFloat_float" tb_formatRealFloat_float,
testProperty "tb_formatRealFloat_double" tb_formatRealFloat_double
],
testProperty "tb_fromText" tb_fromText,
testProperty "tb_singleton" tb_singleton
],
testGroup "read" [
testProperty "t_decimal" t_decimal,
testProperty "tl_decimal" tl_decimal,
testProperty "t_hexadecimal" t_hexadecimal,
testProperty "tl_hexadecimal" tl_hexadecimal,
testProperty "t_double" t_double,
testProperty "tl_double" tl_double,
testProperty "t_rational" t_rational,
testProperty "tl_rational" tl_rational
],
{-
testGroup "input-output" [
testProperty "t_write_read" t_write_read,
testProperty "tl_write_read" tl_write_read,
testProperty "t_write_read_line" t_write_read_line,
testProperty "tl_write_read_line" tl_write_read_line
-- These tests are subject to I/O race conditions when run under
-- test-framework-quickcheck2.
-- testProperty "t_put_get" t_put_get
-- testProperty "tl_put_get" tl_put_get
],
-}
testGroup "lowlevel" [
testProperty "t_dropWord8" t_dropWord8,
testProperty "t_takeWord8" t_takeWord8,
testProperty "t_take_drop_8" t_take_drop_8,
testProperty "t_use_from" t_use_from,
testProperty "t_copy" t_copy
],
testGroup "mul" Mul.tests
]
| text-utf8/text | tests/Tests/Properties.hs | bsd-2-clause | 61,507 | 2 | 24 | 16,179 | 21,578 | 11,275 | 10,303 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Options
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mateusz Kowalczyk 2013
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Definition of the command line interface of Haddock.
-----------------------------------------------------------------------------
module Haddock.Options (
parseHaddockOpts,
Flag(..),
getUsage,
optTitle,
outputDir,
optContentsUrl,
optIndexUrl,
optCssFile,
optSourceCssFile,
sourceUrls,
wikiUrls,
baseUrl,
optParCount,
optDumpInterfaceFile,
optShowInterfaceFile,
optLaTeXStyle,
optMathjax,
qualification,
sinceQualification,
verbosity,
ghcFlags,
reexportFlags,
readIfaceArgs,
optPackageName,
optPackageVersion,
modulePackageInfo,
ignoredSymbols
) where
import qualified Data.Char as Char
import Data.Version
import Control.Applicative
import GHC.Data.FastString
import GHC ( Module, moduleUnit )
import GHC.Unit.State
import Haddock.Types
import Haddock.Utils
import System.Console.GetOpt
import qualified Text.ParserCombinators.ReadP as RP
data Flag
= Flag_BuiltInThemes
| Flag_CSS String
-- | Flag_DocBook
| Flag_ReadInterface String
| Flag_DumpInterface String
| Flag_ShowInterface String
| Flag_Heading String
| Flag_Html
| Flag_Hoogle
| Flag_Lib String
| Flag_OutputDir FilePath
| Flag_Prologue FilePath
| Flag_SourceBaseURL String
| Flag_SourceModuleURL String
| Flag_SourceEntityURL String
| Flag_SourceLEntityURL String
| Flag_WikiBaseURL String
| Flag_BaseURL String
| Flag_WikiModuleURL String
| Flag_WikiEntityURL String
| Flag_LaTeX
| Flag_LaTeXStyle String
| Flag_QuickJumpIndex
| Flag_HyperlinkedSource
| Flag_SourceCss String
| Flag_Mathjax String
| Flag_Help
| Flag_Verbosity String
| Flag_Version
| Flag_CompatibleInterfaceVersions
| Flag_InterfaceVersion
| Flag_BypassInterfaceVersonCheck
| Flag_UseContents String
| Flag_GenContents
| Flag_UseIndex String
| Flag_GenIndex
| Flag_IgnoreAllExports
| Flag_HideModule String
| Flag_ShowModule String
| Flag_ShowAllModules
| Flag_ShowExtensions String
| Flag_OptGhc String
| Flag_GhcLibDir String
| Flag_GhcVersion
| Flag_PrintGhcPath
| Flag_PrintGhcLibDir
| Flag_NoWarnings
| Flag_UseUnicode
| Flag_NoTmpCompDir
| Flag_Qualification String
| Flag_PrettyHtml
| Flag_NoPrintMissingDocs
| Flag_PackageName String
| Flag_PackageVersion String
| Flag_Reexport String
| Flag_SinceQualification String
| Flag_IgnoreLinkSymbol String
| Flag_ParCount (Maybe Int)
deriving (Eq, Show)
options :: Bool -> [OptDescr Flag]
options backwardsCompat =
[
Option ['B'] [] (ReqArg Flag_GhcLibDir "DIR")
"path to a GHC lib dir, to override the default path",
Option ['o'] ["odir"] (ReqArg Flag_OutputDir "DIR")
"directory in which to put the output files",
Option ['l'] ["lib"] (ReqArg Flag_Lib "DIR")
"location of Haddock's auxiliary files",
Option ['i'] ["read-interface"] (ReqArg Flag_ReadInterface "FILE")
"read an interface from FILE",
Option ['D'] ["dump-interface"] (ReqArg Flag_DumpInterface "FILE")
"write the resulting interface to FILE",
Option [] ["show-interface"] (ReqArg Flag_ShowInterface "FILE")
"print the interface in a human readable form",
-- Option ['S'] ["docbook"] (NoArg Flag_DocBook)
-- "output in DocBook XML",
Option ['h'] ["html"] (NoArg Flag_Html)
"output in HTML (XHTML 1.0)",
Option [] ["latex"] (NoArg Flag_LaTeX) "use experimental LaTeX rendering",
Option [] ["latex-style"] (ReqArg Flag_LaTeXStyle "FILE") "provide your own LaTeX style in FILE",
Option [] ["mathjax"] (ReqArg Flag_Mathjax "URL") "URL FOR mathjax",
Option ['U'] ["use-unicode"] (NoArg Flag_UseUnicode) "use Unicode in HTML output",
Option [] ["hoogle"] (NoArg Flag_Hoogle)
"output for Hoogle; you may want --package-name and --package-version too",
Option [] ["quickjump"] (NoArg Flag_QuickJumpIndex)
"generate an index for interactive documentation navigation",
Option [] ["hyperlinked-source"] (NoArg Flag_HyperlinkedSource)
"generate highlighted and hyperlinked source code (for use with --html)",
Option [] ["source-css"] (ReqArg Flag_SourceCss "FILE")
"use custom CSS file instead of default one in hyperlinked source",
Option [] ["source-base"] (ReqArg Flag_SourceBaseURL "URL")
"URL for a source code link on the contents\nand index pages",
Option ['s'] (if backwardsCompat then ["source", "source-module"] else ["source-module"])
(ReqArg Flag_SourceModuleURL "URL")
"URL for a source code link for each module\n(using the %{FILE} or %{MODULE} vars)",
Option [] ["source-entity"] (ReqArg Flag_SourceEntityURL "URL")
"URL for a source code link for each entity\n(using the %{FILE}, %{MODULE}, %{NAME},\n%{KIND} or %{LINE} vars)",
Option [] ["source-entity-line"] (ReqArg Flag_SourceLEntityURL "URL")
"URL for a source code link for each entity.\nUsed if name links are unavailable, eg. for TH splices.",
Option [] ["comments-base"] (ReqArg Flag_WikiBaseURL "URL")
"URL for a comments link on the contents\nand index pages",
Option [] ["base-url"] (ReqArg Flag_BaseURL "URL")
"Base URL for static assets (eg. css, javascript, json files etc.).\nWhen given statis assets will not be copied.",
Option [] ["comments-module"] (ReqArg Flag_WikiModuleURL "URL")
"URL for a comments link for each module\n(using the %{MODULE} var)",
Option [] ["comments-entity"] (ReqArg Flag_WikiEntityURL "URL")
"URL for a comments link for each entity\n(using the %{FILE}, %{MODULE}, %{NAME},\n%{KIND} or %{LINE} vars)",
Option ['c'] ["css", "theme"] (ReqArg Flag_CSS "PATH")
"the CSS file or theme directory to use for HTML output",
Option [] ["built-in-themes"] (NoArg Flag_BuiltInThemes)
"include all the built-in haddock themes",
Option ['p'] ["prologue"] (ReqArg Flag_Prologue "FILE")
"file containing prologue text",
Option ['t'] ["title"] (ReqArg Flag_Heading "TITLE")
"page heading",
Option ['q'] ["qual"] (ReqArg Flag_Qualification "QUAL")
"qualification of names, one of \n'none' (default), 'full', 'local'\n'relative' or 'aliased'",
Option ['?'] ["help"] (NoArg Flag_Help)
"display this help and exit",
Option ['V'] ["version"] (NoArg Flag_Version)
"output version information and exit",
Option [] ["compatible-interface-versions"] (NoArg Flag_CompatibleInterfaceVersions)
"output compatible interface file versions and exit",
Option [] ["interface-version"] (NoArg Flag_InterfaceVersion)
"output interface file version and exit",
Option [] ["bypass-interface-version-check"] (NoArg Flag_BypassInterfaceVersonCheck)
"bypass the interface file version check (dangerous)",
Option ['v'] ["verbosity"] (ReqArg Flag_Verbosity "VERBOSITY")
"set verbosity level",
Option [] ["use-contents"] (ReqArg Flag_UseContents "URL")
"use a separately-generated HTML contents page",
Option [] ["gen-contents"] (NoArg Flag_GenContents)
"generate an HTML contents from specified\ninterfaces",
Option [] ["use-index"] (ReqArg Flag_UseIndex "URL")
"use a separately-generated HTML index",
Option [] ["gen-index"] (NoArg Flag_GenIndex)
"generate an HTML index from specified\ninterfaces",
Option [] ["ignore-all-exports"] (NoArg Flag_IgnoreAllExports)
"behave as if all modules have the\nignore-exports attribute",
Option [] ["hide"] (ReqArg Flag_HideModule "MODULE")
"behave as if MODULE has the hide attribute",
Option [] ["show"] (ReqArg Flag_ShowModule "MODULE")
"behave as if MODULE does not have the hide attribute",
Option [] ["show-all"] (NoArg Flag_ShowAllModules)
"behave as if not modules have the hide attribute",
Option [] ["show-extensions"] (ReqArg Flag_ShowExtensions "MODULE")
"behave as if MODULE has the show-extensions attribute",
Option [] ["optghc"] (ReqArg Flag_OptGhc "OPTION")
"option to be forwarded to GHC",
Option [] ["ghc-version"] (NoArg Flag_GhcVersion)
"output GHC version in numeric format",
Option [] ["print-ghc-path"] (NoArg Flag_PrintGhcPath)
"output path to GHC binary",
Option [] ["print-ghc-libdir"] (NoArg Flag_PrintGhcLibDir)
"output GHC lib dir",
Option ['w'] ["no-warnings"] (NoArg Flag_NoWarnings) "turn off all warnings",
Option [] ["no-tmp-comp-dir"] (NoArg Flag_NoTmpCompDir)
"do not re-direct compilation output to a temporary directory",
Option [] ["pretty-html"] (NoArg Flag_PrettyHtml)
"generate html with newlines and indenting (for use with --html)",
Option [] ["no-print-missing-docs"] (NoArg Flag_NoPrintMissingDocs)
"don't print information about any undocumented entities",
Option [] ["reexport"] (ReqArg Flag_Reexport "MOD")
"reexport the module MOD, adding it to the index",
Option [] ["package-name"] (ReqArg Flag_PackageName "NAME")
"name of the package being documented",
Option [] ["package-version"] (ReqArg Flag_PackageVersion "VERSION")
"version of the package being documented in usual x.y.z.w format",
Option [] ["since-qual"] (ReqArg Flag_SinceQualification "QUAL")
"package qualification of @since, one of\n'always' (default) or 'only-external'",
Option [] ["ignore-link-symbol"] (ReqArg Flag_IgnoreLinkSymbol "SYMBOL")
"name of a symbol which does not trigger a warning in case of link issue",
Option ['j'] [] (OptArg (\count -> Flag_ParCount (fmap read count)) "n")
"load modules in parallel"
]
getUsage :: IO String
getUsage = do
prog <- getProgramName
return $ usageInfo (usageHeader prog) (options False)
where
usageHeader :: String -> String
usageHeader prog = "Usage: " ++ prog ++ " [OPTION...] file...\n"
parseHaddockOpts :: [String] -> IO ([Flag], [String])
parseHaddockOpts params =
case getOpt Permute (options True) params of
(flags, args, []) -> return (flags, args)
(_, _, errors) -> do
usage <- getUsage
throwE (concat errors ++ usage)
optPackageVersion :: [Flag] -> Maybe Data.Version.Version
optPackageVersion flags =
let ver = optLast [ v | Flag_PackageVersion v <- flags ]
in ver >>= fmap fst . optLast . RP.readP_to_S parseVersion
optPackageName :: [Flag] -> Maybe PackageName
optPackageName flags =
optLast [ PackageName $ mkFastString n | Flag_PackageName n <- flags ]
optTitle :: [Flag] -> Maybe String
optTitle flags =
case [str | Flag_Heading str <- flags] of
[] -> Nothing
(t:_) -> Just t
outputDir :: [Flag] -> FilePath
outputDir flags =
case [ path | Flag_OutputDir path <- flags ] of
[] -> "."
paths -> last paths
optContentsUrl :: [Flag] -> Maybe String
optContentsUrl flags = optLast [ url | Flag_UseContents url <- flags ]
optIndexUrl :: [Flag] -> Maybe String
optIndexUrl flags = optLast [ url | Flag_UseIndex url <- flags ]
optCssFile :: [Flag] -> Maybe FilePath
optCssFile flags = optLast [ str | Flag_CSS str <- flags ]
optSourceCssFile :: [Flag] -> Maybe FilePath
optSourceCssFile flags = optLast [ str | Flag_SourceCss str <- flags ]
sourceUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String, Maybe String)
sourceUrls flags =
(optLast [str | Flag_SourceBaseURL str <- flags]
,optLast [str | Flag_SourceModuleURL str <- flags]
,optLast [str | Flag_SourceEntityURL str <- flags]
,optLast [str | Flag_SourceLEntityURL str <- flags])
wikiUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String)
wikiUrls flags =
(optLast [str | Flag_WikiBaseURL str <- flags]
,optLast [str | Flag_WikiModuleURL str <- flags]
,optLast [str | Flag_WikiEntityURL str <- flags])
baseUrl :: [Flag] -> Maybe String
baseUrl flags = optLast [str | Flag_BaseURL str <- flags]
optDumpInterfaceFile :: [Flag] -> Maybe FilePath
optDumpInterfaceFile flags = optLast [ str | Flag_DumpInterface str <- flags ]
optShowInterfaceFile :: [Flag] -> Maybe FilePath
optShowInterfaceFile flags = optLast [ str | Flag_ShowInterface str <- flags ]
optLaTeXStyle :: [Flag] -> Maybe String
optLaTeXStyle flags = optLast [ str | Flag_LaTeXStyle str <- flags ]
optMathjax :: [Flag] -> Maybe String
optMathjax flags = optLast [ str | Flag_Mathjax str <- flags ]
optParCount :: [Flag] -> Maybe (Maybe Int)
optParCount flags = optLast [ n | Flag_ParCount n <- flags ]
qualification :: [Flag] -> Either String QualOption
qualification flags =
case map (map Char.toLower) [ str | Flag_Qualification str <- flags ] of
[] -> Right OptNoQual
["none"] -> Right OptNoQual
["full"] -> Right OptFullQual
["local"] -> Right OptLocalQual
["relative"] -> Right OptRelativeQual
["aliased"] -> Right OptAliasedQual
[arg] -> Left $ "unknown qualification type " ++ show arg
_:_ -> Left "qualification option given multiple times"
sinceQualification :: [Flag] -> Either String SinceQual
sinceQualification flags =
case map (map Char.toLower) [ str | Flag_SinceQualification str <- flags ] of
[] -> Right Always
["always"] -> Right Always
["external"] -> Right External
[arg] -> Left $ "unknown since-qualification type " ++ show arg
_:_ -> Left "since-qualification option given multiple times"
verbosity :: [Flag] -> Verbosity
verbosity flags =
case [ str | Flag_Verbosity str <- flags ] of
[] -> Normal
x:_ -> case parseVerbosity x of
Left e -> throwE e
Right v -> v
ignoredSymbols :: [Flag] -> [String]
ignoredSymbols flags = [ symbol | Flag_IgnoreLinkSymbol symbol <- flags ]
ghcFlags :: [Flag] -> [String]
ghcFlags flags = [ option | Flag_OptGhc option <- flags ]
reexportFlags :: [Flag] -> [String]
reexportFlags flags = [ option | Flag_Reexport option <- flags ]
readIfaceArgs :: [Flag] -> [(DocPaths, FilePath)]
readIfaceArgs flags = [ parseIfaceOption s | Flag_ReadInterface s <- flags ]
where
parseIfaceOption :: String -> (DocPaths, FilePath)
parseIfaceOption str =
case break (==',') str of
(fpath, ',':rest) ->
case break (==',') rest of
(src, ',':file) -> ((fpath, Just src), file)
(file, _) -> ((fpath, Nothing), file)
(file, _) -> (("", Nothing), file)
-- | Like 'listToMaybe' but returns the last element instead of the first.
optLast :: [a] -> Maybe a
optLast [] = Nothing
optLast xs = Just (last xs)
-- | This function has a potential to return 'Nothing' because package name and
-- versions can no longer reliably be extracted in all cases: if the package is
-- not installed yet then this info is no longer available.
--
-- The @--package-name@ and @--package-version@ Haddock flags allow the user to
-- specify this information manually and it is returned here if present.
modulePackageInfo :: UnitState
-> [Flag] -- ^ Haddock flags are checked as they may contain
-- the package name or version provided by the user
-- which we prioritise
-> Maybe Module
-> (Maybe PackageName, Maybe Data.Version.Version)
modulePackageInfo _unit_state _flags Nothing = (Nothing, Nothing)
modulePackageInfo unit_state flags (Just modu) =
( optPackageName flags <|> fmap unitPackageName pkgDb
, optPackageVersion flags <|> fmap unitPackageVersion pkgDb
)
where
pkgDb = lookupUnit unit_state (moduleUnit modu)
| haskell/haddock | haddock-api/src/Haddock/Options.hs | bsd-2-clause | 16,010 | 0 | 15 | 3,426 | 3,793 | 2,027 | 1,766 | 325 | 8 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.MESA.ProgramBinaryFormats
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.MESA.ProgramBinaryFormats (
-- * Extension Support
glGetMESAProgramBinaryFormats,
gl_MESA_program_binary_formats,
-- * Enums
pattern GL_PROGRAM_BINARY_FORMAT_MESA
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
| haskell-opengl/OpenGLRaw | src/Graphics/GL/MESA/ProgramBinaryFormats.hs | bsd-3-clause | 693 | 0 | 5 | 91 | 47 | 36 | 11 | 7 | 0 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE OverloadedStrings #-}
module Controllers.Reply
( routes ) where
import Control.Monad.CatchIO (try)
import Control.Monad.Trans
import qualified Data.ByteString as BS
import qualified Data.Text as T
import Data.Time
import qualified Heist.Interpreted as I
import Snap.Snaplet
import Snap.Snaplet.Heist
import Text.Digestive
import Application
import Controllers.Topic hiding (routes)
import Controllers.User (withAuthUser)
import qualified Models.Reply as MR
import qualified Models.Topic as MT
import qualified Models.User as MU
import Models.Utils
import Views.ReplyForm
import Views.ReplySplices
import Views.Utils
------------------------------------------------------------------------------
routes :: [(BS.ByteString, Handler App App ())]
routes = [ ("/topic/:topicid/reply", replyToTopicH)
, ("/topic/:topicid/:replyid/reply", replyToReplyH)
, ("/topic/:topicid/:replyid/delete", replyDeleteH)
]
------------------------------------------------------------------------------
topicIdP :: BS.ByteString
topicIdP = "topicid"
replyIdP :: BS.ByteString
replyIdP = "replyid"
------------------------------------------------------------------------------
tplReplyToReplyForm :: BS.ByteString
tplReplyToReplyForm = "reply-to-reply-form"
tplReplyToReplyDetail :: BS.ByteString
tplReplyToReplyDetail = "reply-to-reply-detail"
------------------------------------------------------------------------------
-- | Handler for saving reply to a topic.
--
replyToTopicH :: AppHandler ()
replyToTopicH = withAuthUser $ do
(view, result) <- runReplyForm
case result of
Just reply -> replyVoToReply reply
>>= MR.createReplyToTopic
>> redirectTopicDetailPage (textToS $ replyToTopicId reply)
-- shall be redirect otherwise URL doest change.
Nothing -> toTopicDetailAfterReply view
-- | Two cases go into this branch
-- 1. reply form has errors or
-- 2. GET request via browser, thus shall be same as /topic/:topicid
--
toTopicDetailAfterReply :: View T.Text
-> AppHandler ()
toTopicDetailAfterReply view = do
tid <- decodedParamText topicIdP -- see the route pattern
re <- try (findOneTopic' tid)
renderTopicDetailPage re view
findOneTopic' :: T.Text -> AppHandler MT.Topic
findOneTopic' = MT.findOneTopic . read . textToS
------------------------------------------------------------------------------
-- | Handler for reply to a reply.
--
replyToReplyH :: AppHandler ()
replyToReplyH = withAuthUser $ do
tid <- decodedParamText topicIdP
rid <- decodedParamText replyIdP
(view, result) <- runReplyToRelpyForm
case result of
Just req -> do
reply <- MR.createReplyToTopic =<< replyVoToReply req
heistLocal (I.bindSplice "replyToReply" $ replyToReplySplice reply) $ render tplReplyToReplyDetail
Nothing -> renderDfPageSplices tplReplyToReplyForm view
$ I.bindSplices
$ foldSplices [ ("topicid", I.textSplice tid)
, ("replyid", I.textSplice rid) ]
------------------------------------------------------------------------------
-- | Handler for delete a reply
--
replyDeleteH :: AppHandler ()
replyDeleteH = withAuthUser $ do
tid <- decodedParam topicIdP
maybeRid <- decodedParamTextMaybe replyIdP
case maybeRid of
Nothing -> redirectTopicDetailPage (bsToS tid)
Just rid -> MR.deleteReply (textToObjectId rid)
>> redirectTopicDetailPage (bsToS tid)
------------------------------------------------------------------------------
--
replyVoToReply :: ReplyVo -> AppHandler MR.Reply
replyVoToReply vo = do
now <- liftIO getCurrentTime
(Just uid') <- MU.findCurrentUserId
return $ MR.Reply Nothing
(textToObjectId $ replyToTopicId vo)
(trReplyId' $ replyToReplyId vo)
(replyContent vo)
uid' now
where trReplyId' "" = Nothing
trReplyId' xs = Just $ textToObjectId xs
| HaskellCNOrg/snap-web | src/Controllers/Reply.hs | bsd-3-clause | 4,502 | 0 | 18 | 1,213 | 821 | 440 | 381 | 83 | 2 |
module Hint.All(
Hint(..), ModuHint,
resolveHints, hintRules, builtinHints
) where
import Data.Monoid
import Config.Type
import Data.Either
import Data.List.Extra
import Hint.Type
import Timing
import Util
import Prelude
import Hint.Match
import Hint.List
import Hint.ListRec
import Hint.Monad
import Hint.Lambda
import Hint.Bracket
import Hint.Fixities
import Hint.Naming
import Hint.Pattern
import Hint.Import
import Hint.Export
import Hint.Pragma
import Hint.Restrict
import Hint.Extensions
import Hint.Duplicate
import Hint.Comment
import Hint.Unsafe
import Hint.NewType
import Hint.Smell
import Hint.NumLiteral
-- | A list of the builtin hints wired into HLint.
-- This list is likely to grow over time.
data HintBuiltin =
HintList | HintListRec | HintMonad | HintLambda | HintFixities |
HintBracket | HintNaming | HintPattern | HintImport | HintExport |
HintPragma | HintExtensions | HintUnsafe | HintDuplicate | HintRestrict |
HintComment | HintNewType | HintSmell | HintNumLiteral
deriving (Show,Eq,Ord,Bounded,Enum)
-- See https://github.com/ndmitchell/hlint/issues/1150 - Duplicate is too slow
-- and doesn't provide much value anyway.
issue1150 = True
builtin :: HintBuiltin -> Hint
builtin x = case x of
HintLambda -> decl lambdaHint
HintImport -> modu importHint
HintExport -> modu exportHint
HintComment -> modu commentHint
HintPragma -> modu pragmaHint
HintDuplicate -> if issue1150 then mempty else mods duplicateHint
HintRestrict -> mempty{hintModule=restrictHint}
HintList -> decl listHint
HintNewType -> decl newtypeHint
HintUnsafe -> decl unsafeHint
HintListRec -> decl listRecHint
HintNaming -> decl namingHint
HintBracket -> decl bracketHint
HintFixities -> mempty{hintDecl=fixitiesHint}
HintSmell -> mempty{hintDecl=smellHint,hintModule=smellModuleHint}
HintPattern -> decl patternHint
HintMonad -> decl monadHint
HintExtensions -> modu extensionsHint
HintNumLiteral -> decl numLiteralHint
where
wrap = timed "Hint" (drop 4 $ show x) . forceList
decl f = mempty{hintDecl=const $ \a b c -> wrap $ f a b c}
modu f = mempty{hintModule=const $ \a b -> wrap $ f a b}
mods f = mempty{hintModules=const $ \a -> wrap $ f a}
-- | A list of builtin hints, currently including entries such as @\"List\"@ and @\"Bracket\"@.
builtinHints :: [(String, Hint)]
builtinHints = [(drop 4 $ show h, builtin h) | h <- enumerate]
-- | Transform a list of 'HintBuiltin' or 'HintRule' into a 'Hint'.
resolveHints :: [Either HintBuiltin HintRule] -> Hint
resolveHints xs =
mconcat $ mempty{hintDecl=const $ readMatch rights} : map builtin (nubOrd lefts)
where (lefts,rights) = partitionEithers xs
-- | Transform a list of 'HintRule' into a 'Hint'.
hintRules :: [HintRule] -> Hint
hintRules = resolveHints . map Right
| ndmitchell/hlint | src/Hint/All.hs | bsd-3-clause | 2,934 | 0 | 12 | 595 | 765 | 420 | 345 | 71 | 20 |
{-# LANGUAGE InstanceSigs #-}
module Main where
import Control.Concurrent
import Game
import Rendering
import System.Console.ANSI
import System.Random
class GameAi ai where
run :: ai -> GameBoard -> (MovementDirection, ai)
data MoveUpAi = MoveUpAi
instance GameAi MoveUpAi where
run MoveUpAi _ = (MovementUp, MoveUpAi)
data MoveRandomAi = MoveRandomAi
{ randomGenerator :: StdGen
}
moveFromIndex :: Int -> MovementDirection
moveFromIndex 0 = MovementUp
moveFromIndex 1 = MovementLeft
moveFromIndex 2 = MovementRight
moveFromIndex 3 = MovementDown
generateRandomMove :: (RandomGen g) => g -> (MovementDirection, g)
generateRandomMove randGen = (moveFromIndex index, randGen2)
where
(index, randGen2) = randomR (0, 3) randGen
instance GameAi MoveRandomAi where
run ai _ = (move, MoveRandomAi { randomGenerator = randomGenerator2 })
where
(move, randomGenerator2) = generateRandomMove (randomGenerator ai)
data MoveClockwiseAi = MoveClockwiseAi
{ lastMove :: MovementDirection
}
generateNextClockwiseMove move
| move == MovementUp = MovementRight
| move == MovementRight = MovementDown
| move == MovementDown = MovementLeft
| otherwise = MovementUp
instance GameAi MoveClockwiseAi where
run ai _ = (move, MoveClockwiseAi { lastMove = move })
where
move = generateNextClockwiseMove (lastMove ai)
updateBlockedMovements movementsMade True = 0
updateBlockedMovements movementsMade False = movementsMade + 1
runAi :: (RandomGen g, GameAi ai) => (GameBoard, Integer, Integer, Bool, g, ai) -> IO ()
runAi (board, _, score, True, _, _) = do
clearScreen
putStr "\n"
putStr $ printBoard board
putStrLn $ "No more moves!"
putStrLn $ "Your score is: " ++ (show score)
runAi (board, blockedMovements, score, gameFinished, g, gameAi)
| blockedMovements > 10 = do
clearScreen
putStr "\n"
putStr $ printBoard board
putStrLn $ "Your AI is blocked for more than 10 moves!"
putStrLn $ "Your score is: " ++ (show score)
| otherwise = do
clearScreen
putStr "\n"
putStr $ printBoard board
putStrLn $ "Score: " ++ (show score)
threadDelay 500000
runAi (updatedBoard, updatedBlockedMovements, updatedScore, gameFinished, g2, newAi)
where
(aiMove, newAi) = run gameAi board
(updatedBoard, movementMade, updatedScore, gameFinished, g2) = updateBoard g board aiMove score
updatedBlockedMovements = updateBlockedMovements blockedMovements movementMade
initGameWithAi :: (RandomGen g, GameAi ai) => (GameBoard, Bool, Integer, Bool, g) -> ai -> (GameBoard, Integer, Integer, Bool, g, ai)
initGameWithAi (board, _, score, gameFinished, randGen) gameAi
= (board, 0, score, gameFinished, randGen, gameAi)
main :: IO ()
main = do
stdGen1 <- newStdGen
stdGen2 <- newStdGen
--runAi $ initGameWithAi (initGame stdGen1) (MoveRandomAi { randomGenerator = stdGen2 })
runAi $ initGameWithAi (initGame stdGen1) (MoveClockwiseAi { lastMove = MovementUp })
| anuraags/hs2048 | ai/Main.hs | bsd-3-clause | 3,056 | 0 | 11 | 635 | 895 | 478 | 417 | 69 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE StandaloneDeriving #-}
module GMessages.Network.ClientServer (
ConnectionMessage(..),
PingMessage(..),
WorldMessage(..),
ServiceMessage(..),
Message(..)
) where
import Data.Serialize (Serialize, get, put, Get, Putter)
import GHC.Generics (Generic)
import qualified Linear as L
import Graphics.Rendering.OpenGL (GLfloat)
import Data.Time.Clock (UTCTime(..), DiffTime(..))
import Data.Time.Calendar (Day(..))
import GCommon.Types.Generic (PlayerSettings, PlayerSettingsReset, ClientKey)
data ConnectionMessage = ConnectionRequest PlayerSettings
| ConnectionTerminated
deriving (Show, Eq, Generic)
data PingMessage = PingRequest UTCTime
deriving (Show, Eq, Generic)
data WorldMessage = PositionUpdate (L.V2 GLfloat, GLfloat)
| SettingsUpdate PlayerSettings
| SettingsReset PlayerSettingsReset
| Fire
deriving (Show, Eq, Generic)
data ServiceMessage = PingMessage PingMessage
| ConnectionMessage ConnectionMessage
deriving (Show, Eq, Generic)
data Message = WorldMessage ClientKey WorldMessage
| ServiceMessage ClientKey ServiceMessage
deriving (Show, Eq, Generic)
deriving instance Generic UTCTime
deriving instance Generic Day
instance Serialize DiffTime where
get = realToFrac <$> (get :: Get Double)
put = (put :: Putter Double) . realToFrac
instance Serialize Day
instance Serialize UTCTime
instance Serialize ConnectionMessage
instance Serialize PingMessage
instance Serialize WorldMessage
instance Serialize ServiceMessage
instance Serialize Message
| cernat-catalin/haskellGame | src/GMessages/Network/ClientServer.hs | bsd-3-clause | 1,726 | 0 | 9 | 391 | 419 | 243 | 176 | 43 | 0 |
module Main where
import Control.Monad
import System.Environment
import System.Cmd
import System.Exit
import System.Directory
import L1.ParL
import L1.ErrM
import L1Tox64.Compile
import Paths_schemeCompiler
main :: IO ()
main = do
args <- getArgs
when (length args /= 1) $ do
putStrLn "usage: filename"
exitFailure
runtimeOPath <- getDataFileName "data/runtime.o"
contents <- readFile (head args)
let ts = myLexer contents
case pProgram ts of
Bad s -> do putStrLn "\nParse Failed...\n"
putStrLn "Tokens:"
print ts
putStrLn s
Ok tree -> do writeFile "prog.S" (assembleProgram tree)
rawSystem "as" ["--64", "-o", "prog.o", "prog.S"] >>= throwIfError
rawSystem "gcc" ["-m64", "-o", "a.out", "prog.o", runtimeOPath] >>= throwIfError
throwIfError :: ExitCode -> IO ()
throwIfError ExitSuccess = return ()
throwIfError e@ExitFailure{} = void (exitWith e)
| mhuesch/scheme_compiler | src/L1Tox64/Main.hs | bsd-3-clause | 1,023 | 0 | 14 | 289 | 304 | 147 | 157 | 30 | 2 |
{-
A common practice in many Haskell applications is to define a
helper module for each project that provides commonly needed
imports. The purpose of this module is purely convenience.
-}
module Import
( module Import
, module X
) where
import Data.Default
import Foundation as X
import Language.Haskell.TH
import Yesod as X
import Yesod.Default.Util
import Yesod.Form.Jquery as X (urlJqueryJs)
widgetFile :: FilePath -> ExpQ
widgetFile = widgetFileReload def
{- my experiments
getDomeR :: Handler Html
-- defaultLayout uses the application's standard page layout to display
-- some contents. In our application, we're just using the standard
-- layout, which includes a basic HTML 5 page outline.
getDomeR = defaultLayout $ do
setTitle "Yesod Web Service Homepage"
data MyApp = MyApp
instance Yesod MyApp
mkYesodData "MyApp" [parseRoutes|
/ DomeR GET
|]
-- bubb = warpEnv
-- main :: IO ()
-- main = warpEnv App
-}
| fdilke/fpc-exp | src/Import.hs | bsd-3-clause | 1,040 | 0 | 5 | 271 | 73 | 49 | 24 | 11 | 1 |
{-# LANGUAGE Rank2Types #-}
module Opaleye.Internal.PackMap where
import Control.Applicative (Applicative, pure, (<*>), liftA2)
import qualified Control.Monad.Trans.State as S
import Data.Profunctor (Profunctor, dimap)
import Data.Profunctor.Product (ProductProfunctor, empty, (***!))
import qualified Data.Profunctor.Product as PP
import qualified Data.Functor.Identity as I
-- This is rather like a Control.Lens.Traversal with the type
-- parameters switched but I'm not sure if it should be required to
-- obey the same laws.
data PackMap a b s t = PackMap (Applicative f =>
(a -> f b) -> s -> f t)
packmap :: Applicative f => PackMap a b s t -> (a -> f b) -> s -> f t
packmap (PackMap f) = f
over :: PackMap a b s t -> (a -> b) -> s -> t
over p f = I.runIdentity . packmap p (I.Identity . f)
type PM a = S.State (a, Int)
new :: PM a String
new = do
(a, i) <- S.get
S.put (a, i + 1)
return (show i)
write :: a -> PM [a] ()
write a = do
(as, i) <- S.get
S.put (as ++ [a], i)
run :: PM [a] r -> (r, [a])
run m = (r, as)
where (r, (as, _)) = S.runState m ([], 0)
-- {
-- Boilerplate instance definitions. There's no choice here apart
-- from the order in which the applicative is applied.
instance Functor (PackMap a b s) where
fmap f (PackMap g) = PackMap ((fmap . fmap . fmap) f g)
instance Applicative (PackMap a b s) where
pure x = PackMap (pure (pure (pure x)))
PackMap f <*> PackMap x = PackMap ((liftA2 (liftA2 (<*>))) f x)
instance Profunctor (PackMap a b) where
dimap f g (PackMap q) = PackMap (fmap (dimap f (fmap g)) q)
instance ProductProfunctor (PackMap a b) where
empty = PP.defaultEmpty
(***!) = PP.defaultProfunctorProduct
-- }
| k0001/haskell-opaleye | Opaleye/Internal/PackMap.hs | bsd-3-clause | 1,748 | 0 | 12 | 410 | 715 | 390 | 325 | 37 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.PreProcess
-- Copyright : (c) 2003-2005, Isaac Jones, Malcolm Wallace
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This defines a 'PreProcessor' abstraction which represents a pre-processor
-- that can transform one kind of file into another. There is also a
-- 'PPSuffixHandler' which is a combination of a file extension and a function
-- for configuring a 'PreProcessor'. It defines a bunch of known built-in
-- preprocessors like @cpp@, @cpphs@, @c2hs@, @hsc2hs@, @happy@, @alex@ etc and
-- lists them in 'knownSuffixHandlers'. On top of this it provides a function
-- for actually preprocessing some sources given a bunch of known suffix
-- handlers. This module is not as good as it could be, it could really do with
-- a rewrite to address some of the problems we have with pre-processors.
module Distribution.Simple.PreProcess (preprocessComponent, preprocessExtras,
knownSuffixHandlers, ppSuffixes,
PPSuffixHandler, PreProcessor(..),
mkSimplePreProcessor, runSimplePreProcessor,
ppCpp, ppCpp', ppGreenCard, ppC2hs, ppHsc2hs,
ppHappy, ppAlex, ppUnlit, platformDefines
)
where
import Control.Monad
import Distribution.Simple.PreProcess.Unlit (unlit)
import Distribution.Package
( Package(..), PackageName(..) )
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..)
, Executable(..)
, Library(..), libModules
, TestSuite(..), testModules
, TestSuiteInterface(..)
, Benchmark(..), benchmarkModules, BenchmarkInterface(..) )
import qualified Distribution.InstalledPackageInfo as Installed
( InstalledPackageInfo(..) )
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.CCompiler
( cSourceExtensions )
import Distribution.Simple.Compiler
( CompilerFlavor(..)
, compilerFlavor, compilerCompatVersion, compilerVersion )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), Component(..) )
import Distribution.Simple.BuildPaths (autogenModulesDir,cppHeaderName)
import Distribution.Simple.Utils
( createDirectoryIfMissingVerbose, withUTF8FileContents, writeUTF8File
, die, setupMessage, intercalate, copyFileVerbose, moreRecentFile
, findFileWithExtension, findFileWithExtension'
, getDirectoryContentsRecursive )
import Distribution.Simple.Program
( Program(..), ConfiguredProgram(..), programPath
, requireProgram, requireProgramVersion
, rawSystemProgramConf, rawSystemProgram
, greencardProgram, cpphsProgram, hsc2hsProgram, c2hsProgram
, happyProgram, alexProgram, ghcProgram, ghcjsProgram, gccProgram )
import Distribution.Simple.Test.LibV09
( writeSimpleTestStub, stubFilePath, stubName )
import Distribution.System
( OS(..), buildOS, Arch(..), Platform(..) )
import Distribution.Text
import Distribution.Version
( Version(..), anyVersion, orLaterVersion )
import Distribution.Verbosity
import Data.Maybe (fromMaybe)
import Data.List (nub, isSuffixOf)
import System.Directory (doesFileExist)
import System.Info (os, arch)
import System.FilePath (splitExtension, dropExtensions, (</>), (<.>),
takeDirectory, normalise, replaceExtension,
takeExtensions)
-- |The interface to a preprocessor, which may be implemented using an
-- external program, but need not be. The arguments are the name of
-- the input file, the name of the output file and a verbosity level.
-- Here is a simple example that merely prepends a comment to the given
-- source file:
--
-- > ppTestHandler :: PreProcessor
-- > ppTestHandler =
-- > PreProcessor {
-- > platformIndependent = True,
-- > runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity ->
-- > do info verbosity (inFile++" has been preprocessed to "++outFile)
-- > stuff <- readFile inFile
-- > writeFile outFile ("-- preprocessed as a test\n\n" ++ stuff)
-- > return ExitSuccess
--
-- We split the input and output file names into a base directory and the
-- rest of the file name. The input base dir is the path in the list of search
-- dirs that this file was found in. The output base dir is the build dir where
-- all the generated source files are put.
--
-- The reason for splitting it up this way is that some pre-processors don't
-- simply generate one output .hs file from one input file but have
-- dependencies on other generated files (notably c2hs, where building one
-- .hs file may require reading other .chi files, and then compiling the .hs
-- file may require reading a generated .h file). In these cases the generated
-- files need to embed relative path names to each other (eg the generated .hs
-- file mentions the .h file in the FFI imports). This path must be relative to
-- the base directory where the generated files are located, it cannot be
-- relative to the top level of the build tree because the compilers do not
-- look for .h files relative to there, ie we do not use \"-I .\", instead we
-- use \"-I dist\/build\" (or whatever dist dir has been set by the user)
--
-- Most pre-processors do not care of course, so mkSimplePreProcessor and
-- runSimplePreProcessor functions handle the simple case.
--
data PreProcessor = PreProcessor {
-- Is the output of the pre-processor platform independent? eg happy output
-- is portable haskell but c2hs's output is platform dependent.
-- This matters since only platform independent generated code can be
-- inlcuded into a source tarball.
platformIndependent :: Bool,
-- TODO: deal with pre-processors that have implementaion dependent output
-- eg alex and happy have --ghc flags. However we can't really inlcude
-- ghc-specific code into supposedly portable source tarballs.
runPreProcessor :: (FilePath, FilePath) -- Location of the source file relative to a base dir
-> (FilePath, FilePath) -- Output file name, relative to an output base dir
-> Verbosity -- verbosity
-> IO () -- Should exit if the preprocessor fails
}
-- | Function to determine paths to possible extra C sources for a
-- preprocessor: just takes the path to the build directory and uses
-- this to search for C sources with names that match the
-- preprocessor's output name format.
type PreProcessorExtras = FilePath -> IO [FilePath]
mkSimplePreProcessor :: (FilePath -> FilePath -> Verbosity -> IO ())
-> (FilePath, FilePath)
-> (FilePath, FilePath) -> Verbosity -> IO ()
mkSimplePreProcessor simplePP
(inBaseDir, inRelativeFile)
(outBaseDir, outRelativeFile) verbosity = simplePP inFile outFile verbosity
where inFile = normalise (inBaseDir </> inRelativeFile)
outFile = normalise (outBaseDir </> outRelativeFile)
runSimplePreProcessor :: PreProcessor -> FilePath -> FilePath -> Verbosity
-> IO ()
runSimplePreProcessor pp inFile outFile verbosity =
runPreProcessor pp (".", inFile) (".", outFile) verbosity
-- |A preprocessor for turning non-Haskell files with the given extension
-- into plain Haskell source files.
type PPSuffixHandler
= (String, BuildInfo -> LocalBuildInfo -> PreProcessor)
-- | Apply preprocessors to the sources from 'hsSourceDirs' for a given
-- component (lib, exe, or test suite).
preprocessComponent :: PackageDescription
-> Component
-> LocalBuildInfo
-> Bool
-> Verbosity
-> [PPSuffixHandler]
-> IO ()
preprocessComponent pd comp lbi isSrcDist verbosity handlers = case comp of
(CLib lib@Library{ libBuildInfo = bi }) -> do
let dirs = hsSourceDirs bi ++ [autogenModulesDir lbi]
setupMessage verbosity "Preprocessing library" (packageId pd)
forM_ (map ModuleName.toFilePath $ libModules lib) $
pre dirs (buildDir lbi) (localHandlers bi)
(CExe exe@Executable { buildInfo = bi, exeName = nm }) -> do
let exeDir = buildDir lbi </> nm </> nm ++ "-tmp"
dirs = hsSourceDirs bi ++ [autogenModulesDir lbi]
setupMessage verbosity ("Preprocessing executable '" ++ nm ++ "' for") (packageId pd)
forM_ (map ModuleName.toFilePath $ otherModules bi) $
pre dirs exeDir (localHandlers bi)
pre (hsSourceDirs bi) exeDir (localHandlers bi) $
dropExtensions (modulePath exe)
CTest test@TestSuite{ testName = nm } -> do
setupMessage verbosity ("Preprocessing test suite '" ++ nm ++ "' for") (packageId pd)
case testInterface test of
TestSuiteExeV10 _ f ->
preProcessTest test f $ buildDir lbi </> testName test
</> testName test ++ "-tmp"
TestSuiteLibV09 _ _ -> do
let testDir = buildDir lbi </> stubName test
</> stubName test ++ "-tmp"
writeSimpleTestStub test testDir
preProcessTest test (stubFilePath test) testDir
TestSuiteUnsupported tt -> die $ "No support for preprocessing test "
++ "suite type " ++ display tt
CBench bm@Benchmark{ benchmarkName = nm } -> do
setupMessage verbosity ("Preprocessing benchmark '" ++ nm ++ "' for") (packageId pd)
case benchmarkInterface bm of
BenchmarkExeV10 _ f ->
preProcessBench bm f $ buildDir lbi </> benchmarkName bm
</> benchmarkName bm ++ "-tmp"
BenchmarkUnsupported tt -> die $ "No support for preprocessing benchmark "
++ "type " ++ display tt
where
builtinHaskellSuffixes = ["hs", "lhs", "hsig", "lhsig"]
builtinCSuffixes = cSourceExtensions
builtinSuffixes = builtinHaskellSuffixes ++ builtinCSuffixes
localHandlers bi = [(ext, h bi lbi) | (ext, h) <- handlers]
pre dirs dir lhndlrs fp =
preprocessFile dirs dir isSrcDist fp verbosity builtinSuffixes lhndlrs
preProcessTest test = preProcessComponent (testBuildInfo test)
(testModules test)
preProcessBench bm = preProcessComponent (benchmarkBuildInfo bm)
(benchmarkModules bm)
preProcessComponent bi modules exePath dir = do
let biHandlers = localHandlers bi
sourceDirs = hsSourceDirs bi ++ [ autogenModulesDir lbi ]
sequence_ [ preprocessFile sourceDirs dir isSrcDist
(ModuleName.toFilePath modu) verbosity builtinSuffixes
biHandlers
| modu <- modules ]
preprocessFile (dir : (hsSourceDirs bi)) dir isSrcDist
(dropExtensions $ exePath) verbosity
builtinSuffixes biHandlers
--TODO: try to list all the modules that could not be found
-- not just the first one. It's annoying and slow due to the need
-- to reconfigure after editing the .cabal file each time.
-- |Find the first extension of the file that exists, and preprocess it
-- if required.
preprocessFile
:: [FilePath] -- ^source directories
-> FilePath -- ^build directory
-> Bool -- ^preprocess for sdist
-> FilePath -- ^module file name
-> Verbosity -- ^verbosity
-> [String] -- ^builtin suffixes
-> [(String, PreProcessor)] -- ^possible preprocessors
-> IO ()
preprocessFile searchLoc buildLoc forSDist baseFile verbosity builtinSuffixes handlers = do
-- look for files in the various source dirs with this module name
-- and a file extension of a known preprocessor
psrcFiles <- findFileWithExtension' (map fst handlers) searchLoc baseFile
case psrcFiles of
-- no preprocessor file exists, look for an ordinary source file
-- just to make sure one actually exists at all for this module.
-- Note: by looking in the target/output build dir too, we allow
-- source files to appear magically in the target build dir without
-- any corresponding "real" source file. This lets custom Setup.hs
-- files generate source modules directly into the build dir without
-- the rest of the build system being aware of it (somewhat dodgy)
Nothing -> do
bsrcFiles <- findFileWithExtension builtinSuffixes (buildLoc : searchLoc) baseFile
case bsrcFiles of
Nothing -> die $ "can't find source for " ++ baseFile
++ " in " ++ intercalate ", " searchLoc
_ -> return ()
-- found a pre-processable file in one of the source dirs
Just (psrcLoc, psrcRelFile) -> do
let (srcStem, ext) = splitExtension psrcRelFile
psrcFile = psrcLoc </> psrcRelFile
pp = fromMaybe (error "Distribution.Simple.PreProcess: Just expected")
(lookup (tailNotNull ext) handlers)
-- Preprocessing files for 'sdist' is different from preprocessing
-- for 'build'. When preprocessing for sdist we preprocess to
-- avoid that the user has to have the preprocessors available.
-- ATM, we don't have a way to specify which files are to be
-- preprocessed and which not, so for sdist we only process
-- platform independent files and put them into the 'buildLoc'
-- (which we assume is set to the temp. directory that will become
-- the tarball).
--TODO: eliminate sdist variant, just supply different handlers
when (not forSDist || forSDist && platformIndependent pp) $ do
-- look for existing pre-processed source file in the dest dir to
-- see if we really have to re-run the preprocessor.
ppsrcFiles <- findFileWithExtension builtinSuffixes [buildLoc] baseFile
recomp <- case ppsrcFiles of
Nothing -> return True
Just ppsrcFile ->
psrcFile `moreRecentFile` ppsrcFile
when recomp $ do
let destDir = buildLoc </> dirName srcStem
createDirectoryIfMissingVerbose verbosity True destDir
runPreProcessorWithHsBootHack pp
(psrcLoc, psrcRelFile)
(buildLoc, srcStem <.> "hs")
where
dirName = takeDirectory
tailNotNull [] = []
tailNotNull x = tail x
-- FIXME: This is a somewhat nasty hack. GHC requires that hs-boot files
-- be in the same place as the hs files, so if we put the hs file in dist/
-- then we need to copy the hs-boot file there too. This should probably be
-- done another way. Possibly we should also be looking for .lhs-boot
-- files, but I think that preprocessors only produce .hs files.
runPreProcessorWithHsBootHack pp
(inBaseDir, inRelativeFile)
(outBaseDir, outRelativeFile) = do
runPreProcessor pp
(inBaseDir, inRelativeFile)
(outBaseDir, outRelativeFile) verbosity
exists <- doesFileExist inBoot
when exists $ copyFileVerbose verbosity inBoot outBoot
where
inBoot = replaceExtension inFile "hs-boot"
outBoot = replaceExtension outFile "hs-boot"
inFile = normalise (inBaseDir </> inRelativeFile)
outFile = normalise (outBaseDir </> outRelativeFile)
-- ------------------------------------------------------------
-- * known preprocessors
-- ------------------------------------------------------------
ppGreenCard :: BuildInfo -> LocalBuildInfo -> PreProcessor
ppGreenCard _ lbi
= PreProcessor {
platformIndependent = False,
runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity ->
rawSystemProgramConf verbosity greencardProgram (withPrograms lbi)
(["-tffi", "-o" ++ outFile, inFile])
}
-- This one is useful for preprocessors that can't handle literate source.
-- We also need a way to chain preprocessors.
ppUnlit :: PreProcessor
ppUnlit =
PreProcessor {
platformIndependent = True,
runPreProcessor = mkSimplePreProcessor $ \inFile outFile _verbosity ->
withUTF8FileContents inFile $ \contents ->
either (writeUTF8File outFile) die (unlit inFile contents)
}
ppCpp :: BuildInfo -> LocalBuildInfo -> PreProcessor
ppCpp = ppCpp' []
ppCpp' :: [String] -> BuildInfo -> LocalBuildInfo -> PreProcessor
ppCpp' extraArgs bi lbi =
case compilerFlavor (compiler lbi) of
GHC -> ppGhcCpp ghcProgram (>= Version [6,6] []) args bi lbi
GHCJS -> ppGhcCpp ghcjsProgram (const True) args bi lbi
_ -> ppCpphs args bi lbi
where cppArgs = getCppOptions bi lbi
args = cppArgs ++ extraArgs
ppGhcCpp :: Program -> (Version -> Bool)
-> [String] -> BuildInfo -> LocalBuildInfo -> PreProcessor
ppGhcCpp program xHs extraArgs _bi lbi =
PreProcessor {
platformIndependent = False,
runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity -> do
(prog, version, _) <- requireProgramVersion verbosity
program anyVersion (withPrograms lbi)
rawSystemProgram verbosity prog $
["-E", "-cpp"]
-- This is a bit of an ugly hack. We're going to
-- unlit the file ourselves later on if appropriate,
-- so we need GHC not to unlit it now or it'll get
-- double-unlitted. In the future we might switch to
-- using cpphs --unlit instead.
++ (if xHs version then ["-x", "hs"] else [])
++ [ "-optP-include", "-optP"++ (autogenModulesDir lbi </> cppHeaderName) ]
++ ["-o", outFile, inFile]
++ extraArgs
}
ppCpphs :: [String] -> BuildInfo -> LocalBuildInfo -> PreProcessor
ppCpphs extraArgs _bi lbi =
PreProcessor {
platformIndependent = False,
runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity -> do
(cpphsProg, cpphsVersion, _) <- requireProgramVersion verbosity
cpphsProgram anyVersion (withPrograms lbi)
rawSystemProgram verbosity cpphsProg $
("-O" ++ outFile) : inFile
: "--noline" : "--strip"
: (if cpphsVersion >= Version [1,6] []
then ["--include="++ (autogenModulesDir lbi </> cppHeaderName)]
else [])
++ extraArgs
}
ppHsc2hs :: BuildInfo -> LocalBuildInfo -> PreProcessor
ppHsc2hs bi lbi =
PreProcessor {
platformIndependent = False,
runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity -> do
(gccProg, _) <- requireProgram verbosity gccProgram (withPrograms lbi)
rawSystemProgramConf verbosity hsc2hsProgram (withPrograms lbi) $
[ "--cc=" ++ programPath gccProg
, "--ld=" ++ programPath gccProg ]
-- Additional gcc options
++ [ "--cflag=" ++ opt | opt <- programDefaultArgs gccProg
++ programOverrideArgs gccProg ]
++ [ "--lflag=" ++ opt | opt <- programDefaultArgs gccProg
++ programOverrideArgs gccProg ]
-- OSX frameworks:
++ [ what ++ "=-F" ++ opt
| isOSX
, opt <- nub (concatMap Installed.frameworkDirs pkgs)
, what <- ["--cflag", "--lflag"] ]
++ [ "--lflag=" ++ arg
| isOSX
, opt <- PD.frameworks bi ++ concatMap Installed.frameworks pkgs
, arg <- ["-framework", opt] ]
-- Note that on ELF systems, wherever we use -L, we must also use -R
-- because presumably that -L dir is not on the normal path for the
-- system's dynamic linker. This is needed because hsc2hs works by
-- compiling a C program and then running it.
++ [ "--cflag=" ++ opt | opt <- platformDefines lbi ]
-- Options from the current package:
++ [ "--cflag=-I" ++ dir | dir <- PD.includeDirs bi ]
++ [ "--cflag=" ++ opt | opt <- PD.ccOptions bi
++ PD.cppOptions bi ]
++ [ "--cflag=" ++ opt | opt <-
[ "-I" ++ autogenModulesDir lbi,
"-include", autogenModulesDir lbi </> cppHeaderName ] ]
++ [ "--lflag=-L" ++ opt | opt <- PD.extraLibDirs bi ]
++ [ "--lflag=-Wl,-R," ++ opt | isELF
, opt <- PD.extraLibDirs bi ]
++ [ "--lflag=-l" ++ opt | opt <- PD.extraLibs bi ]
++ [ "--lflag=" ++ opt | opt <- PD.ldOptions bi ]
-- Options from dependent packages
++ [ "--cflag=" ++ opt
| pkg <- pkgs
, opt <- [ "-I" ++ opt | opt <- Installed.includeDirs pkg ]
++ [ opt | opt <- Installed.ccOptions pkg ] ]
++ [ "--lflag=" ++ opt
| pkg <- pkgs
, opt <- [ "-L" ++ opt | opt <- Installed.libraryDirs pkg ]
++ [ "-Wl,-R," ++ opt | isELF
, opt <- Installed.libraryDirs pkg ]
++ [ "-l" ++ opt | opt <- Installed.extraLibraries pkg ]
++ [ opt | opt <- Installed.ldOptions pkg ] ]
++ ["-o", outFile, inFile]
}
where
pkgs = PackageIndex.topologicalOrder (packageHacks (installedPkgs lbi))
isOSX = case buildOS of OSX -> True; _ -> False
isELF = case buildOS of OSX -> False; Windows -> False; AIX -> False; _ -> True;
packageHacks = case compilerFlavor (compiler lbi) of
GHC -> hackRtsPackage
GHCJS -> hackRtsPackage
_ -> id
-- We don't link in the actual Haskell libraries of our dependencies, so
-- the -u flags in the ldOptions of the rts package mean linking fails on
-- OS X (it's ld is a tad stricter than gnu ld). Thus we remove the
-- ldOptions for GHC's rts package:
hackRtsPackage index =
case PackageIndex.lookupPackageName index (PackageName "rts") of
[(_, [rts])]
-> PackageIndex.insert rts { Installed.ldOptions = [] } index
_ -> error "No (or multiple) ghc rts package is registered!!"
ppHsc2hsExtras :: PreProcessorExtras
ppHsc2hsExtras buildBaseDir = filter ("_hsc.c" `isSuffixOf`) `fmap`
getDirectoryContentsRecursive buildBaseDir
ppC2hs :: BuildInfo -> LocalBuildInfo -> PreProcessor
ppC2hs bi lbi =
PreProcessor {
platformIndependent = False,
runPreProcessor = \(inBaseDir, inRelativeFile)
(outBaseDir, outRelativeFile) verbosity -> do
(c2hsProg, _, _) <- requireProgramVersion verbosity
c2hsProgram (orLaterVersion (Version [0,15] []))
(withPrograms lbi)
(gccProg, _) <- requireProgram verbosity gccProgram (withPrograms lbi)
rawSystemProgram verbosity c2hsProg $
-- Options from the current package:
[ "--cpp=" ++ programPath gccProg, "--cppopts=-E" ]
++ [ "--cppopts=" ++ opt | opt <- getCppOptions bi lbi ]
++ [ "--cppopts=-include" ++ (autogenModulesDir lbi </> cppHeaderName) ]
++ [ "--include=" ++ outBaseDir ]
-- Options from dependent packages
++ [ "--cppopts=" ++ opt
| pkg <- pkgs
, opt <- [ "-I" ++ opt | opt <- Installed.includeDirs pkg ]
++ [ opt | opt@('-':c:_) <- Installed.ccOptions pkg
, c `elem` "DIU" ] ]
--TODO: install .chi files for packages, so we can --include
-- those dirs here, for the dependencies
-- input and output files
++ [ "--output-dir=" ++ outBaseDir
, "--output=" ++ outRelativeFile
, inBaseDir </> inRelativeFile ]
}
where
pkgs = PackageIndex.topologicalOrder (installedPkgs lbi)
ppC2hsExtras :: PreProcessorExtras
ppC2hsExtras d = filter (\p -> takeExtensions p == ".chs.c") `fmap`
getDirectoryContentsRecursive d
--TODO: perhaps use this with hsc2hs too
--TODO: remove cc-options from cpphs for cabal-version: >= 1.10
getCppOptions :: BuildInfo -> LocalBuildInfo -> [String]
getCppOptions bi lbi
= platformDefines lbi
++ cppOptions bi
++ ["-I" ++ dir | dir <- PD.includeDirs bi]
++ [opt | opt@('-':c:_) <- PD.ccOptions bi, c `elem` "DIU"]
platformDefines :: LocalBuildInfo -> [String]
platformDefines lbi =
case compilerFlavor comp of
GHC ->
["-D__GLASGOW_HASKELL__=" ++ versionInt version] ++
["-D" ++ os ++ "_BUILD_OS=1"] ++
["-D" ++ arch ++ "_BUILD_ARCH=1"] ++
map (\os' -> "-D" ++ os' ++ "_HOST_OS=1") osStr ++
map (\arch' -> "-D" ++ arch' ++ "_HOST_ARCH=1") archStr
GHCJS ->
compatGlasgowHaskell ++
["-D__GHCJS__=" ++ versionInt version] ++
["-D" ++ os ++ "_BUILD_OS=1"] ++
["-D" ++ arch ++ "_BUILD_ARCH=1"] ++
map (\os' -> "-D" ++ os' ++ "_HOST_OS=1") osStr ++
map (\arch' -> "-D" ++ arch' ++ "_HOST_ARCH=1") archStr
JHC -> ["-D__JHC__=" ++ versionInt version]
HaskellSuite {} ->
["-D__HASKELL_SUITE__"] ++
map (\os' -> "-D" ++ os' ++ "_HOST_OS=1") osStr ++
map (\arch' -> "-D" ++ arch' ++ "_HOST_ARCH=1") archStr
_ -> []
where
comp = compiler lbi
Platform hostArch hostOS = hostPlatform lbi
version = compilerVersion comp
compatGlasgowHaskell =
maybe [] (\v -> ["-D__GLASGOW_HASKELL__=" ++ versionInt v])
(compilerCompatVersion GHC comp)
-- TODO: move this into the compiler abstraction
-- FIXME: this forces GHC's crazy 4.8.2 -> 408 convention on all
-- the other compilers. Check if that's really what they want.
versionInt :: Version -> String
versionInt (Version { versionBranch = [] }) = "1"
versionInt (Version { versionBranch = [n] }) = show n
versionInt (Version { versionBranch = n1:n2:_ })
= -- 6.8.x -> 608
-- 6.10.x -> 610
let s1 = show n1
s2 = show n2
middle = case s2 of
_ : _ : _ -> ""
_ -> "0"
in s1 ++ middle ++ s2
osStr = case hostOS of
Linux -> ["linux"]
Windows -> ["mingw32"]
OSX -> ["darwin"]
FreeBSD -> ["freebsd"]
OpenBSD -> ["openbsd"]
NetBSD -> ["netbsd"]
DragonFly -> ["dragonfly"]
Solaris -> ["solaris2"]
AIX -> ["aix"]
HPUX -> ["hpux"]
IRIX -> ["irix"]
HaLVM -> []
IOS -> ["ios"]
Android -> ["android"]
Ghcjs -> ["ghcjs"]
Hurd -> ["hurd"]
OtherOS _ -> []
archStr = case hostArch of
I386 -> ["i386"]
X86_64 -> ["x86_64"]
PPC -> ["powerpc"]
PPC64 -> ["powerpc64"]
Sparc -> ["sparc"]
Arm -> ["arm"]
Mips -> ["mips"]
SH -> []
IA64 -> ["ia64"]
S390 -> ["s390"]
Alpha -> ["alpha"]
Hppa -> ["hppa"]
Rs6000 -> ["rs6000"]
M68k -> ["m68k"]
Vax -> ["vax"]
JavaScript -> ["javascript"]
OtherArch _ -> []
ppHappy :: BuildInfo -> LocalBuildInfo -> PreProcessor
ppHappy _ lbi = pp { platformIndependent = True }
where pp = standardPP lbi happyProgram (hcFlags hc)
hc = compilerFlavor (compiler lbi)
hcFlags GHC = ["-agc"]
hcFlags GHCJS = ["-agc"]
hcFlags _ = []
ppAlex :: BuildInfo -> LocalBuildInfo -> PreProcessor
ppAlex _ lbi = pp { platformIndependent = True }
where pp = standardPP lbi alexProgram (hcFlags hc)
hc = compilerFlavor (compiler lbi)
hcFlags GHC = ["-g"]
hcFlags GHCJS = ["-g"]
hcFlags _ = []
standardPP :: LocalBuildInfo -> Program -> [String] -> PreProcessor
standardPP lbi prog args =
PreProcessor {
platformIndependent = False,
runPreProcessor = mkSimplePreProcessor $ \inFile outFile verbosity ->
rawSystemProgramConf verbosity prog (withPrograms lbi)
(args ++ ["-o", outFile, inFile])
}
-- |Convenience function; get the suffixes of these preprocessors.
ppSuffixes :: [ PPSuffixHandler ] -> [String]
ppSuffixes = map fst
-- |Standard preprocessors: GreenCard, c2hs, hsc2hs, happy, alex and cpphs.
knownSuffixHandlers :: [ PPSuffixHandler ]
knownSuffixHandlers =
[ ("gc", ppGreenCard)
, ("chs", ppC2hs)
, ("hsc", ppHsc2hs)
, ("x", ppAlex)
, ("y", ppHappy)
, ("ly", ppHappy)
, ("cpphs", ppCpp)
]
-- |Standard preprocessors with possible extra C sources: c2hs, hsc2hs.
knownExtrasHandlers :: [ PreProcessorExtras ]
knownExtrasHandlers = [ ppC2hsExtras, ppHsc2hsExtras ]
-- | Find any extra C sources generated by preprocessing that need to
-- be added to the component (addresses issue #238).
preprocessExtras :: Component
-> LocalBuildInfo
-> IO [FilePath]
preprocessExtras comp lbi = case comp of
CLib _ -> pp $ buildDir lbi
(CExe Executable { exeName = nm }) ->
pp $ buildDir lbi </> nm </> nm ++ "-tmp"
CTest test -> do
case testInterface test of
TestSuiteExeV10 _ _ ->
pp $ buildDir lbi </> testName test </> testName test ++ "-tmp"
TestSuiteLibV09 _ _ ->
pp $ buildDir lbi </> stubName test </> stubName test ++ "-tmp"
TestSuiteUnsupported tt -> die $ "No support for preprocessing test "
++ "suite type " ++ display tt
CBench bm -> do
case benchmarkInterface bm of
BenchmarkExeV10 _ _ ->
pp $ buildDir lbi </> benchmarkName bm </> benchmarkName bm ++ "-tmp"
BenchmarkUnsupported tt -> die $ "No support for preprocessing benchmark "
++ "type " ++ display tt
where
pp dir = (map (dir </>) . concat) `fmap` forM knownExtrasHandlers ($ dir)
| trskop/cabal | Cabal/Distribution/Simple/PreProcess.hs | bsd-3-clause | 30,273 | 157 | 27 | 8,618 | 5,666 | 3,153 | 2,513 | 464 | 40 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses #-}
-- | The @waynodes@ element of a OSM file.
module Data.Geo.OSM.Waynodes
(
Waynodes
, waynodes
) where
import Text.XML.HXT.Arrow.Pickle
import Data.Geo.OSM.Lens.MaximumL
import Control.Lens.Lens
import Control.Newtype
-- | The @waynodes@ element of a OSM file.
newtype Waynodes =
Waynodes String
deriving Eq
-- | Constructs a @waynodes@ with maximum.
waynodes ::
String -- ^ The @maximum@ attribute.
-> Waynodes
waynodes =
Waynodes
instance XmlPickler Waynodes where
xpickle =
xpElem "waynodes" (xpWrap (waynodes, \(Waynodes r) -> r) (xpAttr "maximum" xpText))
instance Show Waynodes where
show =
showPickled []
instance MaximumL Waynodes where
maximumL =
lens unpack (const pack)
instance Newtype Waynodes String where
pack =
Waynodes
unpack (Waynodes x) =
x
| tonymorris/geo-osm | src/Data/Geo/OSM/Waynodes.hs | bsd-3-clause | 890 | 0 | 12 | 166 | 195 | 113 | 82 | 31 | 1 |
-- |Includes the ImageSaving class, for types with savable image content, its
-- instances, and monadic helper functions.
module Tea.ImageSaving ( ImageSaving (save)
, saveM
) where
import Control.Monad.Trans
import Graphics.UI.SDL (saveBMP, Surface)
import Tea.Tea
import Tea.Screen
import Tea.Bitmap
-- |A class instantiated over all types that can save their image content to a
-- BMP file
class ImageSaving v where
-- |Save a BMP image of the providing ImageSaving type to the filename
-- specified
save :: v -> String -> Tea s Bool
save v = liftIO . saveBMP (image_saving_buffer v)
image_saving_buffer :: v -> Surface
-- |A monadic convenience function that takes a Tea action instead of a buffer to save.
saveM :: (ImageSaving v) => Tea s v -> String -> Tea s Bool
saveM m s = m >>= flip save s
instance ImageSaving Screen where
image_saving_buffer = screenBuffer
instance ImageSaving Bitmap where
image_saving_buffer = buffer
| liamoc/tea-hs | Tea/ImageSaving.hs | bsd-3-clause | 1,008 | 0 | 10 | 226 | 194 | 108 | 86 | 19 | 1 |
module Database.Algebra.SQL.Materialization.TemporaryTable
( materialize
) where
import Database.Algebra.SQL.Materialization
import Database.Algebra.SQL.Query
import Database.Algebra.SQL.Tile.Flatten
-- | Wrap all dependencies into temporary tables, and put the root tiles into
-- value queries.
materialize :: MatFun
materialize transformResult =
( map tmpTable deps
, map (QValueQuery . VQSelect . fst) selects
)
where
tmpTable (name, (body, _)) =
QDefinitionQuery $ DQTemporaryTable (VQSelect body) name
selects :: [FlatTile String]
deps :: [(String, FlatTile String)]
(selects, deps) =
flattenTransformResult transformResult
| ulricha/algebra-sql | src/Database/Algebra/SQL/Materialization/TemporaryTable.hs | bsd-3-clause | 725 | 0 | 10 | 170 | 158 | 93 | 65 | 15 | 1 |
module Sexy.Instances.Empty.Maybe () where
import Sexy.Data (Maybe)
import Sexy.Classes (Empty(..), Nil(..))
import Sexy.Instances.Nil.Maybe ()
instance Empty Maybe where
empty = nil
| DanBurton/sexy | src/Sexy/Instances/Empty/Maybe.hs | bsd-3-clause | 187 | 0 | 6 | 25 | 65 | 42 | 23 | 6 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
module Lucid.Foundation.Callouts.Panels where
import Lucid.Base
import Lucid.Html5
import qualified Data.Text as T
import Data.Monoid
panel_ :: T.Text
panel_ = " panel "
callout_ :: T.Text
callout_ = " callout "
| athanclark/lucid-foundation | src/Lucid/Foundation/Callouts/Panels.hs | bsd-3-clause | 293 | 0 | 5 | 46 | 57 | 37 | 20 | 11 | 1 |
{-# LANGUAGE DataKinds #-}
-- | Inventory management and party cycling.
-- TODO: document
module Game.LambdaHack.Client.UI.InventoryClient
( Suitability(..)
, getGroupItem, getAnyItems, getStoreItem
, memberCycle, memberBack, pickLeader
, cursorPointerFloor, cursorPointerEnemy
, moveCursorHuman, tgtFloorHuman, tgtEnemyHuman, epsIncrHuman, tgtClearHuman
, doLook, describeItemC
) where
import Control.Applicative
import Control.Exception.Assert.Sugar
import Control.Monad
import Data.Char (intToDigit)
import qualified Data.Char as Char
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Text (Text)
import qualified Data.Text as T
import qualified NLP.Miniutter.English as MU
import Game.LambdaHack.Client.CommonClient
import Game.LambdaHack.Client.ItemSlot
import qualified Game.LambdaHack.Client.Key as K
import Game.LambdaHack.Client.MonadClient
import Game.LambdaHack.Client.State
import Game.LambdaHack.Client.UI.HumanCmd
import Game.LambdaHack.Client.UI.KeyBindings
import Game.LambdaHack.Client.UI.MonadClientUI
import Game.LambdaHack.Client.UI.MsgClient
import Game.LambdaHack.Client.UI.WidgetClient
import qualified Game.LambdaHack.Common.Ability as Ability
import Game.LambdaHack.Common.Actor
import Game.LambdaHack.Common.ActorState
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.ItemDescription
import Game.LambdaHack.Common.ItemStrongest
import qualified Game.LambdaHack.Common.Kind as Kind
import Game.LambdaHack.Common.Level
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.MonadStateRead
import Game.LambdaHack.Common.Msg
import Game.LambdaHack.Common.Perception
import Game.LambdaHack.Common.Point
import Game.LambdaHack.Common.Request
import Game.LambdaHack.Common.State
import Game.LambdaHack.Common.Vector
import qualified Game.LambdaHack.Content.ItemKind as IK
data ItemDialogState = ISuitable | IAll | INoSuitable | INoAll
deriving (Show, Eq)
ppItemDialogMode :: ItemDialogMode -> (Text, Text)
ppItemDialogMode (MStore cstore) = ppCStore cstore
ppItemDialogMode MOwned = ("in", "our possession")
ppItemDialogMode MStats = ("among", "strenghts")
ppItemDialogModeIn :: ItemDialogMode -> Text
ppItemDialogModeIn c = let (tIn, t) = ppItemDialogMode c in tIn <+> t
ppItemDialogModeFrom :: ItemDialogMode -> Text
ppItemDialogModeFrom c = let (_tIn, t) = ppItemDialogMode c in "from" <+> t
storeFromMode :: ItemDialogMode -> CStore
storeFromMode c = case c of
MStore cstore -> cstore
MOwned -> CGround -- needed to decide display mode in textAllAE
MStats -> CGround -- needed to decide display mode in textAllAE
accessModeBag :: ActorId -> State -> ItemDialogMode -> ItemBag
accessModeBag leader s (MStore cstore) = getActorBag leader cstore s
accessModeBag leader s MOwned = let fid = bfid $ getActorBody leader s
in sharedAllOwnedFid False fid s
accessModeBag _ _ MStats = EM.empty
-- | Let a human player choose any item from a given group.
-- Note that this does not guarantee the chosen item belongs to the group,
-- as the player can override the choice.
-- Used e.g., for applying and projecting.
getGroupItem :: MonadClientUI m
=> m Suitability
-- ^ which items to consider suitable
-> Text -- ^ specific prompt for only suitable items
-> Text -- ^ generic prompt
-> Bool -- ^ whether to enable setting cursor with mouse
-> [CStore] -- ^ initial legal modes
-> [CStore] -- ^ legal modes after Calm taken into account
-> m (SlideOrCmd ((ItemId, ItemFull), ItemDialogMode))
getGroupItem psuit prompt promptGeneric cursor cLegalRaw cLegalAfterCalm = do
let dialogState = if cursor then INoSuitable else ISuitable
soc <- getFull psuit
(\_ _ cCur -> prompt <+> ppItemDialogModeFrom cCur)
(\_ _ cCur -> promptGeneric <+> ppItemDialogModeFrom cCur)
cursor cLegalRaw cLegalAfterCalm True False dialogState
case soc of
Left sli -> return $ Left sli
Right ([(iid, itemFull)], c) -> return $ Right ((iid, itemFull), c)
Right _ -> assert `failure` soc
-- | Let the human player choose any item from a list of items
-- and let him specify the number of items.
-- Used, e.g., for picking up and inventory manipulation.
getAnyItems :: MonadClientUI m
=> m Suitability
-- ^ which items to consider suitable
-> Text -- ^ specific prompt for only suitable items
-> Text -- ^ generic prompt
-> [CStore] -- ^ initial legal modes
-> [CStore] -- ^ legal modes after Calm taken into account
-> Bool -- ^ whether to ask, when the only item
-- in the starting mode is suitable
-> Bool -- ^ whether to ask for the number of items
-> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode))
getAnyItems psuit prompt promptGeneric cLegalRaw cLegalAfterCalm askWhenLone askNumber = do
soc <- getFull psuit
(\_ _ cCur -> prompt <+> ppItemDialogModeFrom cCur)
(\_ _ cCur -> promptGeneric <+> ppItemDialogModeFrom cCur)
False cLegalRaw cLegalAfterCalm
askWhenLone True ISuitable
case soc of
Left _ -> return soc
Right ([(iid, itemFull)], c) -> do
socK <- pickNumber askNumber $ itemK itemFull
case socK of
Left slides -> return $ Left slides
Right k ->
return $ Right ([(iid, itemFull{itemK=k})], c)
Right _ -> return soc
-- | Display all items from a store and let the human player choose any
-- or switch to any other store.
-- Used, e.g., for viewing inventory and item descriptions.
getStoreItem :: MonadClientUI m
=> (Actor -> [ItemFull] -> ItemDialogMode -> Text)
-- ^ how to describe suitable items
-> ItemDialogMode -- ^ initial mode
-> m (SlideOrCmd ((ItemId, ItemFull), ItemDialogMode))
getStoreItem prompt cInitial = do
let allCs = map MStore [CEqp, CInv, CSha]
++ [MOwned]
++ map MStore [CGround, COrgan]
++ [MStats]
(pre, rest) = break (== cInitial) allCs
post = dropWhile (== cInitial) rest
remCs = post ++ pre
soc <- getItem (return SuitsEverything)
prompt prompt False cInitial remCs
True False (cInitial:remCs) ISuitable
case soc of
Left sli -> return $ Left sli
Right ([(iid, itemFull)], c) -> return $ Right ((iid, itemFull), c)
Right _ -> assert `failure` soc
-- | Let the human player choose a single, preferably suitable,
-- item from a list of items. Don't display stores empty for all actors.
-- Start with a non-empty store.
getFull :: MonadClientUI m
=> m Suitability
-- ^ which items to consider suitable
-> (Actor -> [ItemFull] -> ItemDialogMode -> Text)
-- ^ specific prompt for only suitable items
-> (Actor -> [ItemFull] -> ItemDialogMode -> Text)
-- ^ generic prompt
-> Bool -- ^ whether to enable setting cursor with mouse
-> [CStore] -- ^ initial legal modes
-> [CStore] -- ^ legal modes with Calm taken into account
-> Bool -- ^ whether to ask, when the only item
-- in the starting mode is suitable
-> Bool -- ^ whether to permit multiple items as a result
-> ItemDialogState -- ^ the dialog state to start in
-> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode))
getFull psuit prompt promptGeneric cursor cLegalRaw cLegalAfterCalm
askWhenLone permitMulitple initalState = do
side <- getsClient sside
leader <- getLeaderUI
let aidNotEmpty store aid = do
bag <- getsState $ getCBag (CActor aid store)
return $! not $ EM.null bag
partyNotEmpty store = do
as <- getsState $ fidActorNotProjAssocs side
bs <- mapM (aidNotEmpty store . fst) as
return $! or bs
mpsuit <- psuit
let psuitFun = case mpsuit of
SuitsEverything -> const True
SuitsNothing _ -> const False
SuitsSomething f -> f
-- Move the first store that is non-empty for suitable items for this actor
-- to the front, if any.
getCStoreBag <- getsState $ \s cstore -> getCBag (CActor leader cstore) s
let hasThisActor = not . EM.null . getCStoreBag
case filter hasThisActor cLegalAfterCalm of
[] ->
if isNothing (find hasThisActor cLegalRaw) then do
let contLegalRaw = map MStore cLegalRaw
tLegal = map (MU.Text . ppItemDialogModeIn) contLegalRaw
ppLegal = makePhrase [MU.WWxW "nor" tLegal]
failWith $ "no items" <+> ppLegal
else failSer ItemNotCalm
haveThis@(headThisActor : _) -> do
itemToF <- itemToFullClient
let suitsThisActor store =
let bag = getCStoreBag store
in any (\(iid, kit) -> psuitFun $ itemToF iid kit) $ EM.assocs bag
cThisActor cDef = fromMaybe cDef $ find suitsThisActor haveThis
-- Don't display stores totally empty for all actors.
cLegal <- filterM partyNotEmpty cLegalRaw
let breakStores cInit =
let (pre, rest) = break (== cInit) cLegal
post = dropWhile (== cInit) rest
in (MStore cInit, map MStore $ post ++ pre)
-- The last used store may go before even the first nonempty store.
lastStore <- getsClient slastStore
firstStore <-
if lastStore `notElem` cLegalAfterCalm
then return $! cThisActor headThisActor
else do
(itemSlots, organSlots) <- getsClient sslots
let lSlots = if lastStore == COrgan then organSlots else itemSlots
lastSlot <- getsClient slastSlot
case EM.lookup lastSlot lSlots of
Nothing -> return $! cThisActor headThisActor
Just lastIid -> case EM.lookup lastIid $ getCStoreBag lastStore of
Nothing -> return $! cThisActor headThisActor
Just kit -> do
let lastItemFull = itemToF lastIid kit
lastSuits = psuitFun lastItemFull
cLast = cThisActor lastStore
return $! if lastSuits && cLast /= CGround
then lastStore
else cLast
let (modeFirst, modeRest) = breakStores firstStore
getItem psuit prompt promptGeneric cursor modeFirst modeRest
askWhenLone permitMulitple (map MStore cLegal) initalState
-- | Let the human player choose a single, preferably suitable,
-- item from a list of items.
getItem :: MonadClientUI m
=> m Suitability
-- ^ which items to consider suitable
-> (Actor -> [ItemFull] -> ItemDialogMode -> Text)
-- ^ specific prompt for only suitable items
-> (Actor -> [ItemFull] -> ItemDialogMode -> Text)
-- ^ generic prompt
-> Bool -- ^ whether to enable setting cursor with mouse
-> ItemDialogMode -- ^ first mode, legal or not
-> [ItemDialogMode] -- ^ the (rest of) legal modes
-> Bool -- ^ whether to ask, when the only item
-- in the starting mode is suitable
-> Bool -- ^ whether to permit multiple items as a result
-> [ItemDialogMode] -- ^ all legal modes
-> ItemDialogState -- ^ the dialog state to start in
-> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode))
getItem psuit prompt promptGeneric cursor cCur cRest askWhenLone permitMulitple
cLegal initalState = do
leader <- getLeaderUI
accessCBag <- getsState $ accessModeBag leader
let storeAssocs = EM.assocs . accessCBag
allAssocs = concatMap storeAssocs (cCur : cRest)
case (cRest, allAssocs) of
([], [(iid, k)]) | not askWhenLone -> do
itemToF <- itemToFullClient
return $ Right ([(iid, itemToF iid k)], cCur)
_ ->
transition psuit prompt promptGeneric cursor permitMulitple cLegal
0 cCur cRest initalState
data DefItemKey m = DefItemKey
{ defLabel :: Text -- ^ can be undefined if not @defCond@
, defCond :: !Bool
, defAction :: K.KM -> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode))
}
data Suitability =
SuitsEverything
| SuitsNothing Msg
| SuitsSomething (ItemFull -> Bool)
transition :: forall m. MonadClientUI m
=> m Suitability
-> (Actor -> [ItemFull] -> ItemDialogMode -> Text)
-> (Actor -> [ItemFull] -> ItemDialogMode -> Text)
-> Bool
-> Bool
-> [ItemDialogMode]
-> Int
-> ItemDialogMode
-> [ItemDialogMode]
-> ItemDialogState
-> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode))
transition psuit prompt promptGeneric cursor permitMulitple cLegal
numPrefix cCur cRest itemDialogState = do
let recCall =
transition psuit prompt promptGeneric cursor permitMulitple cLegal
(itemSlots, organSlots) <- getsClient sslots
leader <- getLeaderUI
body <- getsState $ getActorBody leader
activeItems <- activeItemsClient leader
fact <- getsState $ (EM.! bfid body) . sfactionD
hs <- partyAfterLeader leader
bagAll <- getsState $ \s -> accessModeBag leader s cCur
lastSlot <- getsClient slastSlot
itemToF <- itemToFullClient
Binding{brevMap} <- askBinding
mpsuit <- psuit -- when throwing, this sets eps and checks cursor validity
(suitsEverything, psuitFun) <- case mpsuit of
SuitsEverything -> return (True, const True)
SuitsNothing err -> do
slides <- promptToSlideshow $ err <+> moreMsg
void $ getInitConfirms ColorFull [] $ slides <> toSlideshow Nothing [[]]
return (False, const False)
-- When throwing, this function takes missile range into accout.
SuitsSomething f -> return (False, f)
let getSingleResult :: ItemId -> (ItemId, ItemFull)
getSingleResult iid = (iid, itemToF iid (bagAll EM.! iid))
getResult :: ItemId -> ([(ItemId, ItemFull)], ItemDialogMode)
getResult iid = ([getSingleResult iid], cCur)
getMultResult :: [ItemId] -> ([(ItemId, ItemFull)], ItemDialogMode)
getMultResult iids = (map getSingleResult iids, cCur)
filterP iid kit = psuitFun $ itemToF iid kit
bagAllSuit = EM.filterWithKey filterP bagAll
isOrgan = cCur == MStore COrgan
lSlots = if isOrgan then organSlots else itemSlots
bagItemSlotsAll = EM.filter (`EM.member` bagAll) lSlots
-- Predicate for slot matching the current prefix, unless the prefix
-- is 0, in which case we display all slots, even if they require
-- the user to start with number keys to get to them.
-- Could be generalized to 1 if prefix 1x exists, etc., but too rare.
hasPrefixOpen x _ = slotPrefix x == numPrefix || numPrefix == 0
bagItemSlotsOpen = EM.filterWithKey hasPrefixOpen bagItemSlotsAll
hasPrefix x _ = slotPrefix x == numPrefix
bagItemSlots = EM.filterWithKey hasPrefix bagItemSlotsOpen
bag = EM.fromList $ map (\iid -> (iid, bagAll EM.! iid))
(EM.elems bagItemSlotsOpen)
suitableItemSlotsAll = EM.filter (`EM.member` bagAllSuit) lSlots
suitableItemSlotsOpen =
EM.filterWithKey hasPrefixOpen suitableItemSlotsAll
suitableItemSlots = EM.filterWithKey hasPrefix suitableItemSlotsOpen
bagSuit = EM.fromList $ map (\iid -> (iid, bagAllSuit EM.! iid))
(EM.elems suitableItemSlotsOpen)
(autoDun, autoLvl) = autoDungeonLevel fact
multipleSlots = if itemDialogState `elem` [IAll, INoAll]
then bagItemSlotsAll
else suitableItemSlotsAll
keyDefs :: [(K.KM, DefItemKey m)]
keyDefs = filter (defCond . snd) $
[ (K.toKM K.NoModifier $ K.Char '?', DefItemKey
{ defLabel = "?"
, defCond = not (EM.null bag)
, defAction = \_ -> recCall numPrefix cCur cRest
$ case itemDialogState of
INoSuitable -> if EM.null bagSuit then IAll else ISuitable
ISuitable -> if suitsEverything then INoAll else IAll
IAll -> if EM.null bag then INoSuitable else INoAll
INoAll -> if suitsEverything then ISuitable else INoSuitable
})
, (K.toKM K.NoModifier $ K.Char '/', DefItemKey
{ defLabel = "/"
, defCond = not $ null cRest
, defAction = \_ -> do
let calmE = calmEnough body activeItems
mcCur = filter (`elem` cLegal) [cCur]
(cCurAfterCalm, cRestAfterCalm) = case cRest ++ mcCur of
c1@(MStore CSha) : c2 : rest | not calmE ->
(c2, c1 : rest)
[MStore CSha] | not calmE -> assert `failure` cRest
c1 : rest -> (c1, rest)
[] -> assert `failure` cRest
recCall numPrefix cCurAfterCalm cRestAfterCalm itemDialogState
})
, (K.toKM K.NoModifier $ K.Char '*', DefItemKey
{ defLabel = "*"
, defCond = permitMulitple && not (EM.null multipleSlots)
, defAction = \_ ->
let eslots = EM.elems multipleSlots
in return $ Right $ getMultResult eslots
})
, (K.toKM K.NoModifier K.Return, DefItemKey
{ defLabel = if lastSlot `EM.member` labelItemSlotsOpen
then let l = makePhrase [slotLabel lastSlot]
in "RET(" <> l <> ")" -- l is on the screen list
else "RET"
, defCond = not (EM.null labelItemSlotsOpen)
, defAction = \_ -> case EM.lookup lastSlot labelItemSlotsOpen of
Just iid -> return $ Right $ getResult iid
Nothing -> case EM.minViewWithKey labelItemSlotsOpen of
Nothing -> assert `failure` "labelItemSlotsOpen empty"
`twith` labelItemSlotsOpen
Just ((l, _), _) -> do
modifyClient $ \cli ->
cli { slastSlot = l
, slastStore = storeFromMode cCur }
recCall numPrefix cCur cRest itemDialogState
})
, let km = M.findWithDefault (K.toKM K.NoModifier K.Tab)
MemberCycle brevMap
in (km, DefItemKey
{ defLabel = K.showKM km
, defCond = not (cCur == MOwned
|| autoLvl
|| not (any (\(_, b) -> blid b == blid body) hs))
, defAction = \_ -> do
err <- memberCycle False
let !_A = assert (err == mempty `blame` err) ()
(cCurUpd, cRestUpd) <- legalWithUpdatedLeader cCur cRest
recCall numPrefix cCurUpd cRestUpd itemDialogState
})
, let km = M.findWithDefault (K.toKM K.NoModifier K.BackTab)
MemberBack brevMap
in (km, DefItemKey
{ defLabel = K.showKM km
, defCond = not (cCur == MOwned || autoDun || null hs)
, defAction = \_ -> do
err <- memberBack False
let !_A = assert (err == mempty `blame` err) ()
(cCurUpd, cRestUpd) <- legalWithUpdatedLeader cCur cRest
recCall numPrefix cCurUpd cRestUpd itemDialogState
})
, let km = M.findWithDefault (K.toKM K.NoModifier (K.KP '/'))
TgtFloor brevMap
in cursorCmdDef False km tgtFloorHuman
, let hackyCmd = Macro "" ["KP_Divide"] -- no keypad, but arrows enough
km = M.findWithDefault (K.toKM K.NoModifier K.RightButtonPress)
hackyCmd brevMap
in cursorCmdDef False km tgtEnemyHuman
, let km = M.findWithDefault (K.toKM K.NoModifier (K.KP '*'))
TgtEnemy brevMap
in cursorCmdDef False km tgtEnemyHuman
, let hackyCmd = Macro "" ["KP_Multiply"] -- no keypad, but arrows OK
km = M.findWithDefault (K.toKM K.NoModifier K.RightButtonPress)
hackyCmd brevMap
in cursorCmdDef False km tgtEnemyHuman
, let km = M.findWithDefault (K.toKM K.NoModifier K.BackSpace)
TgtClear brevMap
in cursorCmdDef False km tgtClearHuman
]
++ numberPrefixes
++ [ let plusMinus = K.Char $ if b then '+' else '-'
km = M.findWithDefault (K.toKM K.NoModifier plusMinus)
(EpsIncr b) brevMap
in cursorCmdDef False km (epsIncrHuman b)
| b <- [True, False]
]
++ arrows
++ [
let km = M.findWithDefault (K.toKM K.NoModifier K.MiddleButtonPress)
CursorPointerEnemy brevMap
in cursorCmdDef False km (cursorPointerEnemy False False)
, let km = M.findWithDefault (K.toKM K.Shift K.MiddleButtonPress)
CursorPointerFloor brevMap
in cursorCmdDef False km (cursorPointerFloor False False)
, let km = M.findWithDefault (K.toKM K.NoModifier K.RightButtonPress)
TgtPointerEnemy brevMap
in cursorCmdDef True km (cursorPointerEnemy True True)
]
prefixCmdDef d =
(K.toKM K.NoModifier $ K.Char (intToDigit d), DefItemKey
{ defLabel = ""
, defCond = True
, defAction = \_ ->
recCall (10 * numPrefix + d) cCur cRest itemDialogState
})
numberPrefixes = map prefixCmdDef [0..9]
cursorCmdDef verbose km cmd =
(km, DefItemKey
{ defLabel = "keypad, mouse"
, defCond = cursor && EM.null bagFiltered
, defAction = \_ -> do
look <- cmd
when verbose $
void $ getInitConfirms ColorFull []
$ look <> toSlideshow Nothing [[]]
recCall numPrefix cCur cRest itemDialogState
})
arrows =
let kCmds = K.moveBinding False False
(`moveCursorHuman` 1) (`moveCursorHuman` 10)
in map (uncurry $ cursorCmdDef False) kCmds
lettersDef :: DefItemKey m
lettersDef = DefItemKey
{ defLabel = slotRange $ EM.keys labelItemSlots
, defCond = True
, defAction = \K.KM{key} -> case key of
K.Char l -> case EM.lookup (SlotChar numPrefix l) bagItemSlots of
Nothing -> assert `failure` "unexpected slot"
`twith` (l, bagItemSlots)
Just iid -> return $ Right $ getResult iid
_ -> assert `failure` "unexpected key:" `twith` K.showKey key
}
(labelItemSlotsOpen, labelItemSlots, bagFiltered, promptChosen) =
case itemDialogState of
ISuitable -> (suitableItemSlotsOpen,
suitableItemSlots,
bagSuit,
prompt body activeItems cCur <> ":")
IAll -> (bagItemSlotsOpen,
bagItemSlots,
bag,
promptGeneric body activeItems cCur <> ":")
INoSuitable -> (suitableItemSlotsOpen,
suitableItemSlots,
EM.empty,
prompt body activeItems cCur <> ":")
INoAll -> (bagItemSlotsOpen,
bagItemSlots,
EM.empty,
promptGeneric body activeItems cCur <> ":")
io <- case cCur of
MStats -> statsOverlay leader -- TODO: describe each stat when selected
_ -> itemOverlay (storeFromMode cCur) (blid body) bagFiltered
runDefItemKey keyDefs lettersDef io bagItemSlots promptChosen
statsOverlay :: MonadClient m => ActorId -> m Overlay
statsOverlay aid = do
b <- getsState $ getActorBody aid
activeItems <- activeItemsClient aid
let block n = n + if braced b then 50 else 0
prSlot :: (IK.EqpSlot, Int -> Text) -> Text
prSlot (eqpSlot, f) =
let fullText t =
" "
<> makePhrase [ MU.Text $ T.justifyLeft 22 ' '
$ IK.slotName eqpSlot
, MU.Text t ]
<> " "
valueText = f $ sumSlotNoFilter eqpSlot activeItems
in fullText valueText
-- Some values can be negative, for others 0 is equivalent but shorter.
slotList = -- TODO: [IK.EqpSlotAddHurtMelee..IK.EqpSlotAddLight]
[ (IK.EqpSlotAddHurtMelee, \t -> tshow t <> "%")
-- TODO: not applicable right now, IK.EqpSlotAddHurtRanged
, (IK.EqpSlotAddArmorMelee, \t -> "[" <> tshow (block t) <> "%]")
, (IK.EqpSlotAddArmorRanged, \t -> "{" <> tshow (block t) <> "%}")
, (IK.EqpSlotAddMaxHP, \t -> tshow $ max 0 t)
, (IK.EqpSlotAddMaxCalm, \t -> tshow $ max 0 t)
, (IK.EqpSlotAddSpeed, \t -> tshow (max 0 t) <> "m/10s")
, (IK.EqpSlotAddSight, \t ->
tshow (max 0 $ min (fromIntegral $ bcalm b `div` (5 * oneM)) t)
<> "m")
, (IK.EqpSlotAddSmell, \t -> tshow (max 0 t) <> "m")
, (IK.EqpSlotAddLight, \t -> tshow (max 0 t) <> "m")
]
skills = sumSkills activeItems
-- TODO: are negative total skills meaningful?
prAbility :: Ability.Ability -> Text
prAbility ability =
let fullText t =
" "
<> makePhrase [ MU.Text $ T.justifyLeft 22 ' '
$ "ability" <+> tshow ability
, MU.Text t ]
<> " "
valueText = tshow $ EM.findWithDefault 0 ability skills
in fullText valueText
abilityList = [minBound..maxBound]
return $! toOverlay $ map prSlot slotList ++ map prAbility abilityList
legalWithUpdatedLeader :: MonadClientUI m
=> ItemDialogMode
-> [ItemDialogMode]
-> m (ItemDialogMode, [ItemDialogMode])
legalWithUpdatedLeader cCur cRest = do
leader <- getLeaderUI
let newLegal = cCur : cRest -- not updated in any way yet
b <- getsState $ getActorBody leader
activeItems <- activeItemsClient leader
let calmE = calmEnough b activeItems
legalAfterCalm = case newLegal of
c1@(MStore CSha) : c2 : rest | not calmE -> (c2, c1 : rest)
[MStore CSha] | not calmE -> (MStore CGround, newLegal)
c1 : rest -> (c1, rest)
[] -> assert `failure` (cCur, cRest)
return legalAfterCalm
runDefItemKey :: MonadClientUI m
=> [(K.KM, DefItemKey m)]
-> DefItemKey m
-> Overlay
-> EM.EnumMap SlotChar ItemId
-> Text
-> m (SlideOrCmd ([(ItemId, ItemFull)], ItemDialogMode))
runDefItemKey keyDefs lettersDef io labelItemSlots prompt = do
let itemKeys =
let slotKeys = map (K.Char . slotChar) (EM.keys labelItemSlots)
defKeys = map fst keyDefs
in map (K.toKM K.NoModifier) slotKeys ++ defKeys
choice = let letterRange = defLabel lettersDef
keyLabelsRaw = letterRange : map (defLabel . snd) keyDefs
keyLabels = filter (not . T.null) keyLabelsRaw
in "[" <> T.intercalate ", " (nub keyLabels)
akm <- displayChoiceUI (prompt <+> choice) io itemKeys
case akm of
Left slides -> failSlides slides
Right km ->
case lookup km{K.pointer=Nothing} keyDefs of
Just keyDef -> defAction keyDef km
Nothing -> defAction lettersDef km
pickNumber :: MonadClientUI m => Bool -> Int -> m (SlideOrCmd Int)
pickNumber askNumber kAll = do
let kDefault = kAll
if askNumber && kAll > 1 then do
let tDefault = tshow kDefault
kbound = min 9 kAll
kprompt = "Choose number [1-" <> tshow kbound
<> ", RET(" <> tDefault <> ")"
kkeys = map (K.toKM K.NoModifier)
$ map (K.Char . Char.intToDigit) [1..kbound]
++ [K.Return]
kkm <- displayChoiceUI kprompt emptyOverlay kkeys
case kkm of
Left slides -> failSlides slides
Right K.KM{key} ->
case key of
K.Char l -> return $ Right $ Char.digitToInt l
K.Return -> return $ Right kDefault
_ -> assert `failure` "unexpected key:" `twith` kkm
else return $ Right kAll
-- | Switches current member to the next on the level, if any, wrapping.
memberCycle :: MonadClientUI m => Bool -> m Slideshow
memberCycle verbose = do
side <- getsClient sside
fact <- getsState $ (EM.! side) . sfactionD
leader <- getLeaderUI
body <- getsState $ getActorBody leader
hs <- partyAfterLeader leader
let autoLvl = snd $ autoDungeonLevel fact
case filter (\(_, b) -> blid b == blid body) hs of
_ | autoLvl -> failMsg $ showReqFailure NoChangeLvlLeader
[] -> failMsg "cannot pick any other member on this level"
(np, b) : _ -> do
success <- pickLeader verbose np
let !_A = assert (success `blame` "same leader" `twith` (leader, np, b)) ()
return mempty
-- | Switches current member to the previous in the whole dungeon, wrapping.
memberBack :: MonadClientUI m => Bool -> m Slideshow
memberBack verbose = do
side <- getsClient sside
fact <- getsState $ (EM.! side) . sfactionD
leader <- getLeaderUI
hs <- partyAfterLeader leader
let (autoDun, autoLvl) = autoDungeonLevel fact
case reverse hs of
_ | autoDun -> failMsg $ showReqFailure NoChangeDunLeader
_ | autoLvl -> failMsg $ showReqFailure NoChangeLvlLeader
[] -> failMsg "no other member in the party"
(np, b) : _ -> do
success <- pickLeader verbose np
let !_A = assert (success `blame` "same leader"
`twith` (leader, np, b)) ()
return mempty
partyAfterLeader :: MonadStateRead m => ActorId -> m [(ActorId, Actor)]
partyAfterLeader leader = do
faction <- getsState $ bfid . getActorBody leader
allA <- getsState $ EM.assocs . sactorD
let factionA = filter (\(_, body) ->
not (bproj body) && bfid body == faction) allA
hs = sortBy (comparing keySelected) factionA
i = fromMaybe (-1) $ findIndex ((== leader) . fst) hs
(lt, gt) = (take i hs, drop (i + 1) hs)
return $! gt ++ lt
-- | Select a faction leader. False, if nothing to do.
pickLeader :: MonadClientUI m => Bool -> ActorId -> m Bool
pickLeader verbose aid = do
leader <- getLeaderUI
stgtMode <- getsClient stgtMode
if leader == aid
then return False -- already picked
else do
pbody <- getsState $ getActorBody aid
let !_A = assert (not (bproj pbody)
`blame` "projectile chosen as the leader"
`twith` (aid, pbody)) ()
-- Even if it's already the leader, give his proper name, not 'you'.
let subject = partActor pbody
when verbose $ msgAdd $ makeSentence [subject, "picked as a leader"]
-- Update client state.
s <- getState
modifyClient $ updateLeader aid s
-- Move the cursor, if active, to the new level.
case stgtMode of
Nothing -> return ()
Just _ ->
modifyClient $ \cli -> cli {stgtMode = Just $ TgtMode $ blid pbody}
-- Inform about items, etc.
lookMsg <- lookAt False "" True (bpos pbody) aid ""
when verbose $ msgAdd lookMsg
return True
cursorPointerFloor :: MonadClientUI m => Bool -> Bool -> m Slideshow
cursorPointerFloor verbose addMoreMsg = do
km <- getsClient slastKM
lidV <- viewedLevel
Level{lxsize, lysize} <- getLevel lidV
case K.pointer km of
Just(newPos@Point{..}) | px >= 0 && py >= 0
&& px < lxsize && py < lysize -> do
let scursor = TPoint lidV newPos
modifyClient $ \cli -> cli {scursor, stgtMode = Just $ TgtMode lidV}
if verbose then
doLook addMoreMsg
else do
displayPush "" -- flash the targeting line and path
displayDelay -- for a bit longer
return mempty
_ -> do
stopPlayBack
return mempty
cursorPointerEnemy :: MonadClientUI m => Bool -> Bool -> m Slideshow
cursorPointerEnemy verbose addMoreMsg = do
km <- getsClient slastKM
lidV <- viewedLevel
Level{lxsize, lysize} <- getLevel lidV
case K.pointer km of
Just(newPos@Point{..}) | px >= 0 && py >= 0
&& px < lxsize && py < lysize -> do
bsAll <- getsState $ actorAssocs (const True) lidV
let scursor =
case find (\(_, m) -> bpos m == newPos) bsAll of
Just (im, _) -> TEnemy im True
Nothing -> TPoint lidV newPos
modifyClient $ \cli -> cli {scursor, stgtMode = Just $ TgtMode lidV}
if verbose then
doLook addMoreMsg
else do
displayPush "" -- flash the targeting line and path
displayDelay -- for a bit longer
return mempty
_ -> do
stopPlayBack
return mempty
-- | Move the cursor. Assumes targeting mode.
moveCursorHuman :: MonadClientUI m => Vector -> Int -> m Slideshow
moveCursorHuman dir n = do
leader <- getLeaderUI
stgtMode <- getsClient stgtMode
let lidV = maybe (assert `failure` leader) tgtLevelId stgtMode
Level{lxsize, lysize} <- getLevel lidV
lpos <- getsState $ bpos . getActorBody leader
scursor <- getsClient scursor
cursorPos <- cursorToPos
let cpos = fromMaybe lpos cursorPos
shiftB pos = shiftBounded lxsize lysize pos dir
newPos = iterate shiftB cpos !! n
if newPos == cpos then failMsg "never mind"
else do
let tgt = case scursor of
TVector{} -> TVector $ newPos `vectorToFrom` lpos
_ -> TPoint lidV newPos
modifyClient $ \cli -> cli {scursor = tgt}
doLook False
-- | Cycle targeting mode. Do not change position of the cursor,
-- switch among things at that position.
tgtFloorHuman :: MonadClientUI m => m Slideshow
tgtFloorHuman = do
lidV <- viewedLevel
leader <- getLeaderUI
lpos <- getsState $ bpos . getActorBody leader
cursorPos <- cursorToPos
scursor <- getsClient scursor
stgtMode <- getsClient stgtMode
bsAll <- getsState $ actorAssocs (const True) lidV
let cursor = fromMaybe lpos cursorPos
tgt = case scursor of
_ | isNothing stgtMode -> -- first key press: keep target
scursor
TEnemy a True -> TEnemy a False
TEnemy{} -> TPoint lidV cursor
TEnemyPos{} -> TPoint lidV cursor
TPoint{} -> TVector $ cursor `vectorToFrom` lpos
TVector{} ->
-- For projectiles, we pick here the first that would be picked
-- by '*', so that all other projectiles on the tile come next,
-- without any intervening actors from other tiles.
case find (\(_, m) -> Just (bpos m) == cursorPos) bsAll of
Just (im, _) -> TEnemy im True
Nothing -> TPoint lidV cursor
modifyClient $ \cli -> cli {scursor = tgt, stgtMode = Just $ TgtMode lidV}
doLook False
tgtEnemyHuman :: MonadClientUI m => m Slideshow
tgtEnemyHuman = do
lidV <- viewedLevel
leader <- getLeaderUI
lpos <- getsState $ bpos . getActorBody leader
cursorPos <- cursorToPos
scursor <- getsClient scursor
stgtMode <- getsClient stgtMode
side <- getsClient sside
fact <- getsState $ (EM.! side) . sfactionD
bsAll <- getsState $ actorAssocs (const True) lidV
let ordPos (_, b) = (chessDist lpos $ bpos b, bpos b)
dbs = sortBy (comparing ordPos) bsAll
pickUnderCursor = -- switch to the actor under cursor, if any
let i = fromMaybe (-1)
$ findIndex ((== cursorPos) . Just . bpos . snd) dbs
in splitAt i dbs
(permitAnyActor, (lt, gt)) = case scursor of
TEnemy a permit | isJust stgtMode -> -- pick next enemy
let i = fromMaybe (-1) $ findIndex ((== a) . fst) dbs
in (permit, splitAt (i + 1) dbs)
TEnemy a permit -> -- first key press, retarget old enemy
let i = fromMaybe (-1) $ findIndex ((== a) . fst) dbs
in (permit, splitAt i dbs)
TEnemyPos _ _ _ permit -> (permit, pickUnderCursor)
_ -> (False, pickUnderCursor) -- the sensible default is only-foes
gtlt = gt ++ lt
isEnemy b = isAtWar fact (bfid b)
&& not (bproj b)
&& bhp b > 0
lf = filter (isEnemy . snd) gtlt
tgt | permitAnyActor = case gtlt of
(a, _) : _ -> TEnemy a True
[] -> scursor -- no actors in sight, stick to last target
| otherwise = case lf of
(a, _) : _ -> TEnemy a False
[] -> scursor -- no seen foes in sight, stick to last target
-- Register the chosen enemy, to pick another on next invocation.
modifyClient $ \cli -> cli {scursor = tgt, stgtMode = Just $ TgtMode lidV}
doLook False
-- | Tweak the @eps@ parameter of the targeting digital line.
epsIncrHuman :: MonadClientUI m => Bool -> m Slideshow
epsIncrHuman b = do
stgtMode <- getsClient stgtMode
if isJust stgtMode
then do
modifyClient $ \cli -> cli {seps = seps cli + if b then 1 else -1}
return mempty
else failMsg "never mind" -- no visual feedback, so no sense
tgtClearHuman :: MonadClientUI m => m Slideshow
tgtClearHuman = do
leader <- getLeaderUI
tgt <- getsClient $ getTarget leader
case tgt of
Just _ -> do
modifyClient $ updateTarget leader (const Nothing)
return mempty
Nothing -> do
scursorOld <- getsClient scursor
b <- getsState $ getActorBody leader
let scursor = case scursorOld of
TEnemy _ permit -> TEnemy leader permit
TEnemyPos _ _ _ permit -> TEnemy leader permit
TPoint{} -> TPoint (blid b) (bpos b)
TVector{} -> TVector (Vector 0 0)
modifyClient $ \cli -> cli {scursor}
doLook False
-- | Perform look around in the current position of the cursor.
-- Normally expects targeting mode and so that a leader is picked.
doLook :: MonadClientUI m => Bool -> m Slideshow
doLook addMoreMsg = do
Kind.COps{cotile=Kind.Ops{ouniqGroup}} <- getsState scops
let unknownId = ouniqGroup "unknown space"
stgtMode <- getsClient stgtMode
case stgtMode of
Nothing -> return mempty
Just tgtMode -> do
leader <- getLeaderUI
let lidV = tgtLevelId tgtMode
lvl <- getLevel lidV
cursorPos <- cursorToPos
per <- getPerFid lidV
b <- getsState $ getActorBody leader
let p = fromMaybe (bpos b) cursorPos
canSee = ES.member p (totalVisible per)
inhabitants <- if canSee
then getsState $ posToActors p lidV
else return []
seps <- getsClient seps
mnewEps <- makeLine False b p seps
itemToF <- itemToFullClient
let aims = isJust mnewEps
enemyMsg = case inhabitants of
[] -> ""
(_, body) : rest ->
-- Even if it's the leader, give his proper name, not 'you'.
let subjects = map (partActor . snd) inhabitants
subject = MU.WWandW subjects
verb = "be here"
desc =
if not (null rest) -- many actors, only list names
then ""
else case itemDisco $ itemToF (btrunk body) (1, []) of
Nothing -> "" -- no details, only show the name
Just ItemDisco{itemKind} -> IK.idesc itemKind
pdesc = if desc == "" then "" else "(" <> desc <> ")"
in makeSentence [MU.SubjectVerbSg subject verb] <+> pdesc
vis | lvl `at` p == unknownId = "that is"
| not canSee = "you remember"
| not aims = "you are aware of"
| otherwise = "you see"
-- Show general info about current position.
lookMsg <- lookAt True vis canSee p leader enemyMsg
{- targeting is kind of a menu (or at least mode), so this is menu inside
a menu, which is messy, hence disabled until UI overhauled:
-- Check if there's something lying around at current position.
is <- getsState $ getCBag $ CFloor lidV p
if EM.size is <= 2 then
promptToSlideshow lookMsg
else do
msgAdd lookMsg -- TODO: do not add to history
floorItemOverlay lidV p
-}
promptToSlideshow $ lookMsg <+> if addMoreMsg then moreMsg else ""
-- | Create a list of item names.
_floorItemOverlay :: MonadClientUI m
=> LevelId -> Point
-> m (SlideOrCmd (RequestTimed 'Ability.AbMoveItem))
_floorItemOverlay _lid _p = describeItemC MOwned {-CFloor lid p-}
describeItemC :: MonadClientUI m
=> ItemDialogMode
-> m (SlideOrCmd (RequestTimed 'Ability.AbMoveItem))
describeItemC c = do
let subject = partActor
verbSha body activeItems = if calmEnough body activeItems
then "notice"
else "paw distractedly"
prompt body activeItems c2 =
let (tIn, t) = ppItemDialogMode c2
in case c2 of
MStore CGround -> -- TODO: variant for actors without (unwounded) feet
makePhrase
[ MU.Capitalize $ MU.SubjectVerbSg (subject body) "notice"
, MU.Text "at"
, MU.WownW (MU.Text $ bpronoun body) $ MU.Text "feet" ]
MStore CSha ->
makePhrase
[ MU.Capitalize
$ MU.SubjectVerbSg (subject body) (verbSha body activeItems)
, MU.Text tIn
, MU.Text t ]
MStore COrgan ->
makePhrase
[ MU.Capitalize $ MU.SubjectVerbSg (subject body) "feel"
, MU.Text tIn
, MU.WownW (MU.Text $ bpronoun body) $ MU.Text t ]
MOwned ->
makePhrase
[ MU.Capitalize $ MU.SubjectVerbSg (subject body) "recall"
, MU.Text tIn
, MU.Text t ]
MStats ->
makePhrase
[ MU.Capitalize $ MU.SubjectVerbSg (subject body) "estimate"
, MU.WownW (MU.Text $ bpronoun body) $ MU.Text t ]
_ ->
makePhrase
[ MU.Capitalize $ MU.SubjectVerbSg (subject body) "see"
, MU.Text tIn
, MU.WownW (MU.Text $ bpronoun body) $ MU.Text t ]
ggi <- getStoreItem prompt c
case ggi of
Right ((iid, itemFull), c2) -> do
leader <- getLeaderUI
b <- getsState $ getActorBody leader
activeItems <- activeItemsClient leader
let calmE = calmEnough b activeItems
localTime <- getsState $ getLocalTime (blid b)
let io = itemDesc (storeFromMode c2) localTime itemFull
case c2 of
MStore COrgan -> do
let symbol = jsymbol (itemBase itemFull)
blurb | symbol == '+' = "drop temporary conditions"
| otherwise = "amputate organs"
-- TODO: also forbid on the server, except in special cases.
Left <$> overlayToSlideshow ("Can't"
<+> blurb
<> ", but here's the description.") io
MStore CSha | not calmE ->
Left <$> overlayToSlideshow "Not enough calm to take items from the shared stash, but here's the description." io
MStore fromCStore -> do
let prompt2 = "Where to move the item?"
eqpFree = eqpFreeN b
fstores :: [(K.Key, (CStore, Text))]
fstores =
filter ((/= fromCStore) . fst . snd) $
[ (K.Char 'p', (CInv, "inventory 'p'ack")) ]
++ [ (K.Char 'e', (CEqp, "'e'quipment")) | eqpFree > 0 ]
++ [ (K.Char 's', (CSha, "shared 's'tash")) | calmE ]
++ [ (K.Char 'g', (CGround, "'g'round")) ]
choice = "[" <> T.intercalate ", " (map (snd . snd) fstores)
keys = map (K.toKM K.NoModifier . K.Char) "epsg"
akm <- displayChoiceUI (prompt2 <+> choice) io keys
case akm of
Left slides -> failSlides slides
Right km -> do
case lookup (K.key km) fstores of
Nothing -> return $ Left mempty -- canceled
Just (toCStore, _) -> do
let k = itemK itemFull
kToPick | toCStore == CEqp = min eqpFree k
| otherwise = k
socK <- pickNumber True kToPick
case socK of
Left slides -> return $ Left slides
Right kChosen -> return $ Right $ ReqMoveItems
[(iid, kChosen, fromCStore, toCStore)]
MOwned -> do
-- We can't move items from MOwned, because different copies may come
-- from different stores and we can't guess player's intentions.
found <- getsState $ findIid leader (bfid b) iid
let !_A = assert (not (null found) `blame` ggi) ()
let ppLoc (_, CSha) = MU.Text $ ppCStoreIn CSha <+> "of the party"
ppLoc (b2, store) = MU.Text $ ppCStoreIn store <+> "of"
<+> bname b2
foundTexts = map ppLoc found
prompt2 = makeSentence ["The item is", MU.WWandW foundTexts]
Left <$> overlayToSlideshow prompt2 io
MStats -> assert `failure` ggi
Left slides -> return $ Left slides
| Concomitant/LambdaHack | Game/LambdaHack/Client/UI/InventoryClient.hs | bsd-3-clause | 46,152 | 646 | 37 | 14,823 | 11,822 | 6,315 | 5,507 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE RankNTypes #-}
data A
data B
data ISig e l where
Const :: Int -> ISig e A
Mult :: e A -> e A -> ISig e A
Fst, Snd :: e B -> ISig e A
data PSig e l where
Pair :: e A -> e A -> PSig e B
data Fix f l = In (f (Fix f) l)
type f ==> g = forall a. f a -> g a
class HFunctor h where
hfmap :: f ==> g -> h f ==> h g
instance HFunctor ISig where
hfmap _ (Const i) = Const i
hfmap f (Mult x y) = Mult (f x) (f y)
hfmap f (Fst x) = Fst (f x)
hfmap f (Snd x) = Snd (f x)
instance HFunctor PSig where
hfmap f (Pair x y) = Pair (f x) (f y)
data (f :+: g) (a :: * -> *) l = Inl (f a l) | Inr (g a l)
instance (HFunctor f, HFunctor g) => HFunctor (f :+: g) where
hfmap h (Inl x) = Inl (hfmap h x)
hfmap h (Inr x) = Inr (hfmap h x)
type AExpr = Fix (ISig :+: PSig) A
type BExpr = Fix (ISig :+: PSig) B
e1 :: AExpr
e1 = In (Inl (Const 3))
e2 :: AExpr
e2 = In (Inl (Const 4))
e3 :: AExpr
e3 = In (Inl (Mult e1 e2))
e4 :: BExpr
e4 = In (Inr (Pair e1 e2))
e5 :: AExpr
e5 = In (Inl (Fst e4))
type Alg f a = f a ==> a
fold :: HFunctor f => Alg f a -> Fix f ==> a
fold f (In t) = f (hfmap (fold f) t)
class HFunctor f => Eval f where
evalAlg :: f FString ==> FString
data FString e = FString String deriving Show
mult :: FString e1 -> FString e2 -> FString e3
mult (FString x) (FString y) = FString ("(" ++ x ++ " * " ++ y ++ ")")
pair :: FString e1 -> FString e2 -> FString e3
pair (FString x) (FString y) = FString ("(" ++ x ++ ", " ++ y ++ ")")
fstP :: FString e1 -> FString e2
fstP (FString x) = FString ("fst " ++ x)
sndP :: FString e1 -> FString e2
sndP (FString x) = FString ("snd " ++ x)
instance Eval ISig where
evalAlg (Const i) = FString (show i)
evalAlg (Mult x y) = mult x y
evalAlg (Fst x) = fstP x
evalAlg (Snd x) = sndP x
instance Eval PSig where
evalAlg (Pair x y) = pair x y
instance (Eval f, Eval g) => Eval (f :+: g) where
evalAlg (Inl x) = evalAlg x
evalAlg (Inr x) = evalAlg x
eval :: Eval f => Fix f ==> FString
eval = fold evalAlg
| hy-zhang/parser | experimental/DTC/DTC_HFunctor.hs | bsd-3-clause | 2,402 | 17 | 12 | 647 | 1,176 | 594 | 582 | -1 | -1 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
module Modules.Input.Setting where
import qualified Modules.Input.System as System
import Modules.Input.System(Node)
import qualified EFA.Application.Optimisation.Balance as Balance
import qualified EFA.Application.Optimisation as AppOpt
import qualified EFA.Application.Optimisation.Params as Params
import EFA.Application.Optimisation.Params(Name)
import EFA.Application.Optimisation.Sweep(Sweep)
import qualified EFA.Application.Optimisation.Sweep as Sweep
import qualified EFA.Application.Optimisation.ReqsAndDofs as ReqsAndDofs
import qualified EFA.Flow.Topology.Index as TopoIdx
import qualified EFA.Flow.State.Quantity as StateQty
import qualified EFA.Signal.Signal as Sig
import qualified EFA.Signal.Vector as SV
import qualified EFA.Signal.ConvertTable as CT
import qualified EFA.Equation.Arithmetic as Arith
import qualified Data.Map as Map; import Data.Map (Map)
import Data.Vector (Vector)
import qualified Data.Vector.Unboxed as UV
--import Data.List (transpose)
import qualified EFA.Signal.Record as Record
--import qualified EFA.Signal.ConvertTable as CT
--import qualified EFA.IO.TableParser as Table
import qualified EFA.IO.TableParserTypes as TPT
import qualified Data.NonEmpty as NonEmpty; import Data.NonEmpty ((!:))
import qualified Data.Empty as Empty
import qualified EFA.Application.Optimisation.Base as Base
import qualified EFA.Equation.Result as Result
local, rest, water, gas :: [Double]
{-
local = [0.1, 0.2 .. 3]
rest = [0.1, 0.2 .. 3]
water = [0.1, 0.2 .. 0.8]
gas = [0.1, 0.2 .. 0.8]
-}
{-
local = [1,2]
rest = [3,4]
water = [5,6]
gas = [7,8]
-}
--local = [0.1,0.3 .. 2.1] -- auch ResidualHV
--rest = [0.1, 1 .. 6.1] -- auch ResidualLV
local = [0.1,0.6 .. 6.2]
rest = [0.1,0.3 .. 2.1]
water = [0.1, 0.2 .. 0.8]
gas = [0.1, 0.2 .. 0.8]
reqs :: ReqsAndDofs.Reqs (TopoIdx.Position System.Node, [Double])
reqs = ReqsAndDofs.Reqs $
(TopoIdx.ppos System.LocalRest System.LocalNetwork, local) :
(TopoIdx.ppos System.Rest System.Network, rest) :
[]
dofs :: ReqsAndDofs.Dofs (TopoIdx.Position System.Node, [Double])
dofs = ReqsAndDofs.Dofs $
(TopoIdx.ppos System.Network System.Water, water) :
(TopoIdx.ppos System.LocalNetwork System.Gas, gas) :
[]
sweepPair ::
ReqsAndDofs.Pair ReqsAndDofs.Reqs ReqsAndDofs.Dofs
(TopoIdx.Position System.Node, [Double])
sweepPair = ReqsAndDofs.Pair reqs dofs
sweepPts ::
Map [Double]
(ReqsAndDofs.Pair (Sweep.List Sweep.Sweep UV.Vector)
(Sweep.List Sweep.Sweep UV.Vector) Double)
sweepPts = ReqsAndDofs.mkPts2 sweepPair
sweepLength :: Int
sweepLength = ReqsAndDofs.sweepLength sweepPair
noLegend :: Int -> String
noLegend = (const "")
legend :: Int -> String
legend 0 = "Laden"
legend 1 = "Entladen"
legend _ = "Undefined"
scaleTableEta :: Map Name (Double, Double)
scaleTableEta = Map.fromList $
(System.storage, (1, 0.9)) :
(System.gas, (1, 0.7)) :
(System.transformer, (3, 0.95)) :
(System.coal, (7, 0.45)) :
(System.local, (3, 1)) :
(System.rest, (3, 1)) :
[]
restScale, localScale :: Double
restScale = 0.3
localScale = 0.3
forcingMap ::
Map System.Node (Balance.SocDrive Double)
forcingMap = Map.fromList $
(System.Water, Balance.ChargeDrive (-0.12)) :
[]
varRestPower', varLocalPower' :: [[Double]]
(varLocalPower', varRestPower') = CT.varMat local rest
-- ist die x-Achse
varRestPower1D :: Sig.PSignal UV.Vector Double
varRestPower1D = Sig.fromList rest
varLocalPower1D :: Sig.PSignal UV.Vector Double
varLocalPower1D = Sig.fromList local
varRestPower :: Sig.PSignal2 Vector UV.Vector Double
varRestPower = Sig.fromList2 $ varRestPower'
varLocalPower :: Sig.PSignal2 Vector UV.Vector Double
varLocalPower = Sig.fromList2 $ varLocalPower'
initStorageState :: (Arith.Constant a) => Params.InitStorageState System.Node a
initStorageState =
Params.InitStorageState $ Map.fromList [(System.Water, Arith.fromRational $ 1000)] --0.7*3600*1000)]
initStorageSeq :: (Arith.Constant a) => Params.InitStorageSeq System.Node a
initStorageSeq =
Params.InitStorageSeq $ Map.fromList [(System.Water, Arith.fromRational 1000)]
initEnv :: StateQty.Graph Node
(Result.Result (Sweep UV.Vector Double))
(Result.Result (Sweep UV.Vector Double))
initEnv = AppOpt.storageEdgeXFactors optParams 3 3
$ AppOpt.initialEnv optParams System.stateFlowGraph
etaMap :: TPT.Map Double ->
Map Name (Params.EtaFunction Double Double)
etaMap tabEta = Map.map Params.EtaFunction $
Map.mapKeys Params.Name $
CT.makeEtaFunctions2D
(Map.mapKeys Params.unName scaleTableEta)
tabEta
reqsRec :: (SV.FromList v, SV.Storage v Double,
SV.Convert UV.Vector v) =>
Map String (TPT.T Double) -> Record.PowerRecord Node v Double
reqsRec tabPower =
let (time,
NonEmpty.Cons l
(NonEmpty.Cons r Empty.Cons)) =
CT.getPowerSignalsWithSameTime tabPower
("rest" !: "local" !: Empty.Cons)
ctime = Sig.convert time
pLocal = Sig.offset 0.1 . Sig.scale 3 $ Sig.convert $ l
pRest = Sig.offset 0.2 . Sig.scale 1.3 $ Sig.convert $ r
rRec :: Record.PowerRecord Node UV.Vector Double
rRec = Record.Record ctime (Map.fromList (zip reqsPos [pLocal,pRest]))
-- reqsRec = Record.scatterRnd rndGen 10 0.3 $ Record.Record ctime (Map.fromList (zip reqsPos [pLocal,pRest]))
rRecStep :: Record.PowerRecord Node UV.Vector Double
rRecStep = Record.makeStepped rRec
in Record.makeStepped $ Base.convertRecord rRecStep
reqsPos :: [TopoIdx.Position Node]
reqsPos = ReqsAndDofs.unReqs $ ReqsAndDofs.reqsPos reqs
{-
supportPoints =
Base.supportPoints
[ TopoIdx.ppos System.LocalRest System.LocalNetwork,
TopoIdx.ppos System.Rest System.Network ]
(Base.convertRecord reqsRecStep)
(map (Sig.findSupportPoints. Sig.untype)
[ ModSet.varLocalPower1D, ModSet.varRestPower1D])
-}
------------------------------------------------------------------------
sysParams :: TPT.Map Double -> Params.System Node Double
sysParams tabEta = Params.System {
Params.systemTopology = System.topology,
Params.labeledTopology = System.labeledTopology,
Params.etaTable = tabEta,
Params.etaAssignMap = System.etaAssignMap,
Params.etaMap =etaMap tabEta,
Params.scaleTableEta = scaleTableEta,
Params.storagePositions = ([TopoIdx.ppos System.Water System.Network]),
Params.initStorageState = initStorageState,
Params.initStorageSeq = initStorageSeq }
optParams :: Params.Optimisation Node [] Sweep UV.Vector Double
optParams = Params.Optimisation {
Params.reqsPos = (ReqsAndDofs.reqsPos reqs),
Params.dofsPos = (ReqsAndDofs.dofsPos dofs),
Params.points = sweepPts,
Params.sweepLength = sweepLength,
Params.etaToOptimise = Nothing,
Params.maxEtaIterations = Params.MaxEtaIterations 5,
Params.maxBalanceIterations = Params.MaxBalanceIterations 100,
Params.initialBattForcing =
Balance.ForcingMap
$ Map.fromList [(System.Water, Balance.DischargeDrive 1)],
Params.initialBattForceStep =
Balance.ForcingMap
$ Map.fromList [(System.Water, Balance.ChargeDrive 0.1)],
Params.etaThreshold = Params.EtaThreshold 0.2,
Params.balanceThreshold = Params.BalanceThreshold 0.5,
Params.balanceForcingSeed = Balance.ChargeDrive 0.01 }
simParams :: Record.PowerRecord Node [] Double -> Params.Simulation Node [] Double
simParams rRec = Params.Simulation {
Params.varReqRoomPower1D = Sig.convert $ varLocalPower1D,
Params.varReqRoomPower2D = Sig.convert $ varRestPower ,
Params.reqsRec = rRec, -- Base.convertRecord reqsRecStep,
Params.requirementGrid = [ Sig.convert $ varLocalPower1D,
Sig.convert $ varRestPower1D ],
-- Params.activeSupportPoints = supportPoints,
Params.sequFilterTime=0.01,
Params.sequFilterEnergy=0 }
| energyflowanalysis/efa-2.1 | examples/advanced/energy/src/Modules/Input/Setting.hs | bsd-3-clause | 7,986 | 0 | 14 | 1,385 | 2,085 | 1,183 | 902 | 161 | 1 |
{-# LANGUAGE QuasiQuotes #-}
-- Advent of Code
---- Day 18: Like a GIF for your yard
module AOC2015.Day18 where
-- Part 1 is basically Conways Game of Life
import Data.Array.Repa ((:.) (..), Array, DIM2, U,
Z (..))
import qualified Data.Array.Repa as R
import Data.Array.Repa.Stencil (Boundary (..), Stencil)
import Data.Array.Repa.Stencil.Dim2 (makeStencil2, mapStencil2,
stencil2)
import Data.Bits (Bits (..), (.|.))
import Data.Vector.Unboxed.Base (Unbox)
type Lights a = Array U DIM2 a
stuck :: (Bits a, Num a, Unbox a) => R.DIM2 -> Lights a -> Lights a
stuck e = R.computeS . R.zipWith (.|.) (stuckLights e)
stuckLights :: (Num a, Unbox a) => R.DIM2 -> Lights a
stuckLights sh = R.fromListUnboxed sh [corner x | x <- [1..s]]
where
s = R.size sh
i = truncate $ sqrt $ fromIntegral s
corner 1 = 1
corner n
| n == i = 1
| n == s = 1
| n == (s - i) + 1 = 1
| otherwise = 0
animate :: Lights Int -> Lights Int
animate grid = R.computeS $ R.zipWith step grid adjacent
where
adjacent = mapStencil2 (BoundConst 0) stencil grid
step :: Int -> Int -> Int
step 1 2 = 1
step 1 3 = 1
step 0 3 = 1
step _ _ = 0
stencil :: Stencil DIM2 Int
stencil = [stencil2| 1 1 1
1 0 1
1 1 1 |]
initGrid :: (Num a, Unbox a) => String -> Lights a
initGrid s = R.fromListUnboxed (Z :. size :. size :: R.DIM2) lights
where
scrubbed = filter (/= '\n') s
size = truncate . sqrt . fromIntegral $ length scrubbed
lights = toLight <$> scrubbed
toLight '#' = 1
toLight _ = 0
animateLights :: String -> Int -> Int
animateLights s n = R.sumAllS $ iterate animate (initGrid s) !! n
animateStuckLights :: String -> Int -> Int
animateStuckLights s n = R.sumAllS $ iterate (stuck e . animate) g' !! n
where
g = initGrid s
e = R.extent g
g' = stuck e g
answers :: IO ()
answers = do
i <- readFile "inputs/is2015/day18-input.txt"
let part1 = animateLights i 100
putStrLn $ "Part One: " ++ show part1
let part2 = animateStuckLights i 100
putStrLn $ "Part Two: " ++ show part2
| bitrauser/aoc | src/AOC2015/Day18.hs | bsd-3-clause | 2,345 | 0 | 13 | 786 | 821 | 435 | 386 | 54 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
module AuthServer where
import System.Random
import Control.Monad.Trans.Except
import Control.Monad.Trans.Resource
import Control.Monad.IO.Class
import Data.Aeson
import Data.Aeson.TH
import Data.Bson.Generic
import Data.List.Split
import GHC.Generics
import Network.Wai hiding(Response)
import Network.Wai.Handler.Warp
import Network.Wai.Logger
import Servant
import Servant.API
import Servant.Client
import System.IO
import System.Directory
import System.Environment (getArgs, getProgName, lookupEnv)
import System.Log.Formatter
import System.Log.Handler (setFormatter)
import System.Log.Handler.Simple
import System.Log.Handler.Syslog
import System.Log.Logger
import Data.Bson.Generic
import qualified Data.List as DL
import Data.Maybe (catMaybes, fromJust)
import Data.Text (pack, unpack)
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import Database.MongoDB
import Control.Monad (when)
import Network.HTTP.Client (newManager, defaultManagerSettings)
import Data.UUID.V1
import Data.UUID hiding (null)
import Data.Time
data Response = Response{
response :: String
} deriving (Eq, Show, Generic)
instance ToJSON Response
instance FromJSON Response
data User = User{
uusername :: String,
upassword :: String,
timeout :: String,
token :: String
} deriving (Eq, Show, Generic)
instance ToJSON User
instance FromJSON User
instance ToBSON User
instance FromBSON User
data Signin = Signin{
susername :: String,
spassword :: String
} deriving (Eq, Show, Generic)
instance ToJSON Signin
instance FromJSON Signin
instance ToBSON Signin
instance FromBSON Signin
type ApiHandler = ExceptT ServantErr IO
serverport :: String
serverport = "8082"
serverhost :: String
serverhost = "localhost"
type AuthApi =
"signin" :> ReqBody '[JSON] Signin :> Post '[JSON] User :<|>
"register" :> ReqBody '[JSON] Signin :> Post '[JSON] Response :<|>
"isvalid" :> ReqBody '[JSON] User :> Post '[JSON] Response :<|>
"extend" :> ReqBody '[JSON] User :> Post '[JSON] Response
authApi :: Proxy AuthApi
authApi = Proxy
server :: Server AuthApi
server =
login :<|>
newuser :<|>
checkToken :<|>
extendToken
authApp :: Application
authApp = serve authApi server
mkApp :: IO()
mkApp = do
run (read (serverport) ::Int) authApp
login :: Signin -> ApiHandler User
login signin = liftIO $ do
let uname = susername signin
let psswrd = spassword signin
warnLog $ "Searching for value for key: " ++ uname ++ ", " ++ psswrd
user <- withMongoDbConnection $ do
docs <- find (select ["_id" =: (uname+psswrd)] "USER_RECORD") >>= drainCursor
return $ catMaybes $ DL.map (\ b -> fromBSON b :: Maybe Signin) docs
let thisuser = head $ user
putStrLn (show thisuser)
a <- nextUUID
let tokener = Data.UUID.toString $ fromJust a
currentTime <- getCurrentTime
currentZone <- getCurrentTimeZone
let fiveMinutes = 5 * 60
let newTime = addUTCTime fiveMinutes currentTime
let timeouter = utcToLocalTime currentZone newTime
let finaltimeout = show timeouter
warnLog $ "Storing Session key under key " ++ uname ++ "."
let session = (User (susername thisuser) (spassword thisuser) finaltimeout tokener)
withMongoDbConnection $ upsert (select ["_id" =: uname] "SESSION_RECORD") $ toBSON session
warnLog $ "Session Successfully Stored."
return (session)
newuser :: Signin -> ApiHandler Response
newuser signin = liftIO $ do
let uname = susername signin
let psswrd = spassword signin
warnLog $ "Storing value under key: " ++ uname
let user = (Signin uname psswrd)
withMongoDbConnection $ upsert (select ["_id" =: (uname+psswrd)] "USER_RECORD") $ toBSON user
return (Response "Success")
checkToken :: User -> ApiHandler Response
checkToken user = liftIO $ do
let uname = uusername user
let tokener = token user
warnLog $ "Searching for user: " ++ uname
session <- withMongoDbConnection $ do
docs <- find (select ["_id" =: uname] "SESSION_RECORD") >>= drainCursor
return $ catMaybes $ DL.map (\ b -> fromBSON b :: Maybe User) docs
warnLog $ "User found" ++ (show session)
let thissession = head $ session
let senttoken = token user
let storedtoken = token thissession
case senttoken == storedtoken of
False -> return (Response "Token not valid")
True -> do let tokentimeout = timeout thissession
currentTime <- getCurrentTime
currentZone <- getCurrentTimeZone
let localcurrentTime = show (utcToLocalTime currentZone currentTime)
let tokentimeoutsplit = splitOn " " $ tokentimeout
let localcurrentTimesplit = splitOn " " $ localcurrentTime
case ((tokentimeoutsplit !! 0) == (localcurrentTimesplit !! 0)) of
False -> return (Response "Current date not equal to token date")
True -> do let localcurrenthours = localcurrentTimesplit !! 1
let tokenhours = tokentimeoutsplit !! 1
let localhour = read(((splitOn ":" $ localcurrenthours) !! 0))
let tokenhour = read(((splitOn ":" $ tokenhours) !! 0))
let tokenminutes = read(((splitOn ":" $ tokenhours) !! 1))
let currentminutes = read(((splitOn ":" $ localcurrenthours) !! 1))
let totaltokenminutes = (tokenhour * 60) + tokenminutes
let totalcurrentminutes = (localhour * 60) + currentminutes
case totaltokenminutes > totalcurrentminutes of
False -> return (Response "Token Timeout")
True -> return (Response "Token is Valid")
extendToken :: User -> ApiHandler Response
extendToken user = liftIO $ do
currentTime <- getCurrentTime
currentZone <- getCurrentTimeZone
let fiveMinutes = 5 * 60
let newTime = addUTCTime fiveMinutes currentTime
let timeouter = utcToLocalTime currentZone newTime
let finaltimeout = show timeouter
warnLog $ "Storing Session key under key " ++ (uusername user) ++ "."
let session = (User (uusername user) (upassword user) finaltimeout (token user))
withMongoDbConnection $ upsert (select ["_id" =: (uusername user)] "SESSION_RECORD") $ toBSON session
warnLog $ "Session Successfully Stored."
return (Response "Success")
-- | Logging stuff
iso8601 :: UTCTime -> String
iso8601 = formatTime defaultTimeLocale "%FT%T%q%z"
-- global loggin functions
debugLog, warnLog, errorLog :: String -> IO ()
debugLog = doLog debugM
warnLog = doLog warningM
errorLog = doLog errorM
noticeLog = doLog noticeM
doLog f s = getProgName >>= \ p -> do
t <- getCurrentTime
f p $ (iso8601 t) ++ " " ++ s
withLogging act = withStdoutLogger $ \aplogger -> do
lname <- getProgName
llevel <- logLevel
updateGlobalLogger lname
(setLevel $ case llevel of
"WARNING" -> WARNING
"ERROR" -> ERROR
_ -> DEBUG)
act aplogger
-- | Mongodb helpers...
-- | helper to open connection to mongo database and run action
-- generally run as follows:
-- withMongoDbConnection $ do ...
--
withMongoDbConnection :: Action IO a -> IO a
withMongoDbConnection act = do
ip <- mongoDbIp
port <- mongoDbPort
database <- mongoDbDatabase
pipe <- connect (host ip)
ret <- runResourceT $ liftIO $ access pipe master (pack database) act
Database.MongoDB.close pipe
return ret
-- | helper method to ensure we force extraction of all results
-- note how it is defined recursively - meaning that draincursor' calls itself.
-- the purpose is to iterate through all documents returned if the connection is
-- returning the documents in batch mode, meaning in batches of retruned results with more
-- to come on each call. The function recurses until there are no results left, building an
-- array of returned [Document]
drainCursor :: Cursor -> Action IO [Document]
drainCursor cur = drainCursor' cur []
where
drainCursor' cur res = do
batch <- nextBatch cur
if null batch
then return res
else drainCursor' cur (res ++ batch)
-- | Environment variable functions, that return the environment variable if set, or
-- default values if not set.
-- | The IP address of the mongoDB database that devnostics-rest uses to store and access data
mongoDbIp :: IO String
mongoDbIp = defEnv "MONGODB_IP" Prelude.id "127.0.0.1" True
-- | The port number of the mongoDB database that devnostics-rest uses to store and access data
mongoDbPort :: IO Integer
mongoDbPort = defEnv "MONGODB_PORT" read 27017 False -- 27017 is the default mongodb port
-- | The name of the mongoDB database that devnostics-rest uses to store and access data
mongoDbDatabase :: IO String
mongoDbDatabase = defEnv "MONGODB_DATABASE" Prelude.id "USEHASKELLDB" True
-- | Determines log reporting level. Set to "DEBUG", "WARNING" or "ERROR" as preferred. Loggin is
-- provided by the hslogger library.
logLevel :: IO String
logLevel = defEnv "LOG_LEVEL" Prelude.id "DEBUG" True
-- | Helper function to simplify the setting of environment variables
-- function that looks up environment variable and returns the result of running funtion fn over it
-- or if the environment variable does not exist, returns the value def. The function will optionally log a
-- warning based on Boolean tag
defEnv :: Show a
=> String -- Environment Variable name
-> (String -> a) -- function to process variable string (set as 'id' if not needed)
-> a -- default value to use if environment variable is not set
-> Bool -- True if we should warn if environment variable is not set
-> IO a
defEnv env fn def doWarn = lookupEnv env >>= \ e -> case e of
Just s -> return $ fn s
Nothing -> do
when doWarn (doLog warningM $ "Environment variable: " ++ env ++
" is not set. Defaulting to " ++ (show def))
return def
| Garygunn94/DFS | AuthServer/.stack-work/intero/intero7092bvy.hs | bsd-3-clause | 11,103 | 220 | 18 | 3,039 | 2,518 | 1,356 | 1,162 | 224 | 4 |
-- | C and SystemC RTL Generation
module RTL.C
( generateC
) where
import RTL.Types
generateC :: IO ()
generateC = putStrLn "Generating C..."
| tomahawkins/trs | attic/RTL/C.hs | bsd-3-clause | 150 | 0 | 6 | 32 | 35 | 20 | 15 | 5 | 1 |
--
-- Copyright © 2013-2015 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Network.Druid.Query.DSLSpec where
import Network.Druid.Query.DSL
import Data.Aeson
import Data.Aeson.QQ
import Data.Time.QQ
import Test.Hspec
-- * Data source
data SampleDS = SampleDS
-- * Dimensions
data CarrierD = CarrierD
data MakeD = MakeD
data DeviceD = DeviceD
-- * Metrics
data UserCountM = UserCountM
data DataTransferM = DataTransferM
-- * Mapping to schema
instance DataSource SampleDS where
dataSourceName _ = "sample_datasource"
instance Dimension CarrierD where
dimensionName _ = "carrier"
instance Dimension DeviceD where
dimensionName _ = "device"
instance Dimension MakeD where
dimensionName _ = "make"
instance Metric UserCountM where
metricName _ = "user_count"
instance Metric DataTransferM where
metricName _ = "data_transfer"
-- * Relationships
instance HasDimension SampleDS CarrierD
instance HasDimension SampleDS MakeD
instance HasDimension SampleDS DeviceD
instance HasMetric SampleDS UserCountM
instance HasMetric SampleDS DataTransferM
groupByQueryL :: QueryF SampleDS ()
groupByQueryL = do
filterF $ filterSelector CarrierD "AT&T"
filterF $ filterOr [ filterSelector MakeD "Apple"
, filterSelector MakeD "Samsung"
]
letF (doubleSum DataTransferM) $ \transfer ->
letF (longSum UserCountM) $ \user ->
postAggregationF "usage_transfer" $ user |*| transfer
groupByQueryV :: Value
groupByQueryV = [aesonQQ|
{
"postAggregations" : [
{
"fields" : [
{
"fieldName" : "__var_1",
"type" : "fieldAccess"
},
{
"type" : "fieldAccess",
"fieldName" : "__var_0"
}
],
"name" : "usage_transfer",
"fn" : "*",
"type" : "arithmetic"
}
],
"queryType" : "groupBy",
"dataSource" : "sample_datasource",
"intervals" : [
"2012-01-01T00:00:00/2012-01-03T00:00:00"
],
"granularity" : "day",
"dimensions" : [
"carrier",
"device"
],
"aggregations" : [
{
"name" : "__var_0",
"fieldName" : "data_transfer",
"type" : "doubleSum"
},
{
"name" : "__var_1",
"fieldName" : "user_count",
"type" : "longSum"
}
],
"filter" : {
"fields" : [
{
"value" : "AT&T",
"type" : "selector",
"dimension" : "carrier"
},
{
"type" : "or",
"fields" : [
{
"dimension" : "make",
"type" : "selector",
"value" : "Apple"
},
{
"dimension" : "make",
"value" : "Samsung",
"type" : "selector"
}
]
}
],
"type" : "and"
}
}
|]
spec :: Spec
spec =
describe "ideal DSL" $
it "builds correct query" $ do
let q = groupByQuery SampleDS
[ SomeDimension CarrierD
, SomeDimension DeviceD
]
GranularityDay
[ Interval [utcIso8601| 2012-01-01 |]
[utcIso8601| 2012-01-03 |] ]
groupByQueryL
toJSON q `shouldBe` groupByQueryV
| anchor/druid-query | tests/Network/Druid/Query/DSLSpec.hs | bsd-3-clause | 3,872 | 1 | 14 | 1,423 | 436 | 238 | 198 | 54 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Database.Cassandra.Basic
-- Copyright : Ozgun Ataman
-- License : BSD3
--
-- Maintainer : Ozgun Ataman
-- Stability : experimental
--
-- Low-level functionality for working with Cassandra at the most
-- basic level.
----------------------------------------------------------------------------
module Database.Cassandra.Basic
(
-- * Connection
CPool
, Server
, defServer
, defServers
, KeySpace
, createCassandraPool
-- * MonadCassandra Typeclass
, MonadCassandra (..)
, Cas (..)
, runCas
, transCas
, mapCassandra
-- * Cassandra Operations
, getCol
, get
, getMulti
, insert
, delete
-- * Retrying Queries
, retryCas
, casRetryH
, networkRetryH
-- * Filtering
, Selector(..)
, range
, boundless
, Order(..)
, reverseOrder
, KeySelector(..)
, KeyRangeType(..)
-- * Exceptions
, CassandraException(..)
-- * Utility
, getTime
, throwing
, wrapException
-- * Basic Types
, ColumnFamily
, Key
, ColumnName
, Value
, Column(..)
, col
, packCol
, unpackCol
, packKey
, Row
, ConsistencyLevel(..)
-- * Helpers
, CKey (..)
, fromColKey'
-- * Cassandra Column Key Types
, module Database.Cassandra.Pack
) where
-------------------------------------------------------------------------------
import Control.Applicative
import Control.Concurrent.Async
import Control.Monad
import Control.Monad.Catch
import Control.Monad.Reader
import Control.Retry as R
import Data.ByteString.Lazy (ByteString)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import Data.Traversable (Traversable)
import qualified Database.Cassandra.Thrift.Cassandra_Client as C
import Database.Cassandra.Thrift.Cassandra_Types (ConsistencyLevel (..))
import qualified Database.Cassandra.Thrift.Cassandra_Types as T
import Prelude hiding (catch)
-------------------------------------------------------------------------------
import Database.Cassandra.Pack
import Database.Cassandra.Pool
import Database.Cassandra.Types
-------------------------------------------------------------------------------
-- test = do
-- pool <- createCassandraPool [("127.0.0.1", 9160)] 3 300 "Keyspace1"
-- withResource pool $ \ Cassandra{..} -> do
-- let cp = T.ColumnParent (Just "CF1") Nothing
-- let sr = Just $ T.SliceRange (Just "") (Just "") (Just False) (Just 100)
-- let ks = Just ["eben"]
-- let sp = T.SlicePredicate Nothing sr
-- C.get_slice (cProto, cProto) "darak" cp sp ONE
-- flip runCas pool $ do
-- get "CF1" "CF1" All ONE
-- getCol "CF1" "darak" "eben" ONE
-- insert "CF1" "test1" ONE [col "col1" "val1", col "col2" "val2"]
-- get "CF1" "CF1" All ONE >>= liftIO . print
-- get "CF1" "not here" All ONE >>= liftIO . print
-- delete "CF1" "CF1" (ColNames ["col2"]) ONE
-- get "CF1" "CF1" (Range Nothing Nothing Reversed 1) ONE >>= liftIO . putStrLn . show
-------------------------------------------------------------------------------
-- | All Cassy operations are designed to run inside 'MonadCassandra'
-- context.
--
-- We provide a default concrete 'Cas' datatype, but you can simply
-- make your own application monads an instance of 'MonadCassandra'
-- for conveniently using all operations of this package.
--
-- Please keep in mind that all Cassandra operations may raise
-- 'CassandraException's at any point in time.
class (MonadIO m) => MonadCassandra m where
getCassandraPool :: m CPool
-------------------------------------------------------------------------------
-- | Run a list of cassandra computations in parallel using the async library
mapCassandra :: (Traversable t, MonadCassandra m) => t (Cas b) -> m (t b)
mapCassandra ms = do
cp <- getCassandraPool
let f m = runCas cp m
liftIO $ mapConcurrently f ms
-------------------------------------------------------------------------------
withCassandraPool :: MonadCassandra m => (Cassandra -> IO b) -> m b
withCassandraPool f = do
p <- getCassandraPool
liftIO $ withResource p f
-------------------------------------------------------------------------------
type Cas a = ReaderT CPool IO a
-------------------------------------------------------------------------------
-- | Main running function when using the ad-hoc Cas monad. Just write
-- your cassandra actions within the 'Cas' monad and supply them with
-- a 'CPool' to execute.
runCas :: CPool -> Cas a -> IO a
runCas = flip runReaderT
-- | Unwrap a Cassandra action and return an IO continuation that can
-- then be run in a pure IO context.
--
-- This is useful when you design all your functions in a generic form
-- with 'MonadCassandra' m constraints and then one day need to feed
-- your function to a utility that can only run in an IO context. This
-- function is then your friendly utility for extracting an IO action.
transCas :: MonadCassandra m => Cas a -> m (IO a)
transCas m = do
cp <- getCassandraPool
return $ runCas cp m
-------------------------------------------------------------------------------
instance (MonadIO m) => MonadCassandra (ReaderT CPool m) where
getCassandraPool = ask
------------------------------------------------------------------------------
-- | Get a single key-column value.
getCol
:: (MonadCassandra m, CasType k)
=> ColumnFamily
-> ByteString
-- ^ Row key
-> k
-- ^ Column/SuperColumn key; see 'CasType' for what it can be. Use
-- ByteString in the simple case.
-> ConsistencyLevel
-- ^ Read quorum
-> m (Maybe Column)
getCol cf k cn cl = do
res <- get cf k (ColNames [encodeCas cn]) cl
case res of
[] -> return Nothing
x:_ -> return $ Just x
------------------------------------------------------------------------------
-- | An arbitrary get operation - slice with 'Selector'
get
:: (MonadCassandra m)
=> ColumnFamily
-- ^ in ColumnFamily
-> ByteString
-- ^ Row key to get
-> Selector
-- ^ Slice columns with selector
-> ConsistencyLevel
-> m [Column]
get cf k s cl = withCassandraPool $ \ Cassandra{..} -> do
res <- wrapException $ C.get_slice (cProto, cProto) k cp (mkPredicate s) cl
throwing . return $ mapM castColumn res
where
cp = T.ColumnParent (Just cf) Nothing
------------------------------------------------------------------------------
-- | Do multiple 'get's in one DB hit
getMulti
:: (MonadCassandra m)
=> ColumnFamily
-> KeySelector
-- ^ A selection of rows to fetch in one hit
-> Selector
-- ^ Subject to column selector conditions
-> ConsistencyLevel
-> m (Map ByteString Row)
-- ^ A Map from Row keys to 'Row's is returned
getMulti cf ks s cl = withCassandraPool $ \ Cassandra{..} -> do
case ks of
Keys xs -> do
res <- wrapException $ C.multiget_slice (cProto, cProto) xs cp (mkPredicate s) cl
return $ M.mapMaybe f res
KeyRange {} -> do
res <- wrapException $
C.get_range_slices (cProto, cProto) cp (mkPredicate s) (mkKeyRange ks) cl
return $ collectKeySlices res
where
collectKeySlices :: [T.KeySlice] -> Map ByteString Row
collectKeySlices xs = M.fromList $ mapMaybe collectKeySlice xs
collectKeySlice (T.KeySlice (Just k) (Just xs)) =
case mapM castColumn xs of
Left _ -> Nothing
Right xs' -> Just (k, xs')
collectKeySlice _ = Nothing
cp = T.ColumnParent (Just cf) Nothing
f xs =
case mapM castColumn xs of
Left _ -> Nothing
Right xs' -> Just xs'
------------------------------------------------------------------------------
-- | Insert an entire row into the db.
--
-- This will do as many round-trips as necessary to insert the full
-- row. Please keep in mind that each column and each column of each
-- super-column is sent to the server one by one.
--
-- > insert "testCF" "row1" ONE [packCol ("column key", "some column content")]
insert
:: (MonadCassandra m)
=> ColumnFamily
-> ByteString
-- ^ Row key
-> ConsistencyLevel
-> [Column]
-- ^ best way to make these columns is through "packCol"
-> m ()
insert cf k cl row = withCassandraPool $ \ Cassandra{..} -> do
let insCol cp c = do
c' <- mkThriftCol c
wrapException $ C.insert (cProto, cProto) k cp c' cl
forM_ row $ \ c -> do
case c of
Column{} -> do
let cp = T.ColumnParent (Just cf) Nothing
insCol cp c
SuperColumn cn cols -> do
let cp = T.ColumnParent (Just cf) (Just cn)
mapM_ (insCol cp) cols
-------------------------------------------------------------------------------
-- | Pack key-value pair into 'Column' form ready to be written to Cassandra
packCol :: CasType k => (k, ByteString) -> Column
packCol (k, v) = col (packKey k) v
-------------------------------------------------------------------------------
-- | Unpack a Cassandra 'Column' into a more convenient (k,v) form
unpackCol :: CasType k => Column -> (k, Value)
unpackCol (Column k v _ _) = (decodeCas k, v)
unpackCol _ = error "unpackcol unimplemented for SuperColumn types"
-------------------------------------------------------------------------------
-- | Pack a column key into binary, ready for submission to Cassandra
packKey :: CasType a => a -> ByteString
packKey = encodeCas
------------------------------------------------------------------------------
-- | Delete an entire row, specific columns or a specific sub-set of columns
-- within a SuperColumn.
delete
:: (MonadCassandra m)
=> ColumnFamily
-- ^ In 'ColumnFamily'
-> Key
-- ^ Key to be deleted
-> Selector
-- ^ Columns to be deleted
-> ConsistencyLevel
-> m ()
delete cf k s cl = withCassandraPool $ \ Cassandra {..} -> do
now <- getTime
wrapException $ case s of
All -> C.remove (cProto, cProto) k cpAll now cl
ColNames cs -> forM_ cs $ \c -> do
C.remove (cProto, cProto) k (cpCol c) now cl
SupNames sn cs -> forM_ cs $ \c -> do
C.remove (cProto, cProto) k (cpSCol sn c) now cl
Range{} -> error "delete: Range delete not implemented"
where
-- wipe out the entire row
cpAll = T.ColumnPath (Just cf) Nothing Nothing
-- just a single column
cpCol name = T.ColumnPath (Just cf) Nothing (Just (encodeCas name))
-- scope column by supercol
cpSCol sc name = T.ColumnPath (Just cf) (Just (encodeCas sc)) (Just (encodeCas name))
------------------------------------------------------------------------------
-- | Wrap exceptions of the underlying thrift library into the
-- exception types defined here.
wrapException :: IO a -> IO a
wrapException a = f
where
f = a
`catch` (\ (T.NotFoundException) -> throwM NotFoundException)
`catch` (\ (T.InvalidRequestException e) ->
throwM . InvalidRequestException $ maybe "" id e)
`catch` (\ T.UnavailableException -> throwM UnavailableException)
`catch` (\ T.TimedOutException -> throwM TimedOutException)
`catch` (\ (T.AuthenticationException e) ->
throwM . AuthenticationException $ maybe "" id e)
`catch` (\ (T.AuthorizationException e) ->
throwM . AuthorizationException $ maybe "" id e)
`catch` (\ T.SchemaDisagreementException -> throwM SchemaDisagreementException)
-------------------------------------------------------------------------------
-- | Make exceptions implicit.
throwing :: IO (Either CassandraException a) -> IO a
throwing f = do
res <- f
case res of
Left e -> throwM e
Right a -> return a
-- | 'retrying' with direct cassandra support. Server-related failures
-- will be retried.
--
-- 'UnavailableException', 'TimedOutException' and
-- 'SchemaDisagreementException' will be automatically retried.
retryCas :: (MonadMask m, MonadIO m)
=> RetryPolicy
-- ^ For default settings, just use 'def'
-> m a
-- ^ Action to perform
-> m a
retryCas set f = R.recovering set [casRetryH, networkRetryH] (const f)
| Soostone/cassy | src/Database/Cassandra/Basic.hs | bsd-3-clause | 12,974 | 0 | 23 | 3,064 | 2,427 | 1,329 | 1,098 | 214 | 5 |
{-# LANGUAGE RecordWildCards #-}
module Dots where
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Monoid
import Graphics.Gloss
import Graphics.Gloss.Data.Vector
import Network.WebSockets
import Text.Read
-- | Player's name.
type Name = String
-- | A color for the 'Dot'.
newtype DotColor = DotColor { getDotColor :: Color }
instance Show DotColor where
show (DotColor c) = show (rgbaOfColor c)
instance Read DotColor where
readPrec = fmap (DotColor . uncurry4 makeColor) readPrec
where uncurry4 f (a, b, c, d) = f a b c d
-- | A dot. Each dot represents a player.
data Dot = Dot
{ dotPosition :: Point -- ^ Dot position.
, dotSpeed :: Vector -- ^ Dot speed.
, dotColor :: DotColor -- ^ Dot color.
} deriving (Show, Read)
-- | A universe all 'Dot's live in.
data Universe = Universe
{ universeDots :: Map Name Dot -- ^ All 'Dot's in the universe, by player name.
} deriving (Show, Read)
-- | An empty 'Universe'.
emptyUniverse :: Universe
emptyUniverse = Universe Map.empty
-- | Move a 'Dot' using its speed.
moveDot :: Float -> Dot -> Dot
moveDot dt dot = moveDotByVector (mulSV dt (dotSpeed dot)) dot
-- | Move a 'Dot' by a given 'Vector'.
moveDotByVector :: Vector -> Dot -> Dot
moveDotByVector (dx, dy) dot@Dot{ dotPosition = (x, y) }
= dot { dotPosition = (x + dx, y + dy) }
-- | Accelerate 'Dot' by a given 'Vector'.
accelDotByVector :: Vector -> Dot -> Dot
accelDotByVector (dx, dy) dot@Dot{ dotSpeed = (x, y) }
= dot { dotSpeed = (x + dx, y + dy) }
-- | Directions.
data Dir
= L -- ^ Left.
| R -- ^ Right.
| U -- ^ Up.
| D -- ^ Down.
deriving (Show, Read)
-- | A unit vector pointing in a given direction.
dirVector :: Dir -> Vector
dirVector L = (-1, 0)
dirVector R = ( 1, 0)
dirVector U = ( 0, 1)
dirVector D = ( 0, -1)
-- | Draw the whole 'Universe'.
drawUniverse :: Universe -> Picture
drawUniverse = foldMap drawDotWithName . Map.toList . universeDots
-- | Draw a single 'Dot' with its name just above.
drawDotWithName :: (Name, Dot) -> Picture
drawDotWithName (name, Dot{..}) =
color (getDotColor dotColor) $
uncurry translate dotPosition $
drawName <> drawDot
where
drawName = translate 0 3 (scale 0.1 0.1 (text name))
drawDot = thickCircle 1 1
-- | Update all 'Dot's in the 'Universe'.
updateUniverse :: Float -> Universe -> Universe
updateUniverse dt (Universe u) = Universe (fmap (moveDot dt) u)
-- | Player actions.
data Action
= ActionAccel Dir -- ^ Accelerate in a given direction.
deriving (Show, Read)
-- | Handle a player's 'Action' and update the 'Universe' accordingly.
handlePlayerAction :: Name -> Action -> Universe -> Universe
handlePlayerAction name (ActionAccel dir) (Universe u)
= Universe (Map.adjust (accelDotByVector (dirVector dir)) name u)
-- | A list of different 'DotColor's.
defaultDotColors :: [DotColor]
defaultDotColors = map DotColor [blue, green, red, white, yellow, cyan, magenta, rose, violet, azure, aquamarine, chartreuse, orange]
-- | Add a new player to the 'Universe'.
addPlayer :: Name -> DotColor -> Universe -> Universe
addPlayer name dcolor (Universe u) = Universe (Map.insert name (Dot (0, 0) (0, 0) dcolor) u)
-- =====================================
-- WebSockersData instances are needed
-- to send/receive Haskell structures
-- over websockets
-- =====================================
instance WebSocketsData Action where
fromLazyByteString = read . BL8.unpack
toLazyByteString = BL8.pack . show
instance WebSocketsData Universe where
fromLazyByteString = read . BL8.unpack
toLazyByteString = BL8.pack . show
| fizruk/dots-game | src/Dots.hs | bsd-3-clause | 3,660 | 0 | 11 | 709 | 1,013 | 576 | 437 | 73 | 1 |
module B1.Program.Prices.Main
( main
) where
import Data.Either
import Data.Time
import System.Environment
import B1.Data.Price
import B1.Data.Price.Google
import B1.Data.Price.Mock
import B1.Data.Technicals.Stochastic
import B1.Data.Technicals.StockData
import B1.Program.Prices.Options
main = do
args <- getArgs
(options, nonOptions) <- readOptions args
putStrLn $ "Symbol: " ++ symbol options
putStrLn $ "Data source: " ++ show (dataSource options)
pricesOrError <- getPrices (dataSource options) (symbol options)
either printInfo
(\error -> putStrLn $ " Error: " ++ error)
pricesOrError
getPrices :: DataSource -> String -> IO (Either [Price] String)
getPrices Google symbol = do
now <- getCurrentDate
getGooglePrices (getStartDate now) (getEndDate now) symbol
getPrices Mock _ = return $ Left (getMockPrices 5)
getCurrentDate :: IO LocalTime
getCurrentDate = do
timeZone <- getCurrentTimeZone
time <- getCurrentTime
return $ utcToLocalTime timeZone time
getStartDate :: LocalTime -> LocalTime
getStartDate currentDate@LocalTime { localDay = day } =
currentDate { localDay = (addGregorianYearsClip (-1)) day }
getEndDate :: LocalTime -> LocalTime
getEndDate currentDate = currentDate
printInfo :: [Price] -> IO ()
printInfo stockPrices = do
printData "Prices " $ prices stockData
printData "Trimmed Prices " $
take (numDailyElements stockData) $ prices stockData
printData "Weekly Prices " $ weeklyPrices stockData
printData "Trimmed Weekly Prices " $
take (numWeeklyElements stockData) $ weeklyPrices stockData
printData "Stochastics " $ stochastics stockData
printData "Trimmed Stochastics " $
take (numDailyElements stockData) $ stochastics stockData
printData "Weekly Stochastics " $ weeklyStochastics stockData
printData "Trimmed Weekly Stochastics " $
take (numWeeklyElements stockData) $ weeklyStochastics stockData
printData "Moving Average 200 " $ weeklyStochastics stockData
printData "Moving Average 200" $
take (numDailyElements stockData) $ movingAverage200 stockData
where
weeklyStockPrices = getWeeklyPrices stockPrices
stockData = createStockPriceData stockPrices
printData :: Show a => String -> [a] -> IO ()
printData label values = do
putStrLn $ label ++ " (" ++ show (length values) ++ "):"
mapM_ (\price -> putStrLn $ " " ++ show price) values
putStrLn ""
| btmura/b1 | src/B1/Program/Prices/Main.hs | bsd-3-clause | 2,410 | 0 | 11 | 431 | 714 | 347 | 367 | 59 | 1 |
{-- snippet BookInfo --}
data BookInfo = Book Int String [String]
deriving (Show)
{-- /snippet BookInfo --}
{-- snippet MagazineInfo --}
data MagazineInfo = Magazine Int String [String]
deriving (Show)
{-- /snippet MagazineInfo --}
{-- snippet BookReview --}
-- We will introduce the CustomerID type shortly.
data BookReview = BookReview BookInfo CustomerID String
{-- /snippet BookReview --}
{-- snippet BetterReview --}
type CustomerID = Int
type ReviewBody = String
data BetterReview = BetterReview BookInfo CustomerID ReviewBody
{-- /snippet BetterReview --}
{-- snippet BookRecord --}
type BookRecord = (BookInfo, BookReview)
{-- /snippet BookRecord --}
{-- snippet Customer --}
data Customer = Customer {
customerID :: CustomerID
, customerName :: String
, customerAddress :: Address
} deriving (Show)
{-- /snippet Customer --}
{-- snippet BillingInfo --}
type CardHolder = String
type CardNumber = String
type Address = [String]
data BillingInfo = CreditCard CardNumber CardHolder Address
| CashOnDelivery
| Invoice CustomerID
deriving (Show)
{-- /snippet BillingInfo --}
{-- snippet myInfo --}
myInfo = Book 9780135072455 "Algebra of Programming"
["Richard Bird", "Oege de Moor"]
{-- /snippet myInfo --}
{-- snippet customer1 --}
customer1 = Customer 271828 "J.R. Hacker"
["255 Syntax Ct",
"Milpitas, CA 95134",
"USA"]
{-- /snippet customer1 --}
{-- snippet customer2 --}
customer2 = Customer {
customerID = 271828
, customerAddress = ["1048576 Disk Drive",
"Milpitas, CA 95134",
"USA"]
, customerName = "Jane Q. Citizen"
}
{-- /snippet customer2 --}
{-- snippet ShoppingCart --}
data ShoppingCart = ShoppingCart CustomerID [BookInfo]
deriving (Show)
{-- /snippet ShoppingCart --}
{-- snippet accessors --}
bookID (Book id title authors) = id
bookTitle (Book id title authors) = title
bookAuthors (Book id title authors) = authors
{-- /snippet accessors --}
{-- snippet niceAccessors --}
nicerID (Book id _ _ ) = id
nicerTitle (Book _ title _ ) = title
nicerAuthors (Book _ _ authors) = authors
{-- /snippet niceAccessors --}
| binesiyu/ifl | examples/ch03/BookStore.hs | mit | 2,381 | 0 | 8 | 650 | 409 | 244 | 165 | 41 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
module UU.Parsing.Perms(Perms(), pPerms, pPermsSep, succeedPerms, (~*~), (~$~)) where
import UU.Parsing
import Data.Maybe
-- =======================================================================================
-- ===== PERMUTATIONS ================================================================
-- =======================================================================================
newtype Perms p a = Perms (Maybe (p a), [Br p a])
data Br p a = forall b. Br (Perms p (b -> a)) (p b)
instance IsParser p s => Functor (Perms p) where
fmap f (Perms (mb, bs)) = Perms (fmap (f<$>) mb, map (fmap f) bs)
instance IsParser p s => Functor (Br p) where
fmap f (Br perm p) = Br (fmap (f.) perm) p
(~*~) :: IsParser p s => Perms p (a -> b) -> p a -> Perms p b
perms ~*~ p = perms `add` (getzerop p, getonep p)
(~$~) :: IsParser p s => (a -> b) -> p a -> Perms p b
f ~$~ p = succeedPerms f ~*~ p
succeedPerms :: IsParser p s => a -> Perms p a
succeedPerms x = Perms (Just (pLow x), [])
add :: IsParser p s => Perms p (a -> b) -> (Maybe (p a),Maybe (p a)) -> Perms p b
add b2a@(Perms (eb2a, nb2a)) bp@(eb, nb)
= let changing :: IsParser p s => (a -> b) -> Perms p a -> Perms p b
f `changing` Perms (ep, np) = Perms (fmap (f <$>) ep, [Br ((f.) `changing` pp) p | Br pp p <- np])
in Perms
( do { f <- eb2a
; x <- eb
; return (f <*> x)
}
, (case nb of
Nothing -> id
Just pb -> (Br b2a pb:)
)[ Br ((flip `changing` c) `add` bp) d | Br c d <- nb2a]
)
pPerms :: IsParser p s => Perms p a -> p a
pPerms (Perms (empty,nonempty))
= foldl (<|>) (fromMaybe pFail empty) [ (flip ($)) <$> p <*> pPerms pp
| Br pp p <- nonempty
]
pPermsSep :: IsParser p s => p x -> Perms p a -> p a
pPermsSep (sep :: p z) perm = p2p (pSucceed ()) perm
where p2p :: p () -> Perms p a -> p a
p2p fsep (Perms (mbempty, nonempties)) =
let empty = fromMaybe pFail mbempty
pars (Br t p) = flip ($) <$ fsep <*> p <*> p2p_sep t
in foldr (<|>) empty (map pars nonempties)
p2p_sep = p2p (()<$ sep)
| UU-ComputerScience/uulib | src/UU/Parsing/Perms.hs | bsd-3-clause | 2,318 | 0 | 15 | 700 | 1,063 | 555 | 508 | -1 | -1 |
module Main (main) where
import Data.Functor.Identity (Identity)
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
import Pipes (Pipe, (>->), each)
import Pipes.Prelude (toList)
import Pipes.Extras (scan1i)
main :: IO ()
main = defaultMain tests
tests :: [Test]
tests =
[ testGroup "Scans" [
testCase "Scan1i works for EMA calculation" testScan1i
]
]
testScan1i :: Assertion
testScan1i = transduce (scan1i (\l i -> l * α + i * (1 - α))) [2, 0, 0, 1.5] @?= ([2, 1, 0.5, 1] :: [Double])
where α = 0.5
transduce :: Pipe a b Identity () -> [a] -> [b]
transduce pipe xs = toList (each xs >-> pipe)
| parsonsmatt/Haskell-Pipes-Extras-Library | tests/Main.hs | bsd-3-clause | 702 | 0 | 13 | 142 | 284 | 165 | 119 | 19 | 1 |
-- | Hyper vectorial synthesis
module Csound.Air.Hvs(
HvsSnapshot, HvsMatrix1, HvsMatrix2, HvsMatrix3,
hvs1, hvs2, hvs3,
-- | Csound functions
csdHvs1, csdHvs2, csdHvs3
) where
import Control.Applicative hiding ((<*))
import Control.Monad.Trans.Class
import Csound.Dynamic hiding (int)
import Csound.Typed
import Csound.Typed.Opcode hiding (hvs1, hvs2, hvs3)
import qualified Csound.Typed.Opcode as C(hvs1, hvs2, hvs3)
import Csound.Tab
-- | Hvs vector
type HvsSnapshot = [Double]
-- | 1D matrix
type HvsMatrix1 = [HvsSnapshot]
-- | 2D matrix (grid of vecotrs)
type HvsMatrix2 = [HvsMatrix1]
-- | 3D matrix (cube of vectors)
type HvsMatrix3 = [HvsMatrix2]
-- Hyper Vectorial Synthesis.
-- |
-- Allows one-dimensional Hyper Vectorial Synthesis (HVS) controlled by externally-updated k-variables.
--
-- hvs1 allows one-dimensional Hyper Vectorial Synthesis (HVS) controlled by externally-updated k-variables.
--
-- > hvs1 kx, inumParms, inumPointsX, iOutTab, iPositionsTab, iSnapTab [, iConfigTab]
--
-- csound doc: <http://www.csounds.com/manual/html/hvs1.html>
csdHvs1 :: Sig -> D -> D -> Tab -> Tab -> Tab -> SE ()
csdHvs1 b1 b2 b3 b4 b5 b6 = SE $ (depT_ =<<) $ lift $ f <$> unSig b1 <*> unD b2 <*> unD b3 <*> unTab b4 <*> unTab b5 <*> unTab b6
where f a1 a2 a3 a4 a5 a6 = opcs "hvs1" [(Xr,[Kr,Ir,Ir,Ir,Ir,Ir,Ir])] [a1,a2,a3,a4,a5,a6]
-- |
-- Allows two-dimensional Hyper Vectorial Synthesis (HVS) controlled by externally-updated k-variables.
--
-- hvs2 allows two-dimensional Hyper Vectorial Synthesis (HVS) controlled by externally-updated k-variables.
--
-- > hvs2 kx, ky, inumParms, inumPointsX, inumPointsY, iOutTab, iPositionsTab, iSnapTab [, iConfigTab]
--
-- csound doc: <http://www.csounds.com/manual/html/hvs2.html>
csdHvs2 :: Sig -> Sig -> D -> D -> D -> Tab -> Tab -> Tab -> SE ()
csdHvs2 b1 b2 b3 b4 b5 b6 b7 b8 = SE $ (depT_ =<<) $ lift $ f <$> unSig b1 <*> unSig b2 <*> unD b3 <*> unD b4 <*> unD b5 <*> unTab b6 <*> unTab b7 <*> unTab b8
where f a1 a2 a3 a4 a5 a6 a7 a8 = opcs "hvs2" [(Xr,[Kr,Kr,Ir,Ir,Ir,Ir,Ir,Ir,Ir])] [a1
,a2
,a3
,a4
,a5
,a6
,a7
,a8]
-- |
-- Allows three-dimensional Hyper Vectorial Synthesis (HVS) controlled by externally-updated k-variables.
--
-- hvs3 allows three-dimensional Hyper Vectorial Synthesis (HVS) controlled by externally-updated k-variables.
--
-- > hvs3 kx, ky, kz, inumParms, inumPointsX, inumPointsY, inumPointsZ, iOutTab, iPositionsTab, iSnapTab [, iConfigTab]
--
-- csound doc: <http://www.csounds.com/manual/html/hvs3.html>
csdHvs3 :: Sig -> Sig -> Sig -> D -> D -> D -> D -> Tab -> Tab -> Tab -> SE ()
csdHvs3 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 = SE $ (depT_ =<<) $ lift $ f <$> unSig b1 <*> unSig b2 <*> unSig b3 <*> unD b4 <*> unD b5 <*> unD b6 <*> unD b7 <*> unTab b8 <*> unTab b9 <*> unTab b10
where f a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 = opcs "hvs3" [(Xr
,[Kr,Kr,Kr,Ir,Ir,Ir,Ir,Ir,Ir,Ir,Ir])] [a1,a2,a3,a4,a5,a6,a7,a8,a9,a10]
-- | One dimensional Hyper vectorial synthesis.
-- We can provide a list of vectors (of lists but the same length for all items is assumed)
-- and a signal that ranges from 0 to 1. It interpolates between vectors in the list.
-- As a result we get a n interpolated vector. It's a list but the actual length
-- equals to the length of input vectors.
--
-- An example. We can set the center frequency and resonance of the filter with the single parameter:
--
-- > let f = hvs1 [[100, 0.1], [300, 0.1], [600, 0.5], [800, 0.9]]
-- > dac $ lift1 (\x -> fmap (\[cps, q] -> mlp cps q (saw 110)) $ f x) (uknob 0.5)
--
-- Notice the exact pattern match with the list in the argument of the lambda function:
--
-- > \[cps, q] -> mlp cps q (saw 110)) $ f x
--
-- It's determined by the length of the items in the input list.
hvs1 :: HvsMatrix1 -> Sig -> SE [Sig]
hvs1 as x = do
outTab <- newTab (int numParams)
csdHvs1 x (int numParams) (int numPointsX) outTab positionsTab snapTab
return $ fmap (kr . flip tab outTab . sig . int) [0 .. numParams - 1]
where
numParams = length $ head as
numPointsX = length as
positionsTab = doubles $ fmap fromIntegral [0 .. numPointsX - 1]
snapTab = doubles $ concat as
-- | Two dimensional Hyper vectorial synthesis.
-- Now we provide a list of lists of vectors. The length of all vectors should be the same
-- but there is no limit for the number! So that's how we can control a lot of parameters
-- with pair of signals. The input 2D atrix is the grid of samples.
-- It finds the closest four points in the grid and interpolates between them (it's a weighted sum).
--
-- > hvs2 matrix (x, y)
--
-- The usage is the same as in the case of @hvs1@. An example:
--
-- > g = hvs2 [[[100, 0.1, 0.3], [800, 0.1, 0.5], [1400, 0.1, 0.8]],
-- > [[100, 0.5, 0.3], [800, 0.5, 0.5], [1400, 0.5, 0.8]],
-- > [[100, 0.8, 0.3], [800, 0.8, 0.5], [1400, 0.8, 0.8]]]
-- >
-- > main = dac $ do
-- > (g1, kx) <- uknob 0.5
-- > (g2, ky) <- uknob 0.5
-- > [cfq, q, w] <- g (kx, ky)
-- > panel $ hor [g1, g2]
-- > at (mlp cfq q) $ fmap (cfd w (saw 110)) (white)
hvs2 :: HvsMatrix2 -> Sig2 -> SE [Sig]
hvs2 as (x, y) = do
outTab <- newTab (int numParams)
csdHvs2 x y (int numParams) (int numPointsX) (int numPointsY) outTab positionsTab snapTab
return $ fmap (kr . flip tab outTab . sig . int) [0 .. numParams - 1]
where
numParams = length $ head $ head as
numPointsX = length $ head as
numPointsY = length as
positionsTab = doubles $ fmap fromIntegral [0 .. (numPointsX * numPointsY - 1)]
snapTab = doubles $ concat $ concat as
-- | The three dimensional
hvs3 :: HvsMatrix3 -> Sig3 -> SE [Sig]
hvs3 as (x, y, z) = do
outTab <- newTab (int numParams)
csdHvs3 x y z (int numParams) (int numPointsX) (int numPointsY) (int numPointsZ) outTab positionsTab snapTab
return $ fmap (kr . flip tab outTab . sig . int) [0 .. numParams - 1]
where
numParams = length $ head $ head $ head as
numPointsX = length $ head $ head as
numPointsY = length $ head as
numPointsZ = length as
positionsTab = doubles $ fmap fromIntegral [0 .. (numPointsX * numPointsY * numPointsZ) - 1]
snapTab = doubles $ concat $ concat $ concat as | isomorphism/csound-expression | src/Csound/Air/Hvs.hs | bsd-3-clause | 6,774 | 6 | 18 | 1,872 | 1,555 | 859 | 696 | 62 | 1 |
-------------------------------------------------------------------------------
-- |
-- Module : CCO.Lexing
-- Copyright : (c) 2008 Utrecht University
-- License : All rights reserved
--
-- Maintainer : stefan@cs.uu.nl
-- Stability : provisional
-- Portability : portable
--
-- A library of lexer combinators that expose their functionality through an
-- 'Applicative' interface.
--
-------------------------------------------------------------------------------
module CCO.Lexing (
-- * Lexers
Lexer -- abstract, instances: Functor,
-- Applicative, Alternative
, satisfy -- :: Lexer Char
, message -- :: String -> Lexer a
-- * Derived lexers
, anyChar -- :: Lexer Char
, anyCharFrom -- :: [Char] -> Lexer Char
, anyCharBut -- :: [Char] -> Lexer Char
, range -- :: (Char, Char) -> Lexer Char
, notInRange -- :: (Char, Char) -> Lexer Char
, char -- :: Lexer Char
, string -- :: Lexer String
, space -- :: Lexer Char
, lower -- :: Lexer Char
, upper -- :: Lexer Char
, letter -- :: Lexer Char
, alpha -- :: Lexer Char
, alphaNum -- :: Lexer Char
, digit -- :: Lexer Char
, digit_ -- :: Lexer Int
, binDigit -- :: Lexer Char
, binDigit_ -- :: Lexer Int
, octDigit -- :: Lexer Char
, octDigit_ -- :: Lexer Int
, hexDigit -- :: Lexer Char
, hexDigit_ -- :: Lexer Int
-- * Ignoring recognised input
, ignore -- :: Lexer a -> Lexer b
-- * Symbols
, LexicalUnit (Token, Error, Msg)
, Symbols (Symbols)
-- * Lexing
, lex -- :: Lexer a -> Source -> String ->
-- Symbols a
-- * Utilities
, tokens -- :: Symbols a -> [(SourcePos, a)]
, tokens_ -- :: Symbols a -> [a]
) where
import Prelude hiding (lex)
import CCO.SourcePos (Source, Pos (Pos, EOF), SourcePos (SourcePos))
import Control.Applicative (Applicative (..), Alternative (..), (<$>))
import Data.Char
-------------------------------------------------------------------------------
-- Steps
-------------------------------------------------------------------------------
-- | A @Steps@ represents the tokenisation associated with the recognition of
-- a (part of a) lexeme.
data Steps a = None -- ^ No tokenisation yet.
| Return a -- ^ Produces as a token a value of type @a@.
| Ignore -- ^ Produces a value of type @a@ but ignores it as
-- far as tokenisation is concerned.
-- (Typically used on lexemes that constitute
-- comments or whitespace.)
| Fail String -- ^ Fail with a specified error message.
instance Functor Steps where
fmap _ None = None
fmap f (Return x) = Return (f x)
fmap _ Ignore = Ignore
fmap _ (Fail msg) = Fail msg
instance Applicative Steps where
pure x = Return x
(Fail msg) <*> _ = Fail msg
_ <*> (Fail msg) = Fail msg
None <*> _ = None
_ <*> None = None
Return f <*> Return x = Return (f x)
_ <*> _ = Ignore
instance Alternative Steps where
empty = None
steps@(Return _) <|> _ = steps
steps@Ignore <|> _ = steps
_ <|> steps@(Return _) = steps
_ <|> steps@Ignore = steps
None <|> steps = steps
steps <|> _ = steps
-------------------------------------------------------------------------------
-- Lexers
-------------------------------------------------------------------------------
-- | Type of lexers that produce tokens of type @a@.
data Lexer a = Trie (Steps a) [(Char -> Bool, Lexer (Char -> a))]
-- ^ A @Lexer@ consists of a @Steps@-component that represents
-- the tokenisation for the lexeme currently recognised and
-- a multi-mapping from characters to lexers that represent
-- the next state of the scanner.
instance Functor Lexer where
fmap f (Trie steps edges) =
Trie (fmap f steps) [(p, fmap (f .) next) | (p, next) <- edges]
instance Applicative Lexer where
pure x = Trie (pure x) []
Trie None edges <*> lexer = Trie None
[(p, flip <$> next <*> lexer) | (p, next) <- edges]
Trie (Fail msg) edges <*> lexer = Trie (Fail msg)
[(p, flip <$> next <*> lexer) | (p, next) <- edges]
Trie steps edges <*> lexer@(Trie steps' edges') = Trie (steps <*> steps') $
[(p, smap ((.) <$> steps) next) | (p, next) <- edges'] ++
[(p, flip <$> next <*> lexer) | (p, next) <- edges]
instance Alternative Lexer where
empty = Trie empty []
Trie steps edges <|> Trie steps' edges' =
Trie (steps <|> steps') (edges ++ edges')
-- | Maps a tokenisation over a 'Lexer'.
smap :: Steps (a -> b) -> Lexer a -> Lexer b
smap steps (Trie steps' edges) = Trie (steps <*> steps')
[(p, smap ((.) <$> steps) next) | (p, next) <- edges]
-- | A 'Lexer' that recognises any character that satisfies a specified
-- predicate.
satisfy :: (Char -> Bool) -> Lexer Char
satisfy p = Trie None [(p, Trie (Return id) [])]
-- | A 'Lexer' that will produce a specified error message.
message :: String -> Lexer a
message msg = Trie (Fail msg) []
-------------------------------------------------------------------------------
-- Derived lexers
-------------------------------------------------------------------------------
-- | The trivial 'Lexer' that recognises any character.
anyChar :: Lexer Char
anyChar = satisfy (const True)
-- | A 'Lexer' that recognises any character that appears in a given list.
anyCharFrom :: [Char] -> Lexer Char
anyCharFrom cs = satisfy (`elem` cs)
-- | A 'Lexer' that recognises any character that does not appear in a given
-- list.
anyCharBut :: [Char] -> Lexer Char
anyCharBut tabus = satisfy (`notElem` tabus)
-- | A 'Lexer' that recognises any character that appears in a given range.
-- More efficent than @\\(low, up) -> anyCharFrom [low .. up]@.
range :: (Char, Char) -> Lexer Char
range (low, up) = satisfy (\c -> c >= low && c <= up)
-- | A 'Lexer' that recognises any character that does not appear in a given
-- range.
notInRange :: (Char, Char) -> Lexer Char
notInRange (low, up) = satisfy (\c -> c < low || c > up)
-- | A 'Lexer' that recognises a specified character.
char :: Char -> Lexer Char
char c = satisfy (== c)
-- | A 'Lexer' that recognises a specified 'String'.
string :: String -> Lexer String
string [] = pure []
string (c : cs) = (:) <$> char c <*> string cs
-- | A 'Lexer' that recognises a whitespace character
space :: Lexer Char
space = satisfy isSpace
-- | A 'Lexer' that recognises lower-case alphabetic characters.
lower :: Lexer Char
lower = satisfy isLower
-- | A 'Lexer' that recognises upper-case or title-case alphabetic characters.
upper :: Lexer Char
upper = satisfy isUpper
-- | A 'Lexer' that recognises alphabetic characters. Equivalent to 'alpha'.
letter :: Lexer Char
letter = alpha
-- | A 'Lexer' that recognises alphabetic characters. Equivalet to 'letter'.
alpha :: Lexer Char
alpha = satisfy isAlpha
-- | A 'Lexer' that recognises alphabetic or numeric characters.
alphaNum :: Lexer Char
alphaNum = satisfy isAlphaNum
-- | A 'Lexer' that recognises a digit.
digit :: Lexer Char
digit = satisfy isDigit
-- | A 'Lexer' that recognises a digit and tokenises it as an 'Int'.
digit_ :: Lexer Int
digit_ = (\c -> ord c - ordZero) <$> digit
-- | A 'Lexer' that recognises a binary digit.
binDigit :: Lexer Char
binDigit = range ('0', '1')
-- | A 'Lexer' that recognises a binary digit and tokenises it as an 'Int'.
binDigit_ :: Lexer Int
binDigit_ = (\c -> ord c - ordZero) <$> binDigit
-- | A 'Lexer' that recognises an octal digit.
octDigit :: Lexer Char
octDigit = satisfy isOctDigit
-- | A 'Lexer' that recognises an octal digit and tokenises it as an 'Int'.
octDigit_ :: Lexer Int
octDigit_ = (\c -> ord c - ordZero) <$> octDigit
-- | A 'Lexer that recognises a hexedecimal digit.
hexDigit :: Lexer Char
hexDigit = satisfy isHexDigit
-- | A 'Lexer' that recognises a hexadecimal digit and tokenises it as an
-- 'Int'.
hexDigit_ :: Lexer Int
hexDigit_ = (\c -> ord c - ordZero) <$> digit <|>
(\c -> 10 + (ord c - ordLowerA)) <$> range ('a', 'f') <|>
(\c -> 10 + (ord c - ordUpperA)) <$> range ('A', 'F')
-------------------------------------------------------------------------------
-- Ignoring recognised input
-------------------------------------------------------------------------------
-- | Produces a 'Lexer' that recognises the same inputs as a given underlying
-- 'Lexer', but that does not result in any tokenisation.
--
-- The input recognised by a 'Lexer' constructed with @ignore@ is simply
-- ignored when the 'Lexer' is used to turn a stream of characters into a
-- stream of 'LexicalUnit's.
--
-- Mainly used to suppress the generation of tokens for lexemes that constitute-- lexical units like comments and whitespace.
ignore :: Lexer a -> Lexer b
ignore = smap Ignore
-------------------------------------------------------------------------------
-- Symbols
-------------------------------------------------------------------------------
-- | The type of lexical units.
data LexicalUnit a
= Token a Pos String String -- ^ A tokenised lexeme: its token, its
-- position, the characters it consists
-- of, and its its trailing characters in
-- the input stream.
| Error Pos String String -- ^ An invalid lexeme: its position, the
-- characters it consists of, and its
-- trailing characters in the input
-- stream.
| Msg String Pos String String -- ^ An invalid lexeme, labeled by a custom
-- error message: the message, its
-- position, the characters it consists
-- of, and its trailing characters in the
-- input stream.
-- | The type of streams of symbols described by tokens of type 'a'.
data Symbols a = Symbols Source [LexicalUnit a]
-------------------------------------------------------------------------------
-- Lexing
-------------------------------------------------------------------------------
-- | A @Scan@: an accumulator for the input recognised, a tokenisation for the
-- input recognised, the current position, and the remaining input.
type Scan a = (String -> String, Steps a, Pos, String)
-- | Scanner: takes a 'Lexer', an input position, and an input stream and then
-- produces a 'Scan' for the next lexeme.
scan :: Lexer a -> Pos -> String -> Scan a
scan (Trie steps edges) pos input = (id, steps, pos, input) `sor` consume input
where
consume [] = (id, None, pos, input)
consume (c : cs) =
let lexer = choice [next | (p, next) <- edges, p c]
(acc, steps', pos', input') =
scan (lexer <*> pure c) (incrPos c pos) cs
in ((c :) . acc, steps', pos', input')
-- | Picks the \"best\" of two 'Scan's, favouring the second over the first,
-- except when the second does not allow any tokenisation.
sor :: Scan a -> Scan a -> Scan a
sor scn (_, None, _, _) = scn
sor _ scn = scn
-- | Runs a lexer on a specified input stream.
lex :: Lexer a -> Source -> String -> Symbols a
lex lexer src = let initpos = initialPos
in Symbols src . tokenise initpos id initpos
where
tokenise errpos prefix pos input =
let sentinel = case prefix "" of
[] -> id
lexeme -> (Error errpos lexeme input :)
in case scan lexer pos input of
(_, None, _, []) -> sentinel []
(acc, None, pos', c : input') -> tokenise errpos (prefix . (c :))
(incrPos c pos') input'
(acc, Return x, pos', input') -> sentinel $
Token x pos (acc "") input' :
tokenise pos' id pos' input'
(acc, Fail msg, pos', input') -> Msg msg errpos (acc "") input' :
tokenise pos' id pos' input'
(_, _, pos', input') -> sentinel
(tokenise pos' id pos' input')
-------------------------------------------------------------------------------
-- Source positions
-------------------------------------------------------------------------------
-- | Retrieves the first position in an input stream.
initialPos :: Pos
initialPos = Pos 1 1
-- | Increments a 'Pos' based on the character consumed.
-- If a newline character is consumed, the line number is incremented and the
-- column number is reset to 1; for any other character, the line number is
-- kept unchanged and the column number is incremented by 1.
-- Fails if an attempt is made to increment an 'EOF'-value.
incrPos :: Char -> Pos -> Pos
incrPos '\n' (Pos line column) = Pos (line + 1) 1
incrPos _ (Pos line column) = Pos line (column + 1)
-------------------------------------------------------------------------------
-- Utilities
-------------------------------------------------------------------------------
-- | The 'ord' of '\'0\''.
ordZero :: Int
ordZero = ord '0'
-- | The 'ord' of '\'a\''.
ordLowerA :: Int
ordLowerA = ord 'a'
-- | The 'ord' of '\'A\''.
ordUpperA :: Int
ordUpperA = ord 'A'
-- | Combines multiple 'Alternative's by means of '<|>'.
choice :: Alternative f => [f a] -> f a
choice [] = empty
choice [x] = x
choice xs = foldr1 (<|>) xs
-- | Retrieves all tokens together with their source positions from a list of
-- 'Symbols'.
tokens :: Symbols a -> [(SourcePos, a)]
tokens (Symbols src units) =
[(SourcePos src pos, x) | Token x pos _ _ <- units]
-- | Retrieves all tokens from a list of 'Symbols'.
tokens_ :: Symbols a -> [a]
tokens_ (Symbols _ units) = [x | Token x _ _ _ <- units] | UU-ComputerScience/uu-cco | uu-cco/src/CCO/Lexing.hs | bsd-3-clause | 15,045 | 0 | 16 | 4,629 | 2,919 | 1,624 | 1,295 | 190 | 6 |
-- ensure that the XMM register values are properly preserved across STG
-- exit/entry. Note that this is very sensitive to code generation.
module Main where
import Control.Monad (when)
import System.Exit (exitWith, ExitCode(..))
foreign export ccall fn_hs :: IO ()
fn_hs :: IO ()
fn_hs = return ()
foreign import ccall test :: IO Int
main :: IO ()
main = do res <- test
when (res /= 0) (exitWith $ ExitFailure res)
| sdiehl/ghc | testsuite/tests/rts/T16514.hs | bsd-3-clause | 434 | 0 | 10 | 90 | 128 | 70 | 58 | 10 | 1 |
--------------------------------
-- The Game of Life --
--------------------------------
generations x = 30
data L a = N | C1 a (L a) | C2 a a (L a)
data Tuple2 a b = T2 a b
data Tuple3 a b c = T3 a b c
main = putStr (listChar_string
(append1 (C1 '\FF' N)
(life1 (generations ()) (start ()))))
listChar_string :: L Char -> String
listChar_string N = []
listChar_string (C1 x xs) = x : listChar_string xs
start :: a -> L (L Int)
start x = (C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1 N
(C1
(C1 0
(C1 0
(C1 0
(C1 1
(C1 1
(C1 1
(C1 1
(C1 1
(C1 0
(C1 1
(C1 1
(C1 1
(C1 1
(C1 1
(C1 0
(C1 1
(C1 1
(C1 1
(C1 1
(C1 1
(C1 0
(C1 1
(C1 1
(C1 1
(C1 1
(C1 1
(C1 0 N))))))))))))))))))))))))))) N)))))))))))))))
-- Calculating the next generation
gen1 :: Int -> L (L Int) -> L (L Int)
gen1 n board = map1 row1 (shift1 (copy1 n 0) board)
row1 :: Tuple3 (L Int) (L Int) (L Int) -> L Int
row1 (T3 last this next)
= zipWith31 elt1 (shift2 0 last)
(shift2 0 this)
(shift2 0 next)
elt1 :: Tuple3 Int Int Int
-> (Tuple3 Int Int Int)
-> (Tuple3 Int Int Int) -> Int
elt1 (T3 a b c) (T3 d e f) (T3 g h i)
= if (not (eq tot 2))
&& (not (eq tot 3))
then 0
else if (eq tot 3) then 1 else e
where tot = a `plus` b `plus` c `plus` d
`plus` f `plus` g `plus` h `plus` i
eq :: Int -> Int -> Bool
eq x y = x == y
plus :: Int -> Int -> Int
plus x y = x + y
shiftr1 :: L Int -> L (L Int) -> L (L Int)
shiftr1 x xs = append2 (C1 x N) (init1 xs)
shiftl1 :: L Int -> L (L Int) -> L (L Int)
shiftl1 x xs = append2 (tail1 xs) (C1 x N)
shift1 :: L Int -> L (L Int)
-> L (Tuple3 (L Int) (L Int) (L Int))
shift1 x xs = zip31 (shiftr1 x xs) xs (shiftl1 x xs)
shiftr2 :: Int -> L Int -> L Int
shiftr2 x xs = append3 (C1 x N) (init2 xs)
shiftl2 :: Int -> L Int -> L Int
shiftl2 x xs = append3 (tail2 xs) (C1 x N)
shift2 :: Int -> L Int -> L (Tuple3 Int Int Int)
shift2 x xs = zip32 (shiftr2 x xs) xs (shiftl2 x xs)
-- copy
copy1 :: Int -> Int -> L Int
copy1 0 x = N
copy1 n x = C1 x (copy1 (n-1) x)
copy2 :: Int -> L Int -> L (L Int)
copy2 0 x = N
copy2 n x = C1 x (copy2 (n-1) x)
copy3 :: Int -> Char -> L Char
copy3 0 x = N
copy3 n x = C1 x (copy3 (n-1) x)
-- Displaying one generation
disp1 :: (Tuple2 (L Char) (L (L Int))) -> L Char
disp1 (T2 gen xss)
= append1 gen
(append1 (C1 '\n' (C1 '\n' N))
(foldr_1 (glue1 (C1 '\n' N)) N
(map4 (compose2 concat1 (map2 star1)) xss)))
star1 :: Int -> L Char
star1 i = case i of
0 -> C1 ' ' (C1 ' ' N)
1 -> C1 ' ' (C1 'o' N)
glue1 :: L Char -> L Char -> L Char -> L Char
glue1 s xs ys = append1 xs (append1 s ys)
-- Generating and displaying a sequence of generations
life1 :: Int -> L (L Int) -> L Char
life1 n xss
= foldr_1 (glue1 (copy3 (n+2) '\VT')) N
(map5 disp1
(zip1_ (map6 (string_ListChar.show) (ints 0))
gens))
where
gens = take3 (100 {-740-}::Int) (iterate1 (gen1 n) (initial1 n xss))
ints :: Int -> L Int
ints x = C1 x (ints (x+1))
string_ListChar :: String -> L Char
string_ListChar [] = N
string_ListChar (x:xs) = C1 x (string_ListChar xs)
initial1 :: Int -> L (L Int) -> L (L Int)
initial1 n xss = take1 n (append2 (map3 (compose1 (take2 n)
(`append3` (copy1 n 0))) xss)
(copy2 n (copy1 n 0)))
iterate1 :: (L (L Int) -> L (L Int))
-> L (L Int) -> L (L (L Int))
iterate1 f x = C1 x (iterate1 f (f x))
-- versions of built in functions
-- take
take1 :: Int -> L (L Int) -> L (L Int)
take1 0 _ = N
take1 _ N = N
--should be:take1 (n+1) (C1 x xs) = C1 x (take1 n xs)
take1 n (C1 x xs) | n < 0 = error "Main.take1"
| otherwise = C1 x (take1 (n-1) xs)
take2 :: Int -> L Int -> L Int
take2 0 _ = N
take2 _ N = N
--should be:take2 (n+1) (C1 x xs) = C1 x (take2 n xs)
take2 n (C1 x xs) | n < 0 = error "Main.take2"
| otherwise = C1 x (take2 (n-1) xs)
take3 :: Int -> L (L (L Int))
-> L (L (L Int))
take3 0 _ = N
take3 _ N = N
take3 n (C1 x xs) = C1 x (take3 (n-1) xs)
-- init
init1 :: L (L Int) -> L (L Int)
init1 (C1 x N) = N
init1 (C1 x xs) = C1 x (init1 xs)
init1 N = error "init1 got a bad list"
init2 :: L Int -> L Int
init2 (C1 x N) = N
init2 (C1 x xs) = C1 x (init2 xs)
init2 N = error "init1 got a bad list"
-- tail
tail1 :: L (L Int) -> L (L Int)
tail1 (C1 _ xs) = xs
tail1 N = error "tail1 got a bad list"
tail2 :: L Int -> L Int
tail2 (C1 _ xs) = xs
tail2 N = error "tail2 got a bad list"
-- maps
map1 :: (Tuple3 (L Int) (L Int) (L Int) -> L Int) ->
L (Tuple3 (L Int) (L Int) (L Int))
-> L (L Int)
map1 f N = N
map1 f (C1 x xs) = C1 (f x) (map1 f xs)
map2 :: (Int -> L Char) -> L Int -> L (L Char)
map2 f N = N
map2 f (C1 x xs) = C1 (f x) (map2 f xs)
map3 :: (L Int -> L Int) -> L (L Int) -> L (L Int)
map3 f N = N
map3 f (C1 x xs) = C1 (f x) (map3 f xs)
map4 :: (L Int -> L Char)
-> L (L Int) -> L (L Char)
map4 f N = N
map4 f (C1 x xs) = C1 (f x) (map4 f xs)
map5 :: (Tuple2 (L Char) (L (L Int)) -> L Char)
-> L (Tuple2 (L Char) (L (L Int)))
-> L (L Char)
map5 f N = N
map5 f (C1 x xs) = C1 (f x) (map5 f xs)
map6 :: (Int -> L Char) -> L Int -> L (L Char)
map6 f N = N
map6 f (C1 x xs) = C1 (f x) (map6 f xs)
-- compose
compose2 :: (L (L Char) -> L Char)
-> (L Int -> L (L Char))
-> L Int -> L Char
compose2 f g xs = f (g xs)
compose1 :: (L Int -> L Int)
-> (L Int -> L Int) -> L Int -> L Int
compose1 f g xs = f (g xs)
-- concat
concat1 :: L (L Char) -> L Char
concat1 = foldr_1 append1 N
-- foldr
foldr_1 :: (L Char -> L Char -> L Char)
-> L Char -> L (L Char) -> L Char
foldr_1 f a N = a
foldr_1 f a (C1 x xs) = f x (foldr_1 f a xs)
-- appends
append1 :: L Char -> L Char -> L Char
append1 N ys = ys
append1 (C1 x xs) ys = C1 x (append1 xs ys)
append2 :: L (L Int) -> L (L Int) -> L (L Int)
append2 N ys = ys
append2 (C1 x xs) ys = C1 x (append2 xs ys)
append3 :: L Int -> L Int -> L Int
append3 N ys = ys
append3 (C1 x xs) ys = C1 x (append3 xs ys)
-- zips
pzip f (C1 x1 xs) (C1 y1 ys)
= C1 (f x1 y1) (pzip f xs ys)
pzip f _ _ = N
zip1_ :: L (L Char)
-> L (L (L Int))
-> L (Tuple2 (L Char) (L (L Int)))
zip1_ = pzip T2
zip2_ :: L (L Int)
-> L (L Int)
-> L (Tuple2 (L Int) (L Int))
zip2_ = pzip T2
zip3d :: L Int -> (Tuple2 (L Int) (L Int))
-> (Tuple3 (L Int) (L Int) (L Int))
zip3d x (T2 y z) = T3 x y z
zip3_ :: L (L Int)
-> L (Tuple2 (L Int) (L Int))
-> L (Tuple3 (L Int) (L Int) (L Int))
zip3_ = pzip zip3d
zip4_ :: L Int
-> L Int
-> L (Tuple2 Int Int)
zip4_ = pzip T2
zip5d :: Int -> (Tuple2 Int Int) -> (Tuple3 Int Int Int)
zip5d x (T2 y z) = T3 x y z
zip5_ :: L Int
-> L (Tuple2 Int Int)
-> L (Tuple3 Int Int Int)
zip5_ = pzip zip5d
zip6_ :: L (Tuple3 Int Int Int)
-> L (Tuple3 Int Int Int)
-> L (Tuple2 (Tuple3 Int Int Int)
(Tuple3 Int Int Int))
zip6_ = pzip T2
zip31 :: L (L Int) -> L (L Int)
-> L (L Int)
-> L (Tuple3 (L Int) (L Int) (L Int))
zip31 as bs cs
= zip3_ as (zip2_ bs cs)
zip32 :: L Int -> L Int -> L Int
-> L (Tuple3 Int Int Int)
zip32 as bs cs
= zip5_ as (zip4_ bs cs)
-- zipWith
zipWith21 :: ((Tuple3 Int Int Int)
-> (Tuple2 (Tuple3 Int Int Int)
(Tuple3 Int Int Int)) -> Int)
-> L (Tuple3 Int Int Int)
-> L (Tuple2 (Tuple3 Int Int Int)
(Tuple3 Int Int Int))
-> L Int
zipWith21 = pzip
zipWith31 :: ((Tuple3 Int Int Int)
-> (Tuple3 Int Int Int)
-> (Tuple3 Int Int Int) -> Int)
-> L (Tuple3 Int Int Int)
-> L (Tuple3 Int Int Int)
-> L (Tuple3 Int Int Int) -> L Int
zipWith31 z as bs cs
= zipWith21 z' as (zip6_ bs cs)
where z' a (T2 b c) = z a b c
| olsner/ghc | testsuite/tests/programs/life_space_leak/Main.hs | bsd-3-clause | 8,625 | 0 | 88 | 3,198 | 4,863 | 2,401 | 2,462 | 260 | 3 |
import System.Environment
main = getArgs >>= print
| ryantm/ghc | testsuite/tests/ghci.debugger/getargs.hs | bsd-3-clause | 52 | 0 | 5 | 8 | 15 | 8 | 7 | 2 | 1 |
import Data.Char
main = do
print $ ord 'A'
print $ chr 65
| shigemk2/haskell_abc | import.hs | mit | 67 | 0 | 8 | 22 | 31 | 14 | 17 | 4 | 1 |
module HighOrdFun where
-- : set expandtab ts=4 ruler number spell
fn7 n = length(show n)
{-
functions in languages like Java and C#,
functions are more often seen as
a way of packaging instructions to organize and reuse code.
But in Haskell functions are central
and can be passed around
like other values.
Higher Order Functions
take functions as arguments
and return functions as well.
This is perhaps the easiest way to manipulate lists.
We can partially apply functions on the fly
only providing some of the necessary arguments initially.
Lambda expressions
which are for generating in-line anonymous functions.
Function combination
which creates a new function assembled from other functions.
Functions are Values
either as arguments to other functions
or
created on the fly as needed.
Higher Order Functions
take functions as arguments
return functions as values.
-}
-- FUNCTIONS AS VALUES --
mult2 :: Integer -> Integer
mult2 = (2*)
add1 :: Integer -> Integer
add1 = (+1)
-- here f is a function take as an argument that then gets
-- three passed to it.
pass3 :: Num a => (a -> t) -> t
pass3 f = f 3
-- *HighOrdFun> pass3 add1
-- 4
compose :: (t1 -> t) -> (t2 -> t1) -> t2 -> t
compose f g x = f (g x)
-- *HighOrdFun> compose add1 mult2 4
-- 9
always7 :: Num a => t -> a
always7 x =7
-- *HighOrdFun> always7 6
-- 7
always7' :: b -> Integer
always7' = const 7
-- *HighOrdFun> always7' 6
-- 7
-- *HighOrdFun> (const 7)5
-- 7
-------------------------
-- PARTIAL APPLICATION --
------------------------
{-
in Java all the arguments to a function must be applied in advance.
int foo(int x, int y, int z) {
return x + y + z;
}
foo_1_2 = foo(1,2);
-- foo Java here, must be called with three args.
-----------------------------------------------}
foo :: Num a => a -> a -> a -> a
foo x y z = x + y + z
foo' :: (Eq a, Eq a1, Num a, Num a1, Num a2) => a -> a1 -> a2 -> a2
foo' 1 2 = foo 1 2
-- *HighOrdFun> foo' 1 2 3
-- 6
-- pass (value x) and (function f) = (function f) <- passes (value x)
pass :: t1 -> (t1 -> t) -> t
pass x f = f x
-- passThree is built by partially applying the pass function; pass only gets one argument here, so it is a function with an argument that takes another argument.
passThree :: (Integer -> t) -> t
passThree = pass 3
--------------------------------------------------------------------------------
-- ARGUMENTS MUST BE GIVEN IN ORDER WHEN THEY ARE TO BE PARTIALLY EVALUATED !!!
-- ------------------------------------------------------------------------------
---------------
-- OPERATORS --
-- ------------
-- +,*,:,++ are operators
-- (+),(*),(:),(++) ARE NOW JUST FUNCTIONS
-- *HighOrdFun> (+) 3 5
-- 8
{-
ghci> (*) 2 3
6
ghci> 2 * 3
6
ghci> (*2) 4
8
-}
-- operators get passed easily to Higher-Order-Functions.
pass_3_4 :: (Num a, Num a1) => (a -> a1 -> t) -> t
pass_3_4 f = f 3 4
-- then passing in an operator as a function
-- *HighOrdFun> pass_3_4 (+)
-- 7
-- we can define new operators for special cases
(.+) :: (Num t, Num t1) => (t, t1) -> (t, t1) -> (t, t1)
(a,b) .+ (c,d) = (a + c, b + d)
-- (a,b) is a pattern that matches a pair, (c,d) is another pair. a + c is summing both first elements. b + d are the second elements summed.
-- ---------------------------
-- OPERATORS PARTIALLY APPLIED --
-- ---------------------------
plus1 :: Integer -> Integer
plus1 = (+) 1
plus1' = (1+)
plus1'' = (+1)
----------------------------
{- FUNCTIONS AS OPERATORS --
- -------------------------
ghci>mod 10 2
0
ghci>10 `mod` 2
0
ghci> 4 `div` 2
2
ghci> div 4 2
2
ghci> `div` 4 2
<interactive>:7:1: parse error on input ``'
ghci> (`div`) 4 2
<interactive>:8:7: parse error on input `)'
ghci> (`div`2) 4
2
ghci> (2`div`) 4
0
-- REMEMBER ` NOT ' OTHERWISE --
ghci>4 'div' 2
<interactive>:16:3:
Syntax error on 'div'
---------------------------------}
-- MAP FUNCTION --
-- ------------------------------
-- map traverses a list add applies a function to every element in the list.
-- map :: (a -> b) -> [a] -> [b]
-- ghci> map length ["map","sure","is","fun"]
-- [3,4,2,3]
-- PARTIALLY APPLIED FUNCTIONS WORK WELL
-- ghci> map (1+) [1..11]
-- [2,3,4,5,6,7,8,9,10,11,12]
double :: [Integer] -> [Integer]
double = map (2*)
-- double will combine these two functions but will need a list as an argument.
-- ghci> double [1..11]
-- [2,4,6,8,10,12,14,16,18,20,22]
------------
-- FILTER --
-- ---------
-- tests each list element and makes a new list with what it collects.
-- and note how our composite function fits the type of the one it calls
-- ghci>:i null
-- null :: [a] -> Bool -- Defined in `GHC.List'
notNull :: [a] -> Bool
notNull xs = not (null xs)
-- ghci> filter notNull ["","there","","we","","are"]
-- ["there","we","are"]
-- filter tests and then collects.
isEven x = x `mod` 2 == 0
removeOdd = filter isEven
{-
-
isEven :: Integral a => a -> Bool
removeOdd :: [Integer] -> [Integer]
ghci>removeOdd [1..11]
[2,4,6,8,10]
-- using
filter :: (a -> Bool) -> [a] -> [a] -- Defined in `GHC.List'
map :: (a -> b) -> [a] -> [b] -- Defined in `GHC.Base'
fst :: (a, b) -> a -- Defined in `Data.Tuple'
snd :: (a, b) -> b -- Defined in `Data.Tuple'
-- map says give me the second part of this list of tuples but only after
-- filter using fst to test the fist part of the tuple and because filter will only take Trues that's all that comes back.
ghci> map snd (filter fst [(True, 1),(False,7),(True,11)])
[1,11]
-}
------------------
-- FOLDL and FOLDR --
-- ---------------
{- fold collects from a list and reduces the collection to a new single value
*HighOrdFun> foldl (+) 0 [1..11]
66
-- 0 is the accumulator value (acc) and we want to start accumulating from zero.
-- but we could start with any value.
*HighOrdFun> foldl (+) 10 [1..11]
76
*HighOrdFun> foldl (+) (-10) [1..11]
56
-- just like sum but different.
*HighOrdFun> sum [1..11]
66
*HighOrdFun> sum [1..11] == foldl (+) 0 [1..11]
True
-}
-- show is basically a to->string function
showPlus :: Show a => [Char] -> a -> [Char]
showPlus s x = "(" ++ s ++ "+" ++ (show x) ++ ")"
{-
- *HighOrdFun> showPlus "(1+2)" 3
"((1+2)+3)"
*HighOrdFun> foldl showPlus "0" [1..11]
"(((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)+11)"
-- take out the quotes and we get
*HighOrdFun> (((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)+11)
66
-}
---------------------------------
-- showCons ? how would that work
---------------------------------
{-
- Prelude> foldr (+) 0 [1..11]
66
-- does the same thing but the accumulator goes to the other side
--
-}
showPlus' :: Show a => a -> [Char] -> [Char]
showPlus' x s = "(" ++ (show x) ++ "+" ++ s ++ ")"
{-
*HighOrdFun> foldr showPlus' "0" [1..11]
"(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+(11+0)))))))))))"
*HighOrdFun> foldr (-) 0 [1..11]
6
*HighOrdFun> foldl (-) 0 [1..11]
-66
*HighOrdFun> foldl (*) 0 [1..11]
0
*HighOrdFun> foldr (*) 0 [1..11]
0
*HighOrdFun> foldr (*) 1 [1..11]
39916800
*HighOrdFun> foldl (*) 1 [1..11]
39916800
*HighOrdFun> foldl (+) 1 [1..11]
67
*HighOrdFun> foldr (+) 1 [1..11]
67
*HighOrdFun> foldr (/) 1 [1..11]
2.7070312499999996
*HighOrdFun> foldl (/) 1 [1..11]
2.505210838544172e-8
*HighOrdFun> foldl (/) 0 [1..11]
0.0
*HighOrdFun> foldr (/) 0 [1..11]
Infinity
-- foldl is tail recursive but NOT ON AN INFINITE LIST
-- foldr can be used on an infinite list with caution
---------- --
-- ZIPWITH --
-- ------- --
combines zip with a (function)
*HighOrdFun> zipWith (*) [1..11] [101..111]
[101,204,309,416,525,636,749,864,981,1100,1221]
*HighOrdFun> zipWith (+) [1..11] [101..111]
[102,104,106,108,110,112,114,116,118,120,122]
*HighOrdFun> zipWith (+) [1..11] [101..1111]
[102,104,106,108,110,112,114,116,118,120,122]
*HighOrdFun> zipWith mod [1..11] [2..12]
[1,2,3,4,5,6,7,8,9,10,11]
*HighOrdFun> zipWith (/) [2,3,4] [1,2,3]
[2.0,1.5,1.3333333333333333]
-}
mult3 x y z = x*y*z
{- zipWith3 needs a function that can take three arguments
- *HighOrdFun> zipWith3 mult3 [2,3,4] [1,2,3] [0,1,2]
[0,6,24]
if we wanted to do it with addition but didn't want to have to throw in another
named function we could have done it this way:
*HighOrdFun> zipWith3 (\ x y z -> x+y+z) [2,3,4] [1,2,3] [0,1,2]
[3,6,9]
or with currying
*HighOrdFun> zipWith3 (\x -> \y -> \z -> x+y+z) [2,3,4] [1,2,3] [0,1,2]
[3,6,9]
*HighOrdFun> map (\x -> 2 * x) [1..11]
[2,4,6,8,10,12,14,16,18,20,22]
which is the same as:
*HighOrdFun> map (\x -> 2 * x) [1..11] == map (*2) [1..11]
True
because map has to touch the list [1..11] for it's second argument
*HighOrdFun> map (\x -> 2 * x +1) [1..11]
[3,5,7,9,11,13,15,17,19,21,23]
we can't just throw another (+1)
we so we have to call map recursively
but even that isn't right
*HighOrdFun> map (*2) (map (1+) [1..11])
[4,6,8,10,12,14,16,18,20,22,24]
so we would have to go further
*HighOrdFun> map (+(-1)) (map (*2) (map (1+) [1..11]))
[3,5,7,9,11,13,15,17,19,21,23]
*HighOrdFun> map(+(-1))(map(*2)(map (1+)[1..11])) == map(\x -> 2 * x +1)[1..11]
True
-}
------------------------
-- FUNCTION OPERATORS --
-- ---------------------
-- (.) function composition
-- ($) application
-- length :: [a] -> Int -- Defined in `GHC.List'
{-class Show a where
...
show :: a -> String
...
-- Defined in `GHC.Show'-}
-- stringLength :: [a] -> String
-- stringLength n = length.show n
-- stringLength :: Show a => a -> Int
stringLength n = length(show n)
{-
*HighOrdFun> stringLength [1..11]
"11"
*HighOrdFun> stringLength (product [x^2|x<-[1..1111]])
5807
-} -- fn7 (product [x^2|x<-[1..1111]])
{-------------------------------
-- $
-- -----------------------------
*HighOrdFun> map (\f -> f 3) [(+1), (\x-> 2 *x + 3), (*2)]
[4,9,6]
*HighOrdFun> map ($3) [(+1), (\x -> 2*x +3), (*2)]
[4,9,6]
*HighOrdFun> zipWith ($) [(+1), (\x-> 2*x +3), (*2)] [1,2,3]
[2,7,6]
| HaskellForCats/HaskellForCats | MenaBeginning/Ch007/2014-0130-higherOrderFunc.hs | mit | 9,874 | 2 | 15 | 1,899 | 1,053 | 621 | 432 | -1 | -1 |
-- | Utilities on text.
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UnicodeSyntax #-}
module Apia.Utils.Text
( (+++)
, parens
, toUpperFirst
) where
------------------------------------------------------------------------------
import Apia.Prelude
import Agda.Utils.Impossible ( Impossible(Impossible), throwImpossible )
import Data.Text ( Text )
import qualified Data.Text as T
#include "undefined.h"
------------------------------------------------------------------------------
-- | Append synonymous.
(+++) ∷ Text → Text → Text
(+++) = T.append
-- | Convert the first letter of a text to the corresponding upper-case letter.
toUpperFirst ∷ Text → Text
toUpperFirst xs =
case T.uncons xs of
Just (x', xs') → T.cons (toUpper x') xs'
Nothing → __IMPOSSIBLE__
-- | Wrap text in ( ... ).
parens ∷ Text → Text
parens t = "(" +++ t +++ ")"
| asr/apia | src/Apia/Utils/Text.hs | mit | 934 | 0 | 10 | 174 | 180 | 109 | 71 | 20 | 2 |
module CopyDir
( copyDir
) where
-- Copied from http://stackoverflow.com/questions/6807025/what-is-the-haskell-way-to-copy-a-directory
import System.Directory
import System.FilePath ((</>))
import Control.Applicative ((<$>))
import Control.Concurrent.Async (mapConcurrently)
import Control.Exception (throw)
import Control.Monad (when, void)
copyDir :: FilePath -> FilePath -> IO ()
copyDir src dst = do
whenM (not <$> doesDirectoryExist src) $
throw (userError "source does not exist")
whenM (doesDirectoryExist dst `orM` doesFileExist dst) $
throw (userError "destination already exists")
createDirectoryIfMissing True dst
files <- filter (`notElem` [".", ".."]) <$> getDirectoryContents src
void $ forConcurrently files $ \name -> do
let srcPath = src </> name
let dstPath = dst </> name
isDirectory <- doesDirectoryExist srcPath
if isDirectory
then copyDir srcPath dstPath
else copyFile srcPath dstPath
where
forConcurrently = flip mapConcurrently
whenM s r = s >>= flip when r
orM :: Monad m => m Bool -> m Bool -> m Bool
orM m1 m2 = m1 >>= \x-> if x then return x else m2
| CovenantEyes/libget-hs | src/CopyDir.hs | mit | 1,190 | 0 | 14 | 264 | 365 | 187 | 178 | 27 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module MonadBot.Plugins.Version
( plugin
) where
import Data.List
import Data.Text (pack)
import Data.Version (showVersion)
import Paths_monadbot (version)
import Data.Time
import Data.Time.Clock
import MonadBot.Message
import MonadBot.Plugin.Development
versionHandler :: PluginM UTCTime ()
versionHandler = onCtcp "VERSION" $ do
pref <- getPrefix
case pref of
Just (UserPrefix p _ _) ->
ctcpReply p ["VERSION", "monadbot v" <> pack (showVersion version)]
_ -> return ()
userVersion :: PluginM UTCTime ()
userVersion = onUserCmds ["$version", "$info"] $ do
(channel:_) <- getParams
sendPrivmsg channel ["I am monadbot v" <> pack (showVersion version)]
start <- readState
current <- liftIO getCurrentTime
let diff = round $ diffUTCTime current start
let formatted = formatSeconds diff
sendPrivmsg channel ["Uptime:", pack formatted]
formatSeconds :: Integer -> String
formatSeconds s = unwords $ formatSeconds' s units
where
formatSeconds' _ [] = []
formatSeconds' remainder ((label, time):us) =
case divMod remainder time of
(0, r) ->
formatSeconds' r us
(n, r) ->
(show n ++ label) : formatSeconds' r us
units =
[ ("y", 365 * 24 * 60 * 60)
, ("m", 30 * 24 * 60 * 60)
, ("d", 24 * 60 * 60)
, ("h", 60 * 60)
, ("m", 60)
, ("s", 1)
]
initState :: Irc UTCTime
initState =
liftIO getCurrentTime
plugin :: Plugin UTCTime
plugin =
Plugin
"Version and info handler"
[versionHandler, userVersion]
initState
(const $ return ())
| saevarb/Monadbot | lib/MonadBot/Plugins/Version.hs | mit | 1,678 | 0 | 16 | 449 | 565 | 298 | 267 | 53 | 3 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeSynonymInstances, ExistentialQuantification, Rank2Types #-}
module Perl.SV
( FromSV (..)
, ToSV (..)
, globalSV
, peekGlobalSV
, ToSVObj (..)
, isSV
, isAV
, isHV
, isCV
, svType
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Array.IArray
import Foreign.C.Types
import Foreign.C.String
import Foreign.Ptr
import Perl.Type
import Perl.Constant
import Perl.Class
import Perl.Monad
import Perl.Internal.MonadGlue
peekGlobalSV :: (MonadCatch m, MonadIO m) => String -> PerlT s m (Maybe SV)
peekGlobalSV name = do
sv <- perlWithAnyIO (withCStringLen name) (flip getSV 0)
return $ if sv == nullPtr
then Nothing
else Just sv
globalSV :: (MonadCatch m, MonadIO m) => String -> PerlT s m SV
globalSV name = perlWithAnyIO (withCStringLen name) (flip getSV 1)
isSV, isAV, isHV, isCV :: (MonadCatch m, MonadIO m) => SV -> PerlT s m Bool
isSV sv = svType sv >>= return . (< const_SVt_PVAV)
isAV sv = svType sv >>= return . (== const_SVt_PVAV)
isHV sv = svType sv >>= return . (== const_SVt_PVHV)
isCV sv = svType sv >>= return . (== const_SVt_PVCV)
instance FromSV SV where
fromSVNon = newSV
fromSV = newSVSV
instance FromSV Int where
fromSVNon = return 0
fromSV sv = do
int <- svToInt sv
return (fromIntegral int)
instance FromSV Double where
fromSVNon = return 0
fromSV sv = do
CDouble double <- svToNum sv
return double
instance FromSV String where
fromSVNon = return ""
fromSV sv = do
cStrLen <- svToStr sv
liftIO $ peekCStringLen cStrLen
refFromSVNon :: (MonadCatch m, MonadIO m) => PerlT s m (Ptr a)
refFromSVNon = newSV >>= return . castPtr
refFromSV :: (MonadCatch m, MonadIO m) => SV -> PerlT s m (Ptr a)
refFromSV sv = newSVSV sv >>= return . castPtr
instance FromSV RefSV where
fromSVNon = refFromSVNon
fromSV = refFromSV
instance FromSV RefAV where
fromSVNon = refFromSVNon
fromSV = refFromSV
instance FromSV RefHV where
fromSVNon = refFromSVNon
fromSV = refFromSV
instance FromSV RefCV where
fromSVNon = refFromSVNon
fromSV = refFromSV
instance ToSV ToSVObj where
toSV (ToSVObj a) = toSV a
toSVMortal (ToSVObj a) = toSVMortal a
setSV sv (ToSVObj a) = setSV sv a
asSV (ToSVObj a) = asSV a
instance ToSV SV where
toSV = newSVSV
toSVMortal = newSVSVMortal
setSV = setSVSV
asSV = return
instance ToSV () where
toSV _ = newSV
toSVMortal _ = newSVMortal
setSV sv _ = setSVUndef sv
instance ToSV Int where
toSV n = newIntSV (fromIntegral n)
toSVMortal n = newIntSVMortal (fromIntegral n)
setSV sv = setSVInt sv . fromIntegral
instance ToSV Double where
toSV d = newNumSV (CDouble d)
toSVMortal d = newNumSVMortal (CDouble d)
setSV sv = setSVNum sv . CDouble
instance ToSV String where
toSV str = PerlT $ \perl cv ->
liftIO . withCStringLen str $ \(cstr, len) ->
unPerlT (newStrSV cstr (fromIntegral len)) perl cv
toSVMortal str = PerlT $ \perl cv ->
liftIO . withCStringLen str $ \(cstr, len) ->
unPerlT (newStrSVMortal cstr (fromIntegral len)) perl cv
setSV sv str = PerlT $ \perl cv ->
liftIO . withCStringLen str $ \(cstr, len) ->
unPerlT (setSVStr sv cstr (fromIntegral len)) perl cv
data ToSVObj = forall a. ToSV a => ToSVObj a
instance ToSV RefSV where asSV = return . castPtr
instance ToSV RefAV where asSV = return . castPtr
instance ToSV RefHV where asSV = return . castPtr
instance ToSV RefCV where asSV = return . castPtr
| CindyLinz/Haskell-Perl | src/Perl/SV.hs | mit | 3,545 | 0 | 14 | 739 | 1,276 | 664 | 612 | 109 | 2 |
{-----------------------------------------------------------------------------------------
Module name: Hex
Made by: Tomas Möre 2015
------------------------------------------------------------------------------------------}
module Smutt.Util.Hex (module Hex) where
import Smutt.Util.Hex.String as Hex
| black0range/Smutt | src/Smutt/Util/Hex.hs | mit | 310 | 0 | 4 | 26 | 23 | 17 | 6 | 2 | 0 |
-- Words to sentence
-- https://www.codewars.com/kata/57a06005cf1fa5fbd5000216
module WordsToSentence where
wordsToSentence :: [String] -> String
wordsToSentence = unwords
| gafiatulin/codewars | src/7 kyu/WordsToSentence.hs | mit | 174 | 0 | 6 | 19 | 23 | 15 | 8 | 3 | 1 |
{-#LANGUAGE OverloadedStrings #-}
module Web.Scotty.Lucid where
import Web.Scotty
import Lucid
lucid :: Html a -> ActionM ()
lucid h = do
setHeader "Content-Type" "text/html"
raw . renderBS $ h
| arianvp/scotty-lucid | Web/Scotty/Lucid.hs | mit | 220 | 0 | 8 | 55 | 60 | 31 | 29 | 8 | 1 |
{-# LANGUAGE CPP #-}
{-
Copyright (C) 2008 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- Functions for maintaining user list and session state.
-}
module Network.Gitit.Cache ( expireCachedFile
, lookupCache
, cacheContents )
where
import qualified Data.ByteString as B (ByteString, readFile, writeFile)
import System.FilePath
import System.Directory (doesFileExist, removeFile, createDirectoryIfMissing, getModificationTime)
import Data.Time.Clock (UTCTime)
#if MIN_VERSION_directory(1,2,0)
#else
import System.Time (ClockTime(..))
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
#endif
import Network.Gitit.State
import Network.Gitit.Types
import Control.Monad
import Control.Monad.Trans (liftIO)
import Codec.Binary.UTF8.String (encodeString)
-- | Expire a cached file, identified by its filename in the filestore.
-- If there is an associated exported PDF, expire it too.
-- Returns () after deleting a file from the cache, fails if no cached file.
expireCachedFile :: String -> GititServerPart ()
expireCachedFile file = do
cfg <- getConfig
let target = encodeString $ cacheDir cfg </> file
exists <- liftIO $ doesFileExist target
when exists $ liftIO $ do
liftIO $ removeFile target
expireCachedPDF target
expireCachedPDF :: String -> IO ()
expireCachedPDF file =
when (takeExtension file == ".page") $ do
let pdfname = file ++ ".export.pdf"
exists <- doesFileExist pdfname
when exists $ removeFile pdfname
lookupCache :: String -> GititServerPart (Maybe (UTCTime, B.ByteString))
lookupCache file = do
cfg <- getConfig
let target = encodeString $ cacheDir cfg </> file
exists <- liftIO $ doesFileExist target
if exists
then liftIO $ do
#if MIN_VERSION_directory(1,2,0)
modtime <- getModificationTime target
#else
TOD secs _ <- getModificationTime target
let modtime = posixSecondsToUTCTime $ fromIntegral secs
#endif
contents <- B.readFile target
return $ Just (modtime, contents)
else return Nothing
cacheContents :: String -> B.ByteString -> GititServerPart ()
cacheContents file contents = do
cfg <- getConfig
let target = encodeString $ cacheDir cfg </> file
let targetDir = takeDirectory target
liftIO $ do
createDirectoryIfMissing True targetDir
B.writeFile target contents
expireCachedPDF target
| thielema/gitit | Network/Gitit/Cache.hs | gpl-2.0 | 3,049 | 0 | 13 | 576 | 523 | 266 | 257 | 50 | 2 |
{-# OPTIONS_GHC -Wall -fwarn-tabs -Werror #-}
-------------------------------------------------------------------------------
-- |
-- Module : Input.Mouse
-- Copyright : Copyright (c) 2014 Michael R. Shannon
-- License : GPLv2 or Later
-- Maintainer : mrshannon.aerospace@gmail.com
-- Stability : unstable
-- Portability : portable
--
-- Mouse input module.
-------------------------------------------------------------------------------
module Input.Mouse
( cycleMouse
, diffMouse
, defaultMouseClickOnly
, defaultMouseDownOnly
, defaultMouseTracking
, defaultMouseFPS
, Mouse(..)
, Buttons(..)
, ButtonState(..)
, Position(..)
, DeltaPosition(..)
) where
import Input.Mouse.Types
-- Change button state from pressed to down and released to up.
cycleButton :: ButtonState -> ButtonState
cycleButton bs = if bs <= ButtonDown then ButtonDown else ButtonUp
-- Set all ButtonPressed values to ButtonDown and the ButtonReleased values to
-- ButtonUp. It also resets the wheel ticks to 0.
cycleMouse :: Mouse -> Mouse
cycleMouse m = m { buttons = newButtons, wheelTicks = 0 }
where
b = buttons m
newButtons = b { leftButton = cycleButton $ leftButton b
, middleButton = cycleButton $ middleButton b
, rightButton = cycleButton $ rightButton b
}
-- | Calculate difference between two mouse positions.
diffMouse :: Position -> Position -> DeltaPosition
diffMouse (Position x0 y0) (Position x1 y1) =
DeltaPosition ( fromIntegral x1 - fromIntegral x0 )
( fromIntegral y1 - fromIntegral y0 )
-- Default button state (all buttons up).
defaultButtons :: Buttons
defaultButtons = Buttons
{ leftButton = ButtonUp
, middleButton = ButtonUp
, rightButton = ButtonUp
}
-- Default ClickOnly configuration.
defaultMouseClickOnly :: Mouse
defaultMouseClickOnly = ClickOnly
{ buttons = defaultButtons
, wheelTicks = 0
, downPosition = Position 0 0
, upPosition = Position 0 0
}
-- Default DownOnly configuration.
defaultMouseDownOnly :: Mouse
defaultMouseDownOnly = DownOnly
{ buttons = defaultButtons
, wheelTicks = 0
, downPosition = Position 0 0
, upPosition = Position 0 0
, position = Position 0 0
, deltaPosition = DeltaPosition 0 0
}
-- Default Tracking configuration.
defaultMouseTracking :: Mouse
defaultMouseTracking = Tracking
{ buttons = defaultButtons
, wheelTicks = 0
, downPosition = Position 0 0
, upPosition = Position 0 0
, position = Position 0 0
, deltaPosition = DeltaPosition 0 0
}
-- Default FPS configuration.
defaultMouseFPS :: Mouse
defaultMouseFPS = FPS
{ buttons = defaultButtons
, wheelTicks = 0
, deltaPosition = DeltaPosition 0 0
}
| mrshannon/trees | src/Input/Mouse.hs | gpl-2.0 | 2,894 | 0 | 10 | 729 | 521 | 310 | 211 | 58 | 2 |
{-# LANGUAGE NoImplicitPrelude, LambdaCase #-}
module Lamdu.Eval.Results.Process
( addTypes
) where
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Lamdu.Builtins.Anchors as Builtins
import qualified Lamdu.Calc.Type as T
import qualified Lamdu.Calc.Type.FlatComposite as FlatComposite
import qualified Lamdu.Calc.Type.Nominal as N
import Lamdu.Calc.Type.Scheme (schemeType)
import qualified Lamdu.Calc.Val as V
import Lamdu.Eval.Results (Val(..), Body(..))
import qualified Lamdu.Eval.Results as ER
import Lamdu.Infer (applyNominal)
import Prelude.Compat
extractRecordTypeField :: T.Tag -> T.Type -> Maybe (T.Type, T.Type)
extractRecordTypeField tag typ =
do
comp <- typ ^? T._TRecord
let flat = FlatComposite.fromComposite comp
fieldType <- flat ^. FlatComposite.fields . Lens.at tag
Just
( fieldType
, flat
& FlatComposite.fields . Lens.at tag .~ Nothing
& FlatComposite.toComposite & T.TRecord
)
extractSumTypeField :: T.Tag -> T.Type -> Maybe T.Type
extractSumTypeField tag typ =
do
comp <- typ ^? T._TSum
FlatComposite.fromComposite comp ^. FlatComposite.fields . Lens.at tag
type AddTypes val res = (T.Type -> val -> res) -> T.Type -> Body res
addTypesRecExtend :: V.RecExtend val -> AddTypes val res
addTypesRecExtend (V.RecExtend tag val rest) go typ =
case extractRecordTypeField tag typ of
Nothing ->
-- TODO: this is a work-around for a bug. HACK
-- we currently don't know types for eval results of polymorphic values
case typ of
T.TVar{} ->
V.RecExtend tag
(go typ val)
(go typ rest)
& RRecExtend
_ -> ER.EvalTypeError "addTypes bad type for RRecExtend" & RError
Just (valType, restType) ->
V.RecExtend tag
(go valType val)
(go restType rest)
& RRecExtend
addTypesInject :: V.Inject val -> AddTypes val res
addTypesInject (V.Inject tag val) go typ =
case extractSumTypeField tag typ of
Nothing ->
-- TODO: this is a work-around for a bug. HACK
-- we currently don't know types for eval results of polymorphic values
case typ of
T.TVar{} -> go typ val & V.Inject tag & RInject
_ -> ER.EvalTypeError "addTypes bad type for RInject" & RError
Just valType -> go valType val & V.Inject tag & RInject
addTypesArray :: [val] -> AddTypes val res
addTypesArray items go typ =
do
(_nomId, params) <- typ ^? T._TInst
paramType <- params ^. Lens.at Builtins.valTypeParamId
items <&> go paramType & RArray & Just
& fromMaybe (ER.EvalTypeError "addTypes bad type for RArray" & RError)
addTypes :: Map T.NominalId N.Nominal -> T.Type -> Val () -> Val T.Type
addTypes nomsMap typ (Val () b) =
case b of
RRecExtend recExtend -> recurse (addTypesRecExtend recExtend)
RInject inject -> recurse (addTypesInject inject)
RArray items -> recurse (addTypesArray items)
RFunc -> RFunc
RRecEmpty -> RRecEmpty
RPrimVal l -> RPrimVal l
RError e -> RError e
& Val typ
where
recurse f = f (addTypes nomsMap) (unwrapTInsts nomsMap typ)
-- Will loop forever for bottoms like: newtype Void = Void Void
unwrapTInsts :: Map T.NominalId N.Nominal -> T.Type -> T.Type
unwrapTInsts nomsMap typ =
case typ of
T.TInst tid params ->
Map.lookup tid nomsMap
& fromMaybe (error "addTypes: nominal missing from map")
& applyNominal params
& \case
N.OpaqueNominal -> typ
N.NominalType scheme -> scheme ^. schemeType & unwrapTInsts nomsMap
_ -> typ
| da-x/lamdu | Lamdu/Eval/Results/Process.hs | gpl-3.0 | 3,873 | 0 | 14 | 1,034 | 1,109 | 571 | 538 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.Parsec.Prim
-- Copyright : (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : derek.a.elkins@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- The primitive parser combinators.
--
-----------------------------------------------------------------------------
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts,
UndecidableInstances, FlexibleInstances, RankNTypes #-}
module Text.Parsec.Prim
( unknownError
, sysUnExpectError
, unexpected
, ParsecT
, runParsecT
, mkPT
, Parsec
, Consumed(..)
, Reply(..)
, State(..)
, parsecMap
, parserReturn
, parserBind
, mergeErrorReply
, parserFail
, parserError
, parserZero
, parserPlus
, (<?>)
, (<|>)
, label
, labels
, lookAhead
, Stream(..)
, tokens
, try
, token
, tokenPrim
, tokenPrimEx
, many
, skipMany
, manyAccum
, runPT
, runP
, runParserT
, runParser
, parse
, parseTest
, getPosition
, getInput
, setPosition
, setInput
, getParserState
, setParserState
, updateParserState
, getState
, putState
, modifyState
, setState
, updateState
) where
import qualified Control.Applicative as Applicative ( Applicative(..), Alternative(..) )
import Control.Monad()
import Control.Monad.Trans
import Control.Monad.Identity
import Control.Monad.Reader.Class
import Control.Monad.State.Class
import Control.Monad.Cont.Class
import Control.Monad.Error.Class
import Text.Parsec.Pos
import Text.Parsec.Error
unknownError :: State s u -> ParseError
unknownError state = newErrorUnknown (statePos state)
sysUnExpectError :: String -> SourcePos -> Reply s u a
sysUnExpectError msg pos = Error (newErrorMessage (SysUnExpect msg) pos)
-- | The parser @unexpected msg@ always fails with an unexpected error
-- message @msg@ without consuming any input.
--
-- The parsers 'fail', ('<?>') and @unexpected@ are the three parsers
-- used to generate error messages. Of these, only ('<?>') is commonly
-- used. For an example of the use of @unexpected@, see the definition
-- of 'Text.Parsec.Combinator.notFollowedBy'.
unexpected :: (Stream s m t) => String -> ParsecT s u m a
unexpected msg
= ParsecT $ \s _ _ _ eerr ->
eerr $ newErrorMessage (UnExpect msg) (statePos s)
-- | ParserT monad transformer and Parser type
-- | @ParsecT s u m a@ is a parser with stream type @s@, user state type @u@,
-- underlying monad @m@ and return type @a@. Parsec is strict in the user state.
-- If this is undesirable, simply used a data type like @data Box a = Box a@ and
-- the state type @Box YourStateType@ to add a level of indirection.
newtype ParsecT s u m a
= ParsecT {unParser :: forall b .
State s u
-> (a -> State s u -> ParseError -> m b) -- consumed ok
-> (ParseError -> m b) -- consumed err
-> (a -> State s u -> ParseError -> m b) -- empty ok
-> (ParseError -> m b) -- empty err
-> m b
}
-- | Low-level unpacking of the ParsecT type. To run your parser, please look to
-- runPT, runP, runParserT, runParser and other such functions.
runParsecT :: Monad m => ParsecT s u m a -> State s u -> m (Consumed (m (Reply s u a)))
runParsecT p s = unParser p s cok cerr eok eerr
where cok a s' err = return . Consumed . return $ Ok a s' err
cerr err = return . Consumed . return $ Error err
eok a s' err = return . Empty . return $ Ok a s' err
eerr err = return . Empty . return $ Error err
-- | Low-level creation of the ParsecT type. You really shouldn't have to do this.
mkPT :: Monad m => (State s u -> m (Consumed (m (Reply s u a)))) -> ParsecT s u m a
mkPT k = ParsecT $ \s cok cerr eok eerr -> do
cons <- k s
case cons of
Consumed mrep -> do
rep <- mrep
case rep of
Ok x s' err -> cok x s' err
Error err -> cerr err
Empty mrep -> do
rep <- mrep
case rep of
Ok x s' err -> eok x s' err
Error err -> eerr err
type Parsec s u = ParsecT s u Identity
data Consumed a = Consumed a
| Empty !a
data Reply s u a = Ok a !(State s u) ParseError
| Error ParseError
data State s u = State {
stateInput :: s,
stateRetry :: State s u -> Maybe (State s u),
statePos :: !SourcePos,
stateUser :: !u
}
instance Functor Consumed where
fmap f (Consumed x) = Consumed (f x)
fmap f (Empty x) = Empty (f x)
instance Functor (Reply s u) where
fmap f (Ok x s e) = Ok (f x) s e
fmap _ (Error e) = Error e -- XXX
instance Functor (ParsecT s u m) where
fmap f p = parsecMap f p
parsecMap :: (a -> b) -> ParsecT s u m a -> ParsecT s u m b
parsecMap f p
= ParsecT $ \s cok cerr eok eerr ->
unParser p s (cok . f) cerr (eok . f) eerr
instance Applicative.Applicative (ParsecT s u m) where
pure = return
(<*>) = ap -- TODO: Can this be optimized?
instance Applicative.Alternative (ParsecT s u m) where
empty = mzero
(<|>) = mplus
instance Monad (ParsecT s u m) where
return x = parserReturn x
p >>= f = parserBind p f
fail msg = parserFail msg
instance (MonadIO m) => MonadIO (ParsecT s u m) where
liftIO = lift . liftIO
instance (MonadReader r m) => MonadReader r (ParsecT s u m) where
ask = lift ask
local f p = mkPT $ \s -> local f (runParsecT p s)
-- I'm presuming the user might want a separate, non-backtracking
-- state aside from the Parsec user state.
instance (MonadState s m) => MonadState s (ParsecT s' u m) where
get = lift get
put = lift . put
instance (MonadCont m) => MonadCont (ParsecT s u m) where
callCC f = mkPT $ \s ->
callCC $ \c ->
runParsecT (f (\a -> mkPT $ \s' -> c (pack s' a))) s
where pack s a= Empty $ return (Ok a s (unknownError s))
instance (MonadError e m) => MonadError e (ParsecT s u m) where
throwError = lift . throwError
p `catchError` h = mkPT $ \s ->
runParsecT p s `catchError` \e ->
runParsecT (h e) s
parserReturn :: a -> ParsecT s u m a
parserReturn x
= ParsecT $ \s _ _ eok _ ->
eok x s (unknownError s)
parserBind :: ParsecT s u m a -> (a -> ParsecT s u m b) -> ParsecT s u m b
{-# INLINE parserBind #-}
parserBind m k
= ParsecT $ \s cok cerr eok eerr ->
let
-- consumed-okay case for m
mcok x s err =
let
p' = k x
-- if (k x) consumes, those go straigt up
pcok = cok
pcerr = cerr
-- if (k x) doesn't consume input, but is okay,
-- we still return in the consumed continuation
peok x s err' = cok x s (mergeError err err')
-- if (k x) doesn't consume input, but errors,
-- we first retry if possible then return the
-- error in the 'consumed-error' continuation
peerr err' = case stateRetry s s of
Nothing -> cerr (mergeError err err')
Just s' -> unParser p' s' pcok pcerr peok peerr
in unParser p' s pcok pcerr peok peerr
-- empty-ok case for m
meok x s err =
let
-- in these cases, (k x) can return as empty
pcok = cok
peok x s err' = eok x s (mergeError err err')
pcerr = cerr
peerr err' = eerr (mergeError err err')
in unParser (k x) s pcok pcerr peok peerr
-- consumed-error case for m
mcerr = cerr
-- empty-error case for m
meerr = eerr
in unParser m s mcok mcerr meok meerr
mergeErrorReply :: ParseError -> Reply s u a -> Reply s u a
mergeErrorReply err1 reply -- XXX where to put it?
= case reply of
Ok x state err2 -> Ok x state (mergeError err1 err2)
Error err2 -> Error (mergeError err1 err2)
parserFail :: String -> ParsecT s u m a
parserFail msg
= ParsecT $ \s _ _ _ eerr ->
eerr $ newErrorMessage (Message msg) (statePos s)
parserError err
= ParsecT $ \s _ _ _ eerr ->
eerr err
instance MonadPlus (ParsecT s u m) where
mzero = parserZero
mplus p1 p2 = parserPlus p1 p2
-- | @parserZero@ always fails without consuming any input. @parserZero@ is defined
-- equal to the 'mzero' member of the 'MonadPlus' class and to the 'Control.Applicative.empty' member
-- of the 'Control.Applicative.Applicative' class.
parserZero :: ParsecT s u m a
parserZero
= ParsecT $ \s _ _ _ eerr ->
eerr $ unknownError s
parserPlus :: ParsecT s u m a -> ParsecT s u m a -> ParsecT s u m a
{-# INLINE parserPlus #-}
parserPlus m n
= ParsecT $ \s cok cerr eok eerr ->
let
meerr err =
let
neok y s' err' = eok y s' (mergeError err err')
neerr err' = eerr $ mergeError err err'
in unParser n s cok cerr neok neerr
in unParser m s cok cerr eok meerr
instance MonadTrans (ParsecT s u) where
lift amb = ParsecT $ \s _ _ eok _ -> do
a <- amb
eok a s $ unknownError s
infix 0 <?>
infixr 1 <|>
-- | The parser @p <?> msg@ behaves as parser @p@, but whenever the
-- parser @p@ fails /without consuming any input/, it replaces expect
-- error messages with the expect error message @msg@.
--
-- This is normally used at the end of a set alternatives where we want
-- to return an error message in terms of a higher level construct
-- rather than returning all possible characters. For example, if the
-- @expr@ parser from the 'try' example would fail, the error
-- message is: '...: expecting expression'. Without the @(\<?>)@
-- combinator, the message would be like '...: expecting \"let\" or
-- letter', which is less friendly.
(<?>) :: (ParsecT s u m a) -> String -> (ParsecT s u m a)
p <?> msg = label p msg
-- | This combinator implements choice. The parser @p \<|> q@ first
-- applies @p@. If it succeeds, the value of @p@ is returned. If @p@
-- fails /without consuming any input/, parser @q@ is tried. This
-- combinator is defined equal to the 'mplus' member of the 'MonadPlus'
-- class and the ('Control.Applicative.<|>') member of 'Control.Applicative.Alternative'.
--
-- The parser is called /predictive/ since @q@ is only tried when
-- parser @p@ didn't consume any input (i.e.. the look ahead is 1).
-- This non-backtracking behaviour allows for both an efficient
-- implementation of the parser combinators and the generation of good
-- error messages.
(<|>) :: (ParsecT s u m a) -> (ParsecT s u m a) -> (ParsecT s u m a)
p1 <|> p2 = mplus p1 p2
label :: ParsecT s u m a -> String -> ParsecT s u m a
label p msg
= labels p [msg]
labels :: ParsecT s u m a -> [String] -> ParsecT s u m a
labels p msgs =
ParsecT $ \s cok cerr eok eerr ->
let eok' x s' error = eok x s' $ if errorIsUnknown error
then error
else setExpectErrors error msgs
eerr' err = eerr $ setExpectErrors err msgs
in unParser p s cok cerr eok' eerr'
where
setExpectErrors err [] = setErrorMessage (Expect "") err
setExpectErrors err [msg] = setErrorMessage (Expect msg) err
setExpectErrors err (msg:msgs)
= foldr (\msg' err' -> addErrorMessage (Expect msg') err')
(setErrorMessage (Expect msg) err) msgs
-- TODO: There should be a stronger statement that can be made about this
-- | An instance of @Stream@ has stream type @s@, underlying monad @m@ and token type @t@ determined by the stream
--
-- Some rough guidelines for a \"correct\" instance of Stream:
--
-- * unfoldM uncons gives the [t] corresponding to the stream
--
-- * A @Stream@ instance is responsible for maintaining the \"position within the stream\" in the stream state @s@. This is trivial unless you are using the monad in a non-trivial way.
class (Monad m) => Stream s m t | s -> t where
uncons :: s -> m (Maybe (t,s))
tokens :: (Stream s m t, Eq t)
=> ([t] -> String) -- Pretty print a list of tokens
-> (SourcePos -> [t] -> SourcePos)
-> [t] -- List of tokens to parse
-> ParsecT s u m [t]
{-# INLINE tokens #-}
tokens _ _ []
= ParsecT $ \s _ _ eok _ ->
eok [] s $ unknownError s
tokens showTokens nextposs tts@(tok:toks)
= ParsecT $ \(State input retry pos u) cok cerr eok eerr ->
let
errEof = (setErrorMessage (Expect (showTokens tts))
(newErrorMessage (SysUnExpect "") pos))
errExpect x = (setErrorMessage (Expect (showTokens tts))
(newErrorMessage (SysUnExpect (showTokens [x])) pos))
walk [] rs = ok rs
walk (t:ts) rs = do
sr <- uncons rs
case sr of
Nothing -> cerr $ errEof
Just (x,xs) | t == x -> walk ts xs
| otherwise -> cerr $ errExpect x
ok rs = let pos' = nextposs pos tts
s' = State rs retry pos' u
in cok tts s' (newErrorUnknown pos')
in do
sr <- uncons input
case sr of
Nothing -> eerr $ errEof
Just (x,xs)
| tok == x -> walk toks xs
| otherwise -> eerr $ errExpect x
-- | The parser @try p@ behaves like parser @p@, except that it
-- pretends that it hasn't consumed any input when an error occurs.
--
-- This combinator is used whenever arbitrary look ahead is needed.
-- Since it pretends that it hasn't consumed any input when @p@ fails,
-- the ('<|>') combinator will try its second alternative even when the
-- first parser failed while consuming input.
--
-- The @try@ combinator can for example be used to distinguish
-- identifiers and reserved words. Both reserved words and identifiers
-- are a sequence of letters. Whenever we expect a certain reserved
-- word where we can also expect an identifier we have to use the @try@
-- combinator. Suppose we write:
--
-- > expr = letExpr <|> identifier <?> "expression"
-- >
-- > letExpr = do{ string "let"; ... }
-- > identifier = many1 letter
--
-- If the user writes \"lexical\", the parser fails with: @unexpected
-- \'x\', expecting \'t\' in \"let\"@. Indeed, since the ('<|>') combinator
-- only tries alternatives when the first alternative hasn't consumed
-- input, the @identifier@ parser is never tried (because the prefix
-- \"le\" of the @string \"let\"@ parser is already consumed). The
-- right behaviour can be obtained by adding the @try@ combinator:
--
-- > expr = letExpr <|> identifier <?> "expression"
-- >
-- > letExpr = do{ try (string "let"); ... }
-- > identifier = many1 letter
try :: ParsecT s u m a -> ParsecT s u m a
try p =
ParsecT $ \s cok _ eok eerr ->
unParser p s cok eerr eok eerr
-- In retry f p, if parser p fails after consuming input then us f to modify the
-- state at the point at which p failed and try to continure running p with the
-- new state.
retry :: (State s u -> Maybe (State s u)) -> ParsecT s u m a -> ParsecT s u m a
retry f p = ParsecT $ \s cok cerr eok eerr ->
let
f_old = stateRetry s
pcok x s err = cok x s{stateRetry = f_old} err
pcerr = cerr
peok x s err = eok x s{stateRetry = f_old} err
peerr = eerr
in unParser p s{stateRetry =f} pcok pcerr peok peerr
-- | @lookAhead p@ parses @p@ without consuming any input.
--
-- If @p@ fails and consumes some input, so does @lookAhead@. Combine with 'try'
-- if this is undesirable.
lookAhead :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m a
lookAhead p = do{ state <- getParserState
; x <- p'
; setParserState state
; return x
}
where
p' = ParsecT $ \s cok cerr eok eerr ->
unParser p s eok cerr eok eerr
-- | The parser @token showTok posFromTok testTok@ accepts a token @t@
-- with result @x@ when the function @testTok t@ returns @'Just' x@. The
-- source position of the @t@ should be returned by @posFromTok t@ and
-- the token can be shown using @showTok t@.
--
-- This combinator is expressed in terms of 'tokenPrim'.
-- It is used to accept user defined token streams. For example,
-- suppose that we have a stream of basic tokens tupled with source
-- positions. We can than define a parser that accepts single tokens as:
--
-- > mytoken x
-- > = token showTok posFromTok testTok
-- > where
-- > showTok (pos,t) = show t
-- > posFromTok (pos,t) = pos
-- > testTok (pos,t) = if x == t then Just t else Nothing
token :: (Stream s Identity t)
=> (t -> String) -- ^ Token pretty-printing function.
-> (t -> SourcePos) -- ^ Computes the position of a token.
-> (t -> Maybe a) -- ^ Matching function for the token to parse.
-> Parsec s u a
token showToken tokpos test = tokenPrim showToken nextpos test
where
nextpos _ tok ts = case runIdentity (uncons ts) of
Nothing -> tokpos tok
Just (tok',_) -> tokpos tok'
-- | The parser @tokenPrim showTok nextPos testTok@ accepts a token @t@
-- with result @x@ when the function @testTok t@ returns @'Just' x@. The
-- token can be shown using @showTok t@. The position of the /next/
-- token should be returned when @nextPos@ is called with the current
-- source position @pos@, the current token @t@ and the rest of the
-- tokens @toks@, @nextPos pos t toks@.
--
-- This is the most primitive combinator for accepting tokens. For
-- example, the 'Text.Parsec.Char.char' parser could be implemented as:
--
-- > char c
-- > = tokenPrim showChar nextPos testChar
-- > where
-- > showChar x = "'" ++ x ++ "'"
-- > testChar x = if x == c then Just x else Nothing
-- > nextPos pos x xs = updatePosChar pos x
tokenPrim :: (Stream s m t)
=> (t -> String) -- ^ Token pretty-printing function.
-> (SourcePos -> t -> s -> SourcePos) -- ^ Next position calculating function.
-> (t -> Maybe a) -- ^ Matching function for the token to parse.
-> ParsecT s u m a
{-# INLINE tokenPrim #-}
tokenPrim showToken nextpos test = tokenPrimEx showToken nextpos Nothing test
tokenPrimEx :: (Stream s m t)
=> (t -> String)
-> (SourcePos -> t -> s -> SourcePos)
-> Maybe (SourcePos -> t -> s -> u -> u)
-> (t -> Maybe a)
-> ParsecT s u m a
{-# INLINE tokenPrimEx #-}
tokenPrimEx showToken nextpos Nothing test
= ParsecT $ \(State input retry pos user) cok cerr eok eerr -> do
r <- uncons input
case r of
Nothing -> eerr $ unexpectError "" pos
Just (c,cs)
-> case test c of
Just x -> let newpos = nextpos pos c cs
newstate = State cs retry newpos user
in seq newpos $ seq newstate $
cok x newstate (newErrorUnknown newpos)
Nothing -> eerr $ unexpectError (showToken c) pos
tokenPrimEx showToken nextpos (Just nextState) test
= ParsecT $ \(State input retry pos user) cok cerr eok eerr -> do
r <- uncons input
case r of
Nothing -> eerr $ unexpectError "" pos
Just (c,cs)
-> case test c of
Just x -> let newpos = nextpos pos c cs
newUser = nextState pos c cs user
newstate = State cs retry newpos newUser
in seq newpos $ seq newstate $
cok x newstate $ newErrorUnknown newpos
Nothing -> eerr $ unexpectError (showToken c) pos
unexpectError msg pos = newErrorMessage (SysUnExpect msg) pos
-- | @many p@ applies the parser @p@ /zero/ or more times. Returns a
-- list of the returned values of @p@.
--
-- > identifier = do{ c <- letter
-- > ; cs <- many (alphaNum <|> char '_')
-- > ; return (c:cs)
-- > }
many :: ParsecT s u m a -> ParsecT s u m [a]
many p
= do xs <- manyAccum (:) p
return (reverse xs)
-- | @skipMany p@ applies the parser @p@ /zero/ or more times, skipping
-- its result.
--
-- > spaces = skipMany space
skipMany :: ParsecT s u m a -> ParsecT s u m ()
skipMany p
= do manyAccum (\_ _ -> []) p
return ()
manyAccum :: (a -> [a] -> [a])
-> ParsecT s u m a
-> ParsecT s u m [a]
manyAccum acc p =
ParsecT $ \s cok cerr eok eerr ->
let walk xs x s' err =
unParser p s'
(seq xs $ walk $ acc x xs) -- consumed-ok
cerr -- consumed-err
manyErr -- empty-ok
(\e -> cok (acc x xs) s' e) -- empty-err
in unParser p s (walk []) cerr manyErr (\e -> eok [] s e)
manyErr = error "Text.ParserCombinators.Parsec.Prim.many: combinator 'many' is applied to a parser that accepts an empty string."
-- < Running a parser: monadic (runPT) and pure (runP)
runPT :: (Stream s m t)
=> ParsecT s u m a -> u -> SourceName -> s -> m (Either ParseError a)
runPT p u name s
= do res <- runParsecT p (State s (const Nothing) (initialPos name) u)
r <- parserReply res
case r of
Ok x _ _ -> return (Right x)
Error err -> return (Left err)
where
parserReply res
= case res of
Consumed r -> r
Empty r -> r
runP :: (Stream s Identity t)
=> Parsec s u a -> u -> SourceName -> s -> Either ParseError a
runP p u name s = runIdentity $ runPT p u name s
-- | The most general way to run a parser. @runParserT p state filePath
-- input@ runs parser @p@ on the input list of tokens @input@,
-- obtained from source @filePath@ with the initial user state @st@.
-- The @filePath@ is only used in error messages and may be the empty
-- string. Returns a computation in the underlying monad @m@ that return either a 'ParseError' ('Left') or a
-- value of type @a@ ('Right').
runParserT :: (Stream s m t)
=> ParsecT s u m a -> u -> SourceName -> s -> m (Either ParseError a)
runParserT = runPT
-- | The most general way to run a parser over the Identity monad. @runParser p state filePath
-- input@ runs parser @p@ on the input list of tokens @input@,
-- obtained from source @filePath@ with the initial user state @st@.
-- The @filePath@ is only used in error messages and may be the empty
-- string. Returns either a 'ParseError' ('Left') or a
-- value of type @a@ ('Right').
--
-- > parseFromFile p fname
-- > = do{ input <- readFile fname
-- > ; return (runParser p () fname input)
-- > }
runParser :: (Stream s Identity t)
=> Parsec s u a -> u -> SourceName -> s -> Either ParseError a
runParser = runP
-- | @parse p filePath input@ runs a parser @p@ over Identity without user
-- state. The @filePath@ is only used in error messages and may be the
-- empty string. Returns either a 'ParseError' ('Left')
-- or a value of type @a@ ('Right').
--
-- > main = case (parse numbers "" "11, 2, 43") of
-- > Left err -> print err
-- > Right xs -> print (sum xs)
-- >
-- > numbers = commaSep integer
parse :: (Stream s Identity t)
=> Parsec s () a -> SourceName -> s -> Either ParseError a
parse p = runP p ()
-- | The expression @parseTest p input@ applies a parser @p@ against
-- input @input@ and prints the result to stdout. Used for testing
-- parsers.
parseTest :: (Stream s Identity t, Show a)
=> Parsec s () a -> s -> IO ()
parseTest p input
= case parse p "" input of
Left err -> do putStr "parse error at "
print err
Right x -> print x
-- < Parser state combinators
-- | Returns the current source position. See also 'SourcePos'.
getPosition :: (Monad m) => ParsecT s u m SourcePos
getPosition = do state <- getParserState
return (statePos state)
-- | Returns the current input
getInput :: (Monad m) => ParsecT s u m s
getInput = do state <- getParserState
return (stateInput state)
-- | @setPosition pos@ sets the current source position to @pos@.
setPosition :: (Monad m) => SourcePos -> ParsecT s u m ()
setPosition pos
= do updateParserState (\s -> s{statePos = pos})
return ()
-- | @setInput input@ continues parsing with @input@. The 'getInput' and
-- @setInput@ functions can for example be used to deal with #include
-- files.
setInput :: (Monad m) => s -> ParsecT s u m ()
setInput input
= do updateParserState (\s -> s{stateInput = input})
return ()
-- | Returns the full parser state as a 'State' record.
getParserState :: (Monad m) => ParsecT s u m (State s u)
getParserState = updateParserState id
-- | @setParserState st@ set the full parser state to @st@.
setParserState :: (Monad m) => State s u -> ParsecT s u m (State s u)
setParserState st = updateParserState (const st)
-- | @updateParserState f@ applies function @f@ to the parser state.
updateParserState :: (State s u -> State s u) -> ParsecT s u m (State s u)
updateParserState f =
ParsecT $ \s _ _ eok _ ->
let s' = f s
in eok s' s' $ unknownError s'
-- < User state combinators
-- | Returns the current user state.
getState :: (Monad m) => ParsecT s u m u
getState = stateUser `liftM` getParserState
-- | @putState st@ set the user state to @st@.
putState :: (Monad m) => u -> ParsecT s u m ()
putState u = do updateParserState $ \s -> s { stateUser = u }
return ()
-- | @updateState f@ applies function @f@ to the user state. Suppose
-- that we want to count identifiers in a source, we could use the user
-- state as:
--
-- > expr = do{ x <- identifier
-- > ; updateState (+1)
-- > ; return (Id x)
-- > }
modifyState :: (Monad m) => (u -> u) -> ParsecT s u m ()
modifyState f = do updateParserState $ \s -> s { stateUser = f (stateUser s) }
return ()
-- XXX Compat
-- | An alias for putState for backwards compatibility.
setState :: (Monad m) => u -> ParsecT s u m ()
setState = putState
-- | An alias for modifyState for backwards compatibility.
updateState :: (Monad m) => (u -> u) -> ParsecT s u m ()
updateState = modifyState
| antarestrader/sapphire | Text/Parsec/Prim.hs | gpl-3.0 | 26,946 | 14 | 23 | 8,132 | 6,498 | 3,388 | 3,110 | 433 | 5 |
module Language.Expressions where
-- Contains the data structures describing the structure of the language itself
-- You are free to use a different structure, as long as it describes a similar
-- enough language sufficiently well.
-- A command which performs something - can be a command that takes arguments
-- or an assignment.
data Cmd = Cmd { name :: Expr -- The command name (can be a variable)
, args :: [Expr] -- The command arguments
, inDir :: Maybe Expr -- A redirected input fp
, outDir :: Maybe Expr -- A redirected output fp
, append :: Bool -- If redirected, is it appending?
} | Assign { var :: Expr -- Assignment target
, val :: Expr -- A value to assign to a variable
} deriving Show
-----------------------------------------------------------------------------------------------------
-- A bottom-level expression
data Expr = Var String -- A named variable
| Str String deriving (Eq, Show) -- A mere string, the peasant of expressions
----------------------------------------------------------------------------------------------------
-- A comparison operation
data Comp = CEQ Expr Expr -- ==
| CNE Expr Expr -- /=
| CGE Expr Expr -- >=
| CGT Expr Expr -- >
| CLE Expr Expr -- <=
| CLT Expr Expr -- <
| CLI Expr deriving (Eq, Show) -- A wrapped expression literal - True if nonempty
-----------------------------------------------------------------------------------------------------
-- Something that evaluates to a truth value
data Pred = Pred Comp -- A wrapped comparison
| Not Pred -- Negation
| And Pred Pred -- A binary logical and
| Or Pred Pred -- A binary logical or
| Parens Pred deriving (Eq, Show)-- An expression in parentheses
------------------------------------------------------------------------------------------------------
-- A conditional branching expression - if-then or if-then-else
-- If-then with a condition and a list of actions
data Conditional = If { cond :: Pred -- Predicate to satisfy
, cthen :: [Cmd] -- Actions if satisfied
}
-- An if-then-else with a condition and two possible paths
| IfElse { cond :: Pred -- Predicate to satisfy
, cthen :: [Cmd] -- Actions if satisfied
, celse :: [Cmd] -- Actions otherwise
} deriving Show
--------------------------------------------------------------------------------------------------------
data Loop = While { cond' :: Pred
, cthen' :: [Cmd]
} deriving Show
--------------------------------------------------------------------------------------------------------
-- A top-level expression, wrapping either a conditional expression or a
-- command
data TLExpr = TLCmd Cmd | TLCnd Conditional | TLwl Loop deriving Show | IvanSindija/Project-Shell-Hash | Language/Expressions.hs | gpl-3.0 | 2,628 | 0 | 9 | 403 | 355 | 231 | 124 | 33 | 0 |
-----------------------------------------------------------
-- |
-- Module : Control.Concurrent.Longrun.Timer
-- Copyright : (c) Zoran Bošnjak 2016
-- License : GLPv3
--
-- Functions for long running process handling (Timer).
--
-- Maintainer : Zoran Bošnjak <zoran.bosnjak@via.si>
--
-- This file is part of Longrun.
--
-- Longrun is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Longrun 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 Longrun. If not, see <http://www.gnu.org/licenses/>.
--
-----------------------------------------------------------
module Control.Concurrent.Longrun.Timer
( Timer(..)
, newTimer
, stopTimer
, stopTimer_
, restartTimer
, restartTimer_
, expireTimer
, expireTimer_
) where
import Control.Concurrent.MVar
import Control.Concurrent (ThreadId, myThreadId)
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import qualified Control.Concurrent.STM as STM
import Control.Concurrent.Longrun.Base
import Control.Concurrent.Longrun.Subprocess
data Timer = Timer
{ tSema :: MVar ()
, tParent :: ThreadId
, tTimeout :: Double
, tAction :: Process ()
, tRunning :: STM.TVar (Maybe (Subprocess ()))
, tExpired :: STM.TVar Bool
}
-- | Create new timer.
newTimer :: Double -> Process () -> Process Timer
newTimer seconds action = do
sema <- liftIO $ newMVar ()
parent <- liftIO $ Control.Concurrent.myThreadId
running <- liftIO $ STM.newTVarIO Nothing
expired <- liftIO $ STM.newTVarIO False
return $ Timer
{ tSema = sema
, tParent = parent
, tTimeout = seconds
, tAction = action
, tRunning = running
, tExpired = expired
}
_withSemaphore :: Timer -> Process a -> Process a
_withSemaphore t action = bracket takeSema releaseSema action' where
takeSema = liftIO $ takeMVar (tSema t)
releaseSema _ = liftIO $ putMVar (tSema t) ()
action' _ = action
-- | Stop timer.
_stopTimer :: Timer -> Process Bool
_stopTimer t = do
(running, expired) <- liftIO $ STM.atomically $ do
running <- STM.readTVar $ tRunning t
expired <- STM.readTVar $ tExpired t
STM.writeTVar (tRunning t) Nothing
STM.writeTVar (tExpired t) False
return (running, expired)
case running of
Nothing -> return False
Just a -> do
stop_ a
return (not expired)
stopTimer :: Timer -> Process Bool
stopTimer t = _withSemaphore t (_stopTimer t)
stopTimer_ :: Timer -> Process ()
stopTimer_ t = stopTimer t >> return ()
-- | (Re)start timer.
restartTimer :: Timer -> Process Bool
restartTimer t = _withSemaphore t $ do
parent <- liftIO $ Control.Concurrent.myThreadId
wasRunning <- _stopTimer t
-- start delayed task
d <- spawnTask $ do
sleep $ tTimeout t
liftIO $ STM.atomically $ STM.writeTVar (tExpired t) True
mask_ $ tAction t `onFailureSignal` parent
liftIO $ STM.atomically $ STM.writeTVar (tRunning t) $ Just d
return wasRunning
restartTimer_ :: Timer -> Process ()
restartTimer_ t = restartTimer t >> return ()
-- | Expedite timer expire if running.
expireTimer :: Timer -> Process Bool
expireTimer t = _withSemaphore t $ do
parent <- liftIO $ Control.Concurrent.myThreadId
wasRunning <- _stopTimer t
when wasRunning $ do
_ <- spawnTask $ do
mask_ $ tAction t `onFailureSignal` parent
return ()
return wasRunning
expireTimer_ :: Timer -> Process ()
expireTimer_ t = expireTimer t >> return ()
| zoranbosnjak/longrun | Control/Concurrent/Longrun/Timer.hs | gpl-3.0 | 3,996 | 0 | 17 | 905 | 987 | 510 | 477 | 81 | 2 |
{-# LANGUAGE Arrows, StandaloneDeriving #-}
module Logic
( mainWire
) where
import Control.Applicative
import Control.Arrow
import Control.Wire
import Control.Wire.Unsafe.Event
import FRP.Netwire
import Control.Lens
import Control.Lens.TH
import Control.Monad.Random
import Control.Monad.Fix
import Prelude hiding ((.), id, until)
import Graphics.UI.GLFW as GLFW (Key(..), SpecialKey (..))
import Linear
import Debug.Trace
import qualified Data.Set as Set
import Framework
import Types
type TimeT = Timed NominalDiffTime ()
type WireG = Wire TimeT LevelOver
type WireL = Wire TimeT LevelOver
type SceneWire = WireG IO UI (Scene, Event EvtScene)
deriving instance Show a => Show (Event a)
data EvtScene = Switch (SceneWire -> SceneWire)
isSwitchEvent :: EvtScene -> Bool
isSwitchEvent (Switch _) = True
isSwitchEvent _ = False
data EndReason = Cleared | Died deriving (Show)
data LevelOver = LevelOver EndReason Int deriving (Show)
instance Monoid LevelOver where
mempty = LevelOver Died 0
mappend (LevelOver Died n) (LevelOver Died m) = LevelOver Died (max n m)
mappend (LevelOver _ n) (LevelOver _ m) = LevelOver Cleared (max n m)
traceId :: Show a => a -> a
traceId x = traceShow x x
-- * constants
-------------------------------------------------------------------------------
playerShipSize :: V2 Double
playerShipSize = V2 56 32
-- * wires
-------------------------------------------------------------------------------
mainWire :: WireG IO UI Scene
mainWire = proc ui -> do
rec
-- ... and feed it into the switch in the past
(scene, sceneEvent) <- krSwitch titleWire . (id *** delay NoEvent) -< (ui, switchEvent)
-- filter scene switch events from the result of the scene wire ...
switchEvent <- fmap (\(Switch sw) -> sw) <$> filterE isSwitchEvent -< sceneEvent
returnA -< scene
titleWire :: SceneWire
titleWire = (pure TitleScene &&& events) where
-- handle navigation keys
events = fmap selWire <$> multiKeyEvent [SpecialKey ESC, SpecialKey ENTER] keyPress
selWire (SpecialKey ESC) = Switch $ (const $ inhibit mempty)
selWire (SpecialKey ENTER) = Switch (const gameWire)
pauseWire :: SceneWire -> SceneWire
pauseWire orig = (pure PauseScene &&& events) where
-- handle navigation keys
events = fmap selWire <$> multiKeyEvent [SpecialKey ESC, SpecialKey ENTER] keyPress
selWire (SpecialKey ESC) = Switch (const titleWire)
selWire (SpecialKey ENTER) = Switch (const orig)
gameWire :: SceneWire
gameWire = (go 1 0 &&& events) >>> merge where
--
go stage score = runLevel stage (levelWire stage score) -- levelWire &&& pure NoEvent --
-- level switcher
runLevel n lvl = mkGen $ \t ui -> do
(r, w) <- stepWire lvl t (Right ui)
case r of
Right scene -> return $ (Right (scene, NoEvent), runLevel n w)
Left (LevelOver Died _) ->
return $ (Right (TitleScene, Event $ Switch (const titleWire)), runLevel n w)
Left (LevelOver Cleared score) ->
return $ (Right (TitleScene, NoEvent), go (n+1) score)
merge :: Wire s e m ((Scene, Event EvtScene), Event EvtScene) (Scene, Event EvtScene)
merge = mkPure_ $ \((s, ev1), ev2) -> Right (s, mergeL ev1 ev2)
-- handle navigation keys
events = fmap (const $ Switch pauseWire) <$> keyPress (SpecialKey ESC)
levelWire :: (MonadRandom m, MonadFix m) => Int -> Int -> WireL m UI Scene
levelWire stage score = proc ui -> do
rec
activeBullets <- stepWires . (pure () &&& delay []) -< nextBullets
let bulletEntities = map fst activeBullets
activeSwarm <- stepSwarm (recip $ fromIntegral stage) . delay initialSwarm -< nextSwarm
newAlienBullets <- alienShots -< activeSwarm
(ship, newBullets) <- player -< (ui, bulletEntities)
(nextSwarm, remainingBullets) <- collide -< (activeSwarm, activeBullets)
let nextBullets = newBullets ++ newAlienBullets ++ map snd remainingBullets
case ship of
Nothing -> inhibit (LevelOver Died 0) -< ()
Just ship ->
if null (nextSwarm ^. invaders)
then inhibit (LevelOver Cleared 0) -< ()
else returnA -< GameScene ship bulletEntities nextSwarm
where
initialSwarm = Swarm
(V2 50 50)
[Invader (toEnum (2 * (j `div` 2)))
(V2 (fromIntegral i * 64 + 16)
(fromIntegral j * 32 + 16))
| i <- [0..9], j <- [0..5]]
SwarmRight
SwarmA
player :: Monad m => WireL m (UI, [Bullet]) (Maybe Ship, [WireL m () Bullet])
player = proc (ui, otherBullets) -> do
newShip <- fly -< ui
-- collision detection
let
shipAABB = newShip ^. aabb
playerBulletActive = not . null $ filter (not . isAlienBullet) otherBullets
died = or $ map (\b -> aabbContains shipAABB (b ^. position)) (filter isAlienBullet otherBullets)
newBullets <- fire -< (ui, newShip)
let
newBullet' = if playerBulletActive then [] else newBullets
if died
then returnA -< (Nothing, [])
else returnA -< (Just newShip, newBullet')
where
clamp ui x
| x < leftBound = leftBound
| x > rightBound = rightBound
| otherwise = x
where
leftBound = playerShipSize ^. _x / 2
rightBound = ui ^. windowSize . _x . to fromIntegral - playerShipSize ^. _x / 2
input = liftA2 (+)
(-200 . whenKeyDown (SpecialKey LEFT) <|> 0)
(200 . whenKeyDown (SpecialKey RIGHT) <|> 0)
fly = proc ui -> do
let (V2 w h) = ui ^. windowSize
x <- integralWith clamp 400 . (input &&& id) -< ui
returnA -< Ship (V2 x (fromIntegral h - playerShipSize ^. _y / 2 - 4)) playerShipSize
fire =
let
try = proc (ui, ship) -> do
isShooting -< ui
let bulletPos = ship ^. position - V2 0 (playerShipSize ^. _y)
returnA -< [bullet bulletPos (-300) PlayerBullet]
in try <|> pure []
isShooting :: Monad m => WireL m UI UI
isShooting = (asSoonAs . keyDown (CharKey ' ') &&& id) >>> arr snd >>> (once' --> cooldown >>> isShooting) where
cooldown :: Monad m => WireL m UI UI
cooldown = (asSoonAs . keyUp (CharKey ' ') . after 0.1 &&& id) >>> arr snd
bullet :: (Monad m, Monoid e) => V2 Double -> Double -> BulletOwner -> Wire TimeT e m a Bullet
bullet initialPos vspeed owner = Bullet <$> dieWhenOutside . integral initialPos . pure (V2 0 vspeed) <*> pure owner
where
dieWhenOutside = mkSFN $ \pos@(V2 x y) ->
let isInside = x >= 0 && y >= 0 && x <= 800 && y <= 600
in (pos, if isInside then dieWhenOutside else inhibit mempty)
stepSwarm :: (Monad m) => Double -> WireL m Swarm Swarm
stepSwarm t = id . for (realToFrac t) --> once' . step --> stepSwarm t where
step = proc (Swarm pos invs move anim) -> do
let
(V2 x y) = pos
(w,h) = swarmSize invs
(delta, next) = case move of
SwarmRight
| x + w < 800 -> (V2 10 0, SwarmRight)
| otherwise -> (0, SwarmDown 2 SwarmLeft)
SwarmLeft
| x - 24 > 0 -> (V2 (-10) 0, SwarmLeft)
| otherwise -> (V2 0 10, SwarmDown 2 SwarmRight)
SwarmDown 0 n -> (V2 (sgn' n * 10) 0, n)
SwarmDown i n -> (V2 0 10, SwarmDown (i-1) n)
sgn' SwarmLeft = -1
sgn' _ = 1
returnA -< Swarm (pos ^+^ delta) invs next (animate anim)
animate SwarmA = SwarmB
animate SwarmB = SwarmA
swarmSize invs = (maxXInv + 48, maxYInv + 32) where
maxXInv = maximum $ map (^. position . _x) invs
maxYInv = maximum $ map (^. position . _y) invs
alienShots :: (MonadRandom m) => WireL m Swarm [WireL m () Bullet]
alienShots = spawnBullet . wackelkontaktM 0.01 <|> pure [] where
spawnBullet = mkGen_ $ \swarm -> do
let invs = swarm ^. invaders
i <- getRandomR (0, length invs - 1)
let pos = swarm ^. invaders . to (!!i) . position
return $ Right [bullet (pos ^+^ (swarm ^. position)) 200 AlienBullet]
collide :: (Monad m, MonadFix m) => WireL m (Swarm, [(Bullet, WireL m a Bullet)]) (Swarm, [(Bullet, WireL m a Bullet)])
collide = proc (swarm, bullets) -> do
let
invOff = swarm ^. position
(remainingBullets, newInvs) = collideAll invOff bullets (swarm ^. invaders)
returnA -< (swarm { _invaders = newInvs }, remainingBullets )
where
collideAll :: V2D -> [(Bullet, WireL m a Bullet)] -> [Invader] -> ([(Bullet, WireL m a Bullet)], [Invader])
collideAll off [] invs = ([], invs)
collideAll off (b:bs) invs =
let
(b', invs') = collide1 off b invs
(bs', invs'') = collideAll off bs invs'
in (b' ++ bs', invs'')
collide1 :: V2D -> (Bullet, WireL m a Bullet) -> [Invader] -> ([(Bullet, WireL m a Bullet)],[Invader])
collide1 invOff b [] = ([b], [])
collide1 invOff b (i:is)
| (not $ isAlienBullet $ fst b)
&& aabbContains (translateAABB invOff (i ^. aabb)) (b ^. to fst . position)
= ([], is)
| otherwise = let (bs, is') = collide1 invOff b is in (bs, i:is')
-- * EVENT WIRES
-------------------------------------------------------------------------------
multiKeyEvent :: (Monad m, Monoid e) => [Key] -> (Key -> Wire s e m UI (Event Key)) -> Wire s e m UI (Event Key)
multiKeyEvent ks f = foldl1 (<&) $ Prelude.map f ks
keyDown :: (Monad m, Monoid e) => Key -> Wire s e m UI (Event Key)
keyDown k = now . pure k . whenKeyDown k <|> never
keyUp :: (Monad m, Monoid e) => Key -> Wire s e m UI (Event Key)
keyUp k = now . pure k . whenKeyUp k <|> never
whenKeyDown :: (Monad m, Monoid e) => Key -> Wire s e m UI UI
whenKeyDown k = when (^. pressedKeys . to (Set.member k) )
whenKeyUp :: (Monad m, Monoid e) => Key -> Wire s e m UI UI
whenKeyUp k = unless (^. pressedKeys . to (Set.member k) )
keyPress :: (Monoid e) => Key -> Wire s e m UI (Event Key)
keyPress k =
mkPureN $ \ui ->
if ui ^. pressedKeys ^. to (Set.member k)
then (Right NoEvent, waitRelease)
else (Right NoEvent, keyPress k)
where
waitRelease =
mkPureN $ \ui ->
if ui ^. pressedKeys ^. to (Set.member k)
then (Right NoEvent, waitRelease)
else (Right (Event k), keyPress k)
-- * WIRE COMBINATORS
-------------------------------------------------------------------------------
once' :: (Monoid e) => Wire s e m a a
once' = mkPureN $ \x -> (Right x, inhibit mempty)
stepWires :: (Monad m, Monoid s) => Wire s e m (a, [Wire s e m a b]) [(b, Wire s e m a b)]
stepWires = mkGen $ \dt (x, ws) -> do
results <- mapM (\w -> stepWire w dt (Right x)) ws
return $ (Right [(x', w') | (Right x', w') <- results], stepWires)
-- | Whenever the given wire inhibits, a new wire is constructed using
-- the given function.
--
-- * Depends: like currently active wire.
--
-- * Time: switching restarts time.
switchBy ::
(Monad m, Monoid s)
=> (e -> Maybe (Wire s e m a b)) -- ^ Wire selection function.
-> Wire s e m a b -- ^ Initial wire.
-> Wire s e m a b
switchBy new w0 =
mkGen $ \dt x' ->
let select w' = do
(mx, w) <- stepWire w' dt (Right x')
case mx of
Left ex -> maybe (return (Left ex, switchBy new w)) select (new ex)
Right x -> return (Right x, switchBy new w)
in select w0
switchByOnce ::
(Monad m, Monoid s)
=> (e' -> Wire s e' m a b -> Wire s e m a b) -- ^ Wire selection function.
-> Wire s e' m a b -- ^ Initial wire.
-> Wire s e m a b
switchByOnce new w0 =
mkGen $ \dt x' ->
let select w' = do
(mx, w) <- stepWire w' dt (Right x')
case mx of
Left ex -> stepWire (new ex w) dt (Right x')
Right x -> return (Right x, switchByOnce new w)
in select w0
untilWith :: (Monoid e, Monad m) => b -> Wire s e m (Event a) b
untilWith v = (pure v &&& id) >>> until
wackelkontaktM :: (MonadRandom m, Monoid e)
=> Double -- ^ Occurrence probability.
-> Wire s e m a a
wackelkontaktM p =
mkGen_ $ \x -> do
e <- getRandom
return (if (e < p) then Right x else Left mempty) | fatho/spacemonads | src/Logic.hs | gpl-3.0 | 12,133 | 8 | 21 | 3,248 | 4,870 | 2,508 | 2,362 | -1 | -1 |
import Codec.PPM.Binary
import System.Environment
import MaaS.Mandelbrot
main = do
[f,m,ptx,pty,x,y,z] <- getArgs
let fm = read m :: Int in
let px = read ptx :: Double in
let py = read pty :: Double in
let fx = read x :: Integer in
let fy = read y :: Integer in
let fz = read z :: Double in
writePPM f (fx, fy) (genImage (mandel_map fm px py (fromIntegral fx) (fromIntegral fy) fz) fm)
| maeln/MaaS | mandel.hs | gpl-3.0 | 418 | 1 | 25 | 107 | 207 | 104 | 103 | 12 | 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.Gmail.Users.Threads.Modify
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Modifies the labels applied to the thread. This applies to all messages
-- in the thread.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.threads.modify@.
module Network.Google.Resource.Gmail.Users.Threads.Modify
(
-- * REST Resource
UsersThreadsModifyResource
-- * Creating a Request
, usersThreadsModify
, UsersThreadsModify
-- * Request Lenses
, utmXgafv
, utmUploadProtocol
, utmAccessToken
, utmUploadType
, utmPayload
, utmUserId
, utmId
, utmCallback
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.threads.modify@ method which the
-- 'UsersThreadsModify' request conforms to.
type UsersThreadsModifyResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"threads" :>
Capture "id" Text :>
"modify" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ModifyThreadRequest :>
Post '[JSON] Thread
-- | Modifies the labels applied to the thread. This applies to all messages
-- in the thread.
--
-- /See:/ 'usersThreadsModify' smart constructor.
data UsersThreadsModify =
UsersThreadsModify'
{ _utmXgafv :: !(Maybe Xgafv)
, _utmUploadProtocol :: !(Maybe Text)
, _utmAccessToken :: !(Maybe Text)
, _utmUploadType :: !(Maybe Text)
, _utmPayload :: !ModifyThreadRequest
, _utmUserId :: !Text
, _utmId :: !Text
, _utmCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersThreadsModify' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utmXgafv'
--
-- * 'utmUploadProtocol'
--
-- * 'utmAccessToken'
--
-- * 'utmUploadType'
--
-- * 'utmPayload'
--
-- * 'utmUserId'
--
-- * 'utmId'
--
-- * 'utmCallback'
usersThreadsModify
:: ModifyThreadRequest -- ^ 'utmPayload'
-> Text -- ^ 'utmId'
-> UsersThreadsModify
usersThreadsModify pUtmPayload_ pUtmId_ =
UsersThreadsModify'
{ _utmXgafv = Nothing
, _utmUploadProtocol = Nothing
, _utmAccessToken = Nothing
, _utmUploadType = Nothing
, _utmPayload = pUtmPayload_
, _utmUserId = "me"
, _utmId = pUtmId_
, _utmCallback = Nothing
}
-- | V1 error format.
utmXgafv :: Lens' UsersThreadsModify (Maybe Xgafv)
utmXgafv = lens _utmXgafv (\ s a -> s{_utmXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
utmUploadProtocol :: Lens' UsersThreadsModify (Maybe Text)
utmUploadProtocol
= lens _utmUploadProtocol
(\ s a -> s{_utmUploadProtocol = a})
-- | OAuth access token.
utmAccessToken :: Lens' UsersThreadsModify (Maybe Text)
utmAccessToken
= lens _utmAccessToken
(\ s a -> s{_utmAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
utmUploadType :: Lens' UsersThreadsModify (Maybe Text)
utmUploadType
= lens _utmUploadType
(\ s a -> s{_utmUploadType = a})
-- | Multipart request metadata.
utmPayload :: Lens' UsersThreadsModify ModifyThreadRequest
utmPayload
= lens _utmPayload (\ s a -> s{_utmPayload = a})
-- | The user\'s email address. The special value \`me\` can be used to
-- indicate the authenticated user.
utmUserId :: Lens' UsersThreadsModify Text
utmUserId
= lens _utmUserId (\ s a -> s{_utmUserId = a})
-- | The ID of the thread to modify.
utmId :: Lens' UsersThreadsModify Text
utmId = lens _utmId (\ s a -> s{_utmId = a})
-- | JSONP
utmCallback :: Lens' UsersThreadsModify (Maybe Text)
utmCallback
= lens _utmCallback (\ s a -> s{_utmCallback = a})
instance GoogleRequest UsersThreadsModify where
type Rs UsersThreadsModify = Thread
type Scopes UsersThreadsModify =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify"]
requestClient UsersThreadsModify'{..}
= go _utmUserId _utmId _utmXgafv _utmUploadProtocol
_utmAccessToken
_utmUploadType
_utmCallback
(Just AltJSON)
_utmPayload
gmailService
where go
= buildClient
(Proxy :: Proxy UsersThreadsModifyResource)
mempty
| brendanhay/gogol | gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Threads/Modify.hs | mpl-2.0 | 5,487 | 0 | 21 | 1,405 | 865 | 504 | 361 | 126 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.