code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.MachineLearning.UpdateDataSource -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the 'DataSourceName' of a 'DataSource'. -- -- You can use the GetDataSource operation to view the contents of the -- updated data element. -- -- /See:/ <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_UpdateDataSource.html AWS API Reference> for UpdateDataSource. module Network.AWS.MachineLearning.UpdateDataSource ( -- * Creating a Request updateDataSource , UpdateDataSource -- * Request Lenses , udsDataSourceId , udsDataSourceName -- * Destructuring the Response , updateDataSourceResponse , UpdateDataSourceResponse -- * Response Lenses , udsrsDataSourceId , udsrsResponseStatus ) where import Network.AWS.MachineLearning.Types import Network.AWS.MachineLearning.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'updateDataSource' smart constructor. data UpdateDataSource = UpdateDataSource' { _udsDataSourceId :: !Text , _udsDataSourceName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateDataSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udsDataSourceId' -- -- * 'udsDataSourceName' updateDataSource :: Text -- ^ 'udsDataSourceId' -> Text -- ^ 'udsDataSourceName' -> UpdateDataSource updateDataSource pDataSourceId_ pDataSourceName_ = UpdateDataSource' { _udsDataSourceId = pDataSourceId_ , _udsDataSourceName = pDataSourceName_ } -- | The ID assigned to the 'DataSource' during creation. udsDataSourceId :: Lens' UpdateDataSource Text udsDataSourceId = lens _udsDataSourceId (\ s a -> s{_udsDataSourceId = a}); -- | A new user-supplied name or description of the 'DataSource' that will -- replace the current description. udsDataSourceName :: Lens' UpdateDataSource Text udsDataSourceName = lens _udsDataSourceName (\ s a -> s{_udsDataSourceName = a}); instance AWSRequest UpdateDataSource where type Rs UpdateDataSource = UpdateDataSourceResponse request = postJSON machineLearning response = receiveJSON (\ s h x -> UpdateDataSourceResponse' <$> (x .?> "DataSourceId") <*> (pure (fromEnum s))) instance ToHeaders UpdateDataSource where toHeaders = const (mconcat ["X-Amz-Target" =# ("AmazonML_20141212.UpdateDataSource" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON UpdateDataSource where toJSON UpdateDataSource'{..} = object (catMaybes [Just ("DataSourceId" .= _udsDataSourceId), Just ("DataSourceName" .= _udsDataSourceName)]) instance ToPath UpdateDataSource where toPath = const "/" instance ToQuery UpdateDataSource where toQuery = const mempty -- | Represents the output of an UpdateDataSource operation. -- -- You can see the updated content by using the GetBatchPrediction -- operation. -- -- /See:/ 'updateDataSourceResponse' smart constructor. data UpdateDataSourceResponse = UpdateDataSourceResponse' { _udsrsDataSourceId :: !(Maybe Text) , _udsrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateDataSourceResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udsrsDataSourceId' -- -- * 'udsrsResponseStatus' updateDataSourceResponse :: Int -- ^ 'udsrsResponseStatus' -> UpdateDataSourceResponse updateDataSourceResponse pResponseStatus_ = UpdateDataSourceResponse' { _udsrsDataSourceId = Nothing , _udsrsResponseStatus = pResponseStatus_ } -- | The ID assigned to the 'DataSource' during creation. This value should -- be identical to the value of the 'DataSourceID' in the request. udsrsDataSourceId :: Lens' UpdateDataSourceResponse (Maybe Text) udsrsDataSourceId = lens _udsrsDataSourceId (\ s a -> s{_udsrsDataSourceId = a}); -- | The response status code. udsrsResponseStatus :: Lens' UpdateDataSourceResponse Int udsrsResponseStatus = lens _udsrsResponseStatus (\ s a -> s{_udsrsResponseStatus = a});
olorin/amazonka
amazonka-ml/gen/Network/AWS/MachineLearning/UpdateDataSource.hs
mpl-2.0
5,117
0
13
1,068
669
400
269
88
1
module Propellor.Property.DnsSec where import Propellor.Base import qualified Propellor.Property.File as File -- | Puts the DNSSEC key files in place from PrivData. -- -- signedPrimary uses this, so this property does not normally need to be -- used directly. keysInstalled :: Domain -> RevertableProperty (HasInfo + UnixLike) UnixLike keysInstalled domain = setup <!> cleanup where setup = propertyList "DNSSEC keys installed" $ toProps $ map installkey keys cleanup = propertyList "DNSSEC keys removed" $ toProps $ map (File.notPresent . keyFn domain) keys installkey k = writer (keysrc k) (keyFn domain k) (Context domain) where writer | isPublic k = File.hasPrivContentExposedFrom | otherwise = File.hasPrivContentFrom keys = [ PubZSK, PrivZSK, PubKSK, PrivKSK ] keysrc k = PrivDataSource (DnsSec k) $ unwords [ "The file with extension" , keyExt k , "created by running:" , if isZoneSigningKey k then "dnssec-keygen -a RSASHA256 -b 2048 -n ZONE " ++ domain else "dnssec-keygen -f KSK -a RSASHA256 -b 4096 -n ZONE " ++ domain ] -- | Uses dnssec-signzone to sign a domain's zone file. -- -- signedPrimary uses this, so this property does not normally need to be -- used directly. zoneSigned :: Domain -> FilePath -> RevertableProperty (HasInfo + UnixLike) UnixLike zoneSigned domain zonefile = setup <!> cleanup where setup :: Property (HasInfo + UnixLike) setup = check needupdate (forceZoneSigned domain zonefile) `requires` keysInstalled domain cleanup :: Property UnixLike cleanup = File.notPresent (signedZoneFile zonefile) `before` File.notPresent dssetfile `before` revert (keysInstalled domain) dssetfile = dir </> "-" ++ domain ++ "." dir = takeDirectory zonefile -- Need to update the signed zone file if the zone file or -- any of the keys have a newer timestamp. needupdate = do v <- catchMaybeIO $ getModificationTime (signedZoneFile zonefile) case v of Nothing -> return True Just t1 -> anyM (newerthan t1) $ zonefile : map (keyFn domain) [minBound..maxBound] newerthan t1 f = do t2 <- getModificationTime f return (t2 >= t1) forceZoneSigned :: Domain -> FilePath -> Property UnixLike forceZoneSigned domain zonefile = property ("zone signed for " ++ domain) $ liftIO $ do salt <- take 16 <$> saltSha1 let p = proc "dnssec-signzone" [ "-A" , "-3", salt -- The serial number needs to be increased each time the -- zone is resigned, even if there are no other changes, -- so that it will propagate to secondaries. So, use the -- unixtime serial format. , "-N", "unixtime" , "-o", domain , zonefile -- the ordering of these key files does not matter , keyFn domain PubZSK , keyFn domain PubKSK ] -- Run in the same directory as the zonefile, so it will -- write the dsset file there. (_, _, _, h) <- createProcess $ p { cwd = Just (takeDirectory zonefile) } ifM (checkSuccessProcess h) ( return MadeChange , return FailedChange ) saltSha1 :: IO String saltSha1 = readProcess "sh" [ "-c" , "head -c 1024 /dev/urandom | sha1sum | cut -d ' ' -f 1" ] -- | The file used for a given key. keyFn :: Domain -> DnsSecKey -> FilePath keyFn domain k = "/etc/bind/propellor/dnssec" </> concat [ "K" ++ domain ++ "." , if isZoneSigningKey k then "ZSK" else "KSK" , keyExt k ] -- | These are the extensions that dnssec-keygen looks for. keyExt :: DnsSecKey -> String keyExt k | isPublic k = ".key" | otherwise = ".private" isPublic :: DnsSecKey -> Bool isPublic k = k `elem` [PubZSK, PubKSK] isZoneSigningKey :: DnsSecKey -> Bool isZoneSigningKey k = k `elem` [PubZSK, PrivZSK] -- | dnssec-signzone makes a .signed file signedZoneFile :: FilePath -> FilePath signedZoneFile zonefile = zonefile ++ ".signed"
ArchiveTeam/glowing-computing-machine
src/Propellor/Property/DnsSec.hs
bsd-2-clause
3,756
83
16
745
965
512
453
-1
-1
module Database.Schema.Migrations.Filesystem.Serialize ( serializeMigration ) where import Data.Time () -- for UTCTime Show instance import Data.Maybe ( catMaybes ) import Data.List ( intercalate ) import Database.Schema.Migrations.Migration ( Migration(..) ) type FieldSerializer = Migration -> Maybe String fieldSerializers :: [FieldSerializer] fieldSerializers = [ serializeDesc , serializeTimestamp , serializeDepends , serializeApply , serializeRevert ] serializeDesc :: FieldSerializer serializeDesc m = case mDesc m of Nothing -> Nothing Just desc -> Just $ "Description: " ++ desc serializeTimestamp :: FieldSerializer serializeTimestamp m = Just $ "Created: " ++ (show $ mTimestamp m) serializeDepends :: FieldSerializer serializeDepends m = Just $ "Depends: " ++ (intercalate " " $ mDeps m) serializeRevert :: FieldSerializer serializeRevert m = case mRevert m of Nothing -> Nothing Just revert -> Just $ "Revert:\n" ++ (serializeMultiline revert) serializeApply :: FieldSerializer serializeApply m = Just $ "Apply:\n" ++ (serializeMultiline $ mApply m) commonPrefix :: String -> String -> String commonPrefix a b = map fst $ takeWhile (uncurry (==)) (zip a b) commonPrefixLines :: [String] -> String commonPrefixLines [] = "" commonPrefixLines theLines = foldl1 commonPrefix theLines serializeMultiline :: String -> String serializeMultiline s = let sLines = lines s prefix = case commonPrefixLines sLines of -- If the lines already have a common prefix that -- begins with whitespace, no new prefix is -- necessary. (' ':_) -> "" -- Otherwise, use a new prefix of two spaces. _ -> " " in unlines $ map (prefix ++) sLines serializeMigration :: Migration -> String serializeMigration m = intercalate "\n" fields where fields = catMaybes [ f m | f <- fieldSerializers ]
creswick/dbmigrations
src/Database/Schema/Migrations/Filesystem/Serialize.hs
bsd-3-clause
2,098
0
13
582
499
267
232
46
2
module Test where import Foo.Bar import Foo.Bar.Blub import Ugah.Argh import qualified Control.Monad import Control.Monad (unless) f :: Int -> Int f = (+ 3)
jystic/hsimport
tests/goldenFiles/SymbolTest9.hs
bsd-3-clause
158
0
5
25
54
34
20
8
1
{-# LANGUAGE CPP, GADTs, NondecreasingIndentation #-} ----------------------------------------------------------------------------- -- -- 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, and (b) the type signatures, the -- structure should not be too overwhelming. module X86.CodeGen ( cmmTopCodeGen, generateJumpTableForInstr, InstrBlock ) where #include "HsVersions.h" #include "nativeGen/NCG.h" #include "../includes/MachDeps.h" -- NCG stuff: import X86.Instr import X86.Cond import X86.Regs import X86.RegInfo import CodeGen.Platform import CPrim import Instruction import PIC import NCGMonad import Size import Reg import Platform -- Our intermediate code: import BasicTypes import BlockId import Module ( primPackageKey ) import PprCmm () import CmmUtils import Cmm import Hoopl import CLabel -- The rest: import ForeignCall ( CCallConv(..) ) import OrdList import Outputable import Unique import FastString import FastBool ( isFastTrue ) import DynFlags import Util import Control.Monad import Data.Bits import Data.Int import Data.Maybe import Data.Word is32BitPlatform :: NatM Bool is32BitPlatform = do dflags <- getDynFlags return $ target32Bit (targetPlatform dflags) sse2Enabled :: NatM Bool sse2Enabled = do dflags <- getDynFlags return (isSse2Enabled dflags) sse4_2Enabled :: NatM Bool sse4_2Enabled = do dflags <- getDynFlags return (isSse4_2Enabled dflags) if_sse2 :: NatM a -> NatM a -> NatM a if_sse2 sse2 x87 = do b <- sse2Enabled if b then sse2 else x87 cmmTopCodeGen :: RawCmmDecl -> NatM [NatCmmDecl (Alignment, CmmStatics) Instr] cmmTopCodeGen (CmmProc info lab live graph) = do let blocks = toBlockListEntryFirst graph (nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks picBaseMb <- getPicBaseMaybeNat dflags <- getDynFlags let proc = CmmProc info lab live (ListGraph $ concat nat_blocks) tops = proc : concat statics os = platformOS $ targetPlatform dflags case picBaseMb of Just picBase -> initializePicBase_x86 ArchX86 os picBase tops Nothing -> return tops cmmTopCodeGen (CmmData sec dat) = do return [CmmData sec (1, dat)] -- no translation, we just use CmmStatic basicBlockCodeGen :: CmmBlock -> NatM ( [NatBasicBlock Instr] , [NatCmmDecl (Alignment, CmmStatics) Instr]) basicBlockCodeGen block = do let (CmmEntry id, nodes, tail) = blockSplit block stmts = blockToList nodes mid_instrs <- stmtsToInstrs stmts tail_instrs <- stmtToInstrs tail let instrs = mid_instrs `appOL` tail_instrs -- 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 is32Bit <- is32BitPlatform case stmt of CmmComment s -> return (unitOL (COMMENT s)) CmmAssign reg src | isFloatType ty -> assignReg_FltCode size reg src | is32Bit && isWord64 ty -> assignReg_I64Code reg src | otherwise -> assignReg_IntCode size reg src where ty = cmmRegType dflags reg size = cmmTypeSize ty CmmStore addr src | isFloatType ty -> assignMem_FltCode size addr src | is32Bit && isWord64 ty -> assignMem_I64Code addr src | otherwise -> assignMem_IntCode size addr src where ty = cmmExprType dflags src size = cmmTypeSize ty CmmUnsafeForeignCall target result_regs args -> genCCall dflags is32Bit 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 , cml_args_regs = gregs } -> do dflags <- getDynFlags genJump arg (jumpRegs dflags gregs) _ -> panic "stmtToInstrs: statement should have been cps'd away" jumpRegs :: DynFlags -> [GlobalReg] -> [Reg] jumpRegs dflags gregs = [ RegReal r | Just r <- map (globalRegMaybe platform) gregs ] where platform = targetPlatform dflags -------------------------------------------------------------------------------- -- | '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 -- | Condition codes passed up the tree. -- data CondCode = CondCode Bool Cond InstrBlock -- | a.k.a "Register64" -- Reg is 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 -- data ChildCode64 = ChildCode64 InstrBlock Reg -- | Register's passed up the tree. If the stix code forces the register -- to live in a pre-decided machine register, it comes out as @Fixed@; -- otherwise, it comes out as @Any@, and the parent can decide which -- register to put it in. -- data Register = Fixed Size Reg InstrBlock | Any Size (Reg -> InstrBlock) swizzleRegisterRep :: Register -> Size -> Register swizzleRegisterRep (Fixed _ reg code) size = Fixed size reg code swizzleRegisterRep (Any _ codefn) size = Any size codefn -- | Grab the Reg for a CmmReg getRegisterReg :: Platform -> Bool -> CmmReg -> Reg getRegisterReg _ use_sse2 (CmmLocal (LocalReg u pk)) = let sz = cmmTypeSize pk in if isFloatSize sz && not use_sse2 then RegVirtual (mkVirtualReg u FF80) else RegVirtual (mkVirtualReg u sz) 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 ... -- | 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) ... -} -- | Check whether an integer will fit in 32 bits. -- A CmmInt is intended to be truncated to the appropriate -- number of bits, so here we truncate it to Int64. This is -- important because e.g. -1 as a CmmInt might be either -- -1 or 18446744073709551615. -- is32BitInteger :: Integer -> Bool is32BitInteger i = i64 <= 0x7fffffff && i64 >= -0x80000000 where i64 = fromIntegral i :: Int64 -- | 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 -> CmmReg -> Int -> CmmExpr mangleIndexTree dflags reg off = CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)] where width = typeWidth (cmmRegType dflags reg) -- | The dual to getAnyReg: compute an expression into a register, but -- we don't mind which one it is. getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock) getSomeReg expr = do r <- getRegister expr case r of Any rep code -> do tmp <- getNewRegNat rep return (tmp, code tmp) Fixed _ reg code -> return (reg, code) assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock assignMem_I64Code addrTree valueTree = do Amode addr addr_code <- getAmode addrTree ChildCode64 vcode rlo <- iselExpr64 valueTree let rhi = getHiVRegFromLo rlo -- Little-endian store mov_lo = MOV II32 (OpReg rlo) (OpAddr addr) mov_hi = MOV II32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4))) 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 = MOV II32 (OpReg r_src_lo) (OpReg r_dst_lo) mov_hi = MOV II32 (OpReg r_src_hi) (OpReg r_dst_hi) return ( vcode `snocOL` mov_lo `snocOL` mov_hi ) assignReg_I64Code _ _ = panic "assignReg_I64Code(i386): invalid lvalue" iselExpr64 :: CmmExpr -> NatM ChildCode64 iselExpr64 (CmmLit (CmmInt i _)) = do (rlo,rhi) <- getNewRegPairNat II32 let r = fromIntegral (fromIntegral i :: Word32) q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32) code = toOL [ MOV II32 (OpImm (ImmInteger r)) (OpReg rlo), MOV II32 (OpImm (ImmInteger q)) (OpReg rhi) ] return (ChildCode64 code rlo) iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do Amode addr addr_code <- getAmode addrTree (rlo,rhi) <- getNewRegPairNat II32 let mov_lo = MOV II32 (OpAddr addr) (OpReg rlo) mov_hi = MOV II32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi) 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)) -- we handle addition, but rather badly iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do ChildCode64 code1 r1lo <- iselExpr64 e1 (rlo,rhi) <- getNewRegPairNat II32 let r = fromIntegral (fromIntegral i :: Word32) q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32) r1hi = getHiVRegFromLo r1lo code = code1 `appOL` toOL [ MOV II32 (OpReg r1lo) (OpReg rlo), ADD II32 (OpImm (ImmInteger r)) (OpReg rlo), MOV II32 (OpReg r1hi) (OpReg rhi), ADC II32 (OpImm (ImmInteger q)) (OpReg rhi) ] 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 [ MOV II32 (OpReg r1lo) (OpReg rlo), ADD II32 (OpReg r2lo) (OpReg rlo), MOV II32 (OpReg r1hi) (OpReg rhi), ADC II32 (OpReg r2hi) (OpReg rhi) ] return (ChildCode64 code rlo) iselExpr64 (CmmMachOp (MO_UU_Conv _ W64) [expr]) = do fn <- getAnyReg expr r_dst_lo <- getNewRegNat II32 let r_dst_hi = getHiVRegFromLo r_dst_lo code = fn r_dst_lo return ( ChildCode64 (code `snocOL` MOV II32 (OpImm (ImmInt 0)) (OpReg r_dst_hi)) r_dst_lo ) iselExpr64 expr = pprPanic "iselExpr64(i386)" (ppr expr) -------------------------------------------------------------------------------- getRegister :: CmmExpr -> NatM Register getRegister e = do dflags <- getDynFlags is32Bit <- is32BitPlatform getRegister' dflags is32Bit e getRegister' :: DynFlags -> Bool -> CmmExpr -> NatM Register getRegister' dflags is32Bit (CmmReg reg) = case reg of CmmGlobal PicBaseReg | is32Bit -> -- on x86_64, we have %rip for PicBaseReg, but it's not -- a full-featured register, it can only be used for -- rip-relative addressing. do reg' <- getPicBaseNat (archWordSize is32Bit) return (Fixed (archWordSize is32Bit) reg' nilOL) _ -> do use_sse2 <- sse2Enabled let sz = cmmTypeSize (cmmRegType dflags reg) size | not use_sse2 && isFloatSize sz = FF80 | otherwise = sz -- let platform = targetPlatform dflags return (Fixed size (getRegisterReg platform use_sse2 reg) nilOL) getRegister' dflags is32Bit (CmmRegOff r n) = getRegister' dflags is32Bit $ mangleIndexTree dflags r n -- for 32-bit architectuers, support some 64 -> 32 bit conversions: -- TO_W_(x), TO_W_(x >> 32) getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32) [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) | is32Bit = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 (getHiVRegFromLo rlo) code getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32) [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) | is32Bit = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 (getHiVRegFromLo rlo) code getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32) [x]) | is32Bit = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 rlo code getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32) [x]) | is32Bit = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 rlo code getRegister' _ _ (CmmLit lit@(CmmFloat f w)) = if_sse2 float_const_sse2 float_const_x87 where float_const_sse2 | f == 0.0 = do let size = floatSize w code dst = unitOL (XOR size (OpReg dst) (OpReg dst)) -- I don't know why there are xorpd, xorps, and pxor instructions. -- They all appear to do the same thing --SDM return (Any size code) | otherwise = do Amode addr code <- memConstant (widthInBytes w) lit loadFloatAmode True w addr code float_const_x87 = case w of W64 | f == 0.0 -> let code dst = unitOL (GLDZ dst) in return (Any FF80 code) | f == 1.0 -> let code dst = unitOL (GLD1 dst) in return (Any FF80 code) _otherwise -> do Amode addr code <- memConstant (widthInBytes w) lit loadFloatAmode False w addr code -- catch simple cases of zero- or sign-extended load getRegister' _ _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad addr _]) = do code <- intLoadCode (MOVZxL II8) addr return (Any II32 code) getRegister' _ _ (CmmMachOp (MO_SS_Conv W8 W32) [CmmLoad addr _]) = do code <- intLoadCode (MOVSxL II8) addr return (Any II32 code) getRegister' _ _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad addr _]) = do code <- intLoadCode (MOVZxL II16) addr return (Any II32 code) getRegister' _ _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad addr _]) = do code <- intLoadCode (MOVSxL II16) addr return (Any II32 code) -- catch simple cases of zero- or sign-extended load getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad addr _]) | not is32Bit = do code <- intLoadCode (MOVZxL II8) addr return (Any II64 code) getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W8 W64) [CmmLoad addr _]) | not is32Bit = do code <- intLoadCode (MOVSxL II8) addr return (Any II64 code) getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad addr _]) | not is32Bit = do code <- intLoadCode (MOVZxL II16) addr return (Any II64 code) getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad addr _]) | not is32Bit = do code <- intLoadCode (MOVSxL II16) addr return (Any II64 code) getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad addr _]) | not is32Bit = do code <- intLoadCode (MOV II32) addr -- 32-bit loads zero-extend return (Any II64 code) getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad addr _]) | not is32Bit = do code <- intLoadCode (MOVSxL II32) addr return (Any II64 code) getRegister' _ is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg), CmmLit displacement]) | not is32Bit = do return $ Any II64 (\dst -> unitOL $ LEA II64 (OpAddr (ripRel (litToImm displacement))) (OpReg dst)) getRegister' dflags is32Bit (CmmMachOp mop [x]) = do -- unary MachOps sse2 <- sse2Enabled case mop of MO_F_Neg w | sse2 -> sse2NegCode w x | otherwise -> trivialUFCode FF80 (GNEG FF80) x MO_S_Neg w -> triv_ucode NEGI (intSize w) MO_Not w -> triv_ucode NOT (intSize w) -- Nop conversions MO_UU_Conv W32 W8 -> toI8Reg W32 x MO_SS_Conv W32 W8 -> toI8Reg W32 x MO_UU_Conv W16 W8 -> toI8Reg W16 x MO_SS_Conv W16 W8 -> toI8Reg W16 x MO_UU_Conv W32 W16 -> toI16Reg W32 x MO_SS_Conv W32 W16 -> toI16Reg W32 x MO_UU_Conv W64 W32 | not is32Bit -> conversionNop II64 x MO_SS_Conv W64 W32 | not is32Bit -> conversionNop II64 x MO_UU_Conv W64 W16 | not is32Bit -> toI16Reg W64 x MO_SS_Conv W64 W16 | not is32Bit -> toI16Reg W64 x MO_UU_Conv W64 W8 | not is32Bit -> toI8Reg W64 x MO_SS_Conv W64 W8 | not is32Bit -> toI8Reg W64 x MO_UU_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x MO_SS_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x -- widenings MO_UU_Conv W8 W32 -> integerExtend W8 W32 MOVZxL x MO_UU_Conv W16 W32 -> integerExtend W16 W32 MOVZxL x MO_UU_Conv W8 W16 -> integerExtend W8 W16 MOVZxL x MO_SS_Conv W8 W32 -> integerExtend W8 W32 MOVSxL x MO_SS_Conv W16 W32 -> integerExtend W16 W32 MOVSxL x MO_SS_Conv W8 W16 -> integerExtend W8 W16 MOVSxL x MO_UU_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVZxL x MO_UU_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVZxL x MO_UU_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVZxL x MO_SS_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVSxL x MO_SS_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVSxL x MO_SS_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVSxL x -- for 32-to-64 bit zero extension, amd64 uses an ordinary movl. -- However, we don't want the register allocator to throw it -- away as an unnecessary reg-to-reg move, so we keep it in -- the form of a movzl and print it as a movl later. MO_FF_Conv W32 W64 | sse2 -> coerceFP2FP W64 x | otherwise -> conversionNop FF80 x MO_FF_Conv W64 W32 -> coerceFP2FP W32 x MO_FS_Conv from to -> coerceFP2Int from to x MO_SF_Conv from to -> coerceInt2FP from to x MO_V_Insert {} -> needLlvm MO_V_Extract {} -> needLlvm MO_V_Add {} -> needLlvm MO_V_Sub {} -> needLlvm MO_V_Mul {} -> needLlvm MO_VS_Quot {} -> needLlvm MO_VS_Rem {} -> needLlvm MO_VS_Neg {} -> needLlvm MO_VU_Quot {} -> needLlvm MO_VU_Rem {} -> needLlvm MO_VF_Insert {} -> needLlvm MO_VF_Extract {} -> needLlvm MO_VF_Add {} -> needLlvm MO_VF_Sub {} -> needLlvm MO_VF_Mul {} -> needLlvm MO_VF_Quot {} -> needLlvm MO_VF_Neg {} -> needLlvm _other -> pprPanic "getRegister" (pprMachOp mop) where triv_ucode :: (Size -> Operand -> Instr) -> Size -> NatM Register triv_ucode instr size = trivialUCode size (instr size) x -- signed or unsigned extension. integerExtend :: Width -> Width -> (Size -> Operand -> Operand -> Instr) -> CmmExpr -> NatM Register integerExtend from to instr expr = do (reg,e_code) <- if from == W8 then getByteReg expr else getSomeReg expr let code dst = e_code `snocOL` instr (intSize from) (OpReg reg) (OpReg dst) return (Any (intSize to) code) toI8Reg :: Width -> CmmExpr -> NatM Register toI8Reg new_rep expr = do codefn <- getAnyReg expr return (Any (intSize new_rep) codefn) -- HACK: use getAnyReg to get a byte-addressable register. -- If the source was a Fixed register, this will add the -- mov instruction to put it into the desired destination. -- We're assuming that the destination won't be a fixed -- non-byte-addressable register; it won't be, because all -- fixed registers are word-sized. toI16Reg = toI8Reg -- for now conversionNop :: Size -> CmmExpr -> NatM Register conversionNop new_size expr = do e_code <- getRegister' dflags is32Bit expr return (swizzleRegisterRep e_code new_size) getRegister' _ is32Bit (CmmMachOp mop [x, y]) = do -- dyadic MachOps sse2 <- sse2Enabled case mop of MO_F_Eq _ -> condFltReg is32Bit EQQ x y MO_F_Ne _ -> condFltReg is32Bit NE x y MO_F_Gt _ -> condFltReg is32Bit GTT x y MO_F_Ge _ -> condFltReg is32Bit GE x y MO_F_Lt _ -> condFltReg is32Bit LTT x y MO_F_Le _ -> condFltReg is32Bit LE x y MO_Eq _ -> condIntReg EQQ x y MO_Ne _ -> condIntReg NE x y MO_S_Gt _ -> condIntReg GTT x y MO_S_Ge _ -> condIntReg GE x y MO_S_Lt _ -> condIntReg LTT x y MO_S_Le _ -> condIntReg LE x y MO_U_Gt _ -> condIntReg GU x y MO_U_Ge _ -> condIntReg GEU x y MO_U_Lt _ -> condIntReg LU x y MO_U_Le _ -> condIntReg LEU x y MO_F_Add w | sse2 -> trivialFCode_sse2 w ADD x y | otherwise -> trivialFCode_x87 GADD x y MO_F_Sub w | sse2 -> trivialFCode_sse2 w SUB x y | otherwise -> trivialFCode_x87 GSUB x y MO_F_Quot w | sse2 -> trivialFCode_sse2 w FDIV x y | otherwise -> trivialFCode_x87 GDIV x y MO_F_Mul w | sse2 -> trivialFCode_sse2 w MUL x y | otherwise -> trivialFCode_x87 GMUL x y MO_Add rep -> add_code rep x y MO_Sub rep -> sub_code rep x y MO_S_Quot rep -> div_code rep True True x y MO_S_Rem rep -> div_code rep True False x y MO_U_Quot rep -> div_code rep False True x y MO_U_Rem rep -> div_code rep False False x y MO_S_MulMayOflo rep -> imulMayOflo rep x y MO_Mul rep -> triv_op rep IMUL MO_And rep -> triv_op rep AND MO_Or rep -> triv_op rep OR MO_Xor rep -> triv_op rep XOR {- Shift ops on x86s have constraints on their source, it either has to be Imm, CL or 1 => trivialCode is not restrictive enough (sigh.) -} MO_Shl rep -> shift_code rep SHL x y {-False-} MO_U_Shr rep -> shift_code rep SHR x y {-False-} MO_S_Shr rep -> shift_code rep SAR x y {-False-} MO_V_Insert {} -> needLlvm MO_V_Extract {} -> needLlvm MO_V_Add {} -> needLlvm MO_V_Sub {} -> needLlvm MO_V_Mul {} -> needLlvm MO_VS_Quot {} -> needLlvm MO_VS_Rem {} -> needLlvm MO_VS_Neg {} -> needLlvm MO_VF_Insert {} -> needLlvm MO_VF_Extract {} -> needLlvm MO_VF_Add {} -> needLlvm MO_VF_Sub {} -> needLlvm MO_VF_Mul {} -> needLlvm MO_VF_Quot {} -> needLlvm MO_VF_Neg {} -> needLlvm _other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop) where -------------------- triv_op width instr = trivialCode width op (Just op) x y where op = instr (intSize width) imulMayOflo :: Width -> CmmExpr -> CmmExpr -> NatM Register imulMayOflo rep a b = do (a_reg, a_code) <- getNonClobberedReg a b_code <- getAnyReg b let shift_amt = case rep of W32 -> 31 W64 -> 63 _ -> panic "shift_amt" size = intSize rep code = a_code `appOL` b_code eax `appOL` toOL [ IMUL2 size (OpReg a_reg), -- result in %edx:%eax SAR size (OpImm (ImmInt shift_amt)) (OpReg eax), -- sign extend lower part SUB size (OpReg edx) (OpReg eax) -- compare against upper -- eax==0 if high part == sign extended low part ] return (Fixed size eax code) -------------------- shift_code :: Width -> (Size -> Operand -> Operand -> Instr) -> CmmExpr -> CmmExpr -> NatM Register {- Case1: shift length as immediate -} shift_code width instr x (CmmLit lit) = do x_code <- getAnyReg x let size = intSize width code dst = x_code dst `snocOL` instr size (OpImm (litToImm lit)) (OpReg dst) return (Any size code) {- Case2: shift length is complex (non-immediate) * y must go in %ecx. * we cannot do y first *and* put its result in %ecx, because %ecx might be clobbered by x. * if we do y second, then x cannot be in a clobbered reg. Also, we cannot clobber x's reg with the instruction itself. * so we can either: - do y first, put its result in a fresh tmp, then copy it to %ecx later - do y second and put its result into %ecx. x gets placed in a fresh tmp. This is likely to be better, because the reg alloc can eliminate this reg->reg move here (it won't eliminate the other one, because the move is into the fixed %ecx). -} shift_code width instr x y{-amount-} = do x_code <- getAnyReg x let size = intSize width tmp <- getNewRegNat size y_code <- getAnyReg y let code = x_code tmp `appOL` y_code ecx `snocOL` instr size (OpReg ecx) (OpReg tmp) return (Fixed size tmp code) -------------------- add_code :: Width -> CmmExpr -> CmmExpr -> NatM Register add_code rep x (CmmLit (CmmInt y _)) | is32BitInteger y = add_int rep x y add_code rep x y = trivialCode rep (ADD size) (Just (ADD size)) x y where size = intSize rep -- TODO: There are other interesting patterns we want to replace -- with a LEA, e.g. `(x + offset) + (y << shift)`. -------------------- sub_code :: Width -> CmmExpr -> CmmExpr -> NatM Register sub_code rep x (CmmLit (CmmInt y _)) | is32BitInteger (-y) = add_int rep x (-y) sub_code rep x y = trivialCode rep (SUB (intSize rep)) Nothing x y -- our three-operand add instruction: add_int width x y = do (x_reg, x_code) <- getSomeReg x let size = intSize width imm = ImmInt (fromInteger y) code dst = x_code `snocOL` LEA size (OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm)) (OpReg dst) -- return (Any size code) ---------------------- div_code width signed quotient x y = do (y_op, y_code) <- getRegOrMem y -- cannot be clobbered x_code <- getAnyReg x let size = intSize width widen | signed = CLTD size | otherwise = XOR size (OpReg edx) (OpReg edx) instr | signed = IDIV | otherwise = DIV code = y_code `appOL` x_code eax `appOL` toOL [widen, instr size y_op] result | quotient = eax | otherwise = edx return (Fixed size result code) getRegister' _ _ (CmmLoad mem pk) | isFloatType pk = do Amode addr mem_code <- getAmode mem use_sse2 <- sse2Enabled loadFloatAmode use_sse2 (typeWidth pk) addr mem_code getRegister' _ is32Bit (CmmLoad mem pk) | is32Bit && not (isWord64 pk) = do code <- intLoadCode instr mem return (Any size code) where width = typeWidth pk size = intSize width instr = case width of W8 -> MOVZxL II8 _other -> MOV size -- We always zero-extend 8-bit loads, if we -- can't think of anything better. This is because -- we can't guarantee access to an 8-bit variant of every register -- (esi and edi don't have 8-bit variants), so to make things -- simpler we do our 8-bit arithmetic with full 32-bit registers. -- Simpler memory load code on x86_64 getRegister' _ is32Bit (CmmLoad mem pk) | not is32Bit = do code <- intLoadCode (MOV size) mem return (Any size code) where size = intSize $ typeWidth pk getRegister' _ is32Bit (CmmLit (CmmInt 0 width)) = let size = intSize width -- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits size1 = if is32Bit then size else case size of II64 -> II32 _ -> size code dst = unitOL (XOR size1 (OpReg dst) (OpReg dst)) in return (Any size code) -- optimisation for loading small literals on x86_64: take advantage -- of the automatic zero-extension from 32 to 64 bits, because the 32-bit -- instruction forms are shorter. getRegister' dflags is32Bit (CmmLit lit) | not is32Bit, isWord64 (cmmLitType dflags lit), not (isBigLit lit) = let imm = litToImm lit code dst = unitOL (MOV II32 (OpImm imm) (OpReg dst)) in return (Any II64 code) where isBigLit (CmmInt i _) = i < 0 || i > 0xffffffff isBigLit _ = False -- note1: not the same as (not.is32BitLit), because that checks for -- signed literals that fit in 32 bits, but we want unsigned -- literals here. -- note2: all labels are small, because we're assuming the -- small memory model (see gcc docs, -mcmodel=small). getRegister' dflags _ (CmmLit lit) = do let size = cmmTypeSize (cmmLitType dflags lit) imm = litToImm lit code dst = unitOL (MOV size (OpImm imm) (OpReg dst)) return (Any size code) getRegister' _ _ other | isVecExpr other = needLlvm | otherwise = pprPanic "getRegister(x86)" (ppr other) intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr -> NatM (Reg -> InstrBlock) intLoadCode instr mem = do Amode src mem_code <- getAmode mem return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst)) -- Compute an expression into *any* register, adding the appropriate -- move instruction if necessary. getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock) getAnyReg expr = do r <- getRegister expr anyReg r anyReg :: Register -> NatM (Reg -> InstrBlock) anyReg (Any _ code) = return code anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst) -- A bit like getSomeReg, but we want a reg that can be byte-addressed. -- Fixed registers might not be byte-addressable, so we make sure we've -- got a temporary, inserting an extra reg copy if necessary. getByteReg :: CmmExpr -> NatM (Reg, InstrBlock) getByteReg expr = do is32Bit <- is32BitPlatform if is32Bit then do r <- getRegister expr case r of Any rep code -> do tmp <- getNewRegNat rep return (tmp, code tmp) Fixed rep reg code | isVirtualReg reg -> return (reg,code) | otherwise -> do tmp <- getNewRegNat rep return (tmp, code `snocOL` reg2reg rep reg tmp) -- ToDo: could optimise slightly by checking for -- byte-addressable real registers, but that will -- happen very rarely if at all. else getSomeReg expr -- all regs are byte-addressable on x86_64 -- Another variant: this time we want the result in a register that cannot -- be modified by code to evaluate an arbitrary expression. getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock) getNonClobberedReg expr = do dflags <- getDynFlags r <- getRegister expr case r of Any rep code -> do tmp <- getNewRegNat rep return (tmp, code tmp) Fixed rep reg code -- only certain regs can be clobbered | reg `elem` instrClobberedRegs (targetPlatform dflags) -> do tmp <- getNewRegNat rep return (tmp, code `snocOL` reg2reg rep reg tmp) | otherwise -> return (reg, code) reg2reg :: Size -> Reg -> Reg -> Instr reg2reg size src dst | size == FF80 = GMOV src dst | otherwise = MOV size (OpReg src) (OpReg dst) -------------------------------------------------------------------------------- getAmode :: CmmExpr -> NatM Amode getAmode e = do is32Bit <- is32BitPlatform getAmode' is32Bit e getAmode' :: Bool -> CmmExpr -> NatM Amode getAmode' _ (CmmRegOff r n) = do dflags <- getDynFlags getAmode $ mangleIndexTree dflags r n getAmode' is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg), CmmLit displacement]) | not is32Bit = return $ Amode (ripRel (litToImm displacement)) nilOL -- This is all just ridiculous, since it carefully undoes -- what mangleIndexTree has just done. getAmode' is32Bit (CmmMachOp (MO_Sub _rep) [x, CmmLit lit@(CmmInt i _)]) | is32BitLit is32Bit lit -- ASSERT(rep == II32)??? = do (x_reg, x_code) <- getSomeReg x let off = ImmInt (-(fromInteger i)) return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code) getAmode' is32Bit (CmmMachOp (MO_Add _rep) [x, CmmLit lit]) | is32BitLit is32Bit lit -- ASSERT(rep == II32)??? = do (x_reg, x_code) <- getSomeReg x let off = litToImm lit return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code) -- Turn (lit1 << n + lit2) into (lit2 + lit1 << n) so it will be -- recognised by the next rule. getAmode' is32Bit (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _), b@(CmmLit _)]) = getAmode' is32Bit (CmmMachOp (MO_Add rep) [b,a]) -- Matches: (x + offset) + (y << shift) getAmode' _ (CmmMachOp (MO_Add _) [CmmRegOff x offset, CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)]]) | shift == 0 || shift == 1 || shift == 2 || shift == 3 = x86_complex_amode (CmmReg x) y shift (fromIntegral offset) getAmode' _ (CmmMachOp (MO_Add _) [x, CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)]]) | shift == 0 || shift == 1 || shift == 2 || shift == 3 = x86_complex_amode x y shift 0 getAmode' _ (CmmMachOp (MO_Add _) [x, CmmMachOp (MO_Add _) [CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)], CmmLit (CmmInt offset _)]]) | shift == 0 || shift == 1 || shift == 2 || shift == 3 && is32BitInteger offset = x86_complex_amode x y shift offset getAmode' _ (CmmMachOp (MO_Add _) [x,y]) = x86_complex_amode x y 0 0 getAmode' is32Bit (CmmLit lit) | is32BitLit is32Bit lit = return (Amode (ImmAddr (litToImm lit) 0) nilOL) getAmode' _ expr = do (reg,code) <- getSomeReg expr return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code) -- | Like 'getAmode', but on 32-bit use simple register addressing -- (i.e. no index register). This stops us from running out of -- registers on x86 when using instructions such as cmpxchg, which can -- use up to three virtual registers and one fixed register. getSimpleAmode :: DynFlags -> Bool -> CmmExpr -> NatM Amode getSimpleAmode dflags is32Bit addr | is32Bit = do addr_code <- getAnyReg addr addr_r <- getNewRegNat (intSize (wordWidth dflags)) let amode = AddrBaseIndex (EABaseReg addr_r) EAIndexNone (ImmInt 0) return $! Amode amode (addr_code addr_r) | otherwise = getAmode addr x86_complex_amode :: CmmExpr -> CmmExpr -> Integer -> Integer -> NatM Amode x86_complex_amode base index shift offset = do (x_reg, x_code) <- getNonClobberedReg base -- x must be in a temp, because it has to stay live over y_code -- we could compre x_reg and y_reg and do something better here... (y_reg, y_code) <- getSomeReg index let code = x_code `appOL` y_code base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8; n -> panic $ "x86_complex_amode: unhandled shift! (" ++ show n ++ ")" return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt (fromIntegral offset))) code) -- ----------------------------------------------------------------------------- -- getOperand: sometimes any operand will do. -- getNonClobberedOperand: the value of the operand will remain valid across -- the computation of an arbitrary expression, unless the expression -- is computed directly into a register which the operand refers to -- (see trivialCode where this function is used for an example). getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock) getNonClobberedOperand (CmmLit lit) = do use_sse2 <- sse2Enabled if use_sse2 && isSuitableFloatingPointLit lit then do let CmmFloat _ w = lit Amode addr code <- memConstant (widthInBytes w) lit return (OpAddr addr, code) else do is32Bit <- is32BitPlatform dflags <- getDynFlags if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit)) then return (OpImm (litToImm lit), nilOL) else getNonClobberedOperand_generic (CmmLit lit) getNonClobberedOperand (CmmLoad mem pk) = do is32Bit <- is32BitPlatform use_sse2 <- sse2Enabled if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True) then do dflags <- getDynFlags let platform = targetPlatform dflags Amode src mem_code <- getAmode mem (src',save_code) <- if (amodeCouldBeClobbered platform src) then do tmp <- getNewRegNat (archWordSize is32Bit) return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0), unitOL (LEA (archWordSize is32Bit) (OpAddr src) (OpReg tmp))) else return (src, nilOL) return (OpAddr src', mem_code `appOL` save_code) else do getNonClobberedOperand_generic (CmmLoad mem pk) getNonClobberedOperand e = getNonClobberedOperand_generic e getNonClobberedOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock) getNonClobberedOperand_generic e = do (reg, code) <- getNonClobberedReg e return (OpReg reg, code) amodeCouldBeClobbered :: Platform -> AddrMode -> Bool amodeCouldBeClobbered platform amode = any (regClobbered platform) (addrModeRegs amode) regClobbered :: Platform -> Reg -> Bool regClobbered platform (RegReal (RealRegSingle rr)) = isFastTrue (freeReg platform rr) regClobbered _ _ = False -- getOperand: the operand is not required to remain valid across the -- computation of an arbitrary expression. getOperand :: CmmExpr -> NatM (Operand, InstrBlock) getOperand (CmmLit lit) = do use_sse2 <- sse2Enabled if (use_sse2 && isSuitableFloatingPointLit lit) then do let CmmFloat _ w = lit Amode addr code <- memConstant (widthInBytes w) lit return (OpAddr addr, code) else do is32Bit <- is32BitPlatform dflags <- getDynFlags if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit)) then return (OpImm (litToImm lit), nilOL) else getOperand_generic (CmmLit lit) getOperand (CmmLoad mem pk) = do is32Bit <- is32BitPlatform use_sse2 <- sse2Enabled if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True) then do Amode src mem_code <- getAmode mem return (OpAddr src, mem_code) else getOperand_generic (CmmLoad mem pk) getOperand e = getOperand_generic e getOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock) getOperand_generic e = do (reg, code) <- getSomeReg e return (OpReg reg, code) isOperand :: Bool -> CmmExpr -> Bool isOperand _ (CmmLoad _ _) = True isOperand is32Bit (CmmLit lit) = is32BitLit is32Bit lit || isSuitableFloatingPointLit lit isOperand _ _ = False memConstant :: Int -> CmmLit -> NatM Amode memConstant align lit = do lbl <- getNewLabelNat dflags <- getDynFlags (addr, addr_code) <- if target32Bit (targetPlatform dflags) then do dynRef <- cmmMakeDynamicReference dflags DataReference lbl Amode addr addr_code <- getAmode dynRef return (addr, addr_code) else return (ripRel (ImmCLbl lbl), nilOL) let code = LDATA ReadOnlyData (align, Statics lbl [CmmStaticLit lit]) `consOL` addr_code return (Amode addr code) loadFloatAmode :: Bool -> Width -> AddrMode -> InstrBlock -> NatM Register loadFloatAmode use_sse2 w addr addr_code = do let size = floatSize w code dst = addr_code `snocOL` if use_sse2 then MOV size (OpAddr addr) (OpReg dst) else GLD size addr dst return (Any (if use_sse2 then size else FF80) code) -- if we want a floating-point literal as an operand, we can -- use it directly from memory. However, if the literal is -- zero, we're better off generating it into a register using -- xor. isSuitableFloatingPointLit :: CmmLit -> Bool isSuitableFloatingPointLit (CmmFloat f _) = f /= 0.0 isSuitableFloatingPointLit _ = False getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock) getRegOrMem e@(CmmLoad mem pk) = do is32Bit <- is32BitPlatform use_sse2 <- sse2Enabled if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True) then do Amode src mem_code <- getAmode mem return (OpAddr src, mem_code) else do (reg, code) <- getNonClobberedReg e return (OpReg reg, code) getRegOrMem e = do (reg, code) <- getNonClobberedReg e return (OpReg reg, code) is32BitLit :: Bool -> CmmLit -> Bool is32BitLit is32Bit (CmmInt i W64) | not is32Bit = -- assume that labels are in the range 0-2^31-1: this assumes the -- small memory model (see gcc docs, -mcmodel=small). is32BitInteger i is32BitLit _ _ = True -- Set up a condition code for a conditional branch. getCondCode :: CmmExpr -> NatM CondCode -- yes, they really do seem to want exactly the same! getCondCode (CmmMachOp mop [x, y]) = case mop of MO_F_Eq W32 -> condFltCode EQQ x y MO_F_Ne W32 -> condFltCode NE x y MO_F_Gt W32 -> condFltCode GTT x y MO_F_Ge W32 -> condFltCode GE x y MO_F_Lt W32 -> condFltCode LTT x y MO_F_Le W32 -> condFltCode LE x y MO_F_Eq W64 -> condFltCode EQQ x y MO_F_Ne W64 -> condFltCode NE x y MO_F_Gt W64 -> condFltCode GTT x y MO_F_Ge W64 -> condFltCode GE x y MO_F_Lt W64 -> condFltCode LTT x y MO_F_Le W64 -> condFltCode LE x y MO_Eq _ -> condIntCode EQQ x y MO_Ne _ -> condIntCode NE x y MO_S_Gt _ -> condIntCode GTT x y MO_S_Ge _ -> condIntCode GE x y MO_S_Lt _ -> condIntCode LTT x y MO_S_Le _ -> condIntCode LE x y MO_U_Gt _ -> condIntCode GU x y MO_U_Ge _ -> condIntCode GEU x y MO_U_Lt _ -> condIntCode LU x y MO_U_Le _ -> condIntCode LEU x y _other -> pprPanic "getCondCode(x86,x86_64)" (ppr (CmmMachOp mop [x,y])) getCondCode other = pprPanic "getCondCode(2)(x86,x86_64)" (ppr other) -- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be -- passed back up the tree. condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode condIntCode cond x y = do is32Bit <- is32BitPlatform condIntCode' is32Bit cond x y condIntCode' :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM CondCode -- memory vs immediate condIntCode' is32Bit cond (CmmLoad x pk) (CmmLit lit) | is32BitLit is32Bit lit = do Amode x_addr x_code <- getAmode x let imm = litToImm lit code = x_code `snocOL` CMP (cmmTypeSize pk) (OpImm imm) (OpAddr x_addr) -- return (CondCode False cond code) -- anything vs zero, using a mask -- TODO: Add some sanity checking!!!! condIntCode' is32Bit cond (CmmMachOp (MO_And _) [x,o2]) (CmmLit (CmmInt 0 pk)) | (CmmLit lit@(CmmInt mask _)) <- o2, is32BitLit is32Bit lit = do (x_reg, x_code) <- getSomeReg x let code = x_code `snocOL` TEST (intSize pk) (OpImm (ImmInteger mask)) (OpReg x_reg) -- return (CondCode False cond code) -- anything vs zero condIntCode' _ cond x (CmmLit (CmmInt 0 pk)) = do (x_reg, x_code) <- getSomeReg x let code = x_code `snocOL` TEST (intSize pk) (OpReg x_reg) (OpReg x_reg) -- return (CondCode False cond code) -- anything vs operand condIntCode' is32Bit cond x y | isOperand is32Bit y = do dflags <- getDynFlags (x_reg, x_code) <- getNonClobberedReg x (y_op, y_code) <- getOperand y let code = x_code `appOL` y_code `snocOL` CMP (cmmTypeSize (cmmExprType dflags x)) y_op (OpReg x_reg) return (CondCode False cond code) -- operand vs. anything: invert the comparison so that we can use a -- single comparison instruction. | isOperand is32Bit x , Just revcond <- maybeFlipCond cond = do dflags <- getDynFlags (y_reg, y_code) <- getNonClobberedReg y (x_op, x_code) <- getOperand x let code = y_code `appOL` x_code `snocOL` CMP (cmmTypeSize (cmmExprType dflags x)) x_op (OpReg y_reg) return (CondCode False revcond code) -- anything vs anything condIntCode' _ cond x y = do dflags <- getDynFlags (y_reg, y_code) <- getNonClobberedReg y (x_op, x_code) <- getRegOrMem x let code = y_code `appOL` x_code `snocOL` CMP (cmmTypeSize (cmmExprType dflags x)) (OpReg y_reg) x_op return (CondCode False cond code) -------------------------------------------------------------------------------- condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode condFltCode cond x y = if_sse2 condFltCode_sse2 condFltCode_x87 where condFltCode_x87 = ASSERT(cond `elem` ([EQQ, NE, LE, LTT, GE, GTT])) do (x_reg, x_code) <- getNonClobberedReg x (y_reg, y_code) <- getSomeReg y let code = x_code `appOL` y_code `snocOL` GCMP cond x_reg y_reg -- The GCMP insn does the test and sets the zero flag if comparable -- and true. Hence we always supply EQQ as the condition to test. return (CondCode True EQQ code) -- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be -- an operand, but the right must be a reg. We can probably do better -- than this general case... condFltCode_sse2 = do dflags <- getDynFlags (x_reg, x_code) <- getNonClobberedReg x (y_op, y_code) <- getOperand y let code = x_code `appOL` y_code `snocOL` CMP (floatSize $ cmmExprWidth dflags x) y_op (OpReg x_reg) -- NB(1): we need to use the unsigned comparison operators on the -- result of this comparison. return (CondCode True (condToUnsigned cond) code) -- ----------------------------------------------------------------------------- -- Generating assignments -- Assignments are really at the heart of the whole code generation -- business. Almost all top-level nodes of any real importance are -- assignments, which correspond to loads, stores, or register -- transfers. If we're really lucky, some of the register transfers -- will go away, because we can use the destination register to -- complete the code generation for the right hand side. This only -- fails when the right hand side is forced into a fixed register -- (e.g. the result of a call). assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock -- integer assignment to memory -- specific case of adding/subtracting an integer to a particular address. -- ToDo: catch other cases where we can use an operation directly on a memory -- address. assignMem_IntCode pk addr (CmmMachOp op [CmmLoad addr2 _, CmmLit (CmmInt i _)]) | addr == addr2, pk /= II64 || is32BitInteger i, Just instr <- check op = do Amode amode code_addr <- getAmode addr let code = code_addr `snocOL` instr pk (OpImm (ImmInt (fromIntegral i))) (OpAddr amode) return code where check (MO_Add _) = Just ADD check (MO_Sub _) = Just SUB check _ = Nothing -- ToDo: more? -- general case assignMem_IntCode pk addr src = do is32Bit <- is32BitPlatform Amode addr code_addr <- getAmode addr (code_src, op_src) <- get_op_RI is32Bit src let code = code_src `appOL` code_addr `snocOL` MOV pk op_src (OpAddr addr) -- NOTE: op_src is stable, so it will still be valid -- after code_addr. This may involve the introduction -- of an extra MOV to a temporary register, but we hope -- the register allocator will get rid of it. -- return code where get_op_RI :: Bool -> CmmExpr -> NatM (InstrBlock,Operand) -- code, operator get_op_RI is32Bit (CmmLit lit) | is32BitLit is32Bit lit = return (nilOL, OpImm (litToImm lit)) get_op_RI _ op = do (reg,code) <- getNonClobberedReg op return (code, OpReg reg) -- Assign; dst is a reg, rhs is mem assignReg_IntCode pk reg (CmmLoad src _) = do load_code <- intLoadCode (MOV pk) src dflags <- getDynFlags let platform = targetPlatform dflags return (load_code (getRegisterReg platform False{-no sse2-} reg)) -- dst is a reg, but src could be anything assignReg_IntCode _ reg src = do dflags <- getDynFlags let platform = targetPlatform dflags code <- getAnyReg src return (code (getRegisterReg platform False{-no sse2-} reg)) -- Floating point assignment to memory assignMem_FltCode pk addr src = do (src_reg, src_code) <- getNonClobberedReg src Amode addr addr_code <- getAmode addr use_sse2 <- sse2Enabled let code = src_code `appOL` addr_code `snocOL` if use_sse2 then MOV pk (OpReg src_reg) (OpAddr addr) else GST pk src_reg addr return code -- Floating point assignment to a register/temporary assignReg_FltCode _ reg src = do use_sse2 <- sse2Enabled src_code <- getAnyReg src dflags <- getDynFlags let platform = targetPlatform dflags return (src_code (getRegisterReg platform use_sse2 reg)) genJump :: CmmExpr{-the branch target-} -> [Reg] -> NatM InstrBlock genJump (CmmLoad mem _) regs = do Amode target code <- getAmode mem return (code `snocOL` JMP (OpAddr target) regs) genJump (CmmLit lit) regs = do return (unitOL (JMP (OpImm (litToImm lit)) regs)) genJump expr regs = do (reg,code) <- getSomeReg expr return (code `snocOL` JMP (OpReg reg) regs) -- ----------------------------------------------------------------------------- -- 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. I386: First, we have to ensure that the condition codes are set according to the supplied comparison operation. -} genCondJump :: BlockId -- the branch target -> CmmExpr -- the condition on which to branch -> NatM InstrBlock genCondJump id bool = do CondCode is_float cond cond_code <- getCondCode bool use_sse2 <- sse2Enabled if not is_float || not use_sse2 then return (cond_code `snocOL` JXX cond id) else do lbl <- getBlockIdNat -- see comment with condFltReg let code = case cond of NE -> or_unordered GU -> plain_test GEU -> plain_test _ -> and_ordered plain_test = unitOL ( JXX cond id ) or_unordered = toOL [ JXX cond id, JXX PARITY id ] and_ordered = toOL [ JXX PARITY lbl, JXX cond id, JXX ALWAYS lbl, NEWBLOCK lbl ] return (cond_code `appOL` code) -- ----------------------------------------------------------------------------- -- 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 :: DynFlags -> Bool -- 32 bit platform? -> ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- Unroll memcpy calls if the source and destination pointers are at -- least DWORD aligned and the number of bytes to copy isn't too -- large. Otherwise, call C's memcpy. genCCall dflags is32Bit (PrimTarget MO_Memcpy) _ [dst, src, (CmmLit (CmmInt n _)), (CmmLit (CmmInt align _))] | fromInteger insns <= maxInlineMemcpyInsns dflags && align .&. 3 == 0 = do code_dst <- getAnyReg dst dst_r <- getNewRegNat size code_src <- getAnyReg src src_r <- getNewRegNat size tmp_r <- getNewRegNat size return $ code_dst dst_r `appOL` code_src src_r `appOL` go dst_r src_r tmp_r (fromInteger n) where -- The number of instructions we will generate (approx). We need 2 -- instructions per move. insns = 2 * ((n + sizeBytes - 1) `div` sizeBytes) size = if align .&. 4 /= 0 then II32 else (archWordSize is32Bit) -- The size of each move, in bytes. sizeBytes :: Integer sizeBytes = fromIntegral (sizeInBytes size) go :: Reg -> Reg -> Reg -> Integer -> OrdList Instr go dst src tmp i | i >= sizeBytes = unitOL (MOV size (OpAddr src_addr) (OpReg tmp)) `appOL` unitOL (MOV size (OpReg tmp) (OpAddr dst_addr)) `appOL` go dst src tmp (i - sizeBytes) -- Deal with remaining bytes. | i >= 4 = -- Will never happen on 32-bit unitOL (MOV II32 (OpAddr src_addr) (OpReg tmp)) `appOL` unitOL (MOV II32 (OpReg tmp) (OpAddr dst_addr)) `appOL` go dst src tmp (i - 4) | i >= 2 = unitOL (MOVZxL II16 (OpAddr src_addr) (OpReg tmp)) `appOL` unitOL (MOV II16 (OpReg tmp) (OpAddr dst_addr)) `appOL` go dst src tmp (i - 2) | i >= 1 = unitOL (MOVZxL II8 (OpAddr src_addr) (OpReg tmp)) `appOL` unitOL (MOV II8 (OpReg tmp) (OpAddr dst_addr)) `appOL` go dst src tmp (i - 1) | otherwise = nilOL where src_addr = AddrBaseIndex (EABaseReg src) EAIndexNone (ImmInteger (n - i)) dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone (ImmInteger (n - i)) genCCall dflags _ (PrimTarget MO_Memset) _ [dst, CmmLit (CmmInt c _), CmmLit (CmmInt n _), CmmLit (CmmInt align _)] | fromInteger insns <= maxInlineMemsetInsns dflags && align .&. 3 == 0 = do code_dst <- getAnyReg dst dst_r <- getNewRegNat size return $ code_dst dst_r `appOL` go dst_r (fromInteger n) where (size, val) = case align .&. 3 of 2 -> (II16, c2) 0 -> (II32, c4) _ -> (II8, c) c2 = c `shiftL` 8 .|. c c4 = c2 `shiftL` 16 .|. c2 -- The number of instructions we will generate (approx). We need 1 -- instructions per move. insns = (n + sizeBytes - 1) `div` sizeBytes -- The size of each move, in bytes. sizeBytes :: Integer sizeBytes = fromIntegral (sizeInBytes size) go :: Reg -> Integer -> OrdList Instr go dst i -- TODO: Add movabs instruction and support 64-bit sets. | i >= sizeBytes = -- This might be smaller than the below sizes unitOL (MOV size (OpImm (ImmInteger val)) (OpAddr dst_addr)) `appOL` go dst (i - sizeBytes) | i >= 4 = -- Will never happen on 32-bit unitOL (MOV II32 (OpImm (ImmInteger c4)) (OpAddr dst_addr)) `appOL` go dst (i - 4) | i >= 2 = unitOL (MOV II16 (OpImm (ImmInteger c2)) (OpAddr dst_addr)) `appOL` go dst (i - 2) | i >= 1 = unitOL (MOV II8 (OpImm (ImmInteger c)) (OpAddr dst_addr)) `appOL` go dst (i - 1) | otherwise = nilOL where dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone (ImmInteger (n - i)) genCCall _ _ (PrimTarget MO_WriteBarrier) _ _ = return nilOL -- write barrier compiles to no code on x86/x86-64; -- we keep it this long in order to prevent earlier optimisations. genCCall _ _ (PrimTarget MO_Touch) _ _ = return nilOL genCCall _ is32bit (PrimTarget (MO_Prefetch_Data n )) _ [src] = case n of 0 -> genPrefetch src $ PREFETCH NTA size 1 -> genPrefetch src $ PREFETCH Lvl2 size 2 -> genPrefetch src $ PREFETCH Lvl1 size 3 -> genPrefetch src $ PREFETCH Lvl0 size l -> panic $ "unexpected prefetch level in genCCall MO_Prefetch_Data: " ++ (show l) -- the c / llvm prefetch convention is 0, 1, 2, and 3 -- the x86 corresponding names are : NTA, 2 , 1, and 0 where size = archWordSize is32bit -- need to know what register width for pointers! genPrefetch inRegSrc prefetchCTor = do code_src <- getAnyReg inRegSrc src_r <- getNewRegNat size return $ code_src src_r `appOL` (unitOL (prefetchCTor (OpAddr ((AddrBaseIndex (EABaseReg src_r ) EAIndexNone (ImmInt 0)))) )) -- prefetch always takes an address genCCall dflags is32Bit (PrimTarget (MO_BSwap width)) [dst] [src] = do let platform = targetPlatform dflags let dst_r = getRegisterReg platform False (CmmLocal dst) case width of W64 | is32Bit -> do ChildCode64 vcode rlo <- iselExpr64 src let dst_rhi = getHiVRegFromLo dst_r rhi = getHiVRegFromLo rlo return $ vcode `appOL` toOL [ MOV II32 (OpReg rlo) (OpReg dst_rhi), MOV II32 (OpReg rhi) (OpReg dst_r), BSWAP II32 dst_rhi, BSWAP II32 dst_r ] W16 -> do code_src <- getAnyReg src return $ code_src dst_r `appOL` unitOL (BSWAP II32 dst_r) `appOL` unitOL (SHR II32 (OpImm $ ImmInt 16) (OpReg dst_r)) _ -> do code_src <- getAnyReg src return $ code_src dst_r `appOL` unitOL (BSWAP size dst_r) where size = intSize width genCCall dflags is32Bit (PrimTarget (MO_PopCnt width)) dest_regs@[dst] args@[src] = do sse4_2 <- sse4_2Enabled let platform = targetPlatform dflags if sse4_2 then do code_src <- getAnyReg src src_r <- getNewRegNat size return $ code_src src_r `appOL` (if width == W8 then -- The POPCNT instruction doesn't take a r/m8 unitOL (MOVZxL II8 (OpReg src_r) (OpReg src_r)) `appOL` unitOL (POPCNT II16 (OpReg src_r) (getRegisterReg platform False (CmmLocal dst))) else unitOL (POPCNT size (OpReg src_r) (getRegisterReg platform False (CmmLocal dst)))) else do targetExpr <- cmmMakeDynamicReference dflags CallReference lbl let target = ForeignTarget targetExpr (ForeignConvention CCallConv [NoHint] [NoHint] CmmMayReturn) genCCall dflags is32Bit target dest_regs args where size = intSize width lbl = mkCmmCodeLabel primPackageKey (fsLit (popCntLabel width)) genCCall dflags is32Bit (PrimTarget (MO_UF_Conv width)) dest_regs args = do targetExpr <- cmmMakeDynamicReference dflags CallReference lbl let target = ForeignTarget targetExpr (ForeignConvention CCallConv [NoHint] [NoHint] CmmMayReturn) genCCall dflags is32Bit target dest_regs args where lbl = mkCmmCodeLabel primPackageKey (fsLit (word2FloatLabel width)) genCCall dflags is32Bit (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = do Amode amode addr_code <- if amop `elem` [AMO_Add, AMO_Sub] then getAmode addr else getSimpleAmode dflags is32Bit addr -- See genCCall for MO_Cmpxchg arg <- getNewRegNat size arg_code <- getAnyReg n use_sse2 <- sse2Enabled let platform = targetPlatform dflags dst_r = getRegisterReg platform use_sse2 (CmmLocal dst) code <- op_code dst_r arg amode return $ addr_code `appOL` arg_code arg `appOL` code where -- Code for the operation op_code :: Reg -- Destination reg -> Reg -- Register containing argument -> AddrMode -- Address of location to mutate -> NatM (OrdList Instr) op_code dst_r arg amode = case amop of -- In the common case where dst_r is a virtual register the -- final move should go away, because it's the last use of arg -- and the first use of dst_r. AMO_Add -> return $ toOL [ LOCK (XADD size (OpReg arg) (OpAddr amode)) , MOV size (OpReg arg) (OpReg dst_r) ] AMO_Sub -> return $ toOL [ NEGI size (OpReg arg) , LOCK (XADD size (OpReg arg) (OpAddr amode)) , MOV size (OpReg arg) (OpReg dst_r) ] AMO_And -> cmpxchg_code (\ src dst -> unitOL $ AND size src dst) AMO_Nand -> cmpxchg_code (\ src dst -> toOL [ AND size src dst , NOT size dst ]) AMO_Or -> cmpxchg_code (\ src dst -> unitOL $ OR size src dst) AMO_Xor -> cmpxchg_code (\ src dst -> unitOL $ XOR size src dst) where -- Simulate operation that lacks a dedicated instruction using -- cmpxchg. cmpxchg_code :: (Operand -> Operand -> OrdList Instr) -> NatM (OrdList Instr) cmpxchg_code instrs = do lbl <- getBlockIdNat tmp <- getNewRegNat size return $ toOL [ MOV size (OpAddr amode) (OpReg eax) , JXX ALWAYS lbl , NEWBLOCK lbl -- Keep old value so we can return it: , MOV size (OpReg eax) (OpReg dst_r) , MOV size (OpReg eax) (OpReg tmp) ] `appOL` instrs (OpReg arg) (OpReg tmp) `appOL` toOL [ LOCK (CMPXCHG size (OpReg tmp) (OpAddr amode)) , JXX NE lbl ] size = intSize width genCCall dflags _ (PrimTarget (MO_AtomicRead width)) [dst] [addr] = do load_code <- intLoadCode (MOV (intSize width)) addr let platform = targetPlatform dflags use_sse2 <- sse2Enabled return (load_code (getRegisterReg platform use_sse2 (CmmLocal dst))) genCCall _ _ (PrimTarget (MO_AtomicWrite width)) [] [addr, val] = do code <- assignMem_IntCode (intSize width) addr val return $ code `snocOL` MFENCE genCCall dflags is32Bit (PrimTarget (MO_Cmpxchg width)) [dst] [addr, old, new] = do -- On x86 we don't have enough registers to use cmpxchg with a -- complicated addressing mode, so on that architecture we -- pre-compute the address first. Amode amode addr_code <- getSimpleAmode dflags is32Bit addr newval <- getNewRegNat size newval_code <- getAnyReg new oldval <- getNewRegNat size oldval_code <- getAnyReg old use_sse2 <- sse2Enabled let platform = targetPlatform dflags dst_r = getRegisterReg platform use_sse2 (CmmLocal dst) code = toOL [ MOV size (OpReg oldval) (OpReg eax) , LOCK (CMPXCHG size (OpReg newval) (OpAddr amode)) , MOV size (OpReg eax) (OpReg dst_r) ] return $ addr_code `appOL` newval_code newval `appOL` oldval_code oldval `appOL` code where size = intSize width genCCall _ is32Bit target dest_regs args | is32Bit = genCCall32 target dest_regs args | otherwise = genCCall64 target dest_regs args genCCall32 :: ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock genCCall32 target dest_regs args = do dflags <- getDynFlags let platform = targetPlatform dflags case (target, dest_regs) of -- void return type prim op (PrimTarget op, []) -> outOfLineCmmOp op Nothing args -- we only cope with a single result for foreign calls (PrimTarget op, [r]) -> do l1 <- getNewLabelNat l2 <- getNewLabelNat sse2 <- sse2Enabled if sse2 then outOfLineCmmOp op (Just r) args else case op of MO_F32_Sqrt -> actuallyInlineFloatOp GSQRT FF32 args MO_F64_Sqrt -> actuallyInlineFloatOp GSQRT FF64 args MO_F32_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF32 args MO_F64_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF64 args MO_F32_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF32 args MO_F64_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF64 args MO_F32_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF32 args MO_F64_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF64 args _other_op -> outOfLineCmmOp op (Just r) args where actuallyInlineFloatOp instr size [x] = do res <- trivialUFCode size (instr size) x any <- anyReg res return (any (getRegisterReg platform False (CmmLocal r))) actuallyInlineFloatOp _ _ args = panic $ "genCCall32.actuallyInlineFloatOp: bad number of arguments! (" ++ show (length args) ++ ")" (PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args (PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args (PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args (PrimTarget (MO_Add2 width), [res_h, res_l]) -> case args of [arg_x, arg_y] -> do hCode <- getAnyReg (CmmLit (CmmInt 0 width)) lCode <- getAnyReg (CmmMachOp (MO_Add width) [arg_x, arg_y]) let size = intSize width reg_l = getRegisterReg platform True (CmmLocal res_l) reg_h = getRegisterReg platform True (CmmLocal res_h) code = hCode reg_h `appOL` lCode reg_l `snocOL` ADC size (OpImm (ImmInteger 0)) (OpReg reg_h) return code _ -> panic "genCCall32: Wrong number of arguments/results for add2" (PrimTarget (MO_U_Mul2 width), [res_h, res_l]) -> case args of [arg_x, arg_y] -> do (y_reg, y_code) <- getRegOrMem arg_y x_code <- getAnyReg arg_x let size = intSize width reg_h = getRegisterReg platform True (CmmLocal res_h) reg_l = getRegisterReg platform True (CmmLocal res_l) code = y_code `appOL` x_code rax `appOL` toOL [MUL2 size y_reg, MOV size (OpReg rdx) (OpReg reg_h), MOV size (OpReg rax) (OpReg reg_l)] return code _ -> panic "genCCall32: Wrong number of arguments/results for add2" _ -> genCCall32' dflags target dest_regs args where divOp1 platform signed width results [arg_x, arg_y] = divOp platform signed width results Nothing arg_x arg_y divOp1 _ _ _ _ _ = panic "genCCall32: Wrong number of arguments for divOp1" divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y] = divOp platform signed width results (Just arg_x_high) arg_x_low arg_y divOp2 _ _ _ _ _ = panic "genCCall64: Wrong number of arguments for divOp2" divOp platform signed width [res_q, res_r] m_arg_x_high arg_x_low arg_y = do let size = intSize width reg_q = getRegisterReg platform True (CmmLocal res_q) reg_r = getRegisterReg platform True (CmmLocal res_r) widen | signed = CLTD size | otherwise = XOR size (OpReg rdx) (OpReg rdx) instr | signed = IDIV | otherwise = DIV (y_reg, y_code) <- getRegOrMem arg_y x_low_code <- getAnyReg arg_x_low x_high_code <- case m_arg_x_high of Just arg_x_high -> getAnyReg arg_x_high Nothing -> return $ const $ unitOL widen return $ y_code `appOL` x_low_code rax `appOL` x_high_code rdx `appOL` toOL [instr size y_reg, MOV size (OpReg rax) (OpReg reg_q), MOV size (OpReg rdx) (OpReg reg_r)] divOp _ _ _ _ _ _ _ = panic "genCCall32: Wrong number of results for divOp" genCCall32' :: DynFlags -> ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock genCCall32' dflags target dest_regs args = do let prom_args = map (maybePromoteCArg dflags W32) args -- Align stack to 16n for calls, assuming a starting stack -- alignment of 16n - word_size on procedure entry. Which we -- maintiain. See Note [rts/StgCRun.c : Stack Alignment on X86] sizes = map (arg_size . cmmExprType dflags) (reverse args) raw_arg_size = sum sizes + wORD_SIZE dflags arg_pad_size = (roundTo 16 $ raw_arg_size) - raw_arg_size tot_arg_size = raw_arg_size + arg_pad_size - wORD_SIZE dflags delta0 <- getDeltaNat setDeltaNat (delta0 - arg_pad_size) use_sse2 <- sse2Enabled push_codes <- mapM (push_arg use_sse2) (reverse prom_args) delta <- getDeltaNat MASSERT(delta == delta0 - tot_arg_size) -- deal with static vs dynamic call targets (callinsns,cconv) <- case target of ForeignTarget (CmmLit (CmmLabel lbl)) conv -> -- ToDo: stdcall arg sizes return (unitOL (CALL (Left fn_imm) []), conv) where fn_imm = ImmCLbl lbl ForeignTarget expr conv -> do { (dyn_r, dyn_c) <- getSomeReg expr ; ASSERT( isWord32 (cmmExprType dflags expr) ) return (dyn_c `snocOL` CALL (Right dyn_r) [], conv) } PrimTarget _ -> panic $ "genCCall: Can't handle PrimTarget call type here, error " ++ "probably because too many return values." let push_code | arg_pad_size /= 0 = toOL [SUB II32 (OpImm (ImmInt arg_pad_size)) (OpReg esp), DELTA (delta0 - arg_pad_size)] `appOL` concatOL push_codes | otherwise = concatOL push_codes -- Deallocate parameters after call for ccall; -- but not for stdcall (callee does it) -- -- We have to pop any stack padding we added -- even if we are doing stdcall, though (#5052) pop_size | ForeignConvention StdCallConv _ _ _ <- cconv = arg_pad_size | otherwise = tot_arg_size call = callinsns `appOL` toOL ( (if pop_size==0 then [] else [ADD II32 (OpImm (ImmInt pop_size)) (OpReg esp)]) ++ [DELTA delta0] ) setDeltaNat delta0 dflags <- getDynFlags let platform = targetPlatform dflags let -- assign the results, if necessary assign_code [] = nilOL assign_code [dest] | isFloatType ty = if use_sse2 then let tmp_amode = AddrBaseIndex (EABaseReg esp) EAIndexNone (ImmInt 0) sz = floatSize w in toOL [ SUB II32 (OpImm (ImmInt b)) (OpReg esp), DELTA (delta0 - b), GST sz fake0 tmp_amode, MOV sz (OpAddr tmp_amode) (OpReg r_dest), ADD II32 (OpImm (ImmInt b)) (OpReg esp), DELTA delta0] else unitOL (GMOV fake0 r_dest) | isWord64 ty = toOL [MOV II32 (OpReg eax) (OpReg r_dest), MOV II32 (OpReg edx) (OpReg r_dest_hi)] | otherwise = unitOL (MOV (intSize w) (OpReg eax) (OpReg r_dest)) where ty = localRegType dest w = typeWidth ty b = widthInBytes w r_dest_hi = getHiVRegFromLo r_dest r_dest = getRegisterReg platform use_sse2 (CmmLocal dest) assign_code many = pprPanic "genCCall.assign_code - too many return values:" (ppr many) return (push_code `appOL` call `appOL` assign_code dest_regs) where arg_size :: CmmType -> Int -- Width in bytes arg_size ty = widthInBytes (typeWidth ty) roundTo a x | x `mod` a == 0 = x | otherwise = x + a - (x `mod` a) push_arg :: Bool -> CmmActual {-current argument-} -> NatM InstrBlock -- code push_arg use_sse2 arg -- we don't need the hints on x86 | isWord64 arg_ty = do ChildCode64 code r_lo <- iselExpr64 arg delta <- getDeltaNat setDeltaNat (delta - 8) let r_hi = getHiVRegFromLo r_lo return ( code `appOL` toOL [PUSH II32 (OpReg r_hi), DELTA (delta - 4), PUSH II32 (OpReg r_lo), DELTA (delta - 8), DELTA (delta-8)] ) | isFloatType arg_ty = do (reg, code) <- getSomeReg arg delta <- getDeltaNat setDeltaNat (delta-size) return (code `appOL` toOL [SUB II32 (OpImm (ImmInt size)) (OpReg esp), DELTA (delta-size), let addr = AddrBaseIndex (EABaseReg esp) EAIndexNone (ImmInt 0) size = floatSize (typeWidth arg_ty) in if use_sse2 then MOV size (OpReg reg) (OpAddr addr) else GST size reg addr ] ) | otherwise = do (operand, code) <- getOperand arg delta <- getDeltaNat setDeltaNat (delta-size) return (code `snocOL` PUSH II32 operand `snocOL` DELTA (delta-size)) where arg_ty = cmmExprType dflags arg size = arg_size arg_ty -- Byte size genCCall64 :: ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock genCCall64 target dest_regs args = do dflags <- getDynFlags let platform = targetPlatform dflags case (target, dest_regs) of (PrimTarget op, []) -> -- void return type prim op outOfLineCmmOp op Nothing args (PrimTarget op, [res]) -> -- we only cope with a single result for foreign calls outOfLineCmmOp op (Just res) args (PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args (PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args (PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args (PrimTarget (MO_Add2 width), [res_h, res_l]) -> case args of [arg_x, arg_y] -> do hCode <- getAnyReg (CmmLit (CmmInt 0 width)) lCode <- getAnyReg (CmmMachOp (MO_Add width) [arg_x, arg_y]) let size = intSize width reg_l = getRegisterReg platform True (CmmLocal res_l) reg_h = getRegisterReg platform True (CmmLocal res_h) code = hCode reg_h `appOL` lCode reg_l `snocOL` ADC size (OpImm (ImmInteger 0)) (OpReg reg_h) return code _ -> panic "genCCall64: Wrong number of arguments/results for add2" (PrimTarget (MO_U_Mul2 width), [res_h, res_l]) -> case args of [arg_x, arg_y] -> do (y_reg, y_code) <- getRegOrMem arg_y x_code <- getAnyReg arg_x let size = intSize width reg_h = getRegisterReg platform True (CmmLocal res_h) reg_l = getRegisterReg platform True (CmmLocal res_l) code = y_code `appOL` x_code rax `appOL` toOL [MUL2 size y_reg, MOV size (OpReg rdx) (OpReg reg_h), MOV size (OpReg rax) (OpReg reg_l)] return code _ -> panic "genCCall64: Wrong number of arguments/results for add2" _ -> do dflags <- getDynFlags genCCall64' dflags target dest_regs args where divOp1 platform signed width results [arg_x, arg_y] = divOp platform signed width results Nothing arg_x arg_y divOp1 _ _ _ _ _ = panic "genCCall64: Wrong number of arguments for divOp1" divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y] = divOp platform signed width results (Just arg_x_high) arg_x_low arg_y divOp2 _ _ _ _ _ = panic "genCCall64: Wrong number of arguments for divOp2" divOp platform signed width [res_q, res_r] m_arg_x_high arg_x_low arg_y = do let size = intSize width reg_q = getRegisterReg platform True (CmmLocal res_q) reg_r = getRegisterReg platform True (CmmLocal res_r) widen | signed = CLTD size | otherwise = XOR size (OpReg rdx) (OpReg rdx) instr | signed = IDIV | otherwise = DIV (y_reg, y_code) <- getRegOrMem arg_y x_low_code <- getAnyReg arg_x_low x_high_code <- case m_arg_x_high of Just arg_x_high -> getAnyReg arg_x_high Nothing -> return $ const $ unitOL widen return $ y_code `appOL` x_low_code rax `appOL` x_high_code rdx `appOL` toOL [instr size y_reg, MOV size (OpReg rax) (OpReg reg_q), MOV size (OpReg rdx) (OpReg reg_r)] divOp _ _ _ _ _ _ _ = panic "genCCall64: Wrong number of results for divOp" genCCall64' :: DynFlags -> ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock genCCall64' dflags target dest_regs args = do -- load up the register arguments let prom_args = map (maybePromoteCArg dflags W32) args (stack_args, int_regs_used, fp_regs_used, load_args_code) <- if platformOS platform == OSMinGW32 then load_args_win prom_args [] [] (allArgRegs platform) nilOL else do (stack_args, aregs, fregs, load_args_code) <- load_args prom_args (allIntArgRegs platform) (allFPArgRegs platform) nilOL let fp_regs_used = reverse (drop (length fregs) (reverse (allFPArgRegs platform))) int_regs_used = reverse (drop (length aregs) (reverse (allIntArgRegs platform))) return (stack_args, int_regs_used, fp_regs_used, load_args_code) let arg_regs_used = int_regs_used ++ fp_regs_used arg_regs = [eax] ++ arg_regs_used -- for annotating the call instruction with sse_regs = length fp_regs_used arg_stack_slots = if platformOS platform == OSMinGW32 then length stack_args + length (allArgRegs platform) else length stack_args tot_arg_size = arg_size * arg_stack_slots -- Align stack to 16n for calls, assuming a starting stack -- alignment of 16n - word_size on procedure entry. Which we -- maintain. See Note [rts/StgCRun.c : Stack Alignment on X86] (real_size, adjust_rsp) <- if (tot_arg_size + wORD_SIZE dflags) `rem` 16 == 0 then return (tot_arg_size, nilOL) else do -- we need to adjust... delta <- getDeltaNat setDeltaNat (delta - wORD_SIZE dflags) return (tot_arg_size + wORD_SIZE dflags, toOL [ SUB II64 (OpImm (ImmInt (wORD_SIZE dflags))) (OpReg rsp), DELTA (delta - wORD_SIZE dflags) ]) -- push the stack args, right to left push_code <- push_args (reverse stack_args) nilOL -- On Win64, we also have to leave stack space for the arguments -- that we are passing in registers lss_code <- if platformOS platform == OSMinGW32 then leaveStackSpace (length (allArgRegs platform)) else return nilOL delta <- getDeltaNat -- deal with static vs dynamic call targets (callinsns,_cconv) <- case target of ForeignTarget (CmmLit (CmmLabel lbl)) conv -> -- ToDo: stdcall arg sizes return (unitOL (CALL (Left fn_imm) arg_regs), conv) where fn_imm = ImmCLbl lbl ForeignTarget expr conv -> do (dyn_r, dyn_c) <- getSomeReg expr return (dyn_c `snocOL` CALL (Right dyn_r) arg_regs, conv) PrimTarget _ -> panic $ "genCCall: Can't handle PrimTarget call type here, error " ++ "probably because too many return values." let -- The x86_64 ABI requires us to set %al to the number of SSE2 -- registers that contain arguments, if the called routine -- is a varargs function. We don't know whether it's a -- varargs function or not, so we have to assume it is. -- -- It's not safe to omit this assignment, even if the number -- of SSE2 regs in use is zero. If %al is larger than 8 -- on entry to a varargs function, seg faults ensue. assign_eax n = unitOL (MOV II32 (OpImm (ImmInt n)) (OpReg eax)) let call = callinsns `appOL` toOL ( -- Deallocate parameters after call for ccall; -- stdcall has callee do it, but is not supported on -- x86_64 target (see #3336) (if real_size==0 then [] else [ADD (intSize (wordWidth dflags)) (OpImm (ImmInt real_size)) (OpReg esp)]) ++ [DELTA (delta + real_size)] ) setDeltaNat (delta + real_size) let -- assign the results, if necessary assign_code [] = nilOL assign_code [dest] = case typeWidth rep of W32 | isFloatType rep -> unitOL (MOV (floatSize W32) (OpReg xmm0) (OpReg r_dest)) W64 | isFloatType rep -> unitOL (MOV (floatSize W64) (OpReg xmm0) (OpReg r_dest)) _ -> unitOL (MOV (cmmTypeSize rep) (OpReg rax) (OpReg r_dest)) where rep = localRegType dest r_dest = getRegisterReg platform True (CmmLocal dest) assign_code _many = panic "genCCall.assign_code many" return (load_args_code `appOL` adjust_rsp `appOL` push_code `appOL` lss_code `appOL` assign_eax sse_regs `appOL` call `appOL` assign_code dest_regs) where platform = targetPlatform dflags arg_size = 8 -- always, at the mo load_args :: [CmmExpr] -> [Reg] -- int regs avail for args -> [Reg] -- FP regs avail for args -> InstrBlock -> NatM ([CmmExpr],[Reg],[Reg],InstrBlock) load_args args [] [] code = return (args, [], [], code) -- no more regs to use load_args [] aregs fregs code = return ([], aregs, fregs, code) -- no more args to push load_args (arg : rest) aregs fregs code | isFloatType arg_rep = case fregs of [] -> push_this_arg (r:rs) -> do arg_code <- getAnyReg arg load_args rest aregs rs (code `appOL` arg_code r) | otherwise = case aregs of [] -> push_this_arg (r:rs) -> do arg_code <- getAnyReg arg load_args rest rs fregs (code `appOL` arg_code r) where arg_rep = cmmExprType dflags arg push_this_arg = do (args',ars,frs,code') <- load_args rest aregs fregs code return (arg:args', ars, frs, code') load_args_win :: [CmmExpr] -> [Reg] -- used int regs -> [Reg] -- used FP regs -> [(Reg, Reg)] -- (int, FP) regs avail for args -> InstrBlock -> NatM ([CmmExpr],[Reg],[Reg],InstrBlock) load_args_win args usedInt usedFP [] code = return (args, usedInt, usedFP, code) -- no more regs to use load_args_win [] usedInt usedFP _ code = return ([], usedInt, usedFP, code) -- no more args to push load_args_win (arg : rest) usedInt usedFP ((ireg, freg) : regs) code | isFloatType arg_rep = do arg_code <- getAnyReg arg load_args_win rest (ireg : usedInt) (freg : usedFP) regs (code `appOL` arg_code freg `snocOL` -- If we are calling a varargs function -- then we need to define ireg as well -- as freg MOV II64 (OpReg freg) (OpReg ireg)) | otherwise = do arg_code <- getAnyReg arg load_args_win rest (ireg : usedInt) usedFP regs (code `appOL` arg_code ireg) where arg_rep = cmmExprType dflags arg push_args [] code = return code push_args (arg:rest) code | isFloatType arg_rep = do (arg_reg, arg_code) <- getSomeReg arg delta <- getDeltaNat setDeltaNat (delta-arg_size) let code' = code `appOL` arg_code `appOL` toOL [ SUB (intSize (wordWidth dflags)) (OpImm (ImmInt arg_size)) (OpReg rsp) , DELTA (delta-arg_size), MOV (floatSize width) (OpReg arg_reg) (OpAddr (spRel dflags 0))] push_args rest code' | otherwise = do ASSERT(width == W64) return () (arg_op, arg_code) <- getOperand arg delta <- getDeltaNat setDeltaNat (delta-arg_size) let code' = code `appOL` arg_code `appOL` toOL [ PUSH II64 arg_op, DELTA (delta-arg_size)] push_args rest code' where arg_rep = cmmExprType dflags arg width = typeWidth arg_rep leaveStackSpace n = do delta <- getDeltaNat setDeltaNat (delta - n * arg_size) return $ toOL [ SUB II64 (OpImm (ImmInt (n * wORD_SIZE dflags))) (OpReg rsp), DELTA (delta - n * arg_size)] maybePromoteCArg :: DynFlags -> Width -> CmmExpr -> CmmExpr maybePromoteCArg dflags wto arg | wfrom < wto = CmmMachOp (MO_UU_Conv wfrom wto) [arg] | otherwise = arg where wfrom = cmmExprWidth dflags arg outOfLineCmmOp :: CallishMachOp -> Maybe CmmFormal -> [CmmActual] -> NatM InstrBlock outOfLineCmmOp mop res args = do dflags <- getDynFlags targetExpr <- cmmMakeDynamicReference dflags CallReference lbl let target = ForeignTarget targetExpr (ForeignConvention CCallConv [] [] CmmMayReturn) stmtToInstrs (CmmUnsafeForeignCall target (catMaybes [res]) args') where -- Assume we can call these functions directly, and that they're not in a dynamic library. -- TODO: Why is this ok? Under linux this code will be in libm.so -- Is is because they're really implemented as a primitive instruction by the assembler?? -- BL 2009/12/31 lbl = mkForeignLabel fn Nothing ForeignLabelInThisPackage IsFunction args' = case mop of MO_Memcpy -> init args MO_Memset -> init args MO_Memmove -> init args _ -> args fn = case mop of MO_F32_Sqrt -> fsLit "sqrtf" MO_F32_Sin -> fsLit "sinf" MO_F32_Cos -> fsLit "cosf" MO_F32_Tan -> fsLit "tanf" MO_F32_Exp -> fsLit "expf" MO_F32_Log -> fsLit "logf" MO_F32_Asin -> fsLit "asinf" MO_F32_Acos -> fsLit "acosf" MO_F32_Atan -> fsLit "atanf" MO_F32_Sinh -> fsLit "sinhf" MO_F32_Cosh -> fsLit "coshf" MO_F32_Tanh -> fsLit "tanhf" MO_F32_Pwr -> fsLit "powf" MO_F64_Sqrt -> fsLit "sqrt" MO_F64_Sin -> fsLit "sin" MO_F64_Cos -> fsLit "cos" MO_F64_Tan -> fsLit "tan" MO_F64_Exp -> fsLit "exp" MO_F64_Log -> fsLit "log" MO_F64_Asin -> fsLit "asin" MO_F64_Acos -> fsLit "acos" MO_F64_Atan -> fsLit "atan" MO_F64_Sinh -> fsLit "sinh" MO_F64_Cosh -> fsLit "cosh" MO_F64_Tanh -> fsLit "tanh" MO_F64_Pwr -> fsLit "pow" MO_Memcpy -> fsLit "memcpy" MO_Memset -> fsLit "memset" MO_Memmove -> fsLit "memmove" MO_PopCnt _ -> fsLit "popcnt" MO_BSwap _ -> fsLit "bswap" MO_AtomicRMW _ _ -> fsLit "atomicrmw" MO_AtomicRead _ -> fsLit "atomicread" MO_AtomicWrite _ -> fsLit "atomicwrite" MO_Cmpxchg _ -> fsLit "cmpxchg" MO_UF_Conv _ -> unsupported MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported MO_Add2 {} -> unsupported MO_U_Mul2 {} -> unsupported MO_WriteBarrier -> unsupported MO_Touch -> unsupported (MO_Prefetch_Data _ ) -> unsupported unsupported = panic ("outOfLineCmmOp: " ++ show mop ++ " not supported here") -- ----------------------------------------------------------------------------- -- Generating a table-branch genSwitch :: DynFlags -> CmmExpr -> [Maybe BlockId] -> NatM InstrBlock genSwitch dflags expr ids | gopt Opt_PIC dflags = do (reg,e_code) <- getSomeReg expr lbl <- getNewLabelNat dflags <- getDynFlags dynRef <- cmmMakeDynamicReference dflags DataReference lbl (tableReg,t_code) <- getSomeReg $ dynRef let op = OpAddr (AddrBaseIndex (EABaseReg tableReg) (EAIndex reg (wORD_SIZE dflags)) (ImmInt 0)) return $ if target32Bit (targetPlatform dflags) then e_code `appOL` t_code `appOL` toOL [ ADD (intSize (wordWidth dflags)) op (OpReg tableReg), JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl ] else case platformOS (targetPlatform dflags) of OSDarwin -> -- on Mac OS X/x86_64, put the jump table -- in the text section to work around a -- limitation of the linker. -- ld64 is unable to handle the relocations for -- .quad L1 - L0 -- if L0 is not preceded by a non-anonymous -- label in its section. e_code `appOL` t_code `appOL` toOL [ ADD (intSize (wordWidth dflags)) op (OpReg tableReg), JMP_TBL (OpReg tableReg) ids Text lbl ] _ -> -- HACK: On x86_64 binutils<2.17 is only able -- to generate PC32 relocations, hence we only -- get 32-bit offsets in the jump table. As -- these offsets are always negative we need -- to properly sign extend them to 64-bit. -- This hack should be removed in conjunction -- with the hack in PprMach.hs/pprDataItem -- once binutils 2.17 is standard. e_code `appOL` t_code `appOL` toOL [ MOVSxL II32 op (OpReg reg), ADD (intSize (wordWidth dflags)) (OpReg reg) (OpReg tableReg), JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl ] | otherwise = do (reg,e_code) <- getSomeReg expr lbl <- getNewLabelNat let op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg (wORD_SIZE dflags)) (ImmCLbl lbl)) code = e_code `appOL` toOL [ JMP_TBL op ids ReadOnlyData lbl ] return code generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl (Alignment, CmmStatics) Instr) generateJumpTableForInstr dflags (JMP_TBL _ ids section lbl) = Just (createJumpTable dflags ids section lbl) generateJumpTableForInstr _ _ = Nothing createJumpTable :: DynFlags -> [Maybe BlockId] -> Section -> CLabel -> GenCmmDecl (Alignment, CmmStatics) h g createJumpTable dflags ids section lbl = let jumpTable | gopt Opt_PIC dflags = let jumpTableEntryRel Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags)) jumpTableEntryRel (Just blockid) = CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0) where blockLabel = mkAsmTempLabel (getUnique blockid) in map jumpTableEntryRel ids | otherwise = map (jumpTableEntry dflags) ids in CmmData section (1, Statics lbl jumpTable) -- ----------------------------------------------------------------------------- -- 'condIntReg' and 'condFltReg': condition codes into registers -- Turn those condition codes into integers now (when they appear on -- the right hand side of an assignment). -- -- (If applicable) Do not fill the delay slots here; you will confuse the -- register allocator. condIntReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register condIntReg cond x y = do CondCode _ cond cond_code <- condIntCode cond x y tmp <- getNewRegNat II8 let code dst = cond_code `appOL` toOL [ SETCC cond (OpReg tmp), MOVZxL II8 (OpReg tmp) (OpReg dst) ] return (Any II32 code) condFltReg :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM Register condFltReg is32Bit cond x y = if_sse2 condFltReg_sse2 condFltReg_x87 where condFltReg_x87 = do CondCode _ cond cond_code <- condFltCode cond x y tmp <- getNewRegNat II8 let code dst = cond_code `appOL` toOL [ SETCC cond (OpReg tmp), MOVZxL II8 (OpReg tmp) (OpReg dst) ] return (Any II32 code) condFltReg_sse2 = do CondCode _ cond cond_code <- condFltCode cond x y tmp1 <- getNewRegNat (archWordSize is32Bit) tmp2 <- getNewRegNat (archWordSize is32Bit) let -- We have to worry about unordered operands (eg. comparisons -- against NaN). If the operands are unordered, the comparison -- sets the parity flag, carry flag and zero flag. -- All comparisons are supposed to return false for unordered -- operands except for !=, which returns true. -- -- Optimisation: we don't have to test the parity flag if we -- know the test has already excluded the unordered case: eg > -- and >= test for a zero carry flag, which can only occur for -- ordered operands. -- -- ToDo: by reversing comparisons we could avoid testing the -- parity flag in more cases. code dst = cond_code `appOL` (case cond of NE -> or_unordered dst GU -> plain_test dst GEU -> plain_test dst _ -> and_ordered dst) plain_test dst = toOL [ SETCC cond (OpReg tmp1), MOVZxL II8 (OpReg tmp1) (OpReg dst) ] or_unordered dst = toOL [ SETCC cond (OpReg tmp1), SETCC PARITY (OpReg tmp2), OR II8 (OpReg tmp1) (OpReg tmp2), MOVZxL II8 (OpReg tmp2) (OpReg dst) ] and_ordered dst = toOL [ SETCC cond (OpReg tmp1), SETCC NOTPARITY (OpReg tmp2), AND II8 (OpReg tmp1) (OpReg tmp2), MOVZxL II8 (OpReg tmp2) (OpReg dst) ] return (Any II32 code) -- ----------------------------------------------------------------------------- -- '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. {- The Rules of the Game are: * You cannot assume anything about the destination register dst; it may be anything, including a fixed reg. * You may compute an operand into a fixed reg, but you may not subsequently change the contents of that fixed reg. If you want to do so, first copy the value either to a temporary or into dst. You are free to modify dst even if it happens to be a fixed reg -- that's not your problem. * You cannot assume that a fixed reg will stay live over an arbitrary computation. The same applies to the dst reg. * Temporary regs obtained from getNewRegNat are distinct from each other and from all other regs, and stay live over arbitrary computations. -------------------- SDM's version of The Rules: * If getRegister returns Any, that means it can generate correct code which places the result in any register, period. Even if that register happens to be read during the computation. Corollary #1: this means that if you are generating code for an operation with two arbitrary operands, you cannot assign the result of the first operand into the destination register before computing the second operand. The second operand might require the old value of the destination register. Corollary #2: A function might be able to generate more efficient code if it knows the destination register is a new temporary (and therefore not read by any of the sub-computations). * If getRegister returns Any, then the code it generates may modify only: (a) fresh temporaries (b) the destination register (c) known registers (eg. %ecx is used by shifts) In particular, it may *not* modify global registers, unless the global register happens to be the destination register. -} trivialCode :: Width -> (Operand -> Operand -> Instr) -> Maybe (Operand -> Operand -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCode width instr m a b = do is32Bit <- is32BitPlatform trivialCode' is32Bit width instr m a b trivialCode' :: Bool -> Width -> (Operand -> Operand -> Instr) -> Maybe (Operand -> Operand -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCode' is32Bit width _ (Just revinstr) (CmmLit lit_a) b | is32BitLit is32Bit lit_a = do b_code <- getAnyReg b let code dst = b_code dst `snocOL` revinstr (OpImm (litToImm lit_a)) (OpReg dst) return (Any (intSize width) code) trivialCode' _ width instr _ a b = genTrivialCode (intSize width) instr a b -- This is re-used for floating pt instructions too. genTrivialCode :: Size -> (Operand -> Operand -> Instr) -> CmmExpr -> CmmExpr -> NatM Register genTrivialCode rep instr a b = do (b_op, b_code) <- getNonClobberedOperand b a_code <- getAnyReg a tmp <- getNewRegNat rep let -- We want the value of b to stay alive across the computation of a. -- But, we want to calculate a straight into the destination register, -- because the instruction only has two operands (dst := dst `op` src). -- The troublesome case is when the result of b is in the same register -- as the destination reg. In this case, we have to save b in a -- new temporary across the computation of a. code dst | dst `regClashesWithOp` b_op = b_code `appOL` unitOL (MOV rep b_op (OpReg tmp)) `appOL` a_code dst `snocOL` instr (OpReg tmp) (OpReg dst) | otherwise = b_code `appOL` a_code dst `snocOL` instr b_op (OpReg dst) return (Any rep code) regClashesWithOp :: Reg -> Operand -> Bool reg `regClashesWithOp` OpReg reg2 = reg == reg2 reg `regClashesWithOp` OpAddr amode = any (==reg) (addrModeRegs amode) _ `regClashesWithOp` _ = False ----------- trivialUCode :: Size -> (Operand -> Instr) -> CmmExpr -> NatM Register trivialUCode rep instr x = do x_code <- getAnyReg x let code dst = x_code dst `snocOL` instr (OpReg dst) return (Any rep code) ----------- trivialFCode_x87 :: (Size -> Reg -> Reg -> Reg -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialFCode_x87 instr x y = do (x_reg, x_code) <- getNonClobberedReg x -- these work for float regs too (y_reg, y_code) <- getSomeReg y let size = FF80 -- always, on x87 code dst = x_code `appOL` y_code `snocOL` instr size x_reg y_reg dst return (Any size code) trivialFCode_sse2 :: Width -> (Size -> Operand -> Operand -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialFCode_sse2 pk instr x y = genTrivialCode size (instr size) x y where size = floatSize pk trivialUFCode :: Size -> (Reg -> Reg -> Instr) -> CmmExpr -> NatM Register trivialUFCode size instr x = do (x_reg, x_code) <- getSomeReg x let code dst = x_code `snocOL` instr x_reg dst return (Any size code) -------------------------------------------------------------------------------- coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register coerceInt2FP from to x = if_sse2 coerce_sse2 coerce_x87 where coerce_x87 = do (x_reg, x_code) <- getSomeReg x let opc = case to of W32 -> GITOF; W64 -> GITOD; n -> panic $ "coerceInt2FP.x87: unhandled width (" ++ show n ++ ")" code dst = x_code `snocOL` opc x_reg dst -- ToDo: works for non-II32 reps? return (Any FF80 code) coerce_sse2 = do (x_op, x_code) <- getOperand x -- ToDo: could be a safe operand let opc = case to of W32 -> CVTSI2SS; W64 -> CVTSI2SD n -> panic $ "coerceInt2FP.sse: unhandled width (" ++ show n ++ ")" code dst = x_code `snocOL` opc (intSize from) x_op dst return (Any (floatSize to) code) -- works even if the destination rep is <II32 -------------------------------------------------------------------------------- coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register coerceFP2Int from to x = if_sse2 coerceFP2Int_sse2 coerceFP2Int_x87 where coerceFP2Int_x87 = do (x_reg, x_code) <- getSomeReg x let opc = case from of W32 -> GFTOI; W64 -> GDTOI n -> panic $ "coerceFP2Int.x87: unhandled width (" ++ show n ++ ")" code dst = x_code `snocOL` opc x_reg dst -- ToDo: works for non-II32 reps? return (Any (intSize to) code) coerceFP2Int_sse2 = do (x_op, x_code) <- getOperand x -- ToDo: could be a safe operand let opc = case from of W32 -> CVTTSS2SIQ; W64 -> CVTTSD2SIQ; n -> panic $ "coerceFP2Init.sse: unhandled width (" ++ show n ++ ")" code dst = x_code `snocOL` opc (intSize to) x_op dst return (Any (intSize to) code) -- works even if the destination rep is <II32 -------------------------------------------------------------------------------- coerceFP2FP :: Width -> CmmExpr -> NatM Register coerceFP2FP to x = do use_sse2 <- sse2Enabled (x_reg, x_code) <- getSomeReg x let opc | use_sse2 = case to of W32 -> CVTSD2SS; W64 -> CVTSS2SD; n -> panic $ "coerceFP2FP: unhandled width (" ++ show n ++ ")" | otherwise = GDTOF code dst = x_code `snocOL` opc x_reg dst return (Any (if use_sse2 then floatSize to else FF80) code) -------------------------------------------------------------------------------- sse2NegCode :: Width -> CmmExpr -> NatM Register sse2NegCode w x = do let sz = floatSize w x_code <- getAnyReg x -- This is how gcc does it, so it can't be that bad: let const | FF32 <- sz = CmmInt 0x80000000 W32 | otherwise = CmmInt 0x8000000000000000 W64 Amode amode amode_code <- memConstant (widthInBytes w) const tmp <- getNewRegNat sz let code dst = x_code dst `appOL` amode_code `appOL` toOL [ MOV sz (OpAddr amode) (OpReg tmp), XOR sz (OpReg tmp) (OpReg dst) ] -- return (Any sz code) isVecExpr :: CmmExpr -> Bool isVecExpr (CmmMachOp (MO_V_Insert {}) _) = True isVecExpr (CmmMachOp (MO_V_Extract {}) _) = True isVecExpr (CmmMachOp (MO_V_Add {}) _) = True isVecExpr (CmmMachOp (MO_V_Sub {}) _) = True isVecExpr (CmmMachOp (MO_V_Mul {}) _) = True isVecExpr (CmmMachOp (MO_VS_Quot {}) _) = True isVecExpr (CmmMachOp (MO_VS_Rem {}) _) = True isVecExpr (CmmMachOp (MO_VS_Neg {}) _) = True isVecExpr (CmmMachOp (MO_VF_Insert {}) _) = True isVecExpr (CmmMachOp (MO_VF_Extract {}) _) = True isVecExpr (CmmMachOp (MO_VF_Add {}) _) = True isVecExpr (CmmMachOp (MO_VF_Sub {}) _) = True isVecExpr (CmmMachOp (MO_VF_Mul {}) _) = True isVecExpr (CmmMachOp (MO_VF_Quot {}) _) = True isVecExpr (CmmMachOp (MO_VF_Neg {}) _) = True isVecExpr (CmmMachOp _ [e]) = isVecExpr e isVecExpr _ = False needLlvm :: NatM a needLlvm = sorry $ unlines ["The native code generator does not support vector" ,"instructions. Please use -fllvm."]
lukexi/ghc
compiler/nativeGen/X86/CodeGen.hs
bsd-3-clause
113,982
0
23
38,143
29,903
14,731
15,172
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GLU.NURBS -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- This module corresponds to chapter 7 (NURBS) of the GLU specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GLU.NURBS ( NURBSObj, withNURBSObj, NURBSBeginCallback, withNURBSBeginCallback, NURBSVertexCallback, withNURBSVertexCallback, NURBSNormalCallback, withNURBSNormalCallback, NURBSColorCallback, withNURBSColorCallback, NURBSEndCallback, withNURBSEndCallback, checkForNURBSError, nurbsBeginEndCurve, nurbsCurve, nurbsBeginEndSurface, nurbsSurface, TrimmingPoint, nurbsBeginEndTrim, pwlCurve, trimmingCurve, NURBSMode(..), setNURBSMode, setNURBSCulling, SamplingMethod(..), setSamplingMethod, loadSamplingMatrices, DisplayMode'(..), setDisplayMode' ) where import Control.Monad import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import Graphics.Rendering.GLU.Raw hiding ( NURBSBeginCallback, NURBSVertexCallback, NURBSNormalCallback, NURBSColorCallback, NURBSEndCallback ) import Graphics.Rendering.OpenGL.GL.Tensor import Graphics.Rendering.OpenGL.GL.Capability import Graphics.Rendering.OpenGL.GL.ControlPoint import Graphics.Rendering.OpenGL.GL.CoordTrans import Graphics.Rendering.OpenGL.GL.Exception import Graphics.Rendering.OpenGL.GL.GLboolean import Graphics.Rendering.OpenGL.GL.PrimitiveMode import Graphics.Rendering.OpenGL.GL.PrimitiveModeInternal import Graphics.Rendering.OpenGL.GL.VertexSpec import Graphics.Rendering.OpenGL.GLU.ErrorsInternal import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- -- chapter 7.1: The NURBS Object -- an opaque pointer to a NURBS object type NURBSObj = Ptr GLUnurbs isNullNURBSObj :: NURBSObj -> Bool isNullNURBSObj = (nullPtr ==) withNURBSObj :: a -> (NURBSObj -> IO a) -> IO a withNURBSObj failureValue action = bracket gluNewNurbsRenderer safeDeleteNurbsRenderer (\nurbsObj -> if isNullNURBSObj nurbsObj then do recordOutOfMemory return failureValue else action nurbsObj) safeDeleteNurbsRenderer :: NURBSObj -> IO () safeDeleteNurbsRenderer nurbsObj = unless (isNullNURBSObj nurbsObj) $ gluDeleteNurbsRenderer nurbsObj -------------------------------------------------------------------------------- -- chapter 7.2: Callbacks (begin) type NURBSBeginCallback = PrimitiveMode -> IO () withNURBSBeginCallback :: NURBSObj -> NURBSBeginCallback -> IO a -> IO a withNURBSBeginCallback nurbsObj beginCallback action = bracket (makeNURBSBeginCallback (beginCallback . unmarshalPrimitiveMode)) freeHaskellFunPtr $ \callbackPtr -> do gluNurbsCallback nurbsObj glu_NURBS_BEGIN callbackPtr action -------------------------------------------------------------------------------- -- chapter 7.2: Callbacks (vertex) type NURBSVertexCallback = Vertex3 GLfloat -> IO () withNURBSVertexCallback :: NURBSObj -> NURBSVertexCallback -> IO a -> IO a withNURBSVertexCallback nurbsObj vertexCallback action = bracket (makeNURBSVertexCallback (\p -> peek (castPtr p) >>= vertexCallback)) freeHaskellFunPtr $ \callbackPtr -> do gluNurbsCallback nurbsObj glu_NURBS_VERTEX callbackPtr action -------------------------------------------------------------------------------- -- chapter 7.2: Callbacks (normal) type NURBSNormalCallback = Normal3 GLfloat -> IO () withNURBSNormalCallback :: NURBSObj -> NURBSNormalCallback -> IO a -> IO a withNURBSNormalCallback nurbsObj normalCallback action = bracket (makeNURBSNormalCallback (\p -> peek (castPtr p) >>= normalCallback)) freeHaskellFunPtr $ \callbackPtr -> do gluNurbsCallback nurbsObj glu_NURBS_NORMAL callbackPtr action -------------------------------------------------------------------------------- -- chapter 7.2: Callbacks (color) type NURBSColorCallback = Color4 GLfloat -> IO () withNURBSColorCallback :: NURBSObj -> NURBSColorCallback -> IO a -> IO a withNURBSColorCallback nurbsObj colorCallback action = bracket (makeNURBSColorCallback (\p -> peek (castPtr p) >>= colorCallback)) freeHaskellFunPtr $ \callbackPtr -> do gluNurbsCallback nurbsObj glu_NURBS_COLOR callbackPtr action -------------------------------------------------------------------------------- -- chapter 7.2: Callbacks (end) type NURBSEndCallback = IO () withNURBSEndCallback :: NURBSObj -> NURBSEndCallback -> IO a -> IO a withNURBSEndCallback nurbsObj endCallback action = bracket (makeNURBSEndCallback endCallback) freeHaskellFunPtr $ \callbackPtr -> do gluNurbsCallback nurbsObj glu_NURBS_END callbackPtr action -------------------------------------------------------------------------------- -- chapter 7.2: Callbacks (error) type ErrorCallback = GLenum -> IO () withErrorCallback :: NURBSObj -> ErrorCallback -> IO a -> IO a withErrorCallback nurbsObj errorCallback action = bracket (makeNURBSErrorCallback errorCallback) freeHaskellFunPtr $ \callbackPtr -> do gluNurbsCallback nurbsObj glu_NURBS_ERROR callbackPtr action checkForNURBSError :: NURBSObj -> IO a -> IO a checkForNURBSError nurbsObj = withErrorCallback nurbsObj recordErrorCode -------------------------------------------------------------------------------- -- chapter 7.3: NURBS Curves nurbsBeginEndCurve :: NURBSObj -> IO a -> IO a nurbsBeginEndCurve nurbsObj = bracket_ (gluBeginCurve nurbsObj) (gluEndCurve nurbsObj) nurbsCurve :: ControlPoint c => NURBSObj -> GLint -> Ptr GLfloat -> GLint -> Ptr (c GLfloat) -> GLint -> IO () nurbsCurve nurbsObj knotCount knots stride control order = gluNurbsCurve nurbsObj knotCount knots stride (castPtr control) order (map1Target (pseudoPeek control)) pseudoPeek :: Ptr (c GLfloat) -> c GLfloat pseudoPeek _ = undefined -------------------------------------------------------------------------------- -- chapter 7.4: NURBS Surfaces nurbsBeginEndSurface :: NURBSObj -> IO a -> IO a nurbsBeginEndSurface nurbsObj = bracket_ (gluBeginSurface nurbsObj) (gluEndSurface nurbsObj) nurbsSurface :: ControlPoint c => NURBSObj -> GLint -> Ptr GLfloat -> GLint -> Ptr GLfloat -> GLint -> GLint -> Ptr (c GLfloat) -> GLint -> GLint -> IO () nurbsSurface nurbsObj sKnotCount sKnots tKnotCount tKnots sStride tStride control sOrder tOrder = gluNurbsSurface nurbsObj sKnotCount sKnots tKnotCount tKnots sStride tStride (castPtr control) sOrder tOrder (map2Target (pseudoPeek control)) -------------------------------------------------------------------------------- -- chapter 7.5: Trimming class TrimmingPoint p where trimmingTarget :: p GLfloat -> GLenum instance TrimmingPoint Vertex2 where trimmingTarget = const glu_MAP1_TRIM_2 instance TrimmingPoint Vertex3 where trimmingTarget = const glu_MAP1_TRIM_3 nurbsBeginEndTrim :: NURBSObj -> IO a -> IO a nurbsBeginEndTrim nurbsObj = bracket_ (gluBeginTrim nurbsObj) (gluEndTrim nurbsObj) pwlCurve :: TrimmingPoint p => NURBSObj -> GLint -> Ptr (p GLfloat) -> GLint -> IO () pwlCurve nurbsObj count points stride = gluPwlCurve nurbsObj count (castPtr points) stride (trimmingTarget (pseudoPeek points)) trimmingCurve :: TrimmingPoint c => NURBSObj -> GLint -> Ptr GLfloat -> GLint -> Ptr (c GLfloat) -> GLint -> IO () trimmingCurve nurbsObj knotCount knots stride control order = gluNurbsCurve nurbsObj knotCount knots stride (castPtr control) order (trimmingTarget (pseudoPeek control)) -------------------------------------------------------------------------------- data NURBSMode = NURBSTessellator | NURBSRenderer deriving ( Eq, Ord, Show ) marshalNURBSMode :: NURBSMode -> GLfloat marshalNURBSMode x = fromIntegral $ case x of NURBSTessellator -> glu_NURBS_TESSELLATOR NURBSRenderer -> glu_NURBS_RENDERER setNURBSMode :: NURBSObj -> NURBSMode -> IO () setNURBSMode nurbsObj = gluNurbsProperty nurbsObj glu_NURBS_MODE . marshalNURBSMode -------------------------------------------------------------------------------- setNURBSCulling :: NURBSObj -> Capability -> IO () setNURBSCulling nurbsObj = gluNurbsProperty nurbsObj glu_CULLING . fromIntegral . marshalCapability -------------------------------------------------------------------------------- data SamplingMethod' = PathLength' | ParametricError' | DomainDistance' | ObjectPathLength' | ObjectParametricError' marshalSamplingMethod' :: SamplingMethod' -> GLfloat marshalSamplingMethod' x = fromIntegral $ case x of PathLength' -> glu_PATH_LENGTH ParametricError' -> glu_PARAMETRIC_TOLERANCE DomainDistance' -> glu_DOMAIN_DISTANCE ObjectPathLength' -> glu_OBJECT_PATH_LENGTH ObjectParametricError' -> glu_OBJECT_PARAMETRIC_ERROR setSamplingMethod' :: NURBSObj -> SamplingMethod' -> IO () setSamplingMethod' nurbsObj = gluNurbsProperty nurbsObj glu_SAMPLING_METHOD . marshalSamplingMethod' -------------------------------------------------------------------------------- data SamplingMethod = PathLength GLfloat | ParametricError GLfloat | DomainDistance GLfloat GLfloat | ObjectPathLength GLfloat | ObjectParametricError GLfloat deriving ( Eq, Ord, Show ) setSamplingMethod :: NURBSObj -> SamplingMethod -> IO () setSamplingMethod nurbsObj x = case x of PathLength s -> do gluNurbsProperty nurbsObj glu_SAMPLING_TOLERANCE s setSamplingMethod' nurbsObj PathLength' ParametricError p -> do gluNurbsProperty nurbsObj glu_PARAMETRIC_TOLERANCE p setSamplingMethod' nurbsObj ParametricError' DomainDistance u v -> do gluNurbsProperty nurbsObj glu_U_STEP u gluNurbsProperty nurbsObj glu_V_STEP v setSamplingMethod' nurbsObj DomainDistance' ObjectPathLength s -> do gluNurbsProperty nurbsObj glu_SAMPLING_TOLERANCE s setSamplingMethod' nurbsObj ObjectPathLength' ObjectParametricError p -> do gluNurbsProperty nurbsObj glu_PARAMETRIC_TOLERANCE p setSamplingMethod' nurbsObj ObjectParametricError' -------------------------------------------------------------------------------- setAutoLoadMatrix :: NURBSObj -> Bool -> IO () setAutoLoadMatrix nurbsObj = gluNurbsProperty nurbsObj glu_AUTO_LOAD_MATRIX . marshalGLboolean loadSamplingMatrices :: (Matrix m1, Matrix m2) => NURBSObj -> Maybe (m1 GLfloat, m2 GLfloat, (Position, Size)) -> IO () loadSamplingMatrices nurbsObj = maybe (setAutoLoadMatrix nurbsObj True) (\(mv, proj, (Position x y, Size w h)) -> do withMatrixColumnMajor mv $ \mvBuf -> withMatrixColumnMajor proj $ \projBuf -> withArray [x, y, fromIntegral w, fromIntegral h] $ \viewportBuf -> gluLoadSamplingMatrices nurbsObj mvBuf projBuf viewportBuf setAutoLoadMatrix nurbsObj False) withMatrixColumnMajor :: (Matrix m, MatrixComponent c) => m c -> (Ptr c -> IO a) -> IO a withMatrixColumnMajor mat act = withMatrix mat $ \order p -> if order == ColumnMajor then act p else do elems <- mapM (peekElemOff p) [ 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 ] withArray elems act -------------------------------------------------------------------------------- data DisplayMode' = Fill' | OutlinePolygon | OutlinePatch deriving ( Eq, Ord, Show ) marshalDisplayMode' :: DisplayMode' -> GLfloat marshalDisplayMode' x = fromIntegral $ case x of Fill' -> glu_FILL OutlinePolygon -> glu_OUTLINE_POLYGON OutlinePatch -> glu_OUTLINE_PATCH setDisplayMode' :: NURBSObj -> DisplayMode' -> IO () setDisplayMode' nurbsObj = gluNurbsProperty nurbsObj glu_DISPLAY_MODE . marshalDisplayMode'
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GLU/NURBS.hs
bsd-3-clause
12,171
0
17
2,053
2,629
1,365
1,264
207
5
{-# LANGUAGE FlexibleContexts #-} import Plots import Plots.Axis import Plots.Types hiding (B) import Plots.Themes import Data.List import Diagrams.Prelude import Diagrams.Backend.Rasterific import Diagrams.Backend.CmdLine import Data.Monoid.Recommend myaxis :: Axis B V2 Double myaxis = r2Axis &~ do vectorFieldPlot (map vectorField loc1) loc1 arrowOpts vectorFieldPlot (map vectorField2 loc1) loc1 arrowOpts2 yMin .= Commit 0 point1 = (0.2, 0.2) vector1 = r2 (0.2, 0.2) loc1 = [(x, y) | x <- [0.5,0.7 .. 4.3], y <- [0.5,0.7 .. 4.3]] vectorField (x, y) = r2 ((sin y)/4, (sin (x+1))/4) vectorField2 (x, y) = r2 ((cos y)/4, (cos (x+1))/4) arrowOpts = ( with & arrowHead .~ tri & headLength .~ global 5 & headTexture .~ solid blue) arrowOpts2 = ( with & arrowHead .~ tri & headLength .~ global 5 & headTexture .~ solid red) make :: Diagram B -> IO () make = renderRasterific "test.png" (mkWidth 600) . frame 20 main :: IO () main = make $ renderAxis myaxis
bergey/plots
examples/vectorfield.hs
bsd-3-clause
986
2
11
186
443
232
211
26
1
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Network/HPACK/Huffman.hs" #-} module Network.HPACK.Huffman ( -- * Type HuffmanEncoding , HuffmanDecoding -- * Encoding/decoding , encode , encodeHuffman , decode , decodeHuffman ) where import Network.HPACK.Huffman.Decode import Network.HPACK.Huffman.Encode
phischu/fragnix
tests/packages/scotty/Network.HPACK.Huffman.hs
bsd-3-clause
320
0
4
56
45
32
13
11
0
{-| Module : Idris.Elab.Instance Description : Code to elaborate instances. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} module Idris.Elab.Instance(elabInstance) where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Type import Idris.Elab.Data import Idris.Elab.Utils import Idris.Elab.Term import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Util.Pretty(pretty, text) elabInstance :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) -> [(Name, Docstring (Either Err PTerm))] -> ElabWhat -- ^ phase -> FC -> [(Name, PTerm)] -- ^ constraints -> [Name] -- ^ parent dictionary names (optionally) -> Accessibility -> FnOpts -> Name -- ^ the class -> FC -- ^ precise location of class name -> [PTerm] -- ^ class parameters (i.e. instance) -> [(Name, PTerm)] -- ^ Extra arguments in scope (e.g. instance in where block) -> PTerm -- ^ full instance type -> Maybe Name -- ^ explicit name -> [PDecl] -> Idris () elabInstance info syn doc argDocs what fc cs parents acc opts n nfc ps pextra t expn ds = do ist <- getIState (n, ci) <- case lookupCtxtName n (idris_classes ist) of [c] -> return c [] -> ifail $ show fc ++ ":" ++ show n ++ " is not an interface" cs -> tclift $ tfail $ At fc (CantResolveAlts (map fst cs)) let constraint = PApp fc (PRef fc [] n) (map pexp ps) let iname = mkiname n (namespace info) ps expn putIState (ist { hide_list = addDef iname acc (hide_list ist) }) ist <- getIState let totopts = Dictionary : Inlinable : opts let emptyclass = null (class_methods ci) when (what /= EDefns) $ do nty <- elabType' True info syn doc argDocs fc totopts iname NoFC (piBindp expl_param pextra t) -- if the instance type matches any of the instances we have already, -- and it's not a named instance, then it's overlapping, so report an error case expn of Nothing -> do mapM_ (maybe (return ()) overlapping . findOverlapping ist (class_determiners ci) (delab ist nty)) (map fst $ class_instances ci) addInstance intInst True n iname Just _ -> addInstance intInst False n iname when (what /= ETypes && (not (null ds && not emptyclass))) $ do -- Add the parent implementation names to the privileged set oldOpen <- addOpenImpl parents let ips = zip (class_params ci) ps let ns = case n of NS n ns' -> ns' _ -> [] -- get the implicit parameters that need passing through to the -- where block wparams <- mapM (\p -> case p of PApp _ _ args -> getWParams (map getTm args) a@(PRef fc _ f) -> getWParams [a] _ -> return []) ps ist <- getIState let pnames = nub $ map pname (concat (nub wparams)) ++ concatMap (namesIn [] ist) ps let superclassInstances = map (substInstance ips pnames) (class_default_superclasses ci) undefinedSuperclassInstances <- filterM (fmap not . isOverlapping ist) superclassInstances mapM_ (rec_elabDecl info EAll info) undefinedSuperclassInstances ist <- getIState -- Bring variables in instance head into scope when building the -- dictionary let headVars = nub $ concatMap getHeadVars ps let (headVarTypes, ty) = case lookupTyExact iname (tt_ctxt ist) of Just ty -> (map (\n -> (n, getTypeIn ist n ty)) headVars, ty) _ -> (zip headVars (repeat Placeholder), Erased) logElab 3 $ "Head var types " ++ show headVarTypes ++ " from " ++ show ty let all_meths = map (nsroot . fst) (class_methods ci) let mtys = map (\ (n, (inj, op, t)) -> let t_in = substMatchesShadow ips pnames t mnamemap = map (\n -> (n, PApp fc (PRef fc [] (decorate ns iname n)) (map (toImp fc) headVars))) all_meths t' = substMatchesShadow mnamemap pnames t_in in (decorate ns iname n, op, coninsert cs pextra t', t')) (class_methods ci) logElab 3 (show (mtys, ips)) logElab 5 ("Before defaults: " ++ show ds ++ "\n" ++ show (map fst (class_methods ci))) let ds_defs = insertDefaults ist iname (class_defaults ci) ns ds logElab 3 ("After defaults: " ++ show ds_defs ++ "\n") let ds' = reorderDefs (map fst (class_methods ci)) ds_defs logElab 1 ("Reordered: " ++ show ds' ++ "\n") mapM_ (warnMissing ds' ns iname) (map fst (class_methods ci)) mapM_ (checkInClass (map fst (class_methods ci))) (concatMap defined ds') let wbTys = map mkTyDecl mtys let wbVals_orig = map (decorateid (decorate ns iname)) ds' ist <- getIState let wbVals = map (expandParamsD False ist id pextra (map methName mtys)) wbVals_orig let wb = wbTys ++ wbVals logElab 3 $ "Method types " ++ showSep "\n" (map (show . showDeclImp verbosePPOption . mkTyDecl) mtys) logElab 3 $ "Instance is " ++ show ps ++ " implicits " ++ show (concat (nub wparams)) let lhsImps = map (\n -> pimp n (PRef fc [] n) True) headVars let lhs = PApp fc (PRef fc [] iname) (lhsImps ++ map (toExp .fst) pextra) let rhs = PApp fc (PRef fc [] (instanceCtorName ci)) (map (pexp . (mkMethApp lhsImps)) mtys) logElab 5 $ "Instance LHS " ++ show totopts ++ "\n" ++ showTmImpls lhs ++ " " ++ show headVars logElab 5 $ "Instance RHS " ++ show rhs push_estack iname True logElab 3 ("Method types: " ++ show wbTys) logElab 3 ("Method bodies (before params): " ++ show wbVals_orig) logElab 3 ("Method bodies: " ++ show wbVals) let idecls = [PClauses fc totopts iname [PClause fc iname lhs [] rhs []]] mapM_ (rec_elabDecl info EAll info) (map (impBind headVarTypes) wbTys) mapM_ (rec_elabDecl info EAll info) idecls ctxt <- getContext let ifn_ty = case lookupTyExact iname ctxt of Just t -> t Nothing -> error "Can't happen (interface constructor)" let ifn_is = case lookupCtxtExact iname (idris_implicits ist) of Just t -> t Nothing -> [] let prop_params = getParamsInType ist [] ifn_is ifn_ty logElab 3 $ "Propagating parameters to methods: " ++ show (iname, prop_params) let wbVals' = map (addParams prop_params) wbVals mapM_ (rec_elabDecl info EAll info) wbVals' mapM_ (checkInjectiveDef fc (class_methods ci)) (zip ds' wbVals') pop_estack setOpenImpl oldOpen -- totalityCheckBlock checkInjectiveArgs fc n (class_determiners ci) (lookupTyExact iname (tt_ctxt ist)) addIBC (IBCInstance intInst (isNothing expn) n iname) where intInst = case ps of [PConstant NoFC (AType (ATInt ITNative))] -> True _ -> False mkiname n' ns ps' expn' = case expn' of Nothing -> case ns of [] -> SN (sInstanceN n' (map show ps')) m -> sNS (SN (sInstanceN n' (map show ps'))) m Just nm -> nm substInstance ips pnames (PInstance doc argDocs syn _ cs parents acc opts n nfc ps pextra t expn ds) = PInstance doc argDocs syn fc cs parents acc opts n nfc (map (substMatchesShadow ips pnames) ps) pextra (substMatchesShadow ips pnames t) expn ds isOverlapping i (PInstance doc argDocs syn _ _ _ _ _ n nfc ps pextra t expn _) = case lookupCtxtName n (idris_classes i) of [(n, ci)] -> let iname = (mkiname n (namespace info) ps expn) in case lookupTy iname (tt_ctxt i) of [] -> elabFindOverlapping i ci iname syn t (_:_) -> return True _ -> return False -- couldn't find class, just let elabInstance fail later -- TODO: largely based upon elabType' - should try to abstract -- Issue #1614 in the issue tracker: -- https://github.com/idris-lang/Idris-dev/issues/1614 elabFindOverlapping i ci iname syn t = do ty' <- addUsingConstraints syn fc t -- TODO think: something more in info? ty' <- implicit info syn iname ty' let ty = addImpl [] i ty' ctxt <- getContext (ElabResult tyT _ _ ctxt' newDecls highlights newGName, _) <- tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) iname (TType (UVal 0)) initEState (errAt "type of " iname Nothing (erun fc (build i info ERHS [] iname ty))) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights updateIState $ \i -> i { idris_name = newGName } ctxt <- getContext (cty, _) <- recheckC (constraintNS info) fc id [] tyT let nty = normalise ctxt [] cty return $ any (isJust . findOverlapping i (class_determiners ci) (delab i nty)) (map fst $ class_instances ci) findOverlapping i dets t n | SN (ParentN _ _) <- n = Nothing | otherwise = case lookupTy n (tt_ctxt i) of [t'] -> let tret = getRetType t tret' = getRetType (delab i t') in case matchArgs i dets tret' tret of Right _ -> Just tret' Left _ -> case matchArgs i dets tret tret' of Right _ -> Just tret' Left _ -> Nothing _ -> Nothing overlapping t' = tclift $ tfail (At fc (Msg $ "Overlapping implementation: " ++ show t' ++ " already defined")) getRetType (PPi _ _ _ _ sc) = getRetType sc getRetType t = t matchArgs i dets x y = let x' = keepDets dets x y' = keepDets dets y in matchClause i x' y' keepDets dets (PApp fc f args) = PApp fc f $ let a' = zip [0..] args in map snd (filter (\(i, _) -> i `elem` dets) a') keepDets dets t = t methName (n, _, _, _) = n toExp n = pexp (PRef fc [] n) mkMethApp ps (n, _, _, ty) = lamBind 0 ty (papp fc (PRef fc [] n) (ps ++ map (toExp . fst) pextra ++ methArgs 0 ty)) where needed is p = pname p `elem` map pname is lamBind i (PPi (Constraint _ _) _ _ _ sc) sc' = PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc') lamBind i (PPi _ n _ ty sc) sc' = PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc') lamBind i _ sc = sc methArgs i (PPi (Imp _ _ _ _ _) n _ ty sc) = PImp 0 True [] n (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc methArgs i (PPi (Exp _ _ _) n _ ty sc) = PExp 0 [] (sMN 0 "marg") (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc methArgs i (PPi (Constraint _ _) n _ ty sc) = PConstraint 0 [] (sMN 0 "marg") (PResolveTC fc) : methArgs (i+1) sc methArgs i _ = [] papp fc f [] = f papp fc f as = PApp fc f as getWParams [] = return [] getWParams (p : ps) | PRef _ _ n <- p = do ps' <- getWParams ps ctxt <- getContext case lookupP n ctxt of [] -> return (pimp n (PRef fc [] n) True : ps') _ -> return ps' getWParams (_ : ps) = getWParams ps decorate ns iname (NS (UN nm) s) = NS (SN (WhereN 0 iname (SN (MethodN (UN nm))))) ns decorate ns iname nm = NS (SN (WhereN 0 iname (SN (MethodN nm)))) ns mkTyDecl (n, op, t, _) = PTy emptyDocstring [] syn fc op n NoFC (mkUniqueNames [] [] t) conbind :: [(Name, PTerm)] -> PTerm -> PTerm conbind ((c,ty) : ns) x = PPi constraint c NoFC ty (conbind ns x) conbind [] x = x extrabind :: [(Name, PTerm)] -> PTerm -> PTerm extrabind ((c,ty) : ns) x = PPi expl c NoFC ty (extrabind ns x) extrabind [] x = x coninsert :: [(Name, PTerm)] -> [(Name, PTerm)] -> PTerm -> PTerm coninsert cs ex (PPi p@(Imp _ _ _ _ _) n fc t sc) = PPi p n fc t (coninsert cs ex sc) coninsert cs ex sc = conbind cs (extrabind ex sc) -- Reorder declarations to be in the same order as defined in the -- class declaration (important so that we insert default definitions -- in the right place, and so that dependencies between methods are -- respected) reorderDefs :: [Name] -> [PDecl] -> [PDecl] reorderDefs ns [] = [] reorderDefs [] ds = ds reorderDefs (n : ns) ds = case pick n [] ds of Just (def, ds') -> def : reorderDefs ns ds' Nothing -> reorderDefs ns ds pick n acc [] = Nothing pick n acc (def@(PClauses _ _ cn cs) : ds) | nsroot n == nsroot cn = Just (def, acc ++ ds) pick n acc (d : ds) = pick n (acc ++ [d]) ds insertDefaults :: IState -> Name -> [(Name, (Name, PDecl))] -> [T.Text] -> [PDecl] -> [PDecl] insertDefaults i iname [] ns ds = ds insertDefaults i iname ((n,(dn, clauses)) : defs) ns ds = insertDefaults i iname defs ns (insertDef i n dn clauses ns iname ds) insertDef i meth def clauses ns iname decls | not $ any (clauseFor meth iname ns) decls = let newd = expandParamsD False i (\n -> meth) [] [def] clauses in -- trace (show newd) $ decls ++ [newd] | otherwise = decls warnMissing decls ns iname meth | not $ any (clauseFor meth iname ns) decls = iWarn fc . text $ "method " ++ show meth ++ " not defined" | otherwise = return () checkInClass ns meth | any (eqRoot meth) ns = return () | otherwise = tclift $ tfail (At fc (Msg $ show meth ++ " not a method of class " ++ show n)) eqRoot x y = nsroot x == nsroot y clauseFor m iname ns (PClauses _ _ m' _) = decorate ns iname m == decorate ns iname m' clauseFor m iname ns _ = False getHeadVars :: PTerm -> [Name] getHeadVars (PRef _ _ n) | implicitable n = [n] getHeadVars (PApp _ _ args) = concatMap getHeadVars (map getTm args) getHeadVars (PPair _ _ _ l r) = getHeadVars l ++ getHeadVars r getHeadVars (PDPair _ _ _ l t r) = getHeadVars l ++ getHeadVars t ++ getHeadVars t getHeadVars _ = [] -- | Implicitly bind variables from the instance head in method types impBind :: [(Name, PTerm)] -> PDecl -> PDecl impBind vs (PTy d ds syn fc opts n fc' t) = PTy d ds syn fc opts n fc' (doImpBind (filter (\(n, ty) -> n `notElem` boundIn t) vs) t) where doImpBind [] ty = ty doImpBind ((n, argty) : ns) ty = PPi impl n NoFC argty (doImpBind ns ty) boundIn (PPi _ n _ _ sc) = n : boundIn sc boundIn _ = [] getTypeIn :: IState -> Name -> Type -> PTerm getTypeIn ist n (Bind x b sc) | n == x = delab ist (binderTy b) | otherwise = getTypeIn ist n (substV (P Ref x Erased) sc) getTypeIn ist n tm = Placeholder toImp fc n = pimp n (PRef fc [] n) True -- | Propagate class parameters to method bodies, if they're not -- already there, and they are needed (i.e. appear in method's type) addParams :: [Name] -> PDecl -> PDecl addParams ps (PClauses fc opts n cs) = PClauses fc opts n (map addCParams cs) where addCParams (PClause fc n lhs ws rhs wb) = PClause fc n (addTmParams (dropPs (allNamesIn lhs) ps) lhs) ws rhs wb addCParams (PWith fc n lhs ws sc pn ds) = PWith fc n (addTmParams (dropPs (allNamesIn lhs) ps) lhs) ws sc pn (map (addParams ps) ds) addCParams c = c addTmParams ps (PRef fc hls n) = PApp fc (PRef fc hls n) (map (toImp fc) ps) addTmParams ps (PApp fc ap@(PRef fc' hls n) args) = PApp fc ap (mergePs (map (toImp fc) ps) args) addTmParams ps tm = tm mergePs [] args = args mergePs (p : ps) args | isImplicit p, pname p `notElem` map pname args = p : mergePs ps args where isImplicit (PExp{}) = False isImplicit _ = True mergePs (p : ps) args = mergePs ps args -- Don't propagate a parameter if the name is rebound explicitly dropPs :: [Name] -> [Name] -> [Name] dropPs ns = filter (\x -> x `notElem` ns) addParams ps d = d -- | Check a given method definition is injective, if the class info -- says it needs to be. Takes originally written decl and the one -- with name decoration, so we know which name to look up. checkInjectiveDef :: FC -> [(Name, (Bool, FnOpts, PTerm))] -> (PDecl, PDecl) -> Idris () checkInjectiveDef fc ns (PClauses _ _ n cs, PClauses _ _ elabn _) | Just (True, _, _) <- clookup n ns = do ist <- getIState case lookupDefExact elabn (tt_ctxt ist) of Just (CaseOp _ _ _ _ _ cdefs) -> checkInjectiveCase ist (snd (cases_compiletime cdefs)) where checkInjectiveCase ist (STerm tm) = checkInjectiveApp ist (fst (unApply tm)) checkInjectiveCase _ _ = notifail checkInjectiveApp ist (P (TCon _ _) n _) = return () checkInjectiveApp ist (P (DCon _ _ _) n _) = return () checkInjectiveApp ist (P Ref n _) | Just True <- lookupInjectiveExact n (tt_ctxt ist) = return () checkInjectiveApp ist (P Ref n _) = notifail checkInjectiveApp _ _ = notifail notifail = ierror $ At fc (Msg (show n ++ " must be defined by a type or data constructor")) clookup n [] = Nothing clookup n ((n', d) : ds) | nsroot n == nsroot n' = Just d | otherwise = Nothing checkInjectiveDef fc ns _ = return() checkInjectiveArgs :: FC -> Name -> [Int] -> Maybe Type -> Idris () checkInjectiveArgs fc n ds Nothing = return () checkInjectiveArgs fc n ds (Just ty) = do ist <- getIState let (_, args) = unApply (instantiateRetTy ty) ci 0 ist args where ci i ist (a : as) | i `elem` ds = if isInj ist a then ci (i + 1) ist as else tclift $ tfail (At fc (InvalidTCArg n a)) ci i ist (a : as) = ci (i + 1) ist as ci i ist [] = return () isInj i (P Bound n _) = True isInj i (P _ n _) = isConName n (tt_ctxt i) isInj i (App _ f a) = isInj i f && isInj i a isInj i (V _) = True isInj i (Bind n b sc) = isInj i sc isInj _ _ = True instantiateRetTy (Bind n (Pi _ _ _) sc) = substV (P Bound n Erased) (instantiateRetTy sc) instantiateRetTy t = t
tpsinnem/Idris-dev
src/Idris/Elab/Instance.hs
bsd-3-clause
20,544
1
28
7,028
7,478
3,721
3,757
390
40
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.InsertMap -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable module Yi.Keymap.Vim.InsertMap (defInsertMap) where import Prelude hiding (head) import Control.Applicative ((<$)) import Control.Lens (use) import Control.Monad (forM, liftM2, replicateM_, void, when) import Data.Char (isDigit) import Data.List.NonEmpty (NonEmpty (..), head, toList) import Data.Monoid (Monoid (mempty), (<>)) import qualified Data.Text as T (pack, unpack) import qualified Yi.Buffer as B (bdeleteB, deleteB, deleteRegionB, insertB, insertN) import Yi.Buffer.Adjusted as BA hiding (Insert) import Yi.Editor (EditorM, getEditorDyn, withCurrentBuffer) import Yi.Event (Event) import Yi.Keymap.Vim.Common import Yi.Keymap.Vim.Digraph (charFromDigraph) import Yi.Keymap.Vim.EventUtils (eventToEventString, parseEvents) import Yi.Keymap.Vim.Motion (Move (Move), stringToMove) import Yi.Keymap.Vim.StateUtils import Yi.Keymap.Vim.Utils (selectBinding, selectPureBinding) import Yi.Monad (whenM) import qualified Yi.Rope as R (fromString, fromText) import Yi.TextCompletion (CompletionScope (..), completeWordB) defInsertMap :: [(String, Char)] -> [VimBinding] defInsertMap digraphs = [rawPrintable] <> specials digraphs <> [printable] specials :: [(String, Char)] -> [VimBinding] specials digraphs = [exitBinding digraphs, pasteRegisterBinding, digraphBinding digraphs , oneshotNormalBinding, completionBinding, cursorBinding] exitBinding :: [(String, Char)] -> VimBinding exitBinding digraphs = VimBindingE f where f :: EventString -> VimState -> MatchResult (EditorM RepeatToken) f evs (VimState { vsMode = (Insert _) }) | evs `elem` ["<Esc>", "<C-c>"] = WholeMatch $ do count <- getCountE (Insert starter) <- fmap vsMode getEditorDyn when (count > 1) $ do inputEvents <- fmap (parseEvents . vsOngoingInsertEvents) getEditorDyn replicateM_ (count - 1) $ do when (starter `elem` ['O', 'o']) $ withCurrentBuffer $ insertB '\n' replay digraphs inputEvents modifyStateE $ \s -> s { vsOngoingInsertEvents = mempty } withCurrentBuffer $ moveXorSol 1 modifyStateE $ \s -> s { vsSecondaryCursors = mempty } resetCountE switchModeE Normal withCurrentBuffer $ whenM isCurrentLineAllWhiteSpaceB $ moveToSol >> deleteToEol return Finish f _ _ = NoMatch rawPrintable :: VimBinding rawPrintable = VimBindingE f where f :: EventString -> VimState -> MatchResult (EditorM RepeatToken) f evs s@(VimState { vsMode = (Insert _)}) | vsPaste s && evs `notElem` ["<Esc>", "<C-c>"] = WholeMatch . withCurrentBuffer $ do case evs of "<lt>" -> insertB '<' "<CR>" -> newlineB "<Tab>" -> insertB '\t' "<BS>" -> bdeleteB "<C-h>" -> bdeleteB "<Del>" -> deleteB Character Forward "<Home>" -> moveToSol "<End>" -> moveToEol "<PageUp>" -> scrollScreensB (-1) "<PageDown>" -> scrollScreensB 1 c -> insertN (R.fromText $ _unEv c) return Continue f _ _ = NoMatch replay :: [(String, Char)] -> [Event] -> EditorM () replay _ [] = return () replay digraphs (e1:es1) = do state <- getEditorDyn let recurse = replay digraphs evs1 = eventToEventString e1 bindingMatch1 = selectPureBinding evs1 state (defInsertMap digraphs) case bindingMatch1 of WholeMatch action -> void action >> recurse es1 PartialMatch -> case es1 of [] -> return () (e2:es2) -> do let evs2 = evs1 <> eventToEventString e2 bindingMatch2 = selectPureBinding evs2 state (defInsertMap digraphs) case bindingMatch2 of WholeMatch action -> void action >> recurse es2 _ -> recurse es2 _ -> recurse es1 oneshotNormalBinding :: VimBinding oneshotNormalBinding = VimBindingE (f . T.unpack . _unEv) where f "<C-o>" (VimState { vsMode = Insert _ }) = PartialMatch f ('<':'C':'-':'o':'>':evs) (VimState { vsMode = Insert _ }) = action evs <$ stringToMove (Ev . T.pack $ dropWhile isDigit evs) f _ _ = NoMatch action evs = do let (countString, motionCmd) = span isDigit evs WholeMatch (Move _style _isJump move) = stringToMove . Ev . T.pack $ motionCmd withCurrentBuffer $ move (if null countString then Nothing else Just (read countString)) return Continue pasteRegisterBinding :: VimBinding pasteRegisterBinding = VimBindingE (f . T.unpack . _unEv) where f "<C-r>" (VimState { vsMode = Insert _ }) = PartialMatch f ('<':'C':'-':'r':'>':regName:[]) (VimState { vsMode = Insert _ }) = WholeMatch $ do mr <- getRegisterE regName case mr of Nothing -> return () Just (Register _style rope) -> withCurrentBuffer $ insertRopeWithStyleB rope Inclusive return Continue f _ _ = NoMatch digraphBinding :: [(String, Char)] -> VimBinding digraphBinding digraphs = VimBindingE (f . T.unpack . _unEv) where f ('<':'C':'-':'k':'>':c1:c2:[]) (VimState { vsMode = Insert _ }) = WholeMatch $ do maybe (return ()) (withCurrentBuffer . insertB) $ charFromDigraph digraphs c1 c2 return Continue f ('<':'C':'-':'k':'>':_c1:[]) (VimState { vsMode = Insert _ }) = PartialMatch f "<C-k>" (VimState { vsMode = Insert _ }) = PartialMatch f _ _ = NoMatch printable :: VimBinding printable = VimBindingE f where f evs state@(VimState { vsMode = Insert _ } ) = case selectBinding evs state (specials undefined) of NoMatch -> WholeMatch (printableAction evs) _ -> NoMatch f _ _ = NoMatch printableAction :: EventString -> EditorM RepeatToken printableAction evs = do saveInsertEventStringE evs currentCursor <- withCurrentBuffer pointB IndentSettings et _ sw <- withCurrentBuffer indentSettingsB secondaryCursors <- fmap vsSecondaryCursors getEditorDyn let allCursors = currentCursor :| secondaryCursors marks <- withCurrentBuffer $ forM' allCursors $ \cursor -> do moveTo cursor getMarkB Nothing -- Using autoindenting with multiple cursors -- is just too broken. let (insertB', insertN', deleteB', bdeleteB', deleteRegionB') = if null secondaryCursors then (BA.insertB, BA.insertN, BA.deleteB, BA.bdeleteB, BA.deleteRegionB) else (B.insertB, B.insertN, B.deleteB, B.bdeleteB, B.deleteRegionB) let bufAction = case T.unpack . _unEv $ evs of (c:[]) -> insertB' c "<CR>" -> do isOldLineEmpty <- isCurrentLineEmptyB shouldTrimOldLine <- isCurrentLineAllWhiteSpaceB if isOldLineEmpty then newlineB else if shouldTrimOldLine then savingPointB $ do moveToSol newlineB else do newlineB indentAsTheMostIndentedNeighborLineB firstNonSpaceB "<Tab>" -> do if et then insertN' . R.fromString $ replicate sw ' ' else insertB' '\t' "<C-t>" -> modifyIndentB (+ sw) "<C-d>" -> modifyIndentB (max 0 . subtract sw) "<C-e>" -> insertCharWithBelowB "<C-y>" -> insertCharWithAboveB "<BS>" -> bdeleteB' "<C-h>" -> bdeleteB' "<Home>" -> moveToSol "<End>" -> moveToEol >> leftOnEol "<PageUp>" -> scrollScreensB (-1) "<PageDown>" -> scrollScreensB 1 "<Del>" -> deleteB' Character Forward "<C-w>" -> deleteRegionB' =<< regionOfPartNonEmptyB unitViWordOnLine Backward "<C-u>" -> bdeleteLineB "<lt>" -> insertB' '<' evs' -> error $ "Unhandled event " <> show evs' <> " in insert mode" updatedCursors <- withCurrentBuffer $ do updatedCursors <- forM' marks $ \mark -> do moveTo =<< use (markPointA mark) bufAction pointB mapM_ deleteMarkB $ toList marks moveTo $ head updatedCursors return $ toList updatedCursors modifyStateE $ \s -> s { vsSecondaryCursors = drop 1 updatedCursors } return Continue where forM' :: Monad m => NonEmpty a -> (a -> m b) -> m (NonEmpty b) forM' (x :| xs) f = liftM2 (:|) (f x) (forM xs f) completionBinding :: VimBinding completionBinding = VimBindingE (f . T.unpack . _unEv) where f evs (VimState { vsMode = (Insert _) }) | evs `elem` ["<C-n>", "<C-p>"] = WholeMatch $ do let _direction = if evs == "<C-n>" then Forward else Backward completeWordB FromAllBuffers return Continue f _ _ = NoMatch cursorBinding :: VimBinding cursorBinding = VimBindingE f where f evs (VimState { vsMode = (Insert _) }) | evs `elem` ["<Up>", "<Left>", "<Down>", "<Right>"] = WholeMatch $ do let WholeMatch (Move _style _isJump move) = stringToMove evs withCurrentBuffer $ move Nothing return Continue f _ _ = NoMatch
TOSPIO/yi
src/library/Yi/Keymap/Vim/InsertMap.hs
gpl-2.0
10,169
7
23
3,356
2,900
1,492
1,408
208
22
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP #-} module BuildTyCl ( buildSynonymTyCon, buildFamilyTyCon, buildAlgTyCon, buildDataCon, buildPatSyn, TcMethInfo, buildClass, distinctAbstractTyConRhs, totallyAbstractTyConRhs, mkNewTyConRhs, mkDataTyConRhs, newImplicitBinder, newTyConRepName ) where #include "HsVersions.h" import IfaceEnv import FamInstEnv( FamInstEnvs ) import TysWiredIn( isCTupleTyConName ) import PrelNames( tyConRepModOcc ) import DataCon import PatSyn import Var import VarSet import BasicTypes import Name import MkId import Class import TyCon import Type import Id import Coercion import TcType import SrcLoc( noSrcSpan ) import DynFlags import TcRnMonad import UniqSupply import Util import Outputable ------------------------------------------------------ buildSynonymTyCon :: Name -> [TyVar] -> [Role] -> Type -> Kind -- ^ Kind of the RHS -> TyCon buildSynonymTyCon tc_name tvs roles rhs rhs_kind = mkSynonymTyCon tc_name kind tvs roles rhs where kind = mkPiKinds tvs rhs_kind buildFamilyTyCon :: Name -- ^ Type family name -> [TyVar] -- ^ Type variables -> Maybe Name -- ^ Result variable name -> FamTyConFlav -- ^ Open, closed or in a boot file? -> Kind -- ^ Kind of the RHS -> Maybe Class -- ^ Parent, if exists -> Injectivity -- ^ Injectivity annotation -- See [Injectivity annotation] in HsDecls -> TyCon buildFamilyTyCon tc_name tvs res_tv rhs rhs_kind parent injectivity = mkFamilyTyCon tc_name kind tvs res_tv rhs parent injectivity where kind = mkPiKinds tvs rhs_kind ------------------------------------------------------ distinctAbstractTyConRhs, totallyAbstractTyConRhs :: AlgTyConRhs distinctAbstractTyConRhs = AbstractTyCon True totallyAbstractTyConRhs = AbstractTyCon False mkDataTyConRhs :: [DataCon] -> AlgTyConRhs mkDataTyConRhs cons = DataTyCon { data_cons = cons, is_enum = not (null cons) && all is_enum_con cons -- See Note [Enumeration types] in TyCon } where is_enum_con con | (_tvs, theta, arg_tys, _res) <- dataConSig con = null theta && null arg_tys mkNewTyConRhs :: Name -> TyCon -> DataCon -> TcRnIf m n AlgTyConRhs -- ^ Monadic because it makes a Name for the coercion TyCon -- We pass the Name of the parent TyCon, as well as the TyCon itself, -- because the latter is part of a knot, whereas the former is not. mkNewTyConRhs tycon_name tycon con = do { co_tycon_name <- newImplicitBinder tycon_name mkNewTyCoOcc ; let co_tycon = mkNewTypeCo co_tycon_name tycon etad_tvs etad_roles etad_rhs ; traceIf (text "mkNewTyConRhs" <+> ppr co_tycon) ; return (NewTyCon { data_con = con, nt_rhs = rhs_ty, nt_etad_rhs = (etad_tvs, etad_rhs), nt_co = co_tycon } ) } -- Coreview looks through newtypes with a Nothing -- for nt_co, or uses explicit coercions otherwise where tvs = tyConTyVars tycon roles = tyConRoles tycon inst_con_ty = applyTys (dataConUserType con) (mkTyVarTys tvs) rhs_ty = ASSERT( isFunTy inst_con_ty ) funArgTy inst_con_ty -- Instantiate the data con with the -- type variables from the tycon -- NB: a newtype DataCon has a type that must look like -- forall tvs. <arg-ty> -> T tvs -- Note that we *can't* use dataConInstOrigArgTys here because -- the newtype arising from class Foo a => Bar a where {} -- has a single argument (Foo a) that is a *type class*, so -- dataConInstOrigArgTys returns []. etad_tvs :: [TyVar] -- Matched lazily, so that mkNewTypeCo can etad_roles :: [Role] -- return a TyCon without pulling on rhs_ty etad_rhs :: Type -- See Note [Tricky iface loop] in LoadIface (etad_tvs, etad_roles, etad_rhs) = eta_reduce (reverse tvs) (reverse roles) rhs_ty eta_reduce :: [TyVar] -- Reversed -> [Role] -- also reversed -> Type -- Rhs type -> ([TyVar], [Role], Type) -- Eta-reduced version -- (tyvars in normal order) eta_reduce (a:as) (_:rs) ty | Just (fun, arg) <- splitAppTy_maybe ty, Just tv <- getTyVar_maybe arg, tv == a, not (a `elemVarSet` tyVarsOfType fun) = eta_reduce as rs fun eta_reduce tvs rs ty = (reverse tvs, reverse rs, ty) ------------------------------------------------------ buildDataCon :: FamInstEnvs -> Name -> Bool -- Declared infix -> Promoted TyConRepName -- Promotable -> [HsSrcBang] -> Maybe [HsImplBang] -- See Note [Bangs on imported data constructors] in MkId -> [FieldLabel] -- Field labels -> [TyVar] -> [TyVar] -- Univ and ext -> [(TyVar,Type)] -- Equality spec -> ThetaType -- Does not include the "stupid theta" -- or the GADT equalities -> [Type] -> Type -- Argument and result types -> TyCon -- Rep tycon -> TcRnIf m n DataCon -- A wrapper for DataCon.mkDataCon that -- a) makes the worker Id -- b) makes the wrapper Id if necessary, including -- allocating its unique (hence monadic) buildDataCon fam_envs src_name declared_infix prom_info src_bangs impl_bangs field_lbls univ_tvs ex_tvs eq_spec ctxt arg_tys res_ty rep_tycon = do { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc ; work_name <- newImplicitBinder src_name mkDataConWorkerOcc -- This last one takes the name of the data constructor in the source -- code, which (for Haskell source anyway) will be in the DataName name -- space, and puts it into the VarName name space ; traceIf (text "buildDataCon 1" <+> ppr src_name) ; us <- newUniqueSupply ; dflags <- getDynFlags ; let stupid_ctxt = mkDataConStupidTheta rep_tycon arg_tys univ_tvs data_con = mkDataCon src_name declared_infix prom_info src_bangs field_lbls univ_tvs ex_tvs eq_spec ctxt arg_tys res_ty rep_tycon stupid_ctxt dc_wrk dc_rep dc_wrk = mkDataConWorkId work_name data_con dc_rep = initUs_ us (mkDataConRep dflags fam_envs wrap_name impl_bangs data_con) ; traceIf (text "buildDataCon 2" <+> ppr src_name) ; return data_con } -- The stupid context for a data constructor should be limited to -- the type variables mentioned in the arg_tys -- ToDo: Or functionally dependent on? -- This whole stupid theta thing is, well, stupid. mkDataConStupidTheta :: TyCon -> [Type] -> [TyVar] -> [PredType] mkDataConStupidTheta tycon arg_tys univ_tvs | null stupid_theta = [] -- The common case | otherwise = filter in_arg_tys stupid_theta where tc_subst = zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs) stupid_theta = substTheta tc_subst (tyConStupidTheta tycon) -- Start by instantiating the master copy of the -- stupid theta, taken from the TyCon arg_tyvars = tyVarsOfTypes arg_tys in_arg_tys pred = not $ isEmptyVarSet $ tyVarsOfType pred `intersectVarSet` arg_tyvars ------------------------------------------------------ buildPatSyn :: Name -> Bool -> (Id,Bool) -> Maybe (Id, Bool) -> ([TyVar], ThetaType) -- ^ Univ and req -> ([TyVar], ThetaType) -- ^ Ex and prov -> [Type] -- ^ Argument types -> Type -- ^ Result type -> [FieldLabel] -- ^ Field labels for -- a record pattern synonym -> PatSyn buildPatSyn src_name declared_infix matcher@(matcher_id,_) builder (univ_tvs, req_theta) (ex_tvs, prov_theta) arg_tys pat_ty field_labels = ASSERT((and [ univ_tvs == univ_tvs' , ex_tvs == ex_tvs' , pat_ty `eqType` pat_ty' , prov_theta `eqTypes` prov_theta' , req_theta `eqTypes` req_theta' , arg_tys `eqTypes` arg_tys' ])) mkPatSyn src_name declared_infix (univ_tvs, req_theta) (ex_tvs, prov_theta) arg_tys pat_ty matcher builder field_labels where ((_:univ_tvs'), req_theta', tau) = tcSplitSigmaTy $ idType matcher_id ([pat_ty', cont_sigma, _], _) = tcSplitFunTys tau (ex_tvs', prov_theta', cont_tau) = tcSplitSigmaTy cont_sigma (arg_tys', _) = tcSplitFunTys cont_tau -- ------------------------------------------------------ type TcMethInfo = (Name, DefMethSpec, Type) -- A temporary intermediate, to communicate between -- tcClassSigs and buildClass. buildClass :: Name -- Name of the class/tycon (they have the same Name) -> [TyVar] -> [Role] -> ThetaType -> [FunDep TyVar] -- Functional dependencies -> [ClassATItem] -- Associated types -> [TcMethInfo] -- Method info -> ClassMinimalDef -- Minimal complete definition -> RecFlag -- Info for type constructor -> TcRnIf m n Class buildClass tycon_name tvs roles sc_theta fds at_items sig_stuff mindef tc_isrec = fixM $ \ rec_clas -> -- Only name generation inside loop do { traceIf (text "buildClass") ; datacon_name <- newImplicitBinder tycon_name mkClassDataConOcc ; tc_rep_name <- newTyConRepName tycon_name ; op_items <- mapM (mk_op_item rec_clas) sig_stuff -- Build the selector id and default method id -- Make selectors for the superclasses ; sc_sel_names <- mapM (newImplicitBinder tycon_name . mkSuperDictSelOcc) (takeList sc_theta [fIRST_TAG..]) ; let sc_sel_ids = [ mkDictSelId sc_name rec_clas | sc_name <- sc_sel_names] -- We number off the Dict superclass selectors, 1, 2, 3 etc so that we -- can construct names for the selectors. Thus -- class (C a, C b) => D a b where ... -- gives superclass selectors -- D_sc1, D_sc2 -- (We used to call them D_C, but now we can have two different -- superclasses both called C!) ; let use_newtype = isSingleton arg_tys -- Use a newtype if the data constructor -- (a) has exactly one value field -- i.e. exactly one operation or superclass taken together -- (b) that value is of lifted type (which they always are, because -- we box equality superclasses) -- See note [Class newtypes and equality predicates] -- We treat the dictionary superclasses as ordinary arguments. -- That means that in the case of -- class C a => D a -- we don't get a newtype with no arguments! args = sc_sel_names ++ op_names op_tys = [ty | (_,_,ty) <- sig_stuff] op_names = [op | (op,_,_) <- sig_stuff] arg_tys = sc_theta ++ op_tys rec_tycon = classTyCon rec_clas ; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs") datacon_name False -- Not declared infix NotPromoted -- Class tycons are not promoted (map (const no_bang) args) (Just (map (const HsLazy) args)) [{- No fields -}] tvs [{- no existentials -}] [{- No GADT equalities -}] [{- No theta -}] arg_tys (mkTyConApp rec_tycon (mkTyVarTys tvs)) rec_tycon ; rhs <- if use_newtype then mkNewTyConRhs tycon_name rec_tycon dict_con else if isCTupleTyConName tycon_name then return (TupleTyCon { data_con = dict_con , tup_sort = ConstraintTuple }) else return (mkDataTyConRhs [dict_con]) ; let { clas_kind = mkPiKinds tvs constraintKind ; tycon = mkClassTyCon tycon_name clas_kind tvs roles rhs rec_clas tc_isrec tc_rep_name -- A class can be recursive, and in the case of newtypes -- this matters. For example -- class C a where { op :: C b => a -> b -> Int } -- Because C has only one operation, it is represented by -- a newtype, and it should be a *recursive* newtype. -- [If we don't make it a recursive newtype, we'll expand the -- newtype like a synonym, but that will lead to an infinite -- type] ; result = mkClass tvs fds sc_theta sc_sel_ids at_items op_items mindef tycon } ; traceIf (text "buildClass" <+> ppr tycon) ; return result } where no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict mk_op_item :: Class -> TcMethInfo -> TcRnIf n m ClassOpItem mk_op_item rec_clas (op_name, dm_spec, _) = do { dm_info <- case dm_spec of NoDM -> return NoDefMeth GenericDM -> do { dm_name <- newImplicitBinder op_name mkGenDefMethodOcc ; return (GenDefMeth dm_name) } VanillaDM -> do { dm_name <- newImplicitBinder op_name mkDefaultMethodOcc ; return (DefMeth dm_name) } ; return (mkDictSelId op_name rec_clas, dm_info) } {- Note [Class newtypes and equality predicates] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class (a ~ F b) => C a b where op :: a -> b We cannot represent this by a newtype, even though it's not existential, because there are two value fields (the equality predicate and op. See Trac #2238 Moreover, class (a ~ F b) => C a b where {} Here we can't use a newtype either, even though there is only one field, because equality predicates are unboxed, and classes are boxed. -} newImplicitBinder :: Name -- Base name -> (OccName -> OccName) -- Occurrence name modifier -> TcRnIf m n Name -- Implicit name -- Called in BuildTyCl to allocate the implicit binders of type/class decls -- For source type/class decls, this is the first occurrence -- For iface ones, the LoadIface has alrady allocated a suitable name in the cache newImplicitBinder base_name mk_sys_occ | Just mod <- nameModule_maybe base_name = newGlobalBinder mod occ loc | otherwise -- When typechecking a [d| decl bracket |], -- TH generates types, classes etc with Internal names, -- so we follow suit for the implicit binders = do { uniq <- newUnique ; return (mkInternalName uniq occ loc) } where occ = mk_sys_occ (nameOccName base_name) loc = nameSrcSpan base_name -- | Make the 'TyConRepName' for this 'TyCon' newTyConRepName :: Name -> TcRnIf gbl lcl TyConRepName newTyConRepName tc_name | Just mod <- nameModule_maybe tc_name , (mod, occ) <- tyConRepModOcc mod (nameOccName tc_name) = newGlobalBinder mod occ noSrcSpan | otherwise = newImplicitBinder tc_name mkTyConRepUserOcc
AlexanderPankiv/ghc
compiler/iface/BuildTyCl.hs
bsd-3-clause
16,817
0
19
6,009
2,636
1,444
1,192
236
5
import Test.QuickCheck -- Our QC instances and properties. import Instances import Properties.Delete import Properties.Failure import Properties.Floating import Properties.Focus import Properties.GreedyView import Properties.Insert import Properties.Screen import Properties.Shift import Properties.Stack import Properties.StackSet import Properties.Swap import Properties.View import Properties.Workspace import Properties.Layout.Full import Properties.Layout.Tall import System.Environment import Text.Printf import Control.Monad import Control.Applicative main :: IO () main = do arg <- fmap (drop 1) getArgs let n = if null arg then 100 else read $ head arg args = stdArgs { maxSuccess = n, maxSize = 100 } qc t = do c <- quickCheckWithResult args t case c of Success {} -> return True _ -> return False perform (s, t) = printf "%-35s: " s >> qc t n <- length . filter not <$> mapM perform tests unless (n == 0) (error (show n ++ " test(s) failed")) tests = [("StackSet invariants", property prop_invariant) ,("empty: invariant", property prop_empty_I) ,("empty is empty", property prop_empty) ,("empty / current", property prop_empty_current) ,("empty / member", property prop_member_empty) ,("view : invariant", property prop_view_I) ,("view sets current", property prop_view_current) ,("view idempotent", property prop_view_idem) ,("view reversible", property prop_view_reversible) ,("view is local", property prop_view_local) ,("greedyView : invariant", property prop_greedyView_I) ,("greedyView sets current", property prop_greedyView_current) ,("greedyView is safe", property prop_greedyView_current_id) ,("greedyView idempotent", property prop_greedyView_idem) ,("greedyView reversible", property prop_greedyView_reversible) ,("greedyView is local", property prop_greedyView_local) ,("peek/member", property prop_member_peek) ,("index/length", property prop_index_length) ,("focus left : invariant", property prop_focusUp_I) ,("focus master : invariant", property prop_focusMaster_I) ,("focus right: invariant", property prop_focusDown_I) ,("focusWindow: invariant", property prop_focus_I) ,("focus left/master", property prop_focus_left_master) ,("focus right/master", property prop_focus_right_master) ,("focus master/master", property prop_focus_master_master) ,("focusWindow master", property prop_focusWindow_master) ,("focus left/right", property prop_focus_left) ,("focus right/left", property prop_focus_right) ,("focus all left", property prop_focus_all_l) ,("focus all right", property prop_focus_all_r) ,("focus down is local", property prop_focus_down_local) ,("focus up is local", property prop_focus_up_local) ,("focus master is local", property prop_focus_master_local) ,("focus master idemp", property prop_focusMaster_idem) ,("focusWindow is local", property prop_focusWindow_local) ,("focusWindow works" , property prop_focusWindow_works) ,("focusWindow identity", property prop_focusWindow_identity) ,("findTag", property prop_findIndex) ,("allWindows/member", property prop_allWindowsMember) ,("currentTag", property prop_currentTag) ,("insert: invariant", property prop_insertUp_I) ,("insert/new", property prop_insert_empty) ,("insert is idempotent", property prop_insert_idem) ,("insert is reversible", property prop_insert_delete) ,("insert is local", property prop_insert_local) ,("insert duplicates", property prop_insert_duplicate) ,("insert/peek", property prop_insert_peek) ,("insert/size", property prop_size_insert) ,("delete: invariant", property prop_delete_I) ,("delete/empty", property prop_empty) ,("delete/member", property prop_delete) ,("delete is reversible", property prop_delete_insert) ,("delete is local", property prop_delete_local) ,("delete/focus", property prop_delete_focus) ,("delete last/focus up", property prop_delete_focus_end) ,("delete ~last/focus down", property prop_delete_focus_not_end) ,("filter preserves order", property prop_filter_order) ,("swapLeft", property prop_swap_left) ,("swapRight", property prop_swap_right) ,("swapMaster: invariant", property prop_swap_master_I) ,("swapUp: invariant" , property prop_swap_left_I) ,("swapDown: invariant", property prop_swap_right_I) ,("swapMaster id on focus", property prop_swap_master_focus) ,("swapUp id on focus", property prop_swap_left_focus) ,("swapDown id on focus", property prop_swap_right_focus) ,("swapMaster is idempotent", property prop_swap_master_idempotent) ,("swap all left", property prop_swap_all_l) ,("swap all right", property prop_swap_all_r) ,("swapMaster is local", property prop_swap_master_local) ,("swapUp is local", property prop_swap_left_local) ,("swapDown is local", property prop_swap_right_local) ,("shiftMaster id on focus", property prop_shift_master_focus) ,("shiftMaster is local", property prop_shift_master_local) ,("shiftMaster is idempotent", property prop_shift_master_idempotent) ,("shiftMaster preserves ordering", property prop_shift_master_ordering) ,("shift: invariant" , property prop_shift_I) ,("shift is reversible" , property prop_shift_reversible) ,("shiftWin: invariant" , property prop_shift_win_I) ,("shiftWin is shift on focus", property prop_shift_win_focus) ,("shiftWin fix current" , property prop_shift_win_fix_current) ,("shiftWin identity", property prop_shift_win_indentity) ,("floating is reversible" , property prop_float_reversible) ,("floating sets geometry" , property prop_float_geometry) ,("floats can be deleted", property prop_float_delete) ,("screens includes current", property prop_screens) ,("differentiate works", property prop_differentiate) ,("lookupTagOnScreen", property prop_lookup_current) ,("lookupTagOnVisbleScreen", property prop_lookup_visible) ,("screens works", property prop_screens_works) ,("renaming works", property prop_rename1) ,("ensure works", property prop_ensure) ,("ensure hidden semantics", property prop_ensure_append) ,("mapWorkspace id", property prop_mapWorkspaceId) ,("mapWorkspace inverse", property prop_mapWorkspaceInverse) ,("mapLayout id", property prop_mapLayoutId) ,("mapLayout inverse", property prop_mapLayoutInverse) ,("abort fails", property prop_abort) ,("new fails with abort", property prop_new_abort) ,("point within", property prop_point_within) -- tall layout ,("tile 1 window fullsize", property prop_tile_fullscreen) ,("tiles never overlap", property prop_tile_non_overlap) ,("split horizontal", property prop_split_horizontal) ,("split vertical", property prop_split_vertical) ,("pure layout tall", property prop_purelayout_tall) ,("send shrink tall", property prop_shrink_tall) ,("send expand tall", property prop_expand_tall) ,("send incmaster tall", property prop_incmaster_tall) -- full layout ,("pure layout full", property prop_purelayout_full) ,("send message full", property prop_sendmsg_full) ,("describe full", property prop_desc_full) ,("describe mirror", property prop_desc_mirror) -- resize hints ,("window resize hints: inc", property prop_resize_inc) ,("window resize hints: inc all", property prop_resize_inc_extra) ,("window resize hints: max", property prop_resize_max) ,("window resize hints: max all ", property prop_resize_max_extra) ,("window aspect hints: fits", property prop_aspect_fits) ,("window aspect hints: shrinks ", property prop_aspect_hint_shrink) ,("pointWithin", property prop_point_within) ,("pointWithin mirror", property prop_point_within_mirror) ]
atupal/xmonad-mirror
xmonad/tests/Properties.hs
mit
8,231
0
15
1,601
1,751
1,005
746
154
3
module PackedString where import qualified Prelude as P import Prelude hiding (null) newtype PackedString = PS String deriving (Eq,Ord) instance Show PackedString where showsPrec n (PS s) r = s++r packString = PS unpackPS (PS s) = s null (PS s) = P.null s
forste/haReFork
tools/base/tests/GhcLibraries/PackedString.hs
bsd-3-clause
263
0
8
51
106
59
47
9
1
module AsPatIn1 where f :: Either a b -> Either a b f x@x_1 = x_1
SAdams601/HaRe
old/testing/subIntroPattern/AsPatIn1.hs
bsd-3-clause
67
0
6
17
34
18
16
3
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wall #-} module Bug where class C a where type T a data D a m :: a instance C Int deriving instance C Bool
sdiehl/ghc
testsuite/tests/deriving/should_compile/T14094.hs
bsd-3-clause
230
0
6
47
45
27
18
11
0
-- Trac #8806 module T8806 where f :: Int => Int f x = x + 1 g :: (Int => Show a) => Int g = undefined
urbanslug/ghc
testsuite/tests/typecheck/should_fail/T8806.hs
bsd-3-clause
106
0
7
31
51
28
23
-1
-1
module Graphics.Urho3D.Scene.Internal.CustomLogicComponent( CustomLogicComponent , customLogicComponentCntx , sharedCustomLogicComponentPtrCntx , SharedCustomLogicComponent ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import Graphics.Urho3D.Container.Ptr import qualified Data.Map as Map data CustomLogicComponent customLogicComponentCntx :: C.Context customLogicComponentCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "CustomLogicComponent", [t| CustomLogicComponent |]) ] } sharedPtrImpl "CustomLogicComponent"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Scene/Internal/CustomLogicComponent.hs
mit
650
0
11
88
120
80
40
-1
-1
import Test.Tasty import Test.Tasty.HUnit import InfoTest(infoUnitTests) import InfoInternalTest(infoInternalUnitTests) import QueryTests(queryUnitTests) import UtilitiesTests(utilitiesTests) import DeconstructorTests(deconstructorTests) main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [infoUnitTests, infoInternalUnitTests, queryUnitTests, utilitiesTests, deconstructorTests]
juventietis/HLINQ
Tests/test.hs
mit
400
0
6
32
90
54
36
10
1
{-# OPTIONS_GHC -F -pgmF hspec-discover #-} import Test.Hspec -- main :: IO () -- main = hspec $ do -- specCaesar
pogin503/vbautil
language/haskell/caesar/test/Spec.hs
mit
117
0
4
24
10
7
3
2
0
{-| Module : PansiteApp.CommandLine Description : Command-line parsers for Pansite app Copyright : (C) Richard Cook, 2017-2018 Licence : MIT Maintainer : [email protected] Stability : experimental Portability : portable -} module PansiteApp.CommandLine ( Command (..) , ServerConfig (..) , parseCommand ) where import Data.Monoid ((<>)) import Options.Applicative import PansiteApp.VersionInfo -- TODO: Move into separate module type Port = Int -- TODO: Move into separate module data ServerConfig = ServerConfig Port deriving Show data Command = RunCommand ServerConfig FilePath FilePath | VersionCommand portArg :: Parser Port portArg = option auto (long "port" <> short 'p' <> value 3000 <> metavar "PORT" <> help "Port") configParser :: Parser FilePath configParser = strOption (long "config" <> short 'c' <> value ".pansite.yaml" <> metavar "CONFIG" <> help "Path to YAML application configuration file") outputDirParser :: Parser FilePath outputDirParser = strOption (long "output-dir" <> short 'o' <> value "_output" <> metavar "OUTPUTDIR" <> help "Output directory") serverConfigParser :: Parser ServerConfig serverConfigParser = ServerConfig <$> portArg runCommandParser :: Parser Command runCommandParser = RunCommand <$> serverConfigParser <*> configParser <*> outputDirParser versionCommandParser :: Parser Command versionCommandParser = flag' VersionCommand (short 'v' <> long "version" <> help "Show version") commandParser :: Parser Command commandParser = runCommandParser <|> versionCommandParser parseCommand :: IO Command parseCommand = execParser $ info (helper <*> commandParser) (fullDesc <> progDesc "Run Pansite development server" <> header ("Pansite development server " ++ fullVersionString))
rcook/pansite
app/PansiteApp/CommandLine.hs
mit
1,871
0
11
379
386
200
186
46
1
-- | Data.TSTP.Parent module. -- Adapted from https://github.com/agomezl/tstp2agda. module Data.TSTP.Parent ( Parent ( Parent ) ) where ------------------------------------------------------------------------------ import Data.TSTP.GData ( GTerm(..) ) ------------------------------------------------------------------------------ -- | Parent formula information. data Parent = Parent String [GTerm] deriving (Eq, Ord, Read, Show)
jonaprieto/athena
src/Data/TSTP/Parent.hs
mit
454
0
7
63
69
44
25
7
0
{-# LANGUAGE ScopedTypeVariables #-} module Data.Normalize.Tests where import Data.Normalize import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck testNormal :: forall a. (Show a, Arbitrary a, Eq a, Normalize a) => a -> Test testNormal _ = testGroup "normalization" [ testProperty "isNormal ⇒ no change" (\(a::a) -> if isNormal a then normal a == a else True) ]
Soares/Dater.hs
test/Data/Normalize/Tests.hs
mit
416
0
12
72
125
70
55
10
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} -- | A postgresql backend for persistent. module Database.Persist.Postgresql ( withPostgresqlPool , withPostgresqlConn , createPostgresqlPool , module Database.Persist.Sql , ConnectionString , PostgresConf (..) , openSimpleConn ) where import Database.Persist.Sql import Data.Maybe (mapMaybe) import Data.Fixed (Pico) import qualified Database.PostgreSQL.Simple as PG import qualified Database.PostgreSQL.Simple.BuiltinTypes as PG import qualified Database.PostgreSQL.Simple.Internal as PG import qualified Database.PostgreSQL.Simple.ToField as PGTF import qualified Database.PostgreSQL.Simple.FromField as PGFF import qualified Database.PostgreSQL.Simple.Types as PG import Database.PostgreSQL.Simple.Ok (Ok (..)) import qualified Database.PostgreSQL.LibPQ as LibPQ import Control.Exception (throw) import Control.Monad.IO.Class (MonadIO (..)) import Data.List (intercalate) import Data.Typeable import Data.IORef import qualified Data.Map as Map import Data.Either (partitionEithers) import Control.Arrow import Data.List (sort, groupBy) import Data.Function (on) import Data.Conduit import qualified Data.Conduit.List as CL import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B8 import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Blaze.ByteString.Builder.Char8 as BBB import qualified Blaze.ByteString.Builder.ByteString as BBS import Data.Time.LocalTime (localTimeToUTC, utc) import Data.Text (Text, pack) import Data.Aeson import Control.Monad (forM, mzero) import System.Environment (getEnvironment) import Data.Int (Int64) -- | A @libpq@ connection string. A simple example of connection -- string would be @\"host=localhost port=5432 user=test -- dbname=test password=test\"@. Please read libpq's -- documentation at -- <http://www.postgresql.org/docs/9.1/static/libpq-connect.html> -- for more details on how to create such strings. type ConnectionString = ByteString -- | Create a PostgreSQL connection pool and run the given -- action. The pool is properly released after the action -- finishes using it. Note that you should not use the given -- 'ConnectionPool' outside the action since it may be already -- been released. withPostgresqlPool :: MonadIO m => ConnectionString -- ^ Connection string to the database. -> Int -- ^ Number of connections to be kept open in -- the pool. -> (ConnectionPool -> m a) -- ^ Action to be executed that uses the -- connection pool. -> m a withPostgresqlPool ci = withSqlPool $ open' ci -- | Create a PostgreSQL connection pool. Note that it's your -- responsability to properly close the connection pool when -- unneeded. Use 'withPostgresqlPool' for an automatic resource -- control. createPostgresqlPool :: MonadIO m => ConnectionString -- ^ Connection string to the database. -> Int -- ^ Number of connections to be kept open -- in the pool. -> m ConnectionPool createPostgresqlPool ci = createSqlPool $ open' ci -- | Same as 'withPostgresqlPool', but instead of opening a pool -- of connections, only one connection is opened. withPostgresqlConn :: (MonadIO m, MonadBaseControl IO m) => ConnectionString -> (Connection -> m a) -> m a withPostgresqlConn = withSqlConn . open' open' :: ConnectionString -> IO Connection open' cstr = do PG.connectPostgreSQL cstr >>= openSimpleConn -- | Generate a 'Connection' from a 'PG.Connection' openSimpleConn :: PG.Connection -> IO Connection openSimpleConn conn = do smap <- newIORef $ Map.empty return Connection { connPrepare = prepare' conn , connStmtMap = smap , connInsertSql = insertSql' , connClose = PG.close conn , connMigrateSql = migrate' , connBegin = const $ PG.begin conn , connCommit = const $ PG.commit conn , connRollback = const $ PG.rollback conn , connEscapeName = escape , connNoLimit = "LIMIT ALL" , connRDBMS = "postgresql" } prepare' :: PG.Connection -> Text -> IO Statement prepare' conn sql = do let query = PG.Query (T.encodeUtf8 sql) return Statement { stmtFinalize = return () , stmtReset = return () , stmtExecute = execute' conn query , stmtQuery = withStmt' conn query } insertSql' :: DBName -> [DBName] -> DBName -> InsertSqlResult insertSql' t cols id' = ISRSingle $ pack $ concat [ "INSERT INTO " , T.unpack $ escape t , "(" , intercalate "," $ map (T.unpack . escape) cols , ") VALUES(" , intercalate "," (map (const "?") cols) , ") RETURNING " , T.unpack $ escape id' ] execute' :: PG.Connection -> PG.Query -> [PersistValue] -> IO Int64 execute' conn query vals = PG.execute conn query (map P vals) withStmt' :: MonadResource m => PG.Connection -> PG.Query -> [PersistValue] -> Source m [PersistValue] withStmt' conn query vals = bracketP openS closeS pull where openS = do -- Construct raw query rawquery <- PG.formatQuery conn query (map P vals) -- Take raw connection PG.withConnection conn $ \rawconn -> do -- Execute query mret <- LibPQ.exec rawconn rawquery case mret of Nothing -> do merr <- LibPQ.errorMessage rawconn fail $ case merr of Nothing -> "Postgresql.withStmt': unknown error" Just e -> "Postgresql.withStmt': " ++ B8.unpack e Just ret -> do -- Check result status status <- LibPQ.resultStatus ret case status of LibPQ.TuplesOk -> return () _ -> do msg <- LibPQ.resStatus status mmsg <- LibPQ.resultErrorMessage ret fail $ "Postgresql.withStmt': bad result status " ++ show status ++ " (" ++ (maybe (show msg) (show . (,) msg) mmsg) ++ ")" -- Get number and type of columns cols <- LibPQ.nfields ret getters <- forM [0..cols-1] $ \col -> do oid <- LibPQ.ftype ret col case PG.oid2builtin oid of Nothing -> return $ \bs-> case bs of Nothing -> fail $ "Unexpected null value in backend specific value" Just a -> return $ PersistDbSpecific a Just bt -> return $ getGetter bt $ PG.Field ret col oid -- Ready to go! rowRef <- newIORef (LibPQ.Row 0) rowCount <- LibPQ.ntuples ret return (ret, rowRef, rowCount, getters) closeS (ret, _, _, _) = LibPQ.unsafeFreeResult ret pull x = do y <- liftIO $ pullS x case y of Nothing -> return () Just z -> yield z >> pull x pullS (ret, rowRef, rowCount, getters) = do row <- atomicModifyIORef rowRef (\r -> (r+1, r)) if row == rowCount then return Nothing else fmap Just $ forM (zip getters [0..]) $ \(getter, col) -> do mbs <- LibPQ.getvalue' ret row col case mbs of Nothing -> return PersistNull Just bs -> do ok <- PGFF.runConversion (getter mbs) conn bs `seq` case ok of Errors (exc:_) -> throw exc Errors [] -> error "Got an Errors, but no exceptions" Ok v -> return v -- | Avoid orphan instances. newtype P = P PersistValue instance PGTF.ToField P where toField (P (PersistText t)) = PGTF.toField t toField (P (PersistByteString bs)) = PGTF.toField (PG.Binary bs) toField (P (PersistInt64 i)) = PGTF.toField i toField (P (PersistDouble d)) = PGTF.toField d toField (P (PersistRational r)) = PGTF.Plain $ BBB.fromString $ show (fromRational r :: Pico) -- FIXME: Too Ambigous, can not select precision without information about field toField (P (PersistBool b)) = PGTF.toField b toField (P (PersistDay d)) = PGTF.toField d toField (P (PersistTimeOfDay t)) = PGTF.toField t toField (P (PersistUTCTime t)) = PGTF.toField t toField (P (PersistZonedTime (ZT t))) = PGTF.toField t toField (P PersistNull) = PGTF.toField PG.Null toField (P (PersistList l)) = PGTF.toField $ listToJSON l toField (P (PersistMap m)) = PGTF.toField $ mapToJSON m toField (P (PersistDbSpecific s)) = PGTF.toField (Unknown s) toField (P (PersistObjectId _)) = error "Refusing to serialize a PersistObjectId to a PostgreSQL value" newtype Unknown = Unknown { unUnknown :: ByteString } deriving (Eq, Show, Read, Ord, Typeable) instance PGFF.FromField Unknown where fromField f mdata = case mdata of Nothing -> PGFF.returnError PGFF.UnexpectedNull f "" Just dat -> return (Unknown dat) instance PGTF.ToField Unknown where toField (Unknown a) = PGTF.Escape a type Getter a = PGFF.FieldParser a convertPV :: PGFF.FromField a => (a -> b) -> Getter b convertPV f = (fmap f .) . PGFF.fromField -- FIXME: check if those are correct and complete. getGetter :: PG.BuiltinType -> Getter PersistValue getGetter PG.Bool = convertPV PersistBool getGetter PG.ByteA = convertPV (PersistByteString . unBinary) getGetter PG.Char = convertPV PersistText getGetter PG.Name = convertPV PersistText getGetter PG.Int8 = convertPV PersistInt64 getGetter PG.Int2 = convertPV PersistInt64 getGetter PG.Int4 = convertPV PersistInt64 getGetter PG.Text = convertPV PersistText getGetter PG.Xml = convertPV PersistText getGetter PG.Float4 = convertPV PersistDouble getGetter PG.Float8 = convertPV PersistDouble getGetter PG.AbsTime = convertPV PersistUTCTime getGetter PG.RelTime = convertPV PersistUTCTime getGetter PG.Money = convertPV PersistDouble getGetter PG.BpChar = convertPV PersistText getGetter PG.VarChar = convertPV PersistText getGetter PG.Date = convertPV PersistDay getGetter PG.Time = convertPV PersistTimeOfDay getGetter PG.Timestamp = convertPV (PersistUTCTime . localTimeToUTC utc) getGetter PG.TimestampTZ = convertPV (PersistZonedTime . ZT) getGetter PG.Bit = convertPV PersistInt64 getGetter PG.VarBit = convertPV PersistInt64 getGetter PG.Numeric = convertPV PersistRational getGetter PG.Void = \_ _ -> return PersistNull getGetter PG.UUID = convertPV (PersistDbSpecific . unUnknown) getGetter other = error $ "Postgresql.getGetter: type " ++ show other ++ " not supported." unBinary :: PG.Binary a -> a unBinary (PG.Binary x) = x migrate' :: [EntityDef a] -> (Text -> IO Statement) -> EntityDef SqlType -> IO (Either [Text] [(Bool, Text)]) migrate' allDefs getter val = fmap (fmap $ map showAlterDb) $ do let name = entityDB val old <- getColumns getter val case partitionEithers old of ([], old'') -> do let old' = partitionEithers old'' let new = first (filter $ not . safeToRemove val . cName) $ second (map udToPair) $ mkColumns allDefs val if null old then do let addTable = AddTable $ concat -- Lower case e: see Database.Persistent.GenericSql.Migration [ "CREATe TABLE " , T.unpack $ escape name , "(" , T.unpack $ escape $ entityID val , " SERIAL PRIMARY KEY UNIQUE" , concatMap (\x -> ',' : showColumn x) $ fst new , ")" ] let uniques = flip concatMap (snd new) $ \(uname, ucols) -> [AlterTable name $ AddUniqueConstraint uname ucols] references = mapMaybe (getAddReference name) $ fst new return $ Right $ addTable : uniques ++ references else do let (acs, ats) = getAlters val new old' let acs' = map (AlterColumn name) acs let ats' = map (AlterTable name) ats return $ Right $ acs' ++ ats' (errs, _) -> return $ Left errs type SafeToRemove = Bool data AlterColumn = Type SqlType | IsNull | NotNull | Add' Column | Drop SafeToRemove | Default String | NoDefault | Update' String | AddReference DBName | DropReference DBName type AlterColumn' = (DBName, AlterColumn) data AlterTable = AddUniqueConstraint DBName [DBName] | DropConstraint DBName data AlterDB = AddTable String | AlterColumn DBName AlterColumn' | AlterTable DBName AlterTable -- | Returns all of the columns in the given table currently in the database. getColumns :: (Text -> IO Statement) -> EntityDef a -> IO [Either Text (Either Column (DBName, [DBName]))] getColumns getter def = do stmt <- getter "SELECT column_name,is_nullable,udt_name,column_default,numeric_precision,numeric_scale FROM information_schema.columns WHERE table_name=? AND column_name <> ?" let vals = [ PersistText $ unDBName $ entityDB def , PersistText $ unDBName $ entityID def ] cs <- runResourceT $ stmtQuery stmt vals $$ helper stmt' <- getter "SELECT constraint_name, column_name FROM information_schema.constraint_column_usage WHERE table_name=? AND column_name <> ? ORDER BY constraint_name, column_name" us <- runResourceT $ stmtQuery stmt' vals $$ helperU return $ cs ++ us where getAll front = do x <- CL.head case x of Nothing -> return $ front [] Just [PersistText con, PersistText col] -> getAll (front . (:) (con, col)) Just _ -> getAll front -- FIXME error message? helperU = do rows <- getAll id return $ map (Right . Right . (DBName . fst . head &&& map (DBName . snd))) $ groupBy ((==) `on` fst) rows helper = do x <- CL.head case x of Nothing -> return [] Just x' -> do col <- liftIO $ getColumn getter (entityDB def) x' let col' = case col of Left e -> Left e Right c -> Right $ Left c cols <- helper return $ col' : cols -- | Check if a column name is listed as the "safe to remove" in the entity -- list. safeToRemove :: EntityDef a -> DBName -> Bool safeToRemove def (DBName colName) = any (elem "SafeToRemove" . fieldAttrs) $ filter ((== (DBName colName)) . fieldDB) $ entityFields def getAlters :: EntityDef a -> ([Column], [(DBName, [DBName])]) -> ([Column], [(DBName, [DBName])]) -> ([AlterColumn'], [AlterTable]) getAlters def (c1, u1) (c2, u2) = (getAltersC c1 c2, getAltersU u1 u2) where getAltersC [] old = map (\x -> (cName x, Drop $ safeToRemove def $ cName x)) old getAltersC (new:news) old = let (alters, old') = findAlters new old in alters ++ getAltersC news old' getAltersU :: [(DBName, [DBName])] -> [(DBName, [DBName])] -> [AlterTable] getAltersU [] old = map DropConstraint $ filter (not . isManual) $ map fst old getAltersU ((name, cols):news) old = case lookup name old of Nothing -> AddUniqueConstraint name cols : getAltersU news old Just ocols -> let old' = filter (\(x, _) -> x /= name) old in if sort cols == sort ocols then getAltersU news old' else DropConstraint name : AddUniqueConstraint name cols : getAltersU news old' -- Don't drop constraints which were manually added. isManual (DBName x) = "__manual_" `T.isPrefixOf` x getColumn :: (Text -> IO Statement) -> DBName -> [PersistValue] -> IO (Either Text Column) getColumn getter tname [PersistText x, PersistText y, PersistText z, d, npre, nscl] = case d' of Left s -> return $ Left s Right d'' -> case getType z of Left s -> return $ Left s Right t -> do let cname = DBName x ref <- getRef cname return $ Right Column { cName = cname , cNull = y == "YES" , cSqlType = t , cDefault = d'' , cMaxLen = Nothing , cReference = ref } where getRef cname = do let sql = pack $ concat [ "SELECT COUNT(*) FROM " , "information_schema.table_constraints " , "WHERE table_name=? " , "AND constraint_type='FOREIGN KEY' " , "AND constraint_name=?" ] let ref = refName tname cname stmt <- getter sql runResourceT $ stmtQuery stmt [ PersistText $ unDBName tname , PersistText $ unDBName ref ] $$ do Just [PersistInt64 i] <- CL.head return $ if i == 0 then Nothing else Just (DBName "", ref) d' = case d of PersistNull -> Right Nothing PersistText t -> Right $ Just t _ -> Left $ pack $ "Invalid default column: " ++ show d getType "int4" = Right $ SqlInt32 getType "int8" = Right $ SqlInt64 getType "varchar" = Right $ SqlString getType "date" = Right $ SqlDay getType "bool" = Right $ SqlBool getType "timestamp" = Right $ SqlDayTime getType "timestamptz" = Right $ SqlDayTimeZoned getType "float4" = Right $ SqlReal getType "float8" = Right $ SqlReal getType "bytea" = Right $ SqlBlob getType "time" = Right $ SqlTime getType "numeric" = getNumeric npre nscl getType a = Right $ SqlOther a getNumeric (PersistInt64 a) (PersistInt64 b) = Right $ SqlNumeric (fromIntegral a) (fromIntegral b) getNumeric a b = Left $ pack $ "Can not get numeric field precision, got: " ++ show a ++ " and " ++ show b ++ " as precision and scale" getColumn _ _ x = return $ Left $ pack $ "Invalid result from information_schema: " ++ show x findAlters :: Column -> [Column] -> ([AlterColumn'], [Column]) findAlters col@(Column name isNull sqltype def _maxLen ref) cols = case filter (\c -> cName c == name) cols of [] -> ([(name, Add' col)], cols) Column _ isNull' sqltype' def' _maxLen' ref':_ -> let refDrop Nothing = [] refDrop (Just (_, cname)) = [(name, DropReference cname)] refAdd Nothing = [] refAdd (Just (tname, _)) = [(name, AddReference tname)] modRef = if fmap snd ref == fmap snd ref' then [] else refDrop ref' ++ refAdd ref modNull = case (isNull, isNull') of (True, False) -> [(name, IsNull)] (False, True) -> let up = case def of Nothing -> id Just s -> (:) (name, Update' $ T.unpack s) in up [(name, NotNull)] _ -> [] modType = if sqltype == sqltype' then [] else [(name, Type sqltype)] modDef = if def == def' then [] else case def of Nothing -> [(name, NoDefault)] Just s -> [(name, Default $ T.unpack s)] in (modRef ++ modDef ++ modNull ++ modType, filter (\c -> cName c /= name) cols) -- | Get the references to be added to a table for the given column. getAddReference :: DBName -> Column -> Maybe AlterDB getAddReference table (Column n _nu _ _def _maxLen ref) = case ref of Nothing -> Nothing Just (s, _) -> Just $ AlterColumn table (n, AddReference s) showColumn :: Column -> String showColumn (Column n nu sqlType def _maxLen _ref) = concat [ T.unpack $ escape n , " " , showSqlType sqlType , " " , if nu then "NULL" else "NOT NULL" , case def of Nothing -> "" Just s -> " DEFAULT " ++ T.unpack s ] showSqlType :: SqlType -> String showSqlType SqlString = "VARCHAR" showSqlType SqlInt32 = "INT4" showSqlType SqlInt64 = "INT8" showSqlType SqlReal = "DOUBLE PRECISION" showSqlType (SqlNumeric s prec) = "NUMERIC(" ++ show s ++ "," ++ show prec ++ ")" showSqlType SqlDay = "DATE" showSqlType SqlTime = "TIME" showSqlType SqlDayTime = "TIMESTAMP" showSqlType SqlDayTimeZoned = "TIMESTAMP WITH TIME ZONE" showSqlType SqlBlob = "BYTEA" showSqlType SqlBool = "BOOLEAN" showSqlType (SqlOther t) = T.unpack t showAlterDb :: AlterDB -> (Bool, Text) showAlterDb (AddTable s) = (False, pack s) showAlterDb (AlterColumn t (c, ac)) = (isUnsafe ac, pack $ showAlter t (c, ac)) where isUnsafe (Drop safeToRemove) = not safeToRemove isUnsafe _ = False showAlterDb (AlterTable t at) = (False, pack $ showAlterTable t at) showAlterTable :: DBName -> AlterTable -> String showAlterTable table (AddUniqueConstraint cname cols) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ADD CONSTRAINT " , T.unpack $ escape cname , " UNIQUE(" , intercalate "," $ map (T.unpack . escape) cols , ")" ] showAlterTable table (DropConstraint cname) = concat [ "ALTER TABLE " , T.unpack $ escape table , " DROP CONSTRAINT " , T.unpack $ escape cname ] showAlter :: DBName -> AlterColumn' -> String showAlter table (n, Type t) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ALTER COLUMN " , T.unpack $ escape n , " TYPE " , showSqlType t ] showAlter table (n, IsNull) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ALTER COLUMN " , T.unpack $ escape n , " DROP NOT NULL" ] showAlter table (n, NotNull) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ALTER COLUMN " , T.unpack $ escape n , " SET NOT NULL" ] showAlter table (_, Add' col) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ADD COLUMN " , showColumn col ] showAlter table (n, Drop _) = concat [ "ALTER TABLE " , T.unpack $ escape table , " DROP COLUMN " , T.unpack $ escape n ] showAlter table (n, Default s) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ALTER COLUMN " , T.unpack $ escape n , " SET DEFAULT " , s ] showAlter table (n, NoDefault) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ALTER COLUMN " , T.unpack $ escape n , " DROP DEFAULT" ] showAlter table (n, Update' s) = concat [ "UPDATE " , T.unpack $ escape table , " SET " , T.unpack $ escape n , "=" , s , " WHERE " , T.unpack $ escape n , " IS NULL" ] showAlter table (n, AddReference t2) = concat [ "ALTER TABLE " , T.unpack $ escape table , " ADD CONSTRAINT " , T.unpack $ escape $ refName table n , " FOREIGN KEY(" , T.unpack $ escape n , ") REFERENCES " , T.unpack $ escape t2 ] showAlter table (_, DropReference cname) = concat [ "ALTER TABLE " , T.unpack (escape table) , " DROP CONSTRAINT " , T.unpack $ escape cname ] escape :: DBName -> Text escape (DBName s) = T.pack $ '"' : go (T.unpack s) ++ "\"" where go "" = "" go ('"':xs) = "\"\"" ++ go xs go (x:xs) = x : go xs -- | Information required to connect to a PostgreSQL database -- using @persistent@'s generic facilities. These values are the -- same that are given to 'withPostgresqlPool'. data PostgresConf = PostgresConf { pgConnStr :: ConnectionString -- ^ The connection string. , pgPoolSize :: Int -- ^ How many connections should be held on the connection pool. } instance PersistConfig PostgresConf where type PersistConfigBackend PostgresConf = SqlPersistT type PersistConfigPool PostgresConf = ConnectionPool createPoolConfig (PostgresConf cs size) = createPostgresqlPool cs size runPool _ = runSqlPool loadConfig (Object o) = do database <- o .: "database" host <- o .: "host" port <- o .:? "port" .!= 5432 user <- o .: "user" password <- o .: "password" pool <- o .: "poolsize" let ci = PG.ConnectInfo { PG.connectHost = host , PG.connectPort = port , PG.connectUser = user , PG.connectPassword = password , PG.connectDatabase = database } cstr = PG.postgreSQLConnectionString ci return $ PostgresConf cstr pool loadConfig _ = mzero applyEnv c0 = do env <- getEnvironment return $ addUser env $ addPass env $ addDatabase env $ addPort env $ addHost env c0 where addParam param val c = c { pgConnStr = B8.concat [pgConnStr c, " ", param, "='", pgescape val, "'"] } pgescape = B8.pack . go where go ('\'':rest) = '\\' : '\'' : go rest go ('\\':rest) = '\\' : '\\' : go rest go ( x :rest) = x : go rest go [] = [] maybeAddParam param envvar env = maybe id (addParam param) $ lookup envvar env addHost = maybeAddParam "host" "PGHOST" addPort = maybeAddParam "port" "PGPORT" addUser = maybeAddParam "user" "PGUSER" addPass = maybeAddParam "password" "PGPASS" addDatabase = maybeAddParam "dbname" "PGDATABASE" refName :: DBName -> DBName -> DBName refName (DBName table) (DBName column) = DBName $ T.concat [table, "_", column, "_fkey"] udToPair :: UniqueDef -> (DBName, [DBName]) udToPair ud = (uniqueDBName ud, map snd $ uniqueFields ud)
gbwey/persistentold
persistent-postgresql/Database/Persist/Postgresql.hs
mit
28,107
0
32
9,886
7,639
3,946
3,693
-1
-1
module Main where even1 [] = [] even1 (h:t) = if (even h) then (h:even1(t)) else even1(t) even2 x = [n | n <- x, even n] main = do print (even1 [1,2,3,4,5]) print (even2 [1,2,3,4,5])
skywind3000/language
haskell/evenlist.hs
mit
228
0
10
81
149
81
68
7
2
{-# LANGUAGE GADTs, TypeOperators, PatternSynonyms #-} -- | Solving flex-rigid problems module Tactics.Unification where import Prelude hiding (any, elem) import Control.Newtype import Data.Foldable import qualified Data.Monoid as M import Control.Error import DisplayLang.Name import Evidences.Tm import Evidences.Eval import ProofState.Structure.Developments import ProofState.Edition.News import ProofState.Edition.ProofState import ProofState.Edition.GetSet import ProofState.Edition.Navigation import ProofState.Interface.Search import ProofState.Interface.ProofKit import ProofState.Interface.Definition import ProofState.Interface.Solving import Kit.BwdFwd import Kit.MissingLibrary -- | Solve a flex-rigid problem by filling in the reference (which must be a -- hole) with the given term, which must contain no defined references. It -- records the current location in the proof state (but not the cursor -- position) and returns there afterwards. solveHole :: REF -> INTM -> ProofState (EXTM :=>: VAL) solveHole ref tm = do here <- getCurrentName r <- solveHole' ref [] tm cursorBottom goTo here return r -- | Fill in the hole, accumulating a list of dependencies (references the -- solution depends on) as it passes them. It moves the dependencies to before -- the hole by creating new holes earlier in the proof state and inserting a -- news bulletin that solves the old dependency holes with the new ones. solveHole' :: REF -> [(REF, INTM)] -> INTM -> ProofState (EXTM :=>: VAL) solveHole' ref@(name := HOLE _ :<: _) deps tm = do es <- getEntriesAbove case es of B0 -> goOutBelow >> cursorUp >> solveHole' ref deps tm _ :< e -> pass e where pass :: Entry Bwd -> ProofState (EXTM :=>: VAL) pass (EDEF def@(defName := _) _ _ _ _ _) | name == defName && occurs def = throwDTmStr "solveHole: you can't define something in terms of itself!" | name == defName = do cursorUp news <- makeDeps deps [] cursorDown goIn putNewsBelow news let (tm', _) = tellNews news tm giveOutBelow (evTm tm') | occurs def = do goIn ty :=>: _ <- getGoal "solveHole" solveHole' ref ((def, ty):deps) tm | otherwise = goIn >> solveHole' ref deps tm pass (EPARAM param _ _ _ _) | occurs param = let items :: [ErrorItem DInTmRN] items = [ errMsg "solveHole: param" , errRef param , errMsg "occurs illegally." ] in throwErrorS items | otherwise = cursorUp >> solveHole' ref deps tm pass (EModule modName _ _ _) = goIn >> solveHole' ref deps tm occurs :: REF -> Bool occurs ref = any (== ref) tm || ala' M.Any foldMap (any (== ref) . snd) deps makeDeps :: [(REF, INTM)] -> NewsBulletin -> ProofState NewsBulletin makeDeps [] news = return news makeDeps ((name := HOLE k :<: tyv, ty) : deps) news = do let (ty', _) = tellNews news ty makeKinded k (fst (last name) :<: ty') EDEF ref _ _ _ _ _ <- getEntryAbove makeDeps deps ((name := DEFN (NP ref) :<: tyv, GoodNews) : news) makeDeps _ _ = throwDTmStr ("makeDeps: bad reference kind! Perhaps " ++ "solveHole was called with a term containing unexpanded definitions?" ) solveHole' ref _ _ = throwDInTmRN (stackItem [ errMsg "solveHole:" , errRef ref ]) stripShared :: NEU -> ProofState REF stripShared n = getInScope >>= stripShared' n where stripShared' :: NEU -> Entries -> ProofState REF stripShared' (P ref@(_ := HOLE Hoping :<: _)) B0 = return ref stripShared' (n :$ A (NP r)) (es :< EPARAM paramRef _ _ _ _) | r == paramRef = stripShared' n es stripShared' n (es :< EDEF _ _ _ _ _ _) = stripShared' n es stripShared' n (es :< EModule _ _ _ _) = stripShared' n es stripShared' n es = throwDInTmRN $ stackItem [ errMsg "stripShared: fail on" , errVal (N n) ]
kwangkim/pigment
src-lib/Tactics/Unification.hs
mit
4,124
0
17
1,138
1,190
599
591
88
6
module NGL.Rendering where import Graphics.Rendering.OpenGL as GL import Graphics.UI.GLFW as GLFW import Control.Monad import System.Exit ( exitWith, ExitCode(..) ) import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import NGL.LoadShaders import NGL.Shape data Descriptor = Descriptor VertexArrayObject ArrayIndex NumArrayIndices bufferOffset :: Integral a => a -> Ptr b bufferOffset = plusPtr nullPtr . fromIntegral initResources :: [Vertex2 Float] -> IO Descriptor initResources vs = do triangles <- genObjectName bindVertexArrayObject $= Just triangles let vertices = vs numVertices = length vertices vertexBuffer <- genObjectName bindBuffer ArrayBuffer $= Just vertexBuffer withArray vs $ \ptr -> do let size = fromIntegral (numVertices * sizeOf (head vs)) bufferData ArrayBuffer $= (size, ptr, StaticDraw) let firstIndex = 0 vPosition = AttribLocation 0 vertexAttribPointer vPosition $= (ToFloat, VertexArrayDescriptor 2 Float 0 (bufferOffset firstIndex)) vertexAttribArray vPosition $= Enabled let rgba = [GL.Color4 (1.0) 0.0 0.0 1.0, GL.Color4 (0.0) (1.0) 0.0 1.0, GL.Color4 0.0 (0.0) 1.0 1.0] :: [Color4 GLfloat] colorBuffer <- genObjectName bindBuffer ArrayBuffer $= Just colorBuffer withArray rgba $ \ptr -> do let size = fromIntegral (numVertices * sizeOf (head rgba)) bufferData ArrayBuffer $= (size, ptr, StaticDraw) let firstIndex = 0 vertexColor = AttribLocation 1 vertexAttribPointer vertexColor $= (ToFloat, VertexArrayDescriptor 4 Float 0 (bufferOffset firstIndex)) vertexAttribArray vertexColor $= Enabled program <- loadShaders [ ShaderInfo VertexShader (FileSource "Shaders/triangles.vert"), ShaderInfo FragmentShader (FileSource "Shaders/triangles.frac")] currentProgram $= Just program return $ Descriptor triangles firstIndex (fromIntegral numVertices) keyPressed :: GLFW.KeyCallback keyPressed win GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = shutdown win keyPressed _ _ _ _ _ = return () shutdown :: GLFW.WindowCloseCallback shutdown win = do GLFW.destroyWindow win GLFW.terminate _ <- exitWith ExitSuccess return () resizeWindow :: GLFW.WindowSizeCallback resizeWindow win w h = do GL.viewport $= (GL.Position 0 0, GL.Size (fromIntegral w) (fromIntegral h)) GL.matrixMode $= GL.Projection GL.loadIdentity GL.ortho2D 0 (realToFrac w) (realToFrac h) 0 createWindow :: String -> (Int, Int) -> IO GLFW.Window createWindow title (sizex,sizey) = do GLFW.init GLFW.defaultWindowHints Just win <- GLFW.createWindow sizex sizey title Nothing Nothing GLFW.makeContextCurrent (Just win) GLFW.setWindowSizeCallback win (Just resizeWindow) GLFW.setKeyCallback win (Just keyPressed) GLFW.setWindowCloseCallback win (Just shutdown) return win drawInWindow :: GLFW.Window -> [[Point]] -> IO () drawInWindow win vs = do descriptor <- initResources $ toVertex vs onDisplay win descriptor closeWindow :: GLFW.Window -> IO () closeWindow win = do GLFW.destroyWindow win GLFW.terminate onDisplay :: GLFW.Window -> Descriptor -> IO () onDisplay win descriptor@(Descriptor triangles firstIndex numVertices) = do GL.clearColor $= Color4 1 0 0 1 GL.clear [ColorBuffer] bindVertexArrayObject $= Just triangles drawArrays Triangles firstIndex numVertices GLFW.swapBuffers win forever $ do GLFW.pollEvents onDisplay win descriptor
ublubu/zombieapaperclypse
NGL/Rendering.hs
mit
3,661
0
19
820
1,149
553
596
91
1
-- | -- Module : Main -- Description : Main module. -- Copyright : (c) Maximilian Nitsch, 2015 -- -- License : MIT -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module put all functions together and run the spellchecker. module Main where import Prelude hiding (interact) import Spellchecker.Checker import Spellchecker.CmdLineParser import Spellchecker.Spell (defaultPenalties) import System.IO hiding (interact) import qualified Data.Text.Lazy.IO as TLI -- | Read relevant data from @Configuration@, generates a @DictTrie@, correct -- misspelled content of the input file and write it to defined output file. correctText :: Penalties -> Configuration -> IO () correctText p (Configuration i o c l q) = do trie <- trieFromFile c text <- readInput i hOut <- openFile o WriteMode -- Write @Slice@ directly to @hOut@ or pass is to @correctWord@ function let write (Misc x) = TLI.hPutStr hOut x write (Word x) = TLI.hPutStr hOut =<< correctWord (interact q) trie p l 5 x sequence_ $ write <$> text hClose hOut -- | Main function, start of execution. main :: IO () main = correctText defaultPenalties =<< parseConfig
Ma-Ni/haspell
src/Haspell.hs
mit
1,237
0
13
246
249
134
115
19
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} -- | Run actor. -- import Network.AWS.Wolf import Options.Generic -- | Args -- -- Program arguments. -- data Args = Args { config :: FilePath -- ^ Configuration file. , plan :: FilePath -- ^ Plan file to decide on. , domain :: Maybe Text -- ^ Optional domain to use. } deriving (Show, Generic) instance ParseRecord Args -- | Run decider. -- main :: IO () main = do args <- getRecord "Decider" decideMain (config args) (plan args) (domain args)
swift-nav/wolf
main/decider.hs
mit
591
0
9
139
127
73
54
18
1
-- print1.hs module Print1 where main :: IO () -- IO type: printing to the screen main = putStrLn "hello world!" -- set
younggi/books
haskellbook/practices/print1.hs
mit
129
0
6
32
25
15
10
3
1
-- A small keymap library for gtk -- -- Author : Jens-Ulrik Petersen -- Created: 15 July 2002 -- -- Version: $Revision: 1.6 $ from $Date: 2008/11/03 03:14:11 $ -- -- Copyright (c) 2002, 2008-2009 Jens-Ulrik Holger Petersen -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Library General Public -- License as published by the Free Software Foundation; either -- version 2 of the License, or (at your option) any later version. -- -- This library 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 -- Library General Public License for more details. -- -- Description -- module Graphics.UI.Gtk.Keymap (keymapAdd, keyPressCB, newKeymap, Keymap, Keybinding(..)) where import Data.Map (Map) import qualified Data.Map as Map import Control.Concurrent.MVar (newMVar, modifyMVar_, readMVar, MVar) import Graphics.UI.Gtk.Gdk.Events -- import Debug -- import GdkKeys type Keymap = MVar KeymapHash type KeymapHash = Map (String, Int) (IO ()) data Keybinding = KB [Modifier] String (IO ()) -- -- need to map meta, alt, hyper, super, et al -- data ModSym = ModShift | ModLock | ModCtrl | Mod1 | Mod2 | Mod3 | Mod4 | Mod5 -- deriving Enum newKeymap :: IO Keymap newKeymap = newMVar Map.empty keymapAdd :: Keymap -> Keybinding -> IO () keymapAdd keymap (KB modi name act) = modifyMVar_ keymap $ \keyfm -> do -- debug $ symsToInt modi let bitmap = sum $ map fromEnum modi return $ Map.insert (name, bitmap) act keyfm -- where -- symsToInt :: [ModSym] -> Modifier -- symsToInt ss = foldl (+) 0 $ map (\s -> 2^(fromEnum s)) ss keyPressCB :: Keymap -> Event -> IO Bool keyPressCB keymap Key { eventKeyName = keyName, eventModifier = modi } = do keyfm <- readMVar keymap let bitmap = sum $ map fromEnum modi case Map.lookup (keyName, bitmap) keyfm of Just act -> act >> return True Nothing -> return False keyPressCB _ _ = return False
juhp/hircules
src/Graphics/UI/Gtk/Keymap.hs
mit
2,097
2
13
431
400
228
172
25
2
{-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} module Examples.Rpc.EchoClient (main) where import Data.Function ((&)) import Data.Functor ((<&>)) import Network.Simple.TCP (connect) import qualified Capnp.New as C import Capnp.Rpc (ConnConfig(..), fromClient, handleConn, socketTransport) import Capnp.Gen.Echo.New main :: IO () main = connect "localhost" "4000" $ \(sock, _addr) -> handleConn (socketTransport sock C.defaultLimit) C.def { debugMode = True , withBootstrap = Just $ \_sup client -> let echoClient :: C.Client Echo echoClient = fromClient client in echoClient & C.callP #echo C.def { query = "Hello, World!" } <&> C.pipe #reply >>= C.waitPipeline >>= C.evalLimitT C.defaultLimit . C.parse >>= print }
zenhack/haskell-capnp
examples/lib/Examples/Rpc/EchoClient.hs
mit
928
0
22
288
245
140
105
23
1
module Whip.Interpreter (runProgram) where import Whip.Types (Expr(..), typeOf) import Control.Monad (foldM) import qualified Data.Map.Lazy as M type Scope = M.Map String Expr library :: Scope library = M.fromList [ "print" ~> Lambda pr , "show" ~> Lambda (String . show) ] where (~>) = (,) pr (String s) = Comput $ putStrLn s >> return (Parens []) pr x = error (show x ++ " is not a string") runProgram :: [Expr] -> Either String Scope runProgram = foldM topEval library topEval :: Scope -> Expr -> Either String Scope topEval sc (Parens [Symbol "def", Symbol s, e]) = do v <- eval sc e return $ M.insert s v sc topEval _ x = Left $ "top level naked expression: " ++ show x eval :: Scope -> Expr -> Either String Expr eval s e = case e of Parens (x:xs) -> eval s x >>= call s xs Symbol v -> case M.lookup v s of Just x -> Right x Nothing -> Left (show v ++ " is not defined") x -> Right x call :: Scope -> [Expr] -> Expr -> Either String Expr call _ [] e = Right e call s (x:xs) (Lambda f) = eval s x >>= call s xs . f call _ _ e = Left (typeOf e ++ " is not a function")
L8D/whip-hs
src/Whip/Interpreter.hs
mit
1,198
0
14
350
528
267
261
30
4
module Statistics.FastBayes.Internal ( ) where
cscherrer/fastbayes
src/Statistics/FastBayes/Internal.hs
mit
55
0
3
13
10
7
3
2
0
main = do print $ [f x | x <- xs, p x] == map f (filter p xs) where f = (*2) p = odd xs = take 5 [1..]
fabioyamate/programming-in-haskell
ch07/ex01.hs
mit
131
0
11
59
80
41
39
5
1
yDeferredLighting :: (HasScene a DeferredEntity DeferredEnvironment, HasHDRCamera a, HasDeferredSettings a, DeferredMonad m env) => YageResource (RenderSystem m a (Texture2D PixelRGB8)) yDeferredLighting = do throwWithStack $ glEnable GL_FRAMEBUFFER_SRGB throwWithStack $ buildNamedStrings embeddedShaders ((++) "/res/glsl/") drawGBuffer <- gPass skyPass <- drawSky defaultRadiance <- textureRes (pure (defaultMaterialSRGB^.materialTexture) :: Cubemap (Image PixelRGB8)) voxelize <- voxelizePass 256 256 256 visVoxel <- visualizeVoxelPass drawLights <- lightPass postAmbient <- postAmbientPass renderBloom <- addBloom tonemapPass <- toneMapper debugOverlay <- toneMapper return $ proc input -> do mainViewport <- sysEnv viewport -< () -- render surface attributes for lighting out gbufferTarget <- autoResized mkGbufferTarget -< mainViewport^.rectangle gBuffer <- processPassWithGlobalEnv drawGBuffer -< ( gbufferTarget , input^.scene , input^.hdrCamera.camera ) -- voxelize for ambient occlusion mVoxelOcclusion <- if input^.deferredSettings.activeVoxelAmbientOcclusion then fmap Just voxelize -< input else pure Nothing -< () voxelSceneTarget <- autoResized mkVisVoxelTarget -< mainViewport^.rectangle -- lighting lBufferTarget <- autoResized mkLightBuffer -< mainViewport^.rectangle _lBuffer <- processPassWithGlobalEnv drawLights -< ( lBufferTarget , input^.scene.environment.lights , input^.hdrCamera.camera , gBuffer ) -- ambient let radiance = maybe defaultRadiance (view $ materials.radianceMap.materialTexture) (input^.scene.environment.sky) post <- processPassWithGlobalEnv postAmbient -< ( lBufferTarget , radiance , mVoxelOcclusion , input^.hdrCamera.camera , gBuffer ) -- sky pass skyTarget <- onChange -< (post, gBuffer^.depthChannel) sceneTex <- if isJust $ input^.scene.environment.sky then skyPass -< ( fromJust $ input^.scene.environment.sky , input^.hdrCamera.camera , skyTarget ) else returnA -< post -- bloom pass bloomed <- renderBloom -< (input^.hdrCamera.bloomSettings, sceneTex) -- tone map from hdr (floating) to discrete Word8 finalScene <- tonemapPass -< (input^.hdrCamera.hdrSensor, sceneTex, Just bloomed) if input^.deferredSettings.showDebugOverlay && isJust mVoxelOcclusion then do visVoxTex <- processPassWithGlobalEnv visVoxel -< ( voxelSceneTarget , fromJust mVoxelOcclusion , input^.hdrCamera.camera , [VisualizeSceneVoxel,VisualizePageMask] ) debugOverlay -< (input^.hdrCamera.hdrSensor, finalScene, Just visVoxTex) else returnA -< finalScene
MaxDaten/master-thesis
src/deferred-pbr-pipeline.hs
cc0-1.0
3,497
1
18
1,290
703
352
351
-1
-1
{-# LANGUAGE TemplateHaskell #-} module Rewriting.TRS.Apply where import qualified Rewriting.Apply as A import Rewriting.TRS import Type.Tree import Rewriting.Derive.Instance import Rewriting.TRS.Step import Rewriting.TRS.Steps {- import Rewriting.Derive.Quiz import Rewriting.Derive.Config -} import Autolib.Reporter import Autolib.ToDoc import Autolib.Reader {- import Autolib.FiniteMap import Challenger.Partial import Inter.Types import Inter.Quiz -} import Control.Monad import Data.Typeable data For_TRS = For_TRS deriving ( Eq, Ord, Typeable ) $(derives [makeReader, makeToDoc ] [''For_TRS]) instance A.Apply For_TRS ( TRS Identifier Identifier ) ( Term Identifier Identifier ) ( Step Identifier Identifier ) where example_object_of_size tag s = read "f(a,f(a,b))" -- FIXME example tag = Instance { system = Rewriting.TRS.example , derivation_restriction = Length GT 2 , from = Sized GT 0 , to = Fixed $ read "f(f(b,a),a)" } apply tag system object action = do exec system object action actions tag system object = steps system object -- local variables: -- mode: haskell -- end:
marcellussiegburg/autotool
collection/src/Rewriting/TRS/Apply.hs
gpl-2.0
1,234
0
9
292
268
150
118
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- The vim keymap. module Yi.Keymap.Vim ( keymapSet , mkKeymapSet , defVimConfig , VimBinding (..) , VimOperator (..) , VimConfig (..) , pureEval , impureEval , relayoutFromTo ) where import Data.Char (toUpper) import Data.List (find) import Data.Monoid ((<>)) import Data.Prototype (Proto (Proto), extractValue) import Yi.Buffer (commitUpdateTransactionB, startUpdateTransactionB) import Yi.Editor import Yi.Event (Event (..), Key (KASCII), Modifier (MCtrl, MMeta)) import Yi.Keymap (Keymap, KeymapM, KeymapSet, YiM, modelessKeymapSet, write) import Yi.Keymap.Keys (anyEvent) import Yi.Keymap.Vim.Common import Yi.Keymap.Vim.Digraph (defDigraphs) import Yi.Keymap.Vim.EventUtils (eventToEventString, parseEvents) import Yi.Keymap.Vim.Ex (ExCommand, defExCommandParsers) import Yi.Keymap.Vim.ExMap (defExMap) import Yi.Keymap.Vim.InsertMap (defInsertMap) import Yi.Keymap.Vim.NormalMap (defNormalMap) import Yi.Keymap.Vim.NormalOperatorPendingMap (defNormalOperatorPendingMap) import Yi.Keymap.Vim.Operator (VimOperator (..), defOperators) import Yi.Keymap.Vim.ReplaceMap (defReplaceMap) import Yi.Keymap.Vim.ReplaceSingleCharMap (defReplaceSingleMap) import Yi.Keymap.Vim.SearchMotionMap (defSearchMotionMap) import Yi.Keymap.Vim.StateUtils import Yi.Keymap.Vim.Utils (selectBinding, selectPureBinding) import Yi.Keymap.Vim.VisualMap (defVisualMap) data VimConfig = VimConfig { vimKeymap :: Keymap , vimBindings :: [VimBinding] , vimOperators :: [VimOperator] , vimExCommandParsers :: [EventString -> Maybe ExCommand] , vimDigraphs :: [(String, Char)] , vimRelayout :: Char -> Char } mkKeymapSet :: Proto VimConfig -> KeymapSet mkKeymapSet = modelessKeymapSet . vimKeymap . extractValue keymapSet :: KeymapSet keymapSet = mkKeymapSet defVimConfig defVimConfig :: Proto VimConfig defVimConfig = Proto $ \this -> VimConfig { vimKeymap = defVimKeymap this , vimBindings = concat [ defNormalMap (vimOperators this) , defNormalOperatorPendingMap (vimOperators this) , defExMap (vimExCommandParsers this) , defInsertMap (vimDigraphs this) , defReplaceSingleMap , defReplaceMap , defVisualMap (vimOperators this) , defSearchMotionMap ] , vimOperators = defOperators , vimExCommandParsers = defExCommandParsers , vimDigraphs = defDigraphs , vimRelayout = id } defVimKeymap :: VimConfig -> KeymapM () defVimKeymap config = do e <- anyEvent write $ impureHandleEvent config e True -- This is not in Yi.Keymap.Vim.Eval to avoid circular dependency: -- eval needs to know about bindings, which contains normal bindings, -- which contains '.', which needs to eval things -- So as a workaround '.' just saves a string that needs eval in VimState -- and the actual evaluation happens in impureHandleEvent pureEval :: VimConfig -> EventString -> EditorM () pureEval config = sequence_ . map (pureHandleEvent config) . parseEvents impureEval :: VimConfig -> EventString -> Bool -> YiM () impureEval config s needsToConvertEvents = sequence_ actions where actions = map (\e -> impureHandleEvent config e needsToConvertEvents) $ parseEvents s pureHandleEvent :: VimConfig -> Event -> EditorM () pureHandleEvent config ev = genericHandleEvent allPureBindings selectPureBinding config ev False impureHandleEvent :: VimConfig -> Event -> Bool -> YiM () impureHandleEvent = genericHandleEvent vimBindings selectBinding genericHandleEvent :: MonadEditor m => (VimConfig -> [VimBinding]) -> (EventString -> VimState -> [VimBinding] -> MatchResult (m RepeatToken)) -> VimConfig -> Event -> Bool -> m () genericHandleEvent getBindings pick config unconvertedEvent needsToConvertEvents = do currentState <- withEditor getEditorDyn let event = if needsToConvertEvents then convertEvent (vsMode currentState) (vimRelayout config) unconvertedEvent else unconvertedEvent evs = vsBindingAccumulator currentState <> eventToEventString event bindingMatch = pick evs currentState (getBindings config) prevMode = vsMode currentState case bindingMatch of NoMatch -> withEditor dropBindingAccumulatorE PartialMatch -> withEditor $ do accumulateBindingEventE event accumulateEventE event WholeMatch action -> do repeatToken <- action withEditor $ do dropBindingAccumulatorE accumulateEventE event case repeatToken of Drop -> do resetActiveRegisterE dropAccumulatorE Continue -> return () Finish -> do resetActiveRegisterE flushAccumulatorE withEditor $ do newMode <- vsMode <$> getEditorDyn -- TODO: we should introduce some hook mechanism like autocommands in vim case (prevMode, newMode) of (Insert _, Insert _) -> return () (Insert _, _) -> withCurrentBuffer commitUpdateTransactionB (_, Insert _) -> withCurrentBuffer startUpdateTransactionB _ -> return () performEvalIfNecessary config updateModeIndicatorE currentState performEvalIfNecessary :: VimConfig -> EditorM () performEvalIfNecessary config = do stateAfterAction <- getEditorDyn -- see comment for 'pureEval' modifyStateE $ \s -> s { vsStringToEval = mempty } pureEval config (vsStringToEval stateAfterAction) allPureBindings :: VimConfig -> [VimBinding] allPureBindings config = filter isPure $ vimBindings config where isPure (VimBindingE _) = True isPure _ = False convertEvent :: VimMode -> (Char -> Char) -> Event -> Event convertEvent (Insert _) f (Event (KASCII c) mods) | MCtrl `elem` mods || MMeta `elem` mods = Event (KASCII (f c)) mods convertEvent Ex _ e = e convertEvent (Insert _) _ e = e convertEvent InsertNormal _ e = e convertEvent InsertVisual _ e = e convertEvent Replace _ e = e convertEvent ReplaceSingleChar _ e = e convertEvent (Search _ _) _ e = e convertEvent _ f (Event (KASCII c) mods) = Event (KASCII (f c)) mods convertEvent _ _ e = e relayoutFromTo :: String -> String -> (Char -> Char) relayoutFromTo keysFrom keysTo = \c -> maybe c fst (find ((== c) . snd) (zip (keysTo ++ fmap toUpper' keysTo) (keysFrom ++ fmap toUpper' keysFrom))) where toUpper' ';' = ':' toUpper' a = toUpper a
ethercrow/yi
yi-keymap-vim/src/Yi/Keymap/Vim.hs
gpl-2.0
7,355
0
19
2,073
1,738
942
796
147
9
module Chap02.Suite where import Test.Framework (testGroup, Test) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.Framework.Providers.HUnit (testCase) import Chap02.Exercise01.Test import Chap02.Exercise05.Test {-import Chap02.Exercise06.Test-} import Chap02.Data.UnbalancedSet (UnbalancedSet) import Chap02.Data.UnbalancedSet2 (UnbalancedSet2, unC2E2) import Chap02.Data.UnbalancedSet3 (UnbalancedSet3, unC2E3) import Chap02.Data.UnbalancedSet4 (UnbalancedSet4, unC2E4) import Chap02.Data.Set.Test (testSet) import Chap02.Data.UnbalancedSet.Test (testBSTInv) chap02Suite :: Test chap02Suite = testGroup "Chapter 2" $ [ testGroup "Unbalanced set (default implementation)" $ testSet (undefined :: UnbalancedSet Int) ++ testBSTInv (id :: UnbalancedSet Int -> UnbalancedSet Int) , testGroup "Exercise 1" $ [ testCase "suffixes [1, 2, 3, 4] = [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4], []]" test_suffixes ] , testGroup "Exercise 2" $ testSet (undefined :: UnbalancedSet2 Int) ++ testBSTInv (unC2E2 :: UnbalancedSet2 Int -> UnbalancedSet Int) , testGroup "Exercise 3" $ testSet (undefined :: UnbalancedSet3 Int) ++ testBSTInv (unC2E3 :: UnbalancedSet3 Int -> UnbalancedSet Int) , testGroup "Exercise 4" $ testSet (undefined :: UnbalancedSet4 Int) ++ testBSTInv (unC2E4 :: UnbalancedSet4 Int -> UnbalancedSet Int) , testGroup "Exercise 5" $ [ testCase "complete yields a complete tree" test_CompleteIsComplete , testProperty "balance yields trees of correct size" prop_Sized , testProperty "balance yields balanced trees" prop_Balanced ] ]
stappit/okasaki-pfds
test/Chap02/Suite.hs
gpl-3.0
1,738
0
11
369
382
210
172
32
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Games.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Games.Types ( -- * Service Configuration gamesService -- * OAuth Scopes , plusLoginScope , gamesScope , driveAppDataScope -- * PlayersListCollection , PlayersListCollection (..) -- * RoomJoinRequest , RoomJoinRequest , roomJoinRequest , rjrNetworkDiagnostics , rjrKind , rjrClientAddress , rjrCapabilities -- * PlayerName , PlayerName , playerName , pnGivenName , pnFamilyName -- * Snapshot , Snapshot , snapshot , sLastModifiedMillis , sKind , sProgressValue , sUniqueName , sCoverImage , sId , sDurationMillis , sTitle , sType , sDescription , sDriveId -- * Room , Room , room , rStatus , rVariant , rKind , rAutoMatchingStatus , rCreationDetails , rInviterId , rLastUpdateDetails , rRoomStatusVersion , rParticipants , rApplicationId , rAutoMatchingCriteria , rRoomId , rDescription -- * QuestListResponse , QuestListResponse , questListResponse , qlrNextPageToken , qlrKind , qlrItems -- * TurnBasedMatch , TurnBasedMatch , turnBasedMatch , tbmStatus , tbmVariant , tbmResults , tbmMatchNumber , tbmKind , tbmData , tbmWithParticipantId , tbmCreationDetails , tbmInviterId , tbmLastUpdateDetails , tbmParticipants , tbmApplicationId , tbmAutoMatchingCriteria , tbmPreviousMatchData , tbmPendingParticipantId , tbmUserMatchStatus , tbmMatchId , tbmDescription , tbmRematchId , tbmMatchVersion -- * TurnBasedMatchData , TurnBasedMatchData , turnBasedMatchData , tbmdKind , tbmdData , tbmdDataAvailable -- * ScoresListCollection , ScoresListCollection (..) -- * PlayerEvent , PlayerEvent , playerEvent , peKind , peNumEvents , peFormattedNumEvents , peDefinitionId , pePlayerId -- * PlayerLeaderboardScore , PlayerLeaderboardScore , playerLeaderboardScore , plsScoreTag , plsScoreString , plsKind , plsScoreValue , plsTimeSpan , plsPublicRank , plsSocialRank , plsLeaderboardId , plsWriteTimestamp -- * Application , Application , application , aThemeColor , aLeaderboardCount , aKind , aCategory , aName , aEnabledFeatures , aInstances , aAuthor , aId , aAchievementCount , aAssets , aDescription , aLastUpdatedTimestamp -- * ApplicationCategory , ApplicationCategory , applicationCategory , acSecondary , acKind , acPrimary -- * PlayerScoreListResponse , PlayerScoreListResponse , playerScoreListResponse , pslrSubmittedScores , pslrKind -- * NetworkDiagnostics , NetworkDiagnostics , networkDiagnostics , ndAndroidNetworkType , ndKind , ndNetworkOperatorCode , ndNetworkOperatorName , ndRegistrationLatencyMillis , ndIosNetworkType , ndAndroidNetworkSubtype -- * TurnBasedMatchTurn , TurnBasedMatchTurn , turnBasedMatchTurn , tbmtResults , tbmtKind , tbmtData , tbmtPendingParticipantId , tbmtMatchVersion -- * QuestCriterion , QuestCriterion , questCriterion , qcCurrentContribution , qcCompletionContribution , qcKind , qcInitialPlayerProgress , qcEventId -- * TurnBasedMatchList , TurnBasedMatchList , turnBasedMatchList , tbmlNextPageToken , tbmlKind , tbmlItems -- * PeerChannelDiagnostics , PeerChannelDiagnostics , peerChannelDiagnostics , pcdNumMessagesLost , pcdBytesSent , pcdKind , pcdRoundtripLatencyMillis , pcdBytesReceived , pcdNumMessagesReceived , pcdNumSendFailures , pcdNumMessagesSent -- * RoomList , RoomList , roomList , rlNextPageToken , rlKind , rlItems -- * PushToken , PushToken , pushToken , ptClientRevision , ptKind , ptLanguage , ptId -- * AchievementUpdateResponse , AchievementUpdateResponse , achievementUpdateResponse , aurUpdateOccurred , aurAchievementId , aurKind , aurCurrentState , aurNewlyUnlocked , aurCurrentSteps -- * LeaderboardEntry , LeaderboardEntry , leaderboardEntry , leScoreTag , leWriteTimestampMillis , leKind , leScoreValue , leFormattedScore , leTimeSpan , leFormattedScoreRank , lePlayer , leScoreRank -- * SnapshotListResponse , SnapshotListResponse , snapshotListResponse , slrNextPageToken , slrKind , slrItems -- * PlayerLevel , PlayerLevel , playerLevel , plMaxExperiencePoints , plKind , plMinExperiencePoints , plLevel -- * AchievementUpdateMultipleResponse , AchievementUpdateMultipleResponse , achievementUpdateMultipleResponse , aumrKind , aumrUpdatedAchievements -- * RoomParticipant , RoomParticipant , roomParticipant , rpStatus , rpConnected , rpLeaveReason , rpKind , rpClientAddress , rpId , rpAutoMatched , rpPlayer , rpCapabilities , rpAutoMatchedPlayer -- * ApplicationsGetPlatformType , ApplicationsGetPlatformType (..) -- * EventDefinitionListResponse , EventDefinitionListResponse , eventDefinitionListResponse , edlrNextPageToken , edlrKind , edlrItems -- * Category , Category , category , cKind , cCategory , cExperiencePoints -- * InstanceAndroidDetails , InstanceAndroidDetails , instanceAndroidDetails , iadPackageName , iadPreferred , iadKind , iadEnablePiracyCheck -- * TurnBasedMatchParticipant , TurnBasedMatchParticipant , turnBasedMatchParticipant , tbmpStatus , tbmpKind , tbmpId , tbmpAutoMatched , tbmpPlayer , tbmpAutoMatchedPlayer -- * AchievementDefinitionsListResponse , AchievementDefinitionsListResponse , achievementDefinitionsListResponse , adlrNextPageToken , adlrKind , adlrItems -- * PlayerScoreResponse , PlayerScoreResponse , playerScoreResponse , psrScoreTag , psrKind , psrFormattedScore , psrLeaderboardId , psrBeatenScoreTimeSpans , psrUnbeatenScores -- * AnonymousPlayer , AnonymousPlayer , anonymousPlayer , apAvatarImageURL , apKind , apDisplayName -- * QuestContribution , QuestContribution , questContribution , qKind , qValue , qFormattedValue -- * RoomClientAddress , RoomClientAddress , roomClientAddress , rcaKind , rcaXmppAddress -- * LeaderboardListResponse , LeaderboardListResponse , leaderboardListResponse , llrNextPageToken , llrKind , llrItems -- * PlayerScore , PlayerScore , playerScore , psScoreTag , psScore , psKind , psFormattedScore , psTimeSpan -- * ScoresListWindowCollection , ScoresListWindowCollection (..) -- * TurnBasedAutoMatchingCriteria , TurnBasedAutoMatchingCriteria , turnBasedAutoMatchingCriteria , tbamcKind , tbamcExclusiveBitmask , tbamcMaxAutoMatchingPlayers , tbamcMinAutoMatchingPlayers -- * SnapshotImage , SnapshotImage , snapshotImage , siHeight , siKind , siURL , siMimeType , siWidth -- * RoomStatus , RoomStatus , roomStatus , rsStatus , rsKind , rsAutoMatchingStatus , rsStatusVersion , rsParticipants , rsRoomId -- * PlayerLeaderboardScoreListResponse , PlayerLeaderboardScoreListResponse , playerLeaderboardScoreListResponse , plslrNextPageToken , plslrKind , plslrItems , plslrPlayer -- * InstanceIosDetails , InstanceIosDetails , instanceIosDetails , iidItunesAppId , iidPreferredForIPad , iidSupportIPhone , iidKind , iidSupportIPad , iidPreferredForIPhone , iidBundleIdentifier -- * EventUpdateResponse , EventUpdateResponse , eventUpdateResponse , eurPlayerEvents , eurBatchFailures , eurEventFailures , eurKind -- * RevisionCheckResponse , RevisionCheckResponse , revisionCheckResponse , rcrAPIVersion , rcrKind , rcrRevisionStatus -- * ParticipantResult , ParticipantResult , participantResult , prParticipantId , prKind , prResult , prPlacing -- * Leaderboard , Leaderboard , leaderboard , lKind , lIsIconURLDefault , lName , lId , lIconURL , lOrder -- * MetagameConfig , MetagameConfig , metagameConfig , mcKind , mcCurrentVersion , mcPlayerLevels -- * CategoryListResponse , CategoryListResponse , categoryListResponse , clrNextPageToken , clrKind , clrItems -- * RoomP2PStatus , RoomP2PStatus , roomP2PStatus , rppsStatus , rppsParticipantId , rppsKind , rppsError , rppsErrorReason , rppsConnectionSetupLatencyMillis , rppsUnreliableRoundtripLatencyMillis -- * TurnBasedMatchModification , TurnBasedMatchModification , turnBasedMatchModification , tbmmParticipantId , tbmmKind , tbmmModifiedTimestampMillis -- * EventDefinition , EventDefinition , eventDefinition , edIsDefaultImageURL , edKind , edVisibility , edImageURL , edDisplayName , edId , edChildEvents , edDescription -- * RoomModification , RoomModification , roomModification , rmParticipantId , rmKind , rmModifiedTimestampMillis -- * ScoresListWindowTimeSpan , ScoresListWindowTimeSpan (..) -- * EventUpdateRequest , EventUpdateRequest , eventUpdateRequest , eUpdateCount , eKind , eDefinitionId -- * AchievementUnlockResponse , AchievementUnlockResponse , achievementUnlockResponse , achKind , achNewlyUnlocked -- * ScoresGetTimeSpan , ScoresGetTimeSpan (..) -- * PlayerAchievement , PlayerAchievement , playerAchievement , paKind , paAchievementState , paFormattedCurrentStepsString , paExperiencePoints , paId , paCurrentSteps , paLastUpdatedTimestamp -- * RoomP2PStatuses , RoomP2PStatuses , roomP2PStatuses , rppssKind , rppssUpdates -- * ImageAsset , ImageAsset , imageAsset , iaHeight , iaKind , iaURL , iaWidth , iaName -- * AchievementUpdateMultipleRequest , AchievementUpdateMultipleRequest , achievementUpdateMultipleRequest , aumruKind , aumruUpdates -- * RoomAutoMatchStatus , RoomAutoMatchStatus , roomAutoMatchStatus , ramsKind , ramsWaitEstimateSeconds -- * AchievementUpdateRequest , AchievementUpdateRequest , achievementUpdateRequest , auruAchievementId , auruKind , auruUpdateType , auruSetStepsAtLeastPayload , auruIncrementPayload -- * ScoresGetIncludeRankType , ScoresGetIncludeRankType (..) -- * LeaderboardScoreRank , LeaderboardScoreRank , leaderboardScoreRank , lsrNumScores , lsrKind , lsrFormattedRank , lsrFormattedNumScores , lsrRank -- * RoomCreateRequest , RoomCreateRequest , roomCreateRequest , rooRequestId , rooVariant , rooNetworkDiagnostics , rooKind , rooInvitedPlayerIds , rooClientAddress , rooAutoMatchingCriteria , rooCapabilities -- * PlayerListResponse , PlayerListResponse , playerListResponse , plrNextPageToken , plrKind , plrItems -- * LeaderboardScores , LeaderboardScores , leaderboardScores , lsNextPageToken , lsNumScores , lsKind , lsPlayerScore , lsItems , lsPrevPageToken -- * AchievementDefinition , AchievementDefinition , achievementDefinition , adAchievementType , adFormattedTotalSteps , adRevealedIconURL , adKind , adExperiencePoints , adInitialState , adName , adId , adIsUnlockedIconURLDefault , adTotalSteps , adDescription , adIsRevealedIconURLDefault , adUnlockedIconURL -- * TurnBasedMatchCreateRequest , TurnBasedMatchCreateRequest , turnBasedMatchCreateRequest , tbmcrRequestId , tbmcrVariant , tbmcrKind , tbmcrInvitedPlayerIds , tbmcrAutoMatchingCriteria -- * EventBatchRecordFailure , EventBatchRecordFailure , eventBatchRecordFailure , ebrfKind , ebrfRange , ebrfFailureCause -- * TurnBasedMatchResults , TurnBasedMatchResults , turnBasedMatchResults , tbmrResults , tbmrKind , tbmrData , tbmrMatchVersion -- * PushTokenIdIos , PushTokenIdIos , pushTokenIdIos , ptiiAPNSDeviceToken , ptiiAPNSEnvironment -- * RoomLeaveRequest , RoomLeaveRequest , roomLeaveRequest , rlrKind , rlrReason , rlrLeaveDiagnostics -- * Played , Played , played , pKind , pAutoMatched , pTimeMillis -- * AchievementIncrementResponse , AchievementIncrementResponse , achievementIncrementResponse , airKind , airNewlyUnlocked , airCurrentSteps -- * AchievementRevealResponse , AchievementRevealResponse , achievementRevealResponse , arrKind , arrCurrentState -- * AchievementSetStepsAtLeastResponse , AchievementSetStepsAtLeastResponse , achievementSetStepsAtLeastResponse , assalrKind , assalrNewlyUnlocked , assalrCurrentSteps -- * PlayerAchievementListResponse , PlayerAchievementListResponse , playerAchievementListResponse , palrNextPageToken , palrKind , palrItems -- * EventRecordRequest , EventRecordRequest , eventRecordRequest , errRequestId , errKind , errCurrentTimeMillis , errTimePeriods -- * RoomAutoMatchingCriteria , RoomAutoMatchingCriteria , roomAutoMatchingCriteria , ramcKind , ramcExclusiveBitmask , ramcMaxAutoMatchingPlayers , ramcMinAutoMatchingPlayers -- * ScoresListTimeSpan , ScoresListTimeSpan (..) -- * QuestMilestone , QuestMilestone , questMilestone , qmState , qmKind , qmId , qmCompletionRewardData , qmCriteria -- * PeerSessionDiagnostics , PeerSessionDiagnostics , peerSessionDiagnostics , psdConnectedTimestampMillis , psdParticipantId , psdKind , psdUnreliableChannel , psdReliableChannel -- * PushTokenId , PushTokenId , pushTokenId , ptiIos , ptiKind -- * EventPeriodUpdate , EventPeriodUpdate , eventPeriodUpdate , epuKind , epuTimePeriod , epuUpdates -- * TurnBasedMatchSync , TurnBasedMatchSync , turnBasedMatchSync , tbmsMoreAvailable , tbmsNextPageToken , tbmsKind , tbmsItems -- * ScoreSubmission , ScoreSubmission , scoreSubmission , scoSignature , scoScoreTag , scoScore , scoKind , scoLeaderboardId -- * RoomLeaveDiagnostics , RoomLeaveDiagnostics , roomLeaveDiagnostics , rldPeerSession , rldAndroidNetworkType , rldKind , rldNetworkOperatorCode , rldNetworkOperatorName , rldSocketsUsed , rldIosNetworkType , rldAndroidNetworkSubtype -- * AggregateStats , AggregateStats , aggregateStats , asMax , asKind , asCount , asMin , asSum -- * InstanceWebDetails , InstanceWebDetails , instanceWebDetails , iwdPreferred , iwdKind , iwdLaunchURL -- * TurnBasedMatchRematch , TurnBasedMatchRematch , turnBasedMatchRematch , tRematch , tKind , tPreviousMatch -- * PlayerExperienceInfo , PlayerExperienceInfo , playerExperienceInfo , peiKind , peiCurrentExperiencePoints , peiCurrentLevel , peiNextLevel , peiLastLevelUpTimestampMillis -- * GamesAchievementSetStepsAtLeast , GamesAchievementSetStepsAtLeast , gamesAchievementSetStepsAtLeast , gassalKind , gassalSteps -- * Player , Player , player , plaBannerURLLandscape , plaLastPlayedWith , plaAvatarImageURL , plaKind , plaExperienceInfo , plaName , plaOriginalPlayerId , plaDisplayName , plaTitle , plaBannerURLPortrait , plaPlayerId , plaProFileSettings -- * GamesAchievementIncrement , GamesAchievementIncrement , gamesAchievementIncrement , gaiRequestId , gaiKind , gaiSteps -- * Quest , Quest , quest , queLastUpdatedTimestampMillis , queBannerURL , queState , queMilestones , queKind , queApplicationId , queEndTimestampMillis , queName , queId , queIconURL , queStartTimestampMillis , queNotifyTimestampMillis , queDescription , queIsDefaultBannerURL , queIsDefaultIconURL , queAcceptedTimestampMillis -- * EventChild , EventChild , eventChild , ecKind , ecChildId -- * ApplicationVerifyResponse , ApplicationVerifyResponse , applicationVerifyResponse , avrKind , avrAlternatePlayerId , avrPlayerId -- * PlayerEventListResponse , PlayerEventListResponse , playerEventListResponse , pelrNextPageToken , pelrKind , pelrItems -- * TurnBasedMatchDataRequest , TurnBasedMatchDataRequest , turnBasedMatchDataRequest , tbmdrKind , tbmdrData -- * ProFileSettings , ProFileSettings , proFileSettings , pfsProFileVisible , pfsKind -- * EventPeriodRange , EventPeriodRange , eventPeriodRange , eprKind , eprPeriodStartMillis , eprPeriodEndMillis -- * MetagameListCategoriesByPlayerCollection , MetagameListCategoriesByPlayerCollection (..) -- * AchievementsListState , AchievementsListState (..) -- * EventRecordFailure , EventRecordFailure , eventRecordFailure , erfKind , erfFailureCause , erfEventId -- * PlayerScoreSubmissionList , PlayerScoreSubmissionList , playerScoreSubmissionList , psslKind , psslScores -- * Instance , Instance , instance' , iAndroidInstance , iKind , iWebInstance , iIosInstance , iName , iAcquisitionURI , iPlatformType , iTurnBasedPlay , iRealtimePlay ) where import Network.Google.Games.Types.Product import Network.Google.Games.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v1' of the Google Play Game Services API. This contains the host and root path used as a starting point for constructing service requests. gamesService :: ServiceConfig gamesService = defaultService (ServiceId "games:v1") "www.googleapis.com" -- | Know the list of people in your circles, your age range, and language plusLoginScope :: Proxy '["https://www.googleapis.com/auth/plus.login"] plusLoginScope = Proxy; -- | Share your Google+ profile information and view and manage your game -- activity gamesScope :: Proxy '["https://www.googleapis.com/auth/games"] gamesScope = Proxy; -- | View and manage its own configuration data in your Google Drive driveAppDataScope :: Proxy '["https://www.googleapis.com/auth/drive.appdata"] driveAppDataScope = Proxy;
rueshyna/gogol
gogol-games/gen/Network/Google/Games/Types.hs
mpl-2.0
19,898
0
7
5,332
2,363
1,616
747
715
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.Logging.Folders.Sinks.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists sinks. -- -- /See:/ <https://cloud.google.com/logging/docs/ Stackdriver Logging API Reference> for @logging.folders.sinks.list@. module Network.Google.Resource.Logging.Folders.Sinks.List ( -- * REST Resource FoldersSinksListResource -- * Creating a Request , foldersSinksList , FoldersSinksList -- * Request Lenses , fslParent , fslXgafv , fslUploadProtocol , fslPp , fslAccessToken , fslUploadType , fslBearerToken , fslPageToken , fslPageSize , fslCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.folders.sinks.list@ method which the -- 'FoldersSinksList' request conforms to. type FoldersSinksListResource = "v2" :> Capture "parent" Text :> "sinks" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListSinksResponse -- | Lists sinks. -- -- /See:/ 'foldersSinksList' smart constructor. data FoldersSinksList = FoldersSinksList' { _fslParent :: !Text , _fslXgafv :: !(Maybe Xgafv) , _fslUploadProtocol :: !(Maybe Text) , _fslPp :: !Bool , _fslAccessToken :: !(Maybe Text) , _fslUploadType :: !(Maybe Text) , _fslBearerToken :: !(Maybe Text) , _fslPageToken :: !(Maybe Text) , _fslPageSize :: !(Maybe (Textual Int32)) , _fslCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'FoldersSinksList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fslParent' -- -- * 'fslXgafv' -- -- * 'fslUploadProtocol' -- -- * 'fslPp' -- -- * 'fslAccessToken' -- -- * 'fslUploadType' -- -- * 'fslBearerToken' -- -- * 'fslPageToken' -- -- * 'fslPageSize' -- -- * 'fslCallback' foldersSinksList :: Text -- ^ 'fslParent' -> FoldersSinksList foldersSinksList pFslParent_ = FoldersSinksList' { _fslParent = pFslParent_ , _fslXgafv = Nothing , _fslUploadProtocol = Nothing , _fslPp = True , _fslAccessToken = Nothing , _fslUploadType = Nothing , _fslBearerToken = Nothing , _fslPageToken = Nothing , _fslPageSize = Nothing , _fslCallback = Nothing } -- | Required. The parent resource whose sinks are to be listed. Examples: -- \"projects\/my-logging-project\", \"organizations\/123456789\". fslParent :: Lens' FoldersSinksList Text fslParent = lens _fslParent (\ s a -> s{_fslParent = a}) -- | V1 error format. fslXgafv :: Lens' FoldersSinksList (Maybe Xgafv) fslXgafv = lens _fslXgafv (\ s a -> s{_fslXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). fslUploadProtocol :: Lens' FoldersSinksList (Maybe Text) fslUploadProtocol = lens _fslUploadProtocol (\ s a -> s{_fslUploadProtocol = a}) -- | Pretty-print response. fslPp :: Lens' FoldersSinksList Bool fslPp = lens _fslPp (\ s a -> s{_fslPp = a}) -- | OAuth access token. fslAccessToken :: Lens' FoldersSinksList (Maybe Text) fslAccessToken = lens _fslAccessToken (\ s a -> s{_fslAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). fslUploadType :: Lens' FoldersSinksList (Maybe Text) fslUploadType = lens _fslUploadType (\ s a -> s{_fslUploadType = a}) -- | OAuth bearer token. fslBearerToken :: Lens' FoldersSinksList (Maybe Text) fslBearerToken = lens _fslBearerToken (\ s a -> s{_fslBearerToken = a}) -- | Optional. If present, then retrieve the next batch of results from the -- preceding call to this method. pageToken must be the value of -- nextPageToken from the previous response. The values of other method -- parameters should be identical to those in the previous call. fslPageToken :: Lens' FoldersSinksList (Maybe Text) fslPageToken = lens _fslPageToken (\ s a -> s{_fslPageToken = a}) -- | Optional. The maximum number of results to return from this request. -- Non-positive values are ignored. The presence of nextPageToken in the -- response indicates that more results might be available. fslPageSize :: Lens' FoldersSinksList (Maybe Int32) fslPageSize = lens _fslPageSize (\ s a -> s{_fslPageSize = a}) . mapping _Coerce -- | JSONP fslCallback :: Lens' FoldersSinksList (Maybe Text) fslCallback = lens _fslCallback (\ s a -> s{_fslCallback = a}) instance GoogleRequest FoldersSinksList where type Rs FoldersSinksList = ListSinksResponse type Scopes FoldersSinksList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/logging.admin", "https://www.googleapis.com/auth/logging.read"] requestClient FoldersSinksList'{..} = go _fslParent _fslXgafv _fslUploadProtocol (Just _fslPp) _fslAccessToken _fslUploadType _fslBearerToken _fslPageToken _fslPageSize _fslCallback (Just AltJSON) loggingService where go = buildClient (Proxy :: Proxy FoldersSinksListResource) mempty
rueshyna/gogol
gogol-logging/gen/Network/Google/Resource/Logging/Folders/Sinks/List.hs
mpl-2.0
6,591
0
20
1,668
1,047
606
441
146
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.Container.Projects.Zones.Clusters.NodePools.SetManagement -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the NodeManagement options for a node pool. -- -- /See:/ <https://cloud.google.com/container-engine/ Kubernetes Engine API Reference> for @container.projects.zones.clusters.nodePools.setManagement@. module Network.Google.Resource.Container.Projects.Zones.Clusters.NodePools.SetManagement ( -- * REST Resource ProjectsZonesClustersNodePoolsSetManagementResource -- * Creating a Request , projectsZonesClustersNodePoolsSetManagement , ProjectsZonesClustersNodePoolsSetManagement -- * Request Lenses , pzcnpsmXgafv , pzcnpsmUploadProtocol , pzcnpsmAccessToken , pzcnpsmUploadType , pzcnpsmZone , pzcnpsmPayload , pzcnpsmNodePoolId , pzcnpsmClusterId , pzcnpsmProjectId , pzcnpsmCallback ) where import Network.Google.Container.Types import Network.Google.Prelude -- | A resource alias for @container.projects.zones.clusters.nodePools.setManagement@ method which the -- 'ProjectsZonesClustersNodePoolsSetManagement' request conforms to. type ProjectsZonesClustersNodePoolsSetManagementResource = "v1" :> "projects" :> Capture "projectId" Text :> "zones" :> Capture "zone" Text :> "clusters" :> Capture "clusterId" Text :> "nodePools" :> Capture "nodePoolId" Text :> "setManagement" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetNodePoolManagementRequest :> Post '[JSON] Operation -- | Sets the NodeManagement options for a node pool. -- -- /See:/ 'projectsZonesClustersNodePoolsSetManagement' smart constructor. data ProjectsZonesClustersNodePoolsSetManagement = ProjectsZonesClustersNodePoolsSetManagement' { _pzcnpsmXgafv :: !(Maybe Xgafv) , _pzcnpsmUploadProtocol :: !(Maybe Text) , _pzcnpsmAccessToken :: !(Maybe Text) , _pzcnpsmUploadType :: !(Maybe Text) , _pzcnpsmZone :: !Text , _pzcnpsmPayload :: !SetNodePoolManagementRequest , _pzcnpsmNodePoolId :: !Text , _pzcnpsmClusterId :: !Text , _pzcnpsmProjectId :: !Text , _pzcnpsmCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsZonesClustersNodePoolsSetManagement' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pzcnpsmXgafv' -- -- * 'pzcnpsmUploadProtocol' -- -- * 'pzcnpsmAccessToken' -- -- * 'pzcnpsmUploadType' -- -- * 'pzcnpsmZone' -- -- * 'pzcnpsmPayload' -- -- * 'pzcnpsmNodePoolId' -- -- * 'pzcnpsmClusterId' -- -- * 'pzcnpsmProjectId' -- -- * 'pzcnpsmCallback' projectsZonesClustersNodePoolsSetManagement :: Text -- ^ 'pzcnpsmZone' -> SetNodePoolManagementRequest -- ^ 'pzcnpsmPayload' -> Text -- ^ 'pzcnpsmNodePoolId' -> Text -- ^ 'pzcnpsmClusterId' -> Text -- ^ 'pzcnpsmProjectId' -> ProjectsZonesClustersNodePoolsSetManagement projectsZonesClustersNodePoolsSetManagement pPzcnpsmZone_ pPzcnpsmPayload_ pPzcnpsmNodePoolId_ pPzcnpsmClusterId_ pPzcnpsmProjectId_ = ProjectsZonesClustersNodePoolsSetManagement' { _pzcnpsmXgafv = Nothing , _pzcnpsmUploadProtocol = Nothing , _pzcnpsmAccessToken = Nothing , _pzcnpsmUploadType = Nothing , _pzcnpsmZone = pPzcnpsmZone_ , _pzcnpsmPayload = pPzcnpsmPayload_ , _pzcnpsmNodePoolId = pPzcnpsmNodePoolId_ , _pzcnpsmClusterId = pPzcnpsmClusterId_ , _pzcnpsmProjectId = pPzcnpsmProjectId_ , _pzcnpsmCallback = Nothing } -- | V1 error format. pzcnpsmXgafv :: Lens' ProjectsZonesClustersNodePoolsSetManagement (Maybe Xgafv) pzcnpsmXgafv = lens _pzcnpsmXgafv (\ s a -> s{_pzcnpsmXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pzcnpsmUploadProtocol :: Lens' ProjectsZonesClustersNodePoolsSetManagement (Maybe Text) pzcnpsmUploadProtocol = lens _pzcnpsmUploadProtocol (\ s a -> s{_pzcnpsmUploadProtocol = a}) -- | OAuth access token. pzcnpsmAccessToken :: Lens' ProjectsZonesClustersNodePoolsSetManagement (Maybe Text) pzcnpsmAccessToken = lens _pzcnpsmAccessToken (\ s a -> s{_pzcnpsmAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pzcnpsmUploadType :: Lens' ProjectsZonesClustersNodePoolsSetManagement (Maybe Text) pzcnpsmUploadType = lens _pzcnpsmUploadType (\ s a -> s{_pzcnpsmUploadType = a}) -- | Deprecated. The name of the Google Compute Engine -- [zone](https:\/\/cloud.google.com\/compute\/docs\/zones#available) in -- which the cluster resides. This field has been deprecated and replaced -- by the name field. pzcnpsmZone :: Lens' ProjectsZonesClustersNodePoolsSetManagement Text pzcnpsmZone = lens _pzcnpsmZone (\ s a -> s{_pzcnpsmZone = a}) -- | Multipart request metadata. pzcnpsmPayload :: Lens' ProjectsZonesClustersNodePoolsSetManagement SetNodePoolManagementRequest pzcnpsmPayload = lens _pzcnpsmPayload (\ s a -> s{_pzcnpsmPayload = a}) -- | Deprecated. The name of the node pool to update. This field has been -- deprecated and replaced by the name field. pzcnpsmNodePoolId :: Lens' ProjectsZonesClustersNodePoolsSetManagement Text pzcnpsmNodePoolId = lens _pzcnpsmNodePoolId (\ s a -> s{_pzcnpsmNodePoolId = a}) -- | Deprecated. The name of the cluster to update. This field has been -- deprecated and replaced by the name field. pzcnpsmClusterId :: Lens' ProjectsZonesClustersNodePoolsSetManagement Text pzcnpsmClusterId = lens _pzcnpsmClusterId (\ s a -> s{_pzcnpsmClusterId = a}) -- | Deprecated. The Google Developers Console [project ID or project -- number](https:\/\/support.google.com\/cloud\/answer\/6158840). This -- field has been deprecated and replaced by the name field. pzcnpsmProjectId :: Lens' ProjectsZonesClustersNodePoolsSetManagement Text pzcnpsmProjectId = lens _pzcnpsmProjectId (\ s a -> s{_pzcnpsmProjectId = a}) -- | JSONP pzcnpsmCallback :: Lens' ProjectsZonesClustersNodePoolsSetManagement (Maybe Text) pzcnpsmCallback = lens _pzcnpsmCallback (\ s a -> s{_pzcnpsmCallback = a}) instance GoogleRequest ProjectsZonesClustersNodePoolsSetManagement where type Rs ProjectsZonesClustersNodePoolsSetManagement = Operation type Scopes ProjectsZonesClustersNodePoolsSetManagement = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsZonesClustersNodePoolsSetManagement'{..} = go _pzcnpsmProjectId _pzcnpsmZone _pzcnpsmClusterId _pzcnpsmNodePoolId _pzcnpsmXgafv _pzcnpsmUploadProtocol _pzcnpsmAccessToken _pzcnpsmUploadType _pzcnpsmCallback (Just AltJSON) _pzcnpsmPayload containerService where go = buildClient (Proxy :: Proxy ProjectsZonesClustersNodePoolsSetManagementResource) mempty
brendanhay/gogol
gogol-container/gen/Network/Google/Resource/Container/Projects/Zones/Clusters/NodePools/SetManagement.hs
mpl-2.0
8,308
0
24
1,919
1,029
600
429
164
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Kubernetes.V1.Capabilities where import GHC.Generics import Kubernetes.V1.Capability import qualified Data.Aeson -- | Adds and removes POSIX capabilities from running containers. data Capabilities = Capabilities { add :: Maybe [Capability] -- ^ Added capabilities , drop :: Maybe [Capability] -- ^ Removed capabilities } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON Capabilities instance Data.Aeson.ToJSON Capabilities
minhdoboi/deprecated-openshift-haskell-api
kubernetes/lib/Kubernetes/V1/Capabilities.hs
apache-2.0
625
0
10
91
100
61
39
15
0
import Data.Char ary = ["abcde","fghij","klmno","pqrst","uvwxy","z.?! "] ans [] = Just [] ans (a:[]) = Nothing ans (a:b:s) = let c = if (a <= 0 || a > 6) || (b <= 0 || b > 5) then Nothing else Just ((ary!!(a-1))!!(b-1)) r = ans s in if c == Nothing || r == Nothing then Nothing else let Just c' = c Just r' = r in Just (c':r') ans' x = let r = ans x in if r == Nothing then "NA" else let Just v = r in v main = do c <- getContents let i = map (map digitToInt) $ lines c :: [[Int]] o = map ans' i mapM_ putStrLn o
a143753/AOJ
0127.hs
apache-2.0
638
0
16
243
339
173
166
25
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- | -- Module : Credentials.DynamoDB -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- -- Provides the implementation for storage and retrieval of encrypted credentials -- in DynamoDB. The encryption and decryption is handled by "Credentials.KMS". -- -- See the "Credentials" module for usage information. module Credentials.DynamoDB ( -- * Table DynamoTable (..) , defaultTable -- * Operations , insert , select , delete , truncate , revisions , setup , teardown ) where import Prelude hiding (truncate) import Control.Exception.Lens import Control.Lens hiding (Context) import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Retry import Credentials.DynamoDB.Item import Credentials.KMS as KMS import Credentials.Types import Crypto.Hash (Digest, SHA1) import Data.ByteArray.Encoding import Data.ByteString (ByteString) import Data.Conduit hiding (await) import Data.List.NonEmpty (NonEmpty (..)) import Data.Maybe import Data.Monoid ((<>)) import Data.Ord import Data.Text (Text) import Data.Time.Clock.POSIX import Data.Typeable import Network.AWS import Network.AWS.Data import Network.AWS.DynamoDB import qualified Crypto.Hash as Crypto import qualified Data.ByteString as BS import qualified Data.Conduit as C import qualified Data.Conduit.List as CL import qualified Data.HashMap.Strict as Map import qualified Data.List.NonEmpty as NE -- | A DynamoDB table reference. newtype DynamoTable = DynamoTable { tableName :: Text } deriving (Eq, Ord, Show, FromText, ToText, ToByteString, ToLog) -- | The default DynamoDB table used to store credentials. -- -- /Value:/ @credentials@ defaultTable :: DynamoTable defaultTable = DynamoTable "credentials" -- | Encrypt and insert a new credential revision with the specified name. -- -- The newly inserted revision is returned. insert :: (MonadMask m, MonadAWS m, Typeable m) => KeyId -- ^ The KMS master key ARN or alias. -> Context -- ^ The KMS encryption context. -> Name -- ^ The credential name. -> ByteString -- ^ The unencrypted plaintext. -> DynamoTable -- ^ The DynamoDB table. -> m Revision insert key ctx name plaintext table = do ciphertext <- encrypt key ctx name plaintext catchResourceNotFound table (insertEncrypted name ciphertext table) -- | Select an existing credential, optionally specifying the revision. -- -- The decrypted plaintext and selected revision are returned. select :: MonadAWS m => Context -- ^ The KMS encryption context that was used during insertion. -> Name -- ^ The credential name. -> Maybe Revision -- ^ A revision. If 'Nothing', the latest will be selected. -> DynamoTable -- ^ The DynamoDB table. -> m (ByteString, Revision) select ctx name rev table = do (_, (ciphertext, rev')) <- catchResourceNotFound table (selectEncrypted name rev table) (,rev') <$> decrypt ctx name ciphertext -- | Delete the specific credential revision. delete :: MonadAWS m => Name -- ^ The credential name. -> Revision -- ^ The revision to delete. -> DynamoTable -- ^ The DynamoDB table. -> m () delete name rev table@DynamoTable{..} = catchResourceNotFound table $ do (ver, _) <- selectEncrypted name (Just rev) table void . send $ deleteItem tableName & diKey .~ toItem name <> toItem ver -- | Truncate all of a credential's revisions, so that only -- the latest revision remains. truncate :: MonadAWS m => Name -- ^ The credential name. -> DynamoTable -- ^ The DynamoDB table. -> m () truncate name table@DynamoTable{..} = catchResourceNotFound table $ queryAll $$ CL.mapM_ (deleteMany . view qrsItems) where queryAll = paginate $ queryByName name table & qAttributesToGet ?~ nameField :| [versionField] & qScanIndexForward ?~ True & qLimit ?~ batchSize deleteMany [] = pure () deleteMany (x:xs) = void . send $ batchWriteItem & bwiRequestItems .~ [ (tableName, deleteKey x :| map deleteKey (batchInit xs)) ] deleteKey k = writeRequest & wrDeleteRequest ?~ (deleteRequest & drKey .~ k) batchInit xs | i < n = take (i - 1) xs | otherwise = xs where n = fromIntegral (batchSize - 1) i = length xs batchSize = 50 -- | Scan the entire credential database, grouping pages of results into -- unique credential names and their corresponding revisions. revisions :: MonadAWS m => DynamoTable -- ^ The DynamoDB table. -> Source m (Name, NonEmpty Revision) revisions table = catchResourceNotFound table $ paginate (scanTable table) =$= CL.concatMapM (traverse fromItem . view srsItems) =$= CL.groupOn1 fst =$= CL.map group where group ((name, rev), revs) = (name, desc (rev :| map snd revs)) desc :: NonEmpty (Version, Revision) -> NonEmpty Revision desc = NE.map snd . NE.sortWith (Down . fst) -- | Create the credentials database table. -- -- The returned idempotency flag can be used to notify configuration -- management tools such as ansible whether about system state. setup :: MonadAWS m => DynamoTable -- ^ The DynamoDB table. -> m Setup setup table@DynamoTable{..} = do p <- exists table unless p $ do let iops = provisionedThroughput 1 1 keys = keySchemaElement nameField Hash :| [keySchemaElement versionField Range] attr = ctAttributeDefinitions .~ [ attributeDefinition nameField S , attributeDefinition versionField S , attributeDefinition revisionField B ] -- FIXME: Only non-key attributes need to be specified -- in the non-key attributes .. duh. secn = ctLocalSecondaryIndexes .~ [ localSecondaryIndex revisionField (keySchemaElement nameField Hash :| [keySchemaElement revisionField Range]) (projection & pProjectionType ?~ All) ] void $ send (createTable tableName keys iops & attr & secn) void $ await tableExists (describeTable tableName) pure $ if p then Exists else Created -- | Delete the credentials database table and all data. -- -- /Note:/ Unless you have DynamoDB backups running, this is a completely -- irrevocable action. teardown :: MonadAWS m => DynamoTable -> m () teardown table@DynamoTable{..} = do p <- exists table when p $ do void $ send (deleteTable tableName) void $ await tableNotExists (describeTable tableName) insertEncrypted :: (MonadMask m, MonadAWS m, Typeable m) => Name -> Encrypted -> DynamoTable -> m Revision insertEncrypted name encrypted table@DynamoTable{..} = recovering policy [const cond] write where write = const $ do ver <- maybe 1 (+1) <$> latest name table rev <- genRevision ver void . send $ putItem tableName & piExpected .~ Map.map (const expect) (toItem ver <> toItem rev) & piItem .~ toItem name <> toItem ver <> toItem rev <> toItem encrypted pure rev cond = handler_ _ConditionalCheckFailedException (pure True) expect = expectedAttributeValue & eavExists ?~ False policy = constantDelay 1000 <> limitRetries 5 selectEncrypted :: (MonadThrow m, MonadAWS m) => Name -> Maybe Revision -> DynamoTable -> m (Version, (Encrypted, Revision)) selectEncrypted name rev table@DynamoTable{..} = send (queryByName name table & revision rev) >>= result where result = maybe missing fromItem . listToMaybe . view qrsItems missing = throwM $ SecretMissing name rev tableName -- If revision is specified, the revision index is used and -- a consistent read is done. revision Nothing = id revision (Just r) = (qIndexName ?~ revisionField) . (qKeyConditions <>~ equals r) . (qConsistentRead ?~ True) latest :: (MonadThrow m, MonadAWS m) => Name -> DynamoTable -> m (Maybe Version) latest name table = do rs <- send (queryByName name table & qConsistentRead ?~ True) case listToMaybe (rs ^. qrsItems) of Nothing -> pure Nothing Just m -> Just <$> fromItem m exists :: MonadAWS m => DynamoTable -> m Bool exists DynamoTable{..} = paginate listTables =$= CL.concatMap (view ltrsTableNames) $$ (isJust <$> findC (== tableName)) scanTable :: DynamoTable -> Scan scanTable DynamoTable{..} = scan tableName & sAttributesToGet ?~ nameField :| [versionField, revisionField] queryByName :: Name -> DynamoTable -> Query queryByName name DynamoTable{..} = query tableName & qLimit ?~ 1 & qScanIndexForward ?~ False & qConsistentRead ?~ False & qKeyConditions .~ equals name genRevision :: MonadIO m => Version -> m Revision genRevision (Version ver) = do ts <- liftIO getPOSIXTime let d = Crypto.hash (toBS (show ts) <> toBS ver) :: Digest SHA1 r = BS.take 7 (convertToBase Base16 d) pure $! Revision r findC :: Monad m => (a -> Bool) -> Consumer a m (Maybe a) findC f = loop where loop = C.await >>= maybe (pure Nothing) go go x | f x = pure (Just x) | otherwise = loop -- FIXME: Over specified due to the coarseness of _ResourceNotFound. catchResourceNotFound :: MonadCatch m => DynamoTable -> m b -> m b catchResourceNotFound DynamoTable{..} = handling_ _ResourceNotFoundException $ throwM $ StorageMissing ("Table " <> tableName <> " doesn't exist.")
brendanhay/credentials
credentials/src/Credentials/DynamoDB.hs
apache-2.0
10,802
0
19
3,081
2,528
1,324
1,204
227
2
-- starman.hs check :: String -> String -> Char -> (Bool, String) check word display c = (c `elem` word, [if x==c then c else y | (x,y) <- zip word display]) turn :: String -> String -> Int -> IO () turn word display n = do putStrLn ("Word: " ++ display ++ " " ++ "Tries: " ++ take n (repeat '*')) if n==0 then putStrLn "You lose." else if word==display then putStrLn "You win!" else mkguess word display n mkguess :: String -> String -> Int -> IO () mkguess word display n = do putStr "Enter your guess: " q <- getLine putStrLn "" let (correct, display') = check word display ((q ++ "_")!!0) let n' = if correct then n else n-1 turn word display' n' starman :: String -> Int -> IO () starman word n = turn word ['-' | x <- word] n
romanegunkov/to-learn
haskell/futurelearn/starman.hs
apache-2.0
876
0
14
295
360
182
178
24
3
module Eval ( eval , evalFlat , evalProgram , evalProgramFlat , uidStreamStart , nextUidFromStream , Result (Normal, Failure) , FailureCause (UnboundVariable, AbsentNonLocal, CircularReference) , FlatValue (FlatNull, FlatBool, FlatInt, FlatStr, FlatInstance, FlatHook) ) where import qualified Value as V import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.List as List import qualified Data.Maybe as Maybe import qualified Method as M import Debug.Trace -- A stream of ids. data UidStream = UidStream Int deriving (Show) -- Returns the next uid from the given stream along with a new stream which is -- guaranteed to never return the uid just returned. nextUidFromStream (UidStream n) = (V.Uid n, UidStream (n + 1)) -- Returns a new fresh uid stream. uidStreamStart = UidStream 0 type ValueLog = [V.Value] -- The pervasive, non-scoped, state. This flows linearly through the evaluation -- independent of scope and control flow -- for instance, leaving a scope can -- restore a previous scope state but nothing can restore a previous pervasive -- state. data PervasiveState hier = PervasiveState { -- The uid stream used for generating identity. uids :: UidStream, -- Object state. objects :: Map.Map V.Uid (V.ObjectState hier), -- The log used for testing evaluation order. valueLog :: ValueLog } deriving (Show) -- A completely empty pervasive state with no objects or state at all. emptyPervasiveState = PervasiveState { uids = uidStreamStart, objects = Map.empty, valueLog = [] } -- Given a pervasive state, returns a fresh object id and a new pervasive state -- to use from that point on. genUid s0 = (uid, s1) where uids0 = uids s0 (uid, uids1) = nextUidFromStream uids0 s1 = s0 {uids = uids1} -- The possible reasons for evaluation to fail. data FailureCause = AbsentNonLocal | ExprNotUnderstood V.Expr | MethodNotUnderstood [(V.Value, V.Value)] | UnboundVariable V.Value | UnknownCall V.Value String [V.Value] | CircularReference V.Value deriving (Show, Eq) -- The result of an evaluation. data Result val fail = Normal val | Failure FailureCause fail deriving (Show) -- A local continuation, the next step during normal evaluation. Continuations -- always continue in the scope they captured when they were created whereas the -- pervasive state is always passed in. type Continuation hier = V.Value -> PervasiveState hier -> Result (V.Value, PervasiveState hier) (PervasiveState hier) endContinuation v p = Normal (v, p) -- Dynamically scoped state, that is, state that propagats from caller to -- callee but not the other way. data DynamicState hier = DynamicState { -- The top nonlocal continuation. nonlocal :: V.Uid -> Continuation hier } absentNonlocal _ _ p0 = (Failure AbsentNonLocal p0) -- Initial empty dynamic state. emptyDynamicState = DynamicState { nonlocal = absentNonlocal } hookScope = Map.fromList ( [ (V.Str "log", V.Hook V.LogHook) , (V.Str "type", V.Hook V.TypeHook) ]) -- Initial empty lexical state. emptyLexicalState methodspace namespace = V.LexicalState { V.scope = hookScope, V.methodspace = methodspace, V.namespace = namespace } -- The complete context state at a particular point in the evaluation. data CompleteState hier = CompleteState { lexical :: V.LexicalState hier, dynamic :: DynamicState hier, pervasive :: PervasiveState hier } -- Initial empty version of the complete evaluation state. emptyCompleteState behavior = CompleteState { lexical = emptyLexicalState behavior Nothing, dynamic = emptyDynamicState, pervasive = emptyPervasiveState } evalExpr expr continue s0 = case expr of V.Literal v -> continue v (pervasive s0) V.Variable stage name -> evalVariable name continue s0 V.LocalBinding name value body -> evalLocalBinding name value body continue s0 V.Sequence exprs -> evalSequence exprs continue s0 V.NewInstance -> evalNewInstance continue s0 V.CallNative subj name args -> evalCallNative subj name args continue s0 V.Invoke args -> evalInvoke args continue s0 V.WithEscape name body -> evalWithEscape name body continue s0 V.Ensure body ensure -> evalEnsure body ensure continue s0 _ -> Failure (ExprNotUnderstood expr) (pervasive s0) evalVariable name continue s0 = if Map.member name scope0 then continue (scope0 Map.! name) (pervasive s0) else evalNamespaceVariable name continue s0 where l0 = lexical s0 scope0 = V.scope l0 -- Updates the pervasive state of an object, setting its data to the given -- state. updateObject uid state p0 = p1 where objects0 = objects p0 objects1 = Map.insert uid state objects0 p1 = p0 {objects=objects1} -- Creates a new object with the given state, returning the object's id and the -- state that now holds the state. newObject state p0 = (uid, p2) where (uid, p1) = genUid p0 p2 = updateObject uid state p1 -- Yields the state of the object with the given uid in the given pervasive -- state. getObject uid p0 = state where objects0 = objects p0 state = objects0 Map.! uid evalNamespaceVariable name continue s0 = if hasNamespace then result else failure where -- Unpack the hasNamespace = Maybe.isJust (V.namespace l0) p0 = pervasive s0 l0 = lexical s0 Just namespaceUid = V.namespace l0 V.NamespaceObject bindings0 = getObject namespaceUid p0 result = case Map.lookup name bindings0 of -- If the variable is already bound we simply look it up and continue. Just (V.Bound value) -> continue value p0 -- If it's being bound there must have been a cycle. Just V.BeingBound -> Failure (CircularReference name) p0 -- If we've not seen it yet it's time to bind it Just (V.Unbound expr lA) -> createBinding expr lA -- If it's simply not there fail Nothing -> failure failure = Failure (UnboundVariable name) p0 createBinding value lA = evalExpr value thenBind sB where bindingsB = Map.insert name V.BeingBound bindings0 pB = updateObject namespaceUid (V.NamespaceObject bindingsB) p0 dB = emptyDynamicState sB = CompleteState {lexical=lA, dynamic=dB, pervasive=pB} thenBind value p2 = continue value p3 where V.NamespaceObject bindings2 = getObject namespaceUid p2 bindings3 = Map.insert name (V.Bound value) bindings2 p3 = updateObject namespaceUid (V.NamespaceObject bindings3) p2 evalLocalBinding name valueExpr bodyExpr continue s0 = evalExpr valueExpr thenBind s0 where thenBind value p1 = evalExpr bodyExpr continue s1 where l0 = lexical s0 scope0 = V.scope l0 scope1 = Map.insert name value scope0 l1 = l0 {V.scope = scope1} s1 = s0 {lexical = l1, pervasive = p1} -- Evaluates a list of expressions, yielding the value of the last one (or Null -- if the list is empty. evalSequence [] continue s0 = continue V.Null (pervasive s0) evalSequence [last] continue s0 = evalExpr last continue s0 evalSequence (next:rest) continue s0 = evalExpr next thenRest s0 where thenRest _ p1 = evalSequence rest continue s1 where s1 = s0 {pervasive = p1} -- Creates a new empty instance. evalNewInstance continue s0 = continue (V.Obj uid) p1 where state = V.InstanceObject V.emptyVaporInstanceState (uid, p1) = newObject state (pervasive s0) -- Evaluates a list of expressions, yielding a list of their values. evalList exprs continue s0 = evalListAccum exprs s0 [] where evalListAccum [] s0 accum = continue (reverse accum) (pervasive s0) evalListAccum (next:rest) s0 accum = evalExpr next thenRest s0 where thenRest value p1 = evalListAccum rest s1 (value:accum) where s1 = s0 {pervasive=p1} evalWithEscape name bodyExpr continue s0 = evalExpr bodyExpr continue s1 where -- Generate a unique id for this escape. p0 = pervasive s0 (escapeUid, p1) = genUid p0 -- Hook the escape into the chain of nonlocals. d0 = dynamic s0 nonlocal0 = nonlocal d0 nonlocal1 targetUid | targetUid == escapeUid = continue | otherwise = nonlocal0 targetUid -- Give the escape hook a name in the body's scope. l0 = lexical s0 scope0 = V.scope l0 scope1 = Map.insert name (V.Hook (V.EscapeHook escapeUid)) scope0 l1 = l0 {V.scope = scope1} d1 = d0 {nonlocal = nonlocal1} s1 = s0 {lexical = l1, dynamic = d1, pervasive = p1} callEscapeHookNative (V.Hook (V.EscapeHook uid)) "!" [val] continue s0 = bail val p0 where d0 = dynamic s0 nonlocal0 = nonlocal d0 bail = nonlocal0 uid p0 = pervasive s0 evalEnsure bodyExpr ensureExpr continue s0 = evalExpr bodyExpr thenEvalEnsure s1 where -- The ensure-block is evaluated in the same dynamic scope as the one in -- which it was defined such that if it escapes itself it won't end in an -- infinite loop. -- -- After evaluating the ensure block we discard its result and continue -- evaluation with the value of the block such that the result value of -- the whole thing is unaffected by the ensure block. -- -- The pervasive state is called pa1 to reflect the fact that there are -- two paths through this code, the non-escape (a) and escape (b) path. thenEvalEnsure bodyValue pa1 = evalExpr ensureExpr thenDiscardValue sa1 where sa1 = s0 {pervasive = pa1} thenDiscardValue ensureValue = continue bodyValue d0 = dynamic s0 nonlocal0 = nonlocal d0 -- If the body escapes we evaluate the ensure block with a continuation -- that continues escaping past this escape. As in the normal case the -- evaluation of the block happens in the same dynamic scope as the one -- in which it is defined, again to avoid looping if it escapes itself. nonlocal1 targetUid escapeValue pb1 = evalExpr ensureExpr thenContinueEscape sb1 where sb1 = s0 {pervasive = pb1} thenContinueEscape ensureValue = nonlocal0 targetUid escapeValue d1 = d0 {nonlocal=nonlocal1} s1 = s0 {dynamic=d1} -- Evaluates a function call expression. evalCallNative recvExpr name argsExprs continue s0 = evalExpr recvExpr thenArgs s0 where thenArgs recv p1 = evalList argsExprs thenCall s1 where s1 = s0 {pervasive=p1} thenCall args p2 = dispatchNative recv name args continue s2 where s2 = s0 {pervasive=p2} evalInvoke argExprs continue s0 = evalList (map snd argExprs) thenInvoke s0 where l0 = lexical s0 methodspace0 = V.methodspace l0 hierarchy0 = V.hierarchy methodspace0 methods0 = V.methods methodspace0 thenInvoke argValues p1 = case method of Nothing -> Failure (MethodNotUnderstood argList) p1 Just method -> continue (V.Int 0) p1 where method = M.sigTreeLookup hierarchy0 methods0 argMap argList = zip (map fst argExprs) argValues argMap = Map.fromList argList -- Natives dispatchNative subj = case subj of V.Hook V.LogHook -> callLogHookNative subj V.Hook (V.EscapeHook _) -> callEscapeHookNative subj V.Hook V.TypeHook -> callTypeHookNative subj V.Int _ -> callIntNative subj _ -> failNative subj callLogHookNative _ "!" [value] continue s0 = continue value p1 where p0 = pervasive s0 log0 = valueLog p0 log1 = log0 ++ [value] p1 = p0 {valueLog = log1} callLogHookNative recv op args continue s0 = failNative recv op args continue s0 callTypeHookNative _ "!" [value] continue s0 = continue result p0 where l0 = lexical s0 p0 = pervasive s0 methodspace0 = V.methodspace l0 hierarchy0 = V.hierarchy methodspace0 result = V.Obj (M.typeOf hierarchy0 value) callTypeHookNative _ "display_name" [V.Obj uid] continue s0 = continue displayName p0 where p0 = pervasive s0 (V.TypeObject state) = (objects p0) Map.! uid (V.TypeState displayName) = state callTypeHookNative recv op args continue s0 = failNative recv op args continue s0 callIntNative (V.Int a) "+" [V.Int b] continue s0 = continue (V.Int (a + b)) (pervasive s0) callIntNative (V.Int a) "-" [V.Int b] continue s0 = continue (V.Int (a - b)) (pervasive s0) callIntNative recv op args continue s0 = failNative recv op args continue s0 failNative recv op args _ s0 = Failure (UnknownCall recv op args) (pervasive s0) -- The set of "magical" root values data RootValues = RootValues { intType :: V.Value, strType :: V.Value, nullType :: V.Value, boolType :: V.Value, fallbackType :: V.Value } deriving (Show) -- Returns the default root state for the given pervasive state, along with the -- pervasive state to use from then on. defaultRootValues p0 = (roots, p5) where rootType pa0 displayName = (V.Obj uid, pa2) where state = V.TypeState displayName (uid, pa1) = genUid pa0 objects1 = objects pa1 objects2 = Map.insert uid (V.TypeObject state) objects1 pa2 = pa1 {objects = objects2} (fallbackType, p1) = rootType p0 V.Null (intType, p2) = rootType p1 (V.Str "Integer") (strType, p3) = rootType p2 (V.Str "String") (nullType, p4) = rootType p3 (V.Str "Null") (boolType, p5) = rootType p4 (V.Str "Bool") roots = RootValues { fallbackType = fallbackType, intType = intType, strType = strType, nullType = nullType, boolType = boolType } -- Given a set of roots and a value, returns the type of the value. typeFromRoots roots value = uid where (V.Obj uid) = case value of V.Int _ -> intType roots V.Str _ -> strType roots V.Null -> nullType roots V.Bool _ -> boolType roots _ -> fallbackType roots -- Default object system data ObjectSystemState = ObjectSystemState { roots :: RootValues, inheritance :: Map.Map V.Uid [V.Uid] } instance M.TypeHierarchy ObjectSystemState where typeOf oss value = typeFromRoots (roots oss) value superTypes oss subtype = Map.findWithDefault [] subtype (inheritance oss) -- Flattened runtime values, that is, values where the part that for Values -- belong in the pervasive state have been extracted and embedded directly in -- the flat value. data FlatValue = FlatNull | FlatBool Bool | FlatInt Int | FlatStr String | FlatHook V.Hook | FlatInstance V.Uid V.InstanceState | FlatType V.Uid V.TypeState deriving (Show, Eq) flatten p V.Null = FlatNull flatten p (V.Bool v) = FlatBool v flatten p (V.Int v) = FlatInt v flatten p (V.Str v) = FlatStr v flatten p (V.Hook v) = FlatHook v flatten p (V.Obj id) = case state of V.InstanceObject state -> FlatInstance id state V.TypeObject state -> FlatType id state where objs = objects p state = objs Map.! id -- Evaluates the given expression, yielding an evaluation result eval :: (M.TypeHierarchy hier) => V.Methodspace hier -> V.Expr -> Result (V.Value, PervasiveState hier) (PervasiveState hier) eval methodspace expr = evalExpr expr endContinuation (emptyCompleteState methodspace) evalFlat :: (M.TypeHierarchy hier) => V.Methodspace hier -> V.Expr -> Result (FlatValue, [FlatValue]) [V.Value] evalFlat behavior expr = case eval behavior expr of Normal (value, p0) -> Normal (flatValue, flatLog) where flatValue = flatten p0 value log = valueLog p0 flatLog = map (flatten p0) log Failure cause p0 -> Failure cause (valueLog p0) -- Given a unified program splits it by stage. The result will be sorted by -- increasing stage. splitProgram (V.UnifiedProgram unifiedDecls body) = V.SplitProgram splitDecls body where stagedDecls = [(stageOf decl, decl) | decl <- unifiedDecls] groups = List.groupBy (\ a b -> fst a == fst b) stagedDecls splitDecls = [(s, map (toSplit . snd) group) | group@((s, _):_) <- groups] stageOf (V.UnifiedNamespaceBinding stage _ _) = stage toSplit (V.UnifiedNamespaceBinding _ name value) = V.SplitNamespaceBinding name value -- Given a list of split declarations returns a list of (name, value) pairs for -- all the namespace declarations. namespaceBindings decls = Maybe.catMaybes (map grabBinding decls) where grabBinding (V.SplitNamespaceBinding name value) = Just (name, value) -- Given a list of namespace declarations etc. yields a lexical scope where -- the namespace declarations have been seeded but not yet evaluated, as well as -- a new pervasive state. lexicalForDeclarations decls methodspace0 p0 = (l1, p2) where (namespaceUid, p1) = newObject (V.NamespaceObject Map.empty) p0 l1 = emptyLexicalState methodspace0 (Just namespaceUid) prepareSingleBinding (name, value) pA = (name, pB) where V.NamespaceObject bindingsA = getObject namespaceUid pA bindingsB = Map.insert name (V.Unbound value l1) bindingsA pB = updateObject namespaceUid (V.NamespaceObject bindingsB) pA prepareBindings [] pA = pA prepareBindings (next:rest) pA = result where (name, pB) = prepareSingleBinding next pA result = prepareBindings rest pB p2 = prepareBindings (namespaceBindings decls) p1 evalProgram :: V.UnifiedProgram -> Result (V.Value, PervasiveState ObjectSystemState) (PervasiveState ObjectSystemState) evalProgram unified = runProgram names s2 where (decls, body) = case splitProgram unified of V.SplitProgram ((_, decls):_) body -> (decls, body) V.SplitProgram [] body -> ([], body) -- Start from a completely empty state. p0 = emptyPervasiveState d0 = emptyDynamicState -- Build the roots after which we're in p1. (roots, p1) = defaultRootValues p0 oss = ObjectSystemState roots Map.empty methodspace1 = V.Methodspace oss M.emptySigTree -- Set up the initial unbound namespace after which we're in p2. names = map fst (namespaceBindings decls) (l2, p2) = lexicalForDeclarations decls methodspace1 p1 s2 = CompleteState {lexical = l2, dynamic = d0, pervasive = p2} -- Touch all the bindings to ensure they get evaluated and then evaluate -- the body. runProgram [] sA = evalExpr body endContinuation sA runProgram (next:rest) sA = evalNamespaceVariable next thenContinue sA where thenContinue value pB = runProgram rest (sA {pervasive=pB}) evalProgramFlat :: V.UnifiedProgram -> Result (FlatValue, [FlatValue]) [V.Value] evalProgramFlat program = case evalProgram program of Normal (value, p0) -> Normal (flatValue, flatLog) where flatValue = flatten p0 value log = (valueLog p0) flatLog = map (flatten p0) log Failure cause p0 -> Failure cause (valueLog p0)
tundra/nls
hs/Eval.hs
apache-2.0
18,653
0
13
4,118
5,033
2,657
2,376
336
10
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} -- | Top-Level Declarations in K3. module Language.K3.Core.Declaration ( Declaration(..), Annotation(..), -- * User defined Annotations Polarity(..), AnnMemDecl(..), PatternRewriteRule, UnorderedConflict(..), PropertyD , getTriggerIds , onDProperty , dPropertyName , dPropertyValue , dPropertyV , isDUID , isDSpan , isDUIDSpan , isDProperty , isDInferredProperty , isDUserProperty , isDSyntax , isDProvenance , isDEffect , isAnyDEffectAnn , isDInferredProvenance , isDInferredEffect , isAnyDInferredEffectAnn ) where import Control.DeepSeq import Data.List import Data.Tree import Data.Typeable import GHC.Generics (Generic) import Language.K3.Core.Annotation import Language.K3.Core.Annotation.Syntax import Language.K3.Core.Common import Language.K3.Core.Expression import Language.K3.Core.Literal import Language.K3.Core.Type import Language.K3.Analysis.Provenance.Core import qualified Language.K3.Analysis.SEffects.Core as S import Language.K3.Utils.Pretty import Data.Text ( Text ) import qualified Data.Text as T import qualified Language.K3.Utils.PrettyText as PT -- | Cycle-breaking import for metaprogramming import {-# SOURCE #-} Language.K3.Core.Metaprogram -- | Top-Level Declarations data Declaration = DGlobal Identifier (K3 Type) (Maybe (K3 Expression)) | DTrigger Identifier (K3 Type) (K3 Expression) -- ^ Trigger declaration. Type is argument type of trigger. Expression -- must be a function taking that argument type and returning unit. | DDataAnnotation Identifier [TypeVarDecl] [AnnMemDecl] -- ^ Name, annotation type parameters, and members | DGenerator MPDeclaration -- ^ Metaprogramming declarations, maintained in the tree for lineage. | DRole Identifier -- ^ Roles, as lightweight modules. These are deprecated. | DTypeDef Identifier (K3 Type) -- ^ Type synonym declaration. deriving (Eq, Ord, Read, Show, Typeable, Generic) -- | Annotation declaration members data AnnMemDecl = Lifted Polarity Identifier (K3 Type) (Maybe (K3 Expression)) [Annotation Declaration] | Attribute Polarity Identifier (K3 Type) (Maybe (K3 Expression)) [Annotation Declaration] | MAnnotation Polarity Identifier [Annotation Declaration] deriving (Eq, Ord, Read, Show, Typeable, Generic) -- | Annotation member polarities data Polarity = Provides | Requires deriving (Eq, Ord, Read, Show, Typeable, Generic) -- | A pattern-based rewrite rule, as used in control annotations. -- This includes a pattern matching expression, a rewritten expression, -- and any declarations used in the rewrite. type PatternRewriteRule = (K3 Expression, K3 Expression, [K3 Declaration]) -- | Annotations on Declarations. data instance Annotation Declaration = DSpan Span | DUID UID | DProperty PropertyD | DSyntax SyntaxAnnotation | DConflict UnorderedConflict -- TODO: organize into categories. -- Provenance and effects may be user-defined (lefts) or inferred (rights) | DProvenance (Either (K3 Provenance) (K3 Provenance)) | DEffect (Either (K3 S.Effect) (K3 S.Effect)) deriving (Eq, Ord, Read, Show, Generic) -- | Unordered Data Conflicts (between triggers) data UnorderedConflict = URW [(Annotation Expression)] (Annotation Expression) | UWW (Annotation Expression) (Annotation Expression) deriving (Eq, Ord, Read, Show, Generic) {- NFData instances for declarations -} instance NFData Declaration instance NFData AnnMemDecl instance NFData Polarity instance NFData (Annotation Declaration) instance NFData UnorderedConflict {- HasUID instances -} instance HasUID (Annotation Declaration) where getUID (DUID u) = Just u getUID _ = Nothing instance HasSpan (Annotation Declaration) where getSpan (DSpan s) = Just s getSpan _ = Nothing -- | Property helpers type PropertyV = (Identifier, Maybe (K3 Literal)) type PropertyD = Either PropertyV PropertyV onDProperty :: (PropertyV -> a) -> PropertyD -> a onDProperty f (Left (n, lopt)) = f (n, lopt) onDProperty f (Right (n, lopt)) = f (n, lopt) dPropertyName :: PropertyD -> String dPropertyName (Left (n,_)) = n dPropertyName (Right (n,_)) = n dPropertyValue :: PropertyD -> Maybe (K3 Literal) dPropertyValue (Left (_,v)) = v dPropertyValue (Right (_,v)) = v dPropertyV :: PropertyD -> PropertyV dPropertyV (Left pv) = pv dPropertyV (Right pv) = pv {- Declaration annotation predicates -} isDSpan :: Annotation Declaration -> Bool isDSpan (DSpan _) = True isDSpan _ = False isDUID :: Annotation Declaration -> Bool isDUID (DUID _) = True isDUID _ = False isDUIDSpan :: Annotation Declaration -> Bool isDUIDSpan a = isDSpan a || isDUID a isDProperty :: Annotation Declaration -> Bool isDProperty (DProperty _) = True isDProperty _ = False isDInferredProperty :: Annotation Declaration -> Bool isDInferredProperty (DProperty (Right _)) = True isDInferredProperty _ = False isDUserProperty :: Annotation Declaration -> Bool isDUserProperty (DProperty (Left _)) = True isDUserProperty _ = False isDSyntax :: Annotation Declaration -> Bool isDSyntax (DSyntax _) = True isDSyntax _ = False isDProvenance :: Annotation Declaration -> Bool isDProvenance (DProvenance _) = True isDProvenance _ = False isDEffect :: Annotation Declaration -> Bool isDEffect (DEffect _) = True isDEffect _ = False isAnyDEffectAnn :: Annotation Declaration -> Bool isAnyDEffectAnn a = isDProvenance a || isDEffect a isDInferredProvenance :: Annotation Declaration -> Bool isDInferredProvenance (DProvenance (Right _)) = True isDInferredProvenance _ = False isDInferredEffect :: Annotation Declaration -> Bool isDInferredEffect (DEffect (Right _)) = True isDInferredEffect _ = False isAnyDInferredEffectAnn :: Annotation Declaration -> Bool isAnyDInferredEffectAnn a = isDInferredProvenance a || isDInferredEffect a {- Utils -} -- Given top level role declaration, return list of all trigger ids in the AST getTriggerIds :: K3 Declaration -> [Identifier] getTriggerIds (Node (DRole _ :@: _) cs) = map getTriggerName $ filter isTrigger cs getTriggerIds _ = error "getTriggerIds expects role declaration" isTrigger :: K3 Declaration -> Bool isTrigger (Node (DTrigger _ _ _:@: _) _) = True isTrigger _ = False getTriggerName :: K3 Declaration -> Identifier getTriggerName (Node (DTrigger n _ _ :@: _) _) = n getTriggerName _ = error "getTriggerName expects trigger declaration" {- Declaration instances -} instance Pretty (K3 Declaration) where prettyLines (Node (DGlobal i t me :@: as) ds) = let (annStr, pAnnStrs) = drawDeclAnnotations as in ["DGlobal " ++ i ++ annStr] ++ ["|"] ++ (if null pAnnStrs then [] else (shift "+- " "| " pAnnStrs) ++ ["|"]) ++ case (me, ds) of (Nothing, []) -> terminalShift t (Just e, []) -> nonTerminalShift t ++ ["|"] ++ terminalShift e (Nothing, _) -> nonTerminalShift t ++ ["|"] ++ drawSubTrees ds (Just e, _) -> nonTerminalShift t ++ ["|"] ++ nonTerminalShift e ++ ["|"] ++ drawSubTrees ds prettyLines (Node (DTrigger i t e :@: as) ds) = let (annStr, pAnnStrs) = drawDeclAnnotations as in ["DTrigger " ++ i ++ annStr] ++ ["|"] ++ (if null pAnnStrs then [] else (shift "+- " "| " pAnnStrs) ++ ["|"]) ++ nonTerminalShift t ++ ["|"] ++ case ds of [] -> terminalShift e _ -> nonTerminalShift e ++ ["|"] ++ drawSubTrees ds prettyLines (Node (DRole i :@: as) ds) = ["DRole " ++ i ++ " :@: " ++ show as, "|"] ++ drawSubTrees ds prettyLines (Node (DDataAnnotation i tvars members :@: as) ds) = ["DDataAnnotation " ++ i ++ if null tvars then "" else ("[" ++ (removeTrailingWhitespace . boxToString $ foldl1 (\a b -> a %+ [", "] %+ b) $ map prettyLines tvars) ++ "]" ) ++ drawAnnotations as, "|"] ++ drawAnnotationMembers members ++ drawSubTrees ds where drawAnnotationMembers [] = [] drawAnnotationMembers [x] = terminalShift x drawAnnotationMembers x = concatMap (\y -> nonTerminalShift y ++ ["|"]) (init x) ++ terminalShift (last x) prettyLines (Node (DGenerator mp :@: as) ds) = ["DGenerator" ++ drawAnnotations as, "|"] ++ terminalShift mp ++ drawSubTrees ds prettyLines (Node (DTypeDef i t :@: _) _) = ["DTypeDef " ++ i ++ " "] `hconcatTop` prettyLines t instance Pretty AnnMemDecl where prettyLines (Lifted pol n t eOpt anns) = let (annStr, pAnnStrs) = drawDeclAnnotations anns in ["Lifted " ++ unwords [show pol, n, annStr]] ++ ["|"] ++ (if null pAnnStrs then [] else (shift "+- " "| " pAnnStrs) ++ ["|"]) ++ case eOpt of Nothing -> terminalShift t Just e -> nonTerminalShift t ++ ["|"] ++ terminalShift e prettyLines (Attribute pol n t eOpt anns) = let (annStr, pAnnStrs) = drawDeclAnnotations anns in ["Attribute " ++ unwords [show pol, n, annStr]] ++ ["|"] ++ (if null pAnnStrs then [] else (shift "+- " "| " pAnnStrs) ++ ["|"]) ++ case eOpt of Nothing -> terminalShift t Just e -> nonTerminalShift t ++ ["|"] ++ terminalShift e prettyLines (MAnnotation pol n anns) = ["MAnnotation " ++ unwords [show pol, n, show anns]] drawDeclAnnotations :: [Annotation Declaration] -> (String, [String]) drawDeclAnnotations as = let (prettyAnns, anns) = partition (\a -> isDProvenance a || isDEffect a) as prettyDeclAnns = drawGroup $ map drawDAnnotation prettyAnns in (drawAnnotations anns, prettyDeclAnns) where drawDAnnotation (DProvenance p) = ["DProvenance "] %+ either prettyLines prettyLines p drawDAnnotation (DEffect e) = ["DEffect "] %+ either prettyLines prettyLines e drawDAnnotation _ = error "Invalid symbol annotation" {- PrettyText instance -} tPipe :: Text tPipe = T.pack "|" aPipe :: [Text] -> [Text] aPipe t = t ++ [tPipe] ntShift :: [Text] -> [Text] ntShift = PT.shift (T.pack "+- ") (T.pack "| ") tTA :: String -> [Annotation Declaration] -> [Text] tTA s as = let (annTxt, pAnnTxt) = drawDeclAnnotationsT as in aPipe [T.append (T.pack s) annTxt] ++ (if null pAnnTxt then [] else aPipe $ ntShift pAnnTxt) tNullTerm :: (PT.Pretty a, PT.Pretty b) => a -> [b] -> [Text] tNullTerm a bl = if null bl then PT.terminalShift a else ((aPipe (PT.nonTerminalShift a) ++) . PT.drawSubTrees) bl tMaybeTerm :: (PT.Pretty a, PT.Pretty b) => a -> Maybe b -> [Text] tMaybeTerm a bOpt = maybe (PT.terminalShift a) ((aPipe (PT.nonTerminalShift a) ++) . PT.terminalShift) bOpt instance PT.Pretty (K3 Declaration) where prettyLines (Node (DGlobal i t me :@: as) ds) = tTA ("DGlobal " ++ i) as ++ case (me, ds) of (Nothing, []) -> PT.terminalShift t (Just e, []) -> aPipe (PT.nonTerminalShift t) ++ PT.terminalShift e (Nothing, _) -> aPipe (PT.nonTerminalShift t) ++ PT.drawSubTrees ds (Just e, _) -> aPipe (PT.nonTerminalShift t) ++ aPipe (PT.nonTerminalShift e) ++ PT.drawSubTrees ds prettyLines (Node (DTrigger i t e :@: as) ds) = tTA ("DTrigger " ++ i) as ++ aPipe (PT.nonTerminalShift t) ++ tNullTerm e ds prettyLines (Node (DRole i :@: as) ds) = tTA ("DRole " ++ i) as ++ PT.drawSubTrees ds prettyLines (Node (DDataAnnotation i tvars members :@: as) ds) = [foldl1 T.append [T.pack $ "DDataAnnotation " ++ i , if null tvars then T.empty else (wrapT "[" (prettyTvars tvars) "]") , PT.drawAnnotations as, T.pack "|"]] ++ drawAnnotationMembersT members ++ PT.drawSubTrees ds where wrapT l body r = foldl1 T.append [T.pack l, body, T.pack r] prettyTvars tvars' = PT.removeTrailingWhitespace . PT.boxToString $ foldl1 (\a b -> a PT.%+ [T.pack ", "] PT.%+ b) $ map PT.prettyLines tvars' drawAnnotationMembersT [] = [] drawAnnotationMembersT [x] = PT.terminalShift x drawAnnotationMembersT x = concatMap (aPipe . PT.nonTerminalShift) (init x) ++ PT.terminalShift (last x) prettyLines (Node (DGenerator mp :@: as) ds) = tTA "DGenerator" as ++ map T.pack (terminalShift mp) ++ PT.drawSubTrees ds prettyLines (Node (DTypeDef i t :@: _) _) = [T.pack $ "DTypeDef " ++ i ++ " "] `PT.hconcatTop` PT.prettyLines t instance PT.Pretty AnnMemDecl where prettyLines (Lifted pol n t eOpt anns) = tTA (unwords ["Lifted", show pol, n]) anns ++ tMaybeTerm t eOpt prettyLines (Attribute pol n t eOpt anns) = tTA (unwords ["Attribute", show pol, n]) anns ++ tMaybeTerm t eOpt prettyLines (MAnnotation pol n anns) = [T.append (T.pack "MAnnotation ") $ T.unwords $ map T.pack [show pol, n, show anns]] drawDeclAnnotationsT :: [Annotation Declaration] -> (Text, [Text]) drawDeclAnnotationsT as = let (prettyAnns, anns) = partition (\a -> isDProvenance a || isDEffect a) as prettyDeclAnns = PT.drawGroup $ map drawDAnnotationT prettyAnns in (PT.drawAnnotations anns, prettyDeclAnns) where drawDAnnotationT (DProvenance p) = [T.pack "DProvenance "] PT.%+ either PT.prettyLines PT.prettyLines p drawDAnnotationT (DEffect e) = [T.pack "DEffect "] PT.%+ either PT.prettyLines PT.prettyLines e drawDAnnotationT _ = error "Invalid symbol annotation"
yliu120/K3
src/Language/K3/Core/Declaration.hs
apache-2.0
13,878
0
23
3,255
4,527
2,362
2,165
275
3
{-# LANGUAGE ScopedTypeVariables #-} module Fifo where import CLaSH.Prelude type Elm = Unsigned 8 type Pntr n = Unsigned (n + 1) type Elms = Vec 4 Elm fifo :: forall n e . (KnownNat n, KnownNat (n+1), KnownNat (n^2)) => (Pntr n, Pntr n, Vec (n^2) e) -> (e, Bool, Bool) -> ((Pntr n,Pntr n,Vec (n^2) e),(Bool,Bool,e)) fifo (rpntr, wpntr, elms) (datain,wrt,rd) = ((rpntr',wpntr',elms'),(full,empty,dataout)) where wpntr' | wrt = wpntr + 1 | otherwise = wpntr rpntr' | rd = rpntr + 1 | otherwise = rpntr mask = resize (maxBound :: Unsigned n) wind = wpntr .&. mask rind = rpntr .&. mask elms' | wrt = replace elms wind datain | otherwise = elms n = fromInteger $ snatToInteger (snat :: SNat n) empty = wpntr == rpntr full = (testBit wpntr n) /= (testBit rpntr n) && (wind == rind) dataout = elms !! rind fifoL :: Signal (Elm,Bool,Bool) -> Signal (Bool,Bool,Elm) fifoL = fifo `mealy` (0,0,replicate d4 0) testdatas :: [[(Elm,Bool,Bool)]] testdatas = [ -- write an element, wait one cycle, write and read, wait a cycle -> [(1,True,False), (2,False,False), (3, True,True), (4,False,False)], -- fill up fifo firs then empty it again [(1,True,False), (2,True,False), (3,True,False), (4,True,False), (5,False,True), (6,False,True),(7,False,True),(8,False,True),(9,False,False)] ] -- Expected value for different testdata inputs express :: [[(Bool, Bool, Elm)]] express = [ [(False,True,0),(False,False,1),(False,False,1),(False,False,3)], [(False,True,0),(False,False,1),(False,False,1),(False,False,1),(True,False,1),(False,False,2),(False,False,3),(False,False,4),(False,True,1)] ]
christiaanb/clash-compiler
examples/Fifo.hs
bsd-2-clause
1,726
0
13
374
853
514
339
-1
-1
{-# LANGUAGE TupleSections #-} -- | Let AI pick the best target for an actor. module Game.LambdaHack.Client.AI.PickTargetClient ( targetStrategy, createPath ) where import Control.Applicative import Control.Exception.Assert.Sugar import Control.Monad import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import Data.List import Data.Maybe import Game.LambdaHack.Client.AI.ConditionClient import Game.LambdaHack.Client.AI.Preferences import Game.LambdaHack.Client.AI.Strategy import Game.LambdaHack.Client.Bfs import Game.LambdaHack.Client.BfsClient import Game.LambdaHack.Client.CommonClient import Game.LambdaHack.Client.MonadClient import Game.LambdaHack.Client.State import Game.LambdaHack.Common.Ability import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Frequency 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.Point import Game.LambdaHack.Common.Random import Game.LambdaHack.Common.State import qualified Game.LambdaHack.Common.Tile as Tile import Game.LambdaHack.Common.Time import Game.LambdaHack.Common.Vector import qualified Game.LambdaHack.Content.ItemKind as IK import Game.LambdaHack.Content.ModeKind import Game.LambdaHack.Content.RuleKind -- | AI proposes possible targets for the actor. Never empty. targetStrategy :: forall m. MonadClient m => ActorId -> m (Strategy (Target, Maybe PathEtc)) targetStrategy aid = do [email protected]{corule, [email protected]{ouniqGroup}} <- getsState scops let stdRuleset = Kind.stdRuleset corule nearby = rnearby stdRuleset itemToF <- itemToFullClient modifyClient $ \cli -> cli { sbfsD = invalidateBfs aid (sbfsD cli) , seps = seps cli + 773 } -- randomize paths b <- getsState $ getActorBody aid activeItems <- activeItemsClient aid lvl@Level{lxsize, lysize} <- getLevel $ blid b let stepAccesible mtgt@(Just (_, (p : q : _ : _, _))) = -- goal not adjacent if accessible cops lvl p q then mtgt else Nothing stepAccesible mtgt = mtgt -- goal can be inaccessible, e.g., suspect mtgtMPath <- getsClient $ EM.lookup aid . stargetD oldTgtUpdatedPath <- case mtgtMPath of Just (tgt, Nothing) -> -- This case is especially for TEnemyPos that would be lost otherwise. -- This is also triggered by @UpdLeadFaction@. The recreated path can be -- different than on the other client (AI or UI), but we don't care -- as long as the target stays the same at least for a moment. createPath aid tgt Just (tgt, Just path) -> do mvalidPos <- aidTgtToPos aid (blid b) (Just tgt) if isNothing mvalidPos then return Nothing -- wrong level else return $! case path of (p : q : rest, (goal, len)) -> stepAccesible $ if bpos b == p then Just (tgt, path) -- no move last turn else if bpos b == q then Just (tgt, (q : rest, (goal, len - 1))) -- step along path else Nothing -- veered off the path ([p], (goal, _)) -> do let !_A = assert (p == goal `blame` (aid, b, mtgtMPath)) () if bpos b == p then Just (tgt, path) -- goal reached; stay there picking up items else Nothing -- somebody pushed us off the goal; let's target again ([], _) -> assert `failure` (aid, b, mtgtMPath) Nothing -> return Nothing -- no target assigned yet let !_A = assert (not $ bproj b) () -- would work, but is probably a bug fact <- getsState $ (EM.! bfid b) . sfactionD allFoes <- getsState $ actorRegularAssocs (isAtWar fact) (blid b) dungeon <- getsState sdungeon -- We assume the actor eventually becomes a leader (or has the same -- set of abilities as the leader, anyway) and set his target accordingly. let actorMaxSk = sumSkills activeItems actorMinSk <- getsState $ actorSkills Nothing aid activeItems condCanProject <- condCanProjectM True aid condHpTooLow <- condHpTooLowM aid condEnoughGear <- condEnoughGearM aid condMeleeBad <- condMeleeBadM aid let friendlyFid fid = fid == bfid b || isAllied fact fid friends <- getsState $ actorRegularList friendlyFid (blid b) -- TODO: refine all this when some actors specialize in ranged attacks -- (then we have to target, but keep the distance, we can do similarly for -- wounded or alone actors, perhaps only until they are shot first time, -- and only if they can shoot at the moment) canEscape <- factionCanEscape (bfid b) explored <- getsClient sexplored smellRadius <- sumOrganEqpClient IK.EqpSlotAddSmell aid let condNoUsableWeapon = all (not . isMelee) activeItems lidExplored = ES.member (blid b) explored allExplored = ES.size explored == EM.size dungeon canSmell = smellRadius > 0 meleeNearby | canEscape = nearby `div` 2 -- not aggresive | otherwise = nearby rangedNearby = 2 * meleeNearby -- Don't target nonmoving actors at all if bad melee, -- because nonmoving can't be lured nor ambushed. -- This is especially important for fences, tower defense actors, etc. -- If content gives nonmoving actor loot, this becomes problematic. targetableMelee aidE body = do activeItemsE <- activeItemsClient aidE let actorMaxSkE = sumSkills activeItemsE attacksFriends = any (adjacent (bpos body) . bpos) friends n = if attacksFriends then rangedNearby else meleeNearby nonmoving = EM.findWithDefault 0 AbMove actorMaxSkE <= 0 return {-keep lazy-} $ chessDist (bpos body) (bpos b) < n && not condNoUsableWeapon && EM.findWithDefault 0 AbMelee actorMaxSk > 0 && not (hpTooLow b activeItems) && not (nonmoving && condMeleeBad) targetableRangedOrSpecial body = chessDist (bpos body) (bpos b) < rangedNearby && condCanProject targetableEnemy (aidE, body) = do tMelee <- targetableMelee aidE body return $! targetableRangedOrSpecial body || tMelee nearbyFoes <- filterM targetableEnemy allFoes let unknownId = ouniqGroup "unknown space" itemUsefulness itemFull = fst <$> totalUsefulness cops b activeItems fact itemFull desirableBag bag = any (\(iid, k) -> let itemFull = itemToF iid k use = itemUsefulness itemFull in desirableItem canEscape use itemFull) $ EM.assocs bag desirable (_, (_, Nothing)) = True desirable (_, (_, Just bag)) = desirableBag bag -- TODO: make more common when weak ranged foes preferred, etc. focused = bspeed b activeItems < speedNormal || condHpTooLow couldMoveLastTurn = let axtorSk = if (fst <$> gleader fact) == Just aid then actorMaxSk else actorMinSk in EM.findWithDefault 0 AbMove axtorSk > 0 isStuck = waitedLastTurn b && couldMoveLastTurn slackTactic = ftactic (gplayer fact) `elem` [TMeleeAndRanged, TMeleeAdjacent, TBlock, TRoam, TPatrol] setPath :: Target -> m (Strategy (Target, Maybe PathEtc)) setPath tgt = do mpath <- createPath aid tgt let take5 (TEnemy{}, pgl) = (tgt, Just pgl) -- for projecting, even by roaming actors take5 (_, pgl@(path, (goal, _))) = if slackTactic then -- Best path only followed 5 moves; then straight on. let path5 = take 5 path vtgt | bpos b == goal = tgt | otherwise = TVector $ towards (bpos b) goal in (vtgt, Just (path5, (last path5, length path5 - 1))) else (tgt, Just pgl) return $! returN "setPath" $ maybe (tgt, Nothing) take5 mpath pickNewTarget :: m (Strategy (Target, Maybe PathEtc)) pickNewTarget = do -- This is mostly lazy and used between 0 and 3 times below. ctriggers <- closestTriggers Nothing aid -- TODO: for foes, items, etc. consider a few nearby, not just one cfoes <- closestFoes nearbyFoes aid case cfoes of (_, (aid2, _)) : _ -> setPath $ TEnemy aid2 False [] -> do -- Tracking enemies is more important than exploring, -- and smelling actors are usually blind, so bad at exploring. -- TODO: prefer closer items to older smells smpos <- if canSmell then closestSmell aid else return [] case smpos of [] -> do let ctriggersEarly = if EM.findWithDefault 0 AbTrigger actorMaxSk > 0 && condEnoughGear then ctriggers else mzero if nullFreq ctriggersEarly then do citems <- if EM.findWithDefault 0 AbMoveItem actorMaxSk > 0 then closestItems aid else return [] case filter desirable citems of [] -> do let vToTgt v0 = do let vFreq = toFreq "vFreq" $ (20, v0) : map (1,) moves v <- rndToAction $ frequency vFreq -- Items and smells, etc. considered every 7 moves. let tra = trajectoryToPathBounded lxsize lysize (bpos b) (replicate 7 v) path = nub $ bpos b : tra return $! returN "tgt with no exploration" ( TVector v , if length path == 1 then Nothing else Just (path, (last path, length path - 1)) ) oldpos = fromMaybe (Point 0 0) (boldpos b) vOld = bpos b `vectorToFrom` oldpos pNew = shiftBounded lxsize lysize (bpos b) vOld if slackTactic && not isStuck && isUnit vOld && bpos b /= pNew && accessible cops lvl (bpos b) pNew then vToTgt vOld else do upos <- if lidExplored then return Nothing else closestUnknown aid case upos of Nothing -> do csuspect <- if lidExplored then return [] else closestSuspect aid case csuspect of [] -> do let ctriggersMiddle = if EM.findWithDefault 0 AbTrigger actorMaxSk > 0 && not allExplored then ctriggers else mzero if nullFreq ctriggersMiddle then do -- All stones turned, time to win or die. afoes <- closestFoes allFoes aid case afoes of (_, (aid2, _)) : _ -> setPath $ TEnemy aid2 False [] -> if nullFreq ctriggers then do furthest <- furthestKnown aid setPath $ TPoint (blid b) furthest else do p <- rndToAction $ frequency ctriggers setPath $ TPoint (blid b) p else do p <- rndToAction $ frequency ctriggers setPath $ TPoint (blid b) p p : _ -> setPath $ TPoint (blid b) p Just p -> setPath $ TPoint (blid b) p (_, (p, _)) : _ -> setPath $ TPoint (blid b) p else do p <- rndToAction $ frequency ctriggers setPath $ TPoint (blid b) p (_, (p, _)) : _ -> setPath $ TPoint (blid b) p tellOthersNothingHere pos = do let f (tgt, _) = case tgt of TEnemyPos _ lid p _ -> p /= pos || lid /= blid b _ -> True modifyClient $ \cli -> cli {stargetD = EM.filter f (stargetD cli)} pickNewTarget updateTgt :: Target -> PathEtc -> m (Strategy (Target, Maybe PathEtc)) updateTgt oldTgt updatedPath@(_, (_, len)) = case oldTgt of TEnemy a permit -> do body <- getsState $ getActorBody a if not focused -- prefers closer foes && a `notElem` map fst nearbyFoes -- old one not close enough || blid body /= blid b -- wrong level || actorDying body -- foe already dying || permit -- never follow a friend more than 1 step then pickNewTarget else if bpos body == fst (snd updatedPath) then return $! returN "TEnemy" (oldTgt, Just updatedPath) -- The enemy didn't move since the target acquired. -- If any walls were added that make the enemy -- unreachable, AI learns that the hard way, -- as soon as it bumps into them. else do let p = bpos body (bfs, mpath) <- getCacheBfsAndPath aid p case mpath of Nothing -> pickNewTarget -- enemy became unreachable Just path -> return $! returN "TEnemy" (oldTgt, Just ( bpos b : path , (p, fromMaybe (assert `failure` mpath) $ accessBfs bfs p) )) TEnemyPos _ lid p permit -- Chase last position even if foe hides or dies, -- to find his companions, loot, etc. | lid /= blid b -- wrong level || chessDist (bpos b) p >= nearby -- too far and not visible || permit -- never follow a friend more than 1 step -> pickNewTarget | p == bpos b -> tellOthersNothingHere p | otherwise -> return $! returN "TEnemyPos" (oldTgt, Just updatedPath) _ | not $ null nearbyFoes -> pickNewTarget -- prefer close foes to anything TPoint lid pos -> do bag <- getsState $ getCBag $ CFloor lid pos let t = lvl `at` pos if lid /= blid b -- wrong level -- Below we check the target could not be picked again in -- pickNewTarget, and only in this case it is invalidated. -- This ensures targets are eventually reached (unless a foe -- shows up) and not changed all the time mid-route -- to equally interesting, but perhaps a bit closer targets, -- most probably already targeted by other actors. || (EM.findWithDefault 0 AbMoveItem actorMaxSk <= 0 || not (desirableBag bag)) -- closestItems && (pos == bpos b || (not canSmell -- closestSmell || let sml = EM.findWithDefault timeZero pos (lsmell lvl) in sml <= ltime lvl) && if not lidExplored then t /= unknownId -- closestUnknown && not (Tile.isSuspect cotile t) -- closestSuspect && not (condEnoughGear && Tile.isStair cotile t) else -- closestTriggers -- Try to kill that very last enemy for his loot before -- leaving the level or dungeon. not (null allFoes) || -- If all explored, escape/block escapes. (not (Tile.isEscape cotile t) || not allExplored) -- The next case is stairs in closestTriggers. -- We don't determine if the stairs are interesting -- (this changes with time), but allow the actor -- to reach them and then retarget, unless he can't -- trigger them at all. && (EM.findWithDefault 0 AbTrigger actorMaxSk <= 0 || not (Tile.isStair cotile t)) -- The remaining case is furthestKnown. This is -- always an unimportant target, so we forget it -- if the actor is stuck (waits, though could move; -- or has zeroed individual moving skill, -- but then should change targets often anyway). && (isStuck || not allExplored)) then pickNewTarget else return $! returN "TPoint" (oldTgt, Just updatedPath) TVector{} | len > 1 -> return $! returN "TVector" (oldTgt, Just updatedPath) TVector{} -> pickNewTarget case oldTgtUpdatedPath of Just (oldTgt, updatedPath) -> updateTgt oldTgt updatedPath Nothing -> pickNewTarget createPath :: MonadClient m => ActorId -> Target -> m (Maybe (Target, PathEtc)) createPath aid tgt = do b <- getsState $ getActorBody aid mpos <- aidTgtToPos aid (blid b) (Just tgt) case mpos of Nothing -> return Nothing -- TODO: for now, an extra turn at target is needed, e.g., to pick up items -- Just p | p == bpos b -> return Nothing Just p -> do (bfs, mpath) <- getCacheBfsAndPath aid p return $! case mpath of Nothing -> Nothing Just path -> Just (tgt, ( bpos b : path , (p, fromMaybe (assert `failure` mpath) $ accessBfs bfs p) ))
Concomitant/LambdaHack
Game/LambdaHack/Client/AI/PickTargetClient.hs
bsd-3-clause
18,697
21
71
7,200
4,110
2,138
1,972
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} module Types where import Data.Text (Text) import qualified Data.Text as T import qualified Trac.Convert as T import Network.Conduit.Client hiding (User, Repo) convert :: Text -> Text convert = T.pack . T.convert . T.unpack -- Used as a kind data PHIDType = Ticket | User | Transaction | Diff | Project | Repo | Commit | File type TicketID = PHID 'Ticket type TransactionID = PHID 'Transaction type UserID = PHID 'User type DiffID = PHID 'Diff type ProjectID = PHID 'Project type CommitID = PHID 'Commit type FileID = PHID 'File unwrapPHID :: PHID a -> Text unwrapPHID (PHID t) = t data KeywordType = Arch | Keyword | OS | Milestone | Component | Type deriving Show
danpalmer/trac-to-phabricator
src/Types.hs
bsd-3-clause
759
0
7
165
232
138
94
20
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Budget.Database.Item where import Prelude hiding (id) import qualified Data.Maybe as MB import Data.Text (unpack, pack) import Data.Time (LocalTime) import qualified Budget.Core as Core import qualified Budget.Core.Data.Expense as E import qualified Budget.Core.Data.Income as I import Database.Relational.Query import Budget.Database.Internal import qualified Budget.Database.ItemCategory as ItemCategory import qualified Budget.Database.ItemType as ItemType import Budget.Database.Schema (defineTable) $(defineTable "item") type Item' = (Item, ItemCategory.ItemCategory) instance From E.Expense Item' where from (i, c) = E.Expense { E.id = id i , E.name = pack . name $ i , E.date = date i , E.note = pack . MB.fromMaybe "" . note $ i , E.amount = amount i , E.category = from c } instance From I.Income Item' where from (i, c) = I.Income { I.id = id i , I.name = pack . name $ i , I.date = date i , I.note = pack . MB.fromMaybe "" . note $ i , I.amount = amount i , I.category = from c } type ItemId = String -- | itemByMonth :: ItemType.ItemTypeName -> (Core.Date, Core.Date) -> Relation () Item' itemByMonth itemTypeName (fromDay, toDay) = relation $ do i <- query item c <- query ItemCategory.itemCategory t <- query ItemType.itemType on $ i ! itemCategory' .=. c ! ItemCategory.id' on $ c ! ItemCategory.itemType' .=. t ! ItemType.id' wheres $ t ! ItemType.name' .=. value (show itemTypeName) wheres $ i ! date' .>=. unsafeSQLiteDayValue fromDay wheres $ i ! date' .<. unsafeSQLiteDayValue toDay return (i >< c) incomeByMonth :: (Core.Date, Core.Date) -> Relation () Item' incomeByMonth = itemByMonth ItemType.Income expenseByMonth :: (Core.Date, Core.Date) -> Relation () Item' expenseByMonth = itemByMonth ItemType.Expense insertFromExpense :: ItemId -> LocalTime -> Core.NewExpenseR -> InsertQuery () insertFromExpense itemId now = insertQueryItem . valueFromExpense where valueFromExpense :: Core.NewExpenseR -> Relation () Item valueFromExpense i = relation . return $ Item |$| value itemId |*| value (Core.newExpenseCategoryId i) |*| unsafeSQLiteDayValue (Core.newExpenseDate i) |*| (value . unpack) (Core.newExpenseName i) |*| value (Core.newExpenseAmount i) |*| (value . Just . unpack) (Core.newExpenseNote i) |*| unsafeSQLiteTimeValue now insertFromIncome :: ItemId -> LocalTime -> Core.NewIncomeR -> InsertQuery () insertFromIncome itemId now = insertQueryItem . valueFromIncome where valueFromIncome :: Core.NewIncomeR -> Relation () Item valueFromIncome i = relation . return $ Item |$| value itemId |*| value (Core.newIncomeCategoryId i) |*| unsafeSQLiteDayValue (Core.newIncomeDate i) |*| (value . unpack) (Core.newIncomeName i) |*| value (Core.newIncomeAmount i) |*| (value . Just . unpack) (Core.newIncomeNote i) |*| unsafeSQLiteTimeValue now
utky/budget
src/Budget/Database/Item.hs
bsd-3-clause
3,219
0
16
746
1,019
538
481
77
1
{-# language CPP #-} -- No documentation found for Chapter "Promoted_From_VK_EXT_host_query_reset" module Vulkan.Core12.Promoted_From_VK_EXT_host_query_reset ( resetQueryPool , PhysicalDeviceHostQueryResetFeatures(..) , StructureType(..) ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.NamedType ((:::)) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkResetQueryPool)) import Vulkan.Core10.Handles (Device_T) import Vulkan.Core10.Handles (QueryPool) import Vulkan.Core10.Handles (QueryPool(..)) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES)) import Vulkan.Core10.Enums.StructureType (StructureType(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkResetQueryPool :: FunPtr (Ptr Device_T -> QueryPool -> Word32 -> Word32 -> IO ()) -> Ptr Device_T -> QueryPool -> Word32 -> Word32 -> IO () -- | vkResetQueryPool - Reset queries in a query pool -- -- = Description -- -- This command sets the status of query indices [@firstQuery@, -- @firstQuery@ + @queryCount@ - 1] to unavailable. -- -- If @queryPool@ is -- 'Vulkan.Core10.Enums.QueryType.QUERY_TYPE_PERFORMANCE_QUERY_KHR' this -- command sets the status of query indices [@firstQuery@, @firstQuery@ + -- @queryCount@ - 1] to unavailable for each pass. -- -- == Valid Usage -- -- - #VUID-vkResetQueryPool-None-02665# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-hostQueryReset hostQueryReset> -- feature /must/ be enabled -- -- - #VUID-vkResetQueryPool-firstQuery-02666# @firstQuery@ /must/ be less -- than the number of queries in @queryPool@ -- -- - #VUID-vkResetQueryPool-firstQuery-02667# The sum of @firstQuery@ and -- @queryCount@ /must/ be less than or equal to the number of queries -- in @queryPool@ -- -- - #VUID-vkResetQueryPool-firstQuery-02741# Submitted commands that -- refer to the range specified by @firstQuery@ and @queryCount@ in -- @queryPool@ /must/ have completed execution -- -- - #VUID-vkResetQueryPool-firstQuery-02742# The range of queries -- specified by @firstQuery@ and @queryCount@ in @queryPool@ /must/ not -- be in use by calls to 'Vulkan.Core10.Query.getQueryPoolResults' or -- 'resetQueryPool' in other threads -- -- == Valid Usage (Implicit) -- -- - #VUID-vkResetQueryPool-device-parameter# @device@ /must/ be a valid -- 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkResetQueryPool-queryPool-parameter# @queryPool@ /must/ be a -- valid 'Vulkan.Core10.Handles.QueryPool' handle -- -- - #VUID-vkResetQueryPool-queryPool-parent# @queryPool@ /must/ have -- been created, allocated, or retrieved from @device@ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_host_query_reset VK_EXT_host_query_reset>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_2 VK_VERSION_1_2>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.QueryPool' resetQueryPool :: forall io . (MonadIO io) => -- | @device@ is the logical device that owns the query pool. Device -> -- | @queryPool@ is the handle of the query pool managing the queries being -- reset. QueryPool -> -- | @firstQuery@ is the initial query index to reset. ("firstQuery" ::: Word32) -> -- | @queryCount@ is the number of queries to reset. ("queryCount" ::: Word32) -> io () resetQueryPool device queryPool firstQuery queryCount = liftIO $ do let vkResetQueryPoolPtr = pVkResetQueryPool (case device of Device{deviceCmds} -> deviceCmds) unless (vkResetQueryPoolPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkResetQueryPool is null" Nothing Nothing let vkResetQueryPool' = mkVkResetQueryPool vkResetQueryPoolPtr traceAroundEvent "vkResetQueryPool" (vkResetQueryPool' (deviceHandle (device)) (queryPool) (firstQuery) (queryCount)) pure $ () -- | VkPhysicalDeviceHostQueryResetFeatures - Structure describing whether -- queries can be reset from the host -- -- = Members -- -- This structure describes the following feature: -- -- = Description -- -- If the 'PhysicalDeviceHostQueryResetFeatures' structure is included in -- the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. 'PhysicalDeviceHostQueryResetFeatures' /can/ also be used in -- the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to -- selectively enable these features. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_host_query_reset VK_EXT_host_query_reset>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_2 VK_VERSION_1_2>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceHostQueryResetFeatures = PhysicalDeviceHostQueryResetFeatures { -- | #extension-features-hostQueryReset# @hostQueryReset@ indicates that the -- implementation supports resetting queries from the host with -- 'resetQueryPool'. hostQueryReset :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceHostQueryResetFeatures) #endif deriving instance Show PhysicalDeviceHostQueryResetFeatures instance ToCStruct PhysicalDeviceHostQueryResetFeatures where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceHostQueryResetFeatures{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (hostQueryReset)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceHostQueryResetFeatures where peekCStruct p = do hostQueryReset <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ PhysicalDeviceHostQueryResetFeatures (bool32ToBool hostQueryReset) instance Storable PhysicalDeviceHostQueryResetFeatures where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceHostQueryResetFeatures where zero = PhysicalDeviceHostQueryResetFeatures zero
expipiplus1/vulkan
src/Vulkan/Core12/Promoted_From_VK_EXT_host_query_reset.hs
bsd-3-clause
8,456
0
17
1,391
1,337
795
542
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} module ClientProxyApi where import System.Random import Control.Monad.Trans.Except import Control.Monad.Trans.Resource hiding (register) import Control.Monad.IO.Class import Data.Aeson import Data.Aeson.TH import Data.Bson.Generic import GHC.Generics import Data.List.Split 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) import Data.Text (pack, unpack) import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Control.Monad (when) import Network.HTTP.Client (newManager, defaultManagerSettings) import System.Process import LRUCache as C import CommonResources type ApiHandler = ExceptT ServantErr IO serverport :: String serverport = "8080" serverhost :: String serverhost = "localhost" authApi :: Proxy AuthApi authApi = Proxy signin :: Signin -> ClientM Session register :: Signin -> ClientM Response signin :<|> register = client authApi signinQuery :: Signin -> ClientM Session signinQuery signindetails = do signinquery <- signin signindetails return signinquery registerQuery :: Signin -> ClientM Response registerQuery registerdetails = do registerquery <- register registerdetails return registerquery directoryApi :: Proxy DirectoryApi directoryApi = Proxy join :: FileServer -> ClientM Response open :: FileName -> ClientM File close :: FileUpload -> ClientM Response allfiles :: Ticket -> ClientM [String] remove :: FileName -> ClientM Response join :<|> open :<|> close :<|> allfiles :<|> remove = client directoryApi openQuery:: FileName -> ClientM File openQuery filename = do openquery <- open filename return openquery lockingApi :: Proxy LockingApi lockingApi = Proxy lock :: FileName -> ClientM Response unlock :: FileName -> ClientM Response islocked :: FileName -> ClientM Response lock :<|> unlock :<|> islocked = client lockingApi transactionApi :: Proxy TransactionApi transactionApi = Proxy begin :: Ticket -> ClientM Response transDownload :: FileName -> ClientM File transUpload :: FileUpload -> ClientM Response transCommit :: Ticket -> ClientM Response begin :<|> transDownload :<|> transUpload :<|> transCommit = client transactionApi mainClient :: IO() mainClient = do createDirectoryIfMissing True ("localstorage/") setCurrentDirectory ("localstorage/") authpart authpart :: IO() authpart = do putStrLn $ "Enter one of the following commands: LOGIN/REGISTER" cmd <- getLine case cmd of "LOGIN" -> authlogin "REGISTER" -> authregister authlogin :: IO () authlogin = do putStrLn $ "Enter your username:" username <- getLine putStrLn $ "Enter your password" password <- getLine let encryptedUname = encryptDecrypt password username let user = (Signin username encryptedUname) manager <- newManager defaultManagerSettings res <- runClientM (signinQuery user) (ClientEnv manager (BaseUrl Http authserverhost (read(authserverport) :: Int) "")) case res of Left err -> do putStrLn $ "Error: " ++ show err authpart Right response -> do let (Session encryptedTicket encryptedSessionKey encryptedTimeout) = response case encryptedTicket of "Failed" -> do putStrLn ("Could not login user") authpart _ -> do putStrLn ("Client Login Successful") let decryptedTicket = encryptDecrypt password encryptedTicket let decryptedSessionKey = encryptDecrypt password encryptedSessionKey cache <- C.newHandle 5 mainloop (Session decryptedTicket decryptedSessionKey encryptedTimeout) cache authregister :: IO () authregister = do putStrLn $ "Enter your details to make a new account" putStrLn $ "Enter your username:" username <- getLine putStrLn $ "Enter your password" password <- getLine let user = (Signin username password) manager <- newManager defaultManagerSettings res <- runClientM (registerQuery user) (ClientEnv manager (BaseUrl Http authserverhost (read(authserverport) :: Int) "")) case res of Left err -> do putStrLn $ "Error: " ++ show err authpart Right response -> authpart mainloop :: Session -> (C.Handle String String) -> IO() mainloop session cache = do putStrLn $ "Enter one of the following commands: FILES/UPLOAD/DOWNLOAD/TRANSACTION/CLOSE" cmd <- getLine case cmd of "FILES" -> displayFiles session cache "UPLOAD" -> uploadFile session cache "DOWNLOAD" -> downloadFile session cache "TRANSACTION" -> transactionMode session cache "CLOSE" -> putStrLn $ "Closing service!" _ -> do putStrLn $ "Invalid Command. Try Again" mainloop session cache updateCache :: Session -> (C.Handle String String) -> IO() updateCache session@(Session ticket sessionKey encryptedTimeout) cache = liftIO $ do putStrLn "Updating Cache..." fileList <- C.iogetContents cache mapM (downloadAndUpdate session cache) fileList putStrLn "Cache Updated" downloadAndUpdate :: Session -> (C.Handle String String) -> String -> IO() downloadAndUpdate session@(Session ticket sessionKey encryptedTimeout) cache fileName = liftIO $ do manager <- newManager defaultManagerSettings let encryptedFN = encryptDecrypt sessionKey fileName res <- runClientM (openQuery (FileName ticket encryptedTimeout encryptedFN)) (ClientEnv manager (BaseUrl Http dirserverhost (read(dirserverport) :: Int) "")) case res of Left err -> putStrLn (show err) Right response -> do let decryptedFC = encryptDecrypt sessionKey (fileContent response) C.ioinsert cache fileName decryptedFC putStrLn ("File: " ++ fileName ++ " Updated in Cache") displayFiles :: Session -> (C.Handle String String) -> IO() displayFiles session@(Session ticket sessionKey encryptedTimeout) cache = do putStrLn "Fetching file list. Please wait." manager <- newManager defaultManagerSettings res <- runClientM (allfiles (Ticket ticket encryptedTimeout)) (ClientEnv manager (BaseUrl Http dirserverhost (read(dirserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right fileEncrypt -> do let decryptedFiles = encryptDecryptArray sessionKey fileEncrypt mapM putStrLn decryptedFiles mainloop session cache uploadFile :: Session -> (C.Handle String String) -> IO() uploadFile session@(Session ticket sessionKey encryptedTimeout) cache = do putStrLn "Please enter the name of the file to upload" fileName <- getLine islocked <- lockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey case islocked of True -> do let cmd = shell ("vim " ++ fileName) createProcess_ "vim" cmd putStrLn $ "Hit enter when youre finished" enter <- getLine fileContent <- readFile fileName let encryptedFN = encryptDecrypt sessionKey fileName let encryptedFC = encryptDecrypt sessionKey fileContent manager <- newManager defaultManagerSettings res <- runClientM (close (FileUpload ticket encryptedTimeout (File encryptedFN encryptedFC))) (ClientEnv manager (BaseUrl Http dirserverhost (read(dirserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right (uploadResponse@(Response encryptedResponse)) -> do C.ioinsert cache (fileName) (fileContent) let decryptResponse = encryptDecrypt sessionKey encryptedResponse putStrLn decryptResponse isunlocked <- unlockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey case isunlocked of True -> putStrLn "File unlocked Successfully" False -> putStrLn "File cant be unlocked...This should never happen" mainloop session cache False -> do putStrLn "Failed to lock file" mainloop session cache downloadFile :: Session -> (C.Handle String String) -> IO() downloadFile session@(Session ticket sessionKey encryptedTimeout) cache = do updateCache session cache putStrLn "Please enter the name of the file to download" fileName <- getLine islocked <- lockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey case islocked of True -> do incache <- C.iolookup cache fileName case incache of (Nothing) -> do manager <- newManager defaultManagerSettings let encryptedFN = encryptDecrypt sessionKey fileName res <- runClientM (openQuery (FileName ticket encryptedTimeout encryptedFN)) (ClientEnv manager (BaseUrl Http dirserverhost (read(dirserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> do let decryptedFC = encryptDecrypt sessionKey (fileContent response) C.ioinsert cache fileName decryptedFC liftIO (writeFile fileName decryptedFC) let cmd = shell ("vim " ++ fileName) createProcess_ "vim" cmd putStrLn $ "When finished please press Enter" yesorno <- getLine putStrLn $ "Would you like to upload your changes? y/n" sure <- getLine case sure of ("y") -> do fileContent <- readFile fileName let file = File (encryptDecrypt sessionKey fileName) (encryptDecrypt sessionKey fileContent) manager <- newManager defaultManagerSettings res <- runClientM (close (FileUpload ticket encryptedTimeout file)) (ClientEnv manager (BaseUrl Http dirserverhost (read(dirserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right (uploadResponse@(Response encryptedResponse)) -> do C.ioinsert cache (fileName) (fileContent) let decryptResponse = encryptDecrypt sessionKey encryptedResponse putStrLn decryptResponse isunlocked <- unlockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey case isunlocked of True -> putStrLn "File unlocked Successfully" False -> putStrLn "File cant be unlocked...This should never happen" mainloop session cache (_) -> do isunlocked <- unlockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey case isunlocked of True -> putStrLn "File unlocked Successfully" False -> putStrLn "File cant be unlocked...This should never happen" mainloop session cache (Just v) -> do putStrLn $ "Cache hit" liftIO (writeFile (fileName) v) let cmd = shell ("vim " ++ fileName) createProcess_ "vim" cmd putStrLn $ "When finished please press enter" yesorno <- getLine putStrLn $ "Would you like to upload changes y/n?" sure <- getLine fileContent <- readFile (fileName) case sure of ("y") -> do let file = File (encryptDecrypt sessionKey fileName) (encryptDecrypt sessionKey fileContent) manager <- newManager defaultManagerSettings res <- runClientM (close (FileUpload ticket encryptedTimeout file)) (ClientEnv manager (BaseUrl Http dirserverhost (read(dirserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right (uploadResponse@(Response encryptedResponse)) -> do C.ioinsert cache (fileName) (fileContent) let decryptResponse = encryptDecrypt sessionKey encryptedResponse putStrLn decryptResponse isunlocked <- unlockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey case isunlocked of True -> putStrLn "File unlocked Successfully" False -> putStrLn "File cant be unlocked...This should never happen" mainloop session cache (_) -> do isunlocked <- unlockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey case isunlocked of True -> putStrLn "File unlocked Successfully" False -> putStrLn "File cant be unlocked...This should never happen" mainloop session cache False -> do putStrLn "Locking Failed" mainloop session cache transactionMode :: Session -> (C.Handle String String) -> IO() transactionMode session@(Session ticket sessionKey encryptedTimeout) cache = liftIO $ do manager <- newManager defaultManagerSettings res <- runClientM (begin (Ticket ticket encryptedTimeout)) (ClientEnv manager (BaseUrl Http transserverhost (read(transserverport) :: Int) "")) case res of Left err -> putStrLn (show err) Right (Response response) -> do case (encryptDecrypt sessionKey response) of "Successful" -> do putStrLn ("Transaction started") putStrLn "Fetching file list. Please wait." res <- runClientM (allfiles (Ticket ticket encryptedTimeout)) (ClientEnv manager (BaseUrl Http dirserverhost (read(dirserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right fileEncrypt -> do let decryptedFiles = encryptDecryptArray sessionKey fileEncrypt mapM putStrLn decryptedFiles putStrLn "Please enter the names of the files you wish to download seperated by a comma:" fileNames <- getLine let clines = splitOn "," fileNames lock <- mapM (\s -> lockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey s)) sessionKey) clines let are_locked = listand lock case are_locked of True -> do createDirectoryIfMissing True ("tmp/") setCurrentDirectory ("tmp/") mapM (transactionProcess session cache) clines putStrLn "All files processed. Press enter to commit the changes" enter <- getLine res <- runClientM (transCommit (Ticket ticket encryptedTimeout)) (ClientEnv manager (BaseUrl Http transserverhost (read(transserverport) :: Int) "")) case res of Left err -> do putStrLn (show err) mainloop session cache Right (Response response) -> do putStrLn ("File commit - " ++ (encryptDecrypt sessionKey response)) setCurrentDirectory ("../") removeDirectoryRecursive ("tmp/") mapM (\s -> unlockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey s)) sessionKey ) clines mainloop session cache False -> do putStrLn "Could not lock all files requested" mainloop session cache _ -> do putStrLn "Transaction Failed" transactionProcess :: Session -> (C.Handle String String) -> String -> IO() transactionProcess session@(Session ticket sessionKey encryptedTimeout) cache fileName = liftIO $ do putStrLn ("Beginning transaction for file: " ++ fileName) manager <- newManager defaultManagerSettings res <- runClientM (transDownload (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName))) (ClientEnv manager (BaseUrl Http transserverhost (read(transserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> do let decryptedFC = encryptDecrypt sessionKey (fileContent response) liftIO (writeFile fileName decryptedFC) let cmd = shell ("vim " ++ fileName) createProcess_ "vim" cmd putStrLn $ "When finished please press Enter" yesorno <- getLine putStrLn $ "Uploading changes" fileContent <- readFile fileName let file = File (encryptDecrypt sessionKey fileName) (encryptDecrypt sessionKey fileContent) manager <- newManager defaultManagerSettings res <- runClientM (transUpload (FileUpload ticket encryptedTimeout file)) (ClientEnv manager (BaseUrl Http transserverhost (read(transserverport) :: Int) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right (uploadResponse@(Response encryptedResponse)) -> do let decryptResponse = encryptDecrypt sessionKey encryptedResponse C.ioinsert cache (fileName) (fileContent) putStrLn ("File: " ++ fileName ++ " " ++ decryptResponse) --isunlocked <- unlockFile (FileName ticket encryptedTimeout (encryptDecrypt sessionKey fileName)) sessionKey --case isunlocked of -- True -> putStrLn "File unlocked Successfully" -- False -> putStrLn "File cant be unlocked...This should never happen" -- mainloop session cache lockFile :: FileName -> String -> IO Bool lockFile fName sessionKey = do manager <- newManager defaultManagerSettings res <- runClientM (lock fName) (ClientEnv manager (BaseUrl Http lockserverhost (read(lockserverport) :: Int) "")) case res of Left err -> do putStrLn $ "Error: " ++ show err return False Right (Response response) -> do putStrLn (encryptDecrypt sessionKey response) case (encryptDecrypt sessionKey response) of "Successful" -> return True _ -> return False unlockFile :: FileName -> String -> IO Bool unlockFile fName sessionKey = do manager <- newManager defaultManagerSettings res <- runClientM (unlock fName) (ClientEnv manager (BaseUrl Http lockserverhost (read(lockserverport) :: Int) "")) case res of Left err -> do putStrLn $ "Error: " ++ show err return False Right (Response response) -> do case (encryptDecrypt sessionKey response) of "Successful" -> return True _ -> return False listand :: [Bool] -> Bool listand [] = True listand (x:xs) | x == False = False | otherwise = listand xs
Garygunn94/DFS
ClientProxy/src/ClientProxyApi.hs
bsd-3-clause
20,133
12
40
5,797
5,115
2,443
2,672
389
12
module NLP.WordNet.PrimTypes where import Data.Array import System.IO import Control.OldException import Data.Dynamic (Typeable) type Offset = Integer -- | The basic part of speech type, either a 'Noun', 'Verb', 'Adj'ective or 'Adv'erb. data POS = Noun | Verb | Adj | Adv deriving (Eq, Ord, Show, Ix, Typeable) allPOS = [Noun ..] data EPOS = POS POS | Satellite | AdjSatellite | IndirectAnt | DirectAnt | UnknownEPos | Pertainym deriving (Eq, Ord, Typeable) fromEPOS (POS p) = p fromEPOS _ = Adj allEPOS = [POS Noun ..] instance Enum POS where toEnum 1 = Noun toEnum 2 = Verb toEnum 3 = Adj toEnum 4 = Adv fromEnum Noun = 1 fromEnum Verb = 2 fromEnum Adj = 3 fromEnum Adv = 4 enumFrom i = enumFromTo i Adv enumFromThen i j = enumFromThenTo i j Adv instance Enum EPOS where toEnum 1 = POS Noun toEnum 2 = POS Verb toEnum 3 = POS Adj toEnum 4 = POS Adv toEnum 5 = Satellite toEnum 6 = AdjSatellite fromEnum (POS Noun) = 1 fromEnum (POS Verb) = 2 fromEnum (POS Adj) = 3 fromEnum (POS Adv) = 4 fromEnum Satellite = 5 fromEnum AdjSatellite = 6 enumFrom i = enumFromTo i AdjSatellite enumFromThen i j = enumFromThenTo i j AdjSatellite instance Show EPOS where showsPrec i (POS p) = showsPrec i p showsPrec i (Satellite) = showString "Satellite" showsPrec i (AdjSatellite) = showString "AdjSatellite" showsPrec i (IndirectAnt) = showString "IndirectAnt" showsPrec i (DirectAnt) = showString "DirectAnt" showsPrec i (Pertainym) = showString "Pertainym" showsPrec i (UnknownEPos) = showString "UnknownEPos" instance Ix EPOS where range (i,j) = [i..j] index (i,j) a = fromEnum a - fromEnum i inRange (i,j) a = a `elem` [i..j] readEPOS :: String -> EPOS readEPOS "n" = POS Noun readEPOS "v" = POS Verb readEPOS "a" = POS Adj readEPOS "r" = POS Adv readEPOS "s" = Satellite data WordNetEnv = WordNetEnv { dataHandles :: Array POS (Handle, Handle), -- index, real excHandles :: Array POS Handle, -- for morphology senseHandle, countListHandle, keyIndexHandle, revKeyIndexHandle :: Maybe Handle, -- these are all optional vSentHandle :: Maybe (Handle, Handle), -- index, real wnReleaseVersion :: Maybe String, dataDirectory :: FilePath, warnAbout :: String -> Exception -> IO () } wordNetEnv0 = WordNetEnv { dataHandles = undefined, excHandles = undefined, senseHandle = Nothing, countListHandle = Nothing, keyIndexHandle = Nothing, revKeyIndexHandle = Nothing, vSentHandle = Nothing, wnReleaseVersion = Nothing, dataDirectory = "", warnAbout = \_ _ -> return () } data SenseKey = SenseKey { senseKeyPOS :: POS, senseKeyString :: String, senseKeyWord :: String } deriving (Show, Typeable) -- | A 'Key' is a simple pointer into the database, which can be -- followed using 'lookupKey'. newtype Key = Key (Offset, POS) deriving (Eq, Typeable) data Synset = Synset { hereIAm :: Offset, ssType :: EPOS, fnum :: Int, pos :: EPOS, ssWords :: [(String, Int, SenseType)], -- (word, lex-id, sense) whichWord :: Maybe Int, forms :: [(Form, Offset, EPOS, Int, Int)], frames :: [(Int, Int)], defn :: String, key :: Maybe Offset, searchType :: Int, headWord :: String, headSense :: SenseType } -- deriving (Show) synset0 = Synset 0 UnknownEPos (-1) undefined [] Nothing [] [] "" Nothing (-1) "" AllSenses -- | The basic type which holds search results. Its 'Show' instance simply -- shows the string corresponding to the associated WordNet synset. data SearchResult = SearchResult { srSenseKey :: Maybe SenseKey, -- | This provides (maybe) the associated overview for a SearchResult. -- The 'Overview' is only available if this 'SearchResult' was -- derived from a real search, rather than 'lookupKey'. srOverview :: Maybe Overview, srIndex :: Maybe Index, -- | This provides (maybe) the associated sense number for a SearchResult. -- The 'SenseType' is only available if this 'SearchResult' was -- derived from a real search, rather than 'lookupKey'. srSenseNum :: Maybe SenseType, srSynset :: Synset } deriving (Typeable) data Index = Index { indexWord :: String, indexPOS :: EPOS, indexSenseCount :: Int, indexForms :: [Form], indexTaggedCount :: Int, indexOffsets :: [Offset] } deriving (Eq, Ord, Show, Typeable) index0 = Index "" (POS Noun) (-1) [] (-1) [] -- | The different types of relations which can hold between WordNet Synsets. data Form = Antonym | Hypernym | Hyponym | Entailment | Similar | IsMember | IsStuff | IsPart | HasMember | HasStuff | HasPart | Meronym | Holonym | CauseTo | PPL | SeeAlso | Attribute | VerbGroup | Derivation | Classification | Class | Nominalization -- misc: | Syns | Freq | Frames | Coords | Relatives | HMeronym | HHolonym | WNGrep | OverviewForm | Unknown deriving (Eq, Ord, Show, Enum, Typeable) -- | A 'SenseType' is a way of controlling search. Either you specify -- a certain sense (using @SenseNumber n@, or, since 'SenseType' is an -- instance of 'Num', you can juse use @n@) or by searching using all -- senses, through 'AllSenses'. The 'Num' instance performs standard -- arithmetic on 'SenseNumber's, and 'fromInteger' yields a 'SenseNumber' (always), -- but any arithmetic involving 'AllSenses' returns 'AllSenses'. data SenseType = AllSenses | SenseNumber Int deriving (Eq, Ord, Show, Typeable) instance Num SenseType where fromInteger = SenseNumber . fromInteger SenseNumber n + SenseNumber m = SenseNumber $ n+m _ + _ = AllSenses SenseNumber n - SenseNumber m = SenseNumber $ n-m _ - _ = AllSenses SenseNumber n * SenseNumber m = SenseNumber $ n*m _ * _ = AllSenses negate (SenseNumber n) = SenseNumber $ negate n negate x = x abs (SenseNumber n) = SenseNumber $ abs n abs x = x signum (SenseNumber n) = SenseNumber $ signum n signum x = x -- | The 'Overview' type is the return type which gives you an -- overview of a word, for all sense and for all parts of speech. data Overview = Overview { nounIndex, verbIndex, adjIndex, advIndex :: Maybe Index } deriving (Eq, Ord, Show, Typeable)
svoisen/HWordNet
NLP/WordNet/PrimTypes.hs
bsd-3-clause
6,634
0
12
1,791
1,725
963
762
152
1
------------------------------------------------------------------------- -- | -- Module : Control.Kleislify -- Copyright : (c) Dylan Just, 2011 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Precomposition and postcomposition of functors and monads. -- -- Variants of Control.Arrow functions, specialised to kleislis. -- Avoids boxing into Kleisli values. module Control.Kleislify where import Control.Monad.Instances import Control.Monad infixr 1 ^=>, =>^, ^<=, <=^ infixr 1 ^->, ->^, ^<-, <-^ -- | precomposition of a monad with a pure function. -- Equivalent to 'Control.Arrow.^>>' -- Equivalent to 'flip (.)' (^=>) :: Monad m => (b -> c) -> (c -> m d) -> b -> m d (^=>) = flip (.) -- | precomposition of a functor with a pure function. -- Equivalent to 'flip (.)' (^->) :: Functor f => (b -> c) -> (c -> f d) -> b -> f d (^->) = flip (.) -- | postcomposition of a monad with a pure function. -- Equivalent to 'Control.Arrow.>>^' (=>^) :: Monad m => (b -> m c) -> (c -> d) -> b -> m d (=>^) = flip (^<=) -- | postcomposition of a functor with a pure function. -- Equivalent to 'Control.Arrow.>>^' (->^) :: Functor f => (b -> f c) -> (c -> d) -> b -> f d (->^) = flip (^<-) -- | precomposition of a monad with a pure function (right-to-left variant). -- Equivalent to 'Control.Arrow.<<^' -- Equivalent to '.' (<=^) :: Monad m => (c -> m d) -> (b -> c) -> (b -> m d) (<=^) = (.) -- | precomposition of a functor with a pure function (right-to-left variant). -- Equivalent to 'Control.Arrow.<<^' -- Equivalent to '.' (<-^) :: Functor f => (c -> f d) -> (b -> c) -> (b -> f d) (<-^) = (.) -- | postcomposition of a monad with a pure function (right-to-left variant). -- Equivalent to 'Control.Arrow.^<<' (^<=) :: Monad m => (c -> d) -> (b -> m c) -> b -> m d (^<=) = liftM . liftM -- | postcomposition of a functor with a pure function (right-to-left variant). -- Equivalent to 'Control.Arrow.^<<' (^<-) :: Functor f => (c -> d) -> (b -> f c) -> b -> f d (^<-) = fmap . fmap
techtangents/kleislify
Control/Kleislify.hs
bsd-3-clause
2,150
0
10
445
540
318
222
21
1
module TriangleKata.Day2 (triangle, TriangleType(..)) where data TriangleType = Illegal | Equilateral | Isosceles | Scalene deriving (Eq, Show) type Triangle = (Int, Int, Int) triangle :: Triangle -> TriangleType triangle (0, 0, 0) = Illegal triangle (a, b, c) | a + b < c || b + c < a || c + a < b = Illegal | a == b && b == c = Equilateral | a == b || b == c || c == a = Isosceles | otherwise = Scalene
Alex-Diez/haskell-tdd-kata
old-katas/src/TriangleKata/Day2.hs
bsd-3-clause
556
0
15
238
200
109
91
16
1
{-# LANGUAGE TypeFamilies,FlexibleContexts #-} module Trie where import Data.Array import Data.Monoid class Ix a => FiniteIx a where maxRange :: a -> (a, a) class (FiniteIx (Base a)) => Flat a where type Base a flatten :: a -> [Base a] data Trie k a = Single a | Trie (Array (Base k) (Trie k a)) a nil :: Monoid a => Trie k a nil = Single mempty root :: Monoid a => Trie k a -> a root (Single x) = x root (Trie _ x) = x path :: (Flat k, Monoid a) => [Base k] -> Trie k a -> Trie k a path [] t = t path (k:ks) (Trie a _) = path ks (a ! k) path _ _ = nil lookup :: (Flat k, Monoid a) => k -> Trie k a -> a lookup k t = root (path (flatten k) t) extend :: (Flat k, Monoid a) => Base k -> Trie k a -> Trie k a extend k (Single x) = Trie (listArray (maxRange k) (repeat nil)) x extend _ t = t insert' :: (Flat k, Monoid a) => [Base k] -> a -> Trie k a -> Trie k a insert' [] v (Single v') = Single (v `mappend` v') insert' [] v (Trie a v') = Trie a (v `mappend` v') insert' (k:ks) v t = Trie (modify (insert' ks v) k a) vs where Trie a vs = extend k t modify f k a = a // [(k, f (a ! k))] insert :: (Flat k, Monoid a) => k -> a -> Trie k a -> Trie k a insert k v t = insert' (flatten k) v t
jystic/QuickSpec
qs1/Trie.hs
bsd-3-clause
1,222
0
12
323
738
376
362
32
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} ----------------------------------------------------------------------------- -- | -- Module : Geometry.Segment -- Copyright : (c) 2011-2017 diagrams team (see LICENSE) -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- A /segment/ is a translation-invariant, atomic path. Currently, -- there are two types: linear (/i.e./ just a straight line to the -- endpoint) and cubic Bézier curves (/i.e./ a curve to an endpoint -- with two control points). This module contains tools for creating -- and manipulating segments, as well as a definition of segments with -- a fixed location (useful for backend implementors). -- -- Generally speaking, casual users should not need this module; the -- higher-level functionality provided by "Geometry.Trail" and -- "Geometry.Path" should usually suffice. However, directly -- manipulating segments can occasionally be useful. -- ----------------------------------------------------------------------------- module Geometry.Segment ( -- * Segments Segment (..) , straight , bezier3 , bézier3 , HasSegments (..) -- * Closing segments , ClosingSegment (..) , linearClosing , cubicClosing , closingSegment -- * Fixed segments , FixedSegment (..) , fixed -- * Crossings , Crossings (..) , isInsideWinding , isInsideEvenOdd -- * Low level -- ** Folding , segmentEnvelope , cubicEnvelope , envelopeOf , traceOf -- ** Segment calculations , paramsTangentTo , splitAtParams , unsafeSplitAtParams , secondDerivAtParam -- , collinear , segmentsEqual , segmentCrossings , linearCrossings , cubicCrossings , segmentParametersAtDirection , bezierParametersAtDirection ) where import Control.Applicative (liftA2) import Control.DeepSeq (NFData (..)) import Control.Lens hiding (at, transform, (<|), (|>)) import Control.Monad import qualified Data.Binary as Binary import Data.Bytes.Get (getWord8) import Data.Bytes.Put (putWord8) import Data.Bytes.Serial import Data.Functor.Classes import Data.Hashable import Data.Hashable.Lifted import Data.List (nub, sort) import qualified Data.Semigroup as Sem import Data.Sequence (Seq) import qualified Data.Sequence as Seq import qualified Data.Serialize as Cereal import GHC.Exts (build) import Linear.Affine import Linear.Metric import Linear.V2 import Linear.V3 import Linear.Vector import qualified Numeric.Interval.Kaucher as K import Numeric.Interval.NonEmpty.Internal (Interval (..), singleton) import Data.Coerce import Diagrams.Solve.Polynomial import Geometry.Angle import Geometry.Direction import Geometry.Envelope import Geometry.Located import Geometry.Parametric import Geometry.Query import Geometry.Space import Geometry.Transform import Geometry.TwoD.Transform ------------------------------------------------------------------------ -- Segments ------------------------------------------------------------------------ -- | The atomic constituents of the concrete representation currently -- used for trails are /segments/, currently limited to single -- straight lines or cubic Bézier curves. Segments are -- /translationally invariant/, that is, they have no particular -- \"location\" and are unaffected by translations. They are, however, -- affected by other transformations such as rotations and scales. data Segment v n = Linear !(v n) | Cubic !(v n) !(v n) !(v n) deriving Functor type instance V (Segment v n) = v type instance N (Segment v n) = n type instance Codomain (Segment v n) = v ------------------------------------------------------------ -- Instances instance (Eq1 v, Eq n) => Eq (Segment v n) where Linear v1 == Linear v2 = eq1 v1 v2 Cubic a1 b1 c1 == Cubic a2 b2 c2 = eq1 a1 a2 && eq1 b1 b2 && eq1 c1 c2 _ == _ = False {-# INLINE (==) #-} instance Show1 v => Show1 (Segment v) where liftShowsPrec x y d seg = case seg of Linear v -> showParen (d > 10) $ showString "straight " . liftShowsPrec x y 11 v Cubic v1 v2 v3 -> showParen (d > 10) $ showString "bezier3 " . liftShowsPrec x y 11 v1 . showChar ' ' . liftShowsPrec x y 11 v2 . showChar ' ' . liftShowsPrec x y 11 v3 instance (Show1 v, Show n) => Show (Segment v n) where showsPrec = showsPrec1 instance Each (Segment v n) (Segment v n) (v n) (v n) where each f (Linear v) = Linear <$> f v each f (Cubic c1 c2 c3) = Cubic <$> f c1 <*> f c2 <*> f c3 {-# INLINE each #-} instance NFData (v n) => NFData (Segment v n) where rnf = \case Linear v -> rnf v Cubic c1 c2 c3 -> rnf c1 `seq` rnf c2 `seq` rnf c3 {-# INLINE rnf #-} instance Hashable1 v => Hashable1 (Segment v) where liftHashWithSalt f s = \case Linear v -> hws s0 v Cubic c1 c2 c3 -> hws (hws (hws s1 c1) c2) c3 where s0 = hashWithSalt s (0::Int) s1 = hashWithSalt s (1::Int) hws = liftHashWithSalt f {-# INLINE liftHashWithSalt #-} instance (Hashable1 v, Hashable n) => Hashable (Segment v n) where hashWithSalt = hashWithSalt1 {-# INLINE hashWithSalt #-} instance Serial1 v => Serial1 (Segment v) where serializeWith f = \case Linear v -> putWord8 0 >> fv v Cubic c1 c2 c3 -> putWord8 1 >> fv c1 >> fv c2 >> fv c3 where fv = serializeWith f {-# INLINE serializeWith #-} deserializeWith m = getWord8 >>= \case 0 -> Linear `liftM` mv _ -> Cubic `liftM` mv `ap` mv `ap` mv where mv = deserializeWith m {-# INLINE deserializeWith #-} instance (Serial1 v, Serial n) => Serial (Segment v n) where serialize = serializeWith serialize {-# INLINE serialize #-} deserialize = deserializeWith deserialize {-# INLINE deserialize #-} instance (Serial1 v, Binary.Binary n) => Binary.Binary (Segment v n) where put = serializeWith Binary.put {-# INLINE put #-} get = deserializeWith Binary.get {-# INLINE get #-} instance (Serial1 v, Cereal.Serialize n) => Cereal.Serialize (Segment v n) where put = serializeWith Cereal.put {-# INLINE put #-} get = deserializeWith Cereal.get {-# INLINE get #-} ------------------------------------------------------------ -- Smart constructors -- | @'straight' v@ constructs a translationally invariant linear -- segment with direction and length given by the vector @v@. straight :: v n -> Segment v n straight = Linear {-# INLINE straight #-} -- | @bezier3 c1 c2 x@ constructs a translationally invariant cubic -- Bézier curve where the offsets from the first endpoint to the -- first and second control point and endpoint are respectively -- given by @c1@, @c2@, and @x@. bezier3 :: v n -> v n -> v n -> Segment v n bezier3 = Cubic {-# INLINE bezier3 #-} -- | @bézier3@ is the same as @bezier3@, but with more snobbery. bézier3 :: v n -> v n -> v n -> Segment v n bézier3 = Cubic {-# INLINE bézier3 #-} -- | Things where the segments can be folded over. class HasSegments t where -- | Fold over the segments in a trail. segments :: Fold t (Segment (V t) (N t)) -- | The offset from the start of the first segment to the end of the -- last segment. offset :: t -> Vn t default offset :: (Additive (V t), Num (N t)) => t -> Vn t offset = foldlOf' segments (\off seg -> off ^+^ offset seg) zero -- | The number of segments. numSegments :: t -> Int numSegments = lengthOf segments instance HasSegments (Segment v n) where segments f s = f s {-# INLINE segments #-} offset (Linear v) = v offset (Cubic _ _ v) = v {-# INLINE offset #-} numSegments _ = 1 {-# INLINE numSegments #-} instance HasSegments a => HasSegments (Located a) where segments = located . segments {-# INLINE segments #-} offset = offset . unLoc {-# INLINE offset #-} numSegments = numSegments . unLoc {-# INLINE numSegments #-} -- Orphan instance because HasSegments is here, and we depend on Loc -- here. One option would be to have a HasOffset class in Geo.Loc and -- HasOffset -> HasSegments. instance (InSpace v n a, HasSegments a, Reversing a) => Reversing (Located a) where reversing = \(Loc p a) -> Loc (p .+^ offset a) (reversing a) {-# INLINE reversing #-} instance (Additive v, Foldable v, Num n) => Transformable (Segment v n) where transform !t (Linear v) = Linear (apply t v) transform !t (Cubic v1 v2 v3) = Cubic (apply t v1) (apply t v2) (apply t v3) {-# INLINE transform #-} instance (Additive v, Num n) => Parametric (Segment v n) where atParam (Linear x) t = t *^ x atParam (Cubic c1 c2 x2) t = (3 * t'*t'*t ) *^ c1 ^+^ (3 * t'*t *t ) *^ c2 ^+^ ( t *t *t ) *^ x2 where t' = 1-t {-# INLINE atParam #-} instance (Additive v, Num n) => Tangential (Segment v n) where Linear v `tangentAtParam` _ = v Cubic c1 c2 c3 `tangentAtParam` t = (3*(3*t*t-4*t+1))*^ c1 ^+^ (3*(2-3*t)*t) *^ c2 ^+^ (3*t*t) *^ c3 {-# INLINE tangentAtParam #-} instance (Additive v, Num n) => TangentEndValues (Segment v n) where tangentAtStart = \case Linear v -> v Cubic c1 _ _ -> 3*^c1 {-# INLINE tangentAtStart #-} tangentAtEnd = \case Linear v -> v Cubic _ c2 c3 -> 3*^(c3 ^-^ c2) {-# INLINE tangentAtEnd #-} instance Num n => DomainBounds (Segment v n) instance (Additive v, Num n) => EndValues (Segment v n) where atStart = const zero {-# INLINE atStart #-} atEnd (Linear v) = v atEnd (Cubic _ _ v) = v {-# INLINE atEnd #-} instance (Additive v, Fractional n) => Sectionable (Segment v n) where splitAtParam (Linear x1) t = (left, right) where left = straight p right = straight (x1 ^-^ p) p = lerp t x1 zero splitAtParam (Cubic c1 c2 x2) t = (left, right) where left = bezier3 a b e right = bezier3 (c ^-^ e) (d ^-^ e) (x2 ^-^ e) p = lerp t c2 c1 a = lerp t c1 zero b = lerp t p a d = lerp t x2 c2 c = lerp t d p e = lerp t c b {-# INLINE splitAtParam #-} reverseDomain (Linear x1) = Linear (negated x1) reverseDomain (Cubic c1 c2 c3) = Cubic (c2 ^-^ c3) (c1 ^-^ c3) (negated c3) {-# INLINE reverseDomain #-} instance (Additive v, Num n) => Reversing (Segment v n) where reversing (Linear x1) = Linear (negated x1) reversing (Cubic c1 c2 c3) = Cubic (c2 ^-^ c3) (c1 ^-^ c3) (negated c3) {-# INLINE reversing #-} instance (Metric v, OrderedField n) => HasArcLength (Segment v n) where arcLengthBounded _ (Linear x1) = K.singleton $ norm x1 arcLengthBounded m s@(Cubic c1 c2 x2) | ub - lb < m = K.I lb ub | otherwise = arcLengthBounded (m/2) l + arcLengthBounded (m/2) r where (l,r) = s `splitAtParam` 0.5 ub = sum (map norm [c1, c2 ^-^ c1, x2 ^-^ c2]) lb = norm x2 arcLengthToParam m s _ | arcLength m s == 0 = 0.5 arcLengthToParam m s@(Linear {}) len = len / arcLength m s arcLengthToParam m s@(Cubic {}) len | len `K.member` K.I (-m/2) (m/2) = 0 | len < 0 = - arcLengthToParam m (fst (splitAtParam s (-1))) (-len) | len `K.member` slen = 1 | len > K.sup slen = 2 * arcLengthToParam m (fst (splitAtParam s 2)) len | len < K.sup llen = (*0.5) $ arcLengthToParam m l len | otherwise = (+0.5) . (*0.5) $ arcLengthToParam (9*m/10) r (len - K.midpoint llen) where (l,r) = s `splitAtParam` 0.5 llen = arcLengthBounded (m/10) l slen = arcLengthBounded m s -- | The second derivative of the parametric curve \(d^2 S(t) / d t^2\). -- This is similar to curvature except the curvature is the norm of the -- second derivative with respect to the segment length \(|d^2 \gamma(s) -- / d s^2|\). secondDerivAtParam :: (Additive v, Num n) => Segment v n -> n -> v n secondDerivAtParam s t = case s of Linear _ -> zero Cubic c1 c2 c3 -> (6*(3*t-2))*^c1 ^+^ (6-18*t)*^c2 ^+^ (6*t)*^c3 -- It's been a while since I've looked at this, not quite sure why it's -- commented out. Something to do with PosInf I think. -- curvatureAtParam :: (Additive v, Floating n) => Segment v n -> n -> n -- curvatureAtParam s t = sqrt (curvatureSqAtParam s t) -- curvatureSqAtParam :: (Additive v, Fractional n) => Segment v n -> n -> PosInf n -- curvatureSqAtParam s t = case s of -- Linear _ -> zero -- Cubic {} -> (qs' * qs'' - (s' `dot` s'')^(2::Int)) / qs'^(3::Int) -- where -- s' = s `tangentAtParam` t -- s'' = s `secondDerivAtParam` t -- qs' = quadrance s' -- qs'' = quadrance s'' -- Envelopes ----------------------------------------------------------- -- | Envelope specialised to cubic segments used for 'segmentEnvelope'. -- This definition specialised to @V2 Double@ and @V3 Double@. cubicEnvelope :: (Metric v, Floating n, Ord n) => v n -> v n -> v n -> v n -> Interval n cubicEnvelope !c1 !c2 !c3 !v | l > 0 = I 0 u | u < 0 = I l 0 | otherwise = I l u where I l u = foldr (\n (I x y) -> I (min x n) (max y n)) (singleton $ c3 `dot` v) (map f quadSol) f t = (Cubic c1 c2 c3 `atParam` t) `dot` v quadSol = filter (\x -> (x>0) && (x<1)) $ quadForm a b c a = 3 * ((3 *^ c1 ^-^ 3 *^ c2 ^+^ c3) `dot` v) b = 6 * (((-2) *^ c1 ^+^ c2) `dot` v) c = (3 *^ c1) `dot` v {-# SPECIALISE cubicEnvelope :: V2 Double -> V2 Double -> V2 Double -> V2 Double -> Interval Double #-} {-# SPECIALISE cubicEnvelope :: V3 Double -> V3 Double -> V3 Double -> V3 Double -> Interval Double #-} -- | Envelope of single segment without the 'Envelope' wrapper. segmentEnvelope :: (Metric v, OrderedField n) => Segment v n -> Direction v n -> Interval n segmentEnvelope !s = \(Dir v) -> case s of Linear l -> let !x = l `dot` v in if x < 0 then I x 0 else I 0 x Cubic c1 c2 c3 -> cubicEnvelope c1 c2 c3 v {-# INLINE segmentEnvelope #-} instance (Metric v, OrderedField n) => Enveloped (Segment v n) where getEnvelope s = Envelope (segmentEnvelope s) {-# INLINE getEnvelope #-} data Pair a b = Pair !a !b getB :: Pair a b -> b getB (Pair _ b) = b -- | Calculate the envelope using a fold over segments. envelopeOf :: (InSpace v n t, Metric v, OrderedField n) => Fold t (Segment v n) -> t -> v n -> Interval n envelopeOf l = \ !t !w -> let f (Pair p e) !seg = Pair (p .+^ offset seg) e' where e' = combine e (moveBy (view _Point p `dot` w) $ segmentEnvelope seg (Dir w)) -- combine (I a1 b1) (I a2 b2) = I (min a1 a2) (max b1 b2) moveBy n (I a b) = I (a + n) (b + n) in getB $ foldlOf' l f (Pair origin (I 0 0)) t {-# INLINE envelopeOf #-} ------------------------------------------------------------------------ -- 2D specific ------------------------------------------------------------------------ -- trace --------------------------------------------------------------- -- | Calculate the trace using a fold over segments. traceOf :: (InSpace V2 n t, OrderedField n) => Fold t (Segment V2 n) -> Point V2 n -- trail start -> t -- trail -> Point V2 n -- trace start -> V2 n -- trace direction -> Seq n -- unsorted list of values traceOf fold p0 trail p v@(V2 !vx !vy) = view _3 $ foldlOf' fold f (p0,False,mempty :: Seq n) trail where !theta = atan2A' vy vx !t2 = scaling (1/norm v) Sem.<> rotation (negated theta) Sem.<> translation (negated $ p^._Point) f (!q,!_nearStart,!ts) (Linear w) | parallel || not inRange = (q .+^ w, False, ts) | otherwise = (q .+^ w, nearEnd, ts :> tv) where parallel = x1 == 0 && x2 /= 0 nearEnd = tw > 0.999 inRange = tw >= 0 && tw <= 1.001 -- tv = x3 / x1 tw = x2 / x1 -- x1 = v `crossZ` w x2 = pq `crossZ` v x3 = pq `crossZ` w pq = q .-. p f (q,nearStart, ts) (Cubic c1 c2 c3) = (q .+^ c3, nearEnd, ts Sem.<> Seq.fromList ts') where P (V2 qx qy) = papply t2 q c1'@(V2 _ y1) = apply t2 c1 c2'@(V2 _ y2) = apply t2 c2 c3'@(V2 _ y3) = apply t2 c3 -- a = 3*y1 - 3*y2 + y3 b = -6*y1 + 3*y2 c = 3*y1 d = qy tcs = filter (liftA2 (&&) (>= startLooking) (<= 1.0001)) (cubForm' 1e-8 a b c d) ts' = map ((+qx) . view _x . atParam (Cubic c1' c2' c3')) tcs -- if there was an intersecion near the end of the previous -- segment, don't look for an intersecion at the beggining of -- this one startLooking | nearStart = 0.0001 | otherwise = 0 -- if there's an intersection near the end of the segment, we -- don't look for an intersecion near the start of the next -- segment nearEnd = any (>0.9999) tcs {-# INLINE traceOf #-} -- crossings ----------------------------------------------------------- -- | The sum of /signed/ crossings of a path as we travel in the -- positive x direction from a given point. -- -- - A point is filled according to the 'Winding' fill rule, if the -- number of 'Crossings' is non-zero (see 'isInsideWinding'). -- -- - A point is filled according to the 'EvenOdd' fill rule, if the -- number of 'Crossings' is odd (see 'isInsideEvenOdd'). -- -- This is the 'HasQuery' result for 'Path's, 'Located' 'Trail's and -- 'Located' 'Loops'. -- -- @ -- 'sample' :: 'Geometry.Path.Path' 'V2' 'Double' -> 'Point' 'V2' 'Double' -> 'Crossings' -- 'sample' :: 'Located' ('Geometry.Trail.Loop' 'V2' 'Double') -> 'Point' 'V2' 'Double' -> 'Crossings' -- 'sample' :: 'Located' ('Geometry.Trail.Trail' 'V2' 'Double') -> 'Point' 'V2' 'Double' -> 'Crossings' -- @ -- -- Note that 'Line's have no inside or outside, so don't contribute -- crossings. newtype Crossings = Crossings Int deriving (Show, Eq, Ord, Num, Enum, Real, Integral) instance Sem.Semigroup Crossings where (<>) = coerce ((+) :: Int -> Int -> Int) {-# INLINE (<>) #-} instance Monoid Crossings where mempty = Crossings 0 {-# INLINE mempty #-} mappend = (Sem.<>) {-# INLINE mappend #-} -- | Test whether the given point is inside the given path, -- by testing whether the point's /winding number/ is nonzero. Note -- that @False@ is /always/ returned for paths consisting of lines -- (as opposed to loops), regardless of the winding number. -- -- @ -- 'isInsideWinding' :: 'Geometry.Path.Path' 'V2' 'Double' -> 'Point' 'V2' 'Double' -> 'Bool' -- 'isInsideWinding' :: 'Located' ('Geometry.Trail.Loop' 'V2' 'Double') -> 'Point' 'V2' 'Double' -> 'Bool' -- 'isInsideWinding' :: 'Located' ('Geometry.Trail.Trail' 'V2' 'Double') -> 'Point' 'V2' 'Double' -> 'Bool' -- @ isInsideWinding :: HasQuery t Crossings => t -> Point (V t) (N t) -> Bool isInsideWinding t = (/= 0) . sample t {-# INLINE isInsideWinding #-} -- | Test whether the given point is inside the given path, -- by testing whether a ray extending from the point in the positive -- x direction crosses the path an even (outside) or odd (inside) -- number of times. Note that @False@ is /always/ returned for -- paths consisting of lines (as opposed to loops), regardless of -- the number of crossings. -- -- @ -- 'isInsideEvenOdd' :: 'Geometry.Path.Path' 'V2' 'Double' -> 'Point' 'V2' 'Double' -> 'Bool' -- 'isInsideEvenOdd' :: 'Located' ('Geometry.Trail.Loop' 'V2' 'Double') -> 'Point' 'V2' 'Double' -> 'Bool' -- 'isInsideEvenOdd' :: 'Located' ('Geometry.Trail.Trail' 'V2' 'Double') -> 'Point' 'V2' 'Double' -> 'Bool' -- @ isInsideEvenOdd :: HasQuery t Crossings => t -> Point (V t) (N t) -> Bool isInsideEvenOdd t = odd . sample t {-# INLINE isInsideEvenOdd #-} -- | The crossings of a single segment given the query point and the -- starting point of the segment. segmentCrossings :: OrderedField n => Point V2 n -- ^ query point -> Point V2 n -- ^ start of segment -> Segment V2 n -> Crossings segmentCrossings q a = \case Linear v -> linearCrossings q a v Cubic c1 c2 c3 -> cubicCrossings q a c1 c2 c3 {-# INLINE segmentCrossings #-} linearCrossings :: OrderedField n => Point V2 n -- ^ query point -> Point V2 n -- ^ start of segment -> V2 n -- ^ c1 -> Crossings linearCrossings q@(P (V2 _ qy)) a@(P (V2 _ ay)) v@(V2 _ vy) | ay <= qy && by > qy && isLeft = 1 | by <= qy && ay > qy && not isLeft = -1 | otherwise = 0 where isLeft = crossZ v (q .-. a) > 0 by = ay + vy {-# SPECIALISE linearCrossings :: Point V2 Double -> Point V2 Double -> V2 Double -> Crossings #-} cubicCrossings :: OrderedField n => Point V2 n -- ^ query point -> Point V2 n -- ^ start of segment -> V2 n -- ^ c1 -> V2 n -- ^ c2 -> V2 n -- ^ c3 -> Crossings cubicCrossings (P (V2 qx qy)) (P (V2 ax ay)) c1@(V2 _ c1y) c2@(V2 _ c2y) c3@(V2 _ c3y) = sum $ map tTest ts' where -- potential t values at which the line y=qy intersects the segment ts' = filter inRange ts ts = cubForm ( 3*c1y - 3*c2y + c3y) (-6*c1y + 3*c2y) ( 3*c1y) (ay - qy) inRange t = t >= 0 && t <= 1 -- Check if the intersection point lies to the right of the query -- point. If it is return return the crossing sign depending on the -- tangent at that point. tTest t | ty == 0 = 0 | ax + dx > qx = sign | otherwise = 0 where sign | theta > 0 = 1 | otherwise = -1 theta = atan2A' ty tx ^. rad V2 dx _ = Cubic c1 c2 c3 `atParam` t V2 tx ty = Cubic c1 c2 c3 `tangentAtParam` t {-# SPECIALISE cubicCrossings :: Point V2 Double -> Point V2 Double -> V2 Double -> V2 Double -> V2 Double -> Crossings #-} -- | The parameters at which the segment is tangent to the given -- direction. paramsTangentTo :: OrderedField n => V2 n -> Segment V2 n -> [n] paramsTangentTo (V2 tx ty) (Cubic (V2 x1 y1) (V2 x2 y2) (V2 x3 y3)) = filter (\x -> x >= 0 && x <= 1) (quadForm a b c) where a = tx*(y3 + 3*(y1 - y2)) - ty*(x3 + 3*(x1 - x2)) b = 2*(tx*(y2 - 2*y1) - ty*(x2 - 2*x1)) c = tx*y1 - ty*x1 paramsTangentTo _ (Linear {}) = [] -- | Split a 'Sectionable' up at the given parameters and return each -- segment, in order. splitAtParams :: (InSpace v n t, Ord n, Fractional n, Sectionable t) => t -> [n] -> [t] splitAtParams t = unsafeSplitAtParams t . nub . sort . filter (\x -> x >= 0 && x < 1) -- | Split a sectionable between a list of times. The list should be -- sorted, distinct and between 0 and 1. unsafeSplitAtParams :: (InSpace v n t, Fractional n, Sectionable t) => t -> [n] -> [t] unsafeSplitAtParams seg0 ts0 = build $ \(|>) z -> let go !_ seg [] = seg |> z go t0 seg (t:ts) = s1 |> go t s2 ts where -- We want to split where t would lie on the original segment -- [0,1] and the partial segment @seg@ we've got to split -- corresponds to [t0,1] of the original segment. To get the -- new parameter we shift back to the origin (-t0) and rescale -- (* 1/(1-t0)). -- -- seg0 -- [-----|----------|-------------] -- 0 t0 t 1 -- -- seg -- [----------|-------------] -- t0 t 1 -- -- seg shifted -- [----------|-------------] -- 0 t - t0 1 - t0 -- -- seg scaled -- [---------------|--------------] -- 0 (t - t0) / (1 - t0) 1 -- t' = (t - t0) / (1 - t0) (s1,s2) = seg `splitAtParam` t' in go 0 seg0 ts0 -- does fusion actually help here? -- would probably be better if ts was given as a (unboxed) vector -- | Checks whether the points on the cubic segment lie in a straight -- line. -- collinear :: OrderedField n => n -> Segment V2 n -> Bool -- collinear _ Linear {} = True -- collinear eps (Cubic c1 c2 c3) = undefined -- | Check if two segments are approximately equal. segmentsEqual :: OrderedField n => n -> Segment V2 n -> Segment V2 n -> Bool segmentsEqual eps (Cubic a1 a2 a3) (Cubic b1 b2 b3) -- controlpoints equal within tol | distance a1 b1 < eps && distance a2 b2 < eps && distance a3 b3 < eps = True -- compare if both are collinear and close together -- - | dist < eps && -- collinear ((eps-dist)/2) cb1 && -- collinear ((eps-dist)/2) cb2 = True | otherwise = False -- where dist = max (abs $ ld b0) (abs $ ld b3) -- ld = distance lineDistance (Line a0 a3) segmentsEqual _ _ _ = undefined ------------------------------------------------------------------------ -- Closing segments ------------------------------------------------------------------------ -- | A ClosingSegment is used to determine how to close a loop. A linear -- closing means to close a trail with a straight line. A cubic closing -- segment means close the trail with a cubic bezier with control -- points c1 and c2. data ClosingSegment v n = LinearClosing | CubicClosing !(v n) !(v n) deriving Functor type instance V (ClosingSegment v n) = v type instance N (ClosingSegment v n) = n instance (Eq1 v, Eq n) => Eq (ClosingSegment v n) where LinearClosing == LinearClosing = True CubicClosing b1 c1 == CubicClosing b2 c2 = eq1 b1 b2 && eq1 c1 c2 _ == _ = False {-# INLINE (==) #-} instance Show1 v => Show1 (ClosingSegment v) where liftShowsPrec x y d = \case LinearClosing -> showString "linearClosing" CubicClosing v1 v2 -> showParen (d > 10) $ showString "cubicClosing " . liftShowsPrec x y 11 v1 . showChar ' ' . liftShowsPrec x y 11 v2 instance (Show1 v, Show n) => Show (ClosingSegment v n) where showsPrec = showsPrec1 instance (Metric v, Foldable v, Num n) => Transformable (ClosingSegment v n) where transform t (CubicClosing c1 c2) = CubicClosing (apply t c1) (apply t c2) transform _ LinearClosing = LinearClosing {-# INLINE transform #-} instance NFData (v n) => NFData (ClosingSegment v n) where rnf = \case LinearClosing -> () CubicClosing c1 c2 -> rnf c1 `seq` rnf c2 {-# INLINE rnf #-} instance Hashable1 v => Hashable1 (ClosingSegment v) where liftHashWithSalt f s = \case LinearClosing -> s0 CubicClosing c1 c2 -> hws (hws s1 c1) c2 where s0 = hashWithSalt s (0::Int) s1 = hashWithSalt s (1::Int) hws = liftHashWithSalt f {-# INLINE liftHashWithSalt #-} instance (Hashable1 v, Hashable n) => Hashable (ClosingSegment v n) where hashWithSalt = hashWithSalt1 {-# INLINE hashWithSalt #-} instance Serial1 v => Serial1 (ClosingSegment v) where serializeWith f = \case LinearClosing -> putWord8 0 CubicClosing c1 c2 -> putWord8 1 >> fv c1 >> fv c2 where fv = serializeWith f {-# INLINE serializeWith #-} deserializeWith m = getWord8 >>= \case 0 -> return LinearClosing _ -> CubicClosing `liftM` mv `ap` mv where mv = deserializeWith m {-# INLINE deserializeWith #-} instance (Serial1 v, Serial n) => Serial (ClosingSegment v n) where serialize = serializeWith serialize {-# INLINE serialize #-} deserialize = deserializeWith deserialize {-# INLINE deserialize #-} instance (Serial1 v, Binary.Binary n) => Binary.Binary (ClosingSegment v n) where put = serializeWith Binary.put {-# INLINE put #-} get = deserializeWith Binary.get {-# INLINE get #-} instance (Serial1 v, Cereal.Serialize n) => Cereal.Serialize (ClosingSegment v n) where put = serializeWith Cereal.put {-# INLINE put #-} get = deserializeWith Cereal.get {-# INLINE get #-} -- | Create a linear closing segment. linearClosing :: ClosingSegment v n linearClosing = LinearClosing {-# INLINE linearClosing #-} -- | Create a closing segment with control points @c1@ and @c2@. cubicClosing :: v n -> v n -> ClosingSegment v n cubicClosing = CubicClosing {-# INLINE cubicClosing #-} -- | Return the segment that closes a trail given the offset from the -- start of the trail to the start of the closing segment. closingSegment :: (Functor v, Num n) => v n -> ClosingSegment v n -> Segment v n closingSegment off LinearClosing = Linear (negated off) closingSegment off (CubicClosing c1 c2) = Cubic c1 c2 (negated off) {-# INLINE closingSegment #-} ------------------------------------------------------------------------ -- Fixed segments ------------------------------------------------------------------------ -- | @FixedSegment@s are like 'Segment's except that they have -- absolute locations. @FixedSegment v@ is isomorphic to @Located -- (Segment Closed v)@, as witnessed by 'mkFixedSeg' and -- 'fromFixedSeg', but @FixedSegment@ is convenient when one needs -- the absolute locations of the vertices and control points. data FixedSegment v n = FLinear !(Point v n) !(Point v n) | FCubic !(Point v n) !(Point v n) !(Point v n) !(Point v n) deriving (Show, Read, Eq) type instance V (FixedSegment v n) = v type instance N (FixedSegment v n) = n instance Each (FixedSegment v n) (FixedSegment v' n') (Point v n) (Point v' n') where each f (FLinear p0 p1) = FLinear <$> f p0 <*> f p1 each f (FCubic p0 p1 p2 p3) = FCubic <$> f p0 <*> f p1 <*> f p2 <*> f p3 {-# INLINE each #-} -- | Reverses the control points. instance Reversing (FixedSegment v n) where reversing (FLinear p0 p1) = FLinear p1 p0 reversing (FCubic p0 p1 p2 p3) = FCubic p3 p2 p1 p0 {-# INLINE reversing #-} instance (Additive v, Foldable v, Num n) => Transformable (FixedSegment v n) where transform t = over each (transform t) {-# INLINE transform #-} instance (Additive v, Num n) => HasOrigin (FixedSegment v n) where moveOriginTo o = over each (moveOriginTo o) {-# INLINE moveOriginTo #-} instance (Metric v, OrderedField n) => Enveloped (FixedSegment v n) where getEnvelope f = moveTo p (getEnvelope s) where (p, s) = viewLoc $ f ^. fixed {-# INLINE getEnvelope #-} instance (Metric v, OrderedField n) => HasArcLength (FixedSegment v n) where arcLengthBounded m s = arcLengthBounded m (s ^. fixed) arcLengthToParam m s = arcLengthToParam m (s ^. fixed) instance (Metric v, OrderedField n) => HasSegments (FixedSegment v n) where segments = fixed . located {-# INLINE segments #-} offset = offset . view fixed {-# INLINE offset #-} numSegments _ = 1 {-# INLINE numSegments #-} instance NFData (v n) => NFData (FixedSegment v n) where rnf = \case FLinear p1 p2 -> rnf p1 `seq` rnf p2 FCubic p1 p2 p3 p4 -> rnf p1 `seq` rnf p2 `seq` rnf p3 `seq` rnf p4 {-# INLINE rnf #-} instance Hashable1 v => Hashable1 (FixedSegment v) where liftHashWithSalt f s = \case FLinear p1 p2 -> hws (hws s0 p1) p2 FCubic p1 p2 p3 p4 -> hws (hws (hws (hws s1 p1) p2) p3) p4 where s0 = hashWithSalt s (0::Int) s1 = hashWithSalt s (1::Int) hws s' = liftHashWithSalt f s' . view _Point {-# INLINE liftHashWithSalt #-} instance (Hashable1 v, Hashable n) => Hashable (FixedSegment v n) where hashWithSalt = hashWithSalt1 {-# INLINE hashWithSalt #-} instance Serial1 v => Serial1 (FixedSegment v) where serializeWith f = \case FLinear p1 p2 -> putWord8 0 >> fv p1 >> fv p2 FCubic p1 p2 p3 p4 -> putWord8 1 >> fv p1 >> fv p2 >> fv p3 >> fv p4 where fv = serializeWith f {-# INLINE serializeWith #-} deserializeWith m = getWord8 >>= \case 0 -> FLinear `liftM` mv `ap` mv _ -> FCubic `liftM` mv `ap` mv `ap` mv `ap` mv where mv = deserializeWith m {-# INLINE deserializeWith #-} instance (Serial1 v, Serial n) => Serial (FixedSegment v n) where serialize = serializeWith serialize {-# INLINE serialize #-} deserialize = deserializeWith deserialize {-# INLINE deserialize #-} instance (Serial1 v, Binary.Binary n) => Binary.Binary (FixedSegment v n) where put = serializeWith Binary.put {-# INLINE put #-} get = deserializeWith Binary.get {-# INLINE get #-} instance (Serial1 v, Cereal.Serialize n) => Cereal.Serialize (FixedSegment v n) where put = serializeWith Cereal.put {-# INLINE put #-} get = deserializeWith Cereal.get {-# INLINE get #-} -- | Fixed segments and located segments are isomorphic. fixed :: (Additive v, Num n) => Iso' (FixedSegment v n) (Located (Segment v n)) fixed = iso fromFixedSeg mkFixedSeg {-# INLINE fixed #-} -- | Make a fixed segment from a located segment. mkFixedSeg :: (Additive v, Num n) => Located (Segment v n) -> FixedSegment v n mkFixedSeg = \case Loc p (Linear v) -> FLinear p (p .+^ v) Loc p (Cubic c1 c2 x2) -> FCubic p (p .+^ c1) (p .+^ c2) (p .+^ x2) {-# INLINE mkFixedSeg #-} -- | Make a located segment from a fixed one. fromFixedSeg :: (Additive v, Num n) => FixedSegment v n -> Located (Segment v n) fromFixedSeg = \case FLinear p1 p2 -> straight (p2 .-. p1) `at` p1 FCubic x1 c1 c2 x2 -> bezier3 (c1 .-. x1) (c2 .-. x1) (x2 .-. x1) `at` x1 {-# INLINE fromFixedSeg #-} type instance Codomain (FixedSegment v n) = Point v instance (Additive v, Num n) => Parametric (FixedSegment v n) where atParam (FLinear p1 p2) t = lerp t p2 p1 atParam (FCubic x1 c1 c2 x2) t = p3 where p11 = lerp t c1 x1 p12 = lerp t c2 c1 p13 = lerp t x2 c2 p21 = lerp t p12 p11 p22 = lerp t p13 p12 p3 = lerp t p22 p21 {-# INLINE atParam #-} instance Num n => DomainBounds (FixedSegment v n) instance (Additive v, Num n) => EndValues (FixedSegment v n) where atStart (FLinear p0 _) = p0 atStart (FCubic p0 _ _ _) = p0 {-# INLINE atStart #-} atEnd (FLinear _ p1) = p1 atEnd (FCubic _ _ _ p1 ) = p1 {-# INLINE atEnd #-} instance (Additive v, Fractional n) => Sectionable (FixedSegment v n) where splitAtParam (FLinear p0 p1) t = (left, right) where left = FLinear p0 p right = FLinear p p1 p = lerp t p1 p0 splitAtParam (FCubic p0 c1 c2 p1) t = (left, right) where left = FCubic p0 a b cut right = FCubic cut c d p1 -- first round a = lerp t c1 p0 p = lerp t c2 c1 d = lerp t p1 c2 -- second round b = lerp t p a c = lerp t d p -- final round cut = lerp t c b {-# INLINE splitAtParam #-} reverseDomain (FLinear p0 p1) = FLinear p1 p0 reverseDomain (FCubic p0 p1 p2 p3) = FCubic p3 p2 p1 p0 {-# INLINE reverseDomain #-} -- closest :: FixedSegment v n -> Point v n -> [n] -- closest = undefined segmentParametersAtDirection :: OrderedField n => V2 n -> Segment V2 n -> [n] segmentParametersAtDirection (V2 tx ty) (Cubic (V2 x1 y1) (V2 x2 y2) (V2 x3 y3)) = filter (\x -> x >= 0 && x <= 1) $ quadForm a b c where a = tx*(y3 + 3*(y1 - y2)) - ty*(x3 + 3*(x1 - x2)) b = 2*(tx*(y2 - 2*y1) - ty*(x2 - 2*x1)) c = tx*y1 - ty*x1 segmentParametersAtDirection _ _ = [] {-# INLINE segmentParametersAtDirection#-} bezierParametersAtDirection :: OrderedField n => V2 n -> FixedSegment V2 n -> [n] bezierParametersAtDirection (V2 tx ty) (FCubic (P (V2 x0 y0)) (P (V2 x1 y1)) (P (V2 x2 y2)) (P (V2 x3 y3))) = filter (\x -> x >= 0 && x <= 1) $ quadForm a b c where a = tx*((y3 - y0) + 3*(y1 - y2)) - ty*((x3 - x0) + 3*(x1 - x2)) b = 2*(tx*((y2 + y0) - 2*y1) - ty*((x2 + x0) - 2*x1)) c = tx*(y1 - y0) - ty*(x1 - x0) bezierParametersAtDirection _ _ = [] {-# INLINE bezierParametersAtDirection#-}
cchalmers/geometry
src/Geometry/Segment.hs
bsd-3-clause
37,298
13
18
10,177
10,713
5,640
5,073
704
3
{-# LANGUAGE OverloadedStrings #-} module CacheDNS.APP.JobQueue ( JobQueue , newJobQueue , addJob , fetchJob ) where import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.STM import qualified Data.ByteString as BS import qualified CacheDNS.DNS as DNS import qualified CacheDNS.IPC.Mailbox as MB import CacheDNS.APP.Types data JobQueue = JobQueue { mailbox :: MB.Mailbox (DNSKey, MB.Mailbox DNSKey) } newJobQueue :: IO JobQueue newJobQueue = do mailbox <- MB.newMailboxIO return JobQueue{ mailbox = mailbox } addJob :: DNSKey -> MB.Mailbox DNSKey -> JobQueue -> IO () addJob key mb jobs = do atomically $ MB.writeMailbox (mailbox jobs) (key,mb) fetchJob :: JobQueue -> IO (DNSKey, MB.Mailbox DNSKey) fetchJob jobs = do mail <- atomically $ MB.readMailbox (mailbox jobs) return mail
DavidAlphaFox/CacheDNS
app/CacheDNS/APP/JobQueue.hs
bsd-3-clause
868
0
12
168
261
144
117
25
1
import Neil main :: IO () main = neil $ do retry 3 $ cmd "cabal install QuickCheck" cmd "hlint test --typecheck --quickcheck" (time,_) <- duration $ cmdCode "hlint src" putStrLn $ "Running HLint on self took " ++ show time ++ "s" cmd "ghc -threaded -rtsopts -isrc -i. src/Paths.hs src/Main.hs --make -O -prof -auto-all -caf-all" cmdCode "src/Main src +RTS -p" cmd "head -n32 Main.prof"
fpco/hlint
travis.hs
bsd-3-clause
416
0
10
95
98
43
55
10
1
{-# LANGUAGE TemplateHaskell #-} module Client.VidDefT where import Control.Lens (makeLenses) import Types makeLenses ''VidDefT newVidDefT :: VidDefT newVidDefT = VidDefT { _vdWidth = 0 , _vdHeight = 0 , _vdNewWidth = 0 , _vdNewHeight = 0 }
ksaveljev/hake-2
src/Client/VidDefT.hs
bsd-3-clause
293
0
6
89
64
39
25
11
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, RankNTypes #-} module XMLSerialization ( chapterToXml ) where -- import Prelude hiding (words) import qualified Data.Map as M import Text.XML.Light import System.Random import Control.Monad.Trans import Control.Monad.Trans.State import Control.Monad.Trans.Except import qualified Control.Monad.Except as C import qualified Control.Exception.Base as B import qualified Control.Monad.State as S import qualified Control.Monad.Reader as R import Lib import CSVParsers import qualified Data.Text as T import qualified Data.ByteString.Lazy as BL import Data.Either import Control.Monad.Trans.Reader import Control.Monad.Identity xmlDOM :: String -> String xmlDOM txt = showTopElement $ Element (unqual "root") [] [ Elem $ Element (unqual "element") [] [Text $ CData CDataText txt Nothing] Nothing ] Nothing textElement :: String -> String -> Element textElement name content = Element (unqual name) [] [ Text $ CData CDataText content Nothing ] Nothing emptyElement :: String -> [(String, String)] -> Element emptyElement name attrs = Element (unqual name) (map toAttr attrs) [] Nothing toAttr :: (String, String) -> Attr toAttr (name, value) = Attr {attrKey = QName { qName = name, qURI = Nothing, qPrefix = Nothing }, attrVal = value} addAttr :: (String, String) -> Element -> Element addAttr = add_attr . toAttr collElement :: String -> [Element] -> Element collElement name children = Element (unqual name) [] (map Elem children) Nothing flashcardToXml :: Flashcard -> Element flashcardToXml card = Element (unqual "QAFlashCard") [] (map Elem [ textElement "FCQuestion" (question card) , collElement "FCAnswer" [textElement "short" $ answer card] , collElement "quiz" [elemQuestion (answer card) (quiz card)] , emptyElement "image" [("position", "belowShortAnswer"),("source", "http://babelbay-assets.mobileacademy.com/images/" ++ index ++ ".jpg")] , emptyElement "audio" [("source", "http://babelbay-assets.mobileacademy.com/audios/" ++ audio card ++ ".wav")] ]) Nothing where index = show (flashCardIndex card) elemQuestion :: String -> [String] -> Element elemQuestion title options = addAttr ("layout", "text") $ collElement "question" $ textElement "title" title : elemOptions options elemOptions (correct:wrongs) = addAttr ("correct", "true") (textElement "option" correct) : map (addAttr ("correct", "false") . textElement "option") wrongs chapterToXml :: Chapter -> Element chapterToXml chapter = Element (unqual "chapter") [ Attr {attrKey = QName { qName = "key", qURI = Nothing, qPrefix = Nothing }, attrVal = show $ chapterIndex chapter} ] (map Elem (textElement "title" (chapterTitle chapter) : map flashcardToXml (chapterCards chapter))) Nothing courseIntroFlashcardToXml :: Element -> CourseIntroFlashcard a -> Element courseIntroFlashcardToXml long fc = collElement "QAFlashCard" [question, answer] where question = textElement "FCQuestion" (courseIntroFCQuestion fc) answer = collElement "FCAnswer" [short, long] short = addAttr ("type", "text") $ textElement "short" (courseIntroFCShortAnswer fc) courseIntroFlashcard1AnswerToXml :: CourseIntroFlashcard String -> Element courseIntroFlashcard1AnswerToXml fc = courseIntroFlashcardToXml (collElement "long" . return . textElement "text" . courseIntroFCLongAnswer $ fc) fc courseIntroFlashcard2AnswerToXml :: CourseIntroFlashcard [String] -> Element courseIntroFlashcard2AnswerToXml fc = courseIntroFlashcardToXml (collElement "long" . return . collElement "simpleList" . map (textElement "item") . courseIntroFCLongAnswer $ fc) fc courseToXml :: String -> Course -> Element courseToXml key course = let intro = courseIntro course in Element (unqual "BookSummary") [] (map Elem $ [ emptyElement "meta" [ ("id", show $ courseId intro) , ("key", key) , ("viewType", "BabelbayQA") ] , textElement "Title" (courseTitle intro) , collElement "introduction" [ textElement "title" (courseIntroTitle intro) , courseIntroFlashcard1AnswerToXml (courseIntroFC1 intro) , courseIntroFlashcard2AnswerToXml (courseIntroFC2 intro) ] ] ++ map chapterToXml (courseChapters course)) Nothing courseKey :: String -> Course -> String courseKey keyPostfix course = "Learn" ++ show (courseLanguage $ courseIntro course) ++ "Language" ++ keyPostfix --- data AppConfig = AppConfig CourseMeta deriving Show data AppState = AppState StdGen deriving Show type App m = ReaderT AppConfig (StateT AppState (ExceptT String m)) runApp :: App m a -> AppConfig -> AppState -> m (Either String (a, AppState)) -- runApp app config state = runExceptT $ (runStateT $ runReaderT app config) state runApp app config = runExceptT . runStateT (runReaderT app config) app :: App IO (IO ()) app = do (AppConfig meta) <- R.ask (AppState g) <- S.get file <- liftIO $ BL.readFile "./final3.csv" csvData <- liftIO $ BL.readFile $ "./content/" ++ target meta ++ "-Table 1.csv" let chapters = toCSVChapters file let intro = toCSVCourseIntro csvData let ecs = mapSnd AppState <$> liftM2 (\x y -> runCSVDataConversion (toCourse x y) g meta) intro chapters let cs = mapFst (["", "Two"] `zip`) <$> ecs let ios = mapFst (mapM_ (uncurry (writeCourse meta) . mapB courseKey)) <$> cs case ios of (Left err) -> do liftIO $ print "error" C.throwError "EXCEPTION" (Right tup) -> do S.put (snd tup) return (fst tup) -- runApp app (AppConfig $ makeCourseMeta "en" "es") (AppState $ mkStdGen 10) >>= handle -- handle (Left str) = print str -- handle (Right i) = fst i -- Control.Exception -- r <- try (readFile "./hello" >>= print )::IO (Either SomeException ()) --liftIO $ print cs --return ((), AppState g) -- write :: App IO ((), StdGen) -- write = do -- (AppConfig meta) <- R.ask -- (AppState g) <- S.get mapFst :: (a -> b) -> (a, c) -> (b, c) mapFst f (x,y) = (f x,y) mapSnd :: (a -> b) -> (c, a) -> (c, b) mapSnd f (x,y) = (x,f y) -- writeCourse :: CourseMeta -> String -> Course -> IO () writeCourse meta key course = do let fileName = key ++ "-" ++ native meta ++ ".xml" writeFile ("/Users/homam/dev/ma/maAssets/" ++ key ++ "/text/" ++ fileName) (ppcTopElement prettyConfigPP (courseToXml key course)) -- liftIO = lift . lift someFunc :: IO () someFunc = do matrix <- BL.readFile "./final.csv" forM_ ["en","ar","fr","de","ru","es"] $ \ targetLang -> do let meta = makeCourseMeta "en" targetLang csvData <- BL.readFile $ "./content/" ++ target meta ++ "-Table 1.csv" let chapters = toCSVChapters matrix let intro = toCSVCourseIntro csvData g <- newStdGen let cs = liftM2 (\x y -> runCSVDataConversion (toCourse x y) g meta) intro chapters write meta cs where write :: CourseMeta -> Either String ([Course], StdGen) -> IO () write _ (Left err) = putStrLn err write meta (Right (cs, _)) = mapM_ -- (putStrLn . ppcTopElement prettyConfigPP . uncurry courseToXml . mapB courseKey) (uncurry (writeCourse meta) . mapB courseKey) (["", "Two"] `zip` cs) writeCourse :: CourseMeta -> String -> Course -> IO () writeCourse meta key course = do let fileName = key ++ "-" ++ native meta ++ ".xml" writeFile ("/Users/homam/dev/ma/maAssets/" ++ key ++ "/text/" ++ fileName) (ppcTopElement prettyConfigPP (courseToXml key course)) -- mapB :: (a -> b -> c) -> (a, b) -> (c, b) mapB f t = (uncurry f t, snd t)
homam/babelbay-ma-parseit
src/XMLSerialization.hs
bsd-3-clause
7,589
0
19
1,476
2,410
1,268
1,142
155
2
module Settings.Builders.GenPrimopCode (genPrimopCodeBuilderArgs) where import Settings.Builders.Common genPrimopCodeBuilderArgs :: Args genPrimopCodeBuilderArgs = builder GenPrimopCode ? mconcat [ output "**/PrimopWrappers.hs" ? arg "--make-haskell-wrappers" , output "**/Prim.hs" ? arg "--make-haskell-source" , output "**/primop-data-decl.hs-incl" ? arg "--data-decl" , output "**/primop-tag.hs-incl" ? arg "--primop-tag" , output "**/primop-list.hs-incl" ? arg "--primop-list" , output "**/primop-has-side-effects.hs-incl" ? arg "--has-side-effects" , output "**/primop-out-of-line.hs-incl" ? arg "--out-of-line" , output "**/primop-commutable.hs-incl" ? arg "--commutable" , output "**/primop-code-size.hs-incl" ? arg "--code-size" , output "**/primop-can-fail.hs-incl" ? arg "--can-fail" , output "**/primop-strictness.hs-incl" ? arg "--strictness" , output "**/primop-fixity.hs-incl" ? arg "--fixity" , output "**/primop-primop-info.hs-incl" ? arg "--primop-primop-info" , output "**/primop-vector-uniques.hs-incl" ? arg "--primop-vector-uniques" , output "**/primop-vector-tys.hs-incl" ? arg "--primop-vector-tys" , output "**/primop-vector-tys-exports.hs-incl" ? arg "--primop-vector-tys-exports" , output "**/primop-vector-tycons.hs-incl" ? arg "--primop-vector-tycons" , output "**/primop-usage.hs-incl" ? arg "--usage" ]
sdiehl/ghc
hadrian/src/Settings/Builders/GenPrimopCode.hs
bsd-3-clause
1,580
0
9
371
272
130
142
22
1
module Model.Feed ( getAllFeeds , getFeed , updateFeed , module Model.Feed.Internal ) where import Import import Model.Feed.Internal import Data.ByteString (ByteString) import Database.Esqueleto -- | Get all feed (title, url, type) 3-tuples. getAllFeeds :: YesodDB App [(Text, Text, FeedType)] getAllFeeds = fmap (map fromValue) $ select $ from $ \f -> do orderBy [asc (f^.FeedUrl)] return (f^.FeedTitle, f^.FeedUrl, f^.FeedType) getFeed :: Text -> YesodDB App (Maybe (Entity Feed)) getFeed = getBy . UniqueFeed updateFeed :: FeedId -> Text -> ByteString -> ByteString -> ByteString -> YesodDB App () updateFeed feed_id title last_modified etag contents = update $ \f -> do set f [ FeedTitle =. val title , FeedLastModified =. val last_modified , FeedEtag =. val etag , FeedContents =. val contents ] where_ (f^.FeedId ==. val feed_id)
duplode/dohaskell
src/Model/Feed.hs
bsd-3-clause
949
0
13
240
308
163
145
25
1
module TestArbitrary (testArbitrary, size) where import Test.Tasty import Test.Tasty.QuickCheck import Data.Maybe import Data.Either import Properties import ArbitraryLambda import BruijnTerm import MakeType import TypeCheck import ShrinkLambda testArbitrary :: TestTree testArbitrary = testGroup "arbitrary" [testGeneration, testshrink] testshrink :: TestTree testshrink = testGroup "shrink" [ testProperty "all normalised untyped" $ forAllUnTypedBruijn $ \ e -> conjoin (map welFormd (shrinkUntypedBruijn e )) , testProperty "all normalised typed " $ forAllTypedBruijn $ \ e -> conjoin (map welFormd (shrinkTypedBruijn e )) , testProperty "all typeable" $ noShrinking $ forAllTypedBruijn $ \ e -> conjoin (map (\en ->counterexample (pShow en) $ isRight $ solver en ) $ shrinkTypedBruijn e ) ] testGeneration :: TestTree testGeneration = testGroup "genration" [ testProperty "corect size type" $ forAll (suchThat (arbitrary :: Gen Int) (> 1)) (\ n -> -- TODO dont use arbitrary (forAll (resize n $ genTyped defaultConf) (\ t -> size (t :: BruijnTerm () () ) == n))) , testProperty "corect size untype" $ forAll (suchThat (arbitrary :: Gen Int) (> 1)) (\ n -> (forAll (resize n genUnTyped ) (\ t -> size (t :: BruijnTerm () ()) == n))) , testProperty "typeable" $ forAllTypedBruijn $ \ e -> isRight $ solver e , testProperty "corect type" $ forAll ( genTerm defaultConf (Just tDouble )) (\ e -> isJust e ==> case solver (fromJust (e :: Maybe (BruijnTerm () ()))) of (Right t) -> unifys t tDouble _ -> False ) , testProperty "noncircular" $ forAllNonCiculair $ not . isCirculair ]
kwibus/myLang
tests/TestArbitrary.hs
bsd-3-clause
1,786
0
20
452
572
301
271
38
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} -- TODO - remove those, once disp for pattern2 is removed {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- ghc options {-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- {-# OPTIONS_GHC -fno-warn-missing-signatures #-} -- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-} -- for the doctests: -- {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# LANGUAGE CPP #-} -- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-} -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <[email protected]> -- Stability : experimental -- Portability: non-portable -- -- This module provides pretty printing functionality for Pire's -- abstract and concrete syntax: expressions, -- and other data structures, defined mutually recursive in terms of exprs module Pire.Pretty.Expr where import Pire.Syntax.Eps import Pire.Syntax.GetNm import Pire.Syntax.Ws import Pire.Syntax.Expr import Pire.Syntax.ExprNm import Pire.Syntax.Pattern import Pire.Pretty.Common import Pire.Pretty.Wrap import Pire.Pretty.Nm () import Pire.Pretty.Ws () import Pire.Pretty.Pattern () import Pire.Pretty.Token () import Pire.Pretty.Binder import Control.Lens import Bound import Bound.Name import Control.Monad.Identity import Control.Monad.Reader import Text.PrettyPrint as TPP #ifdef MIN_VERSION_GLASGOW_HASKELL #if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0) -- ghc >= 7.10.3 #else -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined #endif #else -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) import Control.Applicative #endif import Control.Monad import qualified Data.Text as T import Pire.Utils import Data.Either.Combinators (fromRight') -- for the doctests import Pire.NoPos import Pire.Text2String import Pire.String2Text import Pire.Parser.ParseUtils import Pire.Parser.SimpleExpr import Pire.Parser.Expr hiding (arg) import Pire.Parser.Decl #ifdef PiForallInstalled import qualified PiForall.Parser as P import qualified PiForall.PrettyPrint as PPP import Pire.Untie #endif -- calm down the unused-import warnings -- don't want to turn on -- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- as I do want to see the other unused imports -- and can't get -fno-warn-unused-imports to work w/ doctest (?) -- any better solution? dummy :: TPP.Doc dummy = pp $ nopos $ t2s $ parse simple_expr "foo" dummy2 :: TPP.Doc dummy2 = PPP.disp $ untie $ nopos $ parse expr "foo" dummy3 :: TPP.Doc dummy3 = PPP.disp $ untie $ nopos $ parse decl_ "foo : bar" dummy4 :: TPP.Doc dummy4 = PPP.disp $ fromRight' $ P.parseExpr "foo" #ifdef PiForallInstalled {-| with or without @nopos@, @t2s@, parsed as @simple_expr@, @expr@, or @expr_@, and always cf. with Pi-forall's original pretty printing >>> pp $ parse simple_expr "(x:A) -> B" A -> B >>> pp $ nopos $ parse simple_expr "(x:A) -> B" A -> B >>> pp $ nopos $ t2s $ parse simple_expr "(x:A) -> B" A -> B >>> pp $ nopos $ parse expr "(x:A) -> B" A -> B >>> PPP.disp $ untie $ nopos $ parse expr "(x:A) -> B" A -> B >>> PPP.disp $ fromRight' $ P.parseExpr "(x: A) -> B" A -> B if parsed in white space aware manner, we want the exact input back: >>> pp $ nopos $ parse expr_ "(x:A) -> B" (x:A) -> B now with x on the rhs of the Pi >>> pp $ nopos $ parse simple_expr "(x:A) -> B x" (x : A) -> B x >>> pp $ nopos $ parse expr "(x:A) -> B x" (x : A) -> B x >>> PPP.disp $ untie $ nopos $ parse expr "(x:A) -> B x" (x : A) -> B x >>> PPP.disp $ fromRight' $ P.parseExpr "(x: A) -> B x" (x : A) -> B x in white space aware manner: >>> pp $ nopos $ parse expr_ "(x:A) -> B x" (x:A) -> B x likewise erased Pi's - want to see brackets now! >>> pp $ nopos $ parse expr "[x:A] -> B" [A] -> B >>> pp $ nopos $ parse expr "[x:A] -> B x" [x : A] -> B x >>> >>> PPP.disp $ untie $ nopos $ parse expr "[x:A] -> B" [A] -> B >>> PPP.disp $ untie $ nopos $ parse expr "[x:A] -> B x" [x : A] -> B x and in white space aware manner >>> pp $ nopos $ parse expr_ "[x:A] -> B" [x:A] -> B >>> pp $ nopos $ parse expr_ "[x:A] -> B x" [x:A] -> B x >>> pp $ nopos $ parse expr_ "[A :Type] -> B" [A :Type] -> B more complicated examples: >>> pp $ nopos $ parse expr_ "[A :Type] -> [n:Nat] -> Vec A (Succ n) -> Vec A n" [A :Type] -> [n:Nat] -> Vec A (Succ n) -> Vec A n pretty printing of let, sigma let >>> pp $ nopos $ t2s $ parse expr "let a = 2 in (plus a 4)" let a = 2 in (plus a 4) >>> pp $ nopos $ parse expr "let a = 2 in (plus a 4)" let a = 2 in (plus a 4) >>> pp $ nopos $ t2s $ parse expr_ "let a = 2 in (plus a 4)" let a = 2 in (plus a 4) >>> pp $ nopos $ parse expr_ "let a = 2 in (plus a 4)" let a = 2 in (plus a 4) sigma >>> pp $ nopos $ parse expr "{ x : A | A }" { x : A | A } >>> pp $ nopos $ t2s $ parse expr "{ x : A | A }" { x : A | A } >>> pp $ nopos $ parse expr_ "{ x : A | A }" { x : A | A } >>> pp $ t2s $ nopos $ parse expr_ "{ x : A | A }" { x : A | A } brackets in data types are are handled fine now: cf Pire.Pretty.Decl -} #endif dispExpr :: Expr T.Text T.Text -> M Doc dispExpr (Nat' n) = disp n dispExpr (V v) = disp v dispExpr (BndV _ v) = disp v dispExpr (Ws_ v ws) = (<>) <$> (disp v) <*> disp ws dispExpr (Brackets_ bo v bc) = (<>) <$> (disp bo) <*> ((<>) <$> (disp v) <*> disp bc) dispExpr (f :@ x) | wsAware f = do df <- dispExpr f dx <- dispExpr x return $ df <> dx | otherwise = do df <- dispExpr f dx <- dispExpr x return $ wrapf f df <+> wraparg x dx dispExpr (ErasedApp f x) | wsAware f = do df <- dispExpr f dx <- dispExpr x return $ df <> dx | otherwise = do df <- dispExpr f dx <- dispExpr x return $ wrapf f df <+> brackets dx dispExpr (Lam n s) = (do ; b <- dispExpr $ instantiate1 (V $ n) s ; dn <- disp n ; return $ hang (text "\\" <> dn <+> text ".") 2 b ) dispExpr (Lam_ {}) = return $ text "error: dispExpr(Lam_ ...)" dispExpr (ErasedLam {}) = return $ text "error: dispExpr(ErasedLam ...)" dispExpr (ErasedLam_ {}) = return $ text "error: dispExpr(ErasedLam_ ...)" dispExpr (Lams ns s) = (do ; b <- dispExpr $ instantiate (\idx -> V $ ns !! idx) s ; dvs <- forM ns (disp) ; return $ hang (text "\\" <> sep dvs <+> text ".") 2 b ) dispExpr (Lam' n s) = (do ; b <- dispExpr $ instantiate1 (V $ n) s ; dn <- disp n ; return $ hang (text "\\" <> dn <+> text ".") 2 b ) dispExpr (Lams' ns s) = (do ; b <- dispExpr $ instantiate (\(Name n idx) -> V $ ns !! idx) s ; dns <- forM ns (disp) ; return $ hang (text "\\" <> sep dns <+> text ".") 2 b ) dispExpr (LamPA RuntimeP v annot s) = do dv <- disp v pa <- dispAnnot annot body <- dispExpr $ instantiate1 (V $ v) s return $ hang (text "\\" <> dv <> pa <+> text ".") 2 body dispExpr (LamPA ErasedP v annot s) = do dv <- disp v pa <- dispAnnot annot body <- dispExpr $ instantiate1 (V $ v) s return $ hang (text "\\" <> brackets (dv <> pa) <+> text ".") 2 body dispExpr (LamPAs pas s) = do b <- dispExpr $ instantiate (\idx -> V $ pas !! idx ^. _2) s danns <- Control.Monad.forM pas (\case {(ErasedP, n, a) -> brackets `liftM` ((<>) <$> (disp n) <*> dispAnnot a); (_, n, a) -> (<>) <$> (disp n) <*> dispAnnot a}) return $ hang (text "\\" <> sep danns <+> text ".") 2 b dispExpr (LamPAs' pas s) = do b <- dispExpr $ instantiate (\idx -> V $ name' $ pas !! idx ^. _2) s danns <- Control.Monad.forM pas (\case {(ErasedP, n, a) -> brackets `liftM` ((<>) <$> (disp n) <*> dispAnnot a); (_, n, a) -> (<>) <$> (parens <$> disp n) <*> dispAnnot a}) return $ hang (text "\\" <> sep danns <+> text ".") 2 b dispExpr (LamPAs_ lamtok pas dot s) = do b <- dispExpr $ instantiate (\idx -> Ws_ (V $ pas !! idx ^. _2 & name') $ Ws "") s dlamtok <- disp lamtok danns <- Control.Monad.forM pas (\(_, v, a) -> do { dn <- dispBinder v; return dn `liftM` dispAnnot a }) ddot <- disp dot return $ dlamtok <> hcat danns <> ddot <> b -- -- | Let t (Expr t a) (Scope (Name t ()) (Expr t) a) -- -- | Let_ (LetTok t) (Binder t) (Equal t) (Expr t a) (In t) (Scope (Name t ()) (Expr t) a) -- dispExpr (Let i binds s) = return $ text "error: dispExpr(Let...)" dispExpr (Let nm ex sc) = (do ; dnm <- disp nm ; dex <- dispExpr ex ; let body = instantiate1 (V $ nm) sc ; db <- dispExpr body ; return $ sep [text "let" <+> dnm <+> text "=" <+> dex <+> text "in", db] ) dispExpr (Let_ lettok bndr eq ex intok sc) = (do ; dlet <- disp lettok ; dbndr <- disp bndr ; deq <- disp eq ; dex <- dispExpr ex ; din <- disp intok ; let body = instantiate1 (V $ bndr & name') sc ; dbdy <- dispExpr body ; return $ dlet <> dbndr <> deq <> dex <> din <> dbdy ) dispExpr (TyEq a b) = (<+>) <$> (disp a) <*> ((text "=" <+>) <$> disp b) dispExpr (TyEq_ a eq b) = (<>) <$> disp a <*> ((<>) <$> disp eq <*> disp b) dispExpr Type = return $ text "Type" dispExpr (Type_ ty ws) = (<>) <$> disp ty <*> disp ws dispExpr TyUnit = return $ text "One" dispExpr (TyUnit_ tyu ws) = (<>) <$> disp tyu <*> disp ws dispExpr LitUnit = return $ text "tt" dispExpr (LitUnit_ tt ws) = (<>) <$> disp tt <*> disp ws dispExpr (Position _ e) = dispExpr e dispExpr TyBool = return $ text "Bool" dispExpr (TyBool_ tb ws) = (<>) <$> disp tb <*> disp ws dispExpr (LitBool b) = return $ if b then text "True" else text "False" dispExpr (LitBool_ b _ ws) = if b then (<>) <$> pure "True" <*> disp ws else (<>) <$> pure "False" <*> disp ws dispExpr (If a b c ann) = do da <- disp a db <- disp b dc <- disp c dann <- disp ann return $ text "if" <+> da <+> text "then" <+> db <+> text "else" <+> dc <+> dann dispExpr (If_ if' a then' b else' c ann) = do di <- disp if' da <- disp a dt <- disp then' db <- disp b de <- disp else' dc <- disp c dann <- disp ann return $ di <> da <> dt <> db <> de <> dc <> dann dispExpr (Subst a b annot) = do da <- disp a db <- disp b dat <- disp annot return $ fsep [text "subst" <+> da, text "by" <+> db, dat] dispExpr (Subst_ subst a by b annot) = do ds <- disp subst da <- disp a dby <- disp by db <- disp b dat <- disp annot return $ hcat [ds <> da, dby <> db, dat] dispExpr (Contra ty annot) = do dty <- disp ty dat <- disp annot return $ text "contra" <+> dty <+> dat dispExpr (Contra_ c a annot) = do dc <- disp c da <- disp a dat <- disp annot return $ hcat [dc <> da, dat] dispExpr (Paren e) = do de <- disp e return $ (parens de) dispExpr (Paren_ po e pc) = do dpo <- disp po de <- disp e dpc <- disp pc return $ dpo <> de <> dpc dispExpr (Sigma x tyA s) = do dx <- disp x dA <- disp tyA dB <- dispExpr $ instantiate1 (V $ x) s return $ text "{" <+> dx <+> text ":" <+> dA <+> text "|" <+> dB <+> text "}" dispExpr (Sigma_ bo x col tyA vbar sc bc) = do dbo <- disp bo dx <- disp x dcol <- disp col dA <- disp tyA dvbar <- disp vbar dbdy <- dispExpr $ instantiate1 (V $ x & name') sc dbc <- disp bc return $ dbo <> dx <> dcol <> dA <> dvbar <> dbdy <> dbc -- dispExpr (Prod _ _ _) = return $ text "error: dispExpr(Prod...)" dispExpr (Prod a b ann) = do { ; da <- disp a ; db <- disp b ; dann <- disp ann ; return $ parens (da <+> text "," <+> db) <+> dann -- ; return $ da <> db <> dann } -- dispExpr (Prod_ _ _ _ _ _ _) = return $ text "error: dispExpr(Prod_ ...)" dispExpr (Prod_ po a comma' b pc ann) = do { ; dpo <- disp po ; da <- disp a ; dcomma <- disp comma' ; db <- disp b ; dpc <- disp pc ; dann <- disp ann ; return $ dpo <> da <> dcomma <> db <> dpc <> dann } dispExpr (Pcase _ _ _ _) = return $ text "error: dispExpr(Pcase...)" -- dispExpr (Pcase_ _ _ _ _) = return $ text "error: dispExpr(Pcase_ ...)" dispExpr (Pcase_ pcase ex of' po s comma' t pc arr sc ann) = do dp <- disp pcase dex <- disp ex dof <- disp of' dpo <- disp po ds <- disp s dcomma <- disp comma' dt <- disp t dpc <- disp pc darr <- disp arr -- dsc <- dispExpr $ instantiate1 (V $ s & name') sc dsc <- dispExpr $ instantiate (\i -> if i == 0 then (V $ s & name') else V $ t & name') sc dann <- disp ann return $ dp <> dex <> dof <> dpo <> ds <> dcomma <> dt <> dpc <> darr <> dsc <> dann -- {- -- gatherBinders (ErasedLam b) = -- lunbind b $ \((n,unembed->ma), body) -> do -- dn <- display n -- dt <- display ma -- (rest, body) <- gatherBinders body -- return $ ( brackets (dn <+> dt) : rest, body) -- -} dispExpr (PiP RuntimeP n a s) = (do ; da <- dispExpr a ; dn <- disp n ; let rhs = instantiate1 (V n) s ; drhs <- dispExpr $ rhs ; let lhs = if (n `elem` fv' rhs) then parens (dn <+> colon <+> da) else wraparg (a) da ; return $ lhs <+> text "->" <+> drhs ) dispExpr (PiP ErasedP n a s) = (do ; da <- dispExpr a ; dn <- disp n ; let rhs = instantiate1 (V n) s ; drhs <- dispExpr $ rhs ; let lhs = mandatoryBindParens ErasedP $ if (n `elem` fv' rhs) then (dn <+> colon <+> da) else da ; return $ lhs <+> text "->" <+> drhs ) dispExpr (PiP_ RuntimeP (Ann_ paren@(Paren_ {})) arr s) = do { ; dn <- disp paren ; darr <- disp arr ; db <- dispExpr $ instantiate1 (Ws_ (V $ paren ^. getnm) $ Ws "") s ; return $ dn <> darr <> db } dispExpr (PiP_ ErasedP (Ann_ bracks@(Brackets_ {})) arr s) = do { ; dn <- disp bracks ; darr <- disp arr ; db <- dispExpr $ instantiate1 (Ws_ (V $ bracks ^. getnm) $ Ws "") s ; return $ dn <> darr <> db } -- ann should really only be InferredAnnBnd_ -- this should display fine: -- pp $ nopos $ parse expr_ "[A:Type] -> A -> Vec A 1" -- issues still in Vec.pi: data In .. Here of | There of -- dispExpr (PiP_ eps (Ann_ ann) arr s) = do { ; dn <- disp ann ; darr <- disp arr ; db <- dispExpr $ instantiate1 (Ws_ (V $ ann ^. getnm) $ Ws "") s ; return $ dn <> darr <> db } -- should never occur dispExpr (PiP_ eps ann arr sc) = return $ text "error: dispExpr(PiP_ ...)" -- how about we do the same as in the RuntimeP case ? -- the low level -- dispExpr (PiP_ ErasedP n arr s) = do -- dn <- disp n -- darr <- disp arr -- db <- dispExpr $ instantiate1 n s -- return $ dn <> darr <> db -- dispExpr (PiP_ RuntimeP n@(InferredAnn_ (V_ n' _) ty) arr s) = do -- dty <- disp ty -- darr <- disp arr -- db <- dispExpr $ instantiate1 (V_ n' $ Ws "") s -- return $ dty <> darr <> db -- dispExpr (PiP_ RuntimeP n arr s) = do -- dn <- disp n -- darr <- disp arr -- db <- dispExpr $ instantiate1 n s -- return $ dn <> darr <> db -- dispExpr (PiP_ ErasedP n@(WitnessedAnnInBrackets_ _ (V_ n' _) _ ty _) arr s) = do -- dn <- disp n -- darr <- disp arr -- dty <- disp ty -- db <- dispExpr $ instantiate1 (V_ n' $ Ws "") s -- return $ dn <> darr <> db dispExpr (Pi nm ty sc) = (do { ; let body = instantiate1 (V $ nm) sc ; dty <- dispExpr ty ; dn <- disp nm ; db <- dispExpr body -- have to use the instantiated body, and thus fv' instead of fv ; let lhs = if (nm `elem` fv' body) then parens (dn <+> colon <+> dty) else wraparg (ty) dty ; return $ lhs <+> text "->" <+> db }) dispExpr (Pi_ ann arr sc) = (do { ; let nm = ann ^. getnm ; let body = instantiate1 (V $ nm) sc ; dann <- disp ann ; darr <- disp arr ; db <- dispExpr body ; return $ dann <> darr <> db }) dispExpr (TCon n args) = do dn <- disp n dargs <- mapM dispExpr args let wargs = zipWith wraparg args dargs return $ dn <+> hsep wargs dispExpr (TCon_ nm args) = do dn <- disp nm dargs <- mapM dispExpr args -- don't need wraparg_, I guess -- let wargs = zipWith wraparg_ args dargs let wargs = zipWith (\_ -> id) args dargs return $ dn <> hcat wargs dispExpr (DCon n args annot) = do dn <- disp n dargs <- mapM dispArg args dannot <- dispAnnot annot return $ dn <+> hsep dargs <+> dannot dispExpr (DCon_ n args annot) = do dn <- disp n dargs <- mapM dispArg_ args dannot <- dispAnnot annot return $ dn <> hcat dargs <> dannot dispExpr (Case scrut alts annot) = do dscrut <- disp scrut dalts <- mapM disp alts dannot <- disp annot return $ text "case" <+> dscrut <+> text "of" $$ (nest 2 $ vcat $ dalts) <+> dannot dispExpr (Case_ ctok scrut oftok bo alts bc annot) = do { ; case' <- disp ctok ; dscrut <- disp scrut ; of' <- disp oftok ; dalts <- mapM (\(c, semicol) -> (<>) <$> (disp c) <*> (disp semicol)) alts ; dbo <- disp bo ; dbc <- disp bc ; dannot <- disp annot ; return $ case' <> dscrut <> of' <> dbo <> hcat dalts <> dbc <> dannot } -- dispExpr (CaseIndented_ ctok scrut oftok alts annot) = do { -- ; case' <- disp ctok -- ; dscrut <- disp scrut -- ; of' <- disp oftok -- ; dalts <- mapM (\c -> disp c) alts -- ; dannot <- disp annot -- ; return $ case' <> dscrut <> of' <> hcat dalts <> dannot -- } -- dispExpr (CaseWithBraces_ ctok scrut oftok bo alts bc annot) = do { -- ; case' <- disp ctok -- ; dscrut <- disp scrut -- ; of' <- disp oftok -- ; dalts <- mapM (\(c, semicol) -> (<>) <$> (disp c) <*> (disp semicol)) alts -- ; dbo <- disp bo -- ; dbc <- disp bc -- ; dannot <- disp annot -- ; return $ case' <> dscrut <> of' <> dbo <> hcat dalts <> dbc <> dannot -- } dispExpr (TrustMe annot) = (text "TRUSTME" <>) <$> disp annot dispExpr (TrustMe_ tme ws annot) = (<>) <$> disp tme <*> ((<>) <$> disp ws <*> disp annot) dispExpr (Nat n) = return $ (text . show) n dispExpr (Nat_ nmbr txt ws) = (<>) <$> (pure $ (text . show) nmbr) <*> disp ws dispExpr (Lams_ _ _ _ _) = return $ text "error: dispExpr(Lams_ ...)" -- dispExpr (ErasedLam_ _ _ _ _) = return $ text "error: dispExpr(ErasedLam_ ...)" dispExpr (Refl mty) = do da <- dispAnnot mty return $ text "refl" <+> da dispExpr (Refl_ rfl ws ann) = (<>) <$> disp rfl <*> ((<>) <$> disp ws <*> disp ann) dispExpr (Ann a b) = do da <- dispExpr a db <- dispExpr b return $ parens (da <+> text ":" <+> db) dispExpr (WitnessedAnnEx_ v col ex) = do dv <- disp v dcol <- disp col dex <- disp ex return $ dv <> dcol <> dex dispExpr (InferredAnnBnd_ v ex) = do disp ex dispExpr (WitnessedAnnBnd_ v col ex) = do dv <- disp v dcol <- disp col dex <- disp ex return $ dv <> dcol <> dex dispExpr (Ann_ ex) = disp ex instance Disp (Expr T.Text T.Text) where disp = dispExpr -- instance Disp (Ex) where -- disp = dispExpr instance Disp (Expr String String) where disp e = dispExpr $ s2t e instance Disp (Expr (T.Text, a) (T.Text, a)) where disp = dispExpr . (bimap fst fst) instance Disp (Expr (String, a) (String, a)) where disp = dispExpr . s2t . (bimap fst fst) dispAnnot :: Annot T.Text T.Text -> M Doc dispAnnot (Annot Nothing) = return $ TPP.empty -- dispAnnot_ (Annot_ Nothing ws) = return $ empty dispAnnot (Annot_ Nothing ws) = disp ws dispAnnot (Annot (Just x)) = do st <- ask if (showAnnots st) then (text ":" <+>) <$> (dispExpr x) else return $ TPP.empty dispAnnot (Annot_ (Just x) ws) = do st <- ask if (showAnnots st) then (text ":" <>) <$> (dispExpr x) else disp ws instance Disp (Annot T.Text T.Text) where disp = dispAnnot -- instance Disp (Annot String String) where -- disp = dispAnnot . s2t dispArg :: Arg T.Text T.Text -> M Doc dispArg arg@(Arg ep t) = do st <- ask let annotParens = if showAnnots st then mandatoryBindParens else bindParens let wraparg' (Arg p x) = case x of V _ -> bindParens p TCon _ [] -> bindParens p Type -> bindParens p TyUnit -> bindParens p LitUnit -> bindParens p TyBool -> bindParens p LitBool b -> bindParens p Sigma _ _ _ -> bindParens p Position _ a -> wraparg' (Arg p a) DCon _ [] _ -> annotParens p Prod _ _ _ -> annotParens p TrustMe _ -> annotParens p Refl _ -> annotParens p _ -> mandatoryBindParens p wraparg' arg <$> dispExpr t dispArg_ :: Arg T.Text T.Text -> M Doc -- we have the brackets in the syntax tree -- no need to give them any special treatment dispArg_ (Arg ep t) = disp t -- -- watch out: here orig lunbind dispMatch :: Match T.Text T.Text -> M Doc -- dispMatch (Match pat sc) = do -- dpat <- disp pat -- ds <- disp $ instantiate (\i -> V $ (argPatterns pat) !! i ^. _1 & name') sc -- return $ hang (dpat <+> text "->") 2 ds dispMatch (Match pat sc) = do dpat <- disp pat ds <- disp $ instantiate (\i -> V $ (argPatterns pat) !! i ^. _2 & name') sc return $ hang (dpat <+> text "->") 2 ds -- dispMatch (Match_ pat arr sc) = do -- dpat <- disp pat -- darr <- disp arr -- ds <- disp $ instantiate (\i -> V $ argPatterns pat !! i ^. _1 & name') sc -- return $ dpat <> darr <> ds dispMatch (Match_ pat arr sc) = do dpat <- disp pat darr <- disp arr ds <- disp $ instantiate (\i -> V $ argPatterns pat !! i ^. _2 & name') sc return $ dpat <> darr <> ds instance Disp (Match T.Text T.Text) where disp = dispMatch instance Disp (Match String String) where disp = dispMatch . s2t instance Disp (Match (T.Text, a) (T.Text, a)) where disp = dispMatch . (bimap fst fst) instance Disp (Match (String, a) (String, a)) where disp = dispMatch . s2t . (bimap fst fst)
reuleaux/pire
src/Pire/Pretty/Expr.hs
bsd-3-clause
23,203
45
18
7,127
7,128
3,531
3,597
430
15
module Predef where import Expr import Parser import Syntax -- import TypeCheck initenv :: BEnv initenv = [ ("nat", nat) , ("fix", fix) , ("zero", zero) , ("suc", suc) , ("one", one) , ("two", two) , ("plus", plus) , ("three", three) , ("bool", bool) , ("true", true) , ("false", false) ] -- initalBEnv :: BEnv -- initalBEnv = foldl (\env (n, e) -> (n, repFreeVar e) : env) [] initenv -- initalEnv :: Env -- initalEnv = [("vec", vec), ("cons", cons), ("nil", nil)] parse :: String -> Expr parse str = let Right (Progm [expr]) = parseExpr str in expr -- cons :: Expr -- cons = repFreeVar initalBEnv (parse "pi a : * . pi b : a . pi n : nat . vec a n -> vec a (suc n)") -- nil :: Expr -- nil = repFreeVar initalBEnv (parse "pi a : * . vec a zero") -- vec :: Expr -- vec = repFreeVar initalBEnv (parse "* -> nat -> *") bool :: Expr bool = parse "mu x : * . pi a : * . a -> a -> a" true :: Expr true = parse "fold[bool] (lam a : * . lam t : a . lam f : a . t)" false :: Expr false = parse "fold[bool] (lam a : * . lam t : a . lam f : a . f)" fix :: Expr fix = parse "lam a : * . lam f : a -> a . (lam x : (mu m : * . m -> a) . f ((unfold x) x)) (fold [mu m : * . m -> a] (lam x : (mu m : * . m -> a) . f ((unfold x) x)))" nat :: Expr nat = parse "mu x : * . pi a : * . a -> (x -> a) -> a" zero :: Expr zero = parse "fold[nat] (lam a : * . lam z : a . lam f : (nat -> a) . z)" suc :: Expr suc = parse "lam n : nat . fold[nat] (lam a : * . lam z : a . lam f : (nat -> a) . f n)" one :: Expr one = App suc zero two :: Expr two = App suc one three :: Expr three = App suc two plus :: Expr plus = parse "fix (nat -> nat -> nat) (lam p : (nat -> nat -> nat) . lam n : nat . lam m : nat . (unfold n) nat m (lam l : nat . suc (p l m)))"
bixuanzju/full-version
src/Predef.hs
gpl-3.0
1,865
0
12
579
326
193
133
44
1
{-# LANGUAGE DataKinds, PolyKinds, TemplateHaskell, QuasiQuotes, TypeOperators #-} module HLearn.Models.Regression.Parsing where import Data.List import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Expr import Text.ParserCombinators.Parsec.Language import Text.ParserCombinators.Parsec.Token import qualified Language.Haskell.TH as TH -- import Language.Haskell.TH hiding (Kind) import Language.Haskell.TH.Quote import HLearn.Algebra ------------------------------------------------------------------------------- -- template haskell expr :: QuasiQuoter expr = QuasiQuoter -- { quoteType = \str -> [t| '[] |] { quoteType = exprType } exprType str = return $ go (parseExprSimple str) where go [] = TH.PromotedNilT go (x:xs) = TH.AppT (TH.AppT TH.PromotedConsT $ termType x) $ go xs termType :: Term -> TH.Type termType CVar = TH.PromotedT $ TH.mkName "VarT" termType (CCon x) = TH.AppT (TH.PromotedT $ TH.mkName "ConT") (TH.AppT (TH.AppT (TH.PromotedT $ TH.mkName "Frac") (TH.LitT $ TH.NumTyLit $ floor x)) (TH.LitT $ TH.NumTyLit 1)) termType (CMon op t) = TH.AppT (TH.AppT (TH.PromotedT $ TH.mkName "MonT") (TH.PromotedT $ TH.mkName $ show op)) (termType t) termType (CBin op t1 t2) = TH.AppT (TH.AppT (TH.AppT (TH.PromotedT $ TH.mkName "BinT") (TH.PromotedT $ TH.mkName $ show op)) (termType t1)) (termType t2) data DivFrac = DivFrac Nat Nat ------------------------------------------------------------------------------- -- syntax types type Expr = [Term] data TermT = VarT | ConT Frac | MonT MonOp TermT | BinT BinOp TermT TermT data Term = CVar | CCon Rational | CMon MonOp Term | CBin BinOp Term Term deriving (Read,Show,Eq,Ord) -- instance Show Term where -- show CVar = "CVar" -- show (CCon _) = "CCon" -- show (CMon op t) = "CMon "++show op++" ("++show t++show ")" -- show (CBin op t1 t2) = "CBin "++show op++" ("++show t1++show ") ("++show t2++show ")" data MonOp = CLog | CNeg | CSin deriving (Read,Show,Eq,Ord) data BinOp = Mult | Div | Pow | Add deriving (Read,Show,Eq,Ord) --------------------------------------- isCommutative :: BinOp -> Bool isCommutative Mult = True isCommutative Div = False isCommutative Pow = False isCommutative Add = True canonicalize :: Term -> Term canonicalize (CBin op t1 t2) = if isCommutative op then CBin op (min t1' t2') (max t1' t2') else CBin op t1' t2' where t1' = canonicalize t1 t2' = canonicalize t2 canonicalize (CMon op t) = CMon op $ canonicalize t canonicalize t = t term2expr :: Term -> Expr term2expr t = sort $ go t where go :: Term -> [Term] go (CBin Add t1 t2) = go t1++go t2 go t = [t] --------------------------------------- parseExprSimple :: String -> Expr parseExprSimple str = case parseExpr str of Right expr -> expr Left err -> error $ "parseExprSimple: "++show err parseExpr :: String -> Either ParseError Expr parseExpr str = fmap (term2expr . canonicalize) $ parse exprParser "(unknown)" str lexer = makeTokenParser $ emptyDef { reservedOpNames = ["*","/","+","-"] ++["log"] } matchParens = parens lexer matchWhiteSpace = whiteSpace lexer matchReserved = reserved lexer matchReservedOp = reservedOp lexer matchIdentifier = identifier lexer matchNumber = naturalOrFloat lexer exprParser :: Parser Term exprParser = buildExpressionParser opList matchTerm opList = [ [Prefix (matchReservedOp "-" >> return (CMon CNeg )) ] , [Prefix (matchReservedOp "log" >> return (CMon CLog)) ] , [Infix (matchReservedOp "^" >> return (CBin Pow)) AssocLeft] , [Infix (matchReservedOp "*" >> return (CBin Mult)) AssocLeft] , [Infix (matchReservedOp "/" >> return (CBin Div )) AssocLeft] , [Infix (matchReservedOp "-" >> return (\a b -> CBin Add a (CMon CNeg b) )) AssocLeft] , [Infix (matchReservedOp "+" >> return (CBin Add )) AssocLeft] ] matchTerm :: Parser Term matchTerm = matchWhiteSpace >> (matchParens exprParser <|> var <|> matchConst ) var = char 'x' >> matchWhiteSpace >> return CVar matchConst = do x <- matchNumber case x of Left y -> return $ CCon $ toRational y Right y -> return $ CCon $ toRational y --------------------------------------- data instance Sing (f::TermT) = STerm Term -- data instance Sing (f::Term) = STerm Term data instance Sing (f::MonOp) = SMonOp MonOp data instance Sing (f::BinOp) = SBinOp BinOp -- instance SingI CVar where instance SingI VarT where sing = STerm CVar instance SingI c => SingI (ConT c) where sing = STerm $ CCon (fromSing (sing::Sing c)) -- instance (SingI m, SingI t) => SingI (CMon m t) where instance (SingI m, SingI t) => SingI (MonT m t) where sing = STerm (CMon (fromSing (sing::Sing m)) (fromSing (sing::Sing t))) -- instance (SingI m, SingI t1, SingI t2) => SingI (CBin m t1 t2) where instance (SingI m, SingI t1, SingI t2) => SingI (BinT m t1 t2) where sing = STerm (CBin (fromSing (sing::Sing m)) (fromSing (sing::Sing t1)) (fromSing (sing::Sing t2))) instance SingI CLog where sing = SMonOp CLog instance SingI CSin where sing = SMonOp CSin instance SingI CNeg where sing = SMonOp CNeg instance SingI Mult where sing = SBinOp Mult instance SingI Pow where sing = SBinOp Pow instance SingI Div where sing = SBinOp Div -- instance SingE (Kind :: Term) Term where fromSing (STerm f) = f instance SingE (Kind :: TermT) Term where fromSing (STerm f) = f instance SingE (Kind :: MonOp) MonOp where fromSing (SMonOp f) = f instance SingE (Kind :: BinOp) BinOp where fromSing (SBinOp f) = f ------------------- data instance Sing (xs :: [TermT]) = STermL { unSTermL :: [ Term ] } instance SingI ('[] :: [TermT]) where sing = STermL [] instance ( SingI t , SingI ts ) => SingI (t ': (ts :: [TermT])) where sing = STermL $ (fromSing (sing :: Sing t)) : (unSTermL ( sing :: Sing ts)) instance SingE (Kind :: [TermT]) [Term] where -- instance SingE (Kind :: [a]) [Term] where fromSing (STermL xs) = xs -- instance SingE (Kind :: [Nat]) [Int] where --------------------------------------- ppShowTerm :: Term -> String ppShowTerm CVar = "x" ppShowTerm (CCon r) = show (fromRational r :: Double) ppShowTerm (CMon op t) = ppShowMonOp op ++ "(" ++ ppShowTerm t ++ ")" ppShowTerm (CBin op t1 t2) = "(" ++ ppShowTerm t1 ++ ")"++ ppShowBinOp op ++ "(" ++ ppShowTerm t2 ++ ")" ppShowMonOp :: MonOp -> String ppShowMonOp CLog = "log" ppShowMonOp CNeg = "-" ppShowMonOp CSin = "sin" ppShowBinOp :: BinOp -> String ppShowBinOp Mult = "*" ppShowBinOp Div = "/" ppShowBinOp Pow = "^" --------------------------------------- evalStr :: Floating x => String -> x -> x evalStr str x = case parseExpr str of Right term -> evalExpr term x Left str -> error $ "evalStr: " ++ show str evalExpr :: Floating x => Expr -> x -> x evalExpr (ts) x = sum $ map (flip evalTerm x) ts evalTerm :: Floating x => Term -> x -> x evalTerm CVar x = x evalTerm (CCon c) _ = fromRational c evalTerm (CMon f t) x = (evalMonOp f) (evalTerm t x) evalTerm (CBin f t1 t2) x = (evalBinOp f) (evalTerm t1 x) (evalTerm t2 x) evalMonOp :: Floating x => MonOp -> x -> x evalMonOp CLog = log evalMonOp CNeg = negate evalMonOp CSin = sin evalBinOp :: Floating x => BinOp -> x -> x -> x evalBinOp Mult = (*) evalBinOp Div = (/) evalBinOp Pow = (**) evalBinOp Add = (+) -- train [] :: LinearRegression [expr| 1 + x + x^2 + log x ] Double
iamkingmaker/HLearn
src/HLearn/Models/Regression/Parsing.hs
bsd-3-clause
7,734
5
15
1,789
2,648
1,374
1,274
-1
-1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Configure -- Copyright : (c) David Himmelstrup 2005, -- Duncan Coutts 2005 -- License : BSD-like -- -- Maintainer : [email protected] -- Portability : portable -- -- High level interface to configuring a package. ----------------------------------------------------------------------------- module Distribution.Client.Configure ( configure, configureSetupScript, chooseCabalVersion, checkConfigExFlags ) where import Distribution.Client.Dependency import Distribution.Client.Dependency.Types ( ConstraintSource(..) , LabeledPackageConstraint(..), showConstraintSource ) import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Client.InstallPlan (InstallPlan) import Distribution.Client.IndexUtils as IndexUtils ( getSourcePackages, getInstalledPackages ) import Distribution.Client.PackageIndex ( PackageIndex, elemByPackageName ) import Distribution.Client.PkgConfigDb (PkgConfigDb, readPkgConfigDb) import Distribution.Client.Setup ( ConfigExFlags(..), configureCommand, filterConfigureFlags , RepoContext(..) ) import Distribution.Client.Types as Source import Distribution.Client.SetupWrapper ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions ) import Distribution.Client.Targets ( userToPackageConstraint, userConstraintPackageName ) import qualified Distribution.Client.ComponentDeps as CD import Distribution.Package (PackageId) import Distribution.Client.JobControl (Lock) import Distribution.Simple.Compiler ( Compiler, CompilerInfo, compilerInfo, PackageDB(..), PackageDBStack ) import Distribution.Simple.Program (ProgramConfiguration ) import Distribution.Simple.Setup ( ConfigFlags(..), AllowNewer(..) , fromFlag, toFlag, flagToMaybe, fromFlagOrDefault ) import Distribution.Simple.PackageIndex ( InstalledPackageIndex, lookupPackageName ) import Distribution.Simple.Utils ( defaultPackageDesc ) import qualified Distribution.InstalledPackageInfo as Installed import Distribution.Package ( Package(..), UnitId, packageName , Dependency(..), thisPackageVersion ) import qualified Distribution.PackageDescription as PkgDesc import Distribution.PackageDescription.Parse ( readPackageDescription ) import Distribution.PackageDescription.Configuration ( finalizePackageDescription ) import Distribution.Version ( anyVersion, thisVersion ) import Distribution.Simple.Utils as Utils ( warn, notice, debug, die ) import Distribution.Simple.Setup ( isAllowNewer ) import Distribution.System ( Platform ) import Distribution.Text ( display ) import Distribution.Verbosity as Verbosity ( Verbosity ) import Distribution.Version ( Version(..), VersionRange, orLaterVersion ) import Control.Monad (unless) #if !MIN_VERSION_base(4,8,0) import Data.Monoid (Monoid(..)) #endif import Data.Maybe (isJust, fromMaybe) -- | Choose the Cabal version such that the setup scripts compiled against this -- version will support the given command-line flags. chooseCabalVersion :: ConfigFlags -> Maybe Version -> VersionRange chooseCabalVersion configFlags maybeVersion = maybe defaultVersionRange thisVersion maybeVersion where -- Cabal < 1.19.2 doesn't support '--exact-configuration' which is needed -- for '--allow-newer' to work. allowNewer = isAllowNewer (fromMaybe AllowNewerNone $ configAllowNewer configFlags) defaultVersionRange = if allowNewer then orLaterVersion (Version [1,19,2] []) else anyVersion -- | Configure the package found in the local directory configure :: Verbosity -> PackageDBStack -> RepoContext -> Compiler -> Platform -> ProgramConfiguration -> ConfigFlags -> ConfigExFlags -> [String] -> IO () configure verbosity packageDBs repoCtxt comp platform conf configFlags configExFlags extraArgs = do installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf sourcePkgDb <- getSourcePackages verbosity repoCtxt pkgConfigDb <- readPkgConfigDb verbosity conf checkConfigExFlags verbosity installedPkgIndex (packageIndex sourcePkgDb) configExFlags progress <- planLocalPackage verbosity comp platform configFlags configExFlags installedPkgIndex sourcePkgDb pkgConfigDb notice verbosity "Resolving dependencies..." maybePlan <- foldProgress logMsg (return . Left) (return . Right) progress case maybePlan of Left message -> do warn verbosity $ "solver failed to find a solution:\n" ++ message ++ "Trying configure anyway." setupWrapper verbosity (setupScriptOptions installedPkgIndex Nothing) Nothing configureCommand (const configFlags) extraArgs Right installPlan -> case InstallPlan.ready installPlan of [pkg@(ReadyPackage (ConfiguredPackage (SourcePackage _ _ (LocalUnpackedPackage _) _) _ _ _) _)] -> do configurePackage verbosity platform (compilerInfo comp) (setupScriptOptions installedPkgIndex (Just pkg)) configFlags pkg extraArgs _ -> die $ "internal error: configure install plan should have exactly " ++ "one local ready package." where setupScriptOptions :: InstalledPackageIndex -> Maybe ReadyPackage -> SetupScriptOptions setupScriptOptions = configureSetupScript packageDBs comp platform conf (fromFlagOrDefault (useDistPref defaultSetupScriptOptions) (configDistPref configFlags)) (chooseCabalVersion configFlags (flagToMaybe (configCabalVersion configExFlags))) Nothing False logMsg message rest = debug verbosity message >> rest configureSetupScript :: PackageDBStack -> Compiler -> Platform -> ProgramConfiguration -> FilePath -> VersionRange -> Maybe Lock -> Bool -> InstalledPackageIndex -> Maybe ReadyPackage -> SetupScriptOptions configureSetupScript packageDBs comp platform conf distPref cabalVersion lock forceExternal index mpkg = SetupScriptOptions { useCabalVersion = cabalVersion , useCabalSpecVersion = Nothing , useCompiler = Just comp , usePlatform = Just platform , usePackageDB = packageDBs' , usePackageIndex = index' , useProgramConfig = conf , useDistPref = distPref , useLoggingHandle = Nothing , useWorkingDir = Nothing , setupCacheLock = lock , useWin32CleanHack = False , forceExternalSetupMethod = forceExternal -- If we have explicit setup dependencies, list them; otherwise, we give -- the empty list of dependencies; ideally, we would fix the version of -- Cabal here, so that we no longer need the special case for that in -- `compileSetupExecutable` in `externalSetupMethod`, but we don't yet -- know the version of Cabal at this point, but only find this there. -- Therefore, for now, we just leave this blank. , useDependencies = fromMaybe [] explicitSetupDeps , useDependenciesExclusive = not defaultSetupDeps && isJust explicitSetupDeps , useVersionMacros = not defaultSetupDeps && isJust explicitSetupDeps } where -- When we are compiling a legacy setup script without an explicit -- setup stanza, we typically want to allow the UserPackageDB for -- finding the Cabal lib when compiling any Setup.hs even if we're doing -- a global install. However we also allow looking in a specific package -- db. packageDBs' :: PackageDBStack index' :: Maybe InstalledPackageIndex (packageDBs', index') = case packageDBs of (GlobalPackageDB:dbs) | UserPackageDB `notElem` dbs , Nothing <- explicitSetupDeps -> (GlobalPackageDB:UserPackageDB:dbs, Nothing) -- but if the user is using an odd db stack, don't touch it _otherwise -> (packageDBs, Just index) maybeSetupBuildInfo :: Maybe PkgDesc.SetupBuildInfo maybeSetupBuildInfo = do ReadyPackage (ConfiguredPackage (SourcePackage _ gpkg _ _) _ _ _) _ <- mpkg PkgDesc.setupBuildInfo (PkgDesc.packageDescription gpkg) -- Was a default 'custom-setup' stanza added by 'cabal-install' itself? If -- so, 'setup-depends' must not be exclusive. See #3199. defaultSetupDeps :: Bool defaultSetupDeps = maybe False PkgDesc.defaultSetupDepends maybeSetupBuildInfo explicitSetupDeps :: Maybe [(UnitId, PackageId)] explicitSetupDeps = do -- Check if there is an explicit setup stanza. _buildInfo <- maybeSetupBuildInfo -- Return the setup dependencies computed by the solver ReadyPackage _ deps <- mpkg return [ ( Installed.installedUnitId deppkg , Installed.sourcePackageId deppkg ) | deppkg <- CD.setupDeps deps ] -- | Warn if any constraints or preferences name packages that are not in the -- source package index or installed package index. checkConfigExFlags :: Package pkg => Verbosity -> InstalledPackageIndex -> PackageIndex pkg -> ConfigExFlags -> IO () checkConfigExFlags verbosity installedPkgIndex sourcePkgIndex flags = do unless (null unknownConstraints) $ warn verbosity $ "Constraint refers to an unknown package: " ++ showConstraint (head unknownConstraints) unless (null unknownPreferences) $ warn verbosity $ "Preference refers to an unknown package: " ++ display (head unknownPreferences) where unknownConstraints = filter (unknown . userConstraintPackageName . fst) $ configExConstraints flags unknownPreferences = filter (unknown . \(Dependency name _) -> name) $ configPreferences flags unknown pkg = null (lookupPackageName installedPkgIndex pkg) && not (elemByPackageName sourcePkgIndex pkg) showConstraint (uc, src) = display uc ++ " (" ++ showConstraintSource src ++ ")" -- | Make an 'InstallPlan' for the unpacked package in the current directory, -- and all its dependencies. -- planLocalPackage :: Verbosity -> Compiler -> Platform -> ConfigFlags -> ConfigExFlags -> InstalledPackageIndex -> SourcePackageDb -> PkgConfigDb -> IO (Progress String String InstallPlan) planLocalPackage verbosity comp platform configFlags configExFlags installedPkgIndex (SourcePackageDb _ packagePrefs) pkgConfigDb = do pkg <- readPackageDescription verbosity =<< defaultPackageDesc verbosity solver <- chooseSolver verbosity (fromFlag $ configSolver configExFlags) (compilerInfo comp) let -- We create a local package and ask to resolve a dependency on it localPkg = SourcePackage { packageInfoId = packageId pkg, Source.packageDescription = pkg, packageSource = LocalUnpackedPackage ".", packageDescrOverride = Nothing } testsEnabled = fromFlagOrDefault False $ configTests configFlags benchmarksEnabled = fromFlagOrDefault False $ configBenchmarks configFlags resolverParams = removeUpperBounds (fromMaybe AllowNewerNone $ configAllowNewer configFlags) . addPreferences -- preferences from the config file or command line [ PackageVersionPreference name ver | Dependency name ver <- configPreferences configExFlags ] . addConstraints -- version constraints from the config file or command line -- TODO: should warn or error on constraints that are not on direct -- deps or flag constraints not on the package in question. [ LabeledPackageConstraint (userToPackageConstraint uc) src | (uc, src) <- configExConstraints configExFlags ] . addConstraints -- package flags from the config file or command line [ let pc = PackageConstraintFlags (packageName pkg) (configConfigurationsFlags configFlags) in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget ] . addConstraints -- '--enable-tests' and '--enable-benchmarks' constraints from -- the config file or command line [ let pc = PackageConstraintStanzas (packageName pkg) $ [ TestStanzas | testsEnabled ] ++ [ BenchStanzas | benchmarksEnabled ] in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget ] $ standardInstallPolicy installedPkgIndex (SourcePackageDb mempty packagePrefs) [SpecificSourcePackage localPkg] return (resolveDependencies platform (compilerInfo comp) pkgConfigDb solver resolverParams) -- | Call an installer for an 'SourcePackage' but override the configure -- flags with the ones given by the 'ReadyPackage'. In particular the -- 'ReadyPackage' specifies an exact 'FlagAssignment' and exactly -- versioned package dependencies. So we ignore any previous partial flag -- assignment or dependency constraints and use the new ones. -- -- NB: when updating this function, don't forget to also update -- 'installReadyPackage' in D.C.Install. configurePackage :: Verbosity -> Platform -> CompilerInfo -> SetupScriptOptions -> ConfigFlags -> ReadyPackage -> [String] -> IO () configurePackage verbosity platform comp scriptOptions configFlags (ReadyPackage (ConfiguredPackage (SourcePackage _ gpkg _ _) flags stanzas _) deps) extraArgs = setupWrapper verbosity scriptOptions (Just pkg) configureCommand configureFlags extraArgs where configureFlags = filterConfigureFlags configFlags { configConfigurationsFlags = flags, -- We generate the legacy constraints as well as the new style precise -- deps. In the end only one set gets passed to Setup.hs configure, -- depending on the Cabal version we are talking to. configConstraints = [ thisPackageVersion (packageId deppkg) | deppkg <- CD.nonSetupDeps deps ], configDependencies = [ (packageName (Installed.sourcePackageId deppkg), Installed.installedUnitId deppkg) | deppkg <- CD.nonSetupDeps deps ], -- Use '--exact-configuration' if supported. configExactConfiguration = toFlag True, configVerbosity = toFlag verbosity, configBenchmarks = toFlag (BenchStanzas `elem` stanzas), configTests = toFlag (TestStanzas `elem` stanzas) } pkg = case finalizePackageDescription flags (const True) platform comp [] (enableStanzas stanzas gpkg) of Left _ -> error "finalizePackageDescription ReadyPackage failed" Right (desc, _) -> desc
tolysz/prepare-ghcjs
spec-lts8/cabal/cabal-install/Distribution/Client/Configure.hs
bsd-3-clause
16,322
0
22
4,727
2,628
1,429
1,199
285
3
-- | This module defines 'PerformEvent' and 'TriggerEvent', which mediate the -- interaction between a "Reflex"-based program and the external side-effecting -- actions such as 'IO'. {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} #ifdef USE_REFLEX_OPTIMIZER {-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-} #endif module Reflex.PerformEvent.Class ( PerformEvent (..) , performEventAsync ) where import Reflex.Class import Reflex.TriggerEvent.Class import Control.Monad.Reader import Control.Monad.Trans.Maybe (MaybeT (..)) -- | 'PerformEvent' represents actions that can trigger other actions based on -- 'Event's. class (Reflex t, Monad (Performable m), Monad m) => PerformEvent t m | m -> t where -- | The type of action to be triggered; this is often not the same type as -- the triggering action. type Performable m :: * -> * -- | Perform the action contained in the given 'Event' whenever the 'Event' -- fires. Return the result in another 'Event'. Note that the output 'Event' -- will generally occur later than the input 'Event', since most 'Performable' -- actions cannot be performed during 'Event' propagation. performEvent :: Event t (Performable m a) -> m (Event t a) -- | Like 'performEvent', but do not return the result. May have slightly -- better performance. performEvent_ :: Event t (Performable m ()) -> m () -- | Like 'performEvent', but the resulting 'Event' occurs only when the -- callback (@a -> IO ()@) is called, not when the included action finishes. -- -- NOTE: Despite the name, 'performEventAsync' does not run its action in a -- separate thread - although the action is free to invoke forkIO and then call -- the callback whenever it is ready. This will work properly, even in GHCJS -- (which fully implements concurrency even though JavaScript does not have -- built in concurrency). {-# INLINABLE performEventAsync #-} performEventAsync :: (TriggerEvent t m, PerformEvent t m) => Event t ((a -> IO ()) -> Performable m ()) -> m (Event t a) performEventAsync e = do (eOut, triggerEOut) <- newTriggerEvent performEvent_ $ fmap ($ triggerEOut) e return eOut instance PerformEvent t m => PerformEvent t (ReaderT r m) where type Performable (ReaderT r m) = ReaderT r (Performable m) performEvent_ e = do r <- ask lift $ performEvent_ $ flip runReaderT r <$> e performEvent e = do r <- ask lift $ performEvent $ flip runReaderT r <$> e instance PerformEvent t m => PerformEvent t (MaybeT m) where type Performable (MaybeT m) = MaybeT (Performable m) performEvent_ = lift . performEvent_ . fmapCheap (void . runMaybeT) performEvent = lift . fmap (fmapMaybe id) . performEvent . fmapCheap runMaybeT
ryantrinkle/reflex
src/Reflex/PerformEvent/Class.hs
bsd-3-clause
2,910
0
13
520
541
293
248
-1
-1
{-# LANGUAGE FlexibleContexts, UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Database.Persist.Redis.Store ( execRedisT , RedisBackend )where import Database.Persist import Control.Monad.IO.Class (MonadIO (..)) import qualified Database.Persist.Sql as Sql import qualified Database.Redis as R import Data.Text (Text, pack) import Database.Persist.Redis.Config (RedisT, thisConnection) import Database.Persist.Redis.Internal import Database.Persist.Redis.Update import Web.PathPieces (PathPiece(..)) import Web.HttpApiData (ToHttpApiData (..), FromHttpApiData (..), parseUrlPieceMaybe) import Data.Aeson(FromJSON(..), ToJSON(..)) type RedisBackend = R.Connection -- | Fetches a next key from <object>_id record createKey :: (R.RedisCtx m f, PersistEntity val) => val -> m (f Integer) createKey val = do let keyId = toKeyId val R.incr keyId desugar :: R.TxResult a -> Either String a desugar (R.TxSuccess x) = Right x desugar R.TxAborted = Left "Transaction aborted!" desugar (R.TxError string) = Left string -- | Execute Redis transaction inside RedisT monad transformer execRedisT :: (Monad m, MonadIO m) => R.RedisTx (R.Queued a) -> RedisT m a execRedisT action = do conn <- thisConnection result <- liftIO $ R.runRedis conn $ R.multiExec action -- this is the question if we should support transaction here let r = desugar result case r of (Right x) -> return x (Left x) -> fail x instance HasPersistBackend R.Connection where type BaseBackend R.Connection = R.Connection persistBackend = id instance PersistCore R.Connection where newtype BackendKey R.Connection = RedisKey Text deriving (Show, Read, Eq, Ord, PersistField, FromJSON, ToJSON) instance PersistStoreRead R.Connection where get k = do r <- execRedisT $ R.hgetall (unKey k) if null r then return Nothing else do Entity _ val <- mkEntity k r return $ Just val instance PersistStoreWrite R.Connection where insert val = do keyId <- execRedisT $ createKey val let textKey = toKeyText val keyId key <- toKey textKey _ <- insertKey key val return key insertKey k val = do let fields = toInsertFields val -- Inserts a hash map into <object>_<id> record _ <- execRedisT $ R.hmset (unKey k) fields return () repsert k val = do _ <- execRedisT $ R.del [unKey k] insertKey k val return () replace k val = do delete k insertKey k val return () delete k = do r <- execRedisT $ R.del [unKey k] case r of 0 -> fail "there is no such key!" 1 -> return () _ -> fail "there are a lot of such keys!" update _ [] = return () update k upds = do r <- execRedisT $ R.hgetall (unKey k) if null r then fail "No such key exists!" else do v <- mkEntity k r let (Entity _ val) = cmdUpdate v upds insertKey k val return() instance ToHttpApiData (BackendKey RedisBackend) where toUrlPiece (RedisKey txt) = txt instance FromHttpApiData (BackendKey RedisBackend) where parseUrlPiece = return . RedisKey -- some checking that entity exists and it is in format of entityname_id is omitted instance PathPiece (BackendKey RedisBackend) where toPathPiece = toUrlPiece fromPathPiece = parseUrlPieceMaybe instance Sql.PersistFieldSql (BackendKey RedisBackend) where sqlType _ = Sql.SqlOther (pack "doesn't make much sense for Redis backend")
plow-technologies/persistent
persistent-redis/Database/Persist/Redis/Store.hs
mit
3,780
0
15
976
1,107
554
553
94
2
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="da-DK"> <title>Retest Add-On</title> <maps> <homeID>retest</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/retest/src/main/javahelp/org/zaproxy/addon/retest/resources/help_da_DK/helpset_da_DK.hs
apache-2.0
961
77
67
156
411
208
203
-1
-1
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} module T17646 where data T a where A :: T True B :: T False g :: () g | B <- A = ()
sdiehl/ghc
testsuite/tests/pmcheck/should_compile/T17646.hs
bsd-3-clause
141
0
8
40
51
29
22
8
1
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[PrimOp]{Primitive operations (machine-level)} -} {-# LANGUAGE CPP #-} module PrimOp ( PrimOp(..), PrimOpVecCat(..), allThePrimOps, primOpType, primOpSig, primOpTag, maxPrimOpTag, primOpOcc, tagToEnumKey, primOpOutOfLine, primOpCodeSize, primOpOkForSpeculation, primOpOkForSideEffects, primOpIsCheap, primOpFixity, getPrimOpResultInfo, PrimOpResultInfo(..), PrimCall(..) ) where #include "HsVersions.h" import TysPrim import TysWiredIn import CmmType import Demand import Var ( TyVar ) import OccName ( OccName, pprOccName, mkVarOccFS ) import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) ) import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon, typePrimRep ) import BasicTypes ( Arity, Fixity(..), FixityDirection(..), Boxity(..) ) import ForeignCall ( CLabelString ) import Unique ( Unique, mkPrimOpIdUnique ) import Outputable import FastTypes import FastString import Module ( PackageKey ) {- ************************************************************************ * * \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)} * * ************************************************************************ These are in \tr{state-interface.verb} order. -} -- supplies: -- data PrimOp = ... #include "primop-data-decl.hs-incl" -- Used for the Ord instance primOpTag :: PrimOp -> Int primOpTag op = iBox (tagOf_PrimOp op) -- supplies -- tagOf_PrimOp :: PrimOp -> FastInt #include "primop-tag.hs-incl" tagOf_PrimOp _ = error "tagOf_PrimOp: unknown primop" instance Eq PrimOp where op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2 instance Ord PrimOp where op1 < op2 = tagOf_PrimOp op1 <# tagOf_PrimOp op2 op1 <= op2 = tagOf_PrimOp op1 <=# tagOf_PrimOp op2 op1 >= op2 = tagOf_PrimOp op1 >=# tagOf_PrimOp op2 op1 > op2 = tagOf_PrimOp op1 ># tagOf_PrimOp op2 op1 `compare` op2 | op1 < op2 = LT | op1 == op2 = EQ | otherwise = GT instance Outputable PrimOp where ppr op = pprPrimOp op data PrimOpVecCat = IntVec | WordVec | FloatVec -- An @Enum@-derived list would be better; meanwhile... (ToDo) allThePrimOps :: [PrimOp] allThePrimOps = #include "primop-list.hs-incl" tagToEnumKey :: Unique tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp) {- ************************************************************************ * * \subsection[PrimOp-info]{The essential info about each @PrimOp@} * * ************************************************************************ The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may refer to the primitive operation. The conventional \tr{#}-for- unboxed ops is added on later. The reason for the funny characters in the names is so we do not interfere with the programmer's Haskell name spaces. We use @PrimKinds@ for the ``type'' information, because they're (slightly) more convenient to use than @TyCons@. -} data PrimOpInfo = Dyadic OccName -- string :: T -> T -> T Type | Monadic OccName -- string :: T -> T Type | Compare OccName -- string :: T -> T -> Int# Type | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T [TyVar] [Type] Type mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo mkDyadic str ty = Dyadic (mkVarOccFS str) ty mkMonadic str ty = Monadic (mkVarOccFS str) ty mkCompare str ty = Compare (mkVarOccFS str) ty mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty {- ************************************************************************ * * \subsubsection{Strictness} * * ************************************************************************ Not all primops are strict! -} primOpStrictness :: PrimOp -> Arity -> StrictSig -- See Demand.StrictnessInfo for discussion of what the results -- The arity should be the arity of the primop; that's why -- this function isn't exported. #include "primop-strictness.hs-incl" {- ************************************************************************ * * \subsubsection{Fixity} * * ************************************************************************ -} primOpFixity :: PrimOp -> Maybe Fixity #include "primop-fixity.hs-incl" {- ************************************************************************ * * \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops} * * ************************************************************************ @primOpInfo@ gives all essential information (from which everything else, notably a type, can be constructed) for each @PrimOp@. -} primOpInfo :: PrimOp -> PrimOpInfo #include "primop-primop-info.hs-incl" primOpInfo _ = error "primOpInfo: unknown primop" {- Here are a load of comments from the old primOp info: A @Word#@ is an unsigned @Int#@. @decodeFloat#@ is given w/ Integer-stuff (it's similar). @decodeDouble#@ is given w/ Integer-stuff (it's similar). Decoding of floating-point numbers is sorta Integer-related. Encoding is done with plain ccalls now (see PrelNumExtra.hs). A @Weak@ Pointer is created by the @mkWeak#@ primitive: mkWeak# :: k -> v -> f -> State# RealWorld -> (# State# RealWorld, Weak# v #) In practice, you'll use the higher-level data Weak v = Weak# v mkWeak :: k -> v -> IO () -> IO (Weak v) The following operation dereferences a weak pointer. The weak pointer may have been finalized, so the operation returns a result code which must be inspected before looking at the dereferenced value. deRefWeak# :: Weak# v -> State# RealWorld -> (# State# RealWorld, v, Int# #) Only look at v if the Int# returned is /= 0 !! The higher-level op is deRefWeak :: Weak v -> IO (Maybe v) Weak pointers can be finalized early by using the finalize# operation: finalizeWeak# :: Weak# v -> State# RealWorld -> (# State# RealWorld, Int#, IO () #) The Int# returned is either 0 if the weak pointer has already been finalized, or it has no finalizer (the third component is then invalid). 1 if the weak pointer is still alive, with the finalizer returned as the third component. A {\em stable name/pointer} is an index into a table of stable name entries. Since the garbage collector is told about stable pointers, it is safe to pass a stable pointer to external systems such as C routines. \begin{verbatim} makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #) freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #) eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int# \end{verbatim} It may seem a bit surprising that @makeStablePtr#@ is a @IO@ operation since it doesn't (directly) involve IO operations. The reason is that if some optimisation pass decided to duplicate calls to @makeStablePtr#@ and we only pass one of the stable pointers over, a massive space leak can result. Putting it into the IO monad prevents this. (Another reason for putting them in a monad is to ensure correct sequencing wrt the side-effecting @freeStablePtr@ operation.) An important property of stable pointers is that if you call makeStablePtr# twice on the same object you get the same stable pointer back. Note that we can implement @freeStablePtr#@ using @_ccall_@ (and, besides, it's not likely to be used from Haskell) so it's not a primop. Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR] Stable Names ~~~~~~~~~~~~ A stable name is like a stable pointer, but with three important differences: (a) You can't deRef one to get back to the original object. (b) You can convert one to an Int. (c) You don't need to 'freeStableName' The existence of a stable name doesn't guarantee to keep the object it points to alive (unlike a stable pointer), hence (a). Invariants: (a) makeStableName always returns the same value for a given object (same as stable pointers). (b) if two stable names are equal, it implies that the objects from which they were created were the same. (c) stableNameToInt always returns the same Int for a given stable name. These primops are pretty weird. dataToTag# :: a -> Int (arg must be an evaluated data type) tagToEnum# :: Int -> a (result type must be an enumerated type) The constraints aren't currently checked by the front end, but the code generator will fall over if they aren't satisfied. ************************************************************************ * * Which PrimOps are out-of-line * * ************************************************************************ Some PrimOps need to be called out-of-line because they either need to perform a heap check or they block. -} primOpOutOfLine :: PrimOp -> Bool #include "primop-out-of-line.hs-incl" {- ************************************************************************ * * Failure and side effects * * ************************************************************************ Note [PrimOp can_fail and has_side_effects] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Both can_fail and has_side_effects mean that the primop has some effect that is not captured entirely by its result value. ---------- has_side_effects --------------------- A primop "has_side_effects" if it has some *write* effect, visible elsewhere - writing to the world (I/O) - writing to a mutable data structure (writeIORef) - throwing a synchronous Haskell exception Often such primops have a type like State -> input -> (State, output) so the state token guarantees ordering. In general we rely *only* on data dependencies of the state token to enforce write-effect ordering * NB1: if you inline unsafePerformIO, you may end up with side-effecting ops whose 'state' output is discarded. And programmers may do that by hand; see Trac #9390. That is why we (conservatively) do not discard write-effecting primops even if both their state and result is discarded. * NB2: We consider primops, such as raiseIO#, that can raise a (Haskell) synchronous exception to "have_side_effects" but not "can_fail". We must be careful about not discarding such things; see the paper "A semantics for imprecise exceptions". * NB3: *Read* effects (like reading an IORef) don't count here, because it doesn't matter if we don't do them, or do them more than once. *Sequencing* is maintained by the data dependency of the state token. ---------- can_fail ---------------------------- A primop "can_fail" if it can fail with an *unchecked* exception on some elements of its input domain. Main examples: division (fails on zero demoninator) array indexing (fails if the index is out of bounds) An "unchecked exception" is one that is an outright error, (not turned into a Haskell exception,) such as seg-fault or divide-by-zero error. Such can_fail primops are ALWAYS surrounded with a test that checks for the bad cases, but we need to be very careful about code motion that might move it out of the scope of the test. Note [Transformations affected by can_fail and has_side_effects] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The can_fail and has_side_effects properties have the following effect on program transformations. Summary table is followed by details. can_fail has_side_effects Discard NO NO Float in YES YES Float out NO NO Duplicate YES NO * Discarding. case (a `op` b) of _ -> rhs ===> rhs You should not discard a has_side_effects primop; e.g. case (writeIntArray# a i v s of (# _, _ #) -> True Arguably you should be able to discard this, since the returned stat token is not used, but that relies on NEVER inlining unsafePerformIO, and programmers sometimes write this kind of stuff by hand (Trac #9390). So we (conservatively) never discard a has_side_effects primop. However, it's fine to discard a can_fail primop. For example case (indexIntArray# a i) of _ -> True We can discard indexIntArray#; it has can_fail, but not has_side_effects; see Trac #5658 which was all about this. Notice that indexIntArray# is (in a more general handling of effects) read effect, but we don't care about that here, and treat read effects as *not* has_side_effects. Similarly (a `/#` b) can be discarded. It can seg-fault or cause a hardware exception, but not a synchronous Haskell exception. Synchronous Haskell exceptions, e.g. from raiseIO#, are treated as has_side_effects and hence are not discarded. * Float in. You can float a can_fail or has_side_effects primop *inwards*, but not inside a lambda (see Duplication below). * Float out. You must not float a can_fail primop *outwards* lest you escape the dynamic scope of the test. Example: case d ># 0# of True -> case x /# d of r -> r +# 1 False -> 0 Here we must not float the case outwards to give case x/# d of r -> case d ># 0# of True -> r +# 1 False -> 0 Nor can you float out a has_side_effects primop. For example: if blah then case writeMutVar# v True s0 of (# s1 #) -> s1 else s0 Notice that s0 is mentioned in both branches of the 'if', but only one of these two will actually be consumed. But if we float out to case writeMutVar# v True s0 of (# s1 #) -> if blah then s1 else s0 the writeMutVar will be performed in both branches, which is utterly wrong. * Duplication. You cannot duplicate a has_side_effect primop. You might wonder how this can occur given the state token threading, but just look at Control.Monad.ST.Lazy.Imp.strictToLazy! We get something like this p = case readMutVar# s v of (# s', r #) -> (S# s', r) s' = case p of (s', r) -> s' r = case p of (s', r) -> r (All these bindings are boxed.) If we inline p at its two call sites, we get a catastrophe: because the read is performed once when s' is demanded, and once when 'r' is demanded, which may be much later. Utterly wrong. Trac #3207 is real example of this happening. However, it's fine to duplicate a can_fail primop. That is really the only difference between can_fail and has_side_effects. Note [Implementation: how can_fail/has_side_effects affect transformations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How do we ensure that that floating/duplication/discarding are done right in the simplifier? Two main predicates on primpops test these flags: primOpOkForSideEffects <=> not has_side_effects primOpOkForSpeculation <=> not (has_side_effects || can_fail) * The "no-float-out" thing is achieved by ensuring that we never let-bind a can_fail or has_side_effects primop. The RHS of a let-binding (which can float in and out freely) satisfies exprOkForSpeculation; this is the let/app invariant. And exprOkForSpeculation is false of can_fail and has_side_effects. * So can_fail and has_side_effects primops will appear only as the scrutinees of cases, and that's why the FloatIn pass is capable of floating case bindings inwards. * The no-duplicate thing is done via primOpIsCheap, by making has_side_effects things (very very very) not-cheap! -} primOpHasSideEffects :: PrimOp -> Bool #include "primop-has-side-effects.hs-incl" primOpCanFail :: PrimOp -> Bool #include "primop-can-fail.hs-incl" primOpOkForSpeculation :: PrimOp -> Bool -- See Note [PrimOp can_fail and has_side_effects] -- See comments with CoreUtils.exprOkForSpeculation -- primOpOkForSpeculation => primOpOkForSideEffects primOpOkForSpeculation op = primOpOkForSideEffects op && not (primOpOutOfLine op || primOpCanFail op) -- I think the "out of line" test is because out of line things can -- be expensive (eg sine, cosine), and so we may not want to speculate them primOpOkForSideEffects :: PrimOp -> Bool primOpOkForSideEffects op = not (primOpHasSideEffects op) {- Note [primOpIsCheap] ~~~~~~~~~~~~~~~~~~~~ @primOpIsCheap@, as used in \tr{SimplUtils.hs}. For now (HACK WARNING), we just borrow some other predicates for a what-should-be-good-enough test. "Cheap" means willing to call it more than once, and/or push it inside a lambda. The latter could change the behaviour of 'seq' for primops that can fail, so we don't treat them as cheap. -} primOpIsCheap :: PrimOp -> Bool -- See Note [PrimOp can_fail and has_side_effects] primOpIsCheap op = primOpOkForSpeculation op -- In March 2001, we changed this to -- primOpIsCheap op = False -- thereby making *no* primops seem cheap. But this killed eta -- expansion on case (x ==# y) of True -> \s -> ... -- which is bad. In particular a loop like -- doLoop n = loop 0 -- where -- loop i | i == n = return () -- | otherwise = bar i >> loop (i+1) -- allocated a closure every time round because it doesn't eta expand. -- -- The problem that originally gave rise to the change was -- let x = a +# b *# c in x +# x -- were we don't want to inline x. But primopIsCheap doesn't control -- that (it's exprIsDupable that does) so the problem doesn't occur -- even if primOpIsCheap sometimes says 'True'. {- ************************************************************************ * * PrimOp code size * * ************************************************************************ primOpCodeSize ~~~~~~~~~~~~~~ Gives an indication of the code size of a primop, for the purposes of calculating unfolding sizes; see CoreUnfold.sizeExpr. -} primOpCodeSize :: PrimOp -> Int #include "primop-code-size.hs-incl" primOpCodeSizeDefault :: Int primOpCodeSizeDefault = 1 -- CoreUnfold.primOpSize already takes into account primOpOutOfLine -- and adds some further costs for the args in that case. primOpCodeSizeForeignCall :: Int primOpCodeSizeForeignCall = 4 {- ************************************************************************ * * PrimOp types * * ************************************************************************ -} primOpType :: PrimOp -> Type -- you may want to use primOpSig instead primOpType op = case primOpInfo op of Dyadic _occ ty -> dyadic_fun_ty ty Monadic _occ ty -> monadic_fun_ty ty Compare _occ ty -> compare_fun_ty ty GenPrimOp _occ tyvars arg_tys res_ty -> mkForAllTys tyvars (mkFunTys arg_tys res_ty) primOpOcc :: PrimOp -> OccName primOpOcc op = case primOpInfo op of Dyadic occ _ -> occ Monadic occ _ -> occ Compare occ _ -> occ GenPrimOp occ _ _ _ -> occ -- primOpSig is like primOpType but gives the result split apart: -- (type variables, argument types, result type) -- It also gives arity, strictness info primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig) primOpSig op = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity) where arity = length arg_tys (tyvars, arg_tys, res_ty) = case (primOpInfo op) of Monadic _occ ty -> ([], [ty], ty ) Dyadic _occ ty -> ([], [ty,ty], ty ) Compare _occ ty -> ([], [ty,ty], intPrimTy) GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty ) data PrimOpResultInfo = ReturnsPrim PrimRep | ReturnsAlg TyCon -- Some PrimOps need not return a manifest primitive or algebraic value -- (i.e. they might return a polymorphic value). These PrimOps *must* -- be out of line, or the code generator won't work. getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo getPrimOpResultInfo op = case (primOpInfo op) of Dyadic _ ty -> ReturnsPrim (typePrimRep ty) Monadic _ ty -> ReturnsPrim (typePrimRep ty) Compare _ _ -> ReturnsPrim (tyConPrimRep intPrimTyCon) GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc) | otherwise -> ReturnsAlg tc where tc = tyConAppTyCon ty -- All primops return a tycon-app result -- The tycon can be an unboxed tuple, though, which -- gives rise to a ReturnAlg {- We do not currently make use of whether primops are commutable. We used to try to move constants to the right hand side for strength reduction. -} {- commutableOp :: PrimOp -> Bool #include "primop-commutable.hs-incl" -} -- Utils: dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type dyadic_fun_ty ty = mkFunTys [ty, ty] ty monadic_fun_ty ty = mkFunTy ty ty compare_fun_ty ty = mkFunTys [ty, ty] intPrimTy -- Output stuff: pprPrimOp :: PrimOp -> SDoc pprPrimOp other_op = pprOccName (primOpOcc other_op) {- ************************************************************************ * * \subsubsection[PrimCall]{User-imported primitive calls} * * ************************************************************************ -} data PrimCall = PrimCall CLabelString PackageKey instance Outputable PrimCall where ppr (PrimCall lbl pkgId) = text "__primcall" <+> ppr pkgId <+> ppr lbl
urbanslug/ghc
compiler/prelude/PrimOp.hs
bsd-3-clause
23,414
0
11
6,323
1,586
874
712
-1
-1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} module Aws.Iam.Commands.UpdateAccessKey ( UpdateAccessKey(..) , UpdateAccessKeyResponse(..) ) where import Aws.Core import Aws.Iam.Core import Aws.Iam.Internal import Control.Applicative import Data.Text (Text) import Data.Typeable -- | Changes the status of the specified access key. -- -- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html> data UpdateAccessKey = UpdateAccessKey { uakAccessKeyId :: Text -- ^ ID of the access key to update. , uakStatus :: AccessKeyStatus -- ^ New status of the access key. , uakUserName :: Maybe Text -- ^ Name of the user to whom the access key belongs. If omitted, the -- user will be determined based on the access key used to sign the -- request. } deriving (Eq, Ord, Show, Typeable) instance SignQuery UpdateAccessKey where type ServiceConfiguration UpdateAccessKey = IamConfiguration signQuery UpdateAccessKey{..} = iamAction' "UpdateAccessKey" [ Just ("AccessKeyId", uakAccessKeyId) , Just ("Status", showStatus uakStatus) , ("UserName",) <$> uakUserName ] where showStatus AccessKeyActive = "Active" showStatus _ = "Inactive" data UpdateAccessKeyResponse = UpdateAccessKeyResponse deriving (Eq, Ord, Show, Typeable) instance ResponseConsumer UpdateAccessKey UpdateAccessKeyResponse where type ResponseMetadata UpdateAccessKeyResponse = IamMetadata responseConsumer _ = iamResponseConsumer (const $ return UpdateAccessKeyResponse) instance Transaction UpdateAccessKey UpdateAccessKeyResponse instance AsMemoryResponse UpdateAccessKeyResponse where type MemoryResponse UpdateAccessKeyResponse = UpdateAccessKeyResponse loadToMemory = return
Soostone/aws
Aws/Iam/Commands/UpdateAccessKey.hs
bsd-3-clause
2,063
0
10
521
311
179
132
38
0
module Pretty ( ppexpr ) where import Syntax import Text.PrettyPrint (Doc, (<>), (<+>)) import qualified Text.PrettyPrint as PP parensIf :: Bool -> Doc -> Doc parensIf True = PP.parens parensIf False = id class Pretty p where ppr :: Int -> p -> Doc instance Pretty Expr where ppr _ Zero = PP.text "0" ppr _ Tr = PP.text "true" ppr _ Fl = PP.text "false" ppr p (Succ a) = (parensIf (p > 0) $ PP.text "succ" <+> ppr (p+1) a) ppr p (Pred a) = (parensIf (p > 0) $ PP.text "succ" <+> ppr (p+1) a) ppr p (IsZero a) = (parensIf (p > 0) $ PP.text "iszero" <+> ppr (p+1) a) ppr p (If a b c) = PP.text "if" <+> ppr p a <+> PP.text "then" <+> ppr p b <+> PP.text "else" <+> ppr p c ppexpr :: Expr -> String ppexpr = PP.render . ppr 0
zanesterling/haskell-compiler
src/TypedPeanoArithmetic/Pretty.hs
bsd-3-clause
766
0
12
195
401
205
196
23
1
{-# LANGUAGE TypeFamilies #-} module ShouldFail where foo :: (a,b) -> (a~b => t) -> (a,b) foo p x = p
urbanslug/ghc
testsuite/tests/indexed-types/should_fail/SimpleFail15.hs
bsd-3-clause
105
0
10
24
52
30
22
-1
-1
-- !!! exporting a field name (but not its type) module M where import Mod123_A f :: T -> Int f x = f1 x
ghc-android/ghc
testsuite/tests/module/mod123.hs
bsd-3-clause
106
0
5
26
28
16
12
4
1
import Text.ParserCombinators.Parsec csvFile = endBy line eol line = sepBy cell (char ',') cell = many (noneOf ",\n") eol = char '\n' parseCSV :: String -> Either ParseError [[String]] parseCSV input = parse csvFile "(unknown)" input
zhangjiji/real-world-haskell
ch16/csv2.hs
mit
236
0
8
38
90
46
44
7
1
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-} -- TODO: Add some comments describing how this implementation works. -- | A reimplementation of Data.WordMap that seems to be 1.4-4x faster. module Data.WordMap.Lazy ( -- * Map type WordMap, Key -- * Operators , (!) , (\\) -- * Query , null , size , member , notMember , lookup , findWithDefault , lookupLT , lookupGT , lookupLE , lookupGE -- * Construction , empty , singleton -- ** Insertion , insert , insertWith , insertWithKey , insertLookupWithKey -- ** Delete\/Update , delete , adjust , adjustWithKey , update , updateWithKey , updateLookupWithKey , alter , alterF -- * Combine -- ** Union , union , unionM , unionWith , unionWithM , unionWithKey , unions , unionsWith -- ** Difference , difference , differenceM , differenceWith , differenceWithKey -- ** Intersection , intersection , intersectionM , intersectionWith , intersectionWithM , intersectionWithKey -- * Traversal -- ** Map , map , mapWithKey , traverseWithKey , mapAccum , mapAccumWithKey , mapAccumRWithKey , mapKeys , mapKeysWith , mapKeysMonotonic -- * Folds , foldr , foldl , foldrWithKey , foldlWithKey , foldMapWithKey -- ** Strict folds , foldr' , foldl' , foldrWithKey' , foldlWithKey' -- * Conversion , elems , keys , assocs -- ** Lists , toList , fromList , fromListWith , fromListWithKey -- ** Ordered Lists , toAscList , toDescList , fromAscList , fromAscListWith , fromAscListWithKey , fromDistinctAscList -- * Filter , filter , filterWithKey , partition , partitionWithKey , mapMaybe , mapMaybeWithKey , mapEither , mapEitherWithKey , split , splitLookup , splitRoot -- * Submap , isSubmapOf , isSubmapOfBy , isProperSubmapOf , isProperSubmapOfBy -- * Min\/Max , findMin , findMax , deleteMin , deleteMax , deleteFindMin , deleteFindMax , updateMin , updateMax , updateMinWithKey , updateMaxWithKey , minView , maxView , minViewWithKey , maxViewWithKey -- * Debugging , showTree , valid ) where import Data.WordMap.Base import Data.WordMap.Merge.Base (unionM, differenceM, intersectionM) import Data.WordMap.Merge.Lazy (unionWithM, intersectionWithM) import Control.Applicative (Applicative(..)) import Data.Functor ((<$>)) import Data.Bits (xor) import Data.StrictPair (StrictPair(..), toPair) import qualified Data.List (foldl') import Prelude hiding (foldr, foldl, lookup, null, map, filter, min, max) -- | /O(1)/. A map of one element. -- -- > singleton 1 'a' == fromList [(1, 'a')] -- > size (singleton 1 'a') == 1 singleton :: Key -> a -> WordMap a singleton k v = WordMap (NonEmpty k v Tip) -- | /O(min(n,W))/. Insert a new key\/value pair in the map. -- If the key is already present in the map, the associated value is -- replaced with the supplied value, i.e. 'insert' is equivalent to -- @'insertWith' 'const'@. -- -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')] -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')] -- > insert 5 'x' empty == singleton 5 'x' insert :: Key -> a -> WordMap a -> WordMap a insert = start where start !k v (WordMap Empty) = WordMap (NonEmpty k v Tip) start !k v (WordMap (NonEmpty min minV root)) | k > min = WordMap (NonEmpty min minV (goL k v (xor min k) min root)) | k < min = WordMap (NonEmpty k v (insertMinL (xor min k) min minV root)) | otherwise = WordMap (NonEmpty k v root) goL !k v !_ !_ Tip = Bin k v Tip Tip goL !k v !xorCache !min (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then Bin max maxV (goL k v xorCache min l) r else Bin max maxV l (goR k v xorCacheMax max r) | k > max = if xor min max < xorCacheMax then Bin k v (Bin max maxV l r) Tip else Bin k v l (insertMaxR xorCacheMax max maxV r) | otherwise = Bin max v l r where xorCacheMax = xor k max goR !k v !_ !_ Tip = Bin k v Tip Tip goR !k v !xorCache !max (Bin min minV l r) | k > min = if xorCache < xorCacheMin then Bin min minV l (goR k v xorCache max r) else Bin min minV (goL k v xorCacheMin min l) r | k < min = if xor min max < xorCacheMin then Bin k v Tip (Bin min minV l r) else Bin k v (insertMinL xorCacheMin min minV l) r | otherwise = Bin min v l r where xorCacheMin = xor min k -- | /O(min(n,W))/. Insert with a combining function. -- @'insertWith' f key value mp@ -- will insert the pair (key, value) into @mp@ if key does -- not exist in the map. If the key does exist, the function will -- insert @f new_value old_value@. -- -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")] -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx" insertWith :: (a -> a -> a) -> Key -> a -> WordMap a -> WordMap a insertWith combine = start where start !k v (WordMap Empty) = WordMap (NonEmpty k v Tip) start !k v (WordMap (NonEmpty min minV root)) | k > min = WordMap (NonEmpty min minV (goL k v (xor min k) min root)) | k < min = WordMap (NonEmpty k v (insertMinL (xor min k) min minV root)) | otherwise = WordMap (NonEmpty k (combine v minV) root) goL !k v !_ !_ Tip = Bin k v Tip Tip goL !k v !xorCache !min (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then Bin max maxV (goL k v xorCache min l) r else Bin max maxV l (goR k v xorCacheMax max r) | k > max = if xor min max < xorCacheMax then Bin k v (Bin max maxV l r) Tip else Bin k v l (insertMaxR xorCacheMax max maxV r) | otherwise = Bin max (combine v maxV) l r where xorCacheMax = xor k max goR !k v !_ !_ Tip = Bin k v Tip Tip goR !k v !xorCache !max (Bin min minV l r) | k > min = if xorCache < xorCacheMin then Bin min minV l (goR k v xorCache max r) else Bin min minV (goL k v xorCacheMin min l) r | k < min = if xor min max < xorCacheMin then Bin k v Tip (Bin min minV l r) else Bin k v (insertMinL xorCacheMin min minV l) r | otherwise = Bin min (combine v minV) l r where xorCacheMin = xor min k -- | /O(min(n,W))/. Insert with a combining function. -- @'insertWithKey' f key value mp@ -- will insert the pair (key, value) into @mp@ if key does -- not exist in the map. If the key does exist, the function will -- insert @f key new_value old_value@. -- -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")] -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx" insertWithKey :: (Key -> a -> a -> a) -> Key -> a -> WordMap a -> WordMap a insertWithKey f k = insertWith (f k) k -- | /O(min(n,W))/. The expression (@'insertLookupWithKey' f k x map@) -- is a pair where the first element is equal to (@'lookup' k map@) -- and the second element equal to (@'insertWithKey' f k x map@). -- -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")]) -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")]) -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx") -- -- This is how to define @insertLookup@ using @insertLookupWithKey@: -- -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")]) -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")]) insertLookupWithKey :: (Key -> a -> a -> a) -> Key -> a -> WordMap a -> (Maybe a, WordMap a) insertLookupWithKey combine !k !v = toPair . start where start (WordMap Empty) = Nothing :*: WordMap (NonEmpty k v Tip) start (WordMap (NonEmpty min minV root)) | k > min = let mv :*: root' = goL (xor min k) min root in mv :*: WordMap (NonEmpty min minV root') | k < min = Nothing :*: WordMap (NonEmpty k v (insertMinL (xor min k) min minV root)) | otherwise = Just minV :*: WordMap (NonEmpty k (combine k v minV) root) goL !_ _ Tip = Nothing :*: Bin k v Tip Tip goL !xorCache min (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then let mv :*: l' = goL xorCache min l in mv :*: Bin max maxV l' r else let mv :*: r' = goR xorCacheMax max r in mv :*: Bin max maxV l r' | k > max = if xor min max < xorCacheMax then Nothing :*: Bin k v (Bin max maxV l r) Tip else Nothing :*: Bin k v l (insertMaxR xorCacheMax max maxV r) | otherwise = Just maxV :*: Bin max (combine k v maxV) l r where xorCacheMax = xor k max goR !_ _ Tip = Nothing :*: Bin k v Tip Tip goR !xorCache max (Bin min minV l r) | k > min = if xorCache < xorCacheMin then let mv :*: r' = goR xorCache max r in mv :*: Bin min minV l r' else let mv :*: l' = goL xorCacheMin min l in mv :*: Bin min minV l' r | k < min = if xor min max < xorCacheMin then Nothing :*: Bin k v Tip (Bin min minV l r) else Nothing :*: Bin k v (insertMinL xorCacheMin min minV l) r | otherwise = Just minV :*: Bin min (combine k v minV) l r where xorCacheMin = xor min k -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not -- a member of the map, the original map is returned. -- -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > adjust ("new " ++) 7 empty == empty adjust :: (a -> a) -> Key -> WordMap a -> WordMap a adjust f k = k `seq` start where start (WordMap Empty) = WordMap Empty start m@(WordMap (NonEmpty min minV node)) | k > min = WordMap (NonEmpty min minV (goL (xor min k) min node)) | k < min = m | otherwise = WordMap (NonEmpty min (f minV) node) goL !_ _ Tip = Tip goL !xorCache min n@(Bin max maxV l r) | k < max = if xorCache < xorCacheMax then Bin max maxV (goL xorCache min l) r else Bin max maxV l (goR xorCacheMax max r) | k > max = n | otherwise = Bin max (f maxV) l r where xorCacheMax = xor k max goR !_ _ Tip = Tip goR !xorCache max n@(Bin min minV l r) | k > min = if xorCache < xorCacheMin then Bin min minV l (goR xorCache max r) else Bin min minV (goL xorCacheMin min l) r | k < min = n | otherwise = Bin min (f minV) l r where xorCacheMin = xor min k -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not -- a member of the map, the original map is returned. -- -- > let f key x = (show key) ++ ":new " ++ x -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > adjustWithKey f 7 empty == empty adjustWithKey :: (Key -> a -> a) -> Key -> WordMap a -> WordMap a adjustWithKey f k = adjust (f k) k -- | /O(min(n,W))/. The expression (@'update' f k map@) updates the value @x@ -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@. -- -- > let f x = if x == "a" then Just "new a" else Nothing -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" update :: (a -> Maybe a) -> Key -> WordMap a -> WordMap a update f k = k `seq` start where start (WordMap Empty) = WordMap Empty start m@(WordMap (NonEmpty min minV Tip)) | k == min = case f minV of Nothing -> WordMap Empty Just minV' -> WordMap (NonEmpty min minV' Tip) | otherwise = m start m@(WordMap (NonEmpty min minV root@(Bin max maxV l r))) | k < min = m | k == min = case f minV of Nothing -> let DR min' minV' root' = deleteMinL max maxV l r in WordMap (NonEmpty min' minV' root') Just minV' -> WordMap (NonEmpty min minV' root) | otherwise = WordMap (NonEmpty min minV (goL (xor min k) min root)) goL !_ _ Tip = Tip goL !xorCache min n@(Bin max maxV l r) | k < max = if xorCache < xorCacheMax then Bin max maxV (goL xorCache min l) r else Bin max maxV l (goR xorCacheMax max r) | k > max = n | otherwise = case f maxV of Nothing -> extractBinL l r Just maxV' -> Bin max maxV' l r where xorCacheMax = xor k max goR !_ _ Tip = Tip goR !xorCache max n@(Bin min minV l r) | k > min = if xorCache < xorCacheMin then Bin min minV l (goR xorCache max r) else Bin min minV (goL xorCacheMin min l) r | k < min = n | otherwise = case f minV of Nothing -> extractBinR l r Just minV' -> Bin min minV' l r where xorCacheMin = xor min k -- | /O(min(n,W))/. The expression (@'updateWithKey' f k map@) updates the value @x@ -- at @k@ (if it is in the map). If (@f k x@) is 'Nothing', the element is -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@. -- -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateWithKey :: (Key -> a -> Maybe a) -> Key -> WordMap a -> WordMap a updateWithKey f k = update (f k) k -- | /O(min(n,W))/. Lookup and update. -- The function returns original value, if it is updated. -- This is different behavior than 'Data.Map.updateLookupWithKey'. -- Returns the original key value if the map entry is deleted. -- -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:new a")]) -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")]) -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a") updateLookupWithKey :: (Key -> a -> Maybe a) -> Key -> WordMap a -> (Maybe a, WordMap a) updateLookupWithKey f k = k `seq` start where start (WordMap Empty) = (Nothing, WordMap Empty) start m@(WordMap (NonEmpty min minV Tip)) | k == min = case f min minV of Nothing -> (Just minV, WordMap Empty) Just minV' -> (Just minV, WordMap (NonEmpty min minV' Tip)) | otherwise = (Nothing, m) start m@(WordMap (NonEmpty min minV root@(Bin max maxV l r))) | k < min = (Nothing, m) | k == min = case f min minV of Nothing -> let DR min' minV' root' = deleteMinL max maxV l r in (Just minV, WordMap (NonEmpty min' minV' root')) Just minV' -> (Just minV, WordMap (NonEmpty min minV' root)) | otherwise = let (mv, root') = goL (xor min k) min root in (mv, WordMap (NonEmpty min minV root')) goL !_ _ Tip = (Nothing, Tip) goL !xorCache min n@(Bin max maxV l r) | k < max = if xorCache < xorCacheMax then let (mv, l') = goL xorCache min l in (mv, Bin max maxV l' r) else let (mv, r') = goR xorCacheMax max r in (mv, Bin max maxV l r') | k > max = (Nothing, n) | otherwise = case f max maxV of Nothing -> (Just maxV, extractBinL l r) Just maxV' -> (Just maxV, Bin max maxV' l r) where xorCacheMax = xor k max goR !_ _ Tip = (Nothing, Tip) goR !xorCache max n@(Bin min minV l r) | k > min = if xorCache < xorCacheMin then let (mv, r') = goR xorCache max r in (mv, Bin min minV l r') else let (mv, l') = goL xorCacheMin min l in (mv, Bin min minV l' r) | k < min = (Nothing, n) | otherwise = case f min minV of Nothing -> (Just minV, extractBinR l r) Just minV' -> (Just minV, Bin min minV' l r) where xorCacheMin = xor min k -- | /O(min(n,W))/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof. -- 'alter' can be used to insert, delete, or update a value in an 'IntMap'. -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@. alter :: (Maybe a -> Maybe a) -> Key -> WordMap a -> WordMap a alter f k m = case lookup k m of Nothing -> case f Nothing of Nothing -> m Just v -> insert k v m Just v -> case f (Just v) of Nothing -> delete k m Just v' -> insert k v' m -- | /O(log n)/. The expression (@'alterF' f k map@) alters the value @x@ at -- @k@, or absence thereof. 'alterF' can be used to inspect, insert, delete, -- or update a value in an 'IntMap'. In short : @'lookup' k <$> 'alterF' f k m = f -- ('lookup' k m)@. -- -- Example: -- -- @ -- interactiveAlter :: Word -> WordMap String -> IO (WordMap String) -- interactiveAlter k m = alterF f k m where -- f Nothing -> do -- putStrLn $ show k ++ -- " was not found in the map. Would you like to add it?" -- getUserResponse1 :: IO (Maybe String) -- f (Just old) -> do -- putStrLn "The key is currently bound to " ++ show old ++ -- ". Would you like to change or delete it?" -- getUserresponse2 :: IO (Maybe String) -- @ -- -- 'alterF' is the most general operation for working with an individual -- key that may or may not be in a given map. -- -- Note: 'alterF' is a flipped version of the 'at' combinator from -- 'Control.Lens.At'. -- -- @since 0.5.8 alterF :: Functor f => (Maybe a -> f (Maybe a)) -> Key -> WordMap a -> f (WordMap a) alterF f k m = case lookup k m of Nothing -> fmap (\ret -> case ret of Nothing -> m Just v -> insert k v m) (f Nothing) Just v -> fmap (\ret -> case ret of Nothing -> delete k m Just v' -> insert k v' m) (f (Just v)) -- | /O(n+m)/. The union with a combining function. -- -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")] unionWith :: (a -> a -> a) -> WordMap a -> WordMap a -> WordMap a unionWith f = unionWithKey (const f) -- | /O(n+m)/. The union with a combining function. -- -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")] unionWithKey :: (Key -> a -> a -> a) -> WordMap a -> WordMap a -> WordMap a unionWithKey combine = start where start (WordMap Empty) m2 = m2 start m1 (WordMap Empty) = m1 start (WordMap (NonEmpty min1 minV1 root1)) (WordMap (NonEmpty min2 minV2 root2)) | min1 < min2 = WordMap (NonEmpty min1 minV1 (goL2 minV2 min1 root1 min2 root2)) | min1 > min2 = WordMap (NonEmpty min2 minV2 (goL1 minV1 min1 root1 min2 root2)) | otherwise = WordMap (NonEmpty min1 (combine min1 minV1 minV2) (goLFused min1 root1 root2)) -- we choose min1 arbitrarily, as min1 == min2 -- TODO: Should I bind 'minV1' in a closure? It never changes. -- TODO: Should I cache @xor min1 min2@? goL1 minV1 min1 Tip !_ Tip = Bin min1 minV1 Tip Tip goL1 minV1 min1 Tip min2 n2 = goInsertL1 min1 minV1 (xor min1 min2) min2 n2 goL1 minV1 min1 n1 min2 Tip = insertMinL (xor min1 min2) min1 minV1 n1 goL1 minV1 min1 n1@(Bin max1 maxV1 l1 r1) min2 n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 max2 `ltMSB` xor min1 min2 -> disjoint -- we choose min1 and min2 arbitrarily - we just need something from tree 1 and something from tree 2 | xor min2 min1 < xor min1 max2 -> Bin max2 maxV2 (goL1 minV1 min1 n1 min2 l2) r2 -- we choose min1 arbitrarily - we just need something from tree 1 | max1 > max2 -> Bin max1 maxV1 l2 (goR2 maxV2 max1 (Bin min1 minV1 l1 r1) max2 r2) | max1 < max2 -> Bin max2 maxV2 l2 (goR1 maxV1 max1 (Bin min1 minV1 l1 r1) max2 r2) | otherwise -> Bin max1 (combine max1 maxV1 maxV2) l2 (goRFused max1 (Bin min1 minV1 l1 r1) r2) -- we choose max1 arbitrarily, as max1 == max2 EQ | max2 < min1 -> disjoint | max1 > max2 -> Bin max1 maxV1 (goL1 minV1 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | max1 < max2 -> Bin max2 maxV2 (goL1 minV1 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> Bin max1 (combine max1 maxV1 maxV2) (goL1 minV1 min1 l1 min2 l2) (goRFused max1 r1 r2) -- we choose max1 arbitrarily, as max1 == max2 GT | xor min1 max1 `ltMSB` xor min1 min2 -> disjoint -- we choose min1 and min2 arbitrarily - we just need something from tree 1 and something from tree 2 | otherwise -> Bin max1 maxV1 (goL1 minV1 min1 l1 min2 n2) r1 where disjoint = Bin max1 maxV1 n2 (Bin min1 minV1 l1 r1) -- TODO: Should I bind 'minV2' in a closure? It never changes. -- TODO: Should I cache @xor min1 min2@? goL2 minV2 !_ Tip min2 Tip = Bin min2 minV2 Tip Tip goL2 minV2 min1 Tip min2 n2 = insertMinL (xor min1 min2) min2 minV2 n2 goL2 minV2 min1 n1 min2 Tip = goInsertL2 min2 minV2 (xor min1 min2) min1 n1 goL2 minV2 min1 n1@(Bin max1 maxV1 l1 r1) min2 n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 max2 `ltMSB` xor min1 min2 -> disjoint -- we choose min1 and min2 arbitrarily - we just need something from tree 1 and something from tree 2 | otherwise -> Bin max2 maxV2 (goL2 minV2 min1 n1 min2 l2) r2 EQ | max1 < min2 -> disjoint | max1 > max2 -> Bin max1 maxV1 (goL2 minV2 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | max1 < max2 -> Bin max2 maxV2 (goL2 minV2 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> Bin max1 (combine max1 maxV1 maxV2) (goL2 minV2 min1 l1 min2 l2) (goRFused max1 r1 r2) -- we choose max1 arbitrarily, as max1 == max2 GT | xor min1 max1 `ltMSB` xor min1 min2 -> disjoint -- we choose min1 and min2 arbitrarily - we just need something from tree 1 and something from tree 2 | xor min1 min2 < xor min2 max1 -> Bin max1 maxV1 (goL2 minV2 min1 l1 min2 n2) r1 -- we choose min2 arbitrarily - we just need something from tree 2 | max1 > max2 -> Bin max1 maxV1 l1 (goR2 maxV2 max1 r1 max2 (Bin min2 minV2 l2 r2)) | max1 < max2 -> Bin max2 maxV2 l1 (goR1 maxV1 max1 r1 max2 (Bin min2 minV2 l2 r2)) | otherwise -> Bin max1 (combine max1 maxV1 maxV2) l1 (goRFused max1 r1 (Bin min2 minV2 l2 r2)) -- we choose max1 arbitrarily, as max1 == max2 where disjoint = Bin max2 maxV2 n1 (Bin min2 minV2 l2 r2) -- TODO: Should I bind 'min' in a closure? It never changes. -- TODO: Should I use an xor cache here? -- 'goLFused' is called instead of 'goL' if the minimums of the two trees are the same -- Note that because of this property, the trees cannot be disjoint, so we can skip most of the checks in 'goL' goLFused !_ Tip n2 = n2 goLFused !_ n1 Tip = n1 goLFused min n1@(Bin max1 maxV1 l1 r1) n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min max1) (xor min max2) of LT -> Bin max2 maxV2 (goLFused min n1 l2) r2 EQ | max1 > max2 -> Bin max1 maxV1 (goLFused min l1 l2) (goR2 maxV2 max1 r1 max2 r2) | max1 < max2 -> Bin max2 maxV2 (goLFused min l1 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> Bin max1 (combine max1 maxV1 maxV2) (goLFused min l1 l2) (goRFused max1 r1 r2) -- we choose max1 arbitrarily, as max1 == max2 GT -> Bin max1 maxV1 (goLFused min l1 n2) r1 -- TODO: Should I bind 'maxV1' in a closure? It never changes. -- TODO: Should I cache @xor max1 max2@? goR1 maxV1 max1 Tip !_ Tip = Bin max1 maxV1 Tip Tip goR1 maxV1 max1 Tip max2 n2 = goInsertR1 max1 maxV1 (xor max1 max2) max2 n2 goR1 maxV1 max1 n1 max2 Tip = insertMaxR (xor max1 max2) max1 maxV1 n1 goR1 maxV1 max1 n1@(Bin min1 minV1 l1 r1) max2 n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 max2 `ltMSB` xor max1 max2 -> disjoint -- we choose max1 and max2 arbitrarily - we just need something from tree 1 and something from tree 2 | xor min2 max1 > xor max1 max2 -> Bin min2 minV2 l2 (goR1 maxV1 max1 n1 max2 r2) -- we choose max1 arbitrarily - we just need something from tree 1 | min1 < min2 -> Bin min1 minV1 (goL2 minV2 min1 (Bin max1 maxV1 l1 r1) min2 l2) r2 | min1 > min2 -> Bin min2 minV2 (goL1 minV1 min1 (Bin max1 maxV1 l1 r1) min2 l2) r2 | otherwise -> Bin min1 (combine min1 minV1 minV2) (goLFused min1 (Bin max1 maxV1 l1 r1) l2) r2 -- we choose min1 arbitrarily, as min1 == min2 EQ | max1 < min2 -> disjoint | min1 < min2 -> Bin min1 minV1 (goL2 minV2 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | min1 > min2 -> Bin min2 minV2 (goL1 minV1 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> Bin min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2) (goR1 maxV1 max1 r1 max2 r2) -- we choose min1 arbitrarily, as min1 == min2 GT | xor min1 max1 `ltMSB` xor max1 max2 -> disjoint -- we choose max1 and max2 arbitrarily - we just need something from tree 1 and something from tree 2 | otherwise -> Bin min1 minV1 l1 (goR1 maxV1 max1 r1 max2 n2) where disjoint = Bin min1 minV1 (Bin max1 maxV1 l1 r1) n2 -- TODO: Should I bind 'minV2' in a closure? It never changes. -- TODO: Should I cache @xor min1 min2@? goR2 maxV2 !_ Tip max2 Tip = Bin max2 maxV2 Tip Tip goR2 maxV2 max1 Tip max2 n2 = insertMaxR (xor max1 max2) max2 maxV2 n2 goR2 maxV2 max1 n1 max2 Tip = goInsertR2 max2 maxV2 (xor max1 max2) max1 n1 goR2 maxV2 max1 n1@(Bin min1 minV1 l1 r1) max2 n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 max2 `ltMSB` xor max1 max2 -> disjoint -- we choose max1 and max2 arbitrarily - we just need something from tree 1 and something from tree 2 | otherwise -> Bin min2 minV2 l2 (goR2 maxV2 max1 n1 max2 r2) EQ | max2 < min1 -> disjoint | min1 < min2 -> Bin min1 minV1 (goL2 minV2 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | min1 > min2 -> Bin min2 minV2 (goL1 minV1 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | otherwise -> Bin min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2) (goR2 maxV2 max1 r1 max2 r2) -- we choose min1 arbitrarily, as min1 == min2 GT | xor min1 max1 `ltMSB` xor max1 max2 -> disjoint -- we choose max1 and max2 arbitrarily - we just need something from tree 1 and something from tree 2 | xor min1 max2 > xor max2 max1 -> Bin min1 minV1 l1 (goR2 maxV2 max1 r1 max2 n2) -- we choose max2 arbitrarily - we just need something from tree 2 | min1 < min2 -> Bin min1 minV1 (goL2 minV2 min1 l1 min2 (Bin max2 maxV2 l2 r2)) r1 | min1 > min2 -> Bin min2 minV2 (goL1 minV1 min1 l1 min2 (Bin max2 maxV2 l2 r2)) r1 | otherwise -> Bin min1 (combine min1 minV1 minV2) (goLFused min1 l1 (Bin max2 maxV2 l2 r2)) r1 -- we choose min1 arbitrarily, as min1 == min2 where disjoint = Bin min2 minV2 (Bin max2 maxV2 l2 r2) n1 -- TODO: Should I bind 'max' in a closure? It never changes. -- TODO: Should I use an xor cache here? -- 'goRFused' is called instead of 'goR' if the minimums of the two trees are the same -- Note that because of this property, the trees cannot be disjoint, so we can skip most of the checks in 'goR' goRFused !_ Tip n2 = n2 goRFused !_ n1 Tip = n1 goRFused max n1@(Bin min1 minV1 l1 r1) n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max) (xor min2 max) of LT -> Bin min2 minV2 l2 (goRFused max n1 r2) EQ | min1 < min2 -> Bin min1 minV1 (goL2 minV2 min1 l1 min2 l2) (goRFused max r1 r2) | min1 > min2 -> Bin min2 minV2 (goL1 minV1 min1 l1 min2 l2) (goRFused max r1 r2) | otherwise -> Bin min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2) (goRFused max r1 r2) -- we choose min1 arbitrarily, as min1 == min2 GT -> Bin min1 minV1 l1 (goRFused max r1 n2) goInsertL1 k v !_ _ Tip = Bin k v Tip Tip goInsertL1 k v !xorCache min (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then Bin max maxV (goInsertL1 k v xorCache min l) r else Bin max maxV l (goInsertR1 k v xorCacheMax max r) | k > max = if xor min max < xorCacheMax then Bin k v (Bin max maxV l r) Tip else Bin k v l (insertMaxR xorCacheMax max maxV r) | otherwise = Bin max (combine k v maxV) l r where xorCacheMax = xor k max goInsertR1 k v !_ _ Tip = Bin k v Tip Tip goInsertR1 k v !xorCache max (Bin min minV l r) | k > min = if xorCache < xorCacheMin then Bin min minV l (goInsertR1 k v xorCache max r) else Bin min minV (goInsertL1 k v xorCacheMin min l) r | k < min = if xor min max < xorCacheMin then Bin k v Tip (Bin min minV l r) else Bin k v (insertMinL xorCacheMin min minV l) r | otherwise = Bin min (combine k v minV) l r where xorCacheMin = xor min k goInsertL2 k v !_ _ Tip = Bin k v Tip Tip goInsertL2 k v !xorCache min (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then Bin max maxV (goInsertL2 k v xorCache min l) r else Bin max maxV l (goInsertR2 k v xorCacheMax max r) | k > max = if xor min max < xorCacheMax then Bin k v (Bin max maxV l r) Tip else Bin k v l (insertMaxR xorCacheMax max maxV r) | otherwise = Bin max (combine k maxV v) l r where xorCacheMax = xor k max goInsertR2 k v !_ _ Tip = Bin k v Tip Tip goInsertR2 k v !xorCache max (Bin min minV l r) | k > min = if xorCache < xorCacheMin then Bin min minV l (goInsertR2 k v xorCache max r) else Bin min minV (goInsertL2 k v xorCacheMin min l) r | k < min = if xor min max < xorCacheMin then Bin k v Tip (Bin min minV l r) else Bin k v (insertMinL xorCacheMin min minV l) r | otherwise = Bin min (combine k minV v) l r where xorCacheMin = xor min k -- | The union of a list of maps, with a combining operation. -- -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")] unionsWith :: (a -> a -> a) -> [WordMap a] -> WordMap a unionsWith f = Data.List.foldl' (unionWith f) empty -- | /O(n+m)/. Difference with a combining function. -- -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")]) -- > == singleton 3 "b:B" differenceWith :: (a -> b -> Maybe a) -> WordMap a -> WordMap b -> WordMap a differenceWith f = differenceWithKey (const f) -- | /O(n+m)/. Difference with a combining function. When two equal keys are -- encountered, the combining function is applied to the key and both values. -- If it returns 'Nothing', the element is discarded (proper set difference). -- If it returns (@'Just' y@), the element is updated with a new value @y@. -- -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")]) -- > == singleton 3 "3:b|B" differenceWithKey :: (Key -> a -> b -> Maybe a) -> WordMap a -> WordMap b -> WordMap a differenceWithKey combine = start where start (WordMap Empty) !_ = WordMap Empty start !m (WordMap Empty) = m start (WordMap (NonEmpty min1 minV1 root1)) (WordMap (NonEmpty min2 minV2 root2)) | min1 < min2 = WordMap (NonEmpty min1 minV1 (goL2 min1 root1 min2 root2)) | min1 > min2 = WordMap (goL1 minV1 min1 root1 min2 root2) | otherwise = case combine min1 minV1 minV2 of Nothing -> WordMap (goLFused min1 root1 root2) Just minV1' -> WordMap (NonEmpty min1 minV1' (goLFusedKeep min1 root1 root2)) goL1 minV1 min1 Tip min2 n2 = goLookupL min1 minV1 (xor min1 min2) n2 goL1 minV1 min1 n1 _ Tip = NonEmpty min1 minV1 n1 goL1 minV1 min1 n1@(Bin _ _ _ _) _ (Bin max2 _ _ _) | min1 > max2 = NonEmpty min1 minV1 n1 goL1 minV1 min1 n1@(Bin max1 maxV1 l1 r1) min2 n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 min1 < xor min1 max2 -> goL1 minV1 min1 n1 min2 l2 -- min1 is arbitrary here - we just need something from tree 1 | max1 > max2 -> r2lMap $ NonEmpty max1 maxV1 (goR2 max1 (Bin min1 minV1 l1 r1) max2 r2) | max1 < max2 -> r2lMap $ goR1 maxV1 max1 (Bin min1 minV1 l1 r1) max2 r2 | otherwise -> case combine max1 maxV1 maxV2 of Nothing -> r2lMap $ goRFused max1 (Bin min1 minV1 l1 r1) r2 Just maxV1' -> r2lMap $ NonEmpty max1 maxV1' (goRFusedKeep max1 (Bin min1 minV1 l1 r1) r2) EQ | max1 > max2 -> binL (goL1 minV1 min1 l1 min2 l2) (NonEmpty max1 maxV1 (goR2 max1 r1 max2 r2)) | max1 < max2 -> binL (goL1 minV1 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> case combine max1 maxV1 maxV2 of Nothing -> binL (goL1 minV1 min1 l1 min2 l2) (goRFused max1 r1 r2) Just maxV1' -> binL (goL1 minV1 min1 l1 min2 l2) (NonEmpty max1 maxV1' (goRFusedKeep max1 r1 r2)) GT -> binL (goL1 minV1 min1 l1 min2 n2) (NonEmpty max1 maxV1 r1) goL2 !_ Tip !_ !_ = Tip goL2 min1 n1 min2 Tip = deleteL min2 (xor min1 min2) n1 goL2 _ n1@(Bin max1 _ _ _) min2 (Bin _ _ _ _) | min2 > max1 = n1 goL2 min1 n1@(Bin max1 maxV1 l1 r1) min2 n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT -> goL2 min1 n1 min2 l2 EQ | max1 > max2 -> Bin max1 maxV1 (goL2 min1 l1 min2 l2) (goR2 max1 r1 max2 r2) | max1 < max2 -> case goR1 maxV1 max1 r1 max2 r2 of Empty -> goL2 min1 l1 min2 l2 NonEmpty max' maxV' r' -> Bin max' maxV' (goL2 min1 l1 min2 l2) r' | otherwise -> case combine max1 maxV1 maxV2 of Nothing -> case goRFused max1 r1 r2 of Empty -> goL2 min1 l1 min2 l2 NonEmpty max' maxV' r' -> Bin max' maxV' (goL2 min1 l1 min2 l2) r' Just maxV1' -> Bin max1 maxV1' (goL2 min1 l1 min2 l2) (goRFusedKeep max1 r1 r2) GT | xor min1 min2 < xor min2 max1 -> Bin max1 maxV1 (goL2 min1 l1 min2 n2) r1 -- min2 is arbitrary here - we just need something from tree 2 | max1 > max2 -> Bin max1 maxV1 l1 (goR2 max1 r1 max2 (Bin min2 dummyV l2 r2)) | max1 < max2 -> case goR1 maxV1 max1 r1 max2 (Bin min2 dummyV l2 r2) of Empty -> l1 NonEmpty max' maxV' r' -> Bin max' maxV' l1 r' | otherwise -> case combine max1 maxV1 maxV2 of Nothing -> case goRFused max1 r1 (Bin min2 dummyV l2 r2) of Empty -> l1 NonEmpty max' maxV' r' -> Bin max' maxV' l1 r' Just maxV1' -> Bin max1 maxV1' l1 (goRFusedKeep max1 r1 (Bin min2 dummyV l2 r2)) goLFused min = loop where loop Tip !_ = Empty loop (Bin max1 maxV1 l1 r1) Tip = case deleteMinL max1 maxV1 l1 r1 of DR min' minV' n' -> NonEmpty min' minV' n' loop n1@(Bin max1 maxV1 l1 r1) n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min max1) (xor min max2) of LT -> loop n1 l2 EQ | max1 > max2 -> binL (loop l1 l2) (NonEmpty max1 maxV1 (goR2 max1 r1 max2 r2)) | max1 < max2 -> binL (loop l1 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> case combine max1 maxV1 maxV2 of Nothing -> binL (loop l1 l2) (goRFused max1 r1 r2) -- we choose max1 arbitrarily, as max1 == max2 Just maxV1' -> binL (loop l1 l2) (NonEmpty max1 maxV1' (goRFusedKeep max1 r1 r2)) GT -> binL (loop l1 n2) (NonEmpty max1 maxV1 r1) goLFusedKeep min = loop where loop n1 Tip = n1 loop Tip !_ = Tip loop n1@(Bin max1 maxV1 l1 r1) n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min max1) (xor min max2) of LT -> loop n1 l2 EQ | max1 > max2 -> Bin max1 maxV1 (loop l1 l2) (goR2 max1 r1 max2 r2) | max1 < max2 -> case goR1 maxV1 max1 r1 max2 r2 of Empty -> loop l1 l2 NonEmpty max' maxV' r' -> Bin max' maxV' (loop l1 l2) r' | otherwise -> case combine max1 maxV1 maxV2 of Nothing -> case goRFused max1 r1 r2 of -- we choose max1 arbitrarily, as max1 == max2 Empty -> loop l1 l2 NonEmpty max' maxV' r' -> Bin max' maxV' (loop l1 l2) r' Just maxV1' -> Bin max1 maxV1' (loop l1 l2) (goRFusedKeep max1 r1 r2) GT -> Bin max1 maxV1 (loop l1 n2) r1 goR1 maxV1 max1 Tip max2 n2 = goLookupR max1 maxV1 (xor max1 max2) n2 goR1 maxV1 max1 n1 _ Tip = NonEmpty max1 maxV1 n1 goR1 maxV1 max1 n1@(Bin _ _ _ _) _ (Bin min2 _ _ _) | min2 > max1 = NonEmpty max1 maxV1 n1 goR1 maxV1 max1 n1@(Bin min1 minV1 l1 r1) max2 n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 max1 > xor max1 max2 -> goR1 maxV1 max1 n1 max2 r2 -- max1 is arbitrary here - we just need something from tree 1 | min1 < min2 -> l2rMap $ NonEmpty min1 minV1 (goL2 min1 (Bin max1 maxV1 l1 r1) min2 l2) | min1 > min2 -> l2rMap $ goL1 minV1 min1 (Bin max1 maxV1 l1 r1) min2 l2 | otherwise -> case combine min1 minV1 minV2 of Nothing -> l2rMap $ goLFused min1 (Bin max1 maxV1 l1 r1) l2 Just minV1' -> l2rMap $ NonEmpty min1 minV1' (goLFusedKeep min1 (Bin max1 maxV1 l1 r1) l2) EQ | min1 < min2 -> binR (NonEmpty min1 minV1 (goL2 min1 l1 min2 l2)) (goR1 maxV1 max1 r1 max2 r2) | min1 > min2 -> binR (goL1 minV1 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> case combine min1 minV1 minV2 of Nothing -> binR (goLFused min1 l1 l2) (goR1 maxV1 max1 r1 max2 r2) Just minV1' -> binR (NonEmpty min1 minV1' (goLFusedKeep min1 l1 l2)) (goR1 maxV1 max1 r1 max2 r2) GT -> binR (NonEmpty min1 minV1 l1) (goR1 maxV1 max1 r1 max2 n2) goR2 !_ Tip !_ !_ = Tip goR2 max1 n1 max2 Tip = deleteR max2 (xor max1 max2) n1 goR2 _ n1@(Bin min1 _ _ _) max2 (Bin _ _ _ _) | min1 > max2 = n1 goR2 max1 n1@(Bin min1 minV1 l1 r1) max2 n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT -> goR2 max1 n1 max2 r2 EQ | min1 < min2 -> Bin min1 minV1 (goL2 min1 l1 min2 l2) (goR2 max1 r1 max2 r2) | min1 > min2 -> case goL1 minV1 min1 l1 min2 l2 of Empty -> goR2 max1 r1 max2 r2 NonEmpty min' minV' l' -> Bin min' minV' l' (goR2 max1 r1 max2 r2) | otherwise -> case combine min1 minV1 minV2 of Nothing -> case goLFused min1 l1 l2 of Empty -> goR2 max1 r1 max2 r2 NonEmpty min' minV' l' -> Bin min' minV' l' (goR2 max1 r1 max2 r2) Just minV1' -> Bin min1 minV1' (goLFusedKeep min1 l1 l2) (goR2 max1 r1 max2 r2) GT | xor min1 max2 > xor max2 max1 -> Bin min1 minV1 l1 (goR2 max1 r1 max2 n2) -- max2 is arbitrary here - we just need something from tree 2 | min1 < min2 -> Bin min1 minV1 (goL2 min1 l1 min2 (Bin max2 dummyV l2 r2)) r1 | min1 > min2 -> case goL1 minV1 min1 l1 min2 (Bin max2 dummyV l2 r2) of Empty -> r1 NonEmpty min' minV' l' -> Bin min' minV' l' r1 | otherwise -> case combine min1 minV1 minV2 of Nothing -> case goLFused min1 l1 (Bin max2 dummyV l2 r2) of Empty -> r1 NonEmpty min' minV' l' -> Bin min' minV' l' r1 Just minV1' -> Bin min1 minV1' (goLFusedKeep min1 l1 (Bin max2 dummyV l2 r2)) r1 goRFused max = loop where loop Tip !_ = Empty loop (Bin min1 minV1 l1 r1) Tip = case deleteMaxR min1 minV1 l1 r1 of DR max' maxV' n' -> NonEmpty max' maxV' n' loop n1@(Bin min1 minV1 l1 r1) n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max) (xor min2 max) of LT -> loop n1 r2 EQ | min1 < min2 -> binR (NonEmpty min1 minV1 (goL2 min1 l1 min2 l2)) (loop r1 r2) | min1 > min2 -> binR (goL1 minV1 min1 l1 min2 l2) (loop r1 r2) | otherwise -> case combine min1 minV1 minV2 of Nothing -> binR (goLFused min1 l1 l2) (loop r1 r2) -- we choose min1 arbitrarily, as min1 == min2 Just minV1' -> binR (NonEmpty min1 minV1' (goLFusedKeep min1 l1 l2)) (loop r1 r2) GT -> binR (NonEmpty min1 minV1 l1) (loop r1 n2) goRFusedKeep max = loop where loop n1 Tip = n1 loop Tip !_ = Tip loop n1@(Bin min1 minV1 l1 r1) n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max) (xor min2 max) of LT -> loop n1 r2 EQ | min1 < min2 -> Bin min1 minV1 (goL2 min1 l1 min2 l2) (loop r1 r2) | min1 > min2 -> case goL1 minV1 min1 l1 min2 l2 of Empty -> loop r1 r2 NonEmpty min' minV' l' -> Bin min' minV' l' (loop r1 r2) | otherwise -> case combine min1 minV1 minV2 of -- we choose min1 arbitrarily, as min1 == min2 Nothing -> case goLFused min1 l1 l2 of Empty -> loop r1 r2 NonEmpty min' minV' l' -> Bin min' minV' l' (loop r1 r2) Just minV1' -> Bin min1 minV1' (goLFusedKeep min1 l1 l2) (loop r1 r2) GT -> Bin min1 minV1 l1 (loop r1 n2) goLookupL k v !_ Tip = NonEmpty k v Tip goLookupL k v !xorCache (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then goLookupL k v xorCache l else goLookupR k v xorCacheMax r | k > max = NonEmpty k v Tip | otherwise = case combine k v maxV of Nothing -> Empty Just v' -> NonEmpty k v' Tip where xorCacheMax = xor k max goLookupR k v !_ Tip = NonEmpty k v Tip goLookupR k v !xorCache (Bin min minV l r) | k > min = if xorCache < xorCacheMin then goLookupR k v xorCache r else goLookupL k v xorCacheMin l | k < min = NonEmpty k v Tip | otherwise = case combine k v minV of Nothing -> Empty Just v' -> NonEmpty k v' Tip where xorCacheMin = xor min k dummyV = error "impossible" -- | /O(n+m)/. The intersection with a combining function. -- -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA" intersectionWith :: (a -> b -> c) -> WordMap a -> WordMap b -> WordMap c intersectionWith f = intersectionWithKey (const f) -- | /O(n+m)/. The intersection with a combining function. -- -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A" intersectionWithKey :: (Key -> a -> b -> c) -> WordMap a -> WordMap b -> WordMap c intersectionWithKey combine = start where start (WordMap Empty) !_ = WordMap Empty start !_ (WordMap Empty) = WordMap Empty start (WordMap (NonEmpty min1 minV1 root1)) (WordMap (NonEmpty min2 minV2 root2)) | min1 < min2 = WordMap (goL2 minV2 min1 root1 min2 root2) | min1 > min2 = WordMap (goL1 minV1 min1 root1 min2 root2) | otherwise = WordMap (NonEmpty min1 (combine min1 minV1 minV2) (goLFused min1 root1 root2)) -- we choose min1 arbitrarily, as min1 == min2 -- TODO: This scheme might produce lots of unnecessary l2r and r2l calls. This should be rectified. goL1 _ !_ !_ !_ Tip = Empty goL1 minV1 min1 Tip min2 n2 = goLookupL1 min1 minV1 (xor min1 min2) n2 goL1 _ min1 (Bin _ _ _ _) _ (Bin max2 _ _ _) | min1 > max2 = Empty goL1 minV1 min1 n1@(Bin max1 maxV1 l1 r1) min2 n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 min1 < xor min1 max2 -> goL1 minV1 min1 n1 min2 l2 -- min1 is arbitrary here - we just need something from tree 1 | max1 > max2 -> r2lMap $ goR2 maxV2 max1 (Bin min1 minV1 l1 r1) max2 r2 | max1 < max2 -> r2lMap $ goR1 maxV1 max1 (Bin min1 minV1 l1 r1) max2 r2 | otherwise -> r2lMap $ NonEmpty max1 (combine max1 maxV1 maxV2) (goRFused max1 (Bin min1 minV1 l1 r1) r2) EQ | max1 > max2 -> binL (goL1 minV1 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | max1 < max2 -> binL (goL1 minV1 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> case goL1 minV1 min1 l1 min2 l2 of Empty -> r2lMap (NonEmpty max1 (combine max1 maxV1 maxV2) (goRFused max1 r1 r2)) NonEmpty min' minV' l' -> NonEmpty min' minV' (Bin max1 (combine max1 maxV1 maxV2) l' (goRFused max1 r1 r2)) GT -> goL1 minV1 min1 l1 min2 n2 goL2 _ !_ Tip !_ !_ = Empty goL2 minV2 min1 n1 min2 Tip = goLookupL2 min2 minV2 (xor min1 min2) n1 goL2 _ _ (Bin max1 _ _ _) min2 (Bin _ _ _ _) | min2 > max1 = Empty goL2 minV2 min1 n1@(Bin max1 maxV1 l1 r1) min2 n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT -> goL2 minV2 min1 n1 min2 l2 EQ | max1 > max2 -> binL (goL2 minV2 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | max1 < max2 -> binL (goL2 minV2 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> case goL2 minV2 min1 l1 min2 l2 of Empty -> r2lMap (NonEmpty max1 (combine max1 maxV1 maxV2) (goRFused max1 r1 r2)) NonEmpty min' minV' l' -> NonEmpty min' minV' (Bin max1 (combine max1 maxV1 maxV2) l' (goRFused max1 r1 r2)) GT | xor min1 min2 < xor min2 max1 -> goL2 minV2 min1 l1 min2 n2 -- min2 is arbitrary here - we just need something from tree 2 | max1 > max2 -> r2lMap $ goR2 maxV2 max1 r1 max2 (Bin min2 minV2 l2 r2) | max1 < max2 -> r2lMap $ goR1 maxV1 max1 r1 max2 (Bin min2 minV2 l2 r2) | otherwise -> r2lMap $ NonEmpty max1 (combine max1 maxV1 maxV2) (goRFused max1 r1 (Bin min2 minV2 l2 r2)) goLFused min = loop where loop Tip !_ = Tip loop !_ Tip = Tip loop n1@(Bin max1 maxV1 l1 r1) n2@(Bin max2 maxV2 l2 r2) = case compareMSB (xor min max1) (xor min max2) of LT -> loop n1 l2 EQ | max1 > max2 -> case goR2 maxV2 max1 r1 max2 r2 of Empty -> loop l1 l2 NonEmpty max' maxV' r' -> Bin max' maxV' (loop l1 l2) r' | max1 < max2 -> case goR1 maxV1 max1 r1 max2 r2 of Empty -> loop l1 l2 NonEmpty max' maxV' r' -> Bin max' maxV' (loop l1 l2) r' | otherwise -> Bin max1 (combine max1 maxV1 maxV2) (loop l1 l2) (goRFused max1 r1 r2) -- we choose max1 arbitrarily, as max1 == max2 GT -> loop l1 n2 goR1 _ !_ !_ !_ Tip = Empty goR1 maxV1 max1 Tip max2 n2 = goLookupR1 max1 maxV1 (xor max1 max2) n2 goR1 _ max1 (Bin _ _ _ _) _ (Bin min2 _ _ _) | min2 > max1 = Empty goR1 maxV1 max1 n1@(Bin min1 minV1 l1 r1) max2 n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT | xor min2 max1 > xor max1 max2 -> goR1 maxV1 max1 n1 max2 r2 -- max1 is arbitrary here - we just need something from tree 1 | min1 < min2 -> l2rMap $ goL2 minV2 min1 (Bin max1 maxV1 l1 r1) min2 l2 | min1 > min2 -> l2rMap $ goL1 minV1 min1 (Bin max1 maxV1 l1 r1) min2 l2 | otherwise -> l2rMap $ NonEmpty min1 (combine min1 minV1 minV2) (goLFused min1 (Bin max1 maxV1 l1 r1) l2) EQ | min1 < min2 -> binR (goL2 minV2 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | min1 > min2 -> binR (goL1 minV1 min1 l1 min2 l2) (goR1 maxV1 max1 r1 max2 r2) | otherwise -> case goR1 maxV1 max1 r1 max2 r2 of Empty -> l2rMap (NonEmpty min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2)) NonEmpty max' maxV' r' -> NonEmpty max' maxV' (Bin min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2) r') GT -> goR1 maxV1 max1 r1 max2 n2 goR2 _ !_ Tip !_ !_ = Empty goR2 maxV2 max1 n1 max2 Tip = goLookupR2 max2 maxV2 (xor max1 max2) n1 goR2 _ _ (Bin min1 _ _ _) max2 (Bin _ _ _ _) | min1 > max2 = Empty goR2 maxV2 max1 n1@(Bin min1 minV1 l1 r1) max2 n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max1) (xor min2 max2) of LT -> goR2 maxV2 max1 n1 max2 r2 EQ | min1 < min2 -> binR (goL2 minV2 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | min1 > min2 -> binR (goL1 minV1 min1 l1 min2 l2) (goR2 maxV2 max1 r1 max2 r2) | otherwise -> case goR2 maxV2 max1 r1 max2 r2 of Empty -> l2rMap (NonEmpty min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2)) NonEmpty max' maxV' r' -> NonEmpty max' maxV' (Bin min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2) r') GT | xor min1 max2 > xor max2 max1 -> goR2 maxV2 max1 r1 max2 n2 -- max2 is arbitrary here - we just need something from tree 2 | min1 < min2 -> l2rMap $ goL2 minV2 min1 l1 min2 (Bin max2 maxV2 l2 r2) | min1 > min2 -> l2rMap $ goL1 minV1 min1 l1 min2 (Bin max2 maxV2 l2 r2) | otherwise -> l2rMap $ NonEmpty min1 (combine min1 minV1 minV2) (goLFused min1 l1 (Bin max2 maxV2 l2 r2)) goRFused max = loop where loop Tip !_ = Tip loop !_ Tip = Tip loop n1@(Bin min1 minV1 l1 r1) n2@(Bin min2 minV2 l2 r2) = case compareMSB (xor min1 max) (xor min2 max) of LT -> loop n1 r2 EQ | min1 < min2 -> case goL2 minV2 min1 l1 min2 l2 of Empty -> loop r1 r2 NonEmpty min' minV' l' -> Bin min' minV' l' (loop r1 r2) | min1 > min2 -> case goL1 minV1 min1 l1 min2 l2 of Empty -> loop r1 r2 NonEmpty min' minV' l' -> Bin min' minV' l' (loop r1 r2) | otherwise -> Bin min1 (combine min1 minV1 minV2) (goLFused min1 l1 l2) (loop r1 r2) -- we choose max1 arbitrarily, as max1 == max2 GT -> loop r1 n2 goLookupL1 !_ _ !_ Tip = Empty goLookupL1 k v !xorCache (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then goLookupL1 k v xorCache l else goLookupR1 k v xorCacheMax r | k > max = Empty | otherwise = NonEmpty k (combine k v maxV) Tip where xorCacheMax = xor k max goLookupR1 !_ _ !_ Tip = Empty goLookupR1 k v !xorCache (Bin min minV l r) | k > min = if xorCache < xorCacheMin then goLookupR1 k v xorCache r else goLookupL1 k v xorCacheMin l | k < min = Empty | otherwise = NonEmpty k (combine k v minV) Tip where xorCacheMin = xor min k goLookupL2 !_ _ !_ Tip = Empty goLookupL2 k v !xorCache (Bin max maxV l r) | k < max = if xorCache < xorCacheMax then goLookupL2 k v xorCache l else goLookupR2 k v xorCacheMax r | k > max = Empty | otherwise = NonEmpty k (combine k maxV v) Tip where xorCacheMax = xor k max goLookupR2 !_ _ !_ Tip = Empty goLookupR2 k v !xorCache (Bin min minV l r) | k > min = if xorCache < xorCacheMin then goLookupR2 k v xorCache r else goLookupL2 k v xorCacheMin l | k < min = Empty | otherwise = NonEmpty k (combine k minV v) Tip where xorCacheMin = xor min k -- | /O(n)/. Map a function over all values in the map. -- -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")] map :: (a -> b) -> WordMap a -> WordMap b map = fmap -- | /O(n)/. Map a function over all values in the map. -- -- > let f key x = (show key) ++ ":" ++ x -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")] mapWithKey :: forall a b. (Key -> a -> b) -> WordMap a -> WordMap b mapWithKey f = start where start (WordMap Empty) = WordMap Empty start (WordMap (NonEmpty min minV root)) = WordMap (NonEmpty min (f min minV) (go root)) go :: Node t a -> Node t b go Tip = Tip go (Bin k v l r) = Bin k (f k v) (go l) (go r) -- | /O(n)/. -- @'traverseWithKey' f s == 'fromList' <$> 'traverse' (\(k, v) -> (,) k <$> f k v) ('toList' m)@ -- That is, behaves exactly like a regular 'traverse' except that the traversing -- function also has access to the key associated with a value. -- -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')]) -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == Nothing traverseWithKey :: Applicative f => (Key -> a -> f b) -> WordMap a -> f (WordMap b) traverseWithKey f = start where start (WordMap Empty) = pure (WordMap Empty) start (WordMap (NonEmpty min minV root)) = (\minV' root' -> WordMap (NonEmpty min minV' root')) <$> f min minV <*> goL root goL Tip = pure Tip goL (Bin max maxV l r) = (\l' r' maxV' -> Bin max maxV' l' r') <$> goL l <*> goR r <*> f max maxV goR Tip = pure Tip goR (Bin min minV l r) = Bin min <$> f min minV <*> goL l <*> goR r -- | /O(n)/. The function @'mapAccum'@ threads an accumulating -- argument through the map in ascending order of keys. -- -- > let f a b = (a ++ b, b ++ "X") -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")]) mapAccum :: (a -> b -> (a, c)) -> a -> WordMap b -> (a, WordMap c) mapAccum f = mapAccumWithKey (\a _ x -> f a x) -- | /O(n)/. The function @'mapAccumWithKey'@ threads an accumulating -- argument through the map in ascending order of keys. -- -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X") -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")]) mapAccumWithKey :: (a -> Key -> b -> (a, c)) -> a -> WordMap b -> (a, WordMap c) mapAccumWithKey f = start where start a (WordMap Empty) = (a, WordMap Empty) start a (WordMap (NonEmpty min minV root)) = let (a', minV') = f a min minV (a'', root') = goL root a' in (a'', WordMap (NonEmpty min minV' root')) goL Tip a = (a, Tip) goL (Bin max maxV l r) a = let (a', l') = goL l a (a'', r') = goR r a' (a''', maxV') = f a'' max maxV in (a''', Bin max maxV' l' r') goR Tip a = (a, Tip) goR (Bin min minV l r) a = let (a', minV') = f a min minV (a'', l') = goL l a' (a''', r') = goR r a'' in (a''', Bin min minV' l' r') -- | /O(n)/. The function @'mapAccumRWithKey'@ threads an accumulating -- argument through the map in descending order of keys. mapAccumRWithKey :: (a -> Key -> b -> (a, c)) -> a -> WordMap b -> (a, WordMap c) mapAccumRWithKey f = start where start a (WordMap Empty) = (a, WordMap Empty) start a (WordMap (NonEmpty min minV root)) = let (a', root') = goL root a (a'', minV') = f a' min minV in (a'', WordMap (NonEmpty min minV' root')) goL Tip a = (a, Tip) goL (Bin max maxV l r) a = let (a', maxV') = f a max maxV (a'', r') = goR r a' (a''', l') = goL l a'' in (a''', Bin max maxV' l' r') goR Tip a = (a, Tip) goR (Bin min minV l r) a = let (a', r') = goR r a (a'', l') = goL l a' (a''', minV') = f a'' min minV in (a''', Bin min minV' l' r') -- | /O(n*min(n,W))/. -- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@. -- -- The size of the result may be smaller if @f@ maps two or more distinct -- keys to the same new key. In this case the value at the greatest of the -- original keys is retained. -- -- > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")] -- > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c" -- > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c" mapKeys :: (Key -> Key) -> WordMap a -> WordMap a mapKeys f = foldlWithKey' (\m k a -> insert (f k) a m) empty -- | /O(n*min(n,W))/. -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@. -- -- The size of the result may be smaller if @f@ maps two or more distinct -- keys to the same new key. In this case the associated values will be -- combined using @c@. -- -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab" -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab" mapKeysWith :: (a -> a -> a) -> (Key -> Key) -> WordMap a -> WordMap a mapKeysWith combine f = foldlWithKey' (\m k a -> insertWith combine (f k) a m) empty -- | /O(n*min(n,W))/. -- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@ -- is strictly monotonic. -- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@. -- /The precondition is not checked./ -- Semi-formally, we have: -- -- > and [x < y ==> f x < f y | x <- ls, y <- ls] -- > ==> mapKeysMonotonic f s == mapKeys f s -- > where ls = keys s -- -- This means that @f@ maps distinct original keys to distinct resulting keys. -- This function has slightly better performance than 'mapKeys'. -- -- > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")] mapKeysMonotonic :: (Key -> Key) -> WordMap a -> WordMap a mapKeysMonotonic = mapKeys -- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs. fromList :: [(Key, a)] -> WordMap a fromList = Data.List.foldl' (\t (k, a) -> insert k a t) empty -- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'. -- -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "ab"), (5, "cba")] -- > fromListWith (++) [] == empty fromListWith :: (a -> a -> a) -> [(Key, a)] -> WordMap a fromListWith f = Data.List.foldl' (\t (k, a) -> insertWith f k a t) empty -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs with a combining function. See also fromAscListWithKey'. -- -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "3:a|b"), (5, "5:c|5:b|a")] -- > fromListWithKey f [] == empty fromListWithKey :: (Key -> a -> a -> a) -> [(Key, a)] -> WordMap a fromListWithKey f = Data.List.foldl' (\t (k, a) -> insertWithKey f k a t) empty -- TODO: Use the ordering -- | /O(n)/. Build a map from a list of key\/value pairs where -- the keys are in ascending order. -- -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")] fromAscList :: [(Key, a)] -> WordMap a fromAscList = fromList -- | /O(n)/. Build a map from a list of key\/value pairs where -- the keys are in ascending order. -- -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")] fromAscListWith :: (a -> a -> a) -> [(Key, a)] -> WordMap a fromAscListWith = fromListWith -- | /O(n)/. Build a map from a list of key\/value pairs where -- the keys are in ascending order, with a combining function on equal keys. -- /The precondition (input list is ascending) is not checked./ -- -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "5:b|a")] fromAscListWithKey :: (Key -> a -> a -> a) -> [(Key, a)] -> WordMap a fromAscListWithKey = fromListWithKey -- | /O(n)/. Build a map from a list of key\/value pairs where -- the keys are in ascending order and all distinct. -- /The precondition (input list is strictly ascending) is not checked./ -- -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromDistinctAscList :: [(Key, a)] -> WordMap a fromDistinctAscList = fromList -- | /O(n)/. Map values and collect the 'Just' results. -- -- > let f x = if x == "a" then Just "new a" else Nothing -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a" mapMaybe :: (a -> Maybe b) -> WordMap a -> WordMap b mapMaybe f = mapMaybeWithKey (const f) -- | /O(n)/. Map keys\/values and collect the 'Just' results. -- -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3" mapMaybeWithKey :: (Key -> a -> Maybe b) -> WordMap a -> WordMap b mapMaybeWithKey f = start where start (WordMap Empty) = WordMap Empty start (WordMap (NonEmpty min minV root)) = case f min minV of Just minV' -> WordMap (NonEmpty min minV' (goL root)) Nothing -> WordMap (goDeleteL root) goL Tip = Tip goL (Bin max maxV l r) = case f max maxV of Just maxV' -> Bin max maxV' (goL l) (goR r) Nothing -> case goDeleteR r of Empty -> goL l NonEmpty max' maxV' r' -> Bin max' maxV' (goL l) r' goR Tip = Tip goR (Bin min minV l r) = case f min minV of Just minV' -> Bin min minV' (goL l) (goR r) Nothing -> case goDeleteL l of Empty -> goR r NonEmpty min' minV' l' -> Bin min' minV' l' (goR r) goDeleteL Tip = Empty goDeleteL (Bin max maxV l r) = case f max maxV of Just maxV' -> case goDeleteL l of Empty -> case goR r of Tip -> NonEmpty max maxV' Tip Bin minI minVI lI rI -> NonEmpty minI minVI (Bin max maxV' lI rI) NonEmpty min minV l' -> NonEmpty min minV (Bin max maxV' l' (goR r)) Nothing -> binL (goDeleteL l) (goDeleteR r) goDeleteR Tip = Empty goDeleteR (Bin min minV l r) = case f min minV of Just minV' -> case goDeleteR r of Empty -> case goL l of Tip -> NonEmpty min minV' Tip Bin maxI maxVI lI rI -> NonEmpty maxI maxVI (Bin min minV' lI rI) NonEmpty max maxV r' -> NonEmpty max maxV (Bin min minV' (goL l) r') Nothing -> binR (goDeleteL l) (goDeleteR r) -- | /O(n)/. Map values and separate the 'Left' and 'Right' results. -- -- > let f a = if a < "c" then Left a else Right a -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")]) -- > -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) mapEither :: (a -> Either b c) -> WordMap a -> (WordMap b, WordMap c) mapEither f = mapEitherWithKey (const f) -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results. -- -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a) -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")]) -- > -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")]) mapEitherWithKey :: (Key -> a -> Either b c) -> WordMap a -> (WordMap b, WordMap c) mapEitherWithKey func = start where start (WordMap Empty) = (WordMap Empty, WordMap Empty) start (WordMap (NonEmpty min minV root)) = case func min minV of Left v -> let SP t f = goTrueL root in (WordMap (NonEmpty min v t), WordMap f) Right v -> let SP t f = goFalseL root in (WordMap t, WordMap (NonEmpty min v f)) goTrueL Tip = SP Tip Empty goTrueL (Bin max maxV l r) = case func max maxV of Left v -> let SP tl fl = goTrueL l SP tr fr = goTrueR r in SP (Bin max v tl tr) (binL fl fr) Right v -> let SP tl fl = goTrueL l SP tr fr = goFalseR r t = case tr of Empty -> tl NonEmpty max' maxV' r' -> Bin max' maxV' tl r' f = case fl of Empty -> r2lMap $ NonEmpty max v fr NonEmpty min' minV' l' -> NonEmpty min' minV' (Bin max v l' fr) in SP t f goTrueR Tip = SP Tip Empty goTrueR (Bin min minV l r) = case func min minV of Left v -> let SP tl fl = goTrueL l SP tr fr = goTrueR r in SP (Bin min v tl tr) (binR fl fr) Right v -> let SP tl fl = goFalseL l SP tr fr = goTrueR r t = case tl of Empty -> tr NonEmpty min' minV' l' -> Bin min' minV' l' tr f = case fr of Empty -> l2rMap $ NonEmpty min v fl NonEmpty max' maxV' r' -> NonEmpty max' maxV' (Bin min v fl r') in SP t f goFalseL Tip = SP Empty Tip goFalseL (Bin max maxV l r) = case func max maxV of Left v -> let SP tl fl = goFalseL l SP tr fr = goTrueR r t = case tl of Empty -> r2lMap $ NonEmpty max v tr NonEmpty min' minV' l' -> NonEmpty min' minV' (Bin max v l' tr) f = case fr of Empty -> fl NonEmpty max' maxV' r' -> Bin max' maxV' fl r' in SP t f Right v -> let SP tl fl = goFalseL l SP tr fr = goFalseR r in SP (binL tl tr) (Bin max v fl fr) goFalseR Tip = SP Empty Tip goFalseR (Bin min minV l r) = case func min minV of Left v -> let SP tl fl = goTrueL l SP tr fr = goFalseR r t = case tr of Empty -> l2rMap $ NonEmpty min v tl NonEmpty max' maxV' r' -> NonEmpty max' maxV' (Bin min v tl r') f = case fl of Empty -> fr NonEmpty min' minV' l' -> Bin min' minV' l' fr in SP t f Right v -> let SP tl fl = goFalseL l SP tr fr = goFalseR r in SP (binR tl tr) (Bin min v fl fr) -- | /O(min(n,W))/. Update the value at the minimal key. -- -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")] -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateMin :: (a -> Maybe a) -> WordMap a -> WordMap a updateMin _ (WordMap Empty) = WordMap Empty updateMin f m = update f (fst (findMin m)) m -- | /O(min(n,W))/. Update the value at the maximal key. -- -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")] -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateMax :: (a -> Maybe a) -> WordMap a -> WordMap a updateMax _ (WordMap Empty) = WordMap Empty updateMax f m = update f (fst (findMax m)) m -- | /O(min(n,W))/. Update the value at the minimal key. -- -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")] -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateMinWithKey :: (Key -> a -> Maybe a) -> WordMap a -> WordMap a updateMinWithKey _ (WordMap Empty) = WordMap Empty updateMinWithKey f m = updateWithKey f (fst (findMin m)) m -- | /O(min(n,W))/. Update the value at the maximal key. -- -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")] -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateMaxWithKey :: (Key -> a -> Maybe a) -> WordMap a -> WordMap a updateMaxWithKey _ (WordMap Empty) = WordMap Empty updateMaxWithKey f m = updateWithKey f (fst (findMax m)) m
gereeter/bounded-intmap
src/Data/WordMap/Lazy.hs
mit
71,636
0
21
22,348
22,821
11,221
11,600
938
70
{- Author: Jeff Newbern Maintainer: Jeff Newbern <[email protected]> Time-stamp: <Mon Aug 18 15:20:18 2003> License: GPL -} {- DESCRIPTION Example 19 - Nesting the Continuation monad within the I/O monad Usage: Compile the code and run it. Type an integer value and press enter, and the program will print out an answer string whose format and contents depend in a complicated way on the input number. Try: echo "0" | ./ex19 echo "7" | ./ex19 echo "9" | ./ex19 echo "10" | ./ex19 echo "19" | ./ex19 echo "20" | ./ex19 echo "68" | ./ex19 echo "199" | ./ex19 echo "200" | ./ex19 echo "684" | ./ex19 echo "19999" | ./ex19 echo "20000" | ./ex19 echo "20002" | ./ex19 echo "340000" | ./ex19 echo "837364" | ./ex19 echo "1999997" | ./ex19 echo "1999999" | ./ex19 echo "2000000" | ./ex19 echo "2000001" | ./ex19 echo "2000002" | ./ex19 echo "2000003" | ./ex19 echo "2000004" | ./ex19 echo "7001001" | ./ex19 echo "746392736" | ./ex19 -} import IO import Monad import System import Char import Control.Monad.Cont {- We use the continuation monad to perform "escapes" from code blocks. This function implements a complicated control structure to process numbers: Input (n) Output List Shown ========= ====== ========== 0-9 n none 10-199 number of digits in (n/2) digits of (n/2) 200-19999 n digits of (n/2) 20000-1999999 (n/2) backwards none >= 2000000 sum of digits of (n/2) digits of (n/2) -} fun :: IO String fun = do n <- (readLn::IO Int) -- this is an IO monad block return $ (`runCont` id) $ do -- this is a Cont monad block str <- callCC $ \exit1 -> do when (n < 10) (exit1 (show n)) let ns = map digitToInt (show (n `div` 2)) n' <- callCC $ \exit2 -> do when ((length ns) < 3) (exit2 (length ns)) when ((length ns) < 5) (exit2 n) when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) exit1 (dropWhile (=='0') ns') return $ sum ns return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') return $ "Answer: " ++ str -- calls fun with the integer read from the first command-line argument main :: IO () main = do str <- fun putStrLn str -- END OF FILE
maurotrb/hs-exercises
AllAboutMonads/examples/example19.hs
mit
2,747
0
28
1,070
361
183
178
22
1
{-# LANGUAGE RecordWildCards #-} module MLUtil.Graphics.Rendering ( ChartLabels (..) , RPlot () , defaultChartLabels , mkRPlot , renderChartSVG , renderFlowchartSVG ) where import Diagrams.Backend.SVG import Graphics.Rendering.Chart.Backend.Diagrams import Graphics.Rendering.Chart.Easy import MLUtil.Graphics.Flowchart import MLUtil.Graphics.Imports import MLUtil.Graphics.RPlot -- |Chart labels data ChartLabels = ChartLabels { clTitle :: Maybe String , clXAxisLabel :: Maybe String , clYAxisLabel :: Maybe String } deriving Show -- |Default chart labels defaultChartLabels :: ChartLabels defaultChartLabels = ChartLabels { clTitle = Nothing , clXAxisLabel = Nothing , clYAxisLabel = Nothing } -- |Render chart as SVG file renderChartSVG :: FilePath -> ChartLabels -> [RPlot] -> IO () renderChartSVG path ChartLabels{..} ps = toFile def path $ do let setMaybe p (Just x) = p .= x setMaybe p Nothing = return () setMaybe layout_title clTitle setMaybe (layout_x_axis . laxis_title) clXAxisLabel setMaybe (layout_y_axis . laxis_title) clYAxisLabel mapM_ plotRPlot ps -- |Render flowchart as SVG file renderFlowchartSVG :: FilePath -> Flowchart -> IO () renderFlowchartSVG path = renderSVG path (mkWidth 500)
rcook/mlutil
mlutil/src/MLUtil/Graphics/Rendering.hs
mit
1,362
0
13
315
321
178
143
37
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Yage hiding (Event, at, key) import Yage.Rendering import Yage.Math import Yage.Wire import Yage.Examples.Shared import Data.List import Control.Monad import Control.Monad.Random settings :: WindowConfig settings = WindowConfig { windowSize = (800, 600) , windowHints = [ WindowHint'ContextVersionMajor 3 , WindowHint'ContextVersionMinor 2 , WindowHint'OpenGLProfile OpenGLProfile'Core , WindowHint'OpenGLForwardCompat True , WindowHint'RefreshRate 60 --, WindowHint'Resizable False --, WindowHint'Decorated False ] } data Particle = Particle { _particlePosition :: V3 Float --, _cubeOrientation :: Quaternion Float --, _cubeScale :: V3 Float } deriving (Show) makeLenses ''Particle data ParticleSystem = ParticleSystem { _pSystemOrigin :: V3 Float } deriving (Show) makeLenses ''ParticleSystem data ParticleView = ParticleView { _viewCamera :: CameraHandle , _particles :: [ParticleSystem] } deriving (Show) makeLenses ''ParticleView main :: IO () main = yageMain "yage-particles" settings mainWire clockSession initialCamOrientation = axisAngle xAxis (deg2rad (-60)) mainWire :: (Real t) => YageWire t () ParticleView mainWire = proc () -> do -- cubeRot <- cubeRotationByInput -< () particeSys <- particleSystems -< [] cameraPos <- cameraMovementByInput -< () cameraRot <- cameraRotationByInput initialCamOrientation -< () returnA -< ParticleView (fpsCamera & cameraLocation .~ cameraRot `rotate` (V3 0 1 8 + cameraPos) & cameraOrientation .~ cameraRot) [] where -- stolen from https://github.com/ocharles/netwire-classics/blob/master/asteroids/Asteroids.hs particleSystems :: YageWire t [ParticleSystem] [ParticleSystem] particleSystems = go [] where go systems = mkGen $ \ds newSystems -> do stepped <- mapM (\w -> stepWire w ds (Right ())) systems let alive = [ (r, w) | (Right r, w) <- stepped ] spawned <- concat <$> mapM spawnParticles newSystems return (Right (map fst alive), go $ map snd alive ++ spawned) spawnParticles sys = do n <- getRandomR (4, 8) replicateM n $ do velocity <- randomVelocity (5, 10) life <- getRandomR (1, 3) return (for life . integral (sys^.pSystemOrigin) . pure velocity) randomVelocity :: (Applicative m, MonadRandom m) => (Float, Float) -> m (V3 Float) randomVelocity magRange = do v <- V3 <$> getRandomR (-1, 1) <*> getRandomR (-1, 1) <*> getRandomR (-1, 1) mag <- getRandomR magRange return (normalize v ^* mag) cameraMovementByInput :: (Real t) => YageWire t a (V3 Float) cameraMovementByInput = let acc = 20 att = 0.8 toLeft = -xAxis toRight = xAxis forward = -zAxis backward = zAxis in smoothTranslation forward acc att Key'W . smoothTranslation toLeft acc att Key'A . smoothTranslation backward acc att Key'S . smoothTranslation toRight acc att Key'D . 0 cameraRotationByInput :: (Real t) => Quaternion Float -> YageWire t a (Quaternion Float) cameraRotationByInput initial = let upward = V3 0 1 0 rightward = V3 1 0 0 in rotationByVelocity upward rightward . arr(/1000) . meassureMouseVelocity (while . keyDown Key'LeftShift) -- meassureMouseVelocity :: (Real t) => YageWire t' a a -> YageWire t a (V2 Float) meassureMouseVelocity when' = when' . mouseVelocity <|> 0 smoothTranslation :: (Real t) => V3 Float -> Float -> Float -> Key -> YageWire t (V3 Float) (V3 Float) smoothTranslation dir acc att key = let trans = integral 0 . arr (signorm dir ^*) . velocity acc att key in proc inTransV -> do transV <- trans -< () returnA -< inTransV + transV smoothRotationByKey :: (Real t) => (V3 Float, Float) -> Key -> YageWire t (Quaternion Float) (Quaternion Float) smoothRotationByKey (axis, dir) key = let acc = 20 att = 0.85 angleVel = velocity acc att key rot = axisAngle axis <$> integral 0 . arr (dir*) . angleVel in proc inQ -> do rotQ <- rot -< () returnA -< inQ * rotQ rotationByVelocity :: (Real t) => V3 Float -> V3 Float -> YageWire t (V2 Float) (Quaternion Float) rotationByVelocity xMap yMap = let applyOrientations = arr (axisAngle xMap . (^._x)) &&& arr (axisAngle yMap . (^._y)) combineOrientations = arr (\(qu, qr) -> qu * qr) in combineOrientations . applyOrientations . integral 0 velocity :: (Floating b, Ord b, Real t) => b -> b -> Key -> YageWire t a b velocity acc att trigger = integrateAttenuated att 0 . (while . keyDown trigger . pure acc <|> 0) ------------------------------------------------------------------------------- -- View Definition instance HasRenderView ParticleView where getRenderView ParticleView{..} = let floorE = floorEntity & entityScale .~ 10 scene = emptyRenderScene (Camera3D _viewCamera (deg2rad 60)) `addRenderable` floorE in RenderUnit scene
MaxDaten/yage-examples
src/YageWireParticles.hs
mit
5,848
3
20
1,883
1,645
840
805
-1
-1
module Output (handleReport, printRemaining) where import Control.Monad import Data.Char import Data.List import System.Console.ANSI import System.Exit import GitMapConfig handleReport :: Bool -> Bool -> IO (Bool, GitMapRepoSpec, String, String) -> [GitMapRepoSpec] -> IO () handleReport status quiet reportV repos = do (success, repoSpec, gitCmd, output) <- reportV let reposLeft = delete repoSpec repos repoNamesLeft = map gmrsName reposLeft newStatus = status && success printOutput quiet success (gmrsName repoSpec) gitCmd output repoNamesLeft if (null reposLeft) then when (not newStatus) $ die $ "Errors occurred in some repositories. " ++ "You may want to revert any successful changes." else handleReport newStatus quiet reportV reposLeft printOutput :: Bool -> Bool -> String -> String -> String -> [String] -> IO () printOutput quiet success repoName gitCmd output reposLeft = do when (not quiet) $ do cursorUpLine $ 2 + length reposLeft --one removed, plus header setCursorColumn 0 clearFromCursorToScreenEnd when (not $ (quiet && success) || null gitCmd) $ do setColor infoColor putStr $ repoName ++ ": " let (color, message) = if success then (successColor, "success") else (errorColor, "failed") setColor color putStrLn message setColor commandColor putStrLn $ "Ran `" ++ gitCmd ++ "`:" resetColor putStrLn $ dropWhileEnd isSpace $ dropWhile isSpace output putStrLn "" when (not $ quiet || null reposLeft) $ printRemaining reposLeft printRemaining :: [String] -> IO () printRemaining reposLeft = do setColor infoColor putStrLn "Repositories remaining:" mapM_ putStrLn reposLeft resetColor :: IO () resetColor = setSGR [Reset] successColor = Cyan errorColor = Red infoColor = Yellow commandColor = Magenta setColor :: Color -> IO () setColor color = setSGR [SetColor Foreground Vivid color]
ryanreich/gitmap
src/Output.hs
mit
1,984
0
14
442
608
301
307
54
2
module Main where people :: [(String, String)] people = [("name", "Calvin") ,("wat", "John") ,("name", "Thomas") ] {- generic filterByKey function that accepts a string as keyname -} filterByKey :: Eq a => a -> [(a, t)] -> [t] filterByKey _ [] = [] filterByKey p ((k, v):xs) | p == k = v : filterByKey p xs | otherwise = filterByKey p xs filterByName :: [(String, t)] -> [t] filterByName = filterByKey "name" getName :: [(a, b)] -> [b] getName = map snd main :: IO () main = do let names = getName people {- snd simply plucks out the 2nd value in the tuple -} print names let names2 = filterByKey "name" people print names2 let names3 = filterByName people print names3
calvinchengx/learnhaskell
currying/currying2.hs
mit
725
0
10
179
283
151
132
22
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-} module Main where import qualified Graphics.UI.FLTK.LowLevel.FL as FL import Graphics.UI.FLTK.LowLevel.Fl_Enumerations import Graphics.UI.FLTK.LowLevel.Fl_Types import Graphics.UI.FLTK.LowLevel.FLTKHS import Control.Monad import Data.IORef star :: Int -> Int -> Double -> IO () star w h n = do flcPushMatrix flcTranslate (ByXY (ByX (fromIntegral w / 2)) (ByY (fromIntegral h /2))) flcScaleWithY (ByXY (ByX (fromIntegral w / 2)) (ByY (fromIntegral h /2))) forM_ [0..n] $ \i -> do forM_ [(i+1)..n] $ \j -> do let i_vertex :: Double = 2 * pi * i/n + 0.1 j_vertex :: Double = 2 * pi * j/n + 0.1 flcBeginLine flcVertex (PrecisePosition (PreciseX $ cos i_vertex) (PreciseY $ sin i_vertex)) flcVertex (PrecisePosition (PreciseX $ cos j_vertex) (PreciseY $ sin j_vertex)) flcEndLine flcPopMatrix sliderCb :: IORef (Double,Double) -> (Double -> (Double,Double) -> (Double,Double))-> Ref HorSlider -> IO () sliderCb sides' sidesf' slider' = do v' <- getValue slider' modifyIORef sides' (sidesf' v') (Just p') <- getParent slider' redraw p' badDraw :: IORef (Double,Double) -> Int -> Int -> ((Double,Double) -> Double) -> IO () badDraw sides w h which' = do flcSetColor blackColor >> flcRectf (toRectangle (0,0,w,h)) flcSetColor whiteColor >> readIORef sides >>= star w h . which' drawWindow :: IORef (Double, Double) -> ((Double, Double) -> Double) -> Ref WindowBase -> IO () drawWindow sides' whichf' w' = do (Width ww') <- getW w' (Height wh') <- getH w' badDraw sides' ww' wh' whichf' c' <- getChild w' (AtIndex 0) maybe (return ()) (drawChild w') (c' :: Maybe (Ref WidgetBase)) main :: IO () main = do visual' <- FL.visual ModeDouble if (not visual') then print "Xdbe not supported, faking double buffer with pixmaps.\n" else return () sides' <- newIORef (20,20) w01 <- windowNew (toSize (420,420)) Nothing (Just "Fl_Single_Window") setBox w01 FlatBox begin w01 w1 <- singleWindowCustom (Size (Width 400) (Height 400)) (Just (Position (X 10) (Y 10))) (Just "Single Window") (Just (\w -> drawWindow sides' fst (safeCast w))) defaultCustomWidgetFuncs defaultCustomWindowFuncs setBox w1 FlatBox setColor w1 blackColor setResizable w1 (Just w1) begin w1 slider0 <- horSliderNew (toRectangle (20,370,360,25)) Nothing range slider0 2 30 setStep slider0 1 _ <- readIORef sides' >>= setValue slider0 . fst setCallback slider0 (sliderCb sides' (\v (_,s2) -> (v, s2))) end w1 end w01 w02 <- windowNew (Size (Width 420) (Height 420)) Nothing (Just "Fl_Double_Window") setBox w02 FlatBox begin w02 w2 <- doubleWindowCustom (Size (Width 400) (Height 400)) (Just $ Position (X 10) (Y 10)) (Just "Fl_Double_Window") (Just (\w -> drawWindow sides' snd (safeCast w))) defaultCustomWidgetFuncs defaultCustomWindowFuncs setBox w2 FlatBox setColor w2 blackColor setResizable w2 (Just w2) begin w2 slider1 <- horSliderNew (toRectangle (20,370,360,25)) Nothing range slider1 2 30 setStep slider1 1 _ <- readIORef sides' >>= setValue slider1 . fst setCallback slider1 (sliderCb sides' (\v (s1,_) -> (s1,v))) end w2 end w02 showWidget w01 showWidget w1 showWidget w02 showWidget w2 _ <- FL.run return ()
deech/fltkhs-demos
src/Examples/doublebuffer.hs
mit
3,488
0
21
796
1,469
711
758
96
2
module Compiler where import Control.Applicative ((<|>)) data Expr = Val Int | Add Expr Expr deriving Show data Op = Push Int | Plus deriving Show type Stack = [Int] type Code = [Op] -- 1. Adding a stack push :: Int -> Stack -> Stack push n st = n:st add :: Stack -> Stack add (x:y:xs) = x + y:xs eval :: Expr -> Stack -> Stack -- eval (Val n) st = -- push n st -- eval (Add e1 e2) st = -- add (eval e2 (eval e1 st)) eval e st = eval' e id st comp :: Expr -> Code -> Code comp (Val n) st = Push n : st comp (Add x y) st = comp y (comp x (Plus:st)) exec :: Code -> Stack -> Stack exec [] st = st exec (Push x:xs) st = exec xs (x:st) exec (Plus:xs) (x:y:st) = exec xs ((x + y):st) -- 2. Continuation-passing style type Cont = Stack -> Stack -- eval'' e c st = c (eval e st) -- Expanding the type makes it a bit easier to understand the signature -- eval' :: Expr -> (Stack -> Stack) -> (Stack -> Stack) :: Expr -> (Stack -> Stack) -> Stack -> Stack eval' :: Expr -> Cont -> Cont eval' (Val n) c st = c (push n st) eval' (Add x y) c st = -- c (add (eval' y c (eval' x c st))) -- complete non-sense eval' x (eval' y (c . add)) st -- 3. Defunctionalisation haltC :: Cont haltC = id pushC :: Int -> Cont -> Cont pushC n c st = c (push n st) addC :: Cont -> Cont addC c st = c (add st) eval'' :: Expr -> Cont -> Cont eval'' (Val n) c = pushC n c eval'' (Add x y) c = -- addC c (eval'' y c (eval'' x c st)) -- complete non-sense eval'' x (eval'' y (addC c)) data VMCode = HALT | PUSH Int VMCode | ADD VMCode deriving Show execC :: VMCode -> Cont execC HALT = haltC execC (PUSH n c) = pushC n (execC c) execC (ADD c) = addC (execC c) exec' :: VMCode -> Stack -> Stack exec' HALT st = st exec' (PUSH n c) st = execC (PUSH n c) st exec' (ADD c) (x:y:st) = execC (ADD c) (x:y:st) comp' :: Expr -> VMCode comp' e = compHelp e HALT where compHelp :: Expr -> VMCode -> VMCode compHelp (Val n) c = PUSH n c compHelp (Add x y) c = compHelp x (compHelp y (ADD c)) -- Ex. 1 data Expr' = Val' Int | Add' Expr' Expr' | Throw | Catch Expr' Expr' deriving Show data VMCode' = HALT' | PUSH' Int VMCode' | ADD' VMCode' | THROW VMCode' | CATCH VMCode' deriving Show type Stack' = [Result] type Result = Maybe Int meval :: Expr' -> Result meval (Val' n) = Just n meval (Add' x y) = (+) <$> meval x <*> meval y meval Throw = Nothing meval (Catch x h) = meval x <|> meval h comp'' :: Expr' -> VMCode' comp'' e = compHelp e HALT' where compHelp :: Expr' -> VMCode' -> VMCode' compHelp (Val' n) c = PUSH' n c compHelp (Add' e1 e2) c = compHelp e1 (compHelp e2 (ADD' c)) compHelp Throw c = THROW c compHelp (Catch e' h) c = compHelp e' (compHelp h (CATCH c)) exec'' :: VMCode' -> Stack' -> Stack' exec'' HALT' st = st exec'' (PUSH' n c) st = exec'' c (Just n : st) exec'' (ADD' c) (x:y:st) = exec'' c (((+) <$> x <*> y) : st) exec'' (THROW c) st = exec'' c (Nothing : st) exec'' (CATCH c) (e:h:st) = exec'' c ((e <|> h) : st)
futtetennista/IntroductionToFunctionalProgramming
PiH/src/Compiler.hs
mit
3,141
0
11
892
1,376
718
658
132
4
greet name = "hello " ++ name square x = x * x fact n = product [1..n] sumsqrs = sum . map square
craynafinal/cs557_functional_languages
practice/week1/defs.hs
mit
103
0
6
29
53
26
27
4
1
------------------------------------------------------------------------------ -- Module : Data.Time.Calendar.BankHoliday -- Maintainer : [email protected] ------------------------------------------------------------------------------ module Data.Time.Calendar.BankHoliday ( isWeekend , isWeekday , yearFromDay ) where import Data.Time {- | whether the given day is a weekend -} isWeekend :: Day -> Bool isWeekend d = toModifiedJulianDay d `mod` 7 `elem` [3,4] {- | whether the given day is a weekday -} isWeekday :: Day -> Bool isWeekday = not . isWeekend yearFromDay :: Day -> Integer yearFromDay = fst' . toGregorian where fst' :: (a,b,c) -> a fst' (x,_,_) = x
tippenein/BankHoliday
Data/Time/Calendar/BankHoliday.hs
mit
697
0
8
115
141
86
55
13
1
{-# OPTIONS_GHC -F -pgmF htfpp -fno-warn-missing-signatures #-} {-# LANGUAGE QuasiQuotes #-} module Text.Noise.Compiler.Test where import Test.Framework import Data.String.QQ (s) import Data.Maybe import Assertion import Text.Noise.SourceRange (oneLineRange) import qualified Text.Noise.Compiler.Document as D import qualified Text.Noise.Compiler.Document.Color as Color {-# ANN module "HLint: ignore Use camelCase" #-} colorPaint :: String -> D.Paint colorPaint = D.ColorPaint . fromJust. Color.fromHex test_empty = assertOutput (D.Document []) "" test_undefined_function = assertError "Undefined function \"shape.squircle\"." "shape.squircle" test_top_level_expression_type_error = assertError "Top-level expression is not an element." "color.red" test_argument_type_error = assertError "Argument \"cx\" to function \"shape.circle\" has incorrect type." "shape.circle(cx:#ffffff)" test_block_statement_type_error = assertError "Statement in block of function \"group\" has incorrect type." "group with #123456 end" test_bad_filename = assertError "Argument \"file\" to function \"image\" has incorrect type." "image(0,0,50,50,\"http://example.com/image.png\")" test_missing_argument = assertError "Function \"shape.circle\" requires argument \"cx\"." "shape.circle" text_excess_argument = assertError "Too many arguments to function \"color.red\"." "color.red(#ff0000)" test_positional_arg_after_keyword_arg = assertErrorAt (oneLineRange "" 34 7) "Positional argument follows a keyword argument." "gradient.horizontal(from:#abcdef,#123456)" test_keyword_arg_duplicating_positional_arg = assertError "Keyword argument \"from\" duplicates a positional argument." "gradient.horizontal(#abcdef, from: #123456, to: #000000)" test_keyword_arg_duplicating_keyword_arg = assertError "Duplicate keyword argument \"from\" in function call." "gradient.horizontal(from: #abcdef, to: #123456, from: #000000)" test_duplicate_args_in_function_def = assertError "Duplicate argument \"x\" in function definition." "let fn(x,y,x) = color.red" test_define_function_with_0_args = assertOutputElement D.circle { D.fill = colorPaint "ffff00"} [s|let color.yellow = #ffff00 shape.circle(0, 0, 0, fill:color.yellow)|] test_define_function_with_many_args = assertOutputElement D.circle { D.r = 20, D.fill = colorPaint "abcdef" } [s|let circle(r, c) = shape.circle(0, 0,r,c) circle(20, #abcdef)|] test_argument_shadows_function = assertOutputElement D.circle { D.fill = colorPaint "123456" } [s|let x = #abcdef let f(x) = x shape.circle(0, 0, 0, f(#123456))|] test_operators = assertOutputElement D.rectangle { D.x = 1+2, D.y = 3-4, D.width = 5*6, D.height = 7/8 } [s|shape.rectangle(1+2, 3-4, 5*6, 7/8)|] test_operators_associativity = assertOutputElement D.rectangle { D.x = 1-2-3, D.y = 4/5/6, D.width = 1-2+3, D.height = 4/5*6 } [s|shape.rectangle(1-2-3, 4/5/6, 1-2+3, 4/5*6)|] test_operators_precedence = assertOutputElement D.rectangle { D.x = 2+3*4, D.y = 2+3/4, D.width = 2-3*4, D.height = 2-3/4, D.cornerRadius = (2+3)*4 } [s|shape.rectangle(2+3*4, 2+3/4, 2-3*4, 2-3/4, (2+3)*4)|]
brow/noise
tests/Text/Noise/Compiler/Test.hs
mit
3,176
0
10
435
581
334
247
65
1
module Filter.NumberRef (numberRef) where import Text.Pandoc.Definition import Text.Pandoc.Walk replaceInline :: Inline -> Inline -> Inline replaceInline r (Str "#") = r replaceInline _ x = x process :: Inline -> Inline process (Link a is t@('#':xs, _)) = let ref = RawInline (Format "tex") $ "{\\ref{" ++ xs ++ "}}" in Link a (walk (replaceInline ref) is) t process x = x numberRef :: Pandoc -> Pandoc numberRef = walk process
Thhethssmuz/ppp
src/Filter/NumberRef.hs
mit
437
0
14
80
180
95
85
13
1
{-# LANGUAGE ParallelListComp #-} module Tests.MathPolarTest (mathPolarTestDo) where import Test.HUnit import CornerPoints.CornerPoints(CornerPoints(..), (+++)) import CornerPoints.Points(Point(..)) import CornerPoints.Create( slopeAdjustedForVerticalAngle, adjustRadiusForSlope, createCornerPoint, Slope(..), Angle(..), flatXSlope, flatYSlope, ) import Math.Trigonometry(sinDegrees,cosDegrees) import CornerPoints.Radius(Radius(..)) mathPolarTestDo = do {-These don't need to be exported, but leave in case more testing is needed. runTestTT getQuadrantAngleTest runTestTT getQuadrantAngleTest2 runTestTT getQuadrantAngleTest3 runTestTT getQuadrantAngleTest4 runTestTT getQuadrantAngleTest5 runTestTT getQuadrantAngleTest6 runTestTT getQuadrantAngleTest7 -} {- putStrLn "adjust radius for slope" runTestTT adjustRadiusForSlopeTestRad10PosX10PosY0XY10 runTestTT adjustRadiusForSlopeTestRad10PosX0PosY10XY10 runTestTT adjustRadiusForSlopeTestRad10PosX1NegY10XY10 runTestTT adjustRadiusForSlopeTestRad10PosX10NegY1XY10 runTestTT adjustRadiusForSlopeTestRad10PosX1PosY10XY80 runTestTT adjustRadiusForSlopeTestRad10PosX1PosY10XY100 runTestTT adjustRadiusForSlopeTestRad10PosX10NegY1XY100 runTestTT adjustRadiusForSlopeTestRad10PosX1NegY10XY100 runTestTT adjustRadiusForSlopeTestRad10PosX1PosY10XY170 runTestTT adjustRadiusForSlopeTestRad10PosX10NegY1XY170 runTestTT adjustRadiusForSlopeTestRad10PosX1PosY10XY190 runTestTT adjustRadiusForSlopeTestRad10PosX10PosY1XY190 runTestTT adjustRadiusForSlopeTestRad10PosX1PosY10XY260 runTestTT adjustRadiusForSlopeTestRad10PosX10PosY1XY260 runTestTT adjustRadiusForSlopeTestRad10PosX1PosY10XY280 runTestTT adjustRadiusForSlopeTestRad10PosX10PosY1XY280 runTestTT adjustRadiusForSlopeTestRad10PosX1PosY10XY350 runTestTT adjustRadiusForSlopeTestRad10PosX10NegY1XY190 runTestTT adjustRadiusForSlopeTestRad10PosX1NegY1oXY190 -} {-Have a look at the bottom front right corner first, as this is the first corner gen'd.-} putStrLn "\n\n" putStrLn "createCornerPoint tests" runTestTT createCornerPointTestR10PosX0PosY0XY10 runTestTT createCornerPointTestR10PosX0PosY10XY10 runTestTT createCornerPointTestR10PosX0PosY10XY80 runTestTT createCornerPointTestR10PosX1PosY10XY100 runTestTT createCornerPointTestR10PosX1PosY10XY170 runTestTT createCornerPointTestR10PosX10PosY1XY170 runTestTT createCornerPointTestR10PosX1PosY10XY190 runTestTT createCornerPointTestR10PosX1PosY10XY260 --last round of patterns runTestTT createCornerPointTestR10PosX1PosY10XY280 runTestTT createCornerPointTestR10PosX1PosY10XY350 runTestTT createCornerPointTestR10PosX1NegY10XY190 runTestTT createCornerPointTestR10PosX1NegY10XY170 runTestTT createFrontCornerTest ---------------- set xy quadrant tests============================== --MathPolar does not need to export this. --leave for now, in case more testing is needed --runTestTT setQuadrant1YvalTest --runTestTT setQuadrant2YvalTest --runTestTT setQuadrant2Yval170Test --runTestTT setQuadrant3Xval190Test putStrLn "\n\n" putStrLn "slopeForXYAngleAndYslopeTest tests" runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY90 runTestTT slopeForXYAngleAndYslopeTestX0Ypos0XY0 runTestTT slopeForXYAngleAndYslopeTestX0Ypos10XY10 runTestTT slopeForXYAngleAndYslopeTestXPos1Ypos10XY10 runTestTT slopeForXYAngleAndYslopeTestXPos10Ypos1XY10 runTestTT slopeForXYAngleAndYslopeTestXPos10Yneg1XY10 runTestTT slopeForXYAngleAndYslopeTestXPos1Yneg10XY10 runTestTT slopeForXYAngleAndYslopeTestXPos1YPos10XY80 runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY80 runTestTT slopeForXYAngleAndYslopeTestXPos10Yneg1XY80 runTestTT slopeForXYAngleAndYslopeTestXPos1Yneg10XY80 runTestTT slopeForXYAngleAndYslopeTestXPos1YPos10XY100 runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY100 runTestTT slopeForXYAngleAndYslopeTestXPos1YNeg10XY100 runTestTT slopeForXYAngleAndYslopeTestXPos1YPos10XY170 runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY170 runTestTT slopeForXYAngleAndYslopeTestXPos0YNeg1XY170 runTestTT slopeForXYAngleAndYslopeTestXPos1YNeg1XY170 runTestTT slopeForXYAngleAndYslopeTestXPos1YPos10XY190 runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY190 runTestTT slopeForXYAngleAndYslopeTestXPos1YNeg10XY190 runTestTT slopeForXYAngleAndYslopeTestXPos1YPos10XY260 runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY260 runTestTT slopeForXYAngleAndYslopeTestXPos1YPos10XY280 runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY280 runTestTT slopeForXYAngleAndYslopeTestXPos1YNeg10XY280 runTestTT slopeForXYAngleAndYslopeTestXPos10YNeg1XY280 runTestTT slopeForXYAngleAndYslopeTestXPos1YPos10XY350 runTestTT slopeForXYAngleAndYslopeTestXPos10YPos1XY350 runTestTT slopeForXYAngleAndYslopeTestXPos0YNeg10XY100 runTestTT slopeForXYAngleAndYslopeTestnegX0Ypos0XY0 fail1 = TestCase $ assertEqual "fail 1=============================================" (True) (False) fail2 = TestCase $ assertEqual "fail 2============================================" (True) (False) {----------------------------------- set x/y values for target quadrant ------------------------------------------------ setYPolarityForQuadrant :: QuadrantAngle -> Double -> Double setYPolarityForQuadrant angle val = case getCurrentQuadrant angle of Quadrant1 -> negate val Quadrant2 -> val Quadrant3 -> val Quadrant4 -> negate val -} {-Moved setX/YPolarityForQuadrant into createCornerPoint. Leave these here for now, in case further testing is required. setQuadrant1YvalTest = TestCase $ assertEqual "set yval for quadrant1" (-1) (setYPolarityForQuadrant (Quadrant1Angle 1) 1 ) setQuadrant2YvalTest = TestCase $ assertEqual "set yval for quadrant2" (-1) (setYPolarityForQuadrant (Quadrant2Angle 1) 1 ) setQuadrant2Yval170Test = TestCase $ assertEqual "set yval for quadrant2 at 170" (1) (setYPolarityForQuadrant (Quadrant2Angle 170) 1 ) setQuadrant3Xval190Test = TestCase $ assertEqual "set xval for quadrant3 at 190" (-1) (setXPolarityForQuadrant (Quadrant3Angle 190) 1 ) -} {-getQuadrantAngle doen't need to be exported, but leave in case more testing is needed. getQuadrantAngleTest = TestCase $ assertEqual "getQuadrantAngleTest" (Quadrant1Angle 10) (getQuadrantAngle (Angle 10) ) getQuadrantAngleTest2 = TestCase $ assertEqual "getQuadrantAngleTest2" (Quadrant2Angle 80) (getQuadrantAngle (Angle 100) ) getQuadrantAngleTest3 = TestCase $ assertEqual "getQuadrantAngleTest3" (Quadrant2Angle 10) (getQuadrantAngle (Angle 170) ) getQuadrantAngleTest4 = TestCase $ assertEqual "getQuadrantAngleTest4" (Quadrant3Angle 10) (getQuadrantAngle (Angle 190) ) getQuadrantAngleTest5 = TestCase $ assertEqual "getQuadrantAngleTest5" (Quadrant3Angle 80) (getQuadrantAngle (Angle 260) ) getQuadrantAngleTest6 = TestCase $ assertEqual "getQuadrantAngleTest6" (Quadrant4Angle 80) (getQuadrantAngle (Angle 280) ) getQuadrantAngleTest7 = TestCase $ assertEqual "getQuadrantAngleTest7" (Quadrant4Angle 10) (getQuadrantAngle (Angle 350) ) -} {-----------------------------------Test the current z-slope ----------------------------- slopeAdjustedForVerticalAngle xSlope ySlope xyAngle -} {--------all the y angles without an x angle-------} slopeForXYAngleAndYslopeTestX0Ypos0XY0 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestX0Ypos0XY0" (PosSlope (0)) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (Angle 0) ) slopeForXYAngleAndYslopeTestnegX0Ypos0XY0 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestnegX0Ypos0XY0" (NegSlope (0)) (slopeAdjustedForVerticalAngle (NegXSlope 0) (PosYSlope 0) (Angle 0) ) slopeForXYAngleAndYslopeTestX0Ypos10XY10 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY10" (NegSlope (4.92403876506104)) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 5) (Angle 10) ) slopeForXYAngleAndYslopeTestXPos1Ypos10XY10 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY10" (NegSlope (9.67442935245515)) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 10) ) slopeForXYAngleAndYslopeTestXPos10Ypos1XY10 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY10" (PosSlope (0.7516740236570952)) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 10) ) {- x1 = sin(10) * 10 = 1.73648177667 pos y10 = cos(10) * 1 = 0.984807753012 pos y + x = 2.721289529682 so it is a PosSlope -} slopeForXYAngleAndYslopeTestXPos10Yneg1XY10 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos10Yneg1XY10" (PosSlope (2.721289529681511)) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 10) ) {- x1 = sin(10) * 1 = 0.173648177667 pos y10 = cos(10) * 10 = 9.84807753012 pos y + x = 10.021725707787 so it is a PosSlope -} slopeForXYAngleAndYslopeTestXPos1Yneg10XY10 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1Yneg10XY10" (PosSlope (10.02172570778901)) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 10) ) slopeForXYAngleAndYslopeTestXPos1YPos10XY80 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY80" (NegSlope 0.7516740236570961) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 80) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY80 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY80" (PosSlope 9.67442935245515) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 80) ) {- x1 = sin(80) * 10 = 9.84807753012 pos y10 = cos(80) * 1 = 0.173648177667 pos y + x = 10.021725707787 so it is a PosSlope -} slopeForXYAngleAndYslopeTestXPos10Yneg1XY80 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos10Yneg1XY80" (PosSlope (10.02172570778901)) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 80) ) {- x1 = sin(80) * 1 = 0.984807753012 pos y10 = cos(80) * 10 = 1.73648177667 pos y + x = 2.721289529682 so it is a PosSlope -} slopeForXYAngleAndYslopeTestXPos1Yneg10XY80 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1Yneg1XY80" (PosSlope 2.721289529681512) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 80) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY90 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY90" (PosSlope 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 90) ) slopeForXYAngleAndYslopeTestXPos1YPos10XY100 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY80" (PosSlope 2.721289529681512) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 100) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY100 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY80" (PosSlope 10.02172570778901) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 100) ) slopeForXYAngleAndYslopeTestXPos0YNeg10XY100 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos0YNeg10XY100" (NegSlope 1.7364817766693041) (slopeAdjustedForVerticalAngle (PosXSlope 0) (NegYSlope 10) (Angle 100) ) {- x1 = sin(100) * 1 = 0.984807753012 pos y10 = cos(80) * 10 = 1.73648177667 neg y - x = 0.751674023658 NegSlope -} slopeForXYAngleAndYslopeTestXPos1YNeg10XY100 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1YNeg10XY100" (NegSlope 0.7516740236570961) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 100) ) slopeForXYAngleAndYslopeTestXPos1YPos10XY170 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY80" (PosSlope 10.02172570778901) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 170) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY170 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestY80" (PosSlope 2.721289529681511) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 170) ) {- x1 = sin(10) * 0 = 0.173648177667 pos y10 = cos(10) * 10 = 9.84807753012 neg y - x = 9.84807753012 NegSlope -} slopeForXYAngleAndYslopeTestXPos0YNeg1XY170 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos0YNeg1XY170" (NegSlope 9.84807753012208) (slopeAdjustedForVerticalAngle (PosXSlope 0) (NegYSlope 10) (Angle 170) ) {- x1 = sin(10) * 1 = 0 pos y10 = cos(10) * 10 = 9.84807753012 neg y - x = 9.674429352453 NegSlope -} slopeForXYAngleAndYslopeTestXPos1YNeg1XY170 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos0YNeg1XY170" (NegSlope 9.67442935245515) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 170) ) slopeForXYAngleAndYslopeTestXPos1YPos10XY190 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1YPos10XY190" (PosSlope 9.67442935245515) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 190) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY190 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos10YPos1XY190" (NegSlope 0.7516740236570952) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 190) ) {- x1 = sin(10) * 1 = 0.173648177667 neg y10 = cos(10) * 10 = 9.84807753012 neg y + x = 10.021725707787 NegSlope continue here with testing -} slopeForXYAngleAndYslopeTestXPos1YNeg10XY190 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1YNeg10XY190" (NegSlope 10.02172570778901) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 190) ) slopeForXYAngleAndYslopeTestXPos1YPos10XY260 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1YPos10XY260" (PosSlope 0.7516740236570961) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 260) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY260 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos10YPos1XY260" (NegSlope 9.67442935245515) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 260) ) slopeForXYAngleAndYslopeTestXPos1YPos10XY280 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1YPos10XY280" (NegSlope 2.721289529681512) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 280) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY280 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos10YPos1XY280" (NegSlope 10.02172570778901) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 280) ) {- x1 = sin(80) * 1 = 0.984807753012 neg y10 = cos(80) * 10 = 1.73648177667 pos y - x = 0.751674023658 PosSlope 0.7516740236570961 -} slopeForXYAngleAndYslopeTestXPos1YNeg10XY280 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1YNeg10XY280" (PosSlope 0.7516740236570961) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 280) ) {- x1 = sin(80) * 10 = 9.84807753012 neg y10 = cos(80) * 1 = 0.173648177667 pos y - x = 9.674429352453 NegSlope 0.7516740236570961 -} slopeForXYAngleAndYslopeTestXPos10YNeg1XY280 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos10YNeg1XY280" (NegSlope 9.67442935245515) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 280) ) slopeForXYAngleAndYslopeTestXPos1YPos10XY350 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos1YPos10XY350" (NegSlope 10.02172570778901) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 350) ) slopeForXYAngleAndYslopeTestXPos10YPos1XY350 = TestCase $ assertEqual "slopeForXYAngleAndYslopeTestXPos10YPos1XY350" (NegSlope 2.721289529681511) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 350) ) {-test for radius adjustment on the xy plane, for various x and y slopes adjustRadiusForSlope :: Radius -> Slope -> Radius ===================================================================================================================================== non- exhaustive pattern -} {- adjustRadiusForSlopeTestRad10PosX10PosY0XY10 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10PosY0XY10" (DownRadius 9.857785663826117) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 10))) adjustRadiusForSlopeTestRad10PosX0PosY10XY10 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX0PosY10XY10" (UpRadius 9.999139447055672) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 10))) {- x1 = sin(10) * 1 = 0.173648177667 pos y10 = cos(10) * 10 = 9.84807753012 pos y + x = 10.02260159449 so it is a PosSlope adjustedRadius = Rad * cos(slope) = 10 * cos(10.02260159449) = 9.84739177006 UpRadius -} adjustRadiusForSlopeTestRad10PosX1NegY10XY10 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY10" (UpRadius 9.84741837407899) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 10))) {- x1 = sin(10) * 1 = 1.73648177667 pos y10 = cos(10) * 1 = 0.984807753012 pos y + x = 2.721289529682 so it is a PosSlope adjustedRadius = Rad * cos(slope) = 10 * cos(2.721289529682) = 9.9887230255 UpRadius -} adjustRadiusForSlopeTestRad10PosX10NegY1XY10 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10NegY1XY10" (UpRadius 9.988723025495544) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 10))) adjustRadiusForSlopeTestRad10PosX1PosY10XY80 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY80" (DownRadius 9.999139447055672) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 80))) adjustRadiusForSlopeTestRad10PosX1PosY10XY100 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY100" (UpRadius 9.988723025495544) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 100))) {- x1 = sin(80) * 10 = 9.84807753012 pos y10 = cos(80) * 1 = 0.173648177667 neg y + x = 9.674429352453 so it is a PosXYSlope adjustedRadius = Rad * cos(slope) = 10 * cos(9.674429352453) = 9.85778566383 UpRadius -} adjustRadiusForSlopeTestRad10PosX10NegY1XY100 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10NegY1XY100" (UpRadius 9.857785663826117) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 100))) {- x1 = sin(80) * 1 = 0.984807753012 pos y10 = cos(80) * 10 = 1.73648177667 neg y + x = 0.751674023658 NegSlope adjustedRadius = Rad * cos(slope) = 10 * cos(0.751674023658) = 9.99913944706 DownRadius -} adjustRadiusForSlopeTestRad10PosX1NegY10XY100 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1NegY10XY100" (DownRadius 9.999139447055672) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 100))) adjustRadiusForSlopeTestRad10PosX1PosY10XY170 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY170" (UpRadius 9.84741837407899) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 170))) {-((sinDegrees xyAngle) * xSlope) - ((cosDegrees xyAngle) * ySlope) x1 = sin(10) * 10 = 1.73648177667 pos y10 = cos(10) * 1 = 0.984807753012 neg y - x = 0.751674023658 PosXYSlope adjustedRadius = Rad * cos(slope) = 10 * cos(0.751674023658) = 9.99913944706 UpRadius -} adjustRadiusForSlopeTestRad10PosX10NegY1XY170 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10NegY1XY170" (UpRadius 9.999139447055672) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 170))) {- x1 = sin(10) * 10 = 1.73648177667 pos y10 = cos(10) * 1 = 0.984807753012 neg y - x = 9.674429352453 NegSlope adjustedRadius = Rad * cos(slope) = 10 * cos(9.674429352453) = 9.85778566383 DownRadius -} adjustRadiusForSlopeTestRad10PosX1NegY10XY170 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1NegY10XY170" (DownRadius 9.857785663826117) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 170))) {- x1 = sin(10) * 1 = 0.17452406437 neg y10 = cos(10) * 10 = 9.84807753012 pos y - x = 9.67355346575 so it is a PosXYSlope adjustedRadius = Rad * cos(slope) = 10 * cos(9.67355346575) = 9.857785663826117 UpRadius -} adjustRadiusForSlopeTestRad10PosX1PosY10XY190 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY190" (UpRadius 9.857785663826117) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 190))) {- x10 = sin(10) * 10 = 1.73648177667 neg as in 3rd quad y1 - cos(10) * 1 = 0.984807753012 y - x = -0.751674023658 so it is a NegSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos(0.751674023658) = 9.999139447055672 DownRadius as it was a NegSlope -} adjustRadiusForSlopeTestRad10PosX10PosY1XY190 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10PosY1XY190" (DownRadius 9.999139447055672) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 190))) {- x1 = sin(10) * 1 = 0.173648177667 neg y10 = cos(10) * 10 = 9.84807753012 neg y - x = 10.021725707787 so it is a NegSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos( 10.021725707787) = 9.84741837408 DownRadius as it was a NegSlope -} adjustRadiusForSlopeTestRad10PosX1NegY1oXY190 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10PosY1XY190" (DownRadius 9.84741837407899) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (Angle 190))) {- x10 = sin(10) * 10 = 1.73648177667 neg as in 3rd quad y1 - cos(10) * 1 = 0.984807753012 neg as in 3rd quad y + x = -2.721289529682 so it is a NegSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos(2.721289529682) = 9.9887230255 DownRadius as it was a NegSlope -} adjustRadiusForSlopeTestRad10PosX10NegY1XY190 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10NegY1XY190" (DownRadius 9.988723025495544) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (NegYSlope 1) (Angle 190))) {- x1 = sin(80) * 1 = 0.984807753012 neg as it is in 3rd quad y10 = cos(80) * 10 = 1.73648177667 pos as it is in 3rd quad y - x = 0.751674023658 posXYSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos(0.751674023658) = 9.999139447055672 UpRadius as it was a PosXYSlope -} adjustRadiusForSlopeTestRad10PosX1PosY10XY260 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY260" (UpRadius 9.999139447055672) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 260))) {- x10 = sin(80) * 10 = 9.84807753012 neg as it is in 3rd quad y1 = cos(80) * 1 = 0.173648177667 pos as it is in 3rd quad y - x = 9.674429352453 NegSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos(9.674429352453) = 9.85778566383 DownRadius as it was a PosSlope -} adjustRadiusForSlopeTestRad10PosX10PosY1XY260 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10PosY1XY260" (DownRadius 9.857785663826117) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 260))) {- x1 = sin(80) * 1 = 0.984807753012 neg as it is in 4 quad y10 = cos(80) * 10 = 1.73648177667 neg as it is in 4 quad y + x = 2.721289529682 NegSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos(2.721289529682) = 9.9887230255 DownRadius as it was a NegSlope -} adjustRadiusForSlopeTestRad10PosX1PosY10XY280 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY280" (DownRadius 9.988723025495544) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 280))) {- x10 = sin(80) * 10 = 9.84807753012 neg as it is in 4 quad y1 = cos(80) * 1 = 0.173648177667 neg as it is in 4 quad y + x = 10.021725707787 NegSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos(10.021725707787) = 9.84741837408 DownRadius as it was a NegSlope -} adjustRadiusForSlopeTestRad10PosX10PosY1XY280 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX10PosY1XY280" (DownRadius 9.84741837407899) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (Angle 280))) {- x1 = sin(10) * 1 = 0.173648177667 neg as it is in 4 quad y10 = cos(10) * 10 = 9.84807753012 neg as it is in 4 quad y + x = 10.021725707787 NegSlope adjustedRadius = Rad * cos(xySlope) = 10 * cos(10.021725707787) = 9.84741837408 DownRadius as it was a NegSlope -} adjustRadiusForSlopeTestRad10PosX1PosY10XY350 = TestCase $ assertEqual "adjustRadiusForSlopeTestRad10PosX1PosY10XY350" (DownRadius 9.84741837407899) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (Angle 350))) -} {--------------------------------------------Create CornerPonts and test them.----------------------------------------------------------} {-This is a bottom front right corner with no z-slope. singleF4PointTest = TestCase $ assertEqual --test values: xyAngle 0; xSlope 0, ySlope 0, radius 18 "the bottom right front corner using Equal instance" ( F4 ( Point 0 (-18) 0 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0})18 0 0 0 ) createCornerPoint :: (Point-> CornerPoints) -> Point -> Radius -> QuadrantAngle -> Slope -> CornerPoints -} {- createFrontCornerTest = TestCase $ assertEqual "recreate the front corner to see what is wrong with my vertical faces" (F3 (Point 1 (-6.123233995736766e-17) 50)) (createCornerPoint (F3) (Point{x_axis=0, y_axis=0, z_axis=50}) (Radius 1) (adjustRadiusForSlope (Radius 1) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 90))) (Angle 90)--(xyQuadrantAngle 90) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 90)) ) -} --was simplified createFrontCornerTest = TestCase $ assertEqual "recreate the front corner to see what is wrong with my vertical faces" (F3 (Point 1 (-6.123233995736766e-17) 50)) (createCornerPoint (F3) (Point{x_axis=0, y_axis=0, z_axis=50}) (Radius 1) --(adjustRadiusForSlope (Radius 1) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 90))) (Angle 90)--(xyQuadrantAngle 90) (PosXSlope 0) (PosYSlope 0) --(slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 90)) ) {- createCornerPointTestR10PosX0PosY0XY10 = TestCase $ assertEqual "createCornerPointTestR10PosX0PosY0XY10 this is the first non-exhaust failure" ( F4 ( Point 1.7364817766693033 (-9.84807753012208) 0 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 10))) (Angle 10)--(xyQuadrantAngle 10) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 10)) ) -} --was simplified createCornerPointTestR10PosX0PosY0XY10 = TestCase $ assertEqual "createCornerPointTestR10PosX0PosY0XY10 this is the first non-exhaust failure" ( F4 ( Point 1.7364817766693033 (-9.84807753012208) 0 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) --(adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 10))) (Angle 10)--(xyQuadrantAngle 10) (PosXSlope 0) (PosYSlope 0) --(slopeAdjustedForVerticalAngle (PosXSlope 0) (PosYSlope 0) (xyQuadrantAngle 10)) ) {- z = radius * sin(xySlope) = 10 * sin(9.67442935245515) = 1.68049451236 -} {- createCornerPointTestR10PosX0PosY10XY10 = TestCase $ assertEqual "createCornerPointTestR10PosX0PosY10XY10" ( F4 ( Point 1.7117865163545964 (-9.708023749268555) (-1.6804945123576784) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 10))) (Angle 10)--(xyQuadrantAngle 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 10)) ) -} --was simplified createCornerPointTestR10PosX0PosY10XY10 = TestCase $ assertEqual "createCornerPointTestR10PosX0PosY10XY10" ( F4 ( Point 1.7117865163545964 (-9.708023749268555) (-1.6804945123576784) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (Angle 10)--(xyQuadrantAngle 10) (PosXSlope 1) (PosYSlope 10) ) {- z = radius * sin(xySlope) = 10 * sin(9.67442935245515) = -0.13118810287215432 this is just assumed, as I did not have a corresponding xySlope test. If all the others work out though, I will ass-u-me this is right. -} {- createCornerPointTestR10PosX0PosY10XY80 = TestCase $ assertEqual "createCornerPointTestR10PosX0PosY10XY80" ( F4 ( Point 9.847230050910628 (-1.7363323432187356) (-0.13118810287215432) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 80))) (Angle 80)--(xyQuadrantAngle 80) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 80)) ) -} --was simplified createCornerPointTestR10PosX0PosY10XY80 = TestCase $ assertEqual "createCornerPointTestR10PosX0PosY10XY80" ( F4 ( Point 9.847230050910628 (-1.7363323432187356) (-0.13118810287215432) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (Angle 80)--(xyQuadrantAngle 80) (PosXSlope 1) (PosYSlope 10) ) {- z = radius * sin(xySlope) = 10 * sin( 2.721289529681512) = 0.47477607347 -} {- createCornerPointTestR10PosX1PosY10XY100 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY100" ( F4 ( Point 9.83697187819957 (1.734523550597009) (0.47477607346532197) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 100))) (Angle 100)--(Quadrant2Angle 100)--(xyQuadrantAngle 100) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 100)) ) -} --was simplified createCornerPointTestR10PosX1PosY10XY100 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY100" ( F4 ( Point 9.83697187819957 (1.734523550597009) (0.47477607346532197) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (Angle 100)--(Quadrant2Angle 100)--(xyQuadrantAngle 100) (PosXSlope 1) (PosYSlope 10) ) createCornerPointTestR10PosX1NegY10XY170 = TestCase $ assertEqual "createCornerPointTestR10PosX1NegY10XY170 and now this one is failing" ( F4 ( Point 1.7117865163545964 (9.708023749268555) (-1.6804945123576784) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) --(adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (xyQuadrantAngle 170))) (Angle 170)--(xyQuadrantAngle 170) --(slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (xyQuadrantAngle 170)) (PosXSlope 1) (NegYSlope 10) ) {- createCornerPointTestR10PosX1PosY10XY170 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY170" ( F4 ( Point 1.7099862553826626 (9.69781396194786) 1.740215896333419 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 170))) (Angle 170)--(xyQuadrantAngle 170) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 170)) ) -} --was simplified createCornerPointTestR10PosX1PosY10XY170 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY170" ( F4 ( Point 1.7099862553826626 (9.69781396194786) 1.740215896333419 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (Angle 170)--(xyQuadrantAngle 170) (PosXSlope 1) (PosYSlope 10) ) {- z = radius * sin(xySlope) = 10 * sin() = -} {- createCornerPointTestR10PosX10PosY1XY170 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY170" ( F4 ( Point 1.734523550597008 (9.83697187819957) 0.47477607346532175 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (xyQuadrantAngle 170))) (Angle 170)--(xyQuadrantAngle 170) (slopeAdjustedForVerticalAngle (PosXSlope 10) (PosYSlope 1) (xyQuadrantAngle 170)) ) -} --was simplified createCornerPointTestR10PosX10PosY1XY170 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY170" ( F4 ( Point 1.734523550597008 (9.83697187819957) 0.47477607346532175 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) (Angle 170)--(xyQuadrantAngle 170) (PosXSlope 10) (PosYSlope 1) ) --was simplified createCornerPointTestR10PosX1PosY10XY190 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY190" ( F4 ( Point (-1.7117865163545964) 9.708023749268555 1.6804945123576784 )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) --(adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 190))) (Angle 190)--(xyQuadrantAngle 190) --(slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 190)) (PosXSlope 1) (PosYSlope 10) ) --was simplified createCornerPointTestR10PosX1NegY10XY190 = TestCase $ assertEqual "createCornerPointTestR10PosX1NegY10XY190 fail 0" ( F4 ( Point (-1.7099862553826626) 9.69781396194786 (-1.740215896333419) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) --(adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (xyQuadrantAngle 190))) (Angle 190)--(xyQuadrantAngle 190) --(slopeAdjustedForVerticalAngle (PosXSlope 1) (NegYSlope 10) (xyQuadrantAngle 190)) (PosXSlope 1) (NegYSlope 10) ) --was simplified createCornerPointTestR10PosX1PosY10XY260 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY260" ( F4 ( Point (-9.847230050910628) (1.7363323432187356) (0.13118810287215432) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) --(adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 260))) (Angle 260)--(xyQuadrantAngle 260) --(slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 260)) (PosXSlope 1) (PosYSlope 10) ) --was simplified createCornerPointTestR10PosX1PosY10XY280 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY280 fail 280" ( F4 ( Point (-9.83697187819957) (-1.734523550597009) (-0.47477607346532197) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) --(adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 280))) (Angle 280)--(xyQuadrantAngle 280) --(slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 280)) (PosXSlope 1) (PosYSlope 10) ) --was simplified createCornerPointTestR10PosX1PosY10XY350 = TestCase $ assertEqual "createCornerPointTestR10PosX1PosY10XY350 fail 350" ( F4 ( Point (-1.7099862553826626) (-9.69781396194786) (-1.740215896333419) )) (createCornerPoint (F4) (Point{x_axis=0, y_axis=0, z_axis=0}) (Radius 10) --(adjustRadiusForSlope (Radius 10) (slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 350))) (Angle 350)--(xyQuadrantAngle 350) --(slopeAdjustedForVerticalAngle (PosXSlope 1) (PosYSlope 10) (xyQuadrantAngle 350)) (PosXSlope 1) (PosYSlope 10) )
heathweiss/Tricad
src/Tests/MathPolarTest.hs
gpl-2.0
36,239
0
12
5,099
3,487
1,825
1,662
321
1
{-# language TemplateHaskell #-} {-# language DeriveDataTypeable #-} {-# language FlexibleInstances #-} {-# language MultiParamTypeClasses #-} {-# language DisambiguateRecordFields #-} module DPLLT.Top where import DPLLT.Data import DPLLT.Trace -- import DPLL.Pattern -- import DPLL.Roll import Challenger.Partial import Autolib.ToDoc import Autolib.Reader import Autolib.Reporter import Inter.Types hiding ( Var ) import Inter.Quiz import Data.Typeable import System.Random data DPLLT = DPLLT deriving Typeable data Instance = Instance { modus :: Modus , cnf :: CNF , max_solution_length :: Maybe Int } deriving Typeable instance0 :: Instance instance0 = Instance { modus = modus0 , cnf = read "[[p,q,r],[!p, 0 <= x+y ],[q,!r],[p,!q,r, 0 <= -x],[!q,r]]" , max_solution_length = Nothing } derives [makeReader, makeToDoc] [''DPLLT, ''Instance ] instance Show DPLLT where show = render . toDoc instance OrderScore DPLLT where scoringOrder _ = None instance Partial DPLLT Instance [Step] where describe _ i = vcat [ text "Gesucht ist eine vollständige DPLLT-Rechnung" </> case max_solution_length i of Nothing -> empty Just l -> text "mit höchstens" <+> toDoc l <+> text "Schritten" , text "mit diesen Eigenschaften:" </> toDoc (DPLLT.Top.modus i) , text "für diese Formel:" </> toDoc (cnf i) ] initial _ i = let p = case clause_learning $ DPLLT.Top.modus i of True -> read "Backjump 1 [ p, ! q ]" False -> Backtrack in read "[ Decide ! p, Propagate {use = Boolean [p, !q], obtain = !q }, Conflict Theory]" ++ [p] ++ read "[ SAT ]" partial _ i steps = do DPLLT.Trace.execute (DPLLT.Top.modus i) (cnf i) steps return () total _ i steps = do case max_solution_length i of Nothing -> return () Just l -> when (length steps > l) $ reject $ text "Die Anzahl der Schritte" <+> parens (toDoc $ length steps) <+> text "ist größer als" <+> toDoc l case reverse steps of SAT : _ -> return () UNSAT : _ -> return () _ -> reject $ text "die Rechnung soll vollständig sein (mit SAT oder UNSAT enden)" make_fixed = direct DPLLT instance0 {- instance Generator DPLLT Config ( Instance, [Step] ) where generator p conf key = do (c, s, o) <- roll conf return ( Instance { modus = DPLLT.Roll.modus conf , max_solution_length = case require_max_solution_length conf of DPLLTT.Roll.No -> Nothing Yes { allow_extra = e } -> Just $ o + e , cnf = c } , s ) instance Project DPLLT ( Instance, [Step] ) Instance where project p (c, s) = c make_quiz = quiz DPLLT config0 -}
marcellussiegburg/autotool
collection/src/DPLLT/Top.hs
gpl-2.0
3,010
0
19
971
596
306
290
59
1
{-# LANGUAGE BangPatterns #-} -- | Miscellaneous functions and types that belong to no other module module Data.VPlan.Util ( -- * Group and Monoid functions -- Note: The functions for monoids/groups in this module are not really efficient, but -- that shouldn't matter most of the time. gquot , gmod , gquotMod , glcm ) where import Control.Lens import Control.Monad import Data.Group import Data.Monoid -- TODO: Maybe a better name for the following 3 functions? -- Suggestions: gdiv: howMany -- gdivMod: ??? -- gmod: rest?, ??? -- | This is the inverse of 'timesN'. It calculates how many times a given -- group object fits into another object of the same group. It's basically -- a 'quot' function that works on arbitrary groups. -- -- Examples: -- -- >>> (Sum 11) `gmod` (Sum 2) (Sum 11) -- 5 -- -- >>> (Product 27) `gmod` (Product 3) -- 3 gquot :: (Ord a, Group a) => a -> a -> Int gquot xs x = fst $ xs `gquotMod` x -- | A version of divMod that works for arbitrary groups. gquotMod :: (Ord a, Group a) => a -> a -> (Int, a) gquotMod xs x | xs < mempty = over _1 negate $ over _2 (\r -> if r /= mempty then x <> invert r else r) $ gquotMod (invert xs) x | x < mempty = over _1 negate $ over _2 (mappend x) $ gquotMod xs (invert x) | x > xs = (0,xs) | x == xs = (1,mempty) | otherwise = over _1 (+ getSum steps) $ (xs <> invert half) `gquotMod` x where (steps, half) = until moreThanHalf (join mappend) (Sum 1, x) moreThanHalf (_,a) = (xs <> invert a) < a -- | This is like mod, but for arbitrary groups. -- -- Examples: -- -- >>> (Sum 11) `gmod` (Sum 2) -- Sum 1 -- -- >>> (Product 29) `gmod` (Product $ 3 % 1) -- Product {getProduct = 29 % 27} gmod :: (Ord a, Group a) => a -> a -> a gmod xs x = snd $ xs `gquotMod` x -- | This is like lcm, but for arbitrary monoids. -- -- Examples: -- -- >>> (Sum 6) `glcm` (Sum 4) -- Sum 12 -- -- >>> (Product 4) `glcm` (Product 8) -- Product 64 -- = Product (4 * 4 * 4) = Product (8 * 8) -- glcm :: (Ord a, Monoid a) => a -> a -> a glcm a' b' = go a' b' where go !a !b | a > b = go a (b <> b') | a < b = go (a <> a') b | otherwise = a
bennofs/vplan
src/Data/VPlan/Util.hs
gpl-3.0
2,256
0
13
626
591
325
266
30
2
module Math.Structure.Multiplicative.Semigroup where import Prelude hiding ( (*), (/), recip, (^), (^^) ) import Numeric.Natural ( Natural(..) ) import Math.Structure.Additive.DecidableZero import Math.Structure.Multiplicative.Magma class MultiplicativeMagma a => MultiplicativeSemigroup a where pow1p :: Natural -> a -> a pow1p = pow1pStd pow1pStd :: MultiplicativeSemigroup a => Natural -> a -> a pow1pStd n a = (!! fromIntegral n) $ iterate (*a) a
martinra/algebraic-structures
src/Math/Structure/Multiplicative/Semigroup.hs
gpl-3.0
473
2
8
82
149
90
59
11
1
{- This file is part of HNH. HNH 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. HNH 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 HNH. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Francisco Ferreira -} module GenerateConstraints ( Constraint , getConstraints ) where import Syntax import TypeUtils(getType, getPatType, getAltType, getAltPatTypes) import Control.Monad.State(execState, State, get, put) type Constraint = (Type, Type, Declaration) getConstraints :: Declaration -> [Constraint] getConstraints d = execState (processDecl d) [] addConstraint :: Declaration -> Type -> Type -> State [Constraint] () addConstraint d t1 t2 = do st <- get if t1 == t2 then return () else put ((t1, t2, d):st) processDecls :: [Declaration] -> State [Constraint] () processDecls decls = do mapM processDecl decls; return () processDecl d@(PatBindDcl pat e) = do processExp d e addConstraint d (getPatType pat) (getType e) processDecl decl = return () processExp d (ParensExp e t) = do processExp d e addConstraint d t (getType e) processExp d (TupleExp es t) = do mapM (processExp d) es addConstraint d t (TupleType (map getType es)) processExp d (FExp e1 e2 t) = do processExp d e1 processExp d e2 addConstraint d (getType e1) (FunType (getType e2) t) processExp d (LambdaExp ps e t) = do processExp d e addConstraint d t ts' where ts = map getPatType ps ts'= foldr FunType (getType e) ts processExp d (LetExp decls e t) = do processDecls decls processExp d e addConstraint d t (getType e) processExp d (IfExp e1 e2 e3 t) = do processExp d e1 processExp d e2 processExp d e3 addConstraint d (getType e2) (getType e3) addConstraint d t (getType e2) addConstraint d (getType e1) (DataType "Bool" []) processExp d (CaseExp es alts t) = do mapM (processExp d) es mapM (processAlt d t (map getType es)) alts -- all the exps in alts must have the same type allSameType d (map getAltType alts) -- the alt exps should be the same type as the case addConstraint d t (getAltType (head alts)) -- all the patterns in the alts should have the same type mapM (allSameType d) (rows2cols (map getAltPatTypes alts)) -- the exps and the patterns should have the same type mapM (allSameType d) (rows2cols [(map getType es) ,(getAltPatTypes (head alts))]) return () processExp d (ListExp es t) = do mapM (processExp d) es allSameType d (map getType es) case es of [] -> addConstraint d t (DataType "List" [VarType "a"]) _ -> addConstraint d t (DataType "List" [(getType (head es))]) processExp d e = return () processAlt d caseT ts (Alternative ps e) = do processExp d e mapM (\(t, p)-> do {-addConstraint d caseT (getPatType p)-} return $ addConstraint d t (getPatType p)) (zip ts ps) allSameType d (t1:t2:ts) = do addConstraint d t1 t2 allSameType d (t2:ts) allSameType d _ = return () {- rows2cols takes some lists, and returns a list of the list of the first element of each list and the list of the second element of each list etc... -} rows2cols :: [[ a ]] -> [[ a ]] rows2cols t = if (length . head $ t) > 1 then (map head t):rows2cols (map tail t) else [concat t]
fferreira/hnh
GenerateConstraints.hs
gpl-3.0
4,008
0
17
1,121
1,230
602
628
78
2
{-# LANGUAGE TemplateHaskell #-} module Types where import Control.Lens data LCMConfig = LCMConfig { _limit :: Integer } data LCMState = LCMState { _currentprod :: Integer , _counter :: Integer } $(makeLenses ''LCMConfig) $(makeLenses ''LCMState)
ignuki/projecteuler
5/Types.hs
gpl-3.0
262
0
8
50
70
39
31
10
0
func :: ((a, b, c), (a, b, c), (a, b, c))
lspitzner/brittany
data/Test27.hs
agpl-3.0
42
0
6
11
42
27
15
1
0
module HEP.Jet.FastJet.Class.TNamed ( TNamed(..) , ITNamed(..) , upcastTNamed , newTNamed ) where -- import HEP.Jet.FastJet.Class.Interface -- import HEP.Jet.FastJet.Class.Implementation () import HEP.Jet.FastJet.Class.TNamed.RawType import HEP.Jet.FastJet.Class.TNamed.Interface import HEP.Jet.FastJet.Class.TNamed.Implementation
wavewave/HFastJet
oldsrc/HEP/Jet/FastJet/Class/TNamed.hs
lgpl-2.1
349
0
5
43
60
45
15
9
0
{-# LANGUAGE OverloadedStrings #-} module XTag.Model.Type where import Data.Aeson import qualified Data.ByteString.UTF8 as C type BookId = C.ByteString data Book = Book { bookId :: C.ByteString , bookName :: C.ByteString , bookPageCount :: Integer } deriving Show data BookIndex = BookIndex { index :: Integer , total :: Integer , books :: [Book] } deriving (Show) instance ToJSON C.ByteString where toJSON str = toJSON $ C.toString str instance ToJSON Book where toJSON (Book id name total) = object ["id" .= id, "name" .= name, "total" .= total] instance ToJSON BookIndex where toJSON (BookIndex index total books) = object ["index" .= index, "total" .= total, "items" .= books]
yeyan/xtag
src/XTag/Model/Type.hs
lgpl-3.0
788
0
9
214
228
130
98
24
0