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 RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.BitTorrent.Tracker.TestData ( TrackerEntry (..) , isUdpTracker , isHttpTracker , trackers , badTracker ) where import Data.Maybe import Data.String import Network.URI import Data.Torrent data TrackerEntry = TrackerEntry { -- | May be used to show tracker name in test suite report. trackerName :: String -- | Announce uri of the tracker. , trackerURI :: URI -- | Some trackers abadoned, so don't even try to announce. , tryAnnounce :: Bool -- | Some trackers do not support scraping, so we should not even -- try to scrape them. , tryScraping :: Bool -- | Some trackers allow , hashList :: Maybe [InfoHash] } isUdpTracker :: TrackerEntry -> Bool isUdpTracker TrackerEntry {..} = uriScheme trackerURI == "udp:" isHttpTracker :: TrackerEntry -> Bool isHttpTracker TrackerEntry {..} = uriScheme trackerURI == "http:" || uriScheme trackerURI == "https:" instance IsString URI where fromString str = fromMaybe err $ parseURI str where err = error $ "fromString: bad URI " ++ show str trackerEntry :: URI -> TrackerEntry trackerEntry uri = TrackerEntry { trackerName = maybe "<unknown>" uriRegName (uriAuthority uri) , trackerURI = uri , tryAnnounce = False , tryScraping = False , hashList = Nothing } announceOnly :: String -> URI -> TrackerEntry announceOnly name uri = (trackerEntry uri) { trackerName = name , tryAnnounce = True } announceScrape :: String -> URI -> TrackerEntry announceScrape name uri = (announceOnly name uri) { tryScraping = True } notWorking :: String -> URI -> TrackerEntry notWorking name uri = (trackerEntry uri) { trackerName = name } trackers :: [TrackerEntry] trackers = [ (announceOnly "LinuxTracker" "http://linuxtracker.org:2710/00000000000000000000000000000000/announce") { hashList = Just ["1c82a95b9e02bf3db4183da072ad3ef656aacf0e"] -- debian 7 } , (announceScrape "Arch" "http://tracker.archlinux.org:6969/announce") { hashList = Just ["bc9ae647a3e6c3636de58535dd3f6360ce9f4621"] } , notWorking "rarbg" "udp://9.rarbg.com:2710/announce" , announceScrape "OpenBitTorrent" "udp://tracker.openbittorrent.com:80/announce" , announceScrape "PublicBT" "udp://tracker.publicbt.com:80/announce" , notWorking "OpenBitTorrent" "http://tracker.openbittorrent.com:80/announce" , notWorking "PublicBT" "http://tracker.publicbt.com:80/announce" ] badTracker :: TrackerEntry badTracker = notWorking "rarbg" "udp://9.rarbg.com:2710/announce"
DavidAlphaFox/bittorrent
tests/Network/BitTorrent/Tracker/TestData.hs
bsd-3-clause
2,679
0
10
550
517
290
227
57
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="it-IT"> <title>DOM XSS Active Scan Rule | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
0xkasun/security-tools
src/org/zaproxy/zap/extension/domxss/resources/help_it_IT/helpset_it_IT.hs
apache-2.0
986
80
66
163
421
213
208
-1
-1
------------------------------------------------------------------------------- -- | -- Module : System.Hardware.Haskino.Test.ExprWord8 -- Copyright : (c) University of Kansas -- License : BSD3 -- Stability : experimental -- -- Quick Check tests for Expressions returning a Expr Word8 ------------------------------------------------------------------------------- {-# LANGUAGE GADTs #-} module System.Hardware.Haskino.Test.IfThenElseWord8 where import Prelude hiding ( quotRem, divMod, quot, rem, div, mod, properFraction, fromInteger, toInteger, (<*) ) import qualified Prelude as P import System.Hardware.Haskino import Data.Boolean import Data.Boolean.Numbers import Data.Boolean.Bits import Data.Int import Data.Word import Test.QuickCheck hiding ((.&.)) import Test.QuickCheck.Monadic litEval8 :: Expr Word8 -> Word8 litEval8 (LitW8 w) = w prop_ifthenelse :: ArduinoConnection -> Word8 -> Word8 -> Property prop_ifthenelse c x y = monadicIO $ do let local = if (x < y) then x else y remote <- run $ send c $ do v <- ifThenElseE ((lit x) <* (lit y)) (return $ lit x) (return $ lit y) return v assert (local == litEval8 remote) main :: IO () main = do conn <- openArduino False "/dev/cu.usbmodem1421" print "IfThenElse Tests:" quickCheck (prop_ifthenelse conn) closeArduino conn
ku-fpg/kansas-amber
tests/ExprTests/IfThenElseWord8.hs
bsd-3-clause
1,353
0
17
239
342
190
152
28
2
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} module Database.Persist.Sql.Migration ( parseMigration , parseMigration' , printMigration , showMigration , getMigration , runMigration , runMigrationSilent , runMigrationUnsafe , migrate ) where import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Trans.Class (MonadTrans (..)) import Control.Monad.IO.Class import Control.Monad.Trans.Writer import Control.Monad.Trans.Reader (ReaderT (..), ask) import Control.Monad (liftM, unless) import Data.Text (Text, unpack, snoc, isPrefixOf, pack) import qualified Data.Text.IO import System.IO import System.IO.Silently (hSilence) import Control.Monad.Trans.Control (liftBaseOp_) import Database.Persist.Sql.Types import Database.Persist.Sql.Raw import Database.Persist.Types allSql :: CautiousMigration -> [Sql] allSql = map snd safeSql :: CautiousMigration -> [Sql] safeSql = allSql . filter (not . fst) parseMigration :: MonadIO m => Migration -> ReaderT SqlBackend m (Either [Text] CautiousMigration) parseMigration = liftIOReader . liftM go . runWriterT . execWriterT where go ([], sql) = Right sql go (errs, _) = Left errs liftIOReader (ReaderT m) = ReaderT $ liftIO . m -- like parseMigration, but call error or return the CautiousMigration parseMigration' :: MonadIO m => Migration -> ReaderT SqlBackend m (CautiousMigration) parseMigration' m = do x <- parseMigration m case x of Left errs -> error $ unlines $ map unpack errs Right sql -> return sql printMigration :: MonadIO m => Migration -> ReaderT SqlBackend m () printMigration m = showMigration m >>= mapM_ (liftIO . Data.Text.IO.putStrLn) showMigration :: MonadIO m => Migration -> ReaderT SqlBackend m [Text] showMigration m = map (flip snoc ';') `liftM` getMigration m getMigration :: MonadIO m => Migration -> ReaderT SqlBackend m [Sql] getMigration m = do mig <- parseMigration' m return $ allSql mig runMigration :: MonadIO m => Migration -> ReaderT SqlBackend m () runMigration m = runMigration' m False >> return () -- | Same as 'runMigration', but returns a list of the SQL commands executed -- instead of printing them to stderr. runMigrationSilent :: (MonadBaseControl IO m, MonadIO m) => Migration -> ReaderT SqlBackend m [Text] runMigrationSilent m = liftBaseOp_ (hSilence [stderr]) $ runMigration' m True runMigration' :: MonadIO m => Migration -> Bool -- ^ is silent? -> ReaderT SqlBackend m [Text] runMigration' m silent = do mig <- parseMigration' m if any fst mig then error $ concat [ "\n\nDatabase migration: manual intervention required.\n" , "The unsafe actions are prefixed by '***' below:\n\n" , unlines $ map displayMigration mig ] else mapM (executeMigrate silent) $ sortMigrations $ safeSql mig where displayMigration :: (Bool, Sql) -> String displayMigration (True, s) = "*** " ++ unpack s ++ ";" displayMigration (False, s) = " " ++ unpack s ++ ";" runMigrationUnsafe :: MonadIO m => Migration -> ReaderT SqlBackend m () runMigrationUnsafe m = do mig <- parseMigration' m mapM_ (executeMigrate False) $ sortMigrations $ allSql mig executeMigrate :: MonadIO m => Bool -> Text -> ReaderT SqlBackend m Text executeMigrate silent s = do unless silent $ liftIO $ hPutStrLn stderr $ "Migrating: " ++ unpack s rawExecute s [] return s -- | Sort the alter DB statements so tables are created before constraints are -- added. sortMigrations :: [Sql] -> [Sql] sortMigrations x = filter isCreate x ++ filter (not . isCreate) x where -- Note the use of lower-case e. This (hack) allows backends to explicitly -- choose to have this special sorting applied. isCreate t = pack "CREATe " `isPrefixOf` t migrate :: [EntityDef] -> EntityDef -> Migration migrate allDefs val = do conn <- lift $ lift ask res <- liftIO $ connMigrateSql conn allDefs (getStmtConn conn) val either tell (lift . tell) res
mitchellwrosen/persistent
persistent/Database/Persist/Sql/Migration.hs
mit
4,181
0
12
955
1,193
624
569
97
3
-- (c) The FFI task force, 2001 -- -- Provides fixed sized, unsigned integral types module Word ( Word8, Word16, Word32, Word64 ) where -- Constraints applying to all of the following types: -- -- * For any types, all arithmetic is performed modulo 2^n, where n is the -- number of bit width of the type. -- -- * The rules that hold for Enum instances over a bounded type such as Int -- (see the section of the Haskell report dealing with arithmetic sequences) -- also hold for the Enum instances over the various Int types defined here. -- 8 bit natural numbers -- data Word8 = 0 | 1 | ... | 255 deriving (Eq, Ord, Enum, Bounded, Show, Read) instance Num Word8 where ... instance Real Word8 where ... instance Integral Word8 where ... instance Ix Word8 where ... -- 16 bit natural numbers -- data Word16 = 0 | 1 | ... | 65535 deriving (Eq, Ord, Enum, Bounded, Show, Read) instance Num Word16 where ... instance Real Word16 where ... instance Integral Word16 where ... instance Ix Word16 where ... -- 32 bit natural numbers -- data Word32 = 0 | 1 | ... | 4294967295 deriving (Eq, Ord, Enum, Bounded, Show, Read) instance Num Word32 where ... instance Real Word32 where ... instance Integral Word32 where ... instance Ix Word32 where ... -- 64 bit natural numbers -- data Word64 = 0 | 1 | ... | 18446744073709551615 deriving (Eq, Ord, Enum, Bounded, Show, Read) instance Num Word64 where ... instance Real Word64 where ... instance Integral Word64 where ... instance Ix Word64 where ...
phischu/gtk2hs
tools/c2hs/doc/c2hs/lib/Word.hs
lgpl-3.0
1,583
17
9
369
310
188
122
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="da-DK"> <title>Getting started Guide</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>SΓΈg</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/gettingStarted/src/main/javahelp/org/zaproxy/zap/extension/gettingStarted/resources/help_da_DK/helpset_da_DK.hs
apache-2.0
964
77
66
157
412
208
204
-1
-1
module A2 where import C2 import D2 sumSq xs = ((sum (map (sq sq_f) xs)) + (sumSquares xs)) + (sumSquares1 xs) sq_f_2 = 2 main = sumSq [1 .. 4]
kmate/HaRe
old/testing/addOneParameter/A2AST.hs
bsd-3-clause
167
0
13
53
80
44
36
8
1
{-# LANGUAGE BangPatterns, CPP, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- -- The register allocator -- -- (c) The University of Glasgow 2004 -- ----------------------------------------------------------------------------- {- The algorithm is roughly: 1) Compute strongly connected components of the basic block list. 2) Compute liveness (mapping from pseudo register to point(s) of death?). 3) Walk instructions in each basic block. We keep track of (a) Free real registers (a bitmap?) (b) Current assignment of temporaries to machine registers and/or spill slots (call this the "assignment"). (c) Partial mapping from basic block ids to a virt-to-loc mapping. When we first encounter a branch to a basic block, we fill in its entry in this table with the current mapping. For each instruction: (a) For each temporary *read* by the instruction: If the temporary does not have a real register allocation: - Allocate a real register from the free list. If the list is empty: - Find a temporary to spill. Pick one that is not used in this instruction (ToDo: not used for a while...) - generate a spill instruction - If the temporary was previously spilled, generate an instruction to read the temp from its spill loc. (optimisation: if we can see that a real register is going to be used soon, then don't use it for allocation). (b) For each real register clobbered by this instruction: If a temporary resides in it, If the temporary is live after this instruction, Move the temporary to another (non-clobbered & free) reg, or spill it to memory. Mark the temporary as residing in both memory and a register if it was spilled (it might need to be read by this instruction). (ToDo: this is wrong for jump instructions?) We do this after step (a), because if we start with movq v1, %rsi which is an instruction that clobbers %rsi, if v1 currently resides in %rsi we want to get movq %rsi, %freereg movq %rsi, %rsi -- will disappear instead of movq %rsi, %freereg movq %freereg, %rsi (c) Update the current assignment (d) If the instruction is a branch: if the destination block already has a register assignment, Generate a new block with fixup code and redirect the jump to the new block. else, Update the block id->assignment mapping with the current assignment. (e) Delete all register assignments for temps which are read (only) and die here. Update the free register list. (f) Mark all registers clobbered by this instruction as not free, and mark temporaries which have been spilled due to clobbering as in memory (step (a) marks then as in both mem & reg). (g) For each temporary *written* by this instruction: Allocate a real register as for (b), spilling something else if necessary. - except when updating the assignment, drop any memory locations that the temporary was previously in, since they will be no longer valid after this instruction. (h) Delete all register assignments for temps which are written and die here (there should rarely be any). Update the free register list. (i) Rewrite the instruction with the new mapping. (j) For each spilled reg known to be now dead, re-add its stack slot to the free list. -} module RegAlloc.Linear.Main ( regAlloc, module RegAlloc.Linear.Base, module RegAlloc.Linear.Stats ) where #include "HsVersions.h" import GhcPrelude import RegAlloc.Linear.State import RegAlloc.Linear.Base import RegAlloc.Linear.StackMap import RegAlloc.Linear.FreeRegs import RegAlloc.Linear.Stats import RegAlloc.Linear.JoinToTargets import qualified RegAlloc.Linear.PPC.FreeRegs as PPC import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC import qualified RegAlloc.Linear.X86.FreeRegs as X86 import qualified RegAlloc.Linear.X86_64.FreeRegs as X86_64 import TargetReg import RegAlloc.Liveness import Instruction import Reg import BlockId import Hoopl.Collections import Cmm hiding (RegSet) import Digraph import DynFlags import Unique import UniqSet import UniqFM import UniqSupply import Outputable import Platform import Data.Maybe import Data.List import Control.Monad -- ----------------------------------------------------------------------------- -- Top level of the register allocator -- Allocate registers regAlloc :: (Outputable instr, Instruction instr) => DynFlags -> LiveCmmDecl statics instr -> UniqSM ( NatCmmDecl statics instr , Maybe Int -- number of extra stack slots required, -- beyond maxSpillSlots , Maybe RegAllocStats) regAlloc _ (CmmData sec d) = return ( CmmData sec d , Nothing , Nothing ) regAlloc _ (CmmProc (LiveInfo info _ _ _) lbl live []) = return ( CmmProc info lbl live (ListGraph []) , Nothing , Nothing ) regAlloc dflags (CmmProc static lbl live sccs) | LiveInfo info entry_ids@(first_id:_) (Just block_live) _ <- static = do -- do register allocation on each component. (final_blocks, stats, stack_use) <- linearRegAlloc dflags entry_ids block_live sccs -- make sure the block that was first in the input list -- stays at the front of the output let ((first':_), rest') = partition ((== first_id) . blockId) final_blocks let max_spill_slots = maxSpillSlots dflags extra_stack | stack_use > max_spill_slots = Just (stack_use - max_spill_slots) | otherwise = Nothing return ( CmmProc info lbl live (ListGraph (first' : rest')) , extra_stack , Just stats) -- bogus. to make non-exhaustive match warning go away. regAlloc _ (CmmProc _ _ _ _) = panic "RegAllocLinear.regAlloc: no match" -- ----------------------------------------------------------------------------- -- Linear sweep to allocate registers -- | Do register allocation on some basic blocks. -- But be careful to allocate a block in an SCC only if it has -- an entry in the block map or it is the first block. -- linearRegAlloc :: (Outputable instr, Instruction instr) => DynFlags -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc dflags entry_ids block_live sccs = case platformArch platform of ArchX86 -> go $ (frInitFreeRegs platform :: X86.FreeRegs) ArchX86_64 -> go $ (frInitFreeRegs platform :: X86_64.FreeRegs) ArchSPARC -> go $ (frInitFreeRegs platform :: SPARC.FreeRegs) ArchSPARC64 -> panic "linearRegAlloc ArchSPARC64" ArchPPC -> go $ (frInitFreeRegs platform :: PPC.FreeRegs) ArchARM _ _ _ -> panic "linearRegAlloc ArchARM" ArchARM64 -> panic "linearRegAlloc ArchARM64" ArchPPC_64 _ -> go $ (frInitFreeRegs platform :: PPC.FreeRegs) ArchAlpha -> panic "linearRegAlloc ArchAlpha" ArchMipseb -> panic "linearRegAlloc ArchMipseb" ArchMipsel -> panic "linearRegAlloc ArchMipsel" ArchJavaScript -> panic "linearRegAlloc ArchJavaScript" ArchUnknown -> panic "linearRegAlloc ArchUnknown" where go f = linearRegAlloc' dflags f entry_ids block_live sccs platform = targetPlatform dflags linearRegAlloc' :: (FR freeRegs, Outputable instr, Instruction instr) => DynFlags -> freeRegs -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc' dflags initFreeRegs entry_ids block_live sccs = do us <- getUniqueSupplyM let (_, stack, stats, blocks) = runR dflags mapEmpty initFreeRegs emptyRegMap (emptyStackMap dflags) us $ linearRA_SCCs entry_ids block_live [] sccs return (blocks, stats, getStackUse stack) linearRA_SCCs :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [NatBasicBlock instr] -> [SCC (LiveBasicBlock instr)] -> RegM freeRegs [NatBasicBlock instr] linearRA_SCCs _ _ blocksAcc [] = return $ reverse blocksAcc linearRA_SCCs entry_ids block_live blocksAcc (AcyclicSCC block : sccs) = do blocks' <- processBlock block_live block linearRA_SCCs entry_ids block_live ((reverse blocks') ++ blocksAcc) sccs linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs) = do blockss' <- process entry_ids block_live blocks [] (return []) False linearRA_SCCs entry_ids block_live (reverse (concat blockss') ++ blocksAcc) sccs {- from John Dias's patch 2008/10/16: The linear-scan allocator sometimes allocates a block before allocating one of its predecessors, which could lead to inconsistent allocations. Make it so a block is only allocated if a predecessor has set the "incoming" assignments for the block, or if it's the procedure's entry block. BL 2009/02: Careful. If the assignment for a block doesn't get set for some reason then this function will loop. We should probably do some more sanity checking to guard against this eventuality. -} process :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [GenBasicBlock (LiveInstr instr)] -> [GenBasicBlock (LiveInstr instr)] -> [[NatBasicBlock instr]] -> Bool -> RegM freeRegs [[NatBasicBlock instr]] process _ _ [] [] accum _ = return $ reverse accum process entry_ids block_live [] next_round accum madeProgress | not madeProgress {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming. pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out." ( text "Unreachable blocks:" $$ vcat (map ppr next_round)) -} = return $ reverse accum | otherwise = process entry_ids block_live next_round [] accum False process entry_ids block_live (b@(BasicBlock id _) : blocks) next_round accum madeProgress = do block_assig <- getBlockAssigR if isJust (mapLookup id block_assig) || id `elem` entry_ids then do b' <- processBlock block_live b process entry_ids block_live blocks next_round (b' : accum) True else process entry_ids block_live blocks (b : next_round) accum madeProgress -- | Do register allocation on this basic block -- processBlock :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ live regs on entry to each basic block -> LiveBasicBlock instr -- ^ block to do register allocation on -> RegM freeRegs [NatBasicBlock instr] -- ^ block with registers allocated processBlock block_live (BasicBlock id instrs) = do initBlock id block_live (instrs', fixups) <- linearRA block_live [] [] id instrs return $ BasicBlock id instrs' : fixups -- | Load the freeregs and current reg assignment into the RegM state -- for the basic block with this BlockId. initBlock :: FR freeRegs => BlockId -> BlockMap RegSet -> RegM freeRegs () initBlock id block_live = do dflags <- getDynFlags let platform = targetPlatform dflags block_assig <- getBlockAssigR case mapLookup id block_assig of -- no prior info about this block: we must consider -- any fixed regs to be allocated, but we can ignore -- virtual regs (presumably this is part of a loop, -- and we'll iterate again). The assignment begins -- empty. Nothing -> do -- pprTrace "initFreeRegs" (text $ show initFreeRegs) (return ()) case mapLookup id block_live of Nothing -> setFreeRegsR (frInitFreeRegs platform) Just live -> setFreeRegsR $ foldl' (flip $ frAllocateReg platform) (frInitFreeRegs platform) [ r | RegReal r <- nonDetEltsUniqSet live ] -- See Note [Unique Determinism and code generation] setAssigR emptyRegMap -- load info about register assignments leading into this block. Just (freeregs, assig) -> do setFreeRegsR freeregs setAssigR assig -- | Do allocation for a sequence of instructions. linearRA :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are live on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> [NatBasicBlock instr] -- ^ accumulator for blocks of fixup code. -> BlockId -- ^ id of the current block, for debugging. -> [LiveInstr instr] -- ^ liveness annotated instructions in this block. -> RegM freeRegs ( [instr] -- instructions after register allocation , [NatBasicBlock instr]) -- fresh blocks of fixup code. linearRA _ accInstr accFixup _ [] = return ( reverse accInstr -- instrs need to be returned in the correct order. , accFixup) -- it doesn't matter what order the fixup blocks are returned in. linearRA block_live accInstr accFixups id (instr:instrs) = do (accInstr', new_fixups) <- raInsn block_live accInstr id instr linearRA block_live accInstr' (new_fixups ++ accFixups) id instrs -- | Do allocation for a single instruction. raInsn :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are love on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> BlockId -- ^ the id of the current block, for debugging -> LiveInstr instr -- ^ the instr to have its regs allocated, with liveness info. -> RegM freeRegs ( [instr] -- new instructions , [NatBasicBlock instr]) -- extra fixup blocks raInsn _ new_instrs _ (LiveInstr ii Nothing) | Just n <- takeDeltaInstr ii = do setDeltaR n return (new_instrs, []) raInsn _ new_instrs _ (LiveInstr ii@(Instr i) Nothing) | isMetaInstr ii = return (i : new_instrs, []) raInsn block_live new_instrs id (LiveInstr (Instr instr) (Just live)) = do assig <- getAssigR -- If we have a reg->reg move between virtual registers, where the -- src register is not live after this instruction, and the dst -- register does not already have an assignment, -- and the source register is assigned to a register, not to a spill slot, -- then we can eliminate the instruction. -- (we can't eliminate it if the source register is on the stack, because -- we do not want to use one spill slot for different virtual registers) case takeRegRegMoveInstr instr of Just (src,dst) | src `elementOfUniqSet` (liveDieRead live), isVirtualReg dst, not (dst `elemUFM` assig), isRealReg src || isInReg src assig -> do case src of (RegReal rr) -> setAssigR (addToUFM assig dst (InReg rr)) -- if src is a fixed reg, then we just map dest to this -- reg in the assignment. src must be an allocatable reg, -- otherwise it wouldn't be in r_dying. _virt -> case lookupUFM assig src of Nothing -> panic "raInsn" Just loc -> setAssigR (addToUFM (delFromUFM assig src) dst loc) -- we have eliminated this instruction {- freeregs <- getFreeRegsR assig <- getAssigR pprTrace "raInsn" (text "ELIMINATED: " <> docToSDoc (pprInstr instr) $$ ppr r_dying <+> ppr w_dying $$ text (show freeregs) $$ ppr assig) $ do -} return (new_instrs, []) _ -> genRaInsn block_live new_instrs id instr (nonDetEltsUniqSet $ liveDieRead live) (nonDetEltsUniqSet $ liveDieWrite live) -- See Note [Unique Determinism and code generation] raInsn _ _ _ instr = pprPanic "raInsn" (text "no match for:" <> ppr instr) -- ToDo: what can we do about -- -- R1 = x -- jump I64[x] // [R1] -- -- where x is mapped to the same reg as R1. We want to coalesce x and -- R1, but the register allocator doesn't know whether x will be -- assigned to again later, in which case x and R1 should be in -- different registers. Right now we assume the worst, and the -- assignment to R1 will clobber x, so we'll spill x into another reg, -- generating another reg->reg move. isInReg :: Reg -> RegMap Loc -> Bool isInReg src assig | Just (InReg _) <- lookupUFM assig src = True | otherwise = False genRaInsn :: (FR freeRegs, Instruction instr, Outputable instr) => BlockMap RegSet -> [instr] -> BlockId -> instr -> [Reg] -> [Reg] -> RegM freeRegs ([instr], [NatBasicBlock instr]) genRaInsn block_live new_instrs block_id instr r_dying w_dying = do dflags <- getDynFlags let platform = targetPlatform dflags case regUsageOfInstr platform instr of { RU read written -> do let real_written = [ rr | (RegReal rr) <- written ] let virt_written = [ vr | (RegVirtual vr) <- written ] -- we don't need to do anything with real registers that are -- only read by this instr. (the list is typically ~2 elements, -- so using nub isn't a problem). let virt_read = nub [ vr | (RegVirtual vr) <- read ] -- debugging {- freeregs <- getFreeRegsR assig <- getAssigR pprDebugAndThen (defaultDynFlags Settings{ sTargetPlatform=platform } undefined) trace "genRaInsn" (ppr instr $$ text "r_dying = " <+> ppr r_dying $$ text "w_dying = " <+> ppr w_dying $$ text "virt_read = " <+> ppr virt_read $$ text "virt_written = " <+> ppr virt_written $$ text "freeregs = " <+> text (show freeregs) $$ text "assig = " <+> ppr assig) $ do -} -- (a), (b) allocate real regs for all regs read by this instruction. (r_spills, r_allocd) <- allocateRegsAndSpill True{-reading-} virt_read [] [] virt_read -- (c) save any temporaries which will be clobbered by this instruction clobber_saves <- saveClobberedTemps real_written r_dying -- (d) Update block map for new destinations -- NB. do this before removing dead regs from the assignment, because -- these dead regs might in fact be live in the jump targets (they're -- only dead in the code that follows in the current basic block). (fixup_blocks, adjusted_instr) <- joinToTargets block_live block_id instr -- (e) Delete all register assignments for temps which are read -- (only) and die here. Update the free register list. releaseRegs r_dying -- (f) Mark regs which are clobbered as unallocatable clobberRegs real_written -- (g) Allocate registers for temporaries *written* (only) (w_spills, w_allocd) <- allocateRegsAndSpill False{-writing-} virt_written [] [] virt_written -- (h) Release registers for temps which are written here and not -- used again. releaseRegs w_dying let -- (i) Patch the instruction patch_map = listToUFM [ (t, RegReal r) | (t, r) <- zip virt_read r_allocd ++ zip virt_written w_allocd ] patched_instr = patchRegsOfInstr adjusted_instr patchLookup patchLookup x = case lookupUFM patch_map x of Nothing -> x Just y -> y -- (j) free up stack slots for dead spilled regs -- TODO (can't be bothered right now) -- erase reg->reg moves where the source and destination are the same. -- If the src temp didn't die in this instr but happened to be allocated -- to the same real reg as the destination, then we can erase the move anyway. let squashed_instr = case takeRegRegMoveInstr patched_instr of Just (src, dst) | src == dst -> [] _ -> [patched_instr] let code = squashed_instr ++ w_spills ++ reverse r_spills ++ clobber_saves ++ new_instrs -- pprTrace "patched-code" ((vcat $ map (docToSDoc . pprInstr) code)) $ do -- pprTrace "pached-fixup" ((ppr fixup_blocks)) $ do return (code, fixup_blocks) } -- ----------------------------------------------------------------------------- -- releaseRegs releaseRegs :: FR freeRegs => [Reg] -> RegM freeRegs () releaseRegs regs = do dflags <- getDynFlags let platform = targetPlatform dflags assig <- getAssigR free <- getFreeRegsR let loop assig !free [] = do setAssigR assig; setFreeRegsR free; return () loop assig !free (RegReal rr : rs) = loop assig (frReleaseReg platform rr free) rs loop assig !free (r:rs) = case lookupUFM assig r of Just (InBoth real _) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs Just (InReg real) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs _ -> loop (delFromUFM assig r) free rs loop assig free regs -- ----------------------------------------------------------------------------- -- Clobber real registers -- For each temp in a register that is going to be clobbered: -- - if the temp dies after this instruction, do nothing -- - otherwise, put it somewhere safe (another reg if possible, -- otherwise spill and record InBoth in the assignment). -- - for allocateRegs on the temps *read*, -- - clobbered regs are allocatable. -- -- for allocateRegs on the temps *written*, -- - clobbered regs are not allocatable. -- saveClobberedTemps :: (Instruction instr, FR freeRegs) => [RealReg] -- real registers clobbered by this instruction -> [Reg] -- registers which are no longer live after this insn -> RegM freeRegs [instr] -- return: instructions to spill any temps that will -- be clobbered. saveClobberedTemps [] _ = return [] saveClobberedTemps clobbered dying = do assig <- getAssigR let to_spill = [ (temp,reg) | (temp, InReg reg) <- nonDetUFMToList assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] , any (realRegsAlias reg) clobbered , temp `notElem` map getUnique dying ] (instrs,assig') <- clobber assig [] to_spill setAssigR assig' return instrs where clobber assig instrs [] = return (instrs, assig) clobber assig instrs ((temp, reg) : rest) = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let regclass = targetClassOfRealReg platform reg freeRegs_thisClass = frGetFreeRegs platform regclass freeRegs case filter (`notElem` clobbered) freeRegs_thisClass of -- (1) we have a free reg of the right class that isn't -- clobbered by this instruction; use it to save the -- clobbered value. (my_reg : _) -> do setFreeRegsR (frAllocateReg platform my_reg freeRegs) let new_assign = addToUFM assig temp (InReg my_reg) let instr = mkRegRegMoveInstr platform (RegReal reg) (RegReal my_reg) clobber new_assign (instr : instrs) rest -- (2) no free registers: spill the value [] -> do (spill, slot) <- spillR (RegReal reg) temp -- record why this reg was spilled for profiling recordSpill (SpillClobber temp) let new_assign = addToUFM assig temp (InBoth reg slot) clobber new_assign (spill : instrs) rest -- | Mark all these real regs as allocated, -- and kick out their vreg assignments. -- clobberRegs :: FR freeRegs => [RealReg] -> RegM freeRegs () clobberRegs [] = return () clobberRegs clobbered = do dflags <- getDynFlags let platform = targetPlatform dflags freeregs <- getFreeRegsR setFreeRegsR $! foldl' (flip $ frAllocateReg platform) freeregs clobbered assig <- getAssigR setAssigR $! clobber assig (nonDetUFMToList assig) -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] where -- if the temp was InReg and clobbered, then we will have -- saved it in saveClobberedTemps above. So the only case -- we have to worry about here is InBoth. Note that this -- also catches temps which were loaded up during allocation -- of read registers, not just those saved in saveClobberedTemps. clobber assig [] = assig clobber assig ((temp, InBoth reg slot) : rest) | any (realRegsAlias reg) clobbered = clobber (addToUFM assig temp (InMem slot)) rest clobber assig (_:rest) = clobber assig rest -- ----------------------------------------------------------------------------- -- allocateRegsAndSpill -- Why are we performing a spill? data SpillLoc = ReadMem StackSlot -- reading from register only in memory | WriteNew -- writing to a new variable | WriteMem -- writing to register only in memory -- Note that ReadNew is not valid, since you don't want to be reading -- from an uninitialized register. We also don't need the location of -- the register in memory, since that will be invalidated by the write. -- Technically, we could coalesce WriteNew and WriteMem into a single -- entry as well. -- EZY -- This function does several things: -- For each temporary referred to by this instruction, -- we allocate a real register (spilling another temporary if necessary). -- We load the temporary up from memory if necessary. -- We also update the register assignment in the process, and -- the list of free registers and free stack slots. allocateRegsAndSpill :: (FR freeRegs, Outputable instr, Instruction instr) => Bool -- True <=> reading (load up spilled regs) -> [VirtualReg] -- don't push these out -> [instr] -- spill insns -> [RealReg] -- real registers allocated (accum.) -> [VirtualReg] -- temps to allocate -> RegM freeRegs ( [instr] , [RealReg]) allocateRegsAndSpill _ _ spills alloc [] = return (spills, reverse alloc) allocateRegsAndSpill reading keep spills alloc (r:rs) = do assig <- getAssigR let doSpill = allocRegsAndSpill_spill reading keep spills alloc r rs assig case lookupUFM assig r of -- case (1a): already in a register Just (InReg my_reg) -> allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- case (1b): already in a register (and memory) -- NB1. if we're writing this register, update its assignment to be -- InReg, because the memory value is no longer valid. -- NB2. This is why we must process written registers here, even if they -- are also read by the same instruction. Just (InBoth my_reg _) -> do when (not reading) (setAssigR (addToUFM assig r (InReg my_reg))) allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- Not already in a register, so we need to find a free one... Just (InMem slot) | reading -> doSpill (ReadMem slot) | otherwise -> doSpill WriteMem Nothing | reading -> pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr r) -- NOTE: if the input to the NCG contains some -- unreachable blocks with junk code, this panic -- might be triggered. Make sure you only feed -- sensible code into the NCG. In CmmPipeline we -- call removeUnreachableBlocks at the end for this -- reason. | otherwise -> doSpill WriteNew -- reading is redundant with reason, but we keep it around because it's -- convenient and it maintains the recursive structure of the allocator. -- EZY allocRegsAndSpill_spill :: (FR freeRegs, Instruction instr, Outputable instr) => Bool -> [VirtualReg] -> [instr] -> [RealReg] -> VirtualReg -> [VirtualReg] -> UniqFM Loc -> SpillLoc -> RegM freeRegs ([instr], [RealReg]) allocRegsAndSpill_spill reading keep spills alloc r rs assig spill_loc = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let freeRegs_thisClass = frGetFreeRegs platform (classOfVirtualReg r) freeRegs case freeRegs_thisClass of -- case (2): we have a free register (my_reg : _) -> do spills' <- loadTemp r spill_loc my_reg spills setAssigR (addToUFM assig r $! newLocation spill_loc my_reg) setFreeRegsR $ frAllocateReg platform my_reg freeRegs allocateRegsAndSpill reading keep spills' (my_reg : alloc) rs -- case (3): we need to push something out to free up a register [] -> do let inRegOrBoth (InReg _) = True inRegOrBoth (InBoth _ _) = True inRegOrBoth _ = False let candidates' = flip delListFromUFM keep $ filterUFM inRegOrBoth $ assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] let candidates = nonDetUFMToList candidates' -- the vregs we could kick out that are already in a slot let candidates_inBoth = [ (temp, reg, mem) | (temp, InBoth reg mem) <- candidates , targetClassOfRealReg platform reg == classOfVirtualReg r ] -- the vregs we could kick out that are only in a reg -- this would require writing the reg to a new slot before using it. let candidates_inReg = [ (temp, reg) | (temp, InReg reg) <- candidates , targetClassOfRealReg platform reg == classOfVirtualReg r ] let result -- we have a temporary that is in both register and mem, -- just free up its register for use. | (temp, my_reg, slot) : _ <- candidates_inBoth = do spills' <- loadTemp r spill_loc my_reg spills let assig1 = addToUFM assig temp (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 allocateRegsAndSpill reading keep spills' (my_reg:alloc) rs -- otherwise, we need to spill a temporary that currently -- resides in a register. | (temp_to_push_out, (my_reg :: RealReg)) : _ <- candidates_inReg = do (spill_insn, slot) <- spillR (RegReal my_reg) temp_to_push_out let spill_store = (if reading then id else reverse) [ -- COMMENT (fsLit "spill alloc") spill_insn ] -- record that this temp was spilled recordSpill (SpillAlloc temp_to_push_out) -- update the register assignment let assig1 = addToUFM assig temp_to_push_out (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 -- if need be, load up a spilled temp into the reg we've just freed up. spills' <- loadTemp r spill_loc my_reg spills allocateRegsAndSpill reading keep (spill_store ++ spills') (my_reg:alloc) rs -- there wasn't anything to spill, so we're screwed. | otherwise = pprPanic ("RegAllocLinear.allocRegsAndSpill: no spill candidates\n") $ vcat [ text "allocating vreg: " <> text (show r) , text "assignment: " <> ppr assig , text "freeRegs: " <> text (show freeRegs) , text "initFreeRegs: " <> text (show (frInitFreeRegs platform `asTypeOf` freeRegs)) ] result -- | Calculate a new location after a register has been loaded. newLocation :: SpillLoc -> RealReg -> Loc -- if the tmp was read from a slot, then now its in a reg as well newLocation (ReadMem slot) my_reg = InBoth my_reg slot -- writes will always result in only the register being available newLocation _ my_reg = InReg my_reg -- | Load up a spilled temporary if we need to (read from memory). loadTemp :: (Instruction instr) => VirtualReg -- the temp being loaded -> SpillLoc -- the current location of this temp -> RealReg -- the hreg to load the temp into -> [instr] -> RegM freeRegs [instr] loadTemp vreg (ReadMem slot) hreg spills = do insn <- loadR (RegReal hreg) slot recordSpill (SpillLoad $ getUnique vreg) return $ {- COMMENT (fsLit "spill load") : -} insn : spills loadTemp _ _ _ spills = return spills
ezyang/ghc
compiler/nativeGen/RegAlloc/Linear/Main.hs
bsd-3-clause
37,857
0
25
13,401
5,786
2,957
2,829
467
13
module SafeLang14_A (IsoInt, h, showH, P, p, showP) where newtype IsoInt = I Int h :: IsoInt h = I 2 showH :: String showH = let I n = h in show n data P = P Int p :: P p = P 3 showP :: P -> String showP (P n) = "Should be 3 := " ++ show n
hferreiro/replay
testsuite/tests/safeHaskell/safeLanguage/SafeLang14_A.hs
bsd-3-clause
255
0
9
78
125
68
57
12
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE Unsafe #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Natural -- Copyright : (C) 2014 Herbert Valerio Riedel, -- (C) 2011 Edward Kmett -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- The arbitrary-precision 'Natural' number type. -- -- __Note__: This is an internal GHC module with an API subject to -- change. It's recommended use the "Numeric.Natural" module to import -- the 'Natural' type. -- -- @since 4.8.0.0 ----------------------------------------------------------------------------- module GHC.Natural ( -- * The 'Natural' number type -- -- | __Warning__: The internal implementation of 'Natural' -- (i.e. which constructors are available) depends on the -- 'Integer' backend used! Natural(..) , isValidNatural -- * Conversions , wordToNatural , naturalToWordMaybe -- * Checked subtraction , minusNaturalMaybe -- * Modular arithmetic , powModNatural ) where #include "MachDeps.h" #if defined(MIN_VERSION_integer_gmp) # define HAVE_GMP_BIGNAT MIN_VERSION_integer_gmp(1,0,0) #else # define HAVE_GMP_BIGNAT 0 #endif import GHC.Arr import GHC.Base import GHC.Exception #if HAVE_GMP_BIGNAT import GHC.Integer.GMP.Internals import Data.Word import Data.Int #endif import GHC.Num import GHC.Real import GHC.Read import GHC.Show import GHC.Enum import GHC.List import Data.Bits import Data.Data default () #if HAVE_GMP_BIGNAT -- TODO: if saturated arithmetic is to used, replace 'throw Underflow' by '0' -- | Type representing arbitrary-precision non-negative integers. -- -- Operations whose result would be negative -- @'throw' ('Underflow' :: 'ArithException')@. -- -- @since 4.8.0.0 data Natural = NatS# GmpLimb# -- ^ in @[0, maxBound::Word]@ | NatJ# {-# UNPACK #-} !BigNat -- ^ in @]maxBound::Word, +inf[@ -- -- __Invariant__: 'NatJ#' is used -- /iff/ value doesn't fit in -- 'NatS#' constructor. deriving (Eq,Ord) -- NB: Order of constructors *must* -- coincide with 'Ord' relation -- | Test whether all internal invariants are satisfied by 'Natural' value -- -- This operation is mostly useful for test-suites and/or code which -- constructs 'Integer' values directly. -- -- @since 4.8.0.0 isValidNatural :: Natural -> Bool isValidNatural (NatS# _) = True isValidNatural (NatJ# bn) = isTrue# (isValidBigNat# bn) && I# (sizeofBigNat# bn) > 0 {-# RULES "fromIntegral/Natural->Natural" fromIntegral = id :: Natural -> Natural "fromIntegral/Natural->Integer" fromIntegral = toInteger :: Natural->Integer "fromIntegral/Natural->Word" fromIntegral = naturalToWord "fromIntegral/Natural->Word8" fromIntegral = (fromIntegral :: Word -> Word8) . naturalToWord "fromIntegral/Natural->Word16" fromIntegral = (fromIntegral :: Word -> Word16) . naturalToWord "fromIntegral/Natural->Word32" fromIntegral = (fromIntegral :: Word -> Word32) . naturalToWord "fromIntegral/Natural->Int8" fromIntegral = (fromIntegral :: Int -> Int8) . naturalToInt "fromIntegral/Natural->Int16" fromIntegral = (fromIntegral :: Int -> Int16) . naturalToInt "fromIntegral/Natural->Int32" fromIntegral = (fromIntegral :: Int -> Int32) . naturalToInt #-} {-# RULES "fromIntegral/Word->Natural" fromIntegral = wordToNatural "fromIntegral/Word8->Natural" fromIntegral = wordToNatural . (fromIntegral :: Word8 -> Word) "fromIntegral/Word16->Natural" fromIntegral = wordToNatural . (fromIntegral :: Word16 -> Word) "fromIntegral/Word32->Natural" fromIntegral = wordToNatural . (fromIntegral :: Word32 -> Word) "fromIntegral/Int->Natural" fromIntegral = intToNatural "fromIntegral/Int8->Natural" fromIntegral = intToNatural . (fromIntegral :: Int8 -> Int) "fromIntegral/Int16->Natural" fromIntegral = intToNatural . (fromIntegral :: Int16 -> Int) "fromIntegral/Int32->Natural" fromIntegral = intToNatural . (fromIntegral :: Int32 -> Int) #-} #if WORD_SIZE_IN_BITS == 64 -- these RULES are valid for Word==Word64 & Int==Int64 {-# RULES "fromIntegral/Natural->Word64" fromIntegral = (fromIntegral :: Word -> Word64) . naturalToWord "fromIntegral/Natural->Int64" fromIntegral = (fromIntegral :: Int -> Int64) . naturalToInt "fromIntegral/Word64->Natural" fromIntegral = wordToNatural . (fromIntegral :: Word64 -> Word) "fromIntegral/Int64->Natural" fromIntegral = intToNatural . (fromIntegral :: Int64 -> Int) #-} #endif instance Show Natural where showsPrec p (NatS# w#) = showsPrec p (W# w#) showsPrec p (NatJ# bn) = showsPrec p (Jp# bn) instance Read Natural where readsPrec d = map (\(n, s) -> (fromInteger n, s)) . filter ((>= 0) . (\(x,_)->x)) . readsPrec d instance Num Natural where fromInteger (S# i#) | I# i# >= 0 = NatS# (int2Word# i#) fromInteger (Jp# bn) = bigNatToNatural bn fromInteger _ = throw Underflow (+) = plusNatural (*) = timesNatural (-) = minusNatural abs = id signum (NatS# 0##) = NatS# 0## signum _ = NatS# 1## negate (NatS# 0##) = NatS# 0## negate _ = throw Underflow instance Real Natural where toRational (NatS# w) = toRational (W# w) toRational (NatJ# bn) = toRational (Jp# bn) #if OPTIMISE_INTEGER_GCD_LCM {-# RULES "gcd/Natural->Natural->Natural" gcd = gcdNatural "lcm/Natural->Natural->Natural" lcm = lcmNatural #-} -- | Compute greatest common divisor. gcdNatural :: Natural -> Natural -> Natural gcdNatural (NatS# 0##) y = y gcdNatural x (NatS# 0##) = x gcdNatural (NatS# 1##) _ = (NatS# 1##) gcdNatural _ (NatS# 1##) = (NatS# 1##) gcdNatural (NatJ# x) (NatJ# y) = bigNatToNatural (gcdBigNat x y) gcdNatural (NatJ# x) (NatS# y) = NatS# (gcdBigNatWord x y) gcdNatural (NatS# x) (NatJ# y) = NatS# (gcdBigNatWord y x) gcdNatural (NatS# x) (NatS# y) = NatS# (gcdWord x y) -- | compute least common multiplier. lcmNatural :: Natural -> Natural -> Natural lcmNatural (NatS# 0##) _ = (NatS# 0##) lcmNatural _ (NatS# 0##) = (NatS# 0##) lcmNatural (NatS# 1##) y = y lcmNatural x (NatS# 1##) = x lcmNatural x y = (x `quot` (gcdNatural x y)) * y #endif instance Enum Natural where succ n = n `plusNatural` NatS# 1## pred n = n `minusNatural` NatS# 1## toEnum = intToNatural fromEnum (NatS# w) | i >= 0 = i where i = fromIntegral (W# w) fromEnum _ = error "fromEnum: out of Int range" enumFrom x = enumDeltaNatural x (NatS# 1##) enumFromThen x y | x <= y = enumDeltaNatural x (y-x) | otherwise = enumNegDeltaToNatural x (x-y) (NatS# 0##) enumFromTo x lim = enumDeltaToNatural x (NatS# 1##) lim enumFromThenTo x y lim | x <= y = enumDeltaToNatural x (y-x) lim | otherwise = enumNegDeltaToNatural x (x-y) lim ---------------------------------------------------------------------------- -- Helpers for 'Enum Natural'; TODO: optimise & make fusion work enumDeltaNatural :: Natural -> Natural -> [Natural] enumDeltaNatural !x d = x : enumDeltaNatural (x+d) d enumDeltaToNatural :: Natural -> Natural -> Natural -> [Natural] enumDeltaToNatural x0 delta lim = go x0 where go x | x > lim = [] | otherwise = x : go (x+delta) enumNegDeltaToNatural :: Natural -> Natural -> Natural -> [Natural] enumNegDeltaToNatural x0 ndelta lim = go x0 where go x | x < lim = [] | x >= ndelta = x : go (x-ndelta) | otherwise = [x] ---------------------------------------------------------------------------- instance Integral Natural where toInteger (NatS# w) = wordToInteger w toInteger (NatJ# bn) = Jp# bn divMod = quotRem div = quot mod = rem quotRem _ (NatS# 0##) = throw DivideByZero quotRem n (NatS# 1##) = (n,NatS# 0##) quotRem n@(NatS# _) (NatJ# _) = (NatS# 0##, n) quotRem (NatS# n) (NatS# d) = case quotRem (W# n) (W# d) of (q,r) -> (wordToNatural q, wordToNatural r) quotRem (NatJ# n) (NatS# d) = case quotRemBigNatWord n d of (# q,r #) -> (bigNatToNatural q, NatS# r) quotRem (NatJ# n) (NatJ# d) = case quotRemBigNat n d of (# q,r #) -> (bigNatToNatural q, bigNatToNatural r) quot _ (NatS# 0##) = throw DivideByZero quot n (NatS# 1##) = n quot (NatS# _) (NatJ# _) = NatS# 0## quot (NatS# n) (NatS# d) = wordToNatural (quot (W# n) (W# d)) quot (NatJ# n) (NatS# d) = bigNatToNatural (quotBigNatWord n d) quot (NatJ# n) (NatJ# d) = bigNatToNatural (quotBigNat n d) rem _ (NatS# 0##) = throw DivideByZero rem _ (NatS# 1##) = NatS# 0## rem n@(NatS# _) (NatJ# _) = n rem (NatS# n) (NatS# d) = wordToNatural (rem (W# n) (W# d)) rem (NatJ# n) (NatS# d) = NatS# (remBigNatWord n d) rem (NatJ# n) (NatJ# d) = bigNatToNatural (remBigNat n d) instance Ix Natural where range (m,n) = [m..n] inRange (m,n) i = m <= i && i <= n unsafeIndex (m,_) i = fromIntegral (i-m) index b i | inRange b i = unsafeIndex b i | otherwise = indexError b i "Natural" instance Bits Natural where NatS# n .&. NatS# m = wordToNatural (W# n .&. W# m) NatS# n .&. NatJ# m = wordToNatural (W# n .&. W# (bigNatToWord m)) NatJ# n .&. NatS# m = wordToNatural (W# (bigNatToWord n) .&. W# m) NatJ# n .&. NatJ# m = bigNatToNatural (andBigNat n m) NatS# n .|. NatS# m = wordToNatural (W# n .|. W# m) NatS# n .|. NatJ# m = NatJ# (orBigNat (wordToBigNat n) m) NatJ# n .|. NatS# m = NatJ# (orBigNat n (wordToBigNat m)) NatJ# n .|. NatJ# m = NatJ# (orBigNat n m) NatS# n `xor` NatS# m = wordToNatural (W# n `xor` W# m) NatS# n `xor` NatJ# m = NatJ# (xorBigNat (wordToBigNat n) m) NatJ# n `xor` NatS# m = NatJ# (xorBigNat n (wordToBigNat m)) NatJ# n `xor` NatJ# m = bigNatToNatural (xorBigNat n m) complement _ = error "Bits.complement: Natural complement undefined" bitSizeMaybe _ = Nothing bitSize = error "Natural: bitSize" isSigned _ = False bit i@(I# i#) | i < finiteBitSize (0::Word) = wordToNatural (bit i) | otherwise = NatJ# (bitBigNat i#) testBit (NatS# w) i = testBit (W# w) i testBit (NatJ# bn) (I# i#) = testBitBigNat bn i# -- TODO: setBit, clearBit, complementBit (needs more primitives) shiftL n 0 = n shiftL (NatS# 0##) _ = NatS# 0## shiftL (NatS# 1##) i = bit i shiftL (NatS# w) (I# i#) = bigNatToNatural $ shiftLBigNat (wordToBigNat w) i# shiftL (NatJ# bn) (I# i#) = bigNatToNatural $ shiftLBigNat bn i# shiftR n 0 = n shiftR (NatS# w) i = wordToNatural $ shiftR (W# w) i shiftR (NatJ# bn) (I# i#) = bigNatToNatural (shiftRBigNat bn i#) rotateL = shiftL rotateR = shiftR popCount (NatS# w) = popCount (W# w) popCount (NatJ# bn) = I# (popCountBigNat bn) zeroBits = NatS# 0## ---------------------------------------------------------------------------- -- | 'Natural' Addition plusNatural :: Natural -> Natural -> Natural plusNatural (NatS# 0##) y = y plusNatural x (NatS# 0##) = x plusNatural (NatS# x) (NatS# y) = case plusWord2# x y of (# 0##, l #) -> NatS# l (# h, l #) -> NatJ# (wordToBigNat2 h l) plusNatural (NatS# x) (NatJ# y) = NatJ# (plusBigNatWord y x) plusNatural (NatJ# x) (NatS# y) = NatJ# (plusBigNatWord x y) plusNatural (NatJ# x) (NatJ# y) = NatJ# (plusBigNat x y) -- | 'Natural' multiplication timesNatural :: Natural -> Natural -> Natural timesNatural _ (NatS# 0##) = NatS# 0## timesNatural (NatS# 0##) _ = NatS# 0## timesNatural x (NatS# 1##) = x timesNatural (NatS# 1##) y = y timesNatural (NatS# x) (NatS# y) = case timesWord2# x y of (# 0##, 0## #) -> NatS# 0## (# 0##, xy #) -> NatS# xy (# h , l #) -> NatJ# $ wordToBigNat2 h l timesNatural (NatS# x) (NatJ# y) = NatJ# $ timesBigNatWord y x timesNatural (NatJ# x) (NatS# y) = NatJ# $ timesBigNatWord x y timesNatural (NatJ# x) (NatJ# y) = NatJ# $ timesBigNat x y -- | 'Natural' subtraction. May @'throw' 'Underflow'@. minusNatural :: Natural -> Natural -> Natural minusNatural x (NatS# 0##) = x minusNatural (NatS# x) (NatS# y) = case subWordC# x y of (# l, 0# #) -> NatS# l _ -> throw Underflow minusNatural (NatS# _) (NatJ# _) = throw Underflow minusNatural (NatJ# x) (NatS# y) = bigNatToNatural $ minusBigNatWord x y minusNatural (NatJ# x) (NatJ# y) = bigNatToNatural $ minusBigNat x y -- | 'Natural' subtraction. Returns 'Nothing's for non-positive results. -- -- @since 4.8.0.0 minusNaturalMaybe :: Natural -> Natural -> Maybe Natural minusNaturalMaybe x (NatS# 0##) = Just x minusNaturalMaybe (NatS# x) (NatS# y) = case subWordC# x y of (# l, 0# #) -> Just (NatS# l) _ -> Nothing where minusNaturalMaybe (NatS# _) (NatJ# _) = Nothing minusNaturalMaybe (NatJ# x) (NatS# y) = Just $ bigNatToNatural $ minusBigNatWord x y minusNaturalMaybe (NatJ# x) (NatJ# y) | isTrue# (isNullBigNat# res) = Nothing | otherwise = Just (bigNatToNatural res) where res = minusBigNat x y -- | Helper for 'minusNatural' and 'minusNaturalMaybe' subWordC# :: Word# -> Word# -> (# Word#, Int# #) subWordC# x# y# = (# d#, c# #) where d# = x# `minusWord#` y# c# = d# `gtWord#` x# -- | Convert 'BigNat' to 'Natural'. -- Throws 'Underflow' if passed a 'nullBigNat'. bigNatToNatural :: BigNat -> Natural bigNatToNatural bn | isTrue# (sizeofBigNat# bn ==# 1#) = NatS# (bigNatToWord bn) | isTrue# (isNullBigNat# bn) = throw Underflow | otherwise = NatJ# bn naturalToBigNat :: Natural -> BigNat naturalToBigNat (NatS# w#) = wordToBigNat w# naturalToBigNat (NatJ# bn) = bn -- | Convert 'Int' to 'Natural'. -- Throws 'Underflow' when passed a negative 'Int'. intToNatural :: Int -> Natural intToNatural i | i<0 = throw Underflow intToNatural (I# i#) = NatS# (int2Word# i#) naturalToWord :: Natural -> Word naturalToWord (NatS# w#) = W# w# naturalToWord (NatJ# bn) = W# (bigNatToWord bn) naturalToInt :: Natural -> Int naturalToInt (NatS# w#) = I# (word2Int# w#) naturalToInt (NatJ# bn) = I# (bigNatToInt bn) #else /* !HAVE_GMP_BIGNAT */ ---------------------------------------------------------------------------- -- Use wrapped 'Integer' as fallback; taken from Edward Kmett's nats package -- | Type representing arbitrary-precision non-negative integers. -- -- Operations whose result would be negative -- @'throw' ('Underflow' :: 'ArithException')@. -- -- @since 4.8.0.0 newtype Natural = Natural Integer -- ^ __Invariant__: non-negative 'Integer' deriving (Eq,Ord,Ix) -- | Test whether all internal invariants are satisfied by 'Natural' value -- -- This operation is mostly useful for test-suites and/or code which -- constructs 'Integer' values directly. -- -- @since 4.8.0.0 isValidNatural :: Natural -> Bool isValidNatural (Natural i) = i >= 0 instance Read Natural where readsPrec d = map (\(n, s) -> (Natural n, s)) . filter ((>= 0) . (\(x,_)->x)) . readsPrec d instance Show Natural where showsPrec d (Natural i) = showsPrec d i instance Num Natural where Natural n + Natural m = Natural (n + m) {-# INLINE (+) #-} Natural n * Natural m = Natural (n * m) {-# INLINE (*) #-} Natural n - Natural m | result < 0 = throw Underflow | otherwise = Natural result where result = n - m {-# INLINE (-) #-} abs (Natural n) = Natural n {-# INLINE abs #-} signum (Natural n) = Natural (signum n) {-# INLINE signum #-} fromInteger n | n >= 0 = Natural n | otherwise = throw Underflow {-# INLINE fromInteger #-} -- | 'Natural' subtraction. Returns 'Nothing's for non-positive results. -- -- @since 4.8.0.0 minusNaturalMaybe :: Natural -> Natural -> Maybe Natural minusNaturalMaybe x y | x >= y = Just (x - y) | otherwise = Nothing instance Bits Natural where Natural n .&. Natural m = Natural (n .&. m) {-# INLINE (.&.) #-} Natural n .|. Natural m = Natural (n .|. m) {-# INLINE (.|.) #-} xor (Natural n) (Natural m) = Natural (xor n m) {-# INLINE xor #-} complement _ = error "Bits.complement: Natural complement undefined" {-# INLINE complement #-} shift (Natural n) = Natural . shift n {-# INLINE shift #-} rotate (Natural n) = Natural . rotate n {-# INLINE rotate #-} bit = Natural . bit {-# INLINE bit #-} setBit (Natural n) = Natural . setBit n {-# INLINE setBit #-} clearBit (Natural n) = Natural . clearBit n {-# INLINE clearBit #-} complementBit (Natural n) = Natural . complementBit n {-# INLINE complementBit #-} testBit (Natural n) = testBit n {-# INLINE testBit #-} bitSizeMaybe _ = Nothing {-# INLINE bitSizeMaybe #-} bitSize = error "Natural: bitSize" {-# INLINE bitSize #-} isSigned _ = False {-# INLINE isSigned #-} shiftL (Natural n) = Natural . shiftL n {-# INLINE shiftL #-} shiftR (Natural n) = Natural . shiftR n {-# INLINE shiftR #-} rotateL (Natural n) = Natural . rotateL n {-# INLINE rotateL #-} rotateR (Natural n) = Natural . rotateR n {-# INLINE rotateR #-} popCount (Natural n) = popCount n {-# INLINE popCount #-} zeroBits = Natural 0 instance Real Natural where toRational (Natural a) = toRational a {-# INLINE toRational #-} instance Enum Natural where pred (Natural 0) = error "Natural.pred: 0" pred (Natural n) = Natural (pred n) {-# INLINE pred #-} succ (Natural n) = Natural (succ n) {-# INLINE succ #-} fromEnum (Natural n) = fromEnum n {-# INLINE fromEnum #-} toEnum n | n < 0 = error "Natural.toEnum: negative" | otherwise = Natural (toEnum n) {-# INLINE toEnum #-} enumFrom = coerce (enumFrom :: Integer -> [Integer]) enumFromThen x y | x <= y = coerce (enumFromThen :: Integer -> Integer -> [Integer]) x y | otherwise = enumFromThenTo x y 0 enumFromTo = coerce (enumFromTo :: Integer -> Integer -> [Integer]) enumFromThenTo = coerce (enumFromThenTo :: Integer -> Integer -> Integer -> [Integer]) instance Integral Natural where quot (Natural a) (Natural b) = Natural (quot a b) {-# INLINE quot #-} rem (Natural a) (Natural b) = Natural (rem a b) {-# INLINE rem #-} div (Natural a) (Natural b) = Natural (div a b) {-# INLINE div #-} mod (Natural a) (Natural b) = Natural (mod a b) {-# INLINE mod #-} divMod (Natural a) (Natural b) = (Natural q, Natural r) where (q,r) = divMod a b {-# INLINE divMod #-} quotRem (Natural a) (Natural b) = (Natural q, Natural r) where (q,r) = quotRem a b {-# INLINE quotRem #-} toInteger (Natural a) = a {-# INLINE toInteger #-} #endif -- | Construct 'Natural' from 'Word' value. -- -- @since 4.8.0.0 wordToNatural :: Word -> Natural #if HAVE_GMP_BIGNAT wordToNatural (W# w#) = NatS# w# #else wordToNatural w = Natural (fromIntegral w) #endif -- | Try downcasting 'Natural' to 'Word' value. -- Returns 'Nothing' if value doesn't fit in 'Word'. -- -- @since 4.8.0.0 naturalToWordMaybe :: Natural -> Maybe Word #if HAVE_GMP_BIGNAT naturalToWordMaybe (NatS# w#) = Just (W# w#) naturalToWordMaybe (NatJ# _) = Nothing #else naturalToWordMaybe (Natural i) | i <= maxw = Just (fromIntegral i) | otherwise = Nothing where maxw = toInteger (maxBound :: Word) #endif -- This follows the same style as the other integral 'Data' instances -- defined in "Data.Data" naturalType :: DataType naturalType = mkIntType "Numeric.Natural.Natural" instance Data Natural where toConstr x = mkIntegralConstr naturalType x gunfold _ z c = case constrRep c of (IntConstr x) -> z (fromIntegral x) _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type Natural" dataTypeOf _ = naturalType -- | \"@'powModNatural' /b/ /e/ /m/@\" computes base @/b/@ raised to -- exponent @/e/@ modulo @/m/@. -- -- @since 4.8.0.0 powModNatural :: Natural -> Natural -> Natural -> Natural #if HAVE_GMP_BIGNAT powModNatural _ _ (NatS# 0##) = throw DivideByZero powModNatural _ _ (NatS# 1##) = NatS# 0## powModNatural _ (NatS# 0##) _ = NatS# 1## powModNatural (NatS# 0##) _ _ = NatS# 0## powModNatural (NatS# 1##) _ _ = NatS# 1## powModNatural (NatS# b) (NatS# e) (NatS# m) = NatS# (powModWord b e m) powModNatural b e (NatS# m) = NatS# (powModBigNatWord (naturalToBigNat b) (naturalToBigNat e) m) powModNatural b e (NatJ# m) = bigNatToNatural (powModBigNat (naturalToBigNat b) (naturalToBigNat e) m) #else -- Portable reference fallback implementation powModNatural _ _ 0 = throw DivideByZero powModNatural _ _ 1 = 0 powModNatural _ 0 _ = 1 powModNatural 0 _ _ = 0 powModNatural 1 _ _ = 1 powModNatural b0 e0 m = go b0 e0 1 where go !b e !r | odd e = go b' e' (r*b `mod` m) | e == 0 = r | otherwise = go b' e' r where b' = b*b `mod` m e' = e `unsafeShiftR` 1 -- slightly faster than "e `div` 2" #endif
urbanslug/ghc
libraries/base/GHC/Natural.hs
bsd-3-clause
21,893
0
13
5,371
4,695
2,371
2,324
165
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} module TcCustomSolverSuper where import GHC.TypeLits import Data.Typeable {- When solving super-class instances, GHC solves the evidence without using the solver (see `tcSuperClasses` in `TcInstDecls`). However, some classes need to be excepted from this behavior, as they have custom solving rules, and this test checks that we got this right. -} class (Typeable x, KnownNat x) => C x class (Typeable x, KnownSymbol x) => D x instance C 2 instance D "2"
wxwxwwxxx/ghc
testsuite/tests/typecheck/should_compile/TcCustomSolverSuper.hs
bsd-3-clause
528
0
6
91
75
40
35
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TypeFamilies #-} -- | This module implements an optimization that tries to statically reuse -- kernel-level allocations. The goal is to lower the static memory usage, which -- might allow more programs to run using intra-group parallelism. module Futhark.Optimise.MemoryBlockMerging (optimise) where import Control.Exception import Control.Monad.Reader import Control.Monad.State.Strict import Data.Function ((&)) import Data.Map (Map, (!)) import qualified Data.Map as M import Data.Set (Set) import qualified Data.Set as S import qualified Futhark.Analysis.Interference as Interference import qualified Futhark.Analysis.LastUse as LastUse import Futhark.Builder.Class import Futhark.Construct import Futhark.IR.GPUMem import qualified Futhark.Optimise.MemoryBlockMerging.GreedyColoring as GreedyColoring import Futhark.Pass (Pass (..), PassM) import qualified Futhark.Pass as Pass import Futhark.Util (invertMap) -- | A mapping from allocation names to their size and space. type Allocs = Map VName (SubExp, Space) getAllocsStm :: Stm GPUMem -> Allocs getAllocsStm (Let (Pat [PatElem name _]) _ (Op (Alloc se sp))) = M.singleton name (se, sp) getAllocsStm (Let _ _ (Op (Alloc _ _))) = error "impossible" getAllocsStm (Let _ _ (If _ then_body else_body _)) = foldMap getAllocsStm (bodyStms then_body) <> foldMap getAllocsStm (bodyStms else_body) getAllocsStm (Let _ _ (DoLoop _ _ body)) = foldMap getAllocsStm (bodyStms body) getAllocsStm _ = mempty getAllocsSegOp :: SegOp lvl GPUMem -> Allocs getAllocsSegOp (SegMap _ _ _ body) = foldMap getAllocsStm (kernelBodyStms body) getAllocsSegOp (SegRed _ _ _ _ body) = foldMap getAllocsStm (kernelBodyStms body) getAllocsSegOp (SegScan _ _ _ _ body) = foldMap getAllocsStm (kernelBodyStms body) getAllocsSegOp (SegHist _ _ _ _ body) = foldMap getAllocsStm (kernelBodyStms body) setAllocsStm :: Map VName SubExp -> Stm GPUMem -> Stm GPUMem setAllocsStm m stm@(Let (Pat [PatElem name _]) _ (Op (Alloc _ _))) | Just s <- M.lookup name m = stm {stmExp = BasicOp $ SubExp s} setAllocsStm _ stm@(Let _ _ (Op (Alloc _ _))) = stm setAllocsStm m stm@(Let _ _ (Op (Inner (SegOp segop)))) = stm {stmExp = Op $ Inner $ SegOp $ setAllocsSegOp m segop} setAllocsStm m stm@(Let _ _ (If cse then_body else_body dec)) = stm { stmExp = If cse (then_body {bodyStms = setAllocsStm m <$> bodyStms then_body}) (else_body {bodyStms = setAllocsStm m <$> bodyStms else_body}) dec } setAllocsStm m stm@(Let _ _ (DoLoop merge form body)) = stm { stmExp = DoLoop merge form (body {bodyStms = setAllocsStm m <$> bodyStms body}) } setAllocsStm _ stm = stm setAllocsSegOp :: Map VName SubExp -> SegOp lvl GPUMem -> SegOp lvl GPUMem setAllocsSegOp m (SegMap lvl sp tps body) = SegMap lvl sp tps $ body {kernelBodyStms = setAllocsStm m <$> kernelBodyStms body} setAllocsSegOp m (SegRed lvl sp segbinops tps body) = SegRed lvl sp segbinops tps $ body {kernelBodyStms = setAllocsStm m <$> kernelBodyStms body} setAllocsSegOp m (SegScan lvl sp segbinops tps body) = SegScan lvl sp segbinops tps $ body {kernelBodyStms = setAllocsStm m <$> kernelBodyStms body} setAllocsSegOp m (SegHist lvl sp segbinops tps body) = SegHist lvl sp segbinops tps $ body {kernelBodyStms = setAllocsStm m <$> kernelBodyStms body} maxSubExp :: MonadBuilder m => Set SubExp -> m SubExp maxSubExp = helper . S.toList where helper (s1 : s2 : sexps) = do z <- letSubExp "maxSubHelper" $ BasicOp $ BinOp (UMax Int64) s1 s2 helper (z : sexps) helper [s] = return s helper [] = error "impossible" definedInExp :: Exp GPUMem -> Set VName definedInExp (Op (Inner (SegOp segop))) = definedInSegOp segop definedInExp (If _ then_body else_body _) = foldMap definedInStm (bodyStms then_body) <> foldMap definedInStm (bodyStms else_body) definedInExp (DoLoop _ _ body) = foldMap definedInStm $ bodyStms body definedInExp _ = mempty definedInStm :: Stm GPUMem -> Set VName definedInStm Let {stmPat = Pat merge, stmExp} = let definedInside = merge & fmap patElemName & S.fromList in definedInExp stmExp <> definedInside definedInSegOp :: SegOp lvl GPUMem -> Set VName definedInSegOp (SegMap _ _ _ body) = foldMap definedInStm $ kernelBodyStms body definedInSegOp (SegRed _ _ _ _ body) = foldMap definedInStm $ kernelBodyStms body definedInSegOp (SegScan _ _ _ _ body) = foldMap definedInStm $ kernelBodyStms body definedInSegOp (SegHist _ _ _ _ body) = foldMap definedInStm $ kernelBodyStms body isKernelInvariant :: SegOp lvl GPUMem -> (SubExp, space) -> Bool isKernelInvariant segop (Var vname, _) = not $ vname `S.member` definedInSegOp segop isKernelInvariant _ _ = True onKernelBodyStms :: MonadBuilder m => SegOp lvl GPUMem -> (Stms GPUMem -> m (Stms GPUMem)) -> m (SegOp lvl GPUMem) onKernelBodyStms (SegMap lvl space ts body) f = do stms <- f $ kernelBodyStms body return $ SegMap lvl space ts $ body {kernelBodyStms = stms} onKernelBodyStms (SegRed lvl space binops ts body) f = do stms <- f $ kernelBodyStms body return $ SegRed lvl space binops ts $ body {kernelBodyStms = stms} onKernelBodyStms (SegScan lvl space binops ts body) f = do stms <- f $ kernelBodyStms body return $ SegScan lvl space binops ts $ body {kernelBodyStms = stms} onKernelBodyStms (SegHist lvl space binops ts body) f = do stms <- f $ kernelBodyStms body return $ SegHist lvl space binops ts $ body {kernelBodyStms = stms} -- | This is the actual optimiser. Given an interference graph and a @SegOp@, -- replace allocations and references to memory blocks inside with a (hopefully) -- reduced number of allocations. optimiseKernel :: (MonadBuilder m, Rep m ~ GPUMem) => Interference.Graph VName -> SegOp lvl GPUMem -> m (SegOp lvl GPUMem) optimiseKernel graph segop0 = do segop <- onKernelBodyStms segop0 $ onKernels $ optimiseKernel graph let allocs = M.filter (isKernelInvariant segop) $ getAllocsSegOp segop (colorspaces, coloring) = GreedyColoring.colorGraph (fmap snd allocs) graph (maxes, maxstms) <- invertMap coloring & M.elems & mapM (maxSubExp . S.map (fst . (allocs !))) & collectStms (colors, stms) <- assert (length maxes == M.size colorspaces) maxes & zip [0 ..] & mapM (\(i, x) -> letSubExp "color" $ Op $ Alloc x $ colorspaces ! i) & collectStms let segop' = setAllocsSegOp (fmap (colors !!) coloring) segop return $ case segop' of SegMap lvl sp tps body -> SegMap lvl sp tps $ body {kernelBodyStms = maxstms <> stms <> kernelBodyStms body} SegRed lvl sp binops tps body -> SegRed lvl sp binops tps $ body {kernelBodyStms = maxstms <> stms <> kernelBodyStms body} SegScan lvl sp binops tps body -> SegScan lvl sp binops tps $ body {kernelBodyStms = maxstms <> stms <> kernelBodyStms body} SegHist lvl sp binops tps body -> SegHist lvl sp binops tps $ body {kernelBodyStms = maxstms <> stms <> kernelBodyStms body} -- | Helper function that modifies kernels found inside some statements. onKernels :: LocalScope GPUMem m => (SegOp SegLevel GPUMem -> m (SegOp SegLevel GPUMem)) -> Stms GPUMem -> m (Stms GPUMem) onKernels f = mapM helper where helper stm@Let {stmExp = Op (Inner (SegOp segop))} = inScopeOf stm $ do exp' <- f segop return $ stm {stmExp = Op $ Inner $ SegOp exp'} helper stm@Let {stmExp = If c then_body else_body dec} = inScopeOf stm $ do then_body_stms <- f `onKernels` bodyStms then_body else_body_stms <- f `onKernels` bodyStms else_body return $ stm { stmExp = If c (then_body {bodyStms = then_body_stms}) (else_body {bodyStms = else_body_stms}) dec } helper stm@Let {stmExp = DoLoop merge form body} = inScopeOf stm $ do stms <- f `onKernels` bodyStms body return $ stm {stmExp = DoLoop merge form (body {bodyStms = stms})} helper stm = inScopeOf stm $ return stm -- | Perform the reuse-allocations optimization. optimise :: Pass GPUMem GPUMem optimise = Pass "reuse allocations" "reuse allocations" $ \prog -> let (lumap, _) = LastUse.analyseProg prog graph = foldMap ( \f -> runReader ( Interference.analyseGPU lumap $ bodyStms $ funDefBody f ) $ scopeOf f ) $ progFuns prog in Pass.intraproceduralTransformation (onStms graph) prog where onStms :: Interference.Graph VName -> Scope GPUMem -> Stms GPUMem -> PassM (Stms GPUMem) onStms graph scope stms = do let m = localScope scope $ optimiseKernel graph `onKernels` stms fmap fst $ modifyNameSource $ runState (runBuilderT m mempty)
HIPERFIT/futhark
src/Futhark/Optimise/MemoryBlockMerging.hs
isc
9,123
0
21
2,146
3,118
1,570
1,548
215
4
{-# LANGUAGE OverloadedStrings #-} module IO where import Prelude hiding (readFile, putStrLn) import Control.Monad (mzero) import Data import Data.Map.Lazy hiding (foldl, map, maximum, member, size) import Data.Text.Lazy hiding (empty, foldl, map, maximum) import Data.Aeson import Data.ByteString.Lazy hiding (empty, foldl, map, maximum) data JsonUnit = JsonUnit { member' :: [Cell], pivot' :: Cell } deriving Show data JsonGame = JsonGame { gid' :: Int, units' :: [JsonUnit], width' :: Int, height' :: Int, filled' :: [Cell], sourceLength' :: Int, sourceSeeds' :: [Int] } deriving Show data JsonSolution = JsonSolution { problemId :: Int, seed :: Int, tag :: Text, solution :: Text } instance FromJSON Cell where parseJSON (Object v) = Cell <$> v .: "x" <*> v .: "y" parseJSON _ = mzero instance FromJSON JsonUnit where parseJSON (Object v) = JsonUnit <$> v .: "members" <*> v .: "pivot" parseJSON _ = mzero instance FromJSON JsonGame where parseJSON (Object v) = JsonGame <$> v .: "id" <*> v .: "units" <*> v .: "width" <*> v .: "height" <*> v .: "filled" <*> v .: "sourceLength" <*> v .: "sourceSeeds" parseJSON _ = mzero instance ToJSON JsonSolution where toJSON solution' = object ["problemId" .= problemId solution', "seed" .= seed solution', "tag" .= tag solution', "solution" .= solution solution'] readJsonGame :: FilePath -> IO (Maybe JsonGame) readJsonGame file = readFile file >>= return . decode printJsonSolution :: [JsonSolution] -> IO () printJsonSolution = putStrLn . encode fromJsonGame :: JsonGame -> Game fromJsonGame json = let size' = Size (width' json) (height' json) in Game { gid = gid' json, size = size', units = map (transformUnit $ width' json) $ units' json, board = foldl fillCell (emptyBoard size') $ filled' json, sourceLength = sourceLength' json, sourceSeeds = sourceSeeds' json } transformUnit :: Int -> JsonUnit -> Unit transformUnit width json = let w' = maximum (map x $ member' json) + 1 h' = maximum (map y $ member' json) + 1 in Unit { member = map (fromCell (pivot' json)) $ member' json, pivot = Cell ((width - w') `div` 2 + (x $ pivot' json)) (y $ pivot' json) } fromCell :: Cell -> Cell -> Position fromCell pivot cell = (x cell - x pivot, y cell - y pivot) emptyBoard :: Size -> Board emptyBoard size = foldl (\m y -> foldl (\m' x -> insert (Cell x y) Empty m') m [0..w size - 1]) empty [0..h size - 1]
marcellussiegburg/icfp-2015
IO.hs
mit
2,757
0
19
811
953
514
439
74
1
module RandomExample1 where import System.Random data Die = DieOne | DieTwo | DieThree | DieFour | DieFive | DieSix deriving (Eq, Show) intToDie :: Int -> Die intToDie n = case n of 1 -> DieOne 2 -> DieTwo 3 -> DieThree 4 -> DieFour 5 -> DieFive 6 -> DieSix x -> error $ "intToDie got non 1-6 integer: " ++ show x rollDieThreeTimes :: (Die, Die, Die) rollDieThreeTimes = do let s = mkStdGen 0 (d1, s1) = randomR (1, 6) s (d2, s2) = randomR (1, 6) s1 (d3, _) = randomR (1, 6) s2 (intToDie d1, intToDie d2, intToDie d3)
JoshuaGross/haskell-learning-log
Code/Haskellbook/State/src/RandomExample1.hs
mit
584
0
11
170
237
129
108
20
7
module Oden.Go.PrettySpec where import Oden.Go.Identifier import Oden.Go.AST import Oden.Go.Type import Oden.Go.Pretty () import Text.PrettyPrint.Leijen import Test.Hspec shouldPrintAs x s = displayS (renderPretty 0.4 100 (pretty x)) "" `shouldBe` s identifierX = Expression (Operand (OperandName (Identifier "x"))) spec :: Spec spec = describe "pretty" $ do describe "Type" $ describe "Interface" $ do it "prints an empty interface" $ Interface [] `shouldPrintAs` "interface{}" it "prints a single-method interface" $ Interface [Method (Identifier "foo") (Parameters [] False) (Returns [])] `shouldPrintAs` "interface {\n foo()\n}" describe "PrimaryExpression" $ do it "prints a function application" $ Application (Operand (OperandName (Identifier "f"))) [Argument identifierX] `shouldPrintAs` "f(x)" it "prints a variadic function application" $ Application (Operand (OperandName (Identifier "f"))) [VariadicSliceArgument identifierX] `shouldPrintAs` "f(x...)" describe "Literal" $ do it "prints a function literal with no parameters and no return value" $ FunctionLiteral (FunctionSignature [] []) (Block []) `shouldPrintAs` "func () {}" it "prints a function literal with no parameters" $ FunctionLiteral (FunctionSignature [] [Basic (Identifier "int") False]) (Block [ReturnStmt [identifierX]]) `shouldPrintAs` "func () int {\n return x\n}" it "prints a function literal with no return value" $ FunctionLiteral (FunctionSignature [FunctionParameter (Identifier "_") (Basic (Identifier "int") False)] []) (Block []) `shouldPrintAs` "func (_ int) {}" it "prints a function literal" $ FunctionLiteral (FunctionSignature [FunctionParameter (Identifier "x") (Basic (Identifier "int") False)] [Basic (Identifier "int") False]) (Block [ReturnStmt [identifierX]]) `shouldPrintAs` "func (x int) int {\n return x\n}" it "prints a function literal with a variadic parameter" $ FunctionLiteral (FunctionSignature [VariadicFunctionParameter (Identifier "_") (Basic (Identifier "int") False)] []) (Block []) `shouldPrintAs` "func (_ ...int) {}" describe "Declaration" $ do it "prints a type declaration" $ TypeDecl (Identifier "Count") (Basic (Identifier "int") False) `shouldPrintAs` "type Count int" it "prints a struct type declaration" $ TypeDecl (Identifier "Count") (Struct [StructField (Identifier "foo") (Basic (Identifier "int") False)]) `shouldPrintAs` "type Count struct {\n foo int\n}" it "prints an interface type declaration" $ TypeDecl (Identifier "Count") (Interface [Method (Identifier "foo") (Parameters [] False) (Returns [])]) `shouldPrintAs` "type Count interface {\n foo()\n}" it "prints an const declaration" $ ConstDecl (Identifier "PI") (Basic (Identifier "float") False) (Expression (Operand (Literal (BasicLiteral (FloatLiteral 3.14))))) `shouldPrintAs` "const PI float = 3.14" it "prints a var declaration" $ VarDecl (VarDeclInitializer (Identifier "count") (Basic (Identifier "int") False) (Expression (Operand (Literal (BasicLiteral (IntLiteral 0)))))) `shouldPrintAs` "var count int = 0" it "prints a function declaration" $ FunctionDecl (Identifier "identity") (FunctionSignature [FunctionParameter (Identifier "x") (Basic (Identifier "int") False)] [Basic (Identifier "int") False]) (Block [ReturnStmt [identifierX]]) `shouldPrintAs` "func identity(x int) int {\n return x\n}" describe "Block" $ do it "prints an empty block" $ Block [] `shouldPrintAs` "{}" it "indents a single stmt in a block" $ Block [ReturnStmt []] `shouldPrintAs` "{\n return\n}" it "indents multiple stmts in a block" $ Block [ReturnStmt [], ReturnStmt []] `shouldPrintAs` "{\n return\n return\n}" it "indents nested blocks" $ Block [BlockStmt (Block [ReturnStmt []])] `shouldPrintAs` "{\n {\n return\n }\n}" describe "Stmt" $ do it "prints a return stmt without expressions" $ ReturnStmt [] `shouldPrintAs` "return" it "prints a return stmt with one expression" $ ReturnStmt [identifierX] `shouldPrintAs` "return x" it "prints a return stmt with multiple expressions" $ ReturnStmt [identifierX, identifierX] `shouldPrintAs` "return x, x" describe "SourceFile" $ do it "prints a source file with only a package clause" $ SourceFile (PackageClause (Identifier "foo")) [] [] `shouldPrintAs` "package foo\n" it "prints a source file with an import" $ SourceFile (PackageClause (Identifier "foo")) [ImportDecl (Identifier "bar") (InterpretedStringLiteral "the/bar")] [] `shouldPrintAs` "package foo\n\nimport bar \"the/bar\"\n" it "prints a source file with a function decl with no stmts" $ SourceFile (PackageClause (Identifier "main")) [] [FunctionDecl (Identifier "main") (FunctionSignature [] []) (Block [])] `shouldPrintAs` "package main\n\nfunc main() {}\n" it "prints a source file with a function decl with a return stmt" $ SourceFile (PackageClause (Identifier "main")) [] [FunctionDecl (Identifier "main") (FunctionSignature [] []) (Block [ReturnStmt []])] `shouldPrintAs` "package main\n\nfunc main() {\n return\n}\n" it "prints a source file with an import and a function decl" $ SourceFile (PackageClause (Identifier "main")) [ImportDecl (Identifier "bar") (InterpretedStringLiteral "the/bar")] [FunctionDecl (Identifier "main") (FunctionSignature [] []) (Block [])] `shouldPrintAs` "package main\n\nimport bar \"the/bar\"\n\nfunc main() {}\n"
AlbinTheander/oden
test/Oden/Go/PrettySpec.hs
mit
6,869
0
25
2,282
1,631
806
825
199
1
module Main (main) where import Network.Hstack import Network.Hstack.Internal import Control.Monad.Identity import Control.Monad.State.Lazy import qualified Data.ByteString as BS import Data.Maybe import Test.Framework.Providers.QuickCheck2 import Test.Framework (defaultMain) test_1 = let a :: OutcomeT Maybe Int a = do c <- return 5 return (c*2) in case (runOutcomeT a) of Just (Ok 10) -> True _ -> False test_2 = let a :: Handler Identity Int Int a = do i <- getInput return (i*2) in case runIdentity . evalAction a $ (Context 5 BS.empty) of Ok 10 -> True _ -> False tests = [ testProperty "CombineT" test_1, testProperty "Handler" test_2] main = defaultMain tests
davidhinkes/hstack
tests/Test.hs
mit
726
0
13
160
260
137
123
28
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} module Hanabi.Client ( startClient ) where import Control.Concurrent.Async (async, cancel) import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, tryTakeMVar) import Control.Monad.IO.Class (liftIO, MonadIO) import Control.Monad.Logger (LoggingT, MonadLogger) import Control.Monad.Trans.Class (lift) import Data.Aeson (encode, eitherDecode, ToJSON) import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.List.NonEmpty as List import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Data.String.Conversions (convertString) import qualified Data.Text as Text import Data.Text (Text) import qualified Network.WebSockets as WS import qualified System.IO as Handle import qualified Hanabi import qualified Hanabi.Client.Cli as Cli import Hanabi.Client.Config (getConfig) import qualified Hanabi.Client.Messaging as Msg import Hanabi.Logging (startLogging, withLogging, logToStderr, Logger, logInfo, logDebug, logWarn) import qualified Hanabi.Print as Print send :: (MonadLogger m, MonadIO m, ToJSON a) => WS.Connection -> a -> m () send conn x = do let msg = encode x logInfo ("Sending JSON:\n" <> convertString (encodePretty x)) liftIO (WS.sendTextData conn msg) receive :: WS.Connection -> LoggingT IO (Either String Msg.Response) receive c = do resp <- liftIO (WS.receiveData c) logDebug ("Received JSON:\n" <> convertString resp) return (eitherDecode resp) startClient :: IO () startClient = do Handle.hSetBuffering Handle.stdin Handle.LineBuffering Handle.hSetBuffering Handle.stdout Handle.LineBuffering Handle.hSetBuffering Handle.stderr Handle.LineBuffering startLogging logToStderr $ \logger -> do logDebug "Starting client." (host, port) <- getConfig name <- Cli.ask "Enter name:" logDebug ("Set name (" <> name <> ")") lift (WS.runClient (convertString host) port "/" (withLogging logger . client logger name)) logDebug "Client stopped." client :: Logger -> Text -> WS.Connection -> LoggingT IO () client logger myName conn = do gameStore <- liftIO newEmptyMVar gameEnded <- liftIO (newEmptyMVar @()) receiveThread <- liftIO (async (withLogging logger (receiver myName gameStore gameEnded conn))) send conn (Msg.ConnectionRequest myName) let myId = Hanabi.PlayerId myName let inputHandler = do input <- Text.toLower <$> Cli.getLn response <- Cli.inputHandler gameStore myId input case response of Cli.SendRequest r -> send conn r Cli.InputErr e -> Cli.putLn e let loop = do inputHandler liftIO (tryTakeMVar gameEnded) >>= \case Nothing -> loop Just _ -> return () loop liftIO (cancel receiveThread) receiver :: Text -> MVar (List.NonEmpty Hanabi.Game) -> MVar () -> WS.Connection -> LoggingT IO () receiver myName gameStore gameEnded conn = receive conn >>= \case Right response -> case response of Msg.GameOverResponse finalScore -> do liftIO (putMVar gameEnded ()) Cli.putLn ("game over - score: " <> Cli.showT finalScore) Msg.ErrorResponse expl details -> do logWarn ("received error message:\n" <> fromMaybe "" details <> "\n" <> expl) loop Msg.ConnectionResponse playerNames -> do Cli.putLn ("current players: " <> Text.intercalate ", " playerNames) --FIXME loop resp -> do let game = Msg.toHanabi (Msg.game_state resp) liftIO (tryTakeMVar gameStore >>= (putMVar gameStore . (maybe (game List.:| [])) (game List.<|))) Print.selectiveFairPrint (Hanabi.PlayerId myName) game loop Left parseError -> logWarn (convertString parseError) >> loop where loop = receiver myName gameStore gameEnded conn
TimoFreiberg/hanabi
src/Hanabi/Client.hs
mit
4,025
0
24
892
1,239
628
611
111
5
----------------------------------------------------------------------------- -- | -- Module : Algebra.Graph.Test.Relation -- Copyright : (c) Andrey Mokhov 2016-2022 -- License : MIT (see the file LICENSE) -- Maintainer : [email protected] -- Stability : experimental -- -- Testsuite for "Algebra.Graph.Relation". ----------------------------------------------------------------------------- module Algebra.Graph.Test.Relation ( -- * Testsuite testRelation ) where import Algebra.Graph.Relation import Algebra.Graph.Relation.Preorder import Algebra.Graph.Relation.Reflexive import Algebra.Graph.Relation.Transitive import Algebra.Graph.Test import Algebra.Graph.Test.API (toIntAPI, relationAPI) import Algebra.Graph.Test.Generic import qualified Algebra.Graph.Class as C tPoly :: Testsuite Relation Ord tPoly = ("Relation.", relationAPI) t :: TestsuiteInt Relation t = fmap toIntAPI tPoly type RI = Relation Int testRelation :: IO () testRelation = do putStrLn "\n============ Relation ============" test "Axioms of graphs" $ size10 $ axioms @RI testConsistent t testShow t testBasicPrimitives t testIsSubgraphOf t testToGraph t testGraphFamilies t testTransformations t testRelational t testInduceJust tPoly putStrLn "\n============ ReflexiveRelation ============" test "Axioms of reflexive graphs" $ size10 $ reflexiveAxioms @(ReflexiveRelation Int) putStrLn "\n============ TransitiveRelation ============" test "Axioms of transitive graphs" $ size10 $ transitiveAxioms @(TransitiveRelation Int) test "path xs == (clique xs :: TransitiveRelation Int)" $ size10 $ \xs -> C.path xs == (C.clique xs :: TransitiveRelation Int) putStrLn "\n============ PreorderRelation ============" test "Axioms of preorder graphs" $ size10 $ preorderAxioms @(PreorderRelation Int) test "path xs == (clique xs :: PreorderRelation Int)" $ size10 $ \xs -> C.path xs == (C.clique xs :: PreorderRelation Int)
snowleopard/alga
test/Algebra/Graph/Test/Relation.hs
mit
2,086
0
12
408
407
206
201
-1
-1
module Settings.Flavours.Quickest (quickestFlavour) where import Flavour import Expression import {-# SOURCE #-} Settings.Default quickestFlavour :: Flavour quickestFlavour = defaultFlavour { name = "quickest" , args = defaultBuilderArgs <> quickestArgs <> defaultPackageArgs , libraryWays = pure [vanilla] , rtsWays = quickestRtsWays } quickestArgs :: Args quickestArgs = sourceArgs $ SourceArgs { hsDefault = pure ["-O0", "-H32m"] , hsLibrary = mempty , hsCompiler = mempty , hsGhc = mempty } quickestRtsWays :: Ways quickestRtsWays = mconcat [ pure [vanilla] , buildHaddock defaultFlavour ? pure [threaded] ]
izgzhen/hadrian
src/Settings/Flavours/Quickest.hs
mit
681
0
9
153
161
96
65
20
1
module Main where import Server main :: IO () main = startServer
evansb/sacred
sacred/Main.hs
mit
68
0
6
15
22
13
9
4
1
-- | -- Module: AI.Fann.Types -- Copyright: (C) 2016 Patrik Sandahl -- Licence: MIT -- Maintainer: Patrik Sandahl <[email protected]> -- Stability: experimental -- Portability: Linux module AI.Fann.Types ( ActivationFunction (..) , InputData , OutputData , activationToInt ) where import qualified Data.Vector.Storable as Vec type InputData = Vec.Vector Float type OutputData = Vec.Vector Float -- | The activation functions used for the neurons during training. data ActivationFunction = Linear | Threshold | ThresholdSymmetric | Sigmoid | SigmoidStepwise | SigmoidSymmetric | SigmoidSymmetricStepwise | Gaussian | GaussianSymmetric | GaussianStepwise | Elliot | ElliotSymmetric | LinearPiece | LinearPieceSymmetric | SinSymmetric | CosSymmetric | Sin | Cos deriving (Eq, Show) -- | Translate an 'ActivationFunction' to Int. activationToInt :: ActivationFunction -> Int activationToInt Linear = 0 activationToInt Threshold = 1 activationToInt ThresholdSymmetric = 2 activationToInt Sigmoid = 3 activationToInt SigmoidStepwise = 4 activationToInt SigmoidSymmetric = 5 activationToInt SigmoidSymmetricStepwise = 6 activationToInt Gaussian = 7 activationToInt GaussianSymmetric = 8 activationToInt GaussianStepwise = 9 activationToInt Elliot = 10 activationToInt ElliotSymmetric = 11 activationToInt LinearPiece = 12 activationToInt LinearPieceSymmetric = 13 activationToInt SinSymmetric = 14 activationToInt CosSymmetric = 15 activationToInt Sin = 16 activationToInt Cos = 17
kosmoskatten/hfann
src/AI/Fann/Types.hs
mit
1,812
0
6
519
287
166
121
47
1
---------- -- Functor ---------- class Functor f where fmap :: (a -> b) -> f a -> f b instance Functor ((->) r) where fmap = (.) --lifting a function ---------------------- -- Applicative Functor ---------------------- class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c liftA2 f a b = f <$> a <*> b --------- -- Monoid --------- class Monoid m where mempty :: m mappend :: m -> m -> m mconcat :: [m] -> m mconcat = foldr mappend mempty foldMap :: (Monoid m, Foldable t) => (a -> m) -> t a -> m data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) instance F.Foldable Tree where foldMap f Empty = mempty foldMap f (Node x l r) = F.foldMap f l `mappend` f x `mappend` F.foldMap f r
zxl20zxl/learnyouahaskell
Typeclasses.hs
mit
924
0
10
293
397
210
187
21
1
module Print3 where myGreeting :: String myGreeting = "hello" ++ "world!" hello :: String hello = "hello" world :: String world = "world!" main :: IO () main = do putStrLn myGreeting putStrLn secondGreeting where secondGreeting = concat [hello, " ", world]
raventid/coursera_learning
haskell/print3.hs
mit
267
0
8
52
84
46
38
12
1
module Hpcb.Data.KicadPCB ( kicadPCB ) where import Hpcb.SExpr import Hpcb.Data.Circuit import Hpcb.Data.NetNumbering import Hpcb.Data.Net -- | Generates the general section from a given circuit. general :: Circuit -> Item general c@(Circuit f g s) = Item "general" [ Item "links" [PInt 0], Item "no_connects" [PInt 0], Item "area" [PInt 0, PInt 0, PInt 0, PInt 0], Item "thickness" [PFloat 1.6], Item "drawings" [PInt drawings], Item "tracks" [PInt tracks], Item "zones" [PInt 0], Item "modules" [PInt modules], Item "nets" [PInt nets] ] where drawings = length g tracks = length s modules = length f nets = length $ listOfNets c -- | Generic layer list. layerList :: Item layerList = Item "layers" [ Item "0" [PString "F.Cu", PString "signal"], Item "31" [PString "B.Cu", PString "signal"], Item "32" [PString "B.Adhes", PString "user"], Item "33" [PString "F.Adhes", PString "user"], Item "34" [PString "B.Paste", PString "user"], Item "35" [PString "F.Paste", PString "user"], Item "36" [PString "B.SilkS", PString "user"], Item "37" [PString "F.SilkS", PString "user"], Item "38" [PString "B.Mask", PString "user"], Item "39" [PString "F.Mask", PString "user"], Item "40" [PString "Dwgs.User", PString "user"], Item "41" [PString "Cmts.User", PString "user"], Item "42" [PString "Eco1.User", PString "user"], Item "43" [PString "Eco2.User", PString "user"], Item "44" [PString "Edge.Cuts", PString "user"], Item "45" [PString "Margin", PString "user"], Item "46" [PString "B.CrtYd", PString "user"], Item "47" [PString "F.CrtYd", PString "user"], Item "48" [PString "B.Fab", PString "user"], Item "49" [PString "F.Fab", PString "user"] ] -- | Generic setup section. setup :: Item setup = Item "setup" [ Item "last_trace_width" [PFloat 0.1524], Item "trace_clearance" [PFloat 0.1524], Item "zone_clearance" [PFloat 0.508], Item "zone_45_only" [PString "no"], Item "trace_min" [PFloat 0.1524], Item "segment_width" [PFloat 0.2], Item "edge_width" [PFloat 0.15], Item "via_size" [PFloat 0.6858], Item "via_drill" [PFloat 0.3302], Item "via_min_size" [PFloat 0.6858], Item "via_min_drill" [PFloat 0.3302], Item "uvia_size" [PFloat 0.762], Item "uvia_drill" [PFloat 0.508], Item "uvias_allowed" [PString "no"], Item "uvia_min_size" [PFloat 0], Item "uvia_min_drill" [PFloat 0], Item "pcb_text_width" [PFloat 0.3], Item "pcb_text_size" [PFloat 1.5, PFloat 1.5], Item "mod_edge_width" [PFloat 0.15], Item "mod_text_size" [PInt 1, PInt 1], Item "mod_text_width" [PFloat 0.15], Item "pad_size" [PFloat 1.524, PFloat 1.524], Item "pad_drill" [PFloat 0.762], Item "pad_to_mask_clearance" [PFloat 0.2], Item "aux_axis_origin" [PInt 0, PInt 0], Item "visible_elements" [PString "FFFFFF7F"], Item "pcbplotparams" [ Item "layerselection" [PString "0x00030_80000001"], Item "usegerberextensions" [PString "false"], Item "excludeedgelayer" [PString "true"], Item "linewidth" [PFloat 0.1], Item "plotframeref" [PString "false"], Item "viasonmask" [PString "false"], Item "mode" [PInt 1], Item "useauxorigin" [PString "false"], Item "hpglpennumber" [PInt 1], Item "hpglpenspeed" [PInt 20], Item "hpglpendiameter" [PInt 15], Item "hpglpenoverlay" [PInt 2], Item "psnegative" [PString "false"], Item "psa4output" [PString "false"], Item "plotreference" [PString "true"], Item "plotvalue" [PString "true"], Item "plotinvisibletext" [PString "false"], Item "padonsilk" [PString "false"], Item "subtractmaskfromsilk" [PString "false"], Item "outputformat" [PInt 1], Item "mirror" [PString "false"], Item "drillshape" [PInt 1], Item "scaleselection" [PInt 1], Item "outputdirectory" [PString "\"\""] ] ] nets :: Circuit -> [Item] nets c = nl where Item _ nl = itemize $ netsMap c -- | Builds the default net class. netClass :: Circuit -> Item netClass c = Item "net_class" ([ PString "Default", PString "\"Ceci est la Netclass par dΓ©faut\"", Item "clearance" [PFloat 0.1524], Item "trace_width" [PFloat 0.1524], Item "via_drill" [PFloat 0.3302], Item "uvia_dia" [PFloat 0.762], Item "uvia_drill" [PFloat 0.508] ] ++ nl ) where nl = map (\n -> Item "add_net" [PString . show $ netName n]) $ listOfNets c -- | Transform a circuit into the S-Expression format. kicadPCB :: Circuit -- ^ Circuit to transform -> Item kicadPCB c@(Circuit f g s) = Item "kicad_pcb" ([ Item "version" [PInt 4], Item "host" [PString "pcbnew", PString "4.0.5+dfsg1-4"], general c, Item "page" [PString "A4"], layerList, setup ] ++ nets c ++ [netClass c] ++ map itemize f ++ map itemize g ++ map itemize s )
iemxblog/hpcb
src/Hpcb/Data/KicadPCB.hs
mit
4,773
0
15
924
1,757
889
868
124
1
module ACME.Yes.PreCure5.GoGo ( module ACME.Yes.PreCure5.GoGo.Profiles , isPreCure5GoGo ) where import ACME.Yes.PreCure5.GoGo.Profiles import ACME.Yes.PreCure5.GoGo.Parser
igrep/yes-precure5-command
ACME/Yes/PreCure5/GoGo.hs
mit
179
0
5
20
38
28
10
5
0
{-# LANGUAGE NoMonomorphismRestriction, FlexibleInstances #-} module Graph.Op ( module Expression.Op , eval, eval0, Graph , example ) where import Expression.Op import qualified Autolib.TES.Binu as U import Autolib.Graph.Graph ( Graph ) import qualified Autolib.Graph.Basic as B import qualified Autolib.Graph.Ops as O import qualified Autolib.Graph.Line as L import Autolib.Hash import Autolib.ToDoc import Autolib.Set ( mkSet ) import Autolib.FiniteMap import Autolib.Reporter eval0 = eval emptyFM eval b = let look x = case lookupFM b x of Just y -> return y Nothing -> reject $ text "Graph.Op.eval:" <+> toDoc x in tfoldR look inter example :: Exp ( Graph Int ) example = read "co P5" instance Ops ( Graph Int ) where bops = U.Binu { U.nullary = nullary , U.unary = unary , U.binary = binary } nullary :: [ Op ( Graph Int ) ] nullary = do ( tag, fun, start ) <- [ ( "K", B.clique . mkSet, 1 ) -- , ( "I", B.independent . mkSet, 2 ) , ( "P", B.path , 3 ) , ( "C", B.circle , 3) ] n <- [ start .. 5 :: Int ] return $ Op { name = tag ++ show n , arity = 0 , precedence = Nothing , assoc = AssocNone , inter = wrapped $ \ [ ] -> fun [ 1 .. n ] } unary :: [ Op ( Graph Int ) ] unary = [ co, line ] co = Op { name = "co" , arity = 1 , precedence = Just 9 , assoc = AssocNone , inter = wrapped $ \ [ x ] -> O.complement x } line = Op { name = "line" , arity = 1 , precedence = Nothing , assoc = AssocNone , inter = wrapped $ \ [ x ] -> L.line_graph x } binary :: [ Op ( Graph Int ) ] binary = [ times, cross, plus ] times = Op { name = "*" , arity = 2 , precedence = Just 8 , assoc = AssocLeft , inter = wrapped $ \ [x, y] -> O.times x y } cross = Op { name = "%" , arity = 2 , precedence = Just 8 , assoc = AssocLeft , inter = wrapped $ \ [x, y] -> O.grid x y } plus = Op { name = "+" , arity = 2 , precedence = Just 7 , assoc = AssocLeft , inter = wrapped $ \ [x, y] -> O.union x y } wrapped fun = \ xs -> return $ O.normalize $ fun xs
Erdwolf/autotool-bonn
src/Graph/Op.hs
gpl-2.0
2,175
14
14
670
817
476
341
58
2
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, UndecidableInstances, FlexibleContexts #-} module Convert.Input where import Autolib.Reader import Autolib.ToDoc import Autolib.Reporter import Autolib.Set import Data.Typeable import Autolib.NFA ( NFAC ) import qualified Autolib.NFA import qualified Autolib.Exp import qualified Autolib.Exp.Inter import qualified Autolib.Exp.Sanity import qualified Exp.Property import qualified NFA.Property import qualified NFA.Test data Autolib.NFA.NFAC c Int => Input c = NFA ( Autolib.NFA.NFA c Int ) | Exp ( Autolib.Exp.RX c ) -- ^ for backward compatibility | Regular_Expression { alphabet :: Set c , expression :: Autolib.Exp.RX c } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''Input]) example :: Input Char example = Regular_Expression { alphabet = mkSet "ab" , expression = read "(a + b^2)^*" } verify_source :: Autolib.NFA.NFAC c Int => Input c -> Reporter () verify_source (NFA aut) = do NFA.Test.test NFA.Property.Sane aut verify_source (Exp e ) = do return () verify_source (e @ Regular_Expression {}) = do Autolib.Exp.Sanity.sanity_alpha ( alphabet e ) ( expression e ) lang :: Autolib.NFA.NFAC c Int => Input c -> Doc lang (NFA aut) = vcat [ text "die von diesem Automaten akzeptierte Sprache:" , nest 4 $ toDoc aut ] lang (Exp e) = vcat [ text "die von diesem Ausdruck erzeugte Sprache:" , nest 4 $ toDoc e ] lang (e @ Regular_Expression {}) = vcat [ text "die von diesem Ausdruck erzeugte Sprache:" , nest 4 $ toDoc $ expression e , text "ΓΌber dem Alphabet" <+> toDoc ( alphabet e ) ] instance Autolib.NFA.NFAC c Int => Nice ( Input c ) where nice = lang min_det_automaton :: Autolib.NFA.NFAC c Int => Input c -> Autolib.NFA.NFA c Int min_det_automaton (NFA aut) = Autolib.NFA.minimize0 aut min_det_automaton (e @ Regular_Expression {}) = Autolib.Exp.Inter.inter_det ( Autolib.Exp.Inter.std_sigma $ setToList $ alphabet e ) ( expression e ) min_det_automaton ( Exp e ) = error "Convert.Input.min_det_automaton: use Regulare_Expression instead of Exp" -- local variables: -- mode: haskell -- end
Erdwolf/autotool-bonn
src/Convert/Input.hs
gpl-2.0
2,230
37
9
479
645
360
285
57
1
{-# LANGUAGE ViewPatterns #-} module Language.Rust.Idiomatic ( itemIdioms ) where import qualified Language.Rust.AST as Rust unsnoc :: [a] -> Maybe ([a], a) unsnoc [] = Nothing unsnoc (x:xs) = case unsnoc xs of Just (a, b) -> Just (x:a, b) Nothing -> Just ([], x) tailExpr :: Rust.Expr -> Maybe (Maybe Rust.Expr) -- If the last statement in this block is a return statement, extract -- its expression (if any) to the final expression position. tailExpr (Rust.Return e) = Just e -- If the last statement is a block, that's a tail-block. tailExpr (Rust.BlockExpr b) = Just (Just (Rust.BlockExpr (tailBlock b))) -- If the last statement is an if-expression, its true and false blocks -- are themselves tail-blocks. -- TODO: treat match-expressions like if-expressions. tailExpr (Rust.IfThenElse c t f) = Just (Just (Rust.IfThenElse c (tailBlock t) (tailBlock f))) -- Otherwise, there's nothing to rewrite. tailExpr _ = Nothing -- Eliminate any return statement that has no statements which -- dynamically follow it. tailBlock :: Rust.Block -> Rust.Block -- If this block already has a final expression, just try to get rid of -- return statements within that expression. tailBlock (Rust.Block b (Just (tailExpr -> Just e))) = Rust.Block b e -- If there's no final expression but the final statement consists of an -- expression that makes sense in the tail position, move it. tailBlock (Rust.Block (unsnoc -> Just (b, Rust.Stmt (tailExpr -> Just e))) Nothing) = Rust.Block b e -- Otherwise, leave this block unchanged. tailBlock b = b itemIdioms :: Rust.Item -> Rust.Item itemIdioms (Rust.Item attrs vis (Rust.Function fattrs name formals ret b)) = Rust.Item attrs vis (Rust.Function fattrs name formals ret (tailBlock b)) itemIdioms i = i
jameysharp/corrode
src/Language/Rust/Idiomatic.hs
gpl-2.0
1,755
0
15
298
484
256
228
21
2
xs = [ 8,2,22,97,38,15,0,40,0,75,4,5,7,78,52,12,50,77,91,8, 49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,4,56,62,0, 81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,3,49,13,36,65, 52,70,95,23,4,60,11,42,69,24,68,56,1,32,56,71,37,2,36,91, 22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80, 24,47,32,60,99,3,45,2,44,75,33,53,78,36,84,20,35,17,12,50, 32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70, 67,26,20,68,2,62,12,20,95,63,94,39,63,8,40,91,66,49,94,21, 24,55,58,5,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72, 21,36,23,9,75,0,76,44,20,45,35,14,0,61,33,97,34,31,33,95, 78,17,53,28,22,75,31,67,15,94,3,80,4,62,16,14,9,53,56,92, 16,39,5,42,96,35,31,47,55,58,88,24,0,17,54,24,36,29,85,57, 86,56,0,48,35,71,89,7,5,44,44,37,44,60,21,58,51,54,17,58, 19,80,81,68,5,94,47,69,28,73,92,13,86,52,17,77,4,89,55,40, 4,52,8,83,97,35,99,16,7,97,57,32,16,26,26,79,33,27,98,66, 88,36,68,87,57,62,20,72,3,46,33,67,46,55,12,32,63,93,53,69, 4,42,16,73,38,25,39,11,24,94,72,18,8,46,29,32,40,62,76,36, 20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,4,36,16, 20,73,35,29,78,31,90,1,74,31,49,71,48,86,81,16,23,57,5,54, 1,70,54,71,83,51,54,69,16,92,33,48,61,43,52,1,89,19,67,48 ] allSeqOfLength :: Int -> Int -> Int -> [a] -> [[a]] allSeqOfLength n w h xs = horizontal ++ vertical ++ forwardDiag ++ backDiag where horizontal = runs [0..w-n] [0..h-1] 1 vertical = runs [0..w-1] [0..h-n] w forwardDiag = runs [n-1..w-1] [0..h-n] (w-1) backDiag = runs [0..w-n] [0..h-n] (w+1) runs xs ys s = [run (x+y*w) s | x <- xs, y <- ys] run i s = map (xs!!) [i,i+s..i+(n-1)*s] answer = maximum $ map (product) $ allSeqOfLength 4 20 20 xs
ciderpunx/project_euler_in_haskell
euler011.hs
gpl-2.0
1,817
0
12
295
1,523
971
552
30
1
module Heqet.Dynamics where import Heqet.Types ppp = 0.05 :: Dynamic pp = 0.1 :: Dynamic p = 0.25 :: Dynamic mp = 0.4 :: Dynamic mf = 0.6 :: Dynamic f = 0.77 :: Dynamic ff = 0.9 :: Dynamic fff = 1 :: Dynamic
Super-Fluid/heqet
Heqet/Dynamics.hs
gpl-3.0
209
0
4
46
75
47
28
10
1
module PropT19 where import Prelude(Bool(..)) import Zeno -- Definitions True && x = x _ && _ = False False || x = x _ || _ = True not True = False not False = True -- Nats data Nat = S Nat | Z (+) :: Nat -> Nat -> Nat Z + y = y (S x) + y = S (x + y) (*) :: Nat -> Nat -> Nat Z * _ = Z (S x) * y = y + (x * y) (==),(/=) :: Nat -> Nat -> Bool Z == Z = True Z == _ = False S _ == Z = False S x == S y = x == y x /= y = not (x == y) (<=) :: Nat -> Nat -> Bool Z <= _ = True _ <= Z = False S x <= S y = x <= y one, zero :: Nat zero = Z one = S Z double :: Nat -> Nat double Z = Z double (S x) = S (S (double x)) even :: Nat -> Bool even Z = True even (S Z) = False even (S (S x)) = even x half :: Nat -> Nat half Z = Z half (S Z) = Z half (S (S x)) = S (half x) mult :: Nat -> Nat -> Nat -> Nat mult Z _ acc = acc mult (S x) y acc = mult x y (y + acc) fac :: Nat -> Nat fac Z = S Z fac (S x) = S x * fac x qfac :: Nat -> Nat -> Nat qfac Z acc = acc qfac (S x) acc = qfac x (S x * acc) exp :: Nat -> Nat -> Nat exp _ Z = S Z exp x (S n) = x * exp x n qexp :: Nat -> Nat -> Nat -> Nat qexp x Z acc = acc qexp x (S n) acc = qexp x n (x * acc) -- Lists length :: [a] -> Nat length [] = Z length (_:xs) = S (length xs) (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) drop :: Nat -> [a] -> [a] drop Z xs = xs drop _ [] = [] drop (S x) (_:xs) = drop x xs rev :: [a] -> [a] rev [] = [] rev (x:xs) = rev xs ++ [x] qrev :: [a] -> [a] -> [a] qrev [] acc = acc qrev (x:xs) acc = qrev xs (x:acc) revflat :: [[a]] -> [a] revflat [] = [] revflat ([]:xss) = revflat xss revflat ((x:xs):xss) = revflat (xs:xss) ++ [x] qrevflat :: [[a]] -> [a] -> [a] qrevflat [] acc = acc qrevflat ([]:xss) acc = qrevflat xss acc qrevflat ((x:xs):xss) acc = qrevflat (xs:xss) (x:acc) rotate :: Nat -> [a] -> [a] rotate Z xs = xs rotate _ [] = [] rotate (S n) (x:xs) = rotate n (xs ++ [x]) elem :: Nat -> [Nat] -> Bool elem _ [] = False elem n (x:xs) = n == x || elem n xs subset :: [Nat] -> [Nat] -> Bool subset [] ys = True subset (x:xs) ys = x `elem` xs && subset xs ys intersect,union :: [Nat] -> [Nat] -> [Nat] (x:xs) `intersect` ys | x `elem` ys = x:(xs `intersect` ys) | otherwise = xs `intersect` ys [] `intersect` ys = [] union (x:xs) ys | x `elem` ys = union xs ys | otherwise = x:(union xs ys) union [] ys = ys isort :: [Nat] -> [Nat] isort [] = [] isort (x:xs) = insert x (isort xs) insert :: Nat -> [Nat] -> [Nat] insert n [] = [n] insert n (x:xs) = case n <= x of True -> n : x : xs False -> x : (insert n xs) count :: Nat -> [Nat] -> Nat count n (x:xs) | n == x = S (count n xs) | otherwise = count n xs count n [] = Z sorted :: [Nat] -> Bool sorted (x:y:xs) = x <= y && sorted (y:xs) sorted _ = True -- Theorem prop_T19 :: [a] -> [a] -> Prop prop_T19 x y = prove (rev (rev x) ++ y :=: rev (rev (x ++ y)))
danr/hipspec
testsuite/prod/zeno_version/PropT19.hs
gpl-3.0
2,988
0
12
922
2,018
1,050
968
114
2
module MimeTypes (MimeType(..), initMimeTypes, mimeTypeOf) where { import qualified Data.Map as Map; import IO; import System.IO.Unsafe; import Data.IORef; import Text.Regex; import Monad; data MimeType = MimeType String String; instance Show MimeType where { showsPrec _ (MimeType part1 part2) = showString (part1 ++ '/' : part2)}; mime_types_ref :: IORef (Map.Map String MimeType); mime_types_ref = unsafePerformIO (newIORef Map.empty); mimeTypeOf :: String -> Maybe MimeType; mimeTypeOf filename = unsafePerformIO (do { mime_types <- readIORef mime_types_ref; let { g (base, "") = Nothing; g (base, ext) = Map.lookup ext mime_types `mplus` g (extension base)}; return $ g (extension filename)}); extension :: String -> (String, String); extension fn = go (reverse fn) "" where { go [] ext = (ext, ""); go ('.' : r) ext = (reverse r, ext); go (x : s) ext = go s (x : ext)}; initMimeTypes :: String -> IO (); initMimeTypes mime_types_file = do { h <- openFile mime_types_file ReadMode; stuff <- hGetContents h; let { mime_types = Map.fromList (parseMimeTypes stuff)}; writeIORef mime_types_ref mime_types}; parseMimeTypes file = [(ext, val) | Just (val, exts) <- map (parseMimeLine . takeWhile (/= '#')) (lines file), ext <- exts]; mimeRegex = mkRegex "^([^/]+)/([^ \t]+)[ \t]+(.*)$"; parseMimeLine l = case matchRegex mimeRegex l of { Just (part1 : part2 : extns : _) -> Just (MimeType part1 part2, words extns); _ -> Nothing}}
ckaestne/CIDE
CIDE_Language_Haskell/test/WSP/Webserver/MimeTypes.hs
gpl-3.0
1,748
0
15
538
603
332
271
43
3
-- file ch03/BadPattern.hs {- An example of what happens when you omit the check for the [] constructor when writing a series of patterns -} badExample (x:xs) = x + badExample xs {- Using a wild card to provide default behaviour for contructors we do not care about -} goodExample (x:xs) = x + goodExample xs goodExample _ = 0
craigem/RealWorldHaskell
ch03/BadPattern.hs
gpl-3.0
334
0
7
67
56
29
27
3
1
module Peer.Handshake.Parse where import Peer.Handshake.Protocol import HTorrentPrelude import Data.Attoparsec as A parseHandshake :: Parser (ByteString, ByteString) parseHandshake = do word8 (fromIntegral protocolLength) >> string protocol <?> "Protocol" A.take 8 <?> "Reserved Bytes" (,) <$> (A.take 20 <?> "Hash") <*> (A.take 20 <?> "Peer ID")
ian-mi/hTorrent
Peer/Handshake/Parse.hs
gpl-3.0
362
0
12
59
115
61
54
9
1
module Parsing where import Text.Trifecta import Control.Applicative data NumberOrString = NOSS String | NOSI Integer deriving (Show) type Major = Integer type Minor = Integer type Patch = Integer type Release = [NumberOrString] type Metadata = [NumberOrString] data SemVer = SemVer Major Minor Patch Release Metadata deriving (Show) parseRelease :: Parser Release parseRelease = do char '-' return [] parseSemVer :: Parser SemVer parseSemVer = do maj <- integer char '.' minor <- integer char '.' patch <- integer release <- (fmap (const []) eof <|> parseRelease) -- many (char '-') return $ SemVer maj minor patch release [(NOSS "")] main :: IO () main = do print $ parseString parseSemVer mempty "2.1.1" print $ parseString parseSemVer mempty "1.0.0-x.7.z.92" --SemVer 2 1 1 [] [] > SemVer 2 10 [] []
thewoolleyman/haskellbook
24/02/haskell-club/Parsing.hs
unlicense
862
0
13
189
267
138
129
31
1
module Polynomial.A330542Spec (main, spec) where import Test.Hspec import Polynomial.A330542 (a330542) main :: IO () main = hspec spec spec :: Spec spec = describe "A330542" $ it "correctly computes the first 20 elements" $ map a330542 [2..21] `shouldBe` expectedValue where expectedValue = [2,6,12,30,60,120,252,504,504,504,504,2730,16380,32760,65520,65520,65520,65520,65520,65520]
peterokagey/haskellOEIS
test/Polynomial/A330542Spec.hs
apache-2.0
397
0
8
57
154
92
62
10
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.NamedTagEventList where import GHC.Generics import Data.Text import Openshift.V1.TagEvent import Openshift.V1.TagEventCondition import qualified Data.Aeson -- | data NamedTagEventList = NamedTagEventList { tag :: Text -- ^ the tag , items :: [TagEvent] -- ^ list of tag events related to the tag , conditions :: Maybe [TagEventCondition] -- ^ the set of conditions that apply to this tag } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON NamedTagEventList instance Data.Aeson.ToJSON NamedTagEventList
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/NamedTagEventList.hs
apache-2.0
723
0
10
113
115
72
43
18
0
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGraphicsScene.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:34 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QGraphicsScene ( ItemIndexMethod, eBspTreeIndex, eNoIndex , SceneLayer, SceneLayers, eItemLayer, fItemLayer, eBackgroundLayer, fBackgroundLayer, eForegroundLayer, fForegroundLayer, eAllLayers, fAllLayers ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CItemIndexMethod a = CItemIndexMethod a type ItemIndexMethod = QEnum(CItemIndexMethod Int) ieItemIndexMethod :: Int -> ItemIndexMethod ieItemIndexMethod x = QEnum (CItemIndexMethod x) instance QEnumC (CItemIndexMethod Int) where qEnum_toInt (QEnum (CItemIndexMethod x)) = x qEnum_fromInt x = QEnum (CItemIndexMethod x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> ItemIndexMethod -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eBspTreeIndex :: ItemIndexMethod eBspTreeIndex = ieItemIndexMethod $ 0 eNoIndex :: ItemIndexMethod eNoIndex = ieItemIndexMethod $ -1 data CSceneLayer a = CSceneLayer a type SceneLayer = QEnum(CSceneLayer Int) ieSceneLayer :: Int -> SceneLayer ieSceneLayer x = QEnum (CSceneLayer x) instance QEnumC (CSceneLayer Int) where qEnum_toInt (QEnum (CSceneLayer x)) = x qEnum_fromInt x = QEnum (CSceneLayer x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> SceneLayer -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () data CSceneLayers a = CSceneLayers a type SceneLayers = QFlags(CSceneLayers Int) ifSceneLayers :: Int -> SceneLayers ifSceneLayers x = QFlags (CSceneLayers x) instance QFlagsC (CSceneLayers Int) where qFlags_toInt (QFlags (CSceneLayers x)) = x qFlags_fromInt x = QFlags (CSceneLayers x) withQFlagsResult x = do ti <- x return $ qFlags_fromInt $ fromIntegral ti withQFlagsListResult x = do til <- x return $ map qFlags_fromInt til instance Qcs (QObject c -> SceneLayers -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qFlags_fromInt hint) return () eItemLayer :: SceneLayer eItemLayer = ieSceneLayer $ 1 eBackgroundLayer :: SceneLayer eBackgroundLayer = ieSceneLayer $ 2 eForegroundLayer :: SceneLayer eForegroundLayer = ieSceneLayer $ 4 eAllLayers :: SceneLayer eAllLayers = ieSceneLayer $ 65535 fItemLayer :: SceneLayers fItemLayer = ifSceneLayers $ 1 fBackgroundLayer :: SceneLayers fBackgroundLayer = ifSceneLayers $ 2 fForegroundLayer :: SceneLayers fForegroundLayer = ifSceneLayers $ 4 fAllLayers :: SceneLayers fAllLayers = ifSceneLayers $ 65535
keera-studios/hsQt
Qtc/Enums/Gui/QGraphicsScene.hs
bsd-2-clause
6,183
0
18
1,403
1,703
846
857
151
1
-- http://www.codewars.com/kata/545f05676b42a0a195000d95 module RankVector where import Data.List import Data.Maybe ranks :: Ord a => [a] -> [Int] ranks xs = map (succ . fromJust . flip elemIndex ys) xs where ys = sortBy (flip compare) xs
Bodigrim/katas
src/haskell/6-Rank-Vector.hs
bsd-2-clause
242
0
9
39
84
45
39
6
1
{-| Module : Grammar.MC Description : Definition of the MC monad. Copyright : (c) Davide Mancusi, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : POSIX This module exports the 'MC' (Monte Carlo) monad, which can be used to stream the pseudo-random number generator seed through different applications. -} module Grammar.MC ( -- * The 'MC' monad MC , Sized , Seed , evalMC , evalMCSized -- * Sampling random numbers , getGen , putGen , getSize , putSize , scaleSize , getSizeMC , putSizeMC , scaleSizeMC , uniform , uniformInt , sampleExp , sampleSizedExp , pickRandom -- * Reexported from 'Control.Monad.State' , lift ) where -- system imports import Control.Monad.State import System.Random.TF import System.Random.TF.Gen import System.Random.TF.Instances import Data.Int import Data.Foldable (Foldable, length, toList) -- local imports import Grammar.Size -------------------- -- the MC monad -- -------------------- -- | Just a type alias for the PRNG seed. type Seed = Int -- | The 'MC' type is just an alias for a monad transformer stack. Yes, 'MC' -- stands for Monte Carlo. type MC = StateT TFGen (State Size) type Sized = State Size oneOverMaxInt64 :: Fractional a => a oneOverMaxInt64 = 1.0 / fromIntegral (maxBound::Int64) {- | How do I escape from the 'MC' monad? Just call 'evalMC' and supply a starting seed for the pseudo-random number generator. -} evalMC :: MC a -- ^ the computation to perform -> Seed -- ^ the starting seed -> a -- ^ the computation result evalMC = let defaultSize = 5.0 in evalMCSized defaultSize {- | If you want more control over the size of the generated expressions, you can use 'evalMCSized' to escape from the 'MC' monad. This allows you to provide an expected size for the resulting expressions. Note that @evalMC == evalMCSized 5.0@. -} evalMCSized :: Size -- ^ the size -> MC a -- ^ the computation to perform -> Seed -- ^ the starting seed -> a -- ^ the computation result evalMCSized size obj seed = let initialGen = mkTFGen seed in evalState (evalStateT obj initialGen) size ----------------------------------------------- -- some machinery to sample random numbers -- ----------------------------------------------- -- | Extract the random-number generator. getGen :: (RandomGen g, MonadState g m) => m g getGen = get -- | Update the random-number generator. putGen :: (RandomGen g, MonadState g m) => g -> m () putGen = put -- | Extract the current size. getSize :: MonadState Size m => m Size getSize = get -- | Update the current size. putSize :: MonadState Size m => Size -> m () putSize = put -- | Scale the current size by a given factor. scaleSize :: MonadState Size m => Size -> m () scaleSize scaling = do size <- get put $ size*scaling -- | Extract the current size. getSizeMC :: MC Size getSizeMC = lift get -- | Update the current size. putSizeMC :: Size -> MC () putSizeMC size = lift (put size) -- | Scale the current size by a given factor. scaleSizeMC :: Size -> MC () scaleSizeMC scaling = do size <- getSizeMC putSizeMC $ size*scaling -- | Return a uniformly distributed 'Fractional' random number between 0 and 1. -- The interval bounds may or may not be included. uniform :: (RandomGen g, Fractional a, MonadState g m) => m a uniform = do gen <- getGen let (i, gen') = randomR (1, maxBound::Int64) gen let xi = fromIntegral (i::Int64) * oneOverMaxInt64 putGen gen' return xi -- | Return a uniformly distributed integer between the specified minimum and -- maximum values (included). uniformInt :: (RandomGen g, Random a, Integral a, MonadState g m) => a -- ^ the minimum value -> a -- ^ the maximum value -> m a -- ^ the sampled value uniformInt minVal maxVal = do gen <- getGen let (xi, gen') = randomR (minVal, maxVal) gen putGen gen' return xi -- | Sample from an exponential distribution of the form -- @ -- f(x) = exp(-&#x3BB; x)/&#x3BB; -- @ sampleExp :: (RandomGen g, MonadState g m) => Double -- ^ The distribution mean -> m Double sampleExp lambda = do xi <- uniform return $ (-lambda) * log xi -- | Sample from an exponential distribution and take the current size as the -- distribution parameter. sampleSizedExp :: MC Double sampleSizedExp = do xi <- uniform lambda <- getSizeMC let lambda' = realToFrac lambda return $ (-lambda') * log xi -- | Pick a random element from a Foldable container. pickRandom :: (RandomGen g, MonadState g m, Foldable t) => t a -> m a pickRandom set = let l = toList set n = length l in do ran <- uniformInt 0 (n-1) return $ l !! ran
arekfu/grammar-haskell
src/Grammar/MC.hs
bsd-3-clause
4,936
0
12
1,237
999
535
464
-1
-1
module Misc where import Control.Applicative import System.Directory import System.FilePath import Data.List feither :: Either a b -> (a -> c) -> (b -> c) -> c feither e f g = either f g e fmaybe :: Maybe a -> b -> (a -> b) -> b fmaybe m f g = maybe f g m dotMo :: String -> Bool dotMo = isSuffixOf ".mo" getDirectoryContentsFullPath :: FilePath -> IO [FilePath] getDirectoryContentsFullPath dir = map (dir </>) <$> getDirectoryContents dir fileName :: FilePath -> String fileName = takeFileName . dropExtension
bergmark/mmdoc
src/Misc.hs
bsd-3-clause
559
0
9
137
197
104
93
15
1
module Main where import HW3Test (hw3Tests) import HW4Test (hw4Tests) import HW5Test (hw5Tests) import HW6Test (hw6Tests) import HW7Test (hw7Tests) import HW8Test (hw8Tests) import HW10Test (hw10Tests) import HW11Test (hw11Tests) import HW12Test (hw12Tests) import Test.Tasty -- TODO: eliminate all the duplication in these hwNTests fns main :: IO () main = do testTrees <- sequence [ hw3Tests , hw4Tests , hw5Tests , hw6Tests , hw7Tests , hw8Tests , hw10Tests , hw11Tests , hw12Tests ] defaultMain (testGroup "All Tests" testTrees)
cgag/cis-194-solutions
test/Main.hs
bsd-3-clause
880
0
9
423
148
88
60
23
1
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} -- Haskell implementation of H2O's priority queue. -- https://github.com/h2o/h2o/blob/master/lib/http2/scheduler.c module RingOfQueues ( Entry , newEntry , renewEntry , item , Node , PriorityQueue(..) , new , enqueue , dequeue , delete ) where import Control.Monad (replicateM) import Data.Array (Array, listArray, (!)) import Data.Bits (setBit, clearBit, shiftR) import Data.IORef import Data.Word (Word64) import Foreign.C.Types (CLLong(..)) import DoublyLinkedQueueIO (Queue, Node) import qualified DoublyLinkedQueueIO as Q ---------------------------------------------------------------- type Weight = Int -- | Abstract data type of entries for priority queues. data Entry a = Entry { item :: a -- ^ Extracting an item from an entry. , weight :: {-# UNPACK #-} !Weight , deficit :: {-# UNPACK #-} !Int } deriving Show newEntry :: a -> Weight -> Entry a newEntry x w = Entry x w 0 -- | Changing the item of an entry. renewEntry :: Entry a -> b -> Entry b renewEntry ent x = ent { item = x } ---------------------------------------------------------------- data PriorityQueue a = PriorityQueue { bitsRef :: IORef Word64 , offsetRef :: IORef Int , queues :: Array Int (Queue (Entry a)) } ---------------------------------------------------------------- bitWidth :: Int bitWidth = 64 relativeIndex :: Int -> Int -> Int relativeIndex idx offset = (offset + idx) `mod` bitWidth ---------------------------------------------------------------- deficitSteps :: Int deficitSteps = 65536 deficitList :: [Int] deficitList = map calc idxs where idxs :: [Double] idxs = [1..256] calc w = round (65536 * 63 / w) deficitTable :: Array Int Int deficitTable = listArray (1,256) deficitList ---------------------------------------------------------------- -- https://en.wikipedia.org/wiki/Find_first_set foreign import ccall unsafe "strings.h ffsll" c_ffs :: CLLong -> CLLong -- | Finding first bit set. O(1) -- -- >>> firstBitSet $ setBit 0 63 -- 63 -- >>> firstBitSet $ setBit 0 62 -- 62 -- >>> firstBitSet $ setBit 0 1 -- 1 -- >>> firstBitSet $ setBit 0 0 -- 0 -- >>> firstBitSet 0 -- -1 firstBitSet :: Word64 -> Int firstBitSet x = ffs x - 1 where ffs = fromIntegral . c_ffs . fromIntegral ---------------------------------------------------------------- new :: IO (PriorityQueue a) new = PriorityQueue <$> newIORef 0 <*> newIORef 0 <*> newQueues where newQueues = listArray (0, bitWidth - 1) <$> replicateM bitWidth Q.new -- | Enqueuing an entry. PriorityQueue is updated. enqueue :: Entry a -> PriorityQueue a -> IO (Node (Entry a)) enqueue ent PriorityQueue{..} = do let (!idx,!deficit') = calcIdxAndDeficit !offidx <- getOffIdx idx node <- push offidx ent { deficit = deficit' } updateBits idx return node where calcIdxAndDeficit = total `divMod` deficitSteps where total = deficitTable ! weight ent + deficit ent getOffIdx idx = relativeIndex idx <$> readIORef offsetRef push offidx ent' = Q.enqueue ent' (queues ! offidx) updateBits idx = modifyIORef' bitsRef $ flip setBit idx -- | Dequeuing an entry. PriorityQueue is updated. dequeue :: PriorityQueue a -> IO (Maybe (Entry a)) dequeue pq@PriorityQueue{..} = do !idx <- getIdx if idx == -1 then return Nothing else do !offidx <- getOffIdx idx updateOffset offidx queueIsEmpty <- checkEmpty offidx updateBits idx queueIsEmpty if queueIsEmpty then dequeue pq else Just <$> pop offidx where getIdx = firstBitSet <$> readIORef bitsRef getOffIdx idx = relativeIndex idx <$> readIORef offsetRef pop offidx = Q.dequeue (queues ! offidx) checkEmpty offidx = Q.isEmpty (queues ! offidx) updateOffset offset' = writeIORef offsetRef offset' updateBits idx isEmpty = modifyIORef' bitsRef shiftClear where shiftClear bits | isEmpty = clearBit (shiftR bits idx) 0 | otherwise = shiftR bits idx -- bits is not updated because it's difficult. delete :: Node (Entry a) -> IO () delete node = Q.delete node
kazu-yamamoto/http2
bench-priority/RingOfQueues.hs
bsd-3-clause
4,292
0
13
914
1,105
588
517
94
3
{-# LANGUAGE PackageImports #-} module Text.ParserCombinators.ReadP (module M) where import "base" Text.ParserCombinators.ReadP as M
silkapp/base-noprelude
src/Text/ParserCombinators/ReadP.hs
bsd-3-clause
138
0
4
18
23
17
6
3
0
module VisualizationData.Queue.Bankers where import VisualizationData.Queue.Interface import qualified Data.List as L import qualified VisualizationData.LenList as LL data BQueue a = BQueue { heads :: LL.LenList a , tails :: LL.LenList a } instance Show a => Show (BQueue a) where show q = "fromList " ++ show (toList q) instance Eq a => Eq (BQueue a) where q == r = toList q == toList r instance Queue BQueue where qempty = empty qsnoc = snoc quncons = uncons toList :: BQueue a -> [a] toList bq = LL.items (heads bq) ++ L.reverse (LL.items (tails bq)) fromList :: [a] -> BQueue a fromList xs = BQueue { heads = LL.fromNormalList xs, tails = mempty } empty :: BQueue a empty = BQueue { heads = mempty, tails = mempty } null :: BQueue a -> Bool null bq = LL.null (heads bq) mappendReverse' :: [a] -> [a] -> [a] mappendReverse' = go [] where go rs [] [] = rs go rs (x:xs) (y:ys) = x : go (y:rs) xs ys go _ _ _ = error "not expected!" mappendReverse :: LL.LenList a -> LL.LenList a -> LL.LenList a mappendReverse (LL.LenList n xs) (LL.LenList m ys) = LL.LenList (n+m) (mappendReverse' xs ys) mkBQueue :: LL.LenList a -> LL.LenList a -> BQueue a mkBQueue xs ys = if LL.length xs > LL.length ys then BQueue { heads = xs, tails = ys } else BQueue { heads = mappendReverse xs ys, tails = mempty } uncons :: BQueue a -> Maybe (a, BQueue a) uncons bq = case LL.uncons (heads bq) of Nothing -> Nothing Just (x, xs) -> Just (x, mkBQueue xs (tails bq)) tail :: BQueue a -> Maybe (BQueue a) tail q = snd <$> uncons q snoc :: BQueue a -> a -> BQueue a snoc bq y = if LL.null (heads bq) then BQueue { heads = LL.singleton y, tails = mempty } else mkBQueue (heads bq) (LL.cons y (tails bq))
timjb/pfds-visualizations
src/VisualizationData/Queue/Bankers.hs
bsd-3-clause
1,779
0
12
427
823
426
397
57
3
{-# LANGUAGE QuasiQuotes #-} module Main where import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit (Assertion, (@?=)) import qualified Data.ByteString.Char8 as B import Data.Loc (SrcLoc, noLoc, startPos) import Control.Exception (SomeException) import Language.C.Quote.C import qualified Language.C.Syntax as C import qualified Language.C.Parser as P import Numeric (showHex) import Objc (objcTests) import CUDA (cudaTests) import System.Exit (exitFailure, exitSuccess) import Text.PrettyPrint.Mainland main :: IO () main = defaultMain tests tests :: [Test] tests = [ constantTests , constantAntiquotationsTests , cQuotationTests , cPatternAntiquotationTests , statementCommentTests , regressionTests , objcTests , cudaTests ] constantTests :: Test constantTests = testGroup "Constants" [ testCase "octal constant" test_octint , testCase "hex constant" test_hexint , testCase "unsigned hex constant" test_hexint_u , testCase "unsigned long hex constant" test_hexint_ul , testCase "unsigned long long hex constant hexint" test_hexint_ull ] where test_octint :: Assertion test_octint = [cexp|010|] @?= C.Const (C.IntConst "010" C.Signed 8 noLoc) noLoc test_hexint :: Assertion test_hexint = [cexp|0x10|] @?= C.Const (C.IntConst "0x10" C.Signed 16 noLoc) noLoc test_hexint_u :: Assertion test_hexint_u = [cexp|0x10U|] @?= C.Const (C.IntConst "0x10U" C.Unsigned 16 noLoc) noLoc test_hexint_ul :: Assertion test_hexint_ul = [cexp|0x10UL|] @?= C.Const (C.LongIntConst "0x10UL" C.Unsigned 16 noLoc) noLoc test_hexint_ull :: Assertion test_hexint_ull = [cexp|0x10ULL|] @?= C.Const (C.LongLongIntConst "0x10ULL" C.Unsigned 16 noLoc) noLoc constantAntiquotationsTests :: Test constantAntiquotationsTests = testGroup "Constant antiquotations" [ testCase "int antiquotes" test_int , testCase "hex Const antiquote" test_hexconst , testCase "unsigned hex Const antiquote" test_hexconst_u , testCase "float antiquotes" test_float , testCase "char antiquote" test_char , testCase "string antiquote" test_string , testCase "unsigned long antiquote of Haskell expression" test_int_hsexp ] where test_int :: Assertion test_int = [cexp|$int:one + $uint:one + $lint:one + $ulint:one + $llint:one + $ullint:one|] @?= [cexp|1 + 1U + 1L + 1UL + 1LL + 1ULL|] where one = 1 test_hexconst :: Assertion test_hexconst = [cexp|$const:(hexconst 10)|] @?= C.Const (C.IntConst "0xa" C.Signed 10 noLoc) noLoc where hexconst :: Integral a => a -> C.Const hexconst i = C.IntConst ("0x" ++ showHex x "") C.Signed x noLoc where x :: Integer x = fromIntegral i test_hexconst_u :: Assertion test_hexconst_u = [cexp|$const:(hexconst_u 10)|] @?= C.Const (C.IntConst "0xa" C.Unsigned 10 noLoc) noLoc where hexconst_u :: Integral a => a -> C.Const hexconst_u i = C.IntConst ("0x" ++ showHex x "") C.Unsigned x noLoc where x :: Integer x = fromIntegral i test_float :: Assertion test_float = [cexp|$float:one + $double:one + $ldouble:one|] @?= [cexp|1.0F + 1.0 + 1.0L|] where one = 1 test_char :: Assertion test_char = [cexp|$char:a|] @?= [cexp|'a'|] where a = 'a' test_string :: Assertion test_string = [cexp|$string:hello|] @?= [cexp|"Hello, world\n"|] where hello = "Hello, world\n" test_int_hsexp :: Assertion test_int_hsexp = [cexp|$ulint:(13 - 2*5)|] @?= [cexp|3UL|] cQuotationTests :: Test cQuotationTests = testGroup "C quotations" [ testCase "identifier antiquote" test_id , testCase "expression antiquote" test_exp , testCase "function antiquote" test_func , testCase "args antiquote" test_args , testCase "declaration antiquote" test_decl , testCase "struct declaration antiquote" test_sdecl , testCase "external declaration antiquote" test_edecl , testCase "enum antiquote" test_enum , testCase "statement antiquote" test_stm , testCase "parameter antiquote" test_param , testCase "type qualifier antiquote" test_tyqual , testCase "type qualifiers antiquote" test_tyquals , testCase "type antiquote" test_ty , testCase "initializer antiquote" test_init , testCase "initializers antiquote" test_inits , testCase "block items antiquote" test_item ] where test_id :: Assertion test_id = [cexp|$id:f($id:x, $id:y)|] @?= [cexp|f(x, y)|] where f :: String f = "f" x :: SrcLoc -> C.Id x = C.Id "x" y :: C.Id y = C.Id "y" noLoc test_exp :: Assertion test_exp = [cexp|$exp:e1 + $exp:e2|] @?= [cexp|1 + 2|] where e1 = [cexp|1|] e2 = [cexp|2|] test_func :: Assertion test_func = [cunit|$func:f|] @?= [cunit|int add(int x) { return x + 10; }|] where f = add 10 add n = [cfun|int add(int x) { return x + $int:n; } |] test_args :: Assertion test_args = [cstm|f($exp:e1, $args:args, $exp:e2);|] @?= [cstm|f(1, 2, 3, 4);|] where e1 = [cexp|1|] e2 = [cexp|4|] args = [[cexp|2|], [cexp|3|]] test_decl :: Assertion test_decl = [cfun|int inc(int n) { $decl:d1; $decls:decls return n + 1; }|] @?= [cfun|int inc(int n) { int i; int j; char c = 'c'; return n + 1; }|] where d1 = [cdecl|int i;|] d2 = [cdecl|int j;|] d3 = [cdecl|char c = 'c';|] decls = [d2, d3] test_sdecl :: Assertion test_sdecl = [cty|struct foo { $sdecl:d1 $sdecls:decls }|] @?= [cty|struct foo { int i; int j; char c; }|] where d1 = [csdecl|int i;|] d2 = [csdecl|int j;|] d3 = [csdecl|char c;|] decls = [d2, d3] test_edecl :: Assertion test_edecl = [cunit|$edecl:d1 $edecls:decls|] @?= [cunit|int i; int j; char c = 'c';|] where d1 = [cedecl|int i;|] d2 = [cedecl|int j;|] d3 = [cedecl|char c = 'c';|] decls = [d2, d3] test_enum :: Assertion test_enum = [cty|enum foo { $enum:enum1, $enums:enums }|] @?= [cty|enum foo { A = 0, B, C = 2 }|] where enum1 = [cenum|A = 0|] enum2 = [cenum|B|] enum3 = [cenum|C = 2|] enums = [enum2, enum3] test_stm :: Assertion test_stm = [cfun|int add(int x) { $stms:stms return x + 1; }|] @?= [cfun|int add(int x) { a = 1; b = 2; return x + 1; }|] where one = 1 stm1 = [cstm|a = $int:one;|] stm2 = [cstm|b = 2;|] stms = [stm1, stm2] test_param :: Assertion test_param = [cdecl|int f($param:ty1, $params:tys);|] @?= [cdecl|int f(char, int, float);|] where ty1 = [cparam|char|] ty2 = [cparam|int|] ty3 = [cparam|float|] tys = [ty2, ty3] test_tyqual :: Assertion test_tyqual = [cdecl|$tyqual:tyqual int i;|] @?= [cdecl|const int i;|] where tyqual = C.Tconst noLoc test_tyquals :: Assertion test_tyquals = [cdecl|$tyquals:tyquals int i;|] @?= [cdecl|const volatile int i;|] where tyquals = [ctyquals|const volatile|] test_ty :: Assertion test_ty = [cdecl|$ty:ty1 f(const $ty:ty2);|] @?= [cdecl|int f(const float);|] where ty1 = [cty|int|] ty2 = [cty|float|] test_init :: Assertion test_init = [cinit|{$init:initializer, .a = 10}|] @?= [cinit|{{.d = 1}, .a = 10}|] where initializer = [cinit|{.d = 1}|] test_inits :: Assertion test_inits = [cinit|{$inits:([initializer1, initializer2])}|] @?= [cinit|{{.d = 1},{.a = 10}}|] where initializer1 = [cinit|{.d = 1}|] initializer2 = [cinit|{.a = 10}|] test_item :: Assertion test_item = [cfun|int add(int x) { int y = 2; return x + y; }|] @?= [cfun|int add(int x) { $items:([item1, item2]) }|] where item1 = [citem|int y = 2;|] item2 = [citem|return x + y;|] cPatternAntiquotationTests :: Test cPatternAntiquotationTests = testGroup "C pattern antiquotations" [ testCase "arguments pattern antiquote" pat_args ] where pat_args :: Assertion pat_args = stms @?= [[cexp|2|], [cexp|3|]] where stms = case [cstm|f(1, 2, 3);|] of [cstm|f(1, $args:es);|] -> es _ -> [] statementCommentTests :: Test statementCommentTests = testGroup "Statement comments" [ testCase "lbrace comment" test_lbrace_comment , testCase "semi comment" test_semi_comment , testCase "c comment" test_c_comment , testCase "c++ comment" test_cxx_comment , testCase "antiquote comment" test_antiquote_comment , testCase "comment at end of statements quote" test_stms_end_comment , testCase "comment before antiquoted statements" test_block_stms_comment ] where test_lbrace_comment :: Assertion test_lbrace_comment = [cstm|{ $comment:("/* Test 1 */") return x + y; }|] @?= [cstm|{/* Test 1 */ return x + y; }|] test_semi_comment :: Assertion test_semi_comment = [cstms|x = 1; $comment:("/* Test 1 */") return x + y;|] @?= [cstms|x = 1; /* Test 1 */ return x + y;|] assign_a_equals_one = C.Exp (Just $ C.Assign (C.Var (C.Id "a" noLoc) noLoc) C.JustAssign (C.Const (C.IntConst "1" C.Signed 1 noLoc) noLoc) noLoc) noLoc test_c_comment = [cstms| a = 1; /* c style comment */ |] @?= [ assign_a_equals_one , C.Comment "/* c style comment */" (C.Exp Nothing noLoc) noLoc ] test_cxx_comment = [cstms| a = 1; // c++ style comment |] @?= [ assign_a_equals_one , C.Comment "// c++ style comment" (C.Exp Nothing noLoc) noLoc ] test_antiquote_comment = [cstms| $comment:("/* antiquote comment */") |] @?= [ C.Comment "/* antiquote comment */" (C.Exp Nothing noLoc) noLoc ] test_stms_end_comment :: Assertion test_stms_end_comment = [cstms|x = 1; return x + y; $comment:("// Test")|] @?= [cstms|x = 1; return x + y; // Test|] test_block_stms_comment :: Assertion test_block_stms_comment = [cstm|{ int a; $decl:decl; /* Test */ $stms:stms }|] @?= [cstm|{ int a; int b; a = 1; b = 2;}|] where decl = [cdecl|int b;|] stm1 = [cstm|a = 1;|] stm2 = [cstm|b = 2;|] stms = [stm1, stm2] regressionTests :: Test regressionTests = testGroup "Regressions" [ testCase "pragmas" test_pragmas , issue48 , testCase "Issue #44" issue44 , issue43 ] where test_pragmas :: Assertion test_pragmas = [cstms| #pragma omp sections { #pragma omp section a = 1; } |] @?= [ C.Pragma "omp sections" noLoc , C.Block [ C.BlockStm (C.Pragma "omp section" noLoc) , C.BlockStm (C.Exp (Just $ C.Assign (C.Var (C.Id "a" noLoc) noLoc) C.JustAssign (C.Const (C.IntConst "1" C.Signed 1 noLoc) noLoc) noLoc) noLoc) ] noLoc ] issue48 :: Test issue48 = testGroup "Issue #48" [ testCase "-(-42)" test_issue48_1 , testCase "--(-42)" test_issue48_2 , testCase "-(--42)" test_issue48_3 , testCase "+(+42)" test_issue48_4 , testCase "++(+42)" test_issue48_5 , testCase "+(++42)" test_issue48_6 ] where test_issue48_1 :: Assertion test_issue48_1 = pretty 80 (ppr [cexp|-(-42)|]) @?= "-(-42)" test_issue48_2 :: Assertion test_issue48_2 = pretty 80 (ppr [cexp|--(-42)|]) @?= "--(-42)" test_issue48_3 :: Assertion test_issue48_3 = pretty 80 (ppr [cexp|-(--42)|]) @?= "-(--42)" test_issue48_4 :: Assertion test_issue48_4 = pretty 80 (ppr [cexp|+(+42)|]) @?= "+(+42)" test_issue48_5 :: Assertion test_issue48_5 = pretty 80 (ppr [cexp|++(+42)|]) @?= "++(+42)" test_issue48_6 :: Assertion test_issue48_6 = pretty 80 (ppr [cexp|+(++42)|]) @?= "+(++42)" issue44 :: Assertion issue44 = case parseDecl "$ty:something c;" of Left err -> fail (show err) Right grp -> (pretty 80 . ppr) grp @?= "$ty:something c" where parseDecl :: String -> Either SomeException C.InitGroup parseDecl s = P.parse [C.Antiquotation] [] P.parseDecl (B.pack s) (startPos "<inline>") issue43 :: Test issue43 = testGroup "Issue #43" [ testCase "float _Complex" test_issue43_1 , testCase "long double _Complex" test_issue43_2 , testCase "long _Complex double" test_issue43_3 , testCase "_Imaginary long double" test_issue43_4 ] where test_issue43_1 :: Assertion test_issue43_1 = [cty|float _Complex|] @?= C.Type (C.DeclSpec [] [] (C.Tfloat_Complex noLoc) noLoc) (C.DeclRoot noLoc) noLoc test_issue43_2 :: Assertion test_issue43_2 = [cty|long double _Complex|] @?= C.Type (C.DeclSpec [] [] (C.Tlong_double_Complex noLoc) noLoc) (C.DeclRoot noLoc) noLoc test_issue43_3 :: Assertion test_issue43_3 = [cty|long _Complex double|] @?= C.Type (C.DeclSpec [] [] (C.Tlong_double_Complex noLoc) noLoc) (C.DeclRoot noLoc) noLoc test_issue43_4 :: Assertion test_issue43_4 = [cty|_Imaginary long double|] @?= C.Type (C.DeclSpec [] [] (C.Tlong_double_Imaginary noLoc) noLoc) (C.DeclRoot noLoc) noLoc
flowbox-public/language-c-quote
tests/unit/Main.hs
bsd-3-clause
15,024
0
21
5,117
3,151
1,900
1,251
346
2
{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} module Data.Logic.Atomic.Class where import Data.Functor.Identity import Data.Functor.Compose class Atomic a r | r -> a where atom :: a -> r data AnyAtomic a = AnyAtomic { getAtomic :: forall r. Atomic a r => r } instance Atomic a (AnyAtomic a) where atom a = AnyAtomic $ atom a -- Atomic instances {{{ instance Atomic Bool Bool where atom = id instance Atomic String String where atom = id instance Atomic a r => Atomic a (Identity r) where atom = return . atom instance Atomic a (f (g r)) => Atomic a (Compose f g r) where atom = Compose . atom instance Atomic a r => Atomic a (Maybe r) where atom = return . atom instance Atomic a r => Atomic a [r] where atom = return . atom instance Atomic a r => Atomic a (Either e r) where atom = return . atom instance Atomic a r => Atomic a (b -> r) where atom = return . atom instance Atomic a r => Atomic a (IO r) where atom = return . atom instance ( Atomic a r , Atomic a s ) => Atomic a (r,s) where atom a = ( atom a , atom a ) instance ( Atomic a r , Atomic a s , Atomic a t ) => Atomic a (r,s,t) where atom a = ( atom a , atom a , atom a ) instance ( Atomic a r , Atomic a s , Atomic a t , Atomic a u ) => Atomic a (r,s,t,u) where atom a = ( atom a , atom a , atom a , atom a) instance ( Atomic a r , Atomic a s , Atomic a t , Atomic a u , Atomic a v ) => Atomic a (r,s,t,u,v) where atom a = ( atom a , atom a , atom a , atom a , atom a ) -- }}}
kylcarte/finally-logical
src/Data/Logic/Atomic/Class.hs
bsd-3-clause
1,629
0
11
432
719
380
339
-1
-1
{-# Language StandaloneDeriving, PatternGuards, CPP, OverloadedStrings #-} module CabalBounds.Main ( cabalBounds ) where import Distribution.PackageDescription (GenericPackageDescription) import Distribution.PackageDescription.Parsec (parseGenericPackageDescription, runParseResult) import Distribution.Parsec.Common (PWarning) import qualified Distribution.PackageDescription.PrettyPrint as PP import Distribution.Simple.Configure (tryGetConfigStateFile) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo) import qualified Distribution.Simple.LocalBuildInfo as BI import qualified Distribution.Package as P import qualified Distribution.Simple.PackageIndex as PX import qualified Distribution.InstalledPackageInfo as PI import qualified Distribution.Version as V import qualified CabalBounds.Args as A import qualified CabalBounds.Bound as B import qualified CabalBounds.Sections as S import qualified CabalBounds.Dependencies as DP import qualified CabalBounds.Drop as DR import qualified CabalBounds.Update as U import qualified CabalBounds.Dump as DU import qualified CabalBounds.HaskellPlatform as HP import CabalBounds.Types import qualified CabalLenses as CL import qualified System.IO.Strict as SIO import System.FilePath ((</>)) import System.Directory (getCurrentDirectory) import Control.Monad.Trans.Except (ExceptT, throwE, runExceptT) import Control.Monad.IO.Class import Control.Lens import qualified Data.HashMap.Strict as HM import Data.List (foldl', sortBy) import Data.Function (on) import Data.Char (toLower) import Data.Maybe (fromMaybe, catMaybes) import qualified Data.Aeson as Aeson import Data.Aeson.Lens import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.Text as T import Data.Text (Text) import qualified Data.List as L import Text.Read (readMaybe) #if MIN_VERSION_Cabal(1,22,0) == 0 import Distribution.Simple.Configure (ConfigStateFileErrorType(..)) #endif #if MIN_VERSION_Cabal(1,22,0) && MIN_VERSION_Cabal(1,22,1) == 0 import Control.Lens #endif #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif type Error = String type SetupConfigFile = FilePath type PlanFile = FilePath type LibraryFile = FilePath type CabalFile = FilePath cabalBounds :: A.Args -> IO (Maybe Error) cabalBounds [email protected] {} = leftToJust <$> runExceptT (do cabalFile <- findCabalFile $ A.cabalFile args pkgDescrp <- packageDescription cabalFile let pkgDescrp' = DR.drop (B.boundOfDrop args) (S.sections args pkgDescrp) (DP.dependencies args) pkgDescrp let outputFile = fromMaybe cabalFile (A.output args) liftIO $ writeFile outputFile (showGenericPackageDescription pkgDescrp')) cabalBounds [email protected] {} = leftToJust <$> runExceptT (do cabalFile <- findCabalFile $ A.cabalFile args pkgDescrp <- packageDescription cabalFile let haskelPlatform = A.haskellPlatform args libFile = A.fromFile args configFile = A.setupConfigFile args planFile = A.planFile args libs <- libraries haskelPlatform libFile configFile planFile cabalFile let pkgDescrp' = U.update (B.boundOfUpdate args) (S.sections args pkgDescrp) (DP.dependencies args) libs pkgDescrp let outputFile = fromMaybe cabalFile (A.output args) liftIO $ writeFile outputFile (showGenericPackageDescription pkgDescrp')) cabalBounds [email protected] {} = leftToJust <$> runExceptT (do cabalFiles <- if null $ A.cabalFiles args then (: []) <$> findCabalFile Nothing else return $ A.cabalFiles args pkgDescrps <- packageDescriptions cabalFiles let libs = sortLibraries $ DU.dump (DP.dependencies args) pkgDescrps case A.output args of Just file -> liftIO $ writeFile file (prettyPrint libs) Nothing -> liftIO $ putStrLn (prettyPrint libs)) cabalBounds [email protected] {} = leftToJust <$> runExceptT (do cabalFile <- findCabalFile $ A.cabalFile args let haskelPlatform = A.haskellPlatform args libFile = A.fromFile args configFile = A.setupConfigFile args planFile = A.planFile args libs <- sortLibraries . toList <$> libraries haskelPlatform libFile configFile planFile cabalFile let libs' = libs ^.. traversed . DP.filterLibrary (DP.dependencies args) case A.output args of Just file -> liftIO $ writeFile file (prettyPrint libs') Nothing -> liftIO $ putStrLn (prettyPrint libs')) cabalBounds [email protected] {} = leftToJust <$> runExceptT (do cabalFile <- findCabalFile $ A.cabalFile args pkgDescrp <- packageDescription cabalFile let outputFile = fromMaybe cabalFile (A.output args) liftIO $ writeFile outputFile (showGenericPackageDescription pkgDescrp)) sortLibraries :: Libraries -> Libraries sortLibraries = sortBy (compare `on` (map toLower . fst)) prettyPrint :: Libraries -> String prettyPrint [] = "[]" prettyPrint (l:ls) = "[ " ++ show l ++ "\n" ++ foldl' (\str l -> str ++ ", " ++ show l ++ "\n") "" ls ++ "]\n"; findCabalFile :: Maybe CabalFile -> ExceptT Error IO CabalFile findCabalFile Nothing = do curDir <- liftIO getCurrentDirectory CL.findCabalFile curDir findCabalFile (Just file) = return file packageDescription :: FilePath -> ExceptT Error IO GenericPackageDescription packageDescription file = do contents <- liftIO $ BS.readFile file let (warnings, result) = runParseResult $ parseGenericPackageDescription contents liftIO $ showWarnings warnings case result of Left (_, errors) -> throwE $ show errors Right pkgDescrp -> return pkgDescrp where showWarnings :: [PWarning] -> IO () showWarnings [] = return () showWarnings ws = putStrLn $ "cabal-bounds: " ++ (L.intercalate ", " $ map show ws) packageDescriptions :: [FilePath] -> ExceptT Error IO [GenericPackageDescription] packageDescriptions [] = throwE "Missing cabal file" packageDescriptions files = mapM packageDescription files libraries :: HP.HPVersion -> LibraryFile -> Maybe SetupConfigFile -> Maybe PlanFile -> CabalFile -> ExceptT Error IO LibraryMap libraries "" "" (Just confFile) _ _ = do librariesFromSetupConfig confFile libraries "" "" _ (Just planFile) _ = do librariesFromPlanFile planFile libraries "" "" Nothing Nothing cabalFile = do newDistDir <- liftIO $ CL.findNewDistDir cabalFile case newDistDir of Just newDistDir -> librariesFromPlanFile $ newDistDir </> "cache" </> "plan.json" Nothing -> do distDir <- liftIO $ CL.findDistDir cabalFile case distDir of Just distDir -> librariesFromSetupConfig $ distDir </> "setup-config" Nothing -> throwE "Couldn't find 'dist-newstyle' nor 'dist' directory! Have you already build the cabal project?" libraries hpVersion libFile _ _ _ = do hpLibs <- haskellPlatformLibraries hpVersion libsFromFile <- librariesFromFile libFile return $ HM.union hpLibs libsFromFile librariesFromFile :: LibraryFile -> ExceptT Error IO LibraryMap librariesFromFile "" = return HM.empty librariesFromFile libFile = do contents <- liftIO $ SIO.readFile libFile libsFrom contents where libsFrom contents | [(libs, _)] <- reads contents :: [([(String, [Int])], String)] = return $ HM.fromList (map (\(pkgName, versBranch) -> (pkgName, V.mkVersion versBranch)) libs) | otherwise = throwE "Invalid format of library file given to '--fromfile'. Expected file with content of type '[(String, [Int])]'." haskellPlatformLibraries :: HP.HPVersion -> ExceptT Error IO LibraryMap haskellPlatformLibraries hpVersion = case hpVersion of "" -> return HM.empty "current" -> return . HM.fromList $ HP.currentLibraries "previous" -> return . HM.fromList $ HP.previousLibraries version | Just libs <- HP.librariesOf version -> return . HM.fromList $ libs | otherwise -> throwE $ "Invalid haskell platform version '" ++ version ++ "'" librariesFromSetupConfig :: SetupConfigFile -> ExceptT Error IO LibraryMap librariesFromSetupConfig "" = return HM.empty librariesFromSetupConfig confFile = do binfo <- liftIO $ tryGetConfigStateFile confFile case binfo of Left e -> throwE $ show e Right bi -> return $ buildInfoLibs bi where buildInfoLibs :: LocalBuildInfo -> LibraryMap buildInfoLibs = HM.fromList . map (\(pkg, v) -> (P.unPackageName pkg, newestVersion v)) . filter ((not . null) . snd) . PX.allPackagesByName . BI.installedPkgs newestVersion :: [PI.InstalledPackageInfo] -> V.Version newestVersion = maximum . map (P.pkgVersion . PI.sourcePackageId) librariesFromPlanFile :: PlanFile -> ExceptT Error IO LibraryMap librariesFromPlanFile planFile = do contents <- liftIO $ LBS.readFile planFile let json = Aeson.decode contents :: Maybe Aeson.Value case json of Just json -> do -- get all ids: ["bytestring-0.10.6.0-2362d1f36f12553920ce3710ae4a4ecb432374f4e5feb33a61b7414b43605a0df", ...] let ids = json ^.. key "install-plan" . _Array . traversed . key "id" . _String let libs = catMaybes $ map parseLibrary ids return . HM.fromList $ libs Nothing -> throwE $ "Couldn't parse json file '" ++ planFile ++ "'" where parseLibrary :: Text -> Maybe (LibName, V.Version) parseLibrary text = case T.breakOnEnd "-" text of (_, "") -> Nothing (_, "inplace") -> Nothing (before, after) -> case parseVersion after of Just vers -> Just (T.unpack . stripSuffix "-" $ before, vers) _ -> parseLibrary $ stripSuffix "-" before parseVersion :: Text -> Maybe V.Version parseVersion text = case catMaybes $ map (readMaybe . T.unpack) $ T.split (== '.') text of [] -> Nothing nums -> Just $ V.mkVersion nums stripSuffix :: Text -> Text -> Text stripSuffix suffix text = fromMaybe text (T.stripSuffix suffix text) leftToJust :: Either a b -> Maybe a leftToJust = either Just (const Nothing) showGenericPackageDescription :: GenericPackageDescription -> String showGenericPackageDescription = #if MIN_VERSION_Cabal(1,22,1) PP.showGenericPackageDescription #elif MIN_VERSION_Cabal(1,22,0) PP.showGenericPackageDescription . clearTargetBuildDepends where clearTargetBuildDepends pkgDescrp = pkgDescrp & CL.allBuildInfo . CL.targetBuildDependsL .~ [] #else ensureLastIsNewline . PP.showGenericPackageDescription where ensureLastIsNewline xs = if last xs == '\n' then xs else xs ++ "\n" #endif #if MIN_VERSION_Cabal(1,22,0) == 0 deriving instance Show ConfigStateFileErrorType #endif
dan-t/cabal-bounds
lib/CabalBounds/Main.hs
bsd-3-clause
11,070
1
20
2,430
2,929
1,510
1,419
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Ordinal.KM.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Ordinal.KM.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "KM Tests" [ makeCorpusTest [Seal Ordinal] corpus ]
facebookincubator/duckling
tests/Duckling/Ordinal/KM/Tests.hs
bsd-3-clause
504
0
9
78
79
50
29
11
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} module FPNLA.Operations.BLAS.Strategies.SYRK.Strategies.DefPar () where import Control.DeepSeq (NFData) import Control.Parallel.Strategies (parMap, rdeepseq) import FPNLA.Matrix (MatrixVector, foldr_v, fromCols_vm, generate_v) import FPNLA.Operations.BLAS (SYRK (syrk)) import FPNLA.Operations.BLAS.Strategies.DataTypes (DefPar_ST) import FPNLA.Operations.Parameters (Elt, TransType (..), blasResultM, dimTrans_m, dimTriang, elemSymm, elemTrans_m) instance (NFData (v e), Elt e, MatrixVector m v e) => SYRK DefPar_ST m v e where syrk _ alpha pmA beta pmB | p /= p' = error "syrk: incompatible ranges" | otherwise = blasResultM $ generatePar_m p p (\i j -> (alpha * pmAMultIJ i j) + beta * elemSymm i j pmB) where (p, p') = dimTriang pmB matMultIJ i j tmA tmB = foldr_v (+) 0 (generate_v (snd $ dimTrans_m tmA) (\k -> (*) (elemTrans_m i k tmA) (elemTrans_m k j tmB)) :: v e) pmAMultIJ i j = case pmA of (NoTrans mA) -> matMultIJ i j pmA (Trans mA) (Trans mA) -> matMultIJ i j (Trans mA) pmA (ConjTrans mA) -> matMultIJ i j (Trans mA) pmA generatePar_m m n gen = fromCols_vm . parMap rdeepseq (\j -> generate_v m (`gen` j) :: v e) $ [0 .. (n - 1)]
mauroblanco/fpnla-examples
src/FPNLA/Operations/BLAS/Strategies/SYRK/Strategies/DefPar.hs
bsd-3-clause
2,176
0
15
1,082
510
280
230
32
0
{-# LANGUAGE CPP, ScopedTypeVariables #-} module TcErrors( reportUnsolved, reportAllUnsolved, warnAllUnsolved, warnDefaulting, solverDepthErrorTcS ) where #include "HsVersions.h" import TcRnTypes import TcRnMonad import TcMType import TcType import RnEnv( unknownNameSuggestions ) import Type import TyCoRep import Kind import Unify ( tcMatchTys ) import Module import FamInst import FamInstEnv ( flattenTys ) import Inst import InstEnv import TyCon import Class import DataCon import TcEvidence import HsBinds ( PatSynBind(..) ) import Name import RdrName ( lookupGRE_Name, GlobalRdrEnv, mkRdrUnqual ) import PrelNames ( typeableClassName, hasKey, ptrRepLiftedDataConKey , ptrRepUnliftedDataConKey ) import Id import Var import VarSet import VarEnv import NameSet import Bag import ErrUtils ( ErrMsg, errDoc, pprLocErrMsg ) import BasicTypes import ConLike ( ConLike(..) ) import Util import FastString import Outputable import SrcLoc import DynFlags import StaticFlags ( opt_PprStyle_Debug ) import ListSetOps ( equivClasses ) import Maybes import qualified GHC.LanguageExtensions as LangExt import Control.Monad ( when ) import Data.List ( partition, mapAccumL, nub, sortBy ) #if __GLASGOW_HASKELL__ > 710 import Data.Semigroup ( Semigroup ) import qualified Data.Semigroup as Semigroup #endif {- ************************************************************************ * * \section{Errors and contexts} * * ************************************************************************ ToDo: for these error messages, should we note the location as coming from the insts, or just whatever seems to be around in the monad just now? Note [Deferring coercion errors to runtime] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While developing, sometimes it is desirable to allow compilation to succeed even if there are type errors in the code. Consider the following case: module Main where a :: Int a = 'a' main = print "b" Even though `a` is ill-typed, it is not used in the end, so if all that we're interested in is `main` it is handy to be able to ignore the problems in `a`. Since we treat type equalities as evidence, this is relatively simple. Whenever we run into a type mismatch in TcUnify, we normally just emit an error. But it is always safe to defer the mismatch to the main constraint solver. If we do that, `a` will get transformed into co :: Int ~ Char co = ... a :: Int a = 'a' `cast` co The constraint solver would realize that `co` is an insoluble constraint, and emit an error with `reportUnsolved`. But we can also replace the right-hand side of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program to compile, and it will run fine unless we evaluate `a`. This is what `deferErrorsToRuntime` does. It does this by keeping track of which errors correspond to which coercion in TcErrors. TcErrors.reportTidyWanteds does not print the errors and does not fail if -fdefer-type-errors is on, so that we can continue compilation. The errors are turned into warnings in `reportUnsolved`. -} -- | Report unsolved goals as errors or warnings. We may also turn some into -- deferred run-time errors if `-fdefer-type-errors` is on. reportUnsolved :: WantedConstraints -> TcM (Bag EvBind) reportUnsolved wanted = do { binds_var <- newTcEvBinds ; defer_errors <- goptM Opt_DeferTypeErrors ; warn_errors <- woptM Opt_WarnDeferredTypeErrors -- implement #10283 ; let type_errors | not defer_errors = TypeError | warn_errors = TypeWarn | otherwise = TypeDefer ; defer_holes <- goptM Opt_DeferTypedHoles ; warn_holes <- woptM Opt_WarnTypedHoles ; let expr_holes | not defer_holes = HoleError | warn_holes = HoleWarn | otherwise = HoleDefer ; partial_sigs <- xoptM LangExt.PartialTypeSignatures ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures ; let type_holes | not partial_sigs = HoleError | warn_partial_sigs = HoleWarn | otherwise = HoleDefer ; report_unsolved (Just binds_var) False type_errors expr_holes type_holes wanted ; getTcEvBinds binds_var } -- | Report *all* unsolved goals as errors, even if -fdefer-type-errors is on -- However, do not make any evidence bindings, because we don't -- have any convenient place to put them. -- See Note [Deferring coercion errors to runtime] -- Used by solveEqualities for kind equalities -- (see Note [Fail fast on kind errors] in TcSimplify] -- and for simplifyDefault. reportAllUnsolved :: WantedConstraints -> TcM () reportAllUnsolved wanted = report_unsolved Nothing False TypeError HoleError HoleError wanted -- | Report all unsolved goals as warnings (but without deferring any errors to -- run-time). See Note [Safe Haskell Overlapping Instances Implementation] in -- TcSimplify warnAllUnsolved :: WantedConstraints -> TcM () warnAllUnsolved wanted = report_unsolved Nothing True TypeWarn HoleWarn HoleWarn wanted -- | Report unsolved goals as errors or warnings. report_unsolved :: Maybe EvBindsVar -- cec_binds -> Bool -- Errors as warnings -> TypeErrorChoice -- Deferred type errors -> HoleChoice -- Expression holes -> HoleChoice -- Type holes -> WantedConstraints -> TcM () report_unsolved mb_binds_var err_as_warn type_errors expr_holes type_holes wanted | isEmptyWC wanted = return () | otherwise = do { traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted) ; wanted <- zonkWC wanted -- Zonk to reveal all information ; env0 <- tcInitTidyEnv -- If we are deferring we are going to need /all/ evidence around, -- including the evidence produced by unflattening (zonkWC) ; let tidy_env = tidyFreeTyCoVars env0 free_tvs free_tvs = tyCoVarsOfWC wanted ; traceTc "reportUnsolved (after zonking and tidying):" $ vcat [ pprTvBndrs (varSetElems free_tvs) , ppr wanted ] ; warn_redundant <- woptM Opt_WarnRedundantConstraints ; let err_ctxt = CEC { cec_encl = [] , cec_tidy = tidy_env , cec_defer_type_errors = type_errors , cec_errors_as_warns = err_as_warn , cec_expr_holes = expr_holes , cec_type_holes = type_holes , cec_suppress = False -- See Note [Suppressing error messages] , cec_warn_redundant = warn_redundant , cec_binds = mb_binds_var } ; tc_lvl <- getTcLevel ; reportWanteds err_ctxt tc_lvl wanted } -------------------------------------------- -- Internal functions -------------------------------------------- -- | An error Report collects messages categorised by their importance. -- See Note [Error report] for details. data Report = Report { report_important :: [SDoc] , report_relevant_bindings :: [SDoc] } {- Note [Error report] The idea is that error msgs are divided into three parts: the main msg, the context block (\"In the second argument of ...\"), and the relevant bindings block, which are displayed in that order, with a mark to divide them. The idea is that the main msg ('report_important') varies depending on the error in question, but context and relevant bindings are always the same, which should simplify visual parsing. The context is added when the the Report is passed off to 'mkErrorReport'. Unfortunately, unlike the context, the relevant bindings are added in multiple places so they have to be in the Report. -} #if __GLASGOW_HASKELL__ > 710 instance Semigroup Report where Report a1 b1 <> Report a2 b2 = Report (a1 ++ a2) (b1 ++ b2) #endif instance Monoid Report where mempty = Report [] [] mappend (Report a1 b1) (Report a2 b2) = Report (a1 ++ a2) (b1 ++ b2) -- | Put a doc into the important msgs block. important :: SDoc -> Report important doc = mempty { report_important = [doc] } -- | Put a doc into the relevant bindings block. relevant_bindings :: SDoc -> Report relevant_bindings doc = mempty { report_relevant_bindings = [doc] } data TypeErrorChoice -- What to do for type errors found by the type checker = TypeError -- A type error aborts compilation with an error message | TypeWarn -- A type error is deferred to runtime, plus a compile-time warning | TypeDefer -- A type error is deferred to runtime; no error or warning at compile time data HoleChoice = HoleError -- A hole is a compile-time error | HoleWarn -- Defer to runtime, emit a compile-time warning | HoleDefer -- Defer to runtime, no warning data ReportErrCtxt = CEC { cec_encl :: [Implication] -- Enclosing implications -- (innermost first) -- ic_skols and givens are tidied, rest are not , cec_tidy :: TidyEnv , cec_binds :: Maybe EvBindsVar -- Nothing <=> Report all errors, including holes -- Do not add any evidence bindings, because -- we have no convenient place to put them -- See TcErrors.reportAllUnsolved -- Just ev <=> make some errors (depending on cec_defer) -- into warnings, and emit evidence bindings -- into 'ev' for unsolved constraints , cec_errors_as_warns :: Bool -- Turn all errors into warnings -- (except for Holes, which are -- controlled by cec_type_holes and -- cec_expr_holes) , cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime -- Irrelevant if cec_binds = Nothing , cec_expr_holes :: HoleChoice -- Holes in expressions , cec_type_holes :: HoleChoice -- Holes in types , cec_warn_redundant :: Bool -- True <=> -Wredundant-constraints , cec_suppress :: Bool -- True <=> More important errors have occurred, -- so create bindings if need be, but -- don't issue any more errors/warnings -- See Note [Suppressing error messages] } {- Note [Suppressing error messages] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The cec_suppress flag says "don't report any errors". Instead, just create evidence bindings (as usual). It's used when more important errors have occurred. Specifically (see reportWanteds) * If there are insoluble Givens, then we are in unreachable code and all bets are off. So don't report any further errors. * If there are any insolubles (eg Int~Bool), here or in a nested implication, then suppress errors from the simple constraints here. Sometimes the simple-constraint errors are a knock-on effect of the insolubles. -} reportImplic :: ReportErrCtxt -> Implication -> TcM () reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given , ic_wanted = wanted, ic_binds = m_evb , ic_status = status, ic_info = info , ic_env = tcl_env, ic_tclvl = tc_lvl }) | BracketSkol <- info , not insoluble = return () -- For Template Haskell brackets report only -- definite errors. The whole thing will be re-checked -- later when we plug it in, and meanwhile there may -- certainly be un-satisfied constraints | otherwise = do { reportWanteds ctxt' tc_lvl wanted ; traceTc "reportImplic" (ppr implic) ; when (cec_warn_redundant ctxt) $ warnRedundantConstraints ctxt' tcl_env info' dead_givens } where insoluble = isInsolubleStatus status (env1, tvs') = mapAccumL tidyTyCoVarBndr (cec_tidy ctxt) tvs info' = tidySkolemInfo env1 info implic' = implic { ic_skols = tvs' , ic_given = map (tidyEvVar env1) given , ic_info = info' } ctxt' = ctxt { cec_tidy = env1 , cec_encl = implic' : cec_encl ctxt , cec_suppress = insoluble || cec_suppress ctxt -- Suppress inessential errors if there -- are are insolubles anywhere in the -- tree rooted here, or we've come across -- a suppress-worthy constraint higher up (Trac #11541) , cec_binds = cec_binds ctxt *> m_evb } -- If cec_binds ctxt is Nothing, that means -- we're reporting *all* errors. Don't change -- that behavior just because we're going into -- an implication. dead_givens = case status of IC_Solved { ics_dead = dead } -> dead _ -> [] warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM () warnRedundantConstraints ctxt env info ev_vars | null redundant_evs = return () | SigSkol {} <- info = setLclEnv env $ -- We want to add "In the type signature for f" -- to the error context, which is a bit tiresome addErrCtxt (text "In" <+> ppr info) $ do { env <- getLclEnv ; msg <- mkErrorReport ctxt env (important doc) ; reportWarning (Reason Opt_WarnRedundantConstraints) msg } | otherwise -- But for InstSkol there already *is* a surrounding -- "In the instance declaration for Eq [a]" context -- and we don't want to say it twice. Seems a bit ad-hoc = do { msg <- mkErrorReport ctxt env (important doc) ; reportWarning (Reason Opt_WarnRedundantConstraints) msg } where doc = text "Redundant constraint" <> plural redundant_evs <> colon <+> pprEvVarTheta redundant_evs redundant_evs = case info of -- See Note [Redundant constraints in instance decls] InstSkol -> filterOut improving ev_vars _ -> ev_vars improving ev_var = any isImprovementPred $ transSuperClasses (idType ev_var) {- Note [Redundant constraints in instance decls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For instance declarations, we don't report unused givens if they can give rise to improvement. Example (Trac #10100): class Add a b ab | a b -> ab, a ab -> b instance Add Zero b b instance Add a b ab => Add (Succ a) b (Succ ab) The context (Add a b ab) for the instance is clearly unused in terms of evidence, since the dictionary has no feilds. But it is still needed! With the context, a wanted constraint Add (Succ Zero) beta (Succ Zero) we will reduce to (Add Zero beta Zero), and thence we get beta := Zero. But without the context we won't find beta := Zero. This only matters in instance declarations.. -} reportWanteds :: ReportErrCtxt -> TcLevel -> WantedConstraints -> TcM () reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) = do { traceTc "reportWanteds" (vcat [ text "Simples =" <+> ppr simples , text "Suppress =" <+> ppr (cec_suppress ctxt)]) ; let tidy_cts = bagToList (mapBag (tidyCt env) (insols `unionBags` simples)) -- First deal with things that are utterly wrong -- Like Int ~ Bool (incl nullary TyCons) -- or Int ~ t a (AppTy on one side) -- These ones are not suppressed by the incoming context ; let ctxt_for_insols = ctxt { cec_suppress = False } ; (ctxt1, cts1) <- tryReporters ctxt_for_insols report1 tidy_cts -- Now all the other constraints. We suppress errors here if -- any of the first batch failed, or if the enclosing context -- says to suppress ; let ctxt2 = ctxt { cec_suppress = cec_suppress ctxt || cec_suppress ctxt1 } ; (_, leftovers) <- tryReporters ctxt2 report2 cts1 ; MASSERT2( null leftovers, ppr leftovers ) -- All the Derived ones have been filtered out of simples -- by the constraint solver. This is ok; we don't want -- to report unsolved Derived goals as errors -- See Note [Do not report derived but soluble errors] ; mapBagM_ (reportImplic ctxt2) implics } -- NB ctxt1: don't suppress inner insolubles if there's only a -- wanted insoluble here; but do suppress inner insolubles -- if there's a *given* insoluble here (= inaccessible code) where env = cec_tidy ctxt -- report1: ones that should *not* be suppresed by -- an insoluble somewhere else in the tree -- It's crucial that anything that is considered insoluble -- (see TcRnTypes.trulyInsoluble) is caught here, otherwise -- we might suppress its error message, and proceed on past -- type checking to get a Lint error later report1 = [ ("custom_error", is_user_type_error, True, mkUserTypeErrorReporter) , ("insoluble1", is_given_eq, True, mkGroupReporter mkEqErr) , ("insoluble2", utterly_wrong, True, mkGroupReporter mkEqErr) , ("skolem eq1", very_wrong, True, mkSkolReporter) , ("skolem eq2", skolem_eq, True, mkSkolReporter) , ("non-tv eq", non_tv_eq, True, mkSkolReporter) , ("Out of scope", is_out_of_scope, True, mkHoleReporter) , ("Holes", is_hole, False, mkHoleReporter) -- The only remaining equalities are alpha ~ ty, -- where alpha is untouchable; and representational equalities , ("Other eqs", is_equality, False, mkGroupReporter mkEqErr) ] -- report2: we suppress these if there are insolubles elsewhere in the tree report2 = [ ("Implicit params", is_ip, False, mkGroupReporter mkIPErr) , ("Irreds", is_irred, False, mkGroupReporter mkIrredErr) , ("Dicts", is_dict, False, mkGroupReporter mkDictErr) ] -- rigid_nom_eq, rigid_nom_tv_eq, is_hole, is_dict, is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool is_given_eq ct pred | EqPred {} <- pred = arisesFromGivens ct | otherwise = False -- I think all given residuals are equalities -- Things like (Int ~N Bool) utterly_wrong _ (EqPred NomEq ty1 ty2) = isRigidTy ty1 && isRigidTy ty2 utterly_wrong _ _ = False -- Things like (a ~N Int) very_wrong _ (EqPred NomEq ty1 ty2) = isSkolemTy tc_lvl ty1 && isRigidTy ty2 very_wrong _ _ = False -- Things like (a ~N b) or (a ~N F Bool) skolem_eq _ (EqPred NomEq ty1 _) = isSkolemTy tc_lvl ty1 skolem_eq _ _ = False -- Things like (F a ~N Int) non_tv_eq _ (EqPred NomEq ty1 _) = not (isTyVarTy ty1) non_tv_eq _ _ = False -- rigid_nom_eq _ pred = isRigidEqPred tc_lvl pred -- -- rigid_nom_tv_eq _ pred -- | EqPred _ ty1 _ <- pred = isRigidEqPred tc_lvl pred && isTyVarTy ty1 -- | otherwise = False is_out_of_scope ct _ = isOutOfScopeCt ct is_hole ct _ = isHoleCt ct is_user_type_error ct _ = isUserTypeErrorCt ct is_equality _ (EqPred {}) = True is_equality _ _ = False is_dict _ (ClassPred {}) = True is_dict _ _ = False is_ip _ (ClassPred cls _) = isIPClass cls is_ip _ _ = False is_irred _ (IrredPred {}) = True is_irred _ _ = False --------------- isSkolemTy :: TcLevel -> Type -> Bool -- The type is a skolem tyvar isSkolemTy tc_lvl ty | Just tv <- getTyVar_maybe ty = isSkolemTyVar tv || (isSigTyVar tv && isTouchableMetaTyVar tc_lvl tv) -- The last case is for touchable SigTvs -- we postpone untouchables to a latter test (too obscure) | otherwise = False isTyFun_maybe :: Type -> Maybe TyCon isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of Just (tc,_) | isTypeFamilyTyCon tc -> Just tc _ -> Nothing -------------------------------------------- -- Reporters -------------------------------------------- type Reporter = ReportErrCtxt -> [Ct] -> TcM () type ReporterSpec = ( String -- Name , Ct -> PredTree -> Bool -- Pick these ones , Bool -- True <=> suppress subsequent reporters , Reporter) -- The reporter itself mkSkolReporter :: Reporter -- Suppress duplicates with either the same LHS, or same location mkSkolReporter ctxt cts = mapM_ (reportGroup mkEqErr ctxt) (group cts) where group [] = [] group (ct:cts) = (ct : yeses) : group noes where (yeses, noes) = partition (group_with ct) cts group_with ct1 ct2 | EQ <- cmp_loc ct1 ct2 = True | EQ <- cmp_lhs_type ct1 ct2 = True | otherwise = False mkHoleReporter :: Reporter -- Reports errors one at a time mkHoleReporter ctxt = mapM_ $ \ct -> do { err <- mkHoleError ctxt ct ; maybeReportHoleError ctxt ct err ; maybeAddDeferredHoleBinding ctxt err ct } mkUserTypeErrorReporter :: Reporter mkUserTypeErrorReporter ctxt = mapM_ $ \ct -> maybeReportError ctxt =<< mkUserTypeError ctxt ct mkUserTypeError :: ReportErrCtxt -> Ct -> TcM ErrMsg mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct $ important $ pprUserTypeErrorTy $ case getUserTypeErrorMsg ct of Just msg -> msg Nothing -> pprPanic "mkUserTypeError" (ppr ct) mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -- Make error message for a group -> Reporter -- Deal with lots of constraints -- Group together errors from same location, -- and report only the first (to avoid a cascade) mkGroupReporter mk_err ctxt cts = mapM_ (reportGroup mk_err ctxt) (equivClasses cmp_loc cts) where cmp_lhs_type :: Ct -> Ct -> Ordering cmp_lhs_type ct1 ct2 = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) -> (eq_rel1 `compare` eq_rel2) `thenCmp` (ty1 `cmpType` ty2) _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2) cmp_loc :: Ct -> Ct -> Ordering cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2) reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt -> [Ct] -> TcM () reportGroup mk_err ctxt cts = case partition isMonadFailInstanceMissing cts of -- Only warn about missing MonadFail constraint when -- there are no other missing contstraints! (monadFailCts, []) -> do { err <- mk_err ctxt monadFailCts ; reportWarning (Reason Opt_WarnMissingMonadFailInstances) err } (_, cts') -> do { err <- mk_err ctxt cts' ; maybeReportError ctxt err ; mapM_ (maybeAddDeferredBinding ctxt err) cts' } -- Add deferred bindings for all -- But see Note [Always warn with -fdefer-type-errors] where isMonadFailInstanceMissing ct = case ctLocOrigin (ctLoc ct) of FailablePattern _pat -> True _otherwise -> False maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM () maybeReportHoleError ctxt ct err -- When -XPartialTypeSignatures is on, warnings (instead of errors) are -- generated for holes in partial type signatures. -- Unless -fwarn_partial_type_signatures is not on, -- in which case the messages are discarded. | isTypeHoleCt ct = -- For partial type signatures, generate warnings only, and do that -- only if -fwarn_partial_type_signatures is on case cec_type_holes ctxt of HoleError -> reportError err HoleWarn -> reportWarning (Reason Opt_WarnPartialTypeSignatures) err HoleDefer -> return () -- Otherwise this is a typed hole in an expression | otherwise = -- If deferring, report a warning only if -Wtyped-holds is on case cec_expr_holes ctxt of HoleError -> reportError err HoleWarn -> reportWarning (Reason Opt_WarnTypedHoles) err HoleDefer -> return () maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM () -- Report the error and/or make a deferred binding for it maybeReportError ctxt err | cec_suppress ctxt -- Some worse error has occurred; = return () -- so suppress this error/warning | cec_errors_as_warns ctxt = reportWarning NoReason err | otherwise = case cec_defer_type_errors ctxt of TypeDefer -> return () TypeWarn -> reportWarning (Reason Opt_WarnDeferredTypeErrors) err TypeError -> reportError err addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () -- See Note [Deferring coercion errors to runtime] addDeferredBinding ctxt err ct | CtWanted { ctev_pred = pred, ctev_dest = dest } <- ctEvidence ct -- Only add deferred bindings for Wanted constraints , Just ev_binds_var <- cec_binds ctxt -- We have somewhere to put the bindings = do { dflags <- getDynFlags ; let err_msg = pprLocErrMsg err err_fs = mkFastString $ showSDoc dflags $ err_msg $$ text "(deferred type error)" err_tm = EvDelayedError pred err_fs ; case dest of EvVarDest evar -> addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm HoleDest hole -> do { -- See Note [Deferred errors for coercion holes] evar <- newEvVar pred ; addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm ; fillCoercionHole hole (mkTcCoVarCo evar) }} | otherwise -- Do not set any evidence for Given/Derived = return () maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () maybeAddDeferredHoleBinding ctxt err ct | isExprHoleCt ct , case cec_expr_holes ctxt of HoleDefer -> True HoleWarn -> True HoleError -> False = addDeferredBinding ctxt err ct -- Only add bindings for holes in expressions | otherwise -- not for holes in partial type signatures = return () maybeAddDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM () maybeAddDeferredBinding ctxt err ct = case cec_defer_type_errors ctxt of TypeDefer -> deferred TypeWarn -> deferred TypeError -> return () where deferred = addDeferredBinding ctxt err ct tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct]) -- Use the first reporter in the list whose predicate says True tryReporters ctxt reporters cts = do { traceTc "tryReporters {" (ppr cts) ; (ctxt', cts') <- go ctxt reporters cts ; traceTc "tryReporters }" (ppr cts') ; return (ctxt', cts') } where go ctxt [] cts = return (ctxt, cts) go ctxt (r : rs) cts = do { (ctxt', cts') <- tryReporter ctxt r cts ; go ctxt' rs cts' } -- Carry on with the rest, because we must make -- deferred bindings for them if we have -fdefer-type-errors -- But suppress their error messages tryReporter :: ReportErrCtxt -> ReporterSpec -> [Ct] -> TcM (ReportErrCtxt, [Ct]) tryReporter ctxt (str, keep_me, suppress_after, reporter) cts | null yeses = return (ctxt, cts) | otherwise = do { traceTc "tryReporter:" (text str <+> ppr yeses) ; reporter ctxt yeses ; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt } ; return (ctxt', nos) } where (yeses, nos) = partition (\ct -> keep_me ct (classifyPredType (ctPred ct))) cts pprArising :: CtOrigin -> SDoc -- Used for the main, top-level error message -- We've done special processing for TypeEq, KindEq, Given pprArising (TypeEqOrigin {}) = empty pprArising (KindEqOrigin {}) = empty pprArising (GivenOrigin {}) = empty pprArising orig = pprCtOrigin orig -- Add the "arising from..." part to a message about bunch of dicts addArising :: CtOrigin -> SDoc -> SDoc addArising orig msg = hang msg 2 (pprArising orig) pprWithArising :: [Ct] -> (CtLoc, SDoc) -- Print something like -- (Eq a) arising from a use of x at y -- (Show a) arising from a use of p at q -- Also return a location for the error message -- Works for Wanted/Derived only pprWithArising [] = panic "pprWithArising" pprWithArising (ct:cts) | null cts = (loc, addArising (ctLocOrigin loc) (pprTheta [ctPred ct])) | otherwise = (loc, vcat (map ppr_one (ct:cts))) where loc = ctLoc ct ppr_one ct' = hang (parens (pprType (ctPred ct'))) 2 (pprCtLoc (ctLoc ct')) mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> Report -> TcM ErrMsg mkErrorMsgFromCt ctxt ct report = mkErrorReport ctxt (ctLocEnv (ctLoc ct)) report mkErrorReport :: ReportErrCtxt -> TcLclEnv -> Report -> TcM ErrMsg mkErrorReport ctxt tcl_env (Report important relevant_bindings) = do { context <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env) ; mkErrDocAt (RealSrcSpan (tcl_loc tcl_env)) (errDoc important [context] relevant_bindings) } type UserGiven = ([EvVar], SkolemInfo, Bool, RealSrcSpan) getUserGivens :: ReportErrCtxt -> [UserGiven] -- One item for each enclosing implication getUserGivens (CEC {cec_encl = ctxt}) = reverse $ [ (givens, info, no_eqs, tcl_loc env) | Implic { ic_given = givens, ic_env = env , ic_no_eqs = no_eqs, ic_info = info } <- ctxt , not (null givens) ] {- Note [Always warn with -fdefer-type-errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When -fdefer-type-errors is on we warn about *all* type errors, even if cec_suppress is on. This can lead to a lot more warnings than you would get errors without -fdefer-type-errors, but if we suppress any of them you might get a runtime error that wasn't warned about at compile time. This is an easy design choice to change; just flip the order of the first two equations for maybeReportError To be consistent, we should also report multiple warnings from a single location in mkGroupReporter, when -fdefer-type-errors is on. But that is perhaps a bit *over*-consistent! Again, an easy choice to change. With #10283, you can now opt out of deferred type error warnings. Note [Deferred errors for coercion holes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we need to defer a type error where the destination for the evidence is a coercion hole. We can't just put the error in the hole, because we can't make an erroneous coercion. (Remember that coercions are erased for runtime.) Instead, we invent a new EvVar, bind it to an error and then make a coercion from that EvVar, filling the hole with that coercion. Because coercions' types are unlifted, the error is guaranteed to be hit before we get to the coercion. Note [Do not report derived but soluble errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The wc_simples include Derived constraints that have not been solved, but are not insoluble (in that case they'd be in wc_insols). We do not want to report these as errors: * Superclass constraints. If we have an unsolved [W] Ord a, we'll also have an unsolved [D] Eq a, and we do not want to report that; it's just noise. * Functional dependencies. For givens, consider class C a b | a -> b data T a where MkT :: C a d => [d] -> T a f :: C a b => T a -> F Int f (MkT xs) = length xs Then we get a [D] b~d. But there *is* a legitimate call to f, namely f (MkT [True]) :: T Bool, in which b=d. So we should not reject the program. For wanteds, something similar data T a where MkT :: C Int b => a -> b -> T a g :: C Int c => c -> () f :: T a -> () f (MkT x y) = g x Here we get [G] C Int b, [W] C Int a, hence [D] a~b. But again f (MkT True True) is a legitimate call. (We leave the Deriveds in wc_simple until reportErrors, so that we don't lose derived superclasses between iterations of the solver.) For functional dependencies, here is a real example, stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs class C a b | a -> b g :: C a b => a -> b -> () f :: C a b => a -> b -> () f xa xb = let loop = g xa in loop xb We will first try to infer a type for loop, and we will succeed: C a b' => b' -> () Subsequently, we will type check (loop xb) and all is good. But, recall that we have to solve a final implication constraint: C a b => (C a b' => .... cts from body of loop .... )) And now we have a problem as we will generate an equality b ~ b' and fail to solve it. ************************************************************************ * * Irreducible predicate errors * * ************************************************************************ -} mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkIrredErr ctxt cts = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1 ; let orig = ctOrigin ct1 msg = couldNotDeduce (getUserGivens ctxt) (map ctPred cts, orig) ; mkErrorMsgFromCt ctxt ct1 $ important msg `mappend` relevant_bindings binds_msg } where (ct1:_) = cts ---------------- mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg mkHoleError ctxt ct@(CHoleCan { cc_occ = occ, cc_hole = hole_sort }) | isOutOfScopeCt ct -- Out of scope variables, like 'a', where 'a' isn't bound -- Suggest possible in-scope variables in the message = do { dflags <- getDynFlags ; rdr_env <- getGlobalRdrEnv ; impInfo <- getImports ; mkErrDocAt (RealSrcSpan (tcl_loc lcl_env)) $ errDoc [out_of_scope_msg] [] [unknownNameSuggestions dflags rdr_env (tcl_rdr lcl_env) impInfo (mkRdrUnqual occ)] } | otherwise -- Explicit holes, like "_" or "_f" = do { (ctxt, binds_msg, ct) <- relevantBindings False ctxt ct -- The 'False' means "don't filter the bindings"; see Trac #8191 ; mkErrorMsgFromCt ctxt ct $ important hole_msg `mappend` relevant_bindings binds_msg } where ct_loc = ctLoc ct lcl_env = ctLocEnv ct_loc hole_ty = ctEvPred (ctEvidence ct) tyvars = tyCoVarsOfTypeList hole_ty boring_type = isTyVarTy hole_ty out_of_scope_msg -- Print v :: ty only if the type has structure | boring_type = hang herald 2 (ppr occ) | otherwise = hang herald 2 pp_with_type pp_with_type = hang (pprPrefixOcc occ) 2 (dcolon <+> pprType hole_ty) herald | isDataOcc occ = text "Data constructor not in scope:" | otherwise = text "Variable not in scope:" hole_msg = case hole_sort of ExprHole -> vcat [ hang (text "Found hole:") 2 pp_with_type , tyvars_msg, expr_hole_hint ] TypeHole -> vcat [ hang (text "Found type wildcard" <+> quotes (ppr occ)) 2 (text "standing for" <+> quotes (pprType hole_ty)) , tyvars_msg, type_hole_hint ] tyvars_msg = ppUnless (null tyvars) $ text "Where:" <+> vcat (map loc_msg tyvars) type_hole_hint | HoleError <- cec_type_holes ctxt = text "To use the inferred type, enable PartialTypeSignatures" | otherwise = empty expr_hole_hint -- Give hint for, say, f x = _x | lengthFS (occNameFS occ) > 1 -- Don't give this hint for plain "_" = text "Or perhaps" <+> quotes (ppr occ) <+> text "is mis-spelled, or not in scope" | otherwise = empty loc_msg tv | isTyVar tv = case tcTyVarDetails tv of SkolemTv {} -> pprSkol (cec_encl ctxt) tv MetaTv {} -> quotes (ppr tv) <+> text "is an ambiguous type variable" det -> pprTcTyVarDetails det | otherwise = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitCoercions dflags then quotes (ppr tv) <+> text "is a coercion variable" else empty mkHoleError _ ct = pprPanic "mkHoleError" (ppr ct) ---------------- mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkIPErr ctxt cts = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1 ; let orig = ctOrigin ct1 preds = map ctPred cts givens = getUserGivens ctxt msg | null givens = addArising orig $ sep [ text "Unbound implicit parameter" <> plural cts , nest 2 (pprTheta preds) ] | otherwise = couldNotDeduce givens (preds, orig) ; mkErrorMsgFromCt ctxt ct1 $ important msg `mappend` relevant_bindings binds_msg } where (ct1:_) = cts {- ************************************************************************ * * Equality errors * * ************************************************************************ Note [Inaccessible code] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a where T1 :: T a T2 :: T Bool f :: (a ~ Int) => T a -> Int f T1 = 3 f T2 = 4 -- Unreachable code Here the second equation is unreachable. The original constraint (a~Int) from the signature gets rewritten by the pattern-match to (Bool~Int), so the danger is that we report the error as coming from the *signature* (Trac #7293). So, for Given errors we replace the env (and hence src-loc) on its CtLoc with that from the immediately enclosing implication. Note [Error messages for untouchables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (Trac #9109) data G a where { GBool :: G Bool } foo x = case x of GBool -> True Here we can't solve (t ~ Bool), where t is the untouchable result meta-var 't', because of the (a ~ Bool) from the pattern match. So we infer the type f :: forall a t. G a -> t making the meta-var 't' into a skolem. So when we come to report the unsolved (t ~ Bool), t won't look like an untouchable meta-var any more. So we don't assert that it is. -} mkEqErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg -- Don't have multiple equality errors from the same location -- E.g. (Int,Bool) ~ (Bool,Int) one error will do! mkEqErr ctxt (ct:_) = mkEqErr1 ctxt ct mkEqErr _ [] = panic "mkEqErr" mkEqErr1 :: ReportErrCtxt -> Ct -> TcM ErrMsg mkEqErr1 ctxt ct | arisesFromGivens ct = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct ; let (given_loc, given_msg) = mk_given (ctLoc ct) (cec_encl ctxt) ; dflags <- getDynFlags ; let report = important given_msg `mappend` relevant_bindings binds_msg ; mkEqErr_help dflags ctxt report (setCtLoc ct given_loc) -- Note [Inaccessible code] Nothing ty1 ty2 } | otherwise -- Wanted or derived = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct ; rdr_env <- getGlobalRdrEnv ; fam_envs <- tcGetFamInstEnvs ; exp_syns <- goptM Opt_PrintExpandedSynonyms ; let (keep_going, is_oriented, wanted_msg) = mk_wanted_extra (ctLoc ct) exp_syns coercible_msg = case ctEqRel ct of NomEq -> empty ReprEq -> mkCoercibleExplanation rdr_env fam_envs ty1 ty2 ; dflags <- getDynFlags ; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctOrigin ct)) ; let report = mconcat [important wanted_msg, important coercible_msg, relevant_bindings binds_msg] ; if keep_going then mkEqErr_help dflags ctxt report ct is_oriented ty1 ty2 else mkErrorMsgFromCt ctxt ct report } where (ty1, ty2) = getEqPredTys (ctPred ct) mk_given :: CtLoc -> [Implication] -> (CtLoc, SDoc) -- For given constraints we overwrite the env (and hence src-loc) -- with one from the implication. See Note [Inaccessible code] mk_given loc [] = (loc, empty) mk_given loc (implic : _) = (setCtLocEnv loc (ic_env implic) , hang (text "Inaccessible code in") 2 (ppr (ic_info implic))) -- If the types in the error message are the same as the types -- we are unifying, don't add the extra expected/actual message mk_wanted_extra :: CtLoc -> Bool -> (Bool, Maybe SwapFlag, SDoc) mk_wanted_extra loc expandSyns = case ctLocOrigin loc of orig@TypeEqOrigin {} -> mkExpectedActualMsg ty1 ty2 orig t_or_k expandSyns where t_or_k = ctLocTypeOrKind_maybe loc KindEqOrigin cty1 mb_cty2 sub_o sub_t_or_k -> (True, Nothing, msg1 $$ msg2) where sub_what = case sub_t_or_k of Just KindLevel -> text "kinds" _ -> text "types" msg1 = sdocWithDynFlags $ \dflags -> case mb_cty2 of Just cty2 | gopt Opt_PrintExplicitCoercions dflags || not (cty1 `pickyEqType` cty2) -> hang (text "When matching" <+> sub_what) 2 (vcat [ ppr cty1 <+> dcolon <+> ppr (typeKind cty1) , ppr cty2 <+> dcolon <+> ppr (typeKind cty2) ]) _ -> text "When matching the kind of" <+> quotes (ppr cty1) msg2 = case sub_o of TypeEqOrigin {} | Just cty2 <- mb_cty2 -> thdOf3 (mkExpectedActualMsg cty1 cty2 sub_o sub_t_or_k expandSyns) _ -> empty _ -> (True, Nothing, empty) -- | This function tries to reconstruct why a "Coercible ty1 ty2" constraint -- is left over. mkCoercibleExplanation :: GlobalRdrEnv -> FamInstEnvs -> TcType -> TcType -> SDoc mkCoercibleExplanation rdr_env fam_envs ty1 ty2 | Just (tc, tys) <- tcSplitTyConApp_maybe ty1 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys , Just msg <- coercible_msg_for_tycon rep_tc = msg | Just (tc, tys) <- splitTyConApp_maybe ty2 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys , Just msg <- coercible_msg_for_tycon rep_tc = msg | Just (s1, _) <- tcSplitAppTy_maybe ty1 , Just (s2, _) <- tcSplitAppTy_maybe ty2 , s1 `eqType` s2 , has_unknown_roles s1 = hang (text "NB: We cannot know what roles the parameters to" <+> quotes (ppr s1) <+> text "have;") 2 (text "we must assume that the role is nominal") | otherwise = empty where coercible_msg_for_tycon tc | isAbstractTyCon tc = Just $ hsep [ text "NB: The type constructor" , quotes (pprSourceTyCon tc) , text "is abstract" ] | isNewTyCon tc , [data_con] <- tyConDataCons tc , let dc_name = dataConName data_con , null (lookupGRE_Name rdr_env dc_name) = Just $ hang (text "The data constructor" <+> quotes (ppr dc_name)) 2 (sep [ text "of newtype" <+> quotes (pprSourceTyCon tc) , text "is not in scope" ]) | otherwise = Nothing has_unknown_roles ty | Just (tc, tys) <- tcSplitTyConApp_maybe ty = length tys >= tyConArity tc -- oversaturated tycon | Just (s, _) <- tcSplitAppTy_maybe ty = has_unknown_roles s | isTyVarTy ty = True | otherwise = False {- -- | Make a listing of role signatures for all the parameterised tycons -- used in the provided types -- SLPJ Jun 15: I could not convince myself that these hints were really -- useful. Maybe they are, but I think we need more work to make them -- actually helpful. mkRoleSigs :: Type -> Type -> SDoc mkRoleSigs ty1 ty2 = ppUnless (null role_sigs) $ hang (text "Relevant role signatures:") 2 (vcat role_sigs) where tcs = nameEnvElts $ tyConsOfType ty1 `plusNameEnv` tyConsOfType ty2 role_sigs = mapMaybe ppr_role_sig tcs ppr_role_sig tc | null roles -- if there are no parameters, don't bother printing = Nothing | isBuiltInSyntax (tyConName tc) -- don't print roles for (->), etc. = Nothing | otherwise = Just $ hsep $ [text "type role", ppr tc] ++ map ppr roles where roles = tyConRoles tc -} mkEqErr_help :: DynFlags -> ReportErrCtxt -> Report -> Ct -> Maybe SwapFlag -- Nothing <=> not sure -> TcType -> TcType -> TcM ErrMsg mkEqErr_help dflags ctxt report ct oriented ty1 ty2 | Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr dflags ctxt report ct oriented tv1 ty2 | Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr dflags ctxt report ct swapped tv2 ty1 | otherwise = reportEqErr ctxt report ct oriented ty1 ty2 where swapped = fmap flipSwap oriented reportEqErr :: ReportErrCtxt -> Report -> Ct -> Maybe SwapFlag -- Nothing <=> not sure -> TcType -> TcType -> TcM ErrMsg reportEqErr ctxt report ct oriented ty1 ty2 = mkErrorMsgFromCt ctxt ct (mconcat [misMatch, eqInfo, report]) where misMatch = important $ misMatchOrCND ctxt ct oriented ty1 ty2 eqInfo = important $ mkEqInfoMsg ct ty1 ty2 mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> Report -> Ct -> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg -- tv1 and ty2 are already tidied mkTyVarEqErr dflags ctxt report ct oriented tv1 ty2 | isUserSkolem ctxt tv1 -- ty2 won't be a meta-tyvar, or else the thing would -- be oriented the other way round; -- see TcCanonical.canEqTyVarTyVar || isSigTyVar tv1 && not (isTyVarTy ty2) || ctEqRel ct == ReprEq && not (isTyVarUnderDatatype tv1 ty2) -- the cases below don't really apply to ReprEq (except occurs check) = mkErrorMsgFromCt ctxt ct $ mconcat [ important $ misMatchOrCND ctxt ct oriented ty1 ty2 , important $ extraTyVarInfo ctxt tv1 ty2 , report ] -- So tv is a meta tyvar (or started that way before we -- generalised it). So presumably it is an *untouchable* -- meta tyvar or a SigTv, else it'd have been unified | OC_Occurs <- occ_check_expand , ctEqRel ct == NomEq || isTyVarUnderDatatype tv1 ty2 -- See Note [Occurs check error] in TcCanonical = do { let occCheckMsg = important $ addArising (ctOrigin ct) $ hang (text "Occurs check: cannot construct the infinite" <+> what <> colon) 2 (sep [ppr ty1, char '~', ppr ty2]) extra2 = important $ mkEqInfoMsg ct ty1 ty2 ; mkErrorMsgFromCt ctxt ct $ mconcat [occCheckMsg, extra2, report] } | OC_Forall <- occ_check_expand = do { let msg = vcat [ text "Cannot instantiate unification variable" <+> quotes (ppr tv1) , hang (text "with a" <+> what <+> text "involving foralls:") 2 (ppr ty2) , nest 2 (text "GHC doesn't yet support impredicative polymorphism") ] -- Unlike the other reports, this discards the old 'report_important' -- instead of augmenting it. This is because the details are not likely -- to be helpful since this is just an unimplemented feature. ; mkErrorMsgFromCt ctxt ct $ report { report_important = [msg] } } -- If the immediately-enclosing implication has 'tv' a skolem, and -- we know by now its an InferSkol kind of skolem, then presumably -- it started life as a SigTv, else it'd have been unified, given -- that there's no occurs-check or forall problem | (implic:_) <- cec_encl ctxt , Implic { ic_skols = skols } <- implic , tv1 `elem` skols = mkErrorMsgFromCt ctxt ct $ mconcat [ important $ misMatchMsg ct oriented ty1 ty2 , important $ extraTyVarInfo ctxt tv1 ty2 , report ] -- Check for skolem escape | (implic:_) <- cec_encl ctxt -- Get the innermost context , Implic { ic_env = env, ic_skols = skols, ic_info = skol_info } <- implic , let esc_skols = filter (`elemVarSet` (tyCoVarsOfType ty2)) skols , not (null esc_skols) = do { let msg = important $ misMatchMsg ct oriented ty1 ty2 esc_doc = sep [ text "because" <+> what <+> text "variable" <> plural esc_skols <+> pprQuotedList esc_skols , text "would escape" <+> if isSingleton esc_skols then text "its scope" else text "their scope" ] tv_extra = important $ vcat [ nest 2 $ esc_doc , sep [ (if isSingleton esc_skols then text "This (rigid, skolem)" <+> what <+> text "variable is" else text "These (rigid, skolem)" <+> what <+> text "variables are") <+> text "bound by" , nest 2 $ ppr skol_info , nest 2 $ text "at" <+> ppr (tcl_loc env) ] ] ; mkErrorMsgFromCt ctxt ct (mconcat [msg, tv_extra, report]) } -- Nastiest case: attempt to unify an untouchable variable -- See Note [Error messages for untouchables] | (implic:_) <- cec_encl ctxt -- Get the innermost context , Implic { ic_env = env, ic_given = given , ic_tclvl = lvl, ic_info = skol_info } <- implic = ASSERT2( isTcTyVar tv1 && not (isTouchableMetaTyVar lvl tv1) , ppr tv1 ) -- See Note [Error messages for untouchables] do { let msg = important $ misMatchMsg ct oriented ty1 ty2 tclvl_extra = important $ nest 2 $ sep [ quotes (ppr tv1) <+> text "is untouchable" , nest 2 $ text "inside the constraints:" <+> pprEvVarTheta given , nest 2 $ text "bound by" <+> ppr skol_info , nest 2 $ text "at" <+> ppr (tcl_loc env) ] tv_extra = important $ extraTyVarInfo ctxt tv1 ty2 add_sig = important $ suggestAddSig ctxt ty1 ty2 ; mkErrorMsgFromCt ctxt ct $ mconcat [msg, tclvl_extra, tv_extra, add_sig, report] } | otherwise = reportEqErr ctxt report ct oriented (mkTyVarTy tv1) ty2 -- This *can* happen (Trac #6123, and test T2627b) -- Consider an ambiguous top-level constraint (a ~ F a) -- Not an occurs check, because F is a type function. where occ_check_expand = occurCheckExpand dflags tv1 ty2 ty1 = mkTyVarTy tv1 what = case ctLocTypeOrKind_maybe (ctLoc ct) of Just KindLevel -> text "kind" _ -> text "type" mkEqInfoMsg :: Ct -> TcType -> TcType -> SDoc -- Report (a) ambiguity if either side is a type function application -- e.g. F a0 ~ Int -- (b) warning about injectivity if both sides are the same -- type function application F a ~ F b -- See Note [Non-injective type functions] -- (c) warning about -fprint-explicit-kinds if that might be helpful mkEqInfoMsg ct ty1 ty2 = tyfun_msg $$ ambig_msg $$ invis_msg where mb_fun1 = isTyFun_maybe ty1 mb_fun2 = isTyFun_maybe ty2 ambig_msg | isJust mb_fun1 || isJust mb_fun2 = snd (mkAmbigMsg False ct) | otherwise = empty invis_msg | Just vis <- tcEqTypeVis ty1 ty2 , vis /= Visible = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitKinds dflags then text "Use -fprint-explicit-kinds to see the kind arguments" else empty | otherwise = empty tyfun_msg | Just tc1 <- mb_fun1 , Just tc2 <- mb_fun2 , tc1 == tc2 = text "NB:" <+> quotes (ppr tc1) <+> text "is a type function, and may not be injective" | otherwise = empty isUserSkolem :: ReportErrCtxt -> TcTyVar -> Bool -- See Note [Reporting occurs-check errors] isUserSkolem ctxt tv = isSkolemTyVar tv && any is_user_skol_tv (cec_encl ctxt) where is_user_skol_tv (Implic { ic_skols = sks, ic_info = skol_info }) = tv `elem` sks && is_user_skol_info skol_info is_user_skol_info (InferSkol {}) = False is_user_skol_info _ = True misMatchOrCND :: ReportErrCtxt -> Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc -- If oriented then ty1 is actual, ty2 is expected misMatchOrCND ctxt ct oriented ty1 ty2 | null givens || (isRigidTy ty1 && isRigidTy ty2) || isGivenCt ct -- If the equality is unconditionally insoluble -- or there is no context, don't report the context = misMatchMsg ct oriented ty1 ty2 | otherwise = couldNotDeduce givens ([eq_pred], orig) where ev = ctEvidence ct eq_pred = ctEvPred ev orig = ctEvOrigin ev givens = [ given | given@(_, _, no_eqs, _) <- getUserGivens ctxt, not no_eqs] -- Keep only UserGivens that have some equalities couldNotDeduce :: [UserGiven] -> (ThetaType, CtOrigin) -> SDoc couldNotDeduce givens (wanteds, orig) = vcat [ addArising orig (text "Could not deduce:" <+> pprTheta wanteds) , vcat (pp_givens givens)] pp_givens :: [UserGiven] -> [SDoc] pp_givens givens = case givens of [] -> [] (g:gs) -> ppr_given (text "from the context:") g : map (ppr_given (text "or from:")) gs where ppr_given herald (gs, skol_info, _, loc) = hang (herald <+> pprEvVarTheta gs) 2 (sep [ text "bound by" <+> ppr skol_info , text "at" <+> ppr loc]) extraTyVarInfo :: ReportErrCtxt -> TcTyVar -> TcType -> SDoc -- Add on extra info about skolem constants -- NB: The types themselves are already tidied extraTyVarInfo ctxt tv1 ty2 = ASSERT2( isTcTyVar tv1, ppr tv1 ) tv_extra tv1 $$ ty_extra ty2 where implics = cec_encl ctxt ty_extra ty = case tcGetTyVar_maybe ty of Just tv -> tv_extra tv Nothing -> empty tv_extra tv | let pp_tv = quotes (ppr tv) = case tcTyVarDetails tv of SkolemTv {} -> pprSkol implics tv FlatSkol {} -> pp_tv <+> text "is a flattening type variable" RuntimeUnk {} -> pp_tv <+> text "is an interactive-debugger skolem" MetaTv {} -> empty suggestAddSig :: ReportErrCtxt -> TcType -> TcType -> SDoc -- See Note [Suggest adding a type signature] suggestAddSig ctxt ty1 ty2 | null inferred_bndrs = empty | [bndr] <- inferred_bndrs = text "Possible fix: add a type signature for" <+> quotes (ppr bndr) | otherwise = text "Possible fix: add type signatures for some or all of" <+> (ppr inferred_bndrs) where inferred_bndrs = nub (get_inf ty1 ++ get_inf ty2) get_inf ty | Just tv <- tcGetTyVar_maybe ty , isSkolemTyVar tv , (_, InferSkol prs) <- getSkolemInfo (cec_encl ctxt) tv = map fst prs | otherwise = [] -------------------- misMatchMsg :: Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc -- Types are already tidy -- If oriented then ty1 is actual, ty2 is expected misMatchMsg ct oriented ty1 ty2 | Just NotSwapped <- oriented = misMatchMsg ct (Just IsSwapped) ty2 ty1 -- These next two cases are when we're about to report, e.g., that -- 'PtrRepLifted doesn't match 'VoidRep. Much better just to say -- lifted vs. unlifted | Just (tc1, []) <- splitTyConApp_maybe ty1 , tc1 `hasKey` ptrRepLiftedDataConKey = lifted_vs_unlifted | Just (tc2, []) <- splitTyConApp_maybe ty2 , tc2 `hasKey` ptrRepLiftedDataConKey = lifted_vs_unlifted | Just (tc1, []) <- splitTyConApp_maybe ty1 , Just (tc2, []) <- splitTyConApp_maybe ty2 , (tc1 `hasKey` ptrRepLiftedDataConKey && tc2 `hasKey` ptrRepUnliftedDataConKey) || (tc1 `hasKey` ptrRepUnliftedDataConKey && tc2 `hasKey` ptrRepLiftedDataConKey) = lifted_vs_unlifted | otherwise -- So now we have Nothing or (Just IsSwapped) -- For some reason we treat Nothing like IsSwapped = addArising orig $ sep [ text herald1 <+> quotes (ppr ty1) , nest padding $ text herald2 <+> quotes (ppr ty2) , sameOccExtra ty2 ty1 ] where herald1 = conc [ "Couldn't match" , if is_repr then "representation of" else "" , if is_oriented then "expected" else "" , what ] herald2 = conc [ "with" , if is_repr then "that of" else "" , if is_oriented then ("actual " ++ what) else "" ] padding = length herald1 - length herald2 is_repr = case ctEqRel ct of { ReprEq -> True; NomEq -> False } is_oriented = isJust oriented orig = ctOrigin ct what = case ctLocTypeOrKind_maybe (ctLoc ct) of Just KindLevel -> "kind" _ -> "type" conc :: [String] -> String conc = foldr1 add_space add_space :: String -> String -> String add_space s1 s2 | null s1 = s2 | null s2 = s1 | otherwise = s1 ++ (' ' : s2) lifted_vs_unlifted = addArising orig $ text "Couldn't match a lifted type with an unlifted type" mkExpectedActualMsg :: Type -> Type -> CtOrigin -> Maybe TypeOrKind -> Bool -> (Bool, Maybe SwapFlag, SDoc) -- NotSwapped means (actual, expected), IsSwapped is the reverse -- First return val is whether or not to print a herald above this msg mkExpectedActualMsg ty1 ty2 (TypeEqOrigin { uo_actual = act , uo_expected = Check exp , uo_thing = maybe_thing }) m_level printExpanded | KindLevel <- level, occurs_check_error = (True, Nothing, empty) | isUnliftedTypeKind act, isLiftedTypeKind exp = (False, Nothing, msg2) | isLiftedTypeKind act, isUnliftedTypeKind exp = (False, Nothing, msg3) | isLiftedTypeKind exp && not (isConstraintKind exp) = (False, Nothing, msg4) | Just msg <- num_args_msg = (False, Nothing, msg $$ msg1) | KindLevel <- level, Just th <- maybe_thing = (False, Nothing, msg5 th) | act `pickyEqType` ty1, exp `pickyEqType` ty2 = (True, Just NotSwapped, empty) | exp `pickyEqType` ty1, act `pickyEqType` ty2 = (True, Just IsSwapped, empty) | otherwise = (True, Nothing, msg1) where level = m_level `orElse` TypeLevel occurs_check_error | Just act_tv <- tcGetTyVar_maybe act , act_tv `elemVarSet` tyCoVarsOfType exp = True | Just exp_tv <- tcGetTyVar_maybe exp , exp_tv `elemVarSet` tyCoVarsOfType act = True | otherwise = False sort = case level of TypeLevel -> text "type" KindLevel -> text "kind" msg1 = case level of KindLevel | Just th <- maybe_thing -> msg5 th _ | not (act `pickyEqType` exp) -> vcat [ text "Expected" <+> sort <> colon <+> ppr exp , text " Actual" <+> sort <> colon <+> ppr act , if printExpanded then expandedTys else empty ] | otherwise -> empty thing_msg = case maybe_thing of Just thing -> \_ -> quotes (ppr thing) <+> text "is" Nothing -> \vowel -> text "got a" <> if vowel then char 'n' else empty msg2 = sep [ text "Expecting a lifted type, but" , thing_msg True, text "unlifted" ] msg3 = sep [ text "Expecting an unlifted type, but" , thing_msg False, text "lifted" ] msg4 = maybe_num_args_msg $$ sep [ text "Expected a type, but" , maybe (text "found something with kind") (\thing -> quotes (ppr thing) <+> text "has kind") maybe_thing , quotes (ppr act) ] msg5 th = hang (text "Expected" <+> kind_desc <> comma) 2 (text "but" <+> quotes (ppr th) <+> text "has kind" <+> quotes (ppr act)) where kind_desc | isConstraintKind exp = text "a constraint" | otherwise = text "kind" <+> quotes (ppr exp) num_args_msg = case level of TypeLevel -> Nothing KindLevel -> let n_act = count_args act n_exp = count_args exp in case n_act - n_exp of n | n /= 0 , Just thing <- maybe_thing , case errorThingNumArgs_maybe thing of Nothing -> n > 0 Just num_act_args -> num_act_args >= -n -- don't report to strip off args that aren't there -> Just $ text "Expecting" <+> speakN (abs n) <+> more_or_fewer <+> plural_n (abs n) (text "argument") <+> text "to" <+> quotes (ppr thing) where more_or_fewer | n < 0 = text "fewer" | otherwise = text "more" _ -> Nothing maybe_num_args_msg = case num_args_msg of Nothing -> empty Just m -> m count_args ty = count isVisibleBinder $ fst $ splitPiTys ty plural_n 1 doc = doc plural_n _ doc = doc <> char 's' expandedTys = ppUnless (expTy1 `pickyEqType` exp && expTy2 `pickyEqType` act) $ vcat [ text "Type synonyms expanded:" , text "Expected type:" <+> ppr expTy1 , text " Actual type:" <+> ppr expTy2 ] (expTy1, expTy2) = expandSynonymsToMatch exp act mkExpectedActualMsg _ _ _ _ _ = panic "mkExpectedAcutalMsg" {- Note [Expanding type synonyms to make types similar] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In type error messages, if -fprint-expanded-types is used, we want to expand type synonyms to make expected and found types as similar as possible, but we shouldn't expand types too much to make type messages even more verbose and harder to understand. The whole point here is to make the difference in expected and found types clearer. `expandSynonymsToMatch` does this, it takes two types, and expands type synonyms only as much as necessary. It should work like this: Given two types t1 and t2: * If they're already same, it shouldn't expand any type synonyms and just return. * If they're in form `C1 t1_1 .. t1_n` and `C2 t2_1 .. t2_m` (C1 and C2 are type constructors), it should expand C1 and C2 if they're different type synonyms. Then it should continue doing same thing on expanded types. If C1 and C2 are same, then we should apply same procedure to arguments of C1 and argument of C2 to make them as similar as possible. Most important thing here is to keep number of synonym expansions at minimum. For example, if t1 is `T (T3, T5, Int)` and t2 is `T (T5, T3, Bool)` where T5 = T4, T4 = T3, ..., T1 = X, we should return `T (T3, T3, Int)` and `T (T3, T3, Bool)`. In the implementation, we just search in all possible solutions for a solution that does minimum amount of expansions. This leads to a complex algorithm: If we have two synonyms like X_m = X_{m-1} = .. X and Y_n = Y_{n-1} = .. Y, where X and Y are rigid types, we expand m * n times. But in practice it's not a problem because deeply nested synonyms with no intervening rigid type constructors are vanishingly rare. -} -- | Expand type synonyms in given types only enough to make them as equal as -- possible. Returned types are the same in terms of used type synonyms. -- -- To expand all synonyms, see 'Type.expandTypeSynonyms'. expandSynonymsToMatch :: Type -> Type -> (Type, Type) expandSynonymsToMatch ty1 ty2 = (ty1_ret, ty2_ret) where (_, ty1_ret, ty2_ret) = go 0 ty1 ty2 -- | Returns (number of synonym expansions done to make types similar, -- type synonym expanded version of first type, -- type synonym expanded version of second type) -- -- Int argument is number of synonym expansions done so far. go :: Int -> Type -> Type -> (Int, Type, Type) go exps t1 t2 | t1 `pickyEqType` t2 = -- Types are same, nothing to do (exps, t1, t2) go exps t1@(TyConApp tc1 tys1) t2@(TyConApp tc2 tys2) | tc1 == tc2 = -- Type constructors are same. They may be synonyms, but we don't -- expand further. let (exps', tys1', tys2') = unzip3 $ zipWith (go 0) tys1 tys2 in (exps + sum exps', TyConApp tc1 tys1', TyConApp tc2 tys2') | otherwise = -- Try to expand type constructors case (coreView t1, coreView t2) of -- When only one of the constructors is a synonym, we just -- expand it and continue search (Just t1', Nothing) -> go (exps + 1) t1' t2 (Nothing, Just t2') -> go (exps + 1) t1 t2' (Just t1', Just t2') -> -- Both constructors are synonyms, but they may be synonyms of -- each other. We just search for minimally expanded solution. -- See Note [Expanding type synonyms to make types similar]. let sol1@(exp1, _, _) = go (exps + 1) t1' t2 sol2@(exp2, _, _) = go (exps + 1) t1 t2' in if exp1 < exp2 then sol1 else sol2 (Nothing, Nothing) -> -- None of the constructors are synonyms, nothing to do (exps, t1, t2) go exps t1@TyConApp{} t2 | Just t1' <- coreView t1 = go (exps + 1) t1' t2 | otherwise = (exps, t1, t2) go exps t1 t2@TyConApp{} | Just t2' <- coreView t2 = go (exps + 1) t1 t2' | otherwise = (exps, t1, t2) go exps (AppTy t1_1 t1_2) (AppTy t2_1 t2_2) = let (exps1, t1_1', t2_1') = go 0 t1_1 t2_1 (exps2, t1_2', t2_2') = go 0 t1_2 t2_2 in (exps + exps1 + exps2, mkAppTy t1_1' t1_2', mkAppTy t2_1' t2_2') go exps (ForAllTy (Anon t1_1) t1_2) (ForAllTy (Anon t2_1) t2_2) = let (exps1, t1_1', t2_1') = go 0 t1_1 t2_1 (exps2, t1_2', t2_2') = go 0 t1_2 t2_2 in (exps + exps1 + exps2, mkFunTy t1_1' t1_2', mkFunTy t2_1' t2_2') go exps (ForAllTy (Named tv1 vis1) t1) (ForAllTy (Named tv2 vis2) t2) = -- NOTE: We may have a bug here, but we just can't reproduce it easily. -- See D1016 comments for details and our attempts at producing a test -- case. Short version: We probably need RnEnv2 to really get this right. let (exps1, t1', t2') = go exps t1 t2 in (exps1, ForAllTy (Named tv1 vis1) t1', ForAllTy (Named tv2 vis2) t2') go exps (CastTy ty1 _) ty2 = go exps ty1 ty2 go exps ty1 (CastTy ty2 _) = go exps ty1 ty2 go exps t1 t2 = (exps, t1, t2) sameOccExtra :: TcType -> TcType -> SDoc -- See Note [Disambiguating (X ~ X) errors] sameOccExtra ty1 ty2 | Just (tc1, _) <- tcSplitTyConApp_maybe ty1 , Just (tc2, _) <- tcSplitTyConApp_maybe ty2 , let n1 = tyConName tc1 n2 = tyConName tc2 same_occ = nameOccName n1 == nameOccName n2 same_pkg = moduleUnitId (nameModule n1) == moduleUnitId (nameModule n2) , n1 /= n2 -- Different Names , same_occ -- but same OccName = text "NB:" <+> (ppr_from same_pkg n1 $$ ppr_from same_pkg n2) | otherwise = empty where ppr_from same_pkg nm | isGoodSrcSpan loc = hang (quotes (ppr nm) <+> text "is defined at") 2 (ppr loc) | otherwise -- Imported things have an UnhelpfulSrcSpan = hang (quotes (ppr nm)) 2 (sep [ text "is defined in" <+> quotes (ppr (moduleName mod)) , ppUnless (same_pkg || pkg == mainUnitId) $ nest 4 $ text "in package" <+> quotes (ppr pkg) ]) where pkg = moduleUnitId mod mod = nameModule nm loc = nameSrcSpan nm {- Note [Suggest adding a type signature] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The OutsideIn algorithm rejects GADT programs that don't have a principal type, and indeed some that do. Example: data T a where MkT :: Int -> T Int f (MkT n) = n Does this have type f :: T a -> a, or f :: T a -> Int? The error that shows up tends to be an attempt to unify an untouchable type variable. So suggestAddSig sees if the offending type variable is bound by an *inferred* signature, and suggests adding a declared signature instead. This initially came up in Trac #8968, concerning pattern synonyms. Note [Disambiguating (X ~ X) errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See Trac #8278 Note [Reporting occurs-check errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Given (a ~ [a]), if 'a' is a rigid type variable bound by a user-supplied type signature, then the best thing is to report that we can't unify a with [a], because a is a skolem variable. That avoids the confusing "occur-check" error message. But nowadays when inferring the type of a function with no type signature, even if there are errors inside, we still generalise its signature and carry on. For example f x = x:x Here we will infer somethiing like f :: forall a. a -> [a] with a deferred error of (a ~ [a]). So in the deferred unsolved constraint 'a' is now a skolem, but not one bound by the programmer in the context! Here we really should report an occurs check. So isUserSkolem distinguishes the two. Note [Non-injective type functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's very confusing to get a message like Couldn't match expected type `Depend s' against inferred type `Depend s1' so mkTyFunInfoMsg adds: NB: `Depend' is type function, and hence may not be injective Warn of loopy local equalities that were dropped. ************************************************************************ * * Type-class errors * * ************************************************************************ -} mkDictErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg mkDictErr ctxt cts = ASSERT( not (null cts) ) do { inst_envs <- tcGetInstEnvs ; let (ct1:_) = cts -- ct1 just for its location min_cts = elim_superclasses cts lookups = map (lookup_cls_inst inst_envs) min_cts (no_inst_cts, overlap_cts) = partition is_no_inst lookups -- Report definite no-instance errors, -- or (iff there are none) overlap errors -- But we report only one of them (hence 'head') because they all -- have the same source-location origin, to try avoid a cascade -- of error from one location ; (ctxt, err) <- mk_dict_err ctxt (head (no_inst_cts ++ overlap_cts)) ; mkErrorMsgFromCt ctxt ct1 (important err) } where no_givens = null (getUserGivens ctxt) is_no_inst (ct, (matches, unifiers, _)) = no_givens && null matches && (null unifiers || all (not . isAmbiguousTyVar) (varSetElems (tyCoVarsOfCt ct))) lookup_cls_inst inst_envs ct -- Note [Flattening in error message generation] = (ct, lookupInstEnv True inst_envs clas (flattenTys emptyInScopeSet tys)) where (clas, tys) = getClassPredTys (ctPred ct) -- When simplifying [W] Ord (Set a), we need -- [W] Eq a, [W] Ord a -- but we really only want to report the latter elim_superclasses cts = filter (\ct -> any (eqType (ctPred ct)) min_preds) cts where min_preds = mkMinimalBySCs (map ctPred cts) mk_dict_err :: ReportErrCtxt -> (Ct, ClsInstLookupResult) -> TcM (ReportErrCtxt, SDoc) -- Report an overlap error if this class constraint results -- from an overlap (returning Left clas), otherwise return (Right pred) mk_dict_err ctxt (ct, (matches, unifiers, unsafe_overlapped)) | null matches -- No matches but perhaps several unifiers = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct ; candidate_insts <- get_candidate_instances ; return (ctxt, cannot_resolve_msg ct candidate_insts binds_msg) } | null unsafe_overlapped -- Some matches => overlap errors = return (ctxt, overlap_msg) | otherwise = return (ctxt, safe_haskell_msg) where orig = ctOrigin ct pred = ctPred ct (clas, tys) = getClassPredTys pred ispecs = [ispec | (ispec, _) <- matches] unsafe_ispecs = [ispec | (ispec, _) <- unsafe_overlapped] givens = getUserGivens ctxt all_tyvars = all isTyVarTy tys get_candidate_instances :: TcM [ClsInst] -- See Note [Report candidate instances] get_candidate_instances | [ty] <- tys -- Only try for single-parameter classes = do { instEnvs <- tcGetInstEnvs ; return (filter (is_candidate_inst ty) (classInstances instEnvs clas)) } | otherwise = return [] is_candidate_inst ty inst -- See Note [Report candidate instances] | [other_ty] <- is_tys inst , Just (tc1, _) <- tcSplitTyConApp_maybe ty , Just (tc2, _) <- tcSplitTyConApp_maybe other_ty = let n1 = tyConName tc1 n2 = tyConName tc2 different_names = n1 /= n2 same_occ_names = nameOccName n1 == nameOccName n2 in different_names && same_occ_names | otherwise = False cannot_resolve_msg :: Ct -> [ClsInst] -> SDoc -> SDoc cannot_resolve_msg ct candidate_insts binds_msg = vcat [ no_inst_msg , nest 2 extra_note , vcat (pp_givens givens) , in_other_words , ppWhen (has_ambig_tvs && not (null unifiers && null givens)) (vcat [ ppUnless lead_with_ambig ambig_msg, binds_msg, potential_msg ]) , show_fixes (add_to_ctxt_fixes has_ambig_tvs ++ drv_fixes) , ppWhen (not (null candidate_insts)) (hang (text "There are instances for similar types:") 2 (vcat (map ppr candidate_insts))) ] -- See Note [Report candidate instances] where orig = ctOrigin ct -- See Note [Highlighting ambiguous type variables] lead_with_ambig = has_ambig_tvs && not (any isRuntimeUnkSkol ambig_tvs) && not (null unifiers) && null givens (has_ambig_tvs, ambig_msg) = mkAmbigMsg lead_with_ambig ct ambig_tvs = uncurry (++) (getAmbigTkvs ct) no_inst_msg | lead_with_ambig = ambig_msg <+> pprArising orig $$ text "prevents the constraint" <+> quotes (pprParendType pred) <+> text "from being solved." | null givens = addArising orig $ text "No instance for" <+> pprParendType pred | otherwise = addArising orig $ text "Could not deduce" <+> pprParendType pred potential_msg = ppWhen (not (null unifiers) && want_potential orig) $ sdocWithDynFlags $ \dflags -> getPprStyle $ \sty -> pprPotentials dflags sty potential_hdr unifiers potential_hdr = vcat [ ppWhen lead_with_ambig $ text "Probable fix: use a type annotation to specify what" <+> pprQuotedList ambig_tvs <+> text "should be." , text "These potential instance" <> plural unifiers <+> text "exist:"] in_other_words | not lead_with_ambig , ProvCtxtOrigin PSB{ psb_id = (L _ name) , psb_def = (L _ pat) } <- orig -- Here we check if the "required" context is empty, otherwise -- the "In other words" is not strictly true , null [ n | (_, SigSkol (PatSynCtxt n) _, _, _) <- givens, name == n ] = vcat [ text "In other words, a successful match on the pattern" , nest 2 $ ppr pat , text "does not provide the constraint" <+> pprParendType pred ] | otherwise = empty -- Report "potential instances" only when the constraint arises -- directly from the user's use of an overloaded function want_potential (TypeEqOrigin {}) = False want_potential _ = True add_to_ctxt_fixes has_ambig_tvs | not has_ambig_tvs && all_tyvars , (orig:origs) <- usefulContext ctxt ct = [sep [ text "add" <+> pprParendType pred <+> text "to the context of" , nest 2 $ ppr_skol orig $$ vcat [ text "or" <+> ppr_skol orig | orig <- origs ] ] ] | otherwise = [] ppr_skol (PatSkol (RealDataCon dc) _) = text "the data constructor" <+> quotes (ppr dc) ppr_skol (PatSkol (PatSynCon ps) _) = text "the pattern synonym" <+> quotes (ppr ps) ppr_skol skol_info = ppr skol_info extra_note | any isFunTy (filterOutInvisibleTypes (classTyCon clas) tys) = text "(maybe you haven't applied a function to enough arguments?)" | className clas == typeableClassName -- Avoid mysterious "No instance for (Typeable T) , [_,ty] <- tys -- Look for (Typeable (k->*) (T k)) , Just (tc,_) <- tcSplitTyConApp_maybe ty , not (isTypeFamilyTyCon tc) = hang (text "GHC can't yet do polykinded") 2 (text "Typeable" <+> parens (ppr ty <+> dcolon <+> ppr (typeKind ty))) | otherwise = empty drv_fixes = case orig of DerivOrigin -> [drv_fix] DerivOriginDC {} -> [drv_fix] DerivOriginCoerce {} -> [drv_fix] _ -> [] drv_fix = hang (text "use a standalone 'deriving instance' declaration,") 2 (text "so you can specify the instance context yourself") -- Normal overlap error overlap_msg = ASSERT( not (null matches) ) vcat [ addArising orig (text "Overlapping instances for" <+> pprType (mkClassPred clas tys)) , ppUnless (null matching_givens) $ sep [text "Matching givens (or their superclasses):" , nest 2 (vcat matching_givens)] , sdocWithDynFlags $ \dflags -> getPprStyle $ \sty -> pprPotentials dflags sty (text "Matching instances:") $ ispecs ++ unifiers , ppWhen (null matching_givens && isSingleton matches && null unifiers) $ -- Intuitively, some given matched the wanted in their -- flattened or rewritten (from given equalities) form -- but the matcher can't figure that out because the -- constraints are non-flat and non-rewritten so we -- simply report back the whole given -- context. Accelerate Smart.hs showed this problem. sep [ text "There exists a (perhaps superclass) match:" , nest 2 (vcat (pp_givens givens))] , ppWhen (isSingleton matches) $ parens (vcat [ text "The choice depends on the instantiation of" <+> quotes (pprWithCommas ppr (tyCoVarsOfTypesList tys)) , ppWhen (null (matching_givens)) $ vcat [ text "To pick the first instance above, use IncoherentInstances" , text "when compiling the other instance declarations"] ])] where givens = getUserGivens ctxt matching_givens = mapMaybe matchable givens matchable (evvars,skol_info,_,loc) = case ev_vars_matching of [] -> Nothing _ -> Just $ hang (pprTheta ev_vars_matching) 2 (sep [ text "bound by" <+> ppr skol_info , text "at" <+> ppr loc]) where ev_vars_matching = filter ev_var_matches (map evVarPred evvars) ev_var_matches ty = case getClassPredTys_maybe ty of Just (clas', tys') | clas' == clas , Just _ <- tcMatchTys tys tys' -> True | otherwise -> any ev_var_matches (immSuperClasses clas' tys') Nothing -> False -- Overlap error because of Safe Haskell (first -- match should be the most specific match) safe_haskell_msg = ASSERT( length matches == 1 && not (null unsafe_ispecs) ) vcat [ addArising orig (text "Unsafe overlapping instances for" <+> pprType (mkClassPred clas tys)) , sep [text "The matching instance is:", nest 2 (pprInstance $ head ispecs)] , vcat [ text "It is compiled in a Safe module and as such can only" , text "overlap instances from the same module, however it" , text "overlaps the following instances from different" <+> text "modules:" , nest 2 (vcat [pprInstances $ unsafe_ispecs]) ] ] {- Note [Report candidate instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we have an unsolved (Num Int), where `Int` is not the Prelude Int, but comes from some other module, then it may be helpful to point out that there are some similarly named instances elsewhere. So we get something like No instance for (Num Int) arising from the literal β€˜3’ There are instances for similar types: instance Num GHC.Types.Int -- Defined in β€˜GHC.Num’ Discussion in Trac #9611. Note [Highlighting ambiguous type variables] ~------------------------------------------- When we encounter ambiguous type variables (i.e. type variables that remain metavariables after type inference), we need a few more conditions before we can reason that *ambiguity* prevents constraints from being solved: - We can't have any givens, as encountering a typeclass error with given constraints just means we couldn't deduce a solution satisfying those constraints and as such couldn't bind the type variable to a known type. - If we don't have any unifiers, we don't even have potential instances from which an ambiguity could arise. - Lastly, I don't want to mess with error reporting for unknown runtime types so we just fall back to the old message there. Once these conditions are satisfied, we can safely say that ambiguity prevents the constraint from being solved. -} usefulContext :: ReportErrCtxt -> Ct -> [SkolemInfo] usefulContext ctxt ct = go (cec_encl ctxt) where pred_tvs = tyCoVarsOfType $ ctPred ct go [] = [] go (ic : ics) | implausible ic = rest | otherwise = ic_info ic : rest where -- Stop when the context binds a variable free in the predicate rest | any (`elemVarSet` pred_tvs) (ic_skols ic) = [] | otherwise = go ics implausible ic | null (ic_skols ic) = True | implausible_info (ic_info ic) = True | otherwise = False implausible_info (SigSkol (InfSigCtxt {} ) _) = True implausible_info (SigSkol (PatSynCtxt name) _) | (ProvCtxtOrigin PSB{ psb_id = (L _ name') }) <- ctOrigin ct , name == name' = True implausible_info _ = False -- Do not suggest adding constraints to an *inferred* type signature, or to -- a pattern synonym signature when its "provided" context is the origin of -- the wanted constraint. For example, -- pattern Pat :: () => Show a => a -> Maybe a -- pattern Pat x = Just x -- This declaration should not give the possible fix: -- add (Show a) to the "required" context of the signature for `Pat' show_fixes :: [SDoc] -> SDoc show_fixes [] = empty show_fixes (f:fs) = sep [ text "Possible fix:" , nest 2 (vcat (f : map (text "or" <+>) fs))] pprPotentials :: DynFlags -> PprStyle -> SDoc -> [ClsInst] -> SDoc -- See Note [Displaying potential instances] pprPotentials dflags sty herald insts | null insts = empty | null show_these = hang herald 2 (vcat [ not_in_scope_msg empty , flag_hint ]) | otherwise = hang herald 2 (vcat [ pprInstances show_these , ppWhen (n_in_scope_hidden > 0) $ text "...plus" <+> speakNOf n_in_scope_hidden (text "other") , not_in_scope_msg (text "...plus") , flag_hint ]) where n_show = 3 :: Int show_potentials = gopt Opt_PrintPotentialInstances dflags (in_scope, not_in_scope) = partition inst_in_scope insts sorted = sortBy fuzzyClsInstCmp in_scope show_these | show_potentials = sorted | otherwise = take n_show sorted n_in_scope_hidden = length sorted - length show_these -- "in scope" means that all the type constructors -- are lexically in scope; these instances are likely -- to be more useful inst_in_scope :: ClsInst -> Bool inst_in_scope cls_inst = foldNameSet ((&&) . name_in_scope) True $ orphNamesOfTypes (is_tys cls_inst) name_in_scope name | isBuiltInSyntax name = True -- E.g. (->) | Just mod <- nameModule_maybe name = qual_in_scope (qualName sty mod (nameOccName name)) | otherwise = True qual_in_scope :: QualifyName -> Bool qual_in_scope NameUnqual = True qual_in_scope (NameQual {}) = True qual_in_scope _ = False not_in_scope_msg herald | null not_in_scope = empty | otherwise = hang (herald <+> speakNOf (length not_in_scope) (text "instance") <+> text "involving out-of-scope types") 2 (ppWhen show_potentials (pprInstances not_in_scope)) flag_hint = ppUnless (show_potentials || length show_these == length insts) $ text "(use -fprint-potential-instances to see them all)" {- Note [Displaying potential instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When showing a list of instances for - overlapping instances (show ones that match) - no such instance (show ones that could match) we want to give it a bit of structure. Here's the plan * Say that an instance is "in scope" if all of the type constructors it mentions are lexically in scope. These are the ones most likely to be useful to the programmer. * Show at most n_show in-scope instances, and summarise the rest ("plus 3 others") * Summarise the not-in-scope instances ("plus 4 not in scope") * Add the flag -fshow-potential-instances which replaces the summary with the full list -} {- Note [Flattening in error message generation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (C (Maybe (F x))), where F is a type function, and we have instances C (Maybe Int) and C (Maybe a) Since (F x) might turn into Int, this is an overlap situation, and indeed (because of flattening) the main solver will have refrained from solving. But by the time we get to error message generation, we've un-flattened the constraint. So we must *re*-flatten it before looking up in the instance environment, lest we only report one matching instance when in fact there are two. Re-flattening is pretty easy, because we don't need to keep track of evidence. We don't re-use the code in TcCanonical because that's in the TcS monad, and we are in TcM here. Note [Suggest -fprint-explicit-kinds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It can be terribly confusing to get an error message like (Trac #9171) Couldn't match expected type β€˜GetParam Base (GetParam Base Int)’ with actual type β€˜GetParam Base (GetParam Base Int)’ The reason may be that the kinds don't match up. Typically you'll get more useful information, but not when it's as a result of ambiguity. This test suggests -fprint-explicit-kinds when all the ambiguous type variables are kind variables. -} mkAmbigMsg :: Bool -- True when message has to be at beginning of sentence -> Ct -> (Bool, SDoc) mkAmbigMsg prepend_msg ct | null ambig_kvs && null ambig_tvs = (False, empty) | otherwise = (True, msg) where (ambig_kvs, ambig_tvs) = getAmbigTkvs ct msg | any isRuntimeUnkSkol ambig_kvs -- See Note [Runtime skolems] || any isRuntimeUnkSkol ambig_tvs = vcat [ text "Cannot resolve unknown runtime type" <> plural ambig_tvs <+> pprQuotedList ambig_tvs , text "Use :print or :force to determine these types"] | not (null ambig_tvs) = pp_ambig (text "type") ambig_tvs | otherwise -- All ambiguous kind variabes; suggest -fprint-explicit-kinds = vcat [ pp_ambig (text "kind") ambig_kvs , sdocWithDynFlags suggest_explicit_kinds ] pp_ambig what tkvs | prepend_msg -- "Ambiguous type variable 't0'" = text "Ambiguous" <+> what <+> text "variable" <> plural tkvs <+> pprQuotedList tkvs | otherwise -- "The type variable 't0' is ambiguous" = text "The" <+> what <+> text "variable" <> plural tkvs <+> pprQuotedList tkvs <+> is_or_are tkvs <+> text "ambiguous" is_or_are [_] = text "is" is_or_are _ = text "are" suggest_explicit_kinds dflags -- See Note [Suggest -fprint-explicit-kinds] | gopt Opt_PrintExplicitKinds dflags = empty | otherwise = text "Use -fprint-explicit-kinds to see the kind arguments" pprSkol :: [Implication] -> TcTyVar -> SDoc pprSkol implics tv | (skol_tvs, skol_info) <- getSkolemInfo implics tv = case skol_info of UnkSkol -> pp_tv <+> text "is an unknown type variable" SigSkol ctxt ty -> ppr_rigid (pprSigSkolInfo ctxt (mkCheckExpType $ mkSpecForAllTys skol_tvs (checkingExpType "pprSkol" ty))) _ -> ppr_rigid (pprSkolInfo skol_info) where pp_tv = quotes (ppr tv) ppr_rigid pp_info = hang (pp_tv <+> text "is a rigid type variable bound by") 2 (sep [ pp_info , text "at" <+> ppr (getSrcLoc tv) ]) getAmbigTkvs :: Ct -> ([Var],[Var]) getAmbigTkvs ct = partition (`elemVarSet` dep_tkv_set) ambig_tkvs where tkv_set = tyCoVarsOfCt ct ambig_tkv_set = filterVarSet isAmbiguousTyVar tkv_set dep_tkv_set = tyCoVarsOfTypes (map tyVarKind (varSetElems tkv_set)) ambig_tkvs = varSetElems ambig_tkv_set getSkolemInfo :: [Implication] -> TcTyVar -> ([TcTyVar], SkolemInfo) -- Get the skolem info for a type variable -- from the implication constraint that binds it getSkolemInfo [] tv = pprPanic "No skolem info:" (ppr tv) getSkolemInfo (implic:implics) tv | let skols = ic_skols implic , tv `elem` ic_skols implic = (skols, ic_info implic) | otherwise = getSkolemInfo implics tv ----------------------- -- relevantBindings looks at the value environment and finds values whose -- types mention any of the offending type variables. It has to be -- careful to zonk the Id's type first, so it has to be in the monad. -- We must be careful to pass it a zonked type variable, too. -- -- We always remove closed top-level bindings, though, -- since they are never relevant (cf Trac #8233) relevantBindings :: Bool -- True <=> filter by tyvar; False <=> no filtering -- See Trac #8191 -> ReportErrCtxt -> Ct -> TcM (ReportErrCtxt, SDoc, Ct) -- Also returns the zonked and tidied CtOrigin of the constraint relevantBindings want_filtering ctxt ct = do { dflags <- getDynFlags ; (env1, tidy_orig) <- zonkTidyOrigin (cec_tidy ctxt) (ctLocOrigin loc) ; let ct_tvs = tyCoVarsOfCt ct `unionVarSet` extra_tvs -- For *kind* errors, report the relevant bindings of the -- enclosing *type* equality, because that's more useful for the programmer extra_tvs = case tidy_orig of KindEqOrigin t1 m_t2 _ _ -> tyCoVarsOfTypes $ t1 : maybeToList m_t2 _ -> emptyVarSet ; traceTc "relevantBindings" $ vcat [ ppr ct , pprCtOrigin (ctLocOrigin loc) , ppr ct_tvs , pprWithCommas id [ ppr id <+> dcolon <+> ppr (idType id) | TcIdBndr id _ <- tcl_bndrs lcl_env ] , pprWithCommas id [ ppr id | TcIdBndr_ExpType id _ _ <- tcl_bndrs lcl_env ] ] ; (tidy_env', docs, discards) <- go env1 ct_tvs (maxRelevantBinds dflags) emptyVarSet [] False (tcl_bndrs lcl_env) -- tcl_bndrs has the innermost bindings first, -- which are probably the most relevant ones ; let doc = ppUnless (null docs) $ hang (text "Relevant bindings include") 2 (vcat docs $$ ppWhen discards discardMsg) -- Put a zonked, tidied CtOrigin into the Ct loc' = setCtLocOrigin loc tidy_orig ct' = setCtLoc ct loc' ctxt' = ctxt { cec_tidy = tidy_env' } ; return (ctxt', doc, ct') } where ev = ctEvidence ct loc = ctEvLoc ev lcl_env = ctLocEnv loc run_out :: Maybe Int -> Bool run_out Nothing = False run_out (Just n) = n <= 0 dec_max :: Maybe Int -> Maybe Int dec_max = fmap (\n -> n - 1) go :: TidyEnv -> TcTyVarSet -> Maybe Int -> TcTyVarSet -> [SDoc] -> Bool -- True <=> some filtered out due to lack of fuel -> [TcIdBinder] -> TcM (TidyEnv, [SDoc], Bool) -- The bool says if we filtered any out -- because of lack of fuel go tidy_env _ _ _ docs discards [] = return (tidy_env, reverse docs, discards) go tidy_env ct_tvs n_left tvs_seen docs discards (tc_bndr : tc_bndrs) = case tc_bndr of TcIdBndr id top_lvl -> go2 (idName id) (idType id) top_lvl TcIdBndr_ExpType name et top_lvl -> do { mb_ty <- readExpType_maybe et -- et really should be filled in by now. But there's a chance -- it hasn't, if, say, we're reporting a kind error en route to -- checking a term. See test indexed-types/should_fail/T8129 ; ty <- case mb_ty of Just ty -> return ty Nothing -> do { traceTc "Defaulting an ExpType in relevantBindings" (ppr et) ; expTypeToType et } ; go2 name ty top_lvl } where go2 id_name id_type top_lvl = do { (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env id_type ; traceTc "relevantBindings 1" (ppr id_name <+> dcolon <+> ppr tidy_ty) ; let id_tvs = tyCoVarsOfType tidy_ty doc = sep [ pprPrefixOcc id_name <+> dcolon <+> ppr tidy_ty , nest 2 (parens (text "bound at" <+> ppr (getSrcLoc id_name)))] new_seen = tvs_seen `unionVarSet` id_tvs ; if (want_filtering && not opt_PprStyle_Debug && id_tvs `disjointVarSet` ct_tvs) -- We want to filter out this binding anyway -- so discard it silently then go tidy_env ct_tvs n_left tvs_seen docs discards tc_bndrs else if isTopLevel top_lvl && not (isNothing n_left) -- It's a top-level binding and we have not specified -- -fno-max-relevant-bindings, so discard it silently then go tidy_env ct_tvs n_left tvs_seen docs discards tc_bndrs else if run_out n_left && id_tvs `subVarSet` tvs_seen -- We've run out of n_left fuel and this binding only -- mentions aleady-seen type variables, so discard it then go tidy_env ct_tvs n_left tvs_seen docs True tc_bndrs -- Keep this binding, decrement fuel else go tidy_env' ct_tvs (dec_max n_left) new_seen (doc:docs) discards tc_bndrs } discardMsg :: SDoc discardMsg = text "(Some bindings suppressed;" <+> text "use -fmax-relevant-binds=N or -fno-max-relevant-binds)" ----------------------- warnDefaulting :: [Ct] -> Type -> TcM () warnDefaulting wanteds default_ty = do { warn_default <- woptM Opt_WarnTypeDefaults ; env0 <- tcInitTidyEnv ; let tidy_env = tidyFreeTyCoVars env0 $ foldr (unionVarSet . tyCoVarsOfCt) emptyVarSet wanteds tidy_wanteds = map (tidyCt tidy_env) wanteds (loc, ppr_wanteds) = pprWithArising tidy_wanteds warn_msg = hang (hsep [ text "Defaulting the following" , text "constraint" <> plural tidy_wanteds , text "to type" , quotes (ppr default_ty) ]) 2 ppr_wanteds ; setCtLocM loc $ warnTc (Reason Opt_WarnTypeDefaults) warn_default warn_msg } {- Note [Runtime skolems] ~~~~~~~~~~~~~~~~~~~~~~ We want to give a reasonably helpful error message for ambiguity arising from *runtime* skolems in the debugger. These are created by in RtClosureInspect.zonkRTTIType. ************************************************************************ * * Error from the canonicaliser These ones are called *during* constraint simplification * * ************************************************************************ -} solverDepthErrorTcS :: CtLoc -> TcType -> TcM a solverDepthErrorTcS loc ty = setCtLocM loc $ do { ty <- zonkTcType ty ; env0 <- tcInitTidyEnv ; let tidy_env = tidyFreeTyCoVars env0 (tyCoVarsOfType ty) tidy_ty = tidyType tidy_env ty msg = vcat [ text "Reduction stack overflow; size =" <+> ppr depth , hang (text "When simplifying the following type:") 2 (ppr tidy_ty) , note ] ; failWithTcM (tidy_env, msg) } where depth = ctLocDepth loc note = vcat [ text "Use -freduction-depth=0 to disable this check" , text "(any upper bound you could choose might fail unpredictably with" , text " minor updates to GHC, so disabling the check is recommended if" , text " you're sure that type checking should terminate)" ]
oldmanmike/ghc
compiler/typecheck/TcErrors.hs
bsd-3-clause
101,589
1
25
31,927
19,338
9,863
9,475
-1
-1
{-# LANGUAGE PackageImports #-} import "hs-yesod-proto-nucleus" Application (develMain) import Prelude (IO) main :: IO () main = develMain
Greif-IT/hs-yesod-proto
hs-yesod-proto-nucleus/app/devel.hs
bsd-3-clause
140
0
6
19
34
20
14
5
1
module Cipher where import Data.Char -- Loops Int values through a specified range modRange :: Int -> Int -> Int -> Int modRange min max val = mod (val - min) (max - min + 1) + min -- 'modRange' for lowercase alphabetic characters alphaLower :: Int -> Int alphaLower = modRange 97 122 -- caesar cipher for single Char cipher :: Int -> Char -> Char cipher x y | not $ isAlpha y = y | otherwise = chr . alphaLower $ x + ord y -- Caesar cipher caesar :: Int -> [Char] -> [Char] caesar = map . cipher -- Caesar cipher decryption unCaesar :: Int -> [Char] -> [Char] unCaesar = map . cipher . negate
pdmurray/haskell-book-ex
src/ch9/Cipher.hs
bsd-3-clause
608
0
9
135
209
112
97
14
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Backend.InductiveGraph.Proto1 where import Backend.InductiveGraph.Draw import Backend.InductiveGraph.DrawTIKZ import Backend.InductiveGraph.InductiveGraph import Backend.InductiveGraph.PrintLatex import Backend.InductiveGraph.Probability import Data.Graph.Inductive.Graph import Language.Operators import Utils.Plot s1 = var "S_1" m1 = var "S_2" m2 = var "S_3" m3 = var "S_4" f :: String -> Float f "S_1" = 0.5 f "S_2" = 0.5 f "S_3" = 0.5 f "S_4" = 0.5 v1 = s1 .& m1 .+ m2 v2 = s1 .+ m2 .+ m3 v3 = s1 .+ m3 vl = ["S_1", "S_2", "S_3", "S_4"] vl123 = ["S_1", "S_2", "S_3", "S_4"] vl23 = ["S_1", "S_3", "S_4"] vl3 = ["S_1", "S_4"] drawp vl e = drawPdfInfoSheet e vl (Just f) drawnp e = drawPdfInfoSheet e vl Nothing dir = "/Users/zaccaria/development/github/org-crypto/polimi-casca/docs/general-ideas/bdd/images" writePdfs :: IO () writePdfs = do drawnp (s1 .| m1) (dir ++ "/s1_p_m1.pdf") drawnp (s1 .+ m1) (dir ++ "/s1_x_m1.pdf") drawnp (s1 .& m1 .+ m2) (dir ++ "/s1_t_m1_x_m2.pdf") drawnp (s1 .& m1) (dir ++ "/s1_t_m1.pdf") drawp vl (s1 .& m1) (dir ++ "/s1_t_m1_r.pdf") drawp vl (s1 .+ m1) (dir ++ "/s1_x_m1_r.pdf") drawp vl (s1 .| m1) (dir ++ "/s1_p_m1_r.pdf") drawp vl (v1) (dir ++ "/v1_r.pdf") drawp vl23 (v2) (dir ++ "/v2_r.pdf") drawp vl3 (v3) (dir ++ "/v3_r.pdf") drawp vl (v1 .<> v2) (dir ++ "/v1_m_v2_r.pdf") drawp vl (v2 .<> v3) (dir ++ "/v2_m_v3_r.pdf") drawp vl (v1 .<> v3) (dir ++ "/v1_m_v3_r.pdf") drawp vl (v1 .<> v2 .<> v3) (dir ++ "/v1_m_v2_m_v3_r.pdf") drawp vl (s1 .& m1 .+ m1) (dir ++ "/s1_t_m1_x_m1_r.pdf") drawp vl (s1 .& m1 .| m1) (dir ++ "/s1_t_m1_p_m1_r.pdf")
vzaccaria/bddtool
src/Backend/InductiveGraph/Proto1.hs
bsd-3-clause
1,685
0
10
304
660
350
310
48
1
module Insomnia.Main.Command where import System.Environment (getArgs) data Command = Typecheck !FilePath | Gamble !FilePath | HelpUsage processArguments :: IO Command processArguments = do args <- getArgs case args of [arg] | arg == "--help" -> return HelpUsage | otherwise -> return $ Typecheck arg ["-c", arg] -> return $ Gamble arg _ -> return HelpUsage printUsage :: IO () printUsage = putStrLn "Usage: insomnia [[-c] FILE | --help]"
lambdageek/insomnia
src/Insomnia/Main/Command.hs
bsd-3-clause
476
0
13
105
147
74
73
20
3
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.EvaluationTable.Page ( evaluationTable ) where import Control.Monad import Data.Function (on) import Data.List (sortBy) import Data.Maybe (fromMaybe) import Data.Map (Map) import qualified Data.Map as Map import Data.String (fromString) import Data.Time (UTCTime) import qualified Bead.Controller.Pages as Pages import Bead.Controller.UserStories (openSubmissions) import Bead.Domain.Entity.Assignment as Assignment import Bead.View.Pagelets import Bead.View.Content import Bead.View.Content.SubmissionTable (formatSubmissionInfo) import qualified Bead.View.Content.Bootstrap as Bootstrap import Text.Blaze.Html5 as H hiding (link, map) import qualified Text.Blaze.Html5.Attributes as A evaluationTable :: ViewHandler evaluationTable = ViewHandler evaluationTablePage evaluationTablePage :: GETContentHandler evaluationTablePage = evaluationTableContent <$> userTimeZoneToLocalTimeConverter <*> userStory openSubmissions evaluationTableContent :: UserTimeConverter -> OpenedSubmissions -> IHtml evaluationTableContent tc = openedSubmissionsCata $ \admincourse admingroup related -> do msg <- getI18N return $ do noUnevaluatedSubmission msg admincourse admingroup related when (not $ null admingroup) $ Bootstrap.rowColMd12 $ do H.h4 $ fromString . msg $ msg_EvaluationTable_GroupAssignment "Group assignments" fromString . msg $ msg_EvaluationTable_GroupAssignmentInfo $ concat [ "Submissions for group assignments sent by the users who correspond " , "the groups administrated by you." ] evaluationTable msg (sortSubmissions admingroup) isGroup when (not $ null admincourse) $ Bootstrap.rowColMd12 $ do H.h4 $ fromString . msg $ msg_EvaluationTable_CourseAssignment "Course assignments" fromString . msg $ msg_EvaluationTable_CourseAssignmentInfo $ concat [ "Submissions for course assignments sent by the users who correspond " , "the courses of groups administrated by you." ] evaluationTable msg (sortSubmissions admincourse) isCourse when (not $ null related) $ Bootstrap.rowColMd12 $ do H.h4 $ fromString . msg $ msg_EvaluationTable_MiscCourseAssignment "Miscellaneous Course assignments" fromString . msg $ msg_EvaluationTable_MiscCourseAssignmentInfo $ concat [ "Submissions for course assignments sent by the users who correspond " , "the courses of groups administrated by you, but not your students." ] evaluationTable msg (sortSubmissions related) isCourse where isGroup = True isCourse = False noUnevaluatedSubmission msg ac ag rl = Bootstrap.rowColMd12 $ if (and [null ac, null ag, null rl]) then (H.p $ fromString $ msg $ msg_EvaluationTable_EmptyUnevaluatedSolutions "There are no unevaluated submissions.") else H.p $ fromString . msg $ msg_EvaluationTable_Info $ concat [ "Only the last unevaluated submission is shown per student. The " , "other submissions may be accessed through the submission table " , "on the home page." ] evaluationTable msg ks isGroup = when (not $ null ks) $ Bootstrap.rowColMd12 $ do Bootstrap.table $ do thead $ H.tr $ do H.th (fromString . msg $ msg_EvaluationTable_Link "Link") H.th (fromString . msg $ msg_EvaluationTable_Assignment "Assignment") H.th (fromString . msg $ msg_EvaluationTable_Username "Username") H.th (fromString . msg $ msg_EvaluationTable_Student "Student") H.th (fromString . msg $ msg_EvaluationTable_Course "Course") when isGroup $ H.th (fromString . msg $ msg_EvaluationTable_Group "Group") H.th (fromString . msg $ msg_EvaluationTable_DateOfSubmission "Date") H.th (fromString. msg $ msg_EvaluationTable_SubmissionInfo "State") tbody $ forM_ ks (submissionInfo tc msg isGroup) submissionInfo tc msg isGroup (key, desc) = H.tr $ do H.td $ link (routeOf (evaluation key)) (msg $ msg_EvaluationTable_Solution "Submission") H.td . fromString . Assignment.name . eAssignment $ desc uid (H.td . fromString) $ eUid desc H.td . fromString . eStudent $ desc H.td . fromString . eCourse $ desc when isGroup $ H.td . fromString . fromMaybe "" . eGroup $ desc H.td . fromString . showDate . tc $ eSubmissionDate desc H.td . submissionIcon msg . eSubmissionInfo $ desc where evaluation k = Pages.evaluation k () submissionIcon :: I18N -> SubmissionInfo -> H.Html submissionIcon msg = formatSubmissionInfo id mempty -- not found (H.i ! A.class_ "glyphicon glyphicon-stop" ! A.style "color:#AAAAAA; font-size: large" ! tooltip (msg_Home_SubmissionCell_NonEvaluated "Non evaluated") $ mempty) -- non-evaluated (bool (H.i ! A.class_ "glyphicon glyphicon-ok-circle" ! A.style "color:#AAAAAA; font-size: large" ! tooltip (msg_Home_SubmissionCell_Tests_Passed "Tests are passed") $ mempty) -- tested accepted (H.i ! A.class_ "glyphicon glyphicon-remove-circle" ! A.style "color:#AAAAAA; font-size: large" ! tooltip (msg_Home_SubmissionCell_Tests_Failed "Tests are failed") $ mempty)) -- tested rejected (H.i ! A.class_ "glyphicon glyphicon-thumbs-up" ! A.style "color:#00FF00; font-size: large" ! tooltip (msg_Home_SubmissionCell_Accepted "Accepted") $ mempty) -- accepted (H.i ! A.class_ "glyphicon glyphicon-thumbs-down" ! A.style "color:#FF0000; font-size: large" ! tooltip (msg_Home_SubmissionCell_Rejected "Rejected") $ mempty) -- rejected where tooltip m = A.title (fromString $ msg m) -- * Sorting submissions -- Create an ordered submission list based on the course group and assignment time ordering, -- the submission list elements are ordered by the submission time of the solution -- The key for the ordering consists of in order a course name, a group name (possible empty), and -- the time of the assignment type SMKey = (String, Maybe String, UTCTime) type SMVal = (SubmissionKey, SubmissionDesc) -- SubmissionMap an ordered map which hold several type SMap = Map SMKey [SMVal] descToKey :: SMVal -> SMKey descToKey (_k,d) = (eCourse d, eGroup d, eAssignmentDate d) insertSMap :: SMap -> SMVal -> SMap insertSMap m x = let key = descToKey x in maybe (Map.insert key [x] m) (\xs -> Map.insert key (x:xs) m) (Map.lookup key m) sortSubmissions :: [SMVal] -> [SMVal] sortSubmissions [] = [] sortSubmissions [s] = [s] sortSubmissions sm = concat . map (sortBy cmp) . map snd . Map.toList . foldl insertSMap Map.empty $ sm where cmp = compare `on` (eSubmissionDate . snd)
andorp/bead
src/Bead/View/Content/EvaluationTable/Page.hs
bsd-3-clause
6,839
0
20
1,460
1,710
874
836
111
2
{-# LANGUAGE OverloadedStrings #-} import qualified Data.Text as T import qualified Data.Text.IO as T import Text.Template main :: IO () main = do t <- T.readFile "samples/sample1.tp" mr <- template convert get t maybe (return ()) T.putStr mr convert :: T.Text -> [T.Text] convert "name" = ["Yoshikuni", "Kazuhiro"] convert "i" = map (T.pack . show) [1 :: Int ..] convert _ = [] get :: T.Text -> IO [T.Text] get = mapM T.readFile . (`map` ["1", "2"]) . (++) . ("samples/" ++) . T.unpack
YoshikuniJujo/template
tests/test2t.hs
bsd-3-clause
496
0
10
93
219
121
98
16
1
{-# LANGUAGE OverloadedStrings #-} module Find (runFind, FindOpt(..)) where import RarecoalLib.Utils (GeneralOptions(..), HistogramOptions(..), setNrProcessors) import RarecoalLib.Core (ModelSpec(..), ModelEvent(..), EventType(..)) import SequenceFormats.RareAlleleHistogram (RareAlleleHistogram(..)) import RarecoalLib.Utils (loadHistogram, ModelBranch, RarecoalException(..), tryEither) import RarecoalLib.MaxUtils (computeLogLikelihood) import RarecoalLib.ModelTemplate (getModelTemplate, makeParameterDict, ModelOptions(..), instantiateModel, ParamOptions(..), ModelTemplate(..)) import Control.Exception (throwIO) import Control.Monad (unless) import Data.List (maximumBy, elemIndex) import System.IO (stderr, hPutStrLn, openFile, IOMode(..), hClose) data FindOpt = FindOpt { fiGeneralOpts :: GeneralOptions, fiModelOpts :: ModelOptions, fiParamOpts :: ParamOptions, fiHistOpts :: HistogramOptions, fiQueryBranch :: ModelBranch, fiEvalPath :: FilePath, fiBranchAge :: Double, fiDeltaTime :: Double, fiMaxTime :: Double } runFind :: FindOpt -> IO () runFind opts = do setNrProcessors (fiGeneralOpts opts) modelTemplate <- getModelTemplate (fiModelOpts opts) modelParams <- makeParameterDict (fiParamOpts opts) modelSpec <- tryEither $ instantiateModel (fiGeneralOpts opts) modelTemplate modelParams (hist, siteRed) <- loadHistogram (fiHistOpts opts) (mtBranchNames modelTemplate) l <- tryEither $ findQueryIndex (mtBranchNames modelTemplate) (fiQueryBranch opts) unless (hasFreeBranch l modelSpec) $ throwIO $ RarecoalModelException ("model must have free branch " ++ show l) let modelSpec' = if fiBranchAge opts > 0.0 then let events = ModelEvent 0.0 (SetFreeze l True) : ModelEvent (fiBranchAge opts) (SetFreeze l False) : mEvents modelSpec in modelSpec {mEvents = events} else modelSpec let nrPops = mNrPops modelSpec' allParamPairs = do branch <- [0..(nrPops - 1)] False <- return $ branch == l False <- return $ isEmptyBranch modelSpec' branch (fiBranchAge opts) time <- getJoinTimes modelSpec' (fiDeltaTime opts) (fiMaxTime opts) (fiBranchAge opts) branch return (branch, time) allLikelihoods <- sequence $ do (k, t) <- allParamPairs return $ computeLogLikelihoodIO hist siteRed modelSpec' (mtBranchNames modelTemplate) k l t writeResult (fiEvalPath opts) allParamPairs allLikelihoods let ((minBranch, minTime), minLL) = maximumBy (\(_, ll1) (_, ll2) -> ll1 `compare` ll2) $ zip allParamPairs allLikelihoods putStrLn $ "highest likelihood point:\nbranch " ++ show minBranch ++ "\ntime " ++ show minTime ++ "\nlog-likelihood " ++ show minLL where hasFreeBranch queryBranch modelSpec = let e = mEvents modelSpec jIndices = concat [[k, l] | ModelEvent _ (Join k l) <- e] in queryBranch `notElem` jIndices findQueryIndex :: [ModelBranch] -> ModelBranch -> Either RarecoalException Int findQueryIndex names branchName = case elemIndex branchName names of Nothing -> Left $ RarecoalModelException ("could not find branch name " ++ branchName) Just i -> return i isEmptyBranch :: ModelSpec -> Int -> Double -> Bool isEmptyBranch modelSpec l t = not $ null previousJoins where previousJoins = [j | ModelEvent t' j@(Join _ l') <- mEvents modelSpec, l' == l, t' < t] getJoinTimes :: ModelSpec -> Double -> Double -> Double -> Int -> [Double] getJoinTimes modelSpec deltaT maxT branchAge k = let allTimes = takeWhile (<=maxT) $ map ((+branchAge) . (*deltaT)) [1.0,2.0..] leaveTimes = [t | ModelEvent t (Join _ l) <- mEvents modelSpec, k == l] in if null leaveTimes then allTimes else filter (<head leaveTimes) allTimes computeLogLikelihoodIO :: RareAlleleHistogram -> Double -> ModelSpec -> [ModelBranch] -> Int -> Int -> Double -> IO Double computeLogLikelihoodIO hist siteRed modelSpec modelBranchNames k l t = do let e = mEvents modelSpec newE = ModelEvent t (Join k l) modelSpec' = modelSpec {mEvents = newE : e} ll <- tryEither $ computeLogLikelihood modelSpec' hist modelBranchNames siteRed hPutStrLn stderr ("branch=" ++ show k ++ ", time=" ++ show t ++ ", ll=" ++ show ll) return ll writeResult :: FilePath -> [(Int, Double)] -> [Double] -> IO () writeResult fp paramPairs allLikelihoods = do h <- openFile fp WriteMode hPutStrLn h "Branch\tTime\tLikelihood" let f (k, t) l = show k ++ "\t" ++ show t ++ "\t" ++ show l l_ = zipWith f paramPairs allLikelihoods mapM_ (hPutStrLn h) l_ hClose h
stschiff/rarecoal
src-rarecoal/Find.hs
gpl-3.0
4,856
0
19
1,142
1,534
798
736
89
2
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.HTools.Backend.Text (testHTools_Backend_Text) where import Test.QuickCheck import qualified Data.Map as Map import Data.List import Data.Maybe import System.Time (ClockTime(..)) import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.TestHTools import Test.Ganeti.HTools.Instance (genInstanceSmallerThanNode, genInstanceOnNodeList) import Test.Ganeti.HTools.Node (genNode, genOnlineNode, genEmptyOnlineNode , genUniqueNodeList) import Ganeti.BasicTypes import Ganeti.Types (InstanceStatus(..)) import qualified Ganeti.HTools.AlgorithmParams as Alg import qualified Ganeti.HTools.Backend.Text as Text import qualified Ganeti.HTools.Cluster as Cluster import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Group as Group import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Loader as Loader import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Types as Types import qualified Ganeti.Utils as Utils -- * Instance text loader tests toYN :: Bool -> String toYN True = "Y" toYN False = "N" prop_Load_Instance :: String -> Int -> Int -> Int -> Types.InstanceStatus -> NonEmptyList Char -> String -> NonNegative Int -> NonNegative Int -> Bool -> Types.DiskTemplate -> Int -> NonNegative Int -> Bool -> [String] -> Property prop_Load_Instance name mem dsk vcpus status (NonEmpty pnode) snode (NonNegative pdx) (NonNegative sdx) autobal dt su (NonNegative spindles) forth ignoredFields = pnode /= snode && pdx /= sdx ==> let vcpus_s = show vcpus dsk_s = show dsk mem_s = show mem su_s = show su status_s = Types.instanceStatusToRaw status ndx = if null snode then [(pnode, pdx)] else [(pnode, pdx), (snode, sdx)] nl = Map.fromList ndx tags = "" sbal = toYN autobal sdt = Types.diskTemplateToRaw dt inst = Text.loadInst nl $ [name, mem_s, dsk_s, vcpus_s, status_s, sbal, pnode, snode, sdt, tags, su_s, show spindles, toYN forth] ++ ignoredFields fail1 = Text.loadInst nl [name, mem_s, dsk_s, vcpus_s, status_s, sbal, pnode, pnode, tags] in case inst of Bad msg -> failTest $ "Failed to load instance: " ++ msg Ok (_, i) -> counterexample "Mismatch in some field while\ \ loading the instance" $ Instance.name i == name && Instance.vcpus i == vcpus && Instance.mem i == mem && Instance.pNode i == pdx && Instance.sNode i == (if null snode then Node.noSecondary else sdx) && Instance.autoBalance i == autobal && Instance.spindleUse i == su && Instance.getTotalSpindles i == Just spindles && Instance.forthcoming i == forth && isBad fail1 prop_Load_InstanceFail :: [(String, Int)] -> [String] -> Property prop_Load_InstanceFail ktn fields = length fields < 10 ==> case Text.loadInst nl fields of Ok _ -> failTest "Managed to load instance from invalid data" Bad msg -> counterexample ("Unrecognised error message: " ++ msg) $ "Invalid/incomplete instance data: '" `isPrefixOf` msg where nl = Map.fromList ktn genInstanceNodes :: Gen (Instance.Instance, Node.List, Types.NameAssoc) genInstanceNodes = do (nl, na) <- genUniqueNodeList genOnlineNode inst <- genInstanceOnNodeList nl return (inst, nl, na) prop_InstanceLSIdempotent :: Property prop_InstanceLSIdempotent = forAll genInstanceNodes $ \(inst, nl, assoc) -> (Text.loadInst assoc . Utils.sepSplit '|' . Text.serializeInstance nl) inst ==? Ok (Instance.name inst, inst) prop_Load_Node :: String -> Int -> Int -> Int -> Int -> Int -> Int -> Bool -> Bool prop_Load_Node name tm nm fm td fd tc fo = let conv v = if v < 0 then "?" else show v tm_s = conv tm nm_s = conv nm fm_s = conv fm td_s = conv td fd_s = conv fd tc_s = conv tc fo_s = toYN fo any_broken = any (< 0) [tm, nm, fm, td, fd, tc] gid = Group.uuid defGroup in case Text.loadNode defGroupAssoc [name, tm_s, nm_s, fm_s, td_s, fd_s, tc_s, fo_s, gid] of Nothing -> False Just (name', node) -> if fo || any_broken then Node.offline node else Node.name node == name' && name' == name && Node.alias node == name && Node.tMem node == fromIntegral tm && Node.nMem node == nm && Node.fMem node == fm && Node.tDsk node == fromIntegral td && Node.fDsk node == fd && Node.tCpu node == fromIntegral tc prop_Load_NodeFail :: [String] -> Property prop_Load_NodeFail fields = length fields < 8 ==> isNothing $ Text.loadNode Map.empty fields prop_Load_NodeSuccess :: String -> NonNegative Int -> NonNegative Int -> NonNegative Int -> NonNegative Int -> NonNegative Int -> NonNegative Int -> Bool -> NonNegative Int -> Bool -> NonNegative Int -> NonNegative Int -> NonNegative Int -> [String] -> Property prop_Load_NodeSuccess name (NonNegative tm) (NonNegative nm) (NonNegative fm) (NonNegative td) (NonNegative fd) (NonNegative tc) fo (NonNegative spindles) excl_stor (NonNegative free_spindles) (NonNegative nos_cpu) (NonNegative cpu_speed) ignoredFields = forAll genTags $ \tags -> let node' = Text.loadNode defGroupAssoc $ [ name, show tm, show nm, show fm , show td, show fd, show tc , toYN fo, Group.uuid defGroup , show spindles , intercalate "," tags , toYN excl_stor , show free_spindles , show nos_cpu , show cpu_speed ] ++ ignoredFields in case node' of Bad msg -> failTest $ "Failed to load node: " ++ msg Ok (_, node) -> conjoin [ Node.name node ==? name , Node.tMem node ==? fromIntegral tm , Node.nMem node ==? nm , Node.fMem node ==? fm , Node.tDsk node ==? fromIntegral td , Node.fDsk node ==? fd , Node.tCpu node ==? fromIntegral tc , Node.nTags node ==? tags , Node.fSpindles node ==? free_spindles , Node.nCpu node ==? nos_cpu , Node.tCpuSpeed node ==? fromIntegral cpu_speed ] prop_NodeLSIdempotent :: Property prop_NodeLSIdempotent = forAll (genNode (Just 1) Nothing) $ \node -> -- override failN1 to what loadNode returns by default -- override pMem, xMem as they are updated after loading [in updateMemStat] let n = Node.setPolicy Types.defIPolicy $ node { Node.failN1 = True, Node.offline = False, Node.pMem = 0, Node.xMem = 0 } in (Text.loadNode defGroupAssoc. Utils.sepSplit '|' . Text.serializeNode defGroupList) n ==? Just (Node.name n, n) prop_ISpecIdempotent :: Types.ISpec -> Property prop_ISpecIdempotent ispec = case Text.loadISpec "dummy" . Utils.sepSplit ',' . Text.serializeISpec $ ispec of Bad msg -> failTest $ "Failed to load ispec: " ++ msg Ok ispec' -> ispec' ==? ispec prop_MultipleMinMaxISpecsIdempotent :: [Types.MinMaxISpecs] -> Property prop_MultipleMinMaxISpecsIdempotent minmaxes = case Text.loadMultipleMinMaxISpecs "dummy" . Utils.sepSplit ';' . Text.serializeMultipleMinMaxISpecs $ minmaxes of Bad msg -> failTest $ "Failed to load min/max ispecs: " ++ msg Ok minmaxes' -> minmaxes' ==? minmaxes prop_IPolicyIdempotent :: Types.IPolicy -> Property prop_IPolicyIdempotent ipol = case Text.loadIPolicy . Utils.sepSplit '|' $ Text.serializeIPolicy owner ipol of Bad msg -> failTest $ "Failed to load ispec: " ++ msg Ok res -> res ==? (owner, ipol) where owner = "dummy" -- | This property, while being in the text tests, does more than just -- test end-to-end the serialisation and loading back workflow; it -- also tests the Loader.mergeData and the actual -- Cluster.iterateAlloc (for well-behaving w.r.t. instance -- allocations, not for the business logic). As such, it's a quite -- complex and slow test, and that's the reason we restrict it to -- small cluster sizes. prop_CreateSerialise :: Property prop_CreateSerialise = forAll genTags $ \ctags -> forAll (choose (1, 20)) $ \maxiter -> forAll (choose (2, 10)) $ \count -> forAll genEmptyOnlineNode $ \node -> forAll (genInstanceSmallerThanNode node `suchThat` -- We want to test with a working node, so don't generate a -- status that indicates a problem with the node. (\i -> Instance.runSt i `elem` [ StatusDown , StatusOffline , ErrorDown , ErrorUp , Running , UserDown ])) $ \inst -> let nl = makeSmallCluster node count reqnodes = Instance.requiredNodes $ Instance.diskTemplate inst opts = Alg.defaultOptions in case Cluster.genAllocNodes opts defGroupList nl reqnodes True >>= \allocn -> Cluster.iterateAlloc opts nl Container.empty (Just maxiter) inst allocn [] [] of Bad msg -> failTest $ "Failed to allocate: " ++ msg Ok (_, _, _, [], _) -> counterexample "Failed to allocate: no allocations" False Ok (_, nl', il, _, _) -> let -- makeSmallCluster created an empty cluster, that had some -- instances allocated, so we need to simulate that the hyperwisor -- now reports less fMem, otherwise Loader.checkData will detect -- missing memory after deserialization. nl1 = Container.map (\n -> n { Node.fMem = Node.recordedFreeMem n }) nl' cdata = Loader.ClusterData defGroupList nl1 il ctags Types.defIPolicy saved = Text.serializeCluster cdata in case Text.parseData saved >>= Loader.mergeData [] [] [] [] (TOD 0 0) of Bad msg -> failTest $ "Failed to load/merge: " ++ msg Ok (Loader.ClusterData gl2 nl2 il2 ctags2 cpol2) -> let (_, nl3) = Loader.updateMissing nl2 il2 0 in conjoin [ ctags2 ==? ctags , cpol2 ==? Types.defIPolicy , il2 ==? il , gl2 ==? defGroupList , nl3 ==? nl1 ] testSuite "HTools/Backend/Text" [ 'prop_Load_Instance , 'prop_Load_InstanceFail , 'prop_InstanceLSIdempotent , 'prop_Load_Node , 'prop_Load_NodeFail , 'prop_Load_NodeSuccess , 'prop_NodeLSIdempotent , 'prop_ISpecIdempotent , 'prop_MultipleMinMaxISpecsIdempotent , 'prop_IPolicyIdempotent , 'prop_CreateSerialise ]
mbakke/ganeti
test/hs/Test/Ganeti/HTools/Backend/Text.hs
bsd-2-clause
13,376
0
31
4,319
2,974
1,572
1,402
241
4
{-# OPTIONS_HADDOCK prune #-} -- | -- This package is deprecated, use Doctest`s cabal integration instead. -- -- See: <https://github.com/sol/doctest-haskell#cabal-integration> module Test.Framework.Providers.DocTest (docTest) where import qualified Test.DocTest as DocTest import Test.Framework import Test.Framework.Providers.HUnit import Data.List(groupBy) import Data.Monoid noColors :: RunnerOptions noColors = mempty { ropt_color_mode = Nothing } {-# DEPRECATED docTest "Use Doctest's cabal integration instead!" #-} docTest::[FilePath] -> [String] -> IO Test docTest rootPaths options = do tests <- DocTest.getDocTests options rootPaths return $ toTestFrameworkGroup (rootPaths ++ options) tests toTestFrameworkTest :: [String] -> DocTest.DocTest -> Test toTestFrameworkTest options test = testCase testName $ DocTest.withInterpreter options $ flip DocTest.toAssertion test where testName = DocTest.firstExpression test toTestFrameworkGroup :: [String] -> [DocTest.DocTest] -> Test toTestFrameworkGroup options examples = testGroup "DocTest" $ map fileTestGroup $ groupBy w examples where w left right = DocTest.sourcePath left == DocTest.sourcePath right fileTestGroup examples = testGroup fileName $ toTestFrameworkTest options `map` examples where fileName = DocTest.sourcePath $ head $ examples
sakari/test-framework-doctest
src/Test/Framework/Providers/DocTest.hs
bsd-3-clause
1,350
0
11
197
317
170
147
23
1
{-| Provides functions to establish connections, both passively and actively, with Openflow switches. -} module Network.Data.OF13.Server ( Switch(..) , Factory , runServer , runServerOne , sendMessage , talk , talk2 , connectToSwitch ) where import Control.Concurrent import Control.Exception import Control.Monad import Data.Binary import Data.Binary.Get import qualified Data.ByteString.Lazy as L import qualified Data.ByteString as S import Network.Socket hiding (recv) import Network.Socket.ByteString (recv, sendAll) type Factory a = Switch -> IO (Maybe a -> IO ()) newtype Switch = Switch Socket -- |Listen (at the specified port) for any number of Openflow switches to connect to this given server. Uses the given -- factory to instantiate Openflow session handlers for these swithes. runServer :: Binary a => Int -> Factory a -> IO () runServer portNum mkHandler = runServer_ portNum $ \(conn, _) -> void $ forkIO $ bracket (mkHandler (Switch conn)) (\handler -> handler Nothing >> close conn) (talk conn) -- |Listen (at the specified port) for a single Openflow switch to connect to this given server (possibly repeatedly). -- Uses the given factory to instantiate Openflow session handlers for these swithes. runServerOne :: Binary a => Int -> Factory a -> IO () runServerOne portNum mkHandler = runServer_ portNum $ \(conn, _) -> void $ bracket (mkHandler (Switch conn)) (\handler -> handler Nothing >> close conn) (talk conn) runServer_ :: Int -> ((Socket, SockAddr) -> IO ()) -> IO () runServer_ portNum f = withSocketsDo $ do addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just $ show portNum) let serveraddr = head addrinfos bracket (socket (addrFamily serveraddr) Stream defaultProtocol) close (\sock -> do setSocketOption sock ReuseAddr 1 bind sock $ addrAddress serveraddr listen sock 1 forever $ accept sock >>= f ) -- |Establishes an Openflow connection to the given server and port, using the specified handler on the connection. connectToSwitch :: Binary a => String -> String -> (Switch -> Maybe a -> IO ()) -> IO () connectToSwitch hostNameOrIp port handler = do addrinfos <- getAddrInfo Nothing (Just hostNameOrIp) (Just port) let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol connect sock (addrAddress serveraddr) talk sock $ handler $ Switch sock talk :: Binary a => Socket -> (Maybe a -> IO ()) -> IO () talk = talk2 get talk2 :: Get a -> Socket -> (Maybe a -> IO ()) -> IO () talk2 getter conn handler = go $ runGetIncremental getter where go (Fail _ _ err) = error err go (Partial f) = do msg <- recv conn bATCH_SIZE if S.null msg then return () else go $ f $ Just msg go (Done unused _ ofm) = do handler $ Just ofm go $ pushChunk (runGetIncremental getter) unused bATCH_SIZE :: Int bATCH_SIZE = 1024 sendMessage :: Binary a => Switch -> [a] -> IO () sendMessage (Switch s) = mapM_ (sendMessage' s) sendMessage' :: Binary a => Socket -> a -> IO () sendMessage' sock = mapM_ (sendAll sock) . L.toChunks . encode
AndreasVoellmy/openflow
src/Network/Data/OF13/Server.hs
bsd-3-clause
3,323
0
15
797
1,040
524
516
78
4
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[PrelNames]{Definitions of prelude modules and names} Nota Bene: all Names defined in here should come from the base package - ModuleNames for prelude modules, e.g. pREL_BASE_Name :: ModuleName - Modules for prelude modules e.g. pREL_Base :: Module - Uniques for Ids, DataCons, TyCons and Classes that the compiler "knows about" in some way e.g. intTyConKey :: Unique minusClassOpKey :: Unique - Names for Ids, DataCons, TyCons and Classes that the compiler "knows about" in some way e.g. intTyConName :: Name minusName :: Name One of these Names contains (a) the module and occurrence name of the thing (b) its Unique The may way the compiler "knows about" one of these things is where the type checker or desugarer needs to look it up. For example, when desugaring list comprehensions the desugarer needs to conjure up 'foldr'. It does this by looking up foldrName in the environment. - RdrNames for Ids, DataCons etc that the compiler may emit into generated code (e.g. for deriving). It's not necessary to know the uniques for these guys, only their names Note [Known-key names] ~~~~~~~~~~~~~~~~~~~~~~ It is *very* important that the compiler gives wired-in things and things with "known-key" names the correct Uniques wherever they occur. We have to be careful about this in exactly two places: 1. When we parse some source code, renaming the AST better yield an AST whose Names have the correct uniques 2. When we read an interface file, the read-in gubbins better have the right uniques This is accomplished through a combination of mechanisms: 1. When parsing source code, the RdrName-decorated AST has some RdrNames which are Exact. These are wired-in RdrNames where the we could directly tell from the parsed syntax what Name to use. For example, when we parse a [] in a type we can just insert an Exact RdrName Name with the listTyConKey. Currently, I believe this is just an optimisation: it would be equally valid to just output Orig RdrNames that correctly record the module etc we expect the final Name to come from. However, were we to eliminate isBuiltInOcc_maybe it would become essential (see point 3). 2. The knownKeyNames (which consist of the basicKnownKeyNames from the module, and those names reachable via the wired-in stuff from TysWiredIn) are used to initialise the "OrigNameCache" in IfaceEnv. This initialization ensures that when the type checker or renamer (both of which use IfaceEnv) look up an original name (i.e. a pair of a Module and an OccName) for a known-key name they get the correct Unique. This is the most important mechanism for ensuring that known-key stuff gets the right Unique, and is why it is so important to place your known-key names in the appropriate lists. 3. For "infinite families" of known-key names (i.e. tuples), we have to be extra careful. Because there are an infinite number of these things, we cannot add them to the list of known-key names used to initialise the OrigNameCache. Instead, we have to rely on never having to look them up in that cache. This is accomplished through a variety of mechanisms: a) The parser recognises them specially and generates an Exact Name (hence not looked up in the orig-name cache) b) The known infinite families of names are specially serialised by BinIface.putName, with that special treatment detected when we read back to ensure that we get back to the correct uniques. Most of the infinite families cannot occur in source code, so mechanisms (a,b) sufficies to ensure that they always have the right Unique. In particular, implicit param TyCon names, constraint tuples and Any TyCons cannot be mentioned by the user. c) IfaceEnv.lookupOrigNameCache uses isBuiltInOcc_maybe to map built-in syntax directly onto the corresponding name, rather than trying to find it in the original-name cache. See also Note [Built-in syntax and the OrigNameCache] -} {-# LANGUAGE CPP #-} module PrelNames ( Unique, Uniquable(..), hasKey, -- Re-exported for convenience ----------------------------------------------------------- module PrelNames, -- A huge bunch of (a) Names, e.g. intTyConName -- (b) Uniques e.g. intTyConKey -- (c) Groups of classes and types -- (d) miscellaneous things -- So many that we export them all ) where #include "HsVersions.h" import Module import OccName import RdrName import Unique import Name import SrcLoc import FastString import Config ( cIntegerLibraryType, IntegerLibrary(..) ) import Panic ( panic ) {- ************************************************************************ * * allNameStrings * * ************************************************************************ -} allNameStrings :: [String] -- Infinite list of a,b,c...z, aa, ab, ac, ... etc allNameStrings = [ c:cs | cs <- "" : allNameStrings, c <- ['a'..'z'] ] {- ************************************************************************ * * \subsection{Local Names} * * ************************************************************************ This *local* name is used by the interactive stuff -} itName :: Unique -> SrcSpan -> Name itName uniq loc = mkInternalName uniq (mkOccNameFS varName (fsLit "it")) loc -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly -- during compiler debugging. mkUnboundName :: OccName -> Name mkUnboundName occ = mkInternalName unboundKey occ noSrcSpan isUnboundName :: Name -> Bool isUnboundName name = name `hasKey` unboundKey {- ************************************************************************ * * \subsection{Known key Names} * * ************************************************************************ This section tells what the compiler knows about the association of names with uniques. These ones are the *non* wired-in ones. The wired in ones are defined in TysWiredIn etc. -} basicKnownKeyNames :: [Name] basicKnownKeyNames = genericTyConNames ++ [ -- Classes. *Must* include: -- classes that are grabbed by key (e.g., eqClassKey) -- classes in "Class.standardClassKeys" (quite a few) eqClassName, -- mentioned, derivable ordClassName, -- derivable boundedClassName, -- derivable numClassName, -- mentioned, numeric enumClassName, -- derivable monadClassName, functorClassName, realClassName, -- numeric integralClassName, -- numeric fractionalClassName, -- numeric floatingClassName, -- numeric realFracClassName, -- numeric realFloatClassName, -- numeric dataClassName, isStringClassName, applicativeClassName, alternativeClassName, foldableClassName, traversableClassName, semigroupClassName, sappendName, monoidClassName, memptyName, mappendName, mconcatName, -- The IO type -- See Note [TyConRepNames for non-wired-in TyCons] ioTyConName, ioDataConName, runMainIOName, -- Type representation types trModuleTyConName, trModuleDataConName, trNameTyConName, trNameSDataConName, trNameDDataConName, trTyConTyConName, trTyConDataConName, -- Typeable typeableClassName, typeRepTyConName, typeRepIdName, mkPolyTyConAppName, mkAppTyName, typeSymbolTypeRepName, typeNatTypeRepName, trGhcPrimModuleName, -- Dynamic toDynName, -- Numeric stuff negateName, minusName, geName, eqName, -- Conversion functions rationalTyConName, ratioTyConName, ratioDataConName, fromRationalName, fromIntegerName, toIntegerName, toRationalName, fromIntegralName, realToFracName, -- String stuff fromStringName, -- Enum stuff enumFromName, enumFromThenName, enumFromThenToName, enumFromToName, -- Applicative stuff pureAName, apAName, thenAName, -- Monad stuff thenIOName, bindIOName, returnIOName, failIOName, bindMName, thenMName, returnMName, fmapName, joinMName, -- MonadFail monadFailClassName, failMName, failMName_preMFP, -- MonadFix monadFixClassName, mfixName, -- Arrow stuff arrAName, composeAName, firstAName, appAName, choiceAName, loopAName, -- Ix stuff ixClassName, -- Show stuff showClassName, -- Read stuff readClassName, -- Stable pointers newStablePtrName, -- GHC Extensions groupWithName, -- Strings and lists unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name, -- Overloaded lists isListClassName, fromListName, fromListNName, toListName, -- List operations concatName, filterName, mapName, zipName, foldrName, buildName, augmentName, appendName, -- FFI primitive types that are not wired-in. stablePtrTyConName, ptrTyConName, funPtrTyConName, int8TyConName, int16TyConName, int32TyConName, int64TyConName, word16TyConName, word32TyConName, word64TyConName, -- Others otherwiseIdName, inlineIdName, eqStringName, assertName, breakpointName, breakpointCondName, breakpointAutoName, opaqueTyConName, assertErrorName, printName, fstName, sndName, -- Integer integerTyConName, mkIntegerName, integerToWord64Name, integerToInt64Name, word64ToIntegerName, int64ToIntegerName, plusIntegerName, timesIntegerName, smallIntegerName, wordToIntegerName, integerToWordName, integerToIntName, minusIntegerName, negateIntegerName, eqIntegerPrimName, neqIntegerPrimName, absIntegerName, signumIntegerName, leIntegerPrimName, gtIntegerPrimName, ltIntegerPrimName, geIntegerPrimName, compareIntegerName, quotRemIntegerName, divModIntegerName, quotIntegerName, remIntegerName, divIntegerName, modIntegerName, floatFromIntegerName, doubleFromIntegerName, encodeFloatIntegerName, encodeDoubleIntegerName, decodeDoubleIntegerName, gcdIntegerName, lcmIntegerName, andIntegerName, orIntegerName, xorIntegerName, complementIntegerName, shiftLIntegerName, shiftRIntegerName, bitIntegerName, -- Float/Double rationalToFloatName, rationalToDoubleName, -- Other classes randomClassName, randomGenClassName, monadPlusClassName, -- Type-level naturals knownNatClassName, knownSymbolClassName, -- Overloaded labels isLabelClassName, -- Implicit Parameters ipClassName, -- Call Stacks callStackTyConName, emptyCallStackName, pushCallStackName, -- Source Locations srcLocDataConName, -- Annotation type checking toAnnotationWrapperName -- The Ordering type , orderingTyConName , ltDataConName, eqDataConName, gtDataConName -- The SPEC type for SpecConstr , specTyConName -- The Either type , eitherTyConName, leftDataConName, rightDataConName -- Plugins , pluginTyConName , frontendPluginTyConName -- Generics , genClassName, gen1ClassName , datatypeClassName, constructorClassName, selectorClassName -- Monad comprehensions , guardMName , liftMName , mzipName -- GHCi Sandbox , ghciIoClassName, ghciStepIoMName -- StaticPtr , staticPtrTyConName , staticPtrDataConName, staticPtrInfoDataConName , fromStaticPtrName -- Fingerprint , fingerprintDataConName -- Custom type errors , errorMessageTypeErrorFamName , typeErrorTextDataConName , typeErrorAppendDataConName , typeErrorVAppendDataConName , typeErrorShowTypeDataConName -- homogeneous equality , eqTyConName ] ++ case cIntegerLibraryType of IntegerGMP -> [integerSDataConName] IntegerSimple -> [] genericTyConNames :: [Name] genericTyConNames = [ v1TyConName, u1TyConName, par1TyConName, rec1TyConName, k1TyConName, m1TyConName, sumTyConName, prodTyConName, compTyConName, rTyConName, dTyConName, cTyConName, sTyConName, rec0TyConName, d1TyConName, c1TyConName, s1TyConName, noSelTyConName, repTyConName, rep1TyConName, uRecTyConName, uAddrTyConName, uCharTyConName, uDoubleTyConName, uFloatTyConName, uIntTyConName, uWordTyConName, prefixIDataConName, infixIDataConName, leftAssociativeDataConName, rightAssociativeDataConName, notAssociativeDataConName, sourceUnpackDataConName, sourceNoUnpackDataConName, noSourceUnpackednessDataConName, sourceLazyDataConName, sourceStrictDataConName, noSourceStrictnessDataConName, decidedLazyDataConName, decidedStrictDataConName, decidedUnpackDataConName, metaDataDataConName, metaConsDataConName, metaSelDataConName ] {- ************************************************************************ * * \subsection{Module names} * * ************************************************************************ --MetaHaskell Extension Add a new module here -} pRELUDE :: Module pRELUDE = mkBaseModule_ pRELUDE_NAME gHC_PRIM, gHC_TYPES, gHC_GENERICS, gHC_MAGIC, gHC_CLASSES, gHC_BASE, gHC_ENUM, gHC_GHCI, gHC_CSTRING, gHC_SHOW, gHC_READ, gHC_NUM, gHC_INTEGER_TYPE, gHC_LIST, gHC_TUPLE, dATA_TUPLE, dATA_EITHER, dATA_STRING, dATA_FOLDABLE, dATA_TRAVERSABLE, dATA_MONOID, dATA_SEMIGROUP, gHC_CONC, gHC_IO, gHC_IO_Exception, gHC_ST, gHC_ARR, gHC_STABLE, gHC_PTR, gHC_ERR, gHC_REAL, gHC_FLOAT, gHC_TOP_HANDLER, sYSTEM_IO, dYNAMIC, tYPEABLE, tYPEABLE_INTERNAL, gENERICS, rEAD_PREC, lEX, gHC_INT, gHC_WORD, mONAD, mONAD_FIX, mONAD_ZIP, mONAD_FAIL, aRROW, cONTROL_APPLICATIVE, gHC_DESUGAR, rANDOM, gHC_EXTS, cONTROL_EXCEPTION_BASE, gHC_TYPELITS, dATA_TYPE_EQUALITY, dATA_COERCE :: Module gHC_PRIM = mkPrimModule (fsLit "GHC.Prim") -- Primitive types and values gHC_TYPES = mkPrimModule (fsLit "GHC.Types") gHC_MAGIC = mkPrimModule (fsLit "GHC.Magic") gHC_CSTRING = mkPrimModule (fsLit "GHC.CString") gHC_CLASSES = mkPrimModule (fsLit "GHC.Classes") gHC_BASE = mkBaseModule (fsLit "GHC.Base") gHC_ENUM = mkBaseModule (fsLit "GHC.Enum") gHC_GHCI = mkBaseModule (fsLit "GHC.GHCi") gHC_SHOW = mkBaseModule (fsLit "GHC.Show") gHC_READ = mkBaseModule (fsLit "GHC.Read") gHC_NUM = mkBaseModule (fsLit "GHC.Num") gHC_INTEGER_TYPE= mkIntegerModule (fsLit "GHC.Integer.Type") gHC_LIST = mkBaseModule (fsLit "GHC.List") gHC_TUPLE = mkPrimModule (fsLit "GHC.Tuple") dATA_TUPLE = mkBaseModule (fsLit "Data.Tuple") dATA_EITHER = mkBaseModule (fsLit "Data.Either") dATA_STRING = mkBaseModule (fsLit "Data.String") dATA_FOLDABLE = mkBaseModule (fsLit "Data.Foldable") dATA_TRAVERSABLE= mkBaseModule (fsLit "Data.Traversable") dATA_SEMIGROUP = mkBaseModule (fsLit "Data.Semigroup") dATA_MONOID = mkBaseModule (fsLit "Data.Monoid") gHC_CONC = mkBaseModule (fsLit "GHC.Conc") gHC_IO = mkBaseModule (fsLit "GHC.IO") gHC_IO_Exception = mkBaseModule (fsLit "GHC.IO.Exception") gHC_ST = mkBaseModule (fsLit "GHC.ST") gHC_ARR = mkBaseModule (fsLit "GHC.Arr") gHC_STABLE = mkBaseModule (fsLit "GHC.Stable") gHC_PTR = mkBaseModule (fsLit "GHC.Ptr") gHC_ERR = mkBaseModule (fsLit "GHC.Err") gHC_REAL = mkBaseModule (fsLit "GHC.Real") gHC_FLOAT = mkBaseModule (fsLit "GHC.Float") gHC_TOP_HANDLER = mkBaseModule (fsLit "GHC.TopHandler") sYSTEM_IO = mkBaseModule (fsLit "System.IO") dYNAMIC = mkBaseModule (fsLit "Data.Dynamic") tYPEABLE = mkBaseModule (fsLit "Data.Typeable") tYPEABLE_INTERNAL = mkBaseModule (fsLit "Data.Typeable.Internal") gENERICS = mkBaseModule (fsLit "Data.Data") rEAD_PREC = mkBaseModule (fsLit "Text.ParserCombinators.ReadPrec") lEX = mkBaseModule (fsLit "Text.Read.Lex") gHC_INT = mkBaseModule (fsLit "GHC.Int") gHC_WORD = mkBaseModule (fsLit "GHC.Word") mONAD = mkBaseModule (fsLit "Control.Monad") mONAD_FIX = mkBaseModule (fsLit "Control.Monad.Fix") mONAD_ZIP = mkBaseModule (fsLit "Control.Monad.Zip") mONAD_FAIL = mkBaseModule (fsLit "Control.Monad.Fail") aRROW = mkBaseModule (fsLit "Control.Arrow") cONTROL_APPLICATIVE = mkBaseModule (fsLit "Control.Applicative") gHC_DESUGAR = mkBaseModule (fsLit "GHC.Desugar") rANDOM = mkBaseModule (fsLit "System.Random") gHC_EXTS = mkBaseModule (fsLit "GHC.Exts") cONTROL_EXCEPTION_BASE = mkBaseModule (fsLit "Control.Exception.Base") gHC_GENERICS = mkBaseModule (fsLit "GHC.Generics") gHC_TYPELITS = mkBaseModule (fsLit "GHC.TypeLits") dATA_TYPE_EQUALITY = mkBaseModule (fsLit "Data.Type.Equality") dATA_COERCE = mkBaseModule (fsLit "Data.Coerce") gHC_PARR' :: Module gHC_PARR' = mkBaseModule (fsLit "GHC.PArr") gHC_SRCLOC :: Module gHC_SRCLOC = mkBaseModule (fsLit "GHC.SrcLoc") gHC_STACK, gHC_STACK_TYPES :: Module gHC_STACK = mkBaseModule (fsLit "GHC.Stack") gHC_STACK_TYPES = mkBaseModule (fsLit "GHC.Stack.Types") gHC_STATICPTR :: Module gHC_STATICPTR = mkBaseModule (fsLit "GHC.StaticPtr") gHC_FINGERPRINT_TYPE :: Module gHC_FINGERPRINT_TYPE = mkBaseModule (fsLit "GHC.Fingerprint.Type") gHC_OVER_LABELS :: Module gHC_OVER_LABELS = mkBaseModule (fsLit "GHC.OverloadedLabels") mAIN, rOOT_MAIN :: Module mAIN = mkMainModule_ mAIN_NAME rOOT_MAIN = mkMainModule (fsLit ":Main") -- Root module for initialisation mkInteractiveModule :: Int -> Module -- (mkInteractiveMoudule 9) makes module 'interactive:M9' mkInteractiveModule n = mkModule interactiveUnitId (mkModuleName ("Ghci" ++ show n)) pRELUDE_NAME, mAIN_NAME :: ModuleName pRELUDE_NAME = mkModuleNameFS (fsLit "Prelude") mAIN_NAME = mkModuleNameFS (fsLit "Main") dATA_ARRAY_PARALLEL_NAME, dATA_ARRAY_PARALLEL_PRIM_NAME :: ModuleName dATA_ARRAY_PARALLEL_NAME = mkModuleNameFS (fsLit "Data.Array.Parallel") dATA_ARRAY_PARALLEL_PRIM_NAME = mkModuleNameFS (fsLit "Data.Array.Parallel.Prim") mkPrimModule :: FastString -> Module mkPrimModule m = mkModule primUnitId (mkModuleNameFS m) mkIntegerModule :: FastString -> Module mkIntegerModule m = mkModule integerUnitId (mkModuleNameFS m) mkBaseModule :: FastString -> Module mkBaseModule m = mkModule baseUnitId (mkModuleNameFS m) mkBaseModule_ :: ModuleName -> Module mkBaseModule_ m = mkModule baseUnitId m mkThisGhcModule :: FastString -> Module mkThisGhcModule m = mkModule thisGhcUnitId (mkModuleNameFS m) mkThisGhcModule_ :: ModuleName -> Module mkThisGhcModule_ m = mkModule thisGhcUnitId m mkMainModule :: FastString -> Module mkMainModule m = mkModule mainUnitId (mkModuleNameFS m) mkMainModule_ :: ModuleName -> Module mkMainModule_ m = mkModule mainUnitId m {- ************************************************************************ * * RdrNames * * ************************************************************************ -} main_RDR_Unqual :: RdrName main_RDR_Unqual = mkUnqual varName (fsLit "main") -- We definitely don't want an Orig RdrName, because -- main might, in principle, be imported into module Main forall_tv_RDR, dot_tv_RDR :: RdrName forall_tv_RDR = mkUnqual tvName (fsLit "forall") dot_tv_RDR = mkUnqual tvName (fsLit ".") eq_RDR, ge_RDR, ne_RDR, le_RDR, lt_RDR, gt_RDR, compare_RDR, ltTag_RDR, eqTag_RDR, gtTag_RDR :: RdrName eq_RDR = nameRdrName eqName ge_RDR = nameRdrName geName ne_RDR = varQual_RDR gHC_CLASSES (fsLit "/=") le_RDR = varQual_RDR gHC_CLASSES (fsLit "<=") lt_RDR = varQual_RDR gHC_CLASSES (fsLit "<") gt_RDR = varQual_RDR gHC_CLASSES (fsLit ">") compare_RDR = varQual_RDR gHC_CLASSES (fsLit "compare") ltTag_RDR = dataQual_RDR gHC_TYPES (fsLit "LT") eqTag_RDR = dataQual_RDR gHC_TYPES (fsLit "EQ") gtTag_RDR = dataQual_RDR gHC_TYPES (fsLit "GT") eqClass_RDR, numClass_RDR, ordClass_RDR, enumClass_RDR, monadClass_RDR :: RdrName eqClass_RDR = nameRdrName eqClassName numClass_RDR = nameRdrName numClassName ordClass_RDR = nameRdrName ordClassName enumClass_RDR = nameRdrName enumClassName monadClass_RDR = nameRdrName monadClassName map_RDR, append_RDR :: RdrName map_RDR = varQual_RDR gHC_BASE (fsLit "map") append_RDR = varQual_RDR gHC_BASE (fsLit "++") foldr_RDR, build_RDR, returnM_RDR, bindM_RDR, failM_RDR_preMFP, failM_RDR:: RdrName foldr_RDR = nameRdrName foldrName build_RDR = nameRdrName buildName returnM_RDR = nameRdrName returnMName bindM_RDR = nameRdrName bindMName failM_RDR_preMFP = nameRdrName failMName_preMFP failM_RDR = nameRdrName failMName left_RDR, right_RDR :: RdrName left_RDR = nameRdrName leftDataConName right_RDR = nameRdrName rightDataConName fromEnum_RDR, toEnum_RDR :: RdrName fromEnum_RDR = varQual_RDR gHC_ENUM (fsLit "fromEnum") toEnum_RDR = varQual_RDR gHC_ENUM (fsLit "toEnum") enumFrom_RDR, enumFromTo_RDR, enumFromThen_RDR, enumFromThenTo_RDR :: RdrName enumFrom_RDR = nameRdrName enumFromName enumFromTo_RDR = nameRdrName enumFromToName enumFromThen_RDR = nameRdrName enumFromThenName enumFromThenTo_RDR = nameRdrName enumFromThenToName ratioDataCon_RDR, plusInteger_RDR, timesInteger_RDR :: RdrName ratioDataCon_RDR = nameRdrName ratioDataConName plusInteger_RDR = nameRdrName plusIntegerName timesInteger_RDR = nameRdrName timesIntegerName ioDataCon_RDR :: RdrName ioDataCon_RDR = nameRdrName ioDataConName eqString_RDR, unpackCString_RDR, unpackCStringFoldr_RDR, unpackCStringUtf8_RDR :: RdrName eqString_RDR = nameRdrName eqStringName unpackCString_RDR = nameRdrName unpackCStringName unpackCStringFoldr_RDR = nameRdrName unpackCStringFoldrName unpackCStringUtf8_RDR = nameRdrName unpackCStringUtf8Name newStablePtr_RDR :: RdrName newStablePtr_RDR = nameRdrName newStablePtrName bindIO_RDR, returnIO_RDR :: RdrName bindIO_RDR = nameRdrName bindIOName returnIO_RDR = nameRdrName returnIOName fromInteger_RDR, fromRational_RDR, minus_RDR, times_RDR, plus_RDR :: RdrName fromInteger_RDR = nameRdrName fromIntegerName fromRational_RDR = nameRdrName fromRationalName minus_RDR = nameRdrName minusName times_RDR = varQual_RDR gHC_NUM (fsLit "*") plus_RDR = varQual_RDR gHC_NUM (fsLit "+") toInteger_RDR, toRational_RDR, fromIntegral_RDR :: RdrName toInteger_RDR = nameRdrName toIntegerName toRational_RDR = nameRdrName toRationalName fromIntegral_RDR = nameRdrName fromIntegralName stringTy_RDR, fromString_RDR :: RdrName stringTy_RDR = tcQual_RDR gHC_BASE (fsLit "String") fromString_RDR = nameRdrName fromStringName fromList_RDR, fromListN_RDR, toList_RDR :: RdrName fromList_RDR = nameRdrName fromListName fromListN_RDR = nameRdrName fromListNName toList_RDR = nameRdrName toListName compose_RDR :: RdrName compose_RDR = varQual_RDR gHC_BASE (fsLit ".") not_RDR, getTag_RDR, succ_RDR, pred_RDR, minBound_RDR, maxBound_RDR, and_RDR, range_RDR, inRange_RDR, index_RDR, unsafeIndex_RDR, unsafeRangeSize_RDR :: RdrName and_RDR = varQual_RDR gHC_CLASSES (fsLit "&&") not_RDR = varQual_RDR gHC_CLASSES (fsLit "not") getTag_RDR = varQual_RDR gHC_BASE (fsLit "getTag") succ_RDR = varQual_RDR gHC_ENUM (fsLit "succ") pred_RDR = varQual_RDR gHC_ENUM (fsLit "pred") minBound_RDR = varQual_RDR gHC_ENUM (fsLit "minBound") maxBound_RDR = varQual_RDR gHC_ENUM (fsLit "maxBound") range_RDR = varQual_RDR gHC_ARR (fsLit "range") inRange_RDR = varQual_RDR gHC_ARR (fsLit "inRange") index_RDR = varQual_RDR gHC_ARR (fsLit "index") unsafeIndex_RDR = varQual_RDR gHC_ARR (fsLit "unsafeIndex") unsafeRangeSize_RDR = varQual_RDR gHC_ARR (fsLit "unsafeRangeSize") readList_RDR, readListDefault_RDR, readListPrec_RDR, readListPrecDefault_RDR, readPrec_RDR, parens_RDR, choose_RDR, lexP_RDR, expectP_RDR :: RdrName readList_RDR = varQual_RDR gHC_READ (fsLit "readList") readListDefault_RDR = varQual_RDR gHC_READ (fsLit "readListDefault") readListPrec_RDR = varQual_RDR gHC_READ (fsLit "readListPrec") readListPrecDefault_RDR = varQual_RDR gHC_READ (fsLit "readListPrecDefault") readPrec_RDR = varQual_RDR gHC_READ (fsLit "readPrec") parens_RDR = varQual_RDR gHC_READ (fsLit "parens") choose_RDR = varQual_RDR gHC_READ (fsLit "choose") lexP_RDR = varQual_RDR gHC_READ (fsLit "lexP") expectP_RDR = varQual_RDR gHC_READ (fsLit "expectP") punc_RDR, ident_RDR, symbol_RDR :: RdrName punc_RDR = dataQual_RDR lEX (fsLit "Punc") ident_RDR = dataQual_RDR lEX (fsLit "Ident") symbol_RDR = dataQual_RDR lEX (fsLit "Symbol") step_RDR, alt_RDR, reset_RDR, prec_RDR, pfail_RDR :: RdrName step_RDR = varQual_RDR rEAD_PREC (fsLit "step") alt_RDR = varQual_RDR rEAD_PREC (fsLit "+++") reset_RDR = varQual_RDR rEAD_PREC (fsLit "reset") prec_RDR = varQual_RDR rEAD_PREC (fsLit "prec") pfail_RDR = varQual_RDR rEAD_PREC (fsLit "pfail") showList_RDR, showList___RDR, showsPrec_RDR, shows_RDR, showString_RDR, showSpace_RDR, showParen_RDR :: RdrName showList_RDR = varQual_RDR gHC_SHOW (fsLit "showList") showList___RDR = varQual_RDR gHC_SHOW (fsLit "showList__") showsPrec_RDR = varQual_RDR gHC_SHOW (fsLit "showsPrec") shows_RDR = varQual_RDR gHC_SHOW (fsLit "shows") showString_RDR = varQual_RDR gHC_SHOW (fsLit "showString") showSpace_RDR = varQual_RDR gHC_SHOW (fsLit "showSpace") showParen_RDR = varQual_RDR gHC_SHOW (fsLit "showParen") undefined_RDR :: RdrName undefined_RDR = varQual_RDR gHC_ERR (fsLit "undefined") error_RDR :: RdrName error_RDR = varQual_RDR gHC_ERR (fsLit "error") -- Generics (constructors and functions) u1DataCon_RDR, par1DataCon_RDR, rec1DataCon_RDR, k1DataCon_RDR, m1DataCon_RDR, l1DataCon_RDR, r1DataCon_RDR, prodDataCon_RDR, comp1DataCon_RDR, unPar1_RDR, unRec1_RDR, unK1_RDR, unComp1_RDR, from_RDR, from1_RDR, to_RDR, to1_RDR, datatypeName_RDR, moduleName_RDR, packageName_RDR, isNewtypeName_RDR, conName_RDR, conFixity_RDR, conIsRecord_RDR, selName_RDR, prefixDataCon_RDR, infixDataCon_RDR, leftAssocDataCon_RDR, rightAssocDataCon_RDR, notAssocDataCon_RDR, uAddrDataCon_RDR, uCharDataCon_RDR, uDoubleDataCon_RDR, uFloatDataCon_RDR, uIntDataCon_RDR, uWordDataCon_RDR, uAddrHash_RDR, uCharHash_RDR, uDoubleHash_RDR, uFloatHash_RDR, uIntHash_RDR, uWordHash_RDR :: RdrName u1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "U1") par1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Par1") rec1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Rec1") k1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "K1") m1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "M1") l1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "L1") r1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "R1") prodDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit ":*:") comp1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Comp1") unPar1_RDR = varQual_RDR gHC_GENERICS (fsLit "unPar1") unRec1_RDR = varQual_RDR gHC_GENERICS (fsLit "unRec1") unK1_RDR = varQual_RDR gHC_GENERICS (fsLit "unK1") unComp1_RDR = varQual_RDR gHC_GENERICS (fsLit "unComp1") from_RDR = varQual_RDR gHC_GENERICS (fsLit "from") from1_RDR = varQual_RDR gHC_GENERICS (fsLit "from1") to_RDR = varQual_RDR gHC_GENERICS (fsLit "to") to1_RDR = varQual_RDR gHC_GENERICS (fsLit "to1") datatypeName_RDR = varQual_RDR gHC_GENERICS (fsLit "datatypeName") moduleName_RDR = varQual_RDR gHC_GENERICS (fsLit "moduleName") packageName_RDR = varQual_RDR gHC_GENERICS (fsLit "packageName") isNewtypeName_RDR = varQual_RDR gHC_GENERICS (fsLit "isNewtype") selName_RDR = varQual_RDR gHC_GENERICS (fsLit "selName") conName_RDR = varQual_RDR gHC_GENERICS (fsLit "conName") conFixity_RDR = varQual_RDR gHC_GENERICS (fsLit "conFixity") conIsRecord_RDR = varQual_RDR gHC_GENERICS (fsLit "conIsRecord") prefixDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Prefix") infixDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Infix") leftAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "LeftAssociative") rightAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "RightAssociative") notAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "NotAssociative") uAddrDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UAddr") uCharDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UChar") uDoubleDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UDouble") uFloatDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UFloat") uIntDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UInt") uWordDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "UWord") uAddrHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uAddr#") uCharHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uChar#") uDoubleHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uDouble#") uFloatHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uFloat#") uIntHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uInt#") uWordHash_RDR = varQual_RDR gHC_GENERICS (fsLit "uWord#") fmap_RDR, pure_RDR, ap_RDR, foldable_foldr_RDR, foldMap_RDR, traverse_RDR, mempty_RDR, mappend_RDR :: RdrName fmap_RDR = varQual_RDR gHC_BASE (fsLit "fmap") pure_RDR = nameRdrName pureAName ap_RDR = nameRdrName apAName foldable_foldr_RDR = varQual_RDR dATA_FOLDABLE (fsLit "foldr") foldMap_RDR = varQual_RDR dATA_FOLDABLE (fsLit "foldMap") traverse_RDR = varQual_RDR dATA_TRAVERSABLE (fsLit "traverse") mempty_RDR = varQual_RDR gHC_BASE (fsLit "mempty") mappend_RDR = varQual_RDR gHC_BASE (fsLit "mappend") eqTyCon_RDR :: RdrName eqTyCon_RDR = tcQual_RDR dATA_TYPE_EQUALITY (fsLit "~") ---------------------- varQual_RDR, tcQual_RDR, clsQual_RDR, dataQual_RDR :: Module -> FastString -> RdrName varQual_RDR mod str = mkOrig mod (mkOccNameFS varName str) tcQual_RDR mod str = mkOrig mod (mkOccNameFS tcName str) clsQual_RDR mod str = mkOrig mod (mkOccNameFS clsName str) dataQual_RDR mod str = mkOrig mod (mkOccNameFS dataName str) {- ************************************************************************ * * \subsection{Known-key names} * * ************************************************************************ Many of these Names are not really "built in", but some parts of the compiler (notably the deriving mechanism) need to mention their names, and it's convenient to write them all down in one place. --MetaHaskell Extension add the constrs and the lower case case -- guys as well (perhaps) e.g. see trueDataConName below -} wildCardName :: Name wildCardName = mkSystemVarName wildCardKey (fsLit "wild") runMainIOName :: Name runMainIOName = varQual gHC_TOP_HANDLER (fsLit "runMainIO") runMainKey orderingTyConName, ltDataConName, eqDataConName, gtDataConName :: Name orderingTyConName = tcQual gHC_TYPES (fsLit "Ordering") orderingTyConKey ltDataConName = dcQual gHC_TYPES (fsLit "LT") ltDataConKey eqDataConName = dcQual gHC_TYPES (fsLit "EQ") eqDataConKey gtDataConName = dcQual gHC_TYPES (fsLit "GT") gtDataConKey specTyConName :: Name specTyConName = tcQual gHC_TYPES (fsLit "SPEC") specTyConKey eitherTyConName, leftDataConName, rightDataConName :: Name eitherTyConName = tcQual dATA_EITHER (fsLit "Either") eitherTyConKey leftDataConName = dcQual dATA_EITHER (fsLit "Left") leftDataConKey rightDataConName = dcQual dATA_EITHER (fsLit "Right") rightDataConKey -- Generics (types) v1TyConName, u1TyConName, par1TyConName, rec1TyConName, k1TyConName, m1TyConName, sumTyConName, prodTyConName, compTyConName, rTyConName, dTyConName, cTyConName, sTyConName, rec0TyConName, d1TyConName, c1TyConName, s1TyConName, noSelTyConName, repTyConName, rep1TyConName, uRecTyConName, uAddrTyConName, uCharTyConName, uDoubleTyConName, uFloatTyConName, uIntTyConName, uWordTyConName, prefixIDataConName, infixIDataConName, leftAssociativeDataConName, rightAssociativeDataConName, notAssociativeDataConName, sourceUnpackDataConName, sourceNoUnpackDataConName, noSourceUnpackednessDataConName, sourceLazyDataConName, sourceStrictDataConName, noSourceStrictnessDataConName, decidedLazyDataConName, decidedStrictDataConName, decidedUnpackDataConName, metaDataDataConName, metaConsDataConName, metaSelDataConName :: Name v1TyConName = tcQual gHC_GENERICS (fsLit "V1") v1TyConKey u1TyConName = tcQual gHC_GENERICS (fsLit "U1") u1TyConKey par1TyConName = tcQual gHC_GENERICS (fsLit "Par1") par1TyConKey rec1TyConName = tcQual gHC_GENERICS (fsLit "Rec1") rec1TyConKey k1TyConName = tcQual gHC_GENERICS (fsLit "K1") k1TyConKey m1TyConName = tcQual gHC_GENERICS (fsLit "M1") m1TyConKey sumTyConName = tcQual gHC_GENERICS (fsLit ":+:") sumTyConKey prodTyConName = tcQual gHC_GENERICS (fsLit ":*:") prodTyConKey compTyConName = tcQual gHC_GENERICS (fsLit ":.:") compTyConKey rTyConName = tcQual gHC_GENERICS (fsLit "R") rTyConKey dTyConName = tcQual gHC_GENERICS (fsLit "D") dTyConKey cTyConName = tcQual gHC_GENERICS (fsLit "C") cTyConKey sTyConName = tcQual gHC_GENERICS (fsLit "S") sTyConKey rec0TyConName = tcQual gHC_GENERICS (fsLit "Rec0") rec0TyConKey d1TyConName = tcQual gHC_GENERICS (fsLit "D1") d1TyConKey c1TyConName = tcQual gHC_GENERICS (fsLit "C1") c1TyConKey s1TyConName = tcQual gHC_GENERICS (fsLit "S1") s1TyConKey noSelTyConName = tcQual gHC_GENERICS (fsLit "NoSelector") noSelTyConKey repTyConName = tcQual gHC_GENERICS (fsLit "Rep") repTyConKey rep1TyConName = tcQual gHC_GENERICS (fsLit "Rep1") rep1TyConKey uRecTyConName = tcQual gHC_GENERICS (fsLit "URec") uRecTyConKey uAddrTyConName = tcQual gHC_GENERICS (fsLit "UAddr") uAddrTyConKey uCharTyConName = tcQual gHC_GENERICS (fsLit "UChar") uCharTyConKey uDoubleTyConName = tcQual gHC_GENERICS (fsLit "UDouble") uDoubleTyConKey uFloatTyConName = tcQual gHC_GENERICS (fsLit "UFloat") uFloatTyConKey uIntTyConName = tcQual gHC_GENERICS (fsLit "UInt") uIntTyConKey uWordTyConName = tcQual gHC_GENERICS (fsLit "UWord") uWordTyConKey prefixIDataConName = dcQual gHC_GENERICS (fsLit "PrefixI") prefixIDataConKey infixIDataConName = dcQual gHC_GENERICS (fsLit "InfixI") infixIDataConKey leftAssociativeDataConName = dcQual gHC_GENERICS (fsLit "LeftAssociative") leftAssociativeDataConKey rightAssociativeDataConName = dcQual gHC_GENERICS (fsLit "RightAssociative") rightAssociativeDataConKey notAssociativeDataConName = dcQual gHC_GENERICS (fsLit "NotAssociative") notAssociativeDataConKey sourceUnpackDataConName = dcQual gHC_GENERICS (fsLit "SourceUnpack") sourceUnpackDataConKey sourceNoUnpackDataConName = dcQual gHC_GENERICS (fsLit "SourceNoUnpack") sourceNoUnpackDataConKey noSourceUnpackednessDataConName = dcQual gHC_GENERICS (fsLit "NoSourceUnpackedness") noSourceUnpackednessDataConKey sourceLazyDataConName = dcQual gHC_GENERICS (fsLit "SourceLazy") sourceLazyDataConKey sourceStrictDataConName = dcQual gHC_GENERICS (fsLit "SourceStrict") sourceStrictDataConKey noSourceStrictnessDataConName = dcQual gHC_GENERICS (fsLit "NoSourceStrictness") noSourceStrictnessDataConKey decidedLazyDataConName = dcQual gHC_GENERICS (fsLit "DecidedLazy") decidedLazyDataConKey decidedStrictDataConName = dcQual gHC_GENERICS (fsLit "DecidedStrict") decidedStrictDataConKey decidedUnpackDataConName = dcQual gHC_GENERICS (fsLit "DecidedUnpack") decidedUnpackDataConKey metaDataDataConName = dcQual gHC_GENERICS (fsLit "MetaData") metaDataDataConKey metaConsDataConName = dcQual gHC_GENERICS (fsLit "MetaCons") metaConsDataConKey metaSelDataConName = dcQual gHC_GENERICS (fsLit "MetaSel") metaSelDataConKey -- Base strings Strings unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name, eqStringName :: Name unpackCStringName = varQual gHC_CSTRING (fsLit "unpackCString#") unpackCStringIdKey unpackCStringFoldrName = varQual gHC_CSTRING (fsLit "unpackFoldrCString#") unpackCStringFoldrIdKey unpackCStringUtf8Name = varQual gHC_CSTRING (fsLit "unpackCStringUtf8#") unpackCStringUtf8IdKey eqStringName = varQual gHC_BASE (fsLit "eqString") eqStringIdKey -- The 'inline' function inlineIdName :: Name inlineIdName = varQual gHC_MAGIC (fsLit "inline") inlineIdKey -- Base classes (Eq, Ord, Functor) fmapName, eqClassName, eqName, ordClassName, geName, functorClassName :: Name eqClassName = clsQual gHC_CLASSES (fsLit "Eq") eqClassKey eqName = varQual gHC_CLASSES (fsLit "==") eqClassOpKey ordClassName = clsQual gHC_CLASSES (fsLit "Ord") ordClassKey geName = varQual gHC_CLASSES (fsLit ">=") geClassOpKey functorClassName = clsQual gHC_BASE (fsLit "Functor") functorClassKey fmapName = varQual gHC_BASE (fsLit "fmap") fmapClassOpKey -- Class Monad monadClassName, thenMName, bindMName, returnMName, failMName_preMFP :: Name monadClassName = clsQual gHC_BASE (fsLit "Monad") monadClassKey thenMName = varQual gHC_BASE (fsLit ">>") thenMClassOpKey bindMName = varQual gHC_BASE (fsLit ">>=") bindMClassOpKey returnMName = varQual gHC_BASE (fsLit "return") returnMClassOpKey failMName_preMFP = varQual gHC_BASE (fsLit "fail") failMClassOpKey_preMFP -- Class MonadFail monadFailClassName, failMName :: Name monadFailClassName = clsQual mONAD_FAIL (fsLit "MonadFail") monadFailClassKey failMName = varQual mONAD_FAIL (fsLit "fail") failMClassOpKey -- Class Applicative applicativeClassName, pureAName, apAName, thenAName :: Name applicativeClassName = clsQual gHC_BASE (fsLit "Applicative") applicativeClassKey apAName = varQual gHC_BASE (fsLit "<*>") apAClassOpKey pureAName = varQual gHC_BASE (fsLit "pure") pureAClassOpKey thenAName = varQual gHC_BASE (fsLit "*>") thenAClassOpKey -- Classes (Foldable, Traversable) foldableClassName, traversableClassName :: Name foldableClassName = clsQual dATA_FOLDABLE (fsLit "Foldable") foldableClassKey traversableClassName = clsQual dATA_TRAVERSABLE (fsLit "Traversable") traversableClassKey -- Classes (Semigroup, Monoid) semigroupClassName, sappendName :: Name semigroupClassName = clsQual dATA_SEMIGROUP (fsLit "Semigroup") semigroupClassKey sappendName = varQual dATA_SEMIGROUP (fsLit "<>") sappendClassOpKey monoidClassName, memptyName, mappendName, mconcatName :: Name monoidClassName = clsQual gHC_BASE (fsLit "Monoid") monoidClassKey memptyName = varQual gHC_BASE (fsLit "mempty") memptyClassOpKey mappendName = varQual gHC_BASE (fsLit "mappend") mappendClassOpKey mconcatName = varQual gHC_BASE (fsLit "mconcat") mconcatClassOpKey -- AMP additions joinMName, alternativeClassName :: Name joinMName = varQual gHC_BASE (fsLit "join") joinMIdKey alternativeClassName = clsQual mONAD (fsLit "Alternative") alternativeClassKey -- joinMIdKey, apAClassOpKey, pureAClassOpKey, thenAClassOpKey, alternativeClassKey :: Unique joinMIdKey = mkPreludeMiscIdUnique 750 apAClassOpKey = mkPreludeMiscIdUnique 751 -- <*> pureAClassOpKey = mkPreludeMiscIdUnique 752 thenAClassOpKey = mkPreludeMiscIdUnique 753 alternativeClassKey = mkPreludeMiscIdUnique 754 -- Functions for GHC extensions groupWithName :: Name groupWithName = varQual gHC_EXTS (fsLit "groupWith") groupWithIdKey -- Random PrelBase functions fromStringName, otherwiseIdName, foldrName, buildName, augmentName, mapName, appendName, assertName, breakpointName, breakpointCondName, breakpointAutoName, opaqueTyConName :: Name fromStringName = varQual dATA_STRING (fsLit "fromString") fromStringClassOpKey otherwiseIdName = varQual gHC_BASE (fsLit "otherwise") otherwiseIdKey foldrName = varQual gHC_BASE (fsLit "foldr") foldrIdKey buildName = varQual gHC_BASE (fsLit "build") buildIdKey augmentName = varQual gHC_BASE (fsLit "augment") augmentIdKey mapName = varQual gHC_BASE (fsLit "map") mapIdKey appendName = varQual gHC_BASE (fsLit "++") appendIdKey assertName = varQual gHC_BASE (fsLit "assert") assertIdKey breakpointName = varQual gHC_BASE (fsLit "breakpoint") breakpointIdKey breakpointCondName= varQual gHC_BASE (fsLit "breakpointCond") breakpointCondIdKey breakpointAutoName= varQual gHC_BASE (fsLit "breakpointAuto") breakpointAutoIdKey opaqueTyConName = tcQual gHC_BASE (fsLit "Opaque") opaqueTyConKey breakpointJumpName :: Name breakpointJumpName = mkInternalName breakpointJumpIdKey (mkOccNameFS varName (fsLit "breakpointJump")) noSrcSpan breakpointCondJumpName :: Name breakpointCondJumpName = mkInternalName breakpointCondJumpIdKey (mkOccNameFS varName (fsLit "breakpointCondJump")) noSrcSpan breakpointAutoJumpName :: Name breakpointAutoJumpName = mkInternalName breakpointAutoJumpIdKey (mkOccNameFS varName (fsLit "breakpointAutoJump")) noSrcSpan -- PrelTup fstName, sndName :: Name fstName = varQual dATA_TUPLE (fsLit "fst") fstIdKey sndName = varQual dATA_TUPLE (fsLit "snd") sndIdKey -- Module GHC.Num numClassName, fromIntegerName, minusName, negateName :: Name numClassName = clsQual gHC_NUM (fsLit "Num") numClassKey fromIntegerName = varQual gHC_NUM (fsLit "fromInteger") fromIntegerClassOpKey minusName = varQual gHC_NUM (fsLit "-") minusClassOpKey negateName = varQual gHC_NUM (fsLit "negate") negateClassOpKey integerTyConName, mkIntegerName, integerSDataConName, integerToWord64Name, integerToInt64Name, word64ToIntegerName, int64ToIntegerName, plusIntegerName, timesIntegerName, smallIntegerName, wordToIntegerName, integerToWordName, integerToIntName, minusIntegerName, negateIntegerName, eqIntegerPrimName, neqIntegerPrimName, absIntegerName, signumIntegerName, leIntegerPrimName, gtIntegerPrimName, ltIntegerPrimName, geIntegerPrimName, compareIntegerName, quotRemIntegerName, divModIntegerName, quotIntegerName, remIntegerName, divIntegerName, modIntegerName, floatFromIntegerName, doubleFromIntegerName, encodeFloatIntegerName, encodeDoubleIntegerName, decodeDoubleIntegerName, gcdIntegerName, lcmIntegerName, andIntegerName, orIntegerName, xorIntegerName, complementIntegerName, shiftLIntegerName, shiftRIntegerName, bitIntegerName :: Name integerTyConName = tcQual gHC_INTEGER_TYPE (fsLit "Integer") integerTyConKey integerSDataConName = dcQual gHC_INTEGER_TYPE (fsLit n) integerSDataConKey where n = case cIntegerLibraryType of IntegerGMP -> "S#" IntegerSimple -> panic "integerSDataConName evaluated for integer-simple" mkIntegerName = varQual gHC_INTEGER_TYPE (fsLit "mkInteger") mkIntegerIdKey integerToWord64Name = varQual gHC_INTEGER_TYPE (fsLit "integerToWord64") integerToWord64IdKey integerToInt64Name = varQual gHC_INTEGER_TYPE (fsLit "integerToInt64") integerToInt64IdKey word64ToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "word64ToInteger") word64ToIntegerIdKey int64ToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "int64ToInteger") int64ToIntegerIdKey plusIntegerName = varQual gHC_INTEGER_TYPE (fsLit "plusInteger") plusIntegerIdKey timesIntegerName = varQual gHC_INTEGER_TYPE (fsLit "timesInteger") timesIntegerIdKey smallIntegerName = varQual gHC_INTEGER_TYPE (fsLit "smallInteger") smallIntegerIdKey wordToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "wordToInteger") wordToIntegerIdKey integerToWordName = varQual gHC_INTEGER_TYPE (fsLit "integerToWord") integerToWordIdKey integerToIntName = varQual gHC_INTEGER_TYPE (fsLit "integerToInt") integerToIntIdKey minusIntegerName = varQual gHC_INTEGER_TYPE (fsLit "minusInteger") minusIntegerIdKey negateIntegerName = varQual gHC_INTEGER_TYPE (fsLit "negateInteger") negateIntegerIdKey eqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "eqInteger#") eqIntegerPrimIdKey neqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "neqInteger#") neqIntegerPrimIdKey absIntegerName = varQual gHC_INTEGER_TYPE (fsLit "absInteger") absIntegerIdKey signumIntegerName = varQual gHC_INTEGER_TYPE (fsLit "signumInteger") signumIntegerIdKey leIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "leInteger#") leIntegerPrimIdKey gtIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "gtInteger#") gtIntegerPrimIdKey ltIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "ltInteger#") ltIntegerPrimIdKey geIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "geInteger#") geIntegerPrimIdKey compareIntegerName = varQual gHC_INTEGER_TYPE (fsLit "compareInteger") compareIntegerIdKey quotRemIntegerName = varQual gHC_INTEGER_TYPE (fsLit "quotRemInteger") quotRemIntegerIdKey divModIntegerName = varQual gHC_INTEGER_TYPE (fsLit "divModInteger") divModIntegerIdKey quotIntegerName = varQual gHC_INTEGER_TYPE (fsLit "quotInteger") quotIntegerIdKey remIntegerName = varQual gHC_INTEGER_TYPE (fsLit "remInteger") remIntegerIdKey divIntegerName = varQual gHC_INTEGER_TYPE (fsLit "divInteger") divIntegerIdKey modIntegerName = varQual gHC_INTEGER_TYPE (fsLit "modInteger") modIntegerIdKey floatFromIntegerName = varQual gHC_INTEGER_TYPE (fsLit "floatFromInteger") floatFromIntegerIdKey doubleFromIntegerName = varQual gHC_INTEGER_TYPE (fsLit "doubleFromInteger") doubleFromIntegerIdKey encodeFloatIntegerName = varQual gHC_INTEGER_TYPE (fsLit "encodeFloatInteger") encodeFloatIntegerIdKey encodeDoubleIntegerName = varQual gHC_INTEGER_TYPE (fsLit "encodeDoubleInteger") encodeDoubleIntegerIdKey decodeDoubleIntegerName = varQual gHC_INTEGER_TYPE (fsLit "decodeDoubleInteger") decodeDoubleIntegerIdKey gcdIntegerName = varQual gHC_INTEGER_TYPE (fsLit "gcdInteger") gcdIntegerIdKey lcmIntegerName = varQual gHC_INTEGER_TYPE (fsLit "lcmInteger") lcmIntegerIdKey andIntegerName = varQual gHC_INTEGER_TYPE (fsLit "andInteger") andIntegerIdKey orIntegerName = varQual gHC_INTEGER_TYPE (fsLit "orInteger") orIntegerIdKey xorIntegerName = varQual gHC_INTEGER_TYPE (fsLit "xorInteger") xorIntegerIdKey complementIntegerName = varQual gHC_INTEGER_TYPE (fsLit "complementInteger") complementIntegerIdKey shiftLIntegerName = varQual gHC_INTEGER_TYPE (fsLit "shiftLInteger") shiftLIntegerIdKey shiftRIntegerName = varQual gHC_INTEGER_TYPE (fsLit "shiftRInteger") shiftRIntegerIdKey bitIntegerName = varQual gHC_INTEGER_TYPE (fsLit "bitInteger") bitIntegerIdKey -- GHC.Real types and classes rationalTyConName, ratioTyConName, ratioDataConName, realClassName, integralClassName, realFracClassName, fractionalClassName, fromRationalName, toIntegerName, toRationalName, fromIntegralName, realToFracName :: Name rationalTyConName = tcQual gHC_REAL (fsLit "Rational") rationalTyConKey ratioTyConName = tcQual gHC_REAL (fsLit "Ratio") ratioTyConKey ratioDataConName = dcQual gHC_REAL (fsLit ":%") ratioDataConKey realClassName = clsQual gHC_REAL (fsLit "Real") realClassKey integralClassName = clsQual gHC_REAL (fsLit "Integral") integralClassKey realFracClassName = clsQual gHC_REAL (fsLit "RealFrac") realFracClassKey fractionalClassName = clsQual gHC_REAL (fsLit "Fractional") fractionalClassKey fromRationalName = varQual gHC_REAL (fsLit "fromRational") fromRationalClassOpKey toIntegerName = varQual gHC_REAL (fsLit "toInteger") toIntegerClassOpKey toRationalName = varQual gHC_REAL (fsLit "toRational") toRationalClassOpKey fromIntegralName = varQual gHC_REAL (fsLit "fromIntegral")fromIntegralIdKey realToFracName = varQual gHC_REAL (fsLit "realToFrac") realToFracIdKey -- PrelFloat classes floatingClassName, realFloatClassName :: Name floatingClassName = clsQual gHC_FLOAT (fsLit "Floating") floatingClassKey realFloatClassName = clsQual gHC_FLOAT (fsLit "RealFloat") realFloatClassKey -- other GHC.Float functions rationalToFloatName, rationalToDoubleName :: Name rationalToFloatName = varQual gHC_FLOAT (fsLit "rationalToFloat") rationalToFloatIdKey rationalToDoubleName = varQual gHC_FLOAT (fsLit "rationalToDouble") rationalToDoubleIdKey -- Class Ix ixClassName :: Name ixClassName = clsQual gHC_ARR (fsLit "Ix") ixClassKey -- Typeable representation types trModuleTyConName , trModuleDataConName , trNameTyConName , trNameSDataConName , trNameDDataConName , trTyConTyConName , trTyConDataConName :: Name trModuleTyConName = tcQual gHC_TYPES (fsLit "Module") trModuleTyConKey trModuleDataConName = dcQual gHC_TYPES (fsLit "Module") trModuleDataConKey trNameTyConName = tcQual gHC_TYPES (fsLit "TrName") trNameTyConKey trNameSDataConName = dcQual gHC_TYPES (fsLit "TrNameS") trNameSDataConKey trNameDDataConName = dcQual gHC_TYPES (fsLit "TrNameD") trNameDDataConKey trTyConTyConName = tcQual gHC_TYPES (fsLit "TyCon") trTyConTyConKey trTyConDataConName = dcQual gHC_TYPES (fsLit "TyCon") trTyConDataConKey -- Class Typeable, and functions for constructing `Typeable` dictionaries typeableClassName , typeRepTyConName , mkPolyTyConAppName , mkAppTyName , typeRepIdName , typeNatTypeRepName , typeSymbolTypeRepName , trGhcPrimModuleName :: Name typeableClassName = clsQual tYPEABLE_INTERNAL (fsLit "Typeable") typeableClassKey typeRepTyConName = tcQual tYPEABLE_INTERNAL (fsLit "TypeRep") typeRepTyConKey typeRepIdName = varQual tYPEABLE_INTERNAL (fsLit "typeRep#") typeRepIdKey mkPolyTyConAppName = varQual tYPEABLE_INTERNAL (fsLit "mkPolyTyConApp") mkPolyTyConAppKey mkAppTyName = varQual tYPEABLE_INTERNAL (fsLit "mkAppTy") mkAppTyKey typeNatTypeRepName = varQual tYPEABLE_INTERNAL (fsLit "typeNatTypeRep") typeNatTypeRepKey typeSymbolTypeRepName = varQual tYPEABLE_INTERNAL (fsLit "typeSymbolTypeRep") typeSymbolTypeRepKey -- this is the Typeable 'Module' for GHC.Prim (which has no code, so we place in GHC.Types) -- See Note [Grand plan for Typeable] in TcTypeable. trGhcPrimModuleName = varQual gHC_TYPES (fsLit "tr$ModuleGHCPrim") trGhcPrimModuleKey -- Custom type errors errorMessageTypeErrorFamName , typeErrorTextDataConName , typeErrorAppendDataConName , typeErrorVAppendDataConName , typeErrorShowTypeDataConName :: Name errorMessageTypeErrorFamName = tcQual gHC_TYPELITS (fsLit "TypeError") errorMessageTypeErrorFamKey typeErrorTextDataConName = dcQual gHC_TYPELITS (fsLit "Text") typeErrorTextDataConKey typeErrorAppendDataConName = dcQual gHC_TYPELITS (fsLit ":<>:") typeErrorAppendDataConKey typeErrorVAppendDataConName = dcQual gHC_TYPELITS (fsLit ":$$:") typeErrorVAppendDataConKey typeErrorShowTypeDataConName = dcQual gHC_TYPELITS (fsLit "ShowType") typeErrorShowTypeDataConKey -- Dynamic toDynName :: Name toDynName = varQual dYNAMIC (fsLit "toDyn") toDynIdKey -- Class Data dataClassName :: Name dataClassName = clsQual gENERICS (fsLit "Data") dataClassKey -- Error module assertErrorName :: Name assertErrorName = varQual gHC_IO_Exception (fsLit "assertError") assertErrorIdKey -- Enum module (Enum, Bounded) enumClassName, enumFromName, enumFromToName, enumFromThenName, enumFromThenToName, boundedClassName :: Name enumClassName = clsQual gHC_ENUM (fsLit "Enum") enumClassKey enumFromName = varQual gHC_ENUM (fsLit "enumFrom") enumFromClassOpKey enumFromToName = varQual gHC_ENUM (fsLit "enumFromTo") enumFromToClassOpKey enumFromThenName = varQual gHC_ENUM (fsLit "enumFromThen") enumFromThenClassOpKey enumFromThenToName = varQual gHC_ENUM (fsLit "enumFromThenTo") enumFromThenToClassOpKey boundedClassName = clsQual gHC_ENUM (fsLit "Bounded") boundedClassKey -- List functions concatName, filterName, zipName :: Name concatName = varQual gHC_LIST (fsLit "concat") concatIdKey filterName = varQual gHC_LIST (fsLit "filter") filterIdKey zipName = varQual gHC_LIST (fsLit "zip") zipIdKey -- Overloaded lists isListClassName, fromListName, fromListNName, toListName :: Name isListClassName = clsQual gHC_EXTS (fsLit "IsList") isListClassKey fromListName = varQual gHC_EXTS (fsLit "fromList") fromListClassOpKey fromListNName = varQual gHC_EXTS (fsLit "fromListN") fromListNClassOpKey toListName = varQual gHC_EXTS (fsLit "toList") toListClassOpKey -- Class Show showClassName :: Name showClassName = clsQual gHC_SHOW (fsLit "Show") showClassKey -- Class Read readClassName :: Name readClassName = clsQual gHC_READ (fsLit "Read") readClassKey -- Classes Generic and Generic1, Datatype, Constructor and Selector genClassName, gen1ClassName, datatypeClassName, constructorClassName, selectorClassName :: Name genClassName = clsQual gHC_GENERICS (fsLit "Generic") genClassKey gen1ClassName = clsQual gHC_GENERICS (fsLit "Generic1") gen1ClassKey datatypeClassName = clsQual gHC_GENERICS (fsLit "Datatype") datatypeClassKey constructorClassName = clsQual gHC_GENERICS (fsLit "Constructor") constructorClassKey selectorClassName = clsQual gHC_GENERICS (fsLit "Selector") selectorClassKey genericClassNames :: [Name] genericClassNames = [genClassName, gen1ClassName] -- GHCi things ghciIoClassName, ghciStepIoMName :: Name ghciIoClassName = clsQual gHC_GHCI (fsLit "GHCiSandboxIO") ghciIoClassKey ghciStepIoMName = varQual gHC_GHCI (fsLit "ghciStepIO") ghciStepIoMClassOpKey -- IO things ioTyConName, ioDataConName, thenIOName, bindIOName, returnIOName, failIOName :: Name ioTyConName = tcQual gHC_TYPES (fsLit "IO") ioTyConKey ioDataConName = dcQual gHC_TYPES (fsLit "IO") ioDataConKey thenIOName = varQual gHC_BASE (fsLit "thenIO") thenIOIdKey bindIOName = varQual gHC_BASE (fsLit "bindIO") bindIOIdKey returnIOName = varQual gHC_BASE (fsLit "returnIO") returnIOIdKey failIOName = varQual gHC_IO (fsLit "failIO") failIOIdKey -- IO things printName :: Name printName = varQual sYSTEM_IO (fsLit "print") printIdKey -- Int, Word, and Addr things int8TyConName, int16TyConName, int32TyConName, int64TyConName :: Name int8TyConName = tcQual gHC_INT (fsLit "Int8") int8TyConKey int16TyConName = tcQual gHC_INT (fsLit "Int16") int16TyConKey int32TyConName = tcQual gHC_INT (fsLit "Int32") int32TyConKey int64TyConName = tcQual gHC_INT (fsLit "Int64") int64TyConKey -- Word module word16TyConName, word32TyConName, word64TyConName :: Name word16TyConName = tcQual gHC_WORD (fsLit "Word16") word16TyConKey word32TyConName = tcQual gHC_WORD (fsLit "Word32") word32TyConKey word64TyConName = tcQual gHC_WORD (fsLit "Word64") word64TyConKey -- PrelPtr module ptrTyConName, funPtrTyConName :: Name ptrTyConName = tcQual gHC_PTR (fsLit "Ptr") ptrTyConKey funPtrTyConName = tcQual gHC_PTR (fsLit "FunPtr") funPtrTyConKey -- Foreign objects and weak pointers stablePtrTyConName, newStablePtrName :: Name stablePtrTyConName = tcQual gHC_STABLE (fsLit "StablePtr") stablePtrTyConKey newStablePtrName = varQual gHC_STABLE (fsLit "newStablePtr") newStablePtrIdKey -- Recursive-do notation monadFixClassName, mfixName :: Name monadFixClassName = clsQual mONAD_FIX (fsLit "MonadFix") monadFixClassKey mfixName = varQual mONAD_FIX (fsLit "mfix") mfixIdKey -- Arrow notation arrAName, composeAName, firstAName, appAName, choiceAName, loopAName :: Name arrAName = varQual aRROW (fsLit "arr") arrAIdKey composeAName = varQual gHC_DESUGAR (fsLit ">>>") composeAIdKey firstAName = varQual aRROW (fsLit "first") firstAIdKey appAName = varQual aRROW (fsLit "app") appAIdKey choiceAName = varQual aRROW (fsLit "|||") choiceAIdKey loopAName = varQual aRROW (fsLit "loop") loopAIdKey -- Monad comprehensions guardMName, liftMName, mzipName :: Name guardMName = varQual mONAD (fsLit "guard") guardMIdKey liftMName = varQual mONAD (fsLit "liftM") liftMIdKey mzipName = varQual mONAD_ZIP (fsLit "mzip") mzipIdKey -- Annotation type checking toAnnotationWrapperName :: Name toAnnotationWrapperName = varQual gHC_DESUGAR (fsLit "toAnnotationWrapper") toAnnotationWrapperIdKey -- Other classes, needed for type defaulting monadPlusClassName, randomClassName, randomGenClassName, isStringClassName :: Name monadPlusClassName = clsQual mONAD (fsLit "MonadPlus") monadPlusClassKey randomClassName = clsQual rANDOM (fsLit "Random") randomClassKey randomGenClassName = clsQual rANDOM (fsLit "RandomGen") randomGenClassKey isStringClassName = clsQual dATA_STRING (fsLit "IsString") isStringClassKey -- Type-level naturals knownNatClassName :: Name knownNatClassName = clsQual gHC_TYPELITS (fsLit "KnownNat") knownNatClassNameKey knownSymbolClassName :: Name knownSymbolClassName = clsQual gHC_TYPELITS (fsLit "KnownSymbol") knownSymbolClassNameKey -- Overloaded labels isLabelClassName :: Name isLabelClassName = clsQual gHC_OVER_LABELS (fsLit "IsLabel") isLabelClassNameKey -- Implicit Parameters ipClassName :: Name ipClassName = clsQual gHC_CLASSES (fsLit "IP") ipClassKey -- Source Locations callStackTyConName, emptyCallStackName, pushCallStackName, srcLocDataConName :: Name callStackTyConName = tcQual gHC_STACK_TYPES (fsLit "CallStack") callStackTyConKey emptyCallStackName = varQual gHC_STACK_TYPES (fsLit "emptyCallStack") emptyCallStackKey pushCallStackName = varQual gHC_STACK_TYPES (fsLit "pushCallStack") pushCallStackKey srcLocDataConName = dcQual gHC_STACK_TYPES (fsLit "SrcLoc") srcLocDataConKey -- plugins pLUGINS :: Module pLUGINS = mkThisGhcModule (fsLit "Plugins") pluginTyConName :: Name pluginTyConName = tcQual pLUGINS (fsLit "Plugin") pluginTyConKey frontendPluginTyConName :: Name frontendPluginTyConName = tcQual pLUGINS (fsLit "FrontendPlugin") frontendPluginTyConKey -- Static pointers staticPtrInfoTyConName :: Name staticPtrInfoTyConName = tcQual gHC_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoTyConKey staticPtrInfoDataConName :: Name staticPtrInfoDataConName = dcQual gHC_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoDataConKey staticPtrTyConName :: Name staticPtrTyConName = tcQual gHC_STATICPTR (fsLit "StaticPtr") staticPtrTyConKey staticPtrDataConName :: Name staticPtrDataConName = dcQual gHC_STATICPTR (fsLit "StaticPtr") staticPtrDataConKey fromStaticPtrName :: Name fromStaticPtrName = varQual gHC_STATICPTR (fsLit "fromStaticPtr") fromStaticPtrClassOpKey fingerprintDataConName :: Name fingerprintDataConName = dcQual gHC_FINGERPRINT_TYPE (fsLit "Fingerprint") fingerprintDataConKey -- homogeneous equality. See Note [The equality types story] in TysPrim eqTyConName :: Name eqTyConName = tcQual dATA_TYPE_EQUALITY (fsLit "~") eqTyConKey {- ************************************************************************ * * \subsection{Local helpers} * * ************************************************************************ All these are original names; hence mkOrig -} varQual, tcQual, clsQual, dcQual :: Module -> FastString -> Unique -> Name varQual = mk_known_key_name varName tcQual = mk_known_key_name tcName clsQual = mk_known_key_name clsName dcQual = mk_known_key_name dataName mk_known_key_name :: NameSpace -> Module -> FastString -> Unique -> Name mk_known_key_name space modu str unique = mkExternalName unique modu (mkOccNameFS space str) noSrcSpan {- ************************************************************************ * * \subsubsection[Uniques-prelude-Classes]{@Uniques@ for wired-in @Classes@} * * ************************************************************************ --MetaHaskell extension hand allocate keys here -} boundedClassKey, enumClassKey, eqClassKey, floatingClassKey, fractionalClassKey, integralClassKey, monadClassKey, dataClassKey, functorClassKey, numClassKey, ordClassKey, readClassKey, realClassKey, realFloatClassKey, realFracClassKey, showClassKey, ixClassKey :: Unique boundedClassKey = mkPreludeClassUnique 1 enumClassKey = mkPreludeClassUnique 2 eqClassKey = mkPreludeClassUnique 3 floatingClassKey = mkPreludeClassUnique 5 fractionalClassKey = mkPreludeClassUnique 6 integralClassKey = mkPreludeClassUnique 7 monadClassKey = mkPreludeClassUnique 8 dataClassKey = mkPreludeClassUnique 9 functorClassKey = mkPreludeClassUnique 10 numClassKey = mkPreludeClassUnique 11 ordClassKey = mkPreludeClassUnique 12 readClassKey = mkPreludeClassUnique 13 realClassKey = mkPreludeClassUnique 14 realFloatClassKey = mkPreludeClassUnique 15 realFracClassKey = mkPreludeClassUnique 16 showClassKey = mkPreludeClassUnique 17 ixClassKey = mkPreludeClassUnique 18 typeableClassKey, typeable1ClassKey, typeable2ClassKey, typeable3ClassKey, typeable4ClassKey, typeable5ClassKey, typeable6ClassKey, typeable7ClassKey :: Unique typeableClassKey = mkPreludeClassUnique 20 typeable1ClassKey = mkPreludeClassUnique 21 typeable2ClassKey = mkPreludeClassUnique 22 typeable3ClassKey = mkPreludeClassUnique 23 typeable4ClassKey = mkPreludeClassUnique 24 typeable5ClassKey = mkPreludeClassUnique 25 typeable6ClassKey = mkPreludeClassUnique 26 typeable7ClassKey = mkPreludeClassUnique 27 monadFixClassKey :: Unique monadFixClassKey = mkPreludeClassUnique 28 monadFailClassKey :: Unique monadFailClassKey = mkPreludeClassUnique 29 monadPlusClassKey, randomClassKey, randomGenClassKey :: Unique monadPlusClassKey = mkPreludeClassUnique 30 randomClassKey = mkPreludeClassUnique 31 randomGenClassKey = mkPreludeClassUnique 32 isStringClassKey :: Unique isStringClassKey = mkPreludeClassUnique 33 applicativeClassKey, foldableClassKey, traversableClassKey :: Unique applicativeClassKey = mkPreludeClassUnique 34 foldableClassKey = mkPreludeClassUnique 35 traversableClassKey = mkPreludeClassUnique 36 genClassKey, gen1ClassKey, datatypeClassKey, constructorClassKey, selectorClassKey :: Unique genClassKey = mkPreludeClassUnique 37 gen1ClassKey = mkPreludeClassUnique 38 datatypeClassKey = mkPreludeClassUnique 39 constructorClassKey = mkPreludeClassUnique 40 selectorClassKey = mkPreludeClassUnique 41 -- KnownNat: see Note [KnowNat & KnownSymbol and EvLit] in TcEvidence knownNatClassNameKey :: Unique knownNatClassNameKey = mkPreludeClassUnique 42 -- KnownSymbol: see Note [KnownNat & KnownSymbol and EvLit] in TcEvidence knownSymbolClassNameKey :: Unique knownSymbolClassNameKey = mkPreludeClassUnique 43 ghciIoClassKey :: Unique ghciIoClassKey = mkPreludeClassUnique 44 isLabelClassNameKey :: Unique isLabelClassNameKey = mkPreludeClassUnique 45 semigroupClassKey, monoidClassKey :: Unique semigroupClassKey = mkPreludeClassUnique 46 monoidClassKey = mkPreludeClassUnique 47 -- Implicit Parameters ipClassKey :: Unique ipClassKey = mkPreludeClassUnique 48 ---------------- Template Haskell ------------------- -- THNames.hs: USES ClassUniques 200-299 ----------------------------------------------------- {- ************************************************************************ * * \subsubsection[Uniques-prelude-TyCons]{@Uniques@ for wired-in @TyCons@} * * ************************************************************************ -} addrPrimTyConKey, arrayPrimTyConKey, arrayArrayPrimTyConKey, boolTyConKey, byteArrayPrimTyConKey, charPrimTyConKey, charTyConKey, doublePrimTyConKey, doubleTyConKey, floatPrimTyConKey, floatTyConKey, funTyConKey, intPrimTyConKey, intTyConKey, int8TyConKey, int16TyConKey, int32PrimTyConKey, int32TyConKey, int64PrimTyConKey, int64TyConKey, integerTyConKey, listTyConKey, foreignObjPrimTyConKey, maybeTyConKey, weakPrimTyConKey, mutableArrayPrimTyConKey, mutableArrayArrayPrimTyConKey, mutableByteArrayPrimTyConKey, orderingTyConKey, mVarPrimTyConKey, ratioTyConKey, rationalTyConKey, realWorldTyConKey, stablePtrPrimTyConKey, stablePtrTyConKey, anyTyConKey, eqTyConKey, heqTyConKey, smallArrayPrimTyConKey, smallMutableArrayPrimTyConKey :: Unique addrPrimTyConKey = mkPreludeTyConUnique 1 arrayPrimTyConKey = mkPreludeTyConUnique 3 boolTyConKey = mkPreludeTyConUnique 4 byteArrayPrimTyConKey = mkPreludeTyConUnique 5 charPrimTyConKey = mkPreludeTyConUnique 7 charTyConKey = mkPreludeTyConUnique 8 doublePrimTyConKey = mkPreludeTyConUnique 9 doubleTyConKey = mkPreludeTyConUnique 10 floatPrimTyConKey = mkPreludeTyConUnique 11 floatTyConKey = mkPreludeTyConUnique 12 funTyConKey = mkPreludeTyConUnique 13 intPrimTyConKey = mkPreludeTyConUnique 14 intTyConKey = mkPreludeTyConUnique 15 int8TyConKey = mkPreludeTyConUnique 16 int16TyConKey = mkPreludeTyConUnique 17 int32PrimTyConKey = mkPreludeTyConUnique 18 int32TyConKey = mkPreludeTyConUnique 19 int64PrimTyConKey = mkPreludeTyConUnique 20 int64TyConKey = mkPreludeTyConUnique 21 integerTyConKey = mkPreludeTyConUnique 22 listTyConKey = mkPreludeTyConUnique 24 foreignObjPrimTyConKey = mkPreludeTyConUnique 25 maybeTyConKey = mkPreludeTyConUnique 26 weakPrimTyConKey = mkPreludeTyConUnique 27 mutableArrayPrimTyConKey = mkPreludeTyConUnique 28 mutableByteArrayPrimTyConKey = mkPreludeTyConUnique 29 orderingTyConKey = mkPreludeTyConUnique 30 mVarPrimTyConKey = mkPreludeTyConUnique 31 ratioTyConKey = mkPreludeTyConUnique 32 rationalTyConKey = mkPreludeTyConUnique 33 realWorldTyConKey = mkPreludeTyConUnique 34 stablePtrPrimTyConKey = mkPreludeTyConUnique 35 stablePtrTyConKey = mkPreludeTyConUnique 36 anyTyConKey = mkPreludeTyConUnique 37 eqTyConKey = mkPreludeTyConUnique 38 heqTyConKey = mkPreludeTyConUnique 39 arrayArrayPrimTyConKey = mkPreludeTyConUnique 40 mutableArrayArrayPrimTyConKey = mkPreludeTyConUnique 41 statePrimTyConKey, stableNamePrimTyConKey, stableNameTyConKey, mutVarPrimTyConKey, ioTyConKey, wordPrimTyConKey, wordTyConKey, word8TyConKey, word16TyConKey, word32PrimTyConKey, word32TyConKey, word64PrimTyConKey, word64TyConKey, liftedConKey, unliftedConKey, anyBoxConKey, kindConKey, boxityConKey, typeConKey, threadIdPrimTyConKey, bcoPrimTyConKey, ptrTyConKey, funPtrTyConKey, tVarPrimTyConKey, eqPrimTyConKey, eqReprPrimTyConKey, eqPhantPrimTyConKey, voidPrimTyConKey :: Unique statePrimTyConKey = mkPreludeTyConUnique 50 stableNamePrimTyConKey = mkPreludeTyConUnique 51 stableNameTyConKey = mkPreludeTyConUnique 52 eqPrimTyConKey = mkPreludeTyConUnique 53 eqReprPrimTyConKey = mkPreludeTyConUnique 54 eqPhantPrimTyConKey = mkPreludeTyConUnique 55 mutVarPrimTyConKey = mkPreludeTyConUnique 56 ioTyConKey = mkPreludeTyConUnique 57 voidPrimTyConKey = mkPreludeTyConUnique 58 wordPrimTyConKey = mkPreludeTyConUnique 59 wordTyConKey = mkPreludeTyConUnique 60 word8TyConKey = mkPreludeTyConUnique 61 word16TyConKey = mkPreludeTyConUnique 62 word32PrimTyConKey = mkPreludeTyConUnique 63 word32TyConKey = mkPreludeTyConUnique 64 word64PrimTyConKey = mkPreludeTyConUnique 65 word64TyConKey = mkPreludeTyConUnique 66 liftedConKey = mkPreludeTyConUnique 67 unliftedConKey = mkPreludeTyConUnique 68 anyBoxConKey = mkPreludeTyConUnique 69 kindConKey = mkPreludeTyConUnique 70 boxityConKey = mkPreludeTyConUnique 71 typeConKey = mkPreludeTyConUnique 72 threadIdPrimTyConKey = mkPreludeTyConUnique 73 bcoPrimTyConKey = mkPreludeTyConUnique 74 ptrTyConKey = mkPreludeTyConUnique 75 funPtrTyConKey = mkPreludeTyConUnique 76 tVarPrimTyConKey = mkPreludeTyConUnique 77 -- Parallel array type constructor parrTyConKey :: Unique parrTyConKey = mkPreludeTyConUnique 82 -- dotnet interop objectTyConKey :: Unique objectTyConKey = mkPreludeTyConUnique 83 eitherTyConKey :: Unique eitherTyConKey = mkPreludeTyConUnique 84 -- Kind constructors liftedTypeKindTyConKey, tYPETyConKey, unliftedTypeKindTyConKey, constraintKindTyConKey, starKindTyConKey, unicodeStarKindTyConKey, runtimeRepTyConKey, vecCountTyConKey, vecElemTyConKey :: Unique liftedTypeKindTyConKey = mkPreludeTyConUnique 87 tYPETyConKey = mkPreludeTyConUnique 88 unliftedTypeKindTyConKey = mkPreludeTyConUnique 89 constraintKindTyConKey = mkPreludeTyConUnique 92 starKindTyConKey = mkPreludeTyConUnique 93 unicodeStarKindTyConKey = mkPreludeTyConUnique 94 runtimeRepTyConKey = mkPreludeTyConUnique 95 vecCountTyConKey = mkPreludeTyConUnique 96 vecElemTyConKey = mkPreludeTyConUnique 97 pluginTyConKey, frontendPluginTyConKey :: Unique pluginTyConKey = mkPreludeTyConUnique 102 frontendPluginTyConKey = mkPreludeTyConUnique 103 unknownTyConKey, unknown1TyConKey, unknown2TyConKey, unknown3TyConKey, opaqueTyConKey :: Unique unknownTyConKey = mkPreludeTyConUnique 129 unknown1TyConKey = mkPreludeTyConUnique 130 unknown2TyConKey = mkPreludeTyConUnique 131 unknown3TyConKey = mkPreludeTyConUnique 132 opaqueTyConKey = mkPreludeTyConUnique 133 -- Generics (Unique keys) v1TyConKey, u1TyConKey, par1TyConKey, rec1TyConKey, k1TyConKey, m1TyConKey, sumTyConKey, prodTyConKey, compTyConKey, rTyConKey, dTyConKey, cTyConKey, sTyConKey, rec0TyConKey, d1TyConKey, c1TyConKey, s1TyConKey, noSelTyConKey, repTyConKey, rep1TyConKey, uRecTyConKey, uAddrTyConKey, uCharTyConKey, uDoubleTyConKey, uFloatTyConKey, uIntTyConKey, uWordTyConKey :: Unique v1TyConKey = mkPreludeTyConUnique 135 u1TyConKey = mkPreludeTyConUnique 136 par1TyConKey = mkPreludeTyConUnique 137 rec1TyConKey = mkPreludeTyConUnique 138 k1TyConKey = mkPreludeTyConUnique 139 m1TyConKey = mkPreludeTyConUnique 140 sumTyConKey = mkPreludeTyConUnique 141 prodTyConKey = mkPreludeTyConUnique 142 compTyConKey = mkPreludeTyConUnique 143 rTyConKey = mkPreludeTyConUnique 144 dTyConKey = mkPreludeTyConUnique 146 cTyConKey = mkPreludeTyConUnique 147 sTyConKey = mkPreludeTyConUnique 148 rec0TyConKey = mkPreludeTyConUnique 149 d1TyConKey = mkPreludeTyConUnique 151 c1TyConKey = mkPreludeTyConUnique 152 s1TyConKey = mkPreludeTyConUnique 153 noSelTyConKey = mkPreludeTyConUnique 154 repTyConKey = mkPreludeTyConUnique 155 rep1TyConKey = mkPreludeTyConUnique 156 uRecTyConKey = mkPreludeTyConUnique 157 uAddrTyConKey = mkPreludeTyConUnique 158 uCharTyConKey = mkPreludeTyConUnique 159 uDoubleTyConKey = mkPreludeTyConUnique 160 uFloatTyConKey = mkPreludeTyConUnique 161 uIntTyConKey = mkPreludeTyConUnique 162 uWordTyConKey = mkPreludeTyConUnique 163 -- Type-level naturals typeNatKindConNameKey, typeSymbolKindConNameKey, typeNatAddTyFamNameKey, typeNatMulTyFamNameKey, typeNatExpTyFamNameKey, typeNatLeqTyFamNameKey, typeNatSubTyFamNameKey , typeSymbolCmpTyFamNameKey, typeNatCmpTyFamNameKey :: Unique typeNatKindConNameKey = mkPreludeTyConUnique 164 typeSymbolKindConNameKey = mkPreludeTyConUnique 165 typeNatAddTyFamNameKey = mkPreludeTyConUnique 166 typeNatMulTyFamNameKey = mkPreludeTyConUnique 167 typeNatExpTyFamNameKey = mkPreludeTyConUnique 168 typeNatLeqTyFamNameKey = mkPreludeTyConUnique 169 typeNatSubTyFamNameKey = mkPreludeTyConUnique 170 typeSymbolCmpTyFamNameKey = mkPreludeTyConUnique 171 typeNatCmpTyFamNameKey = mkPreludeTyConUnique 172 -- Custom user type-errors errorMessageTypeErrorFamKey :: Unique errorMessageTypeErrorFamKey = mkPreludeTyConUnique 173 ntTyConKey:: Unique ntTyConKey = mkPreludeTyConUnique 174 coercibleTyConKey :: Unique coercibleTyConKey = mkPreludeTyConUnique 175 proxyPrimTyConKey :: Unique proxyPrimTyConKey = mkPreludeTyConUnique 176 specTyConKey :: Unique specTyConKey = mkPreludeTyConUnique 177 smallArrayPrimTyConKey = mkPreludeTyConUnique 178 smallMutableArrayPrimTyConKey = mkPreludeTyConUnique 179 staticPtrTyConKey :: Unique staticPtrTyConKey = mkPreludeTyConUnique 180 staticPtrInfoTyConKey :: Unique staticPtrInfoTyConKey = mkPreludeTyConUnique 181 callStackTyConKey :: Unique callStackTyConKey = mkPreludeTyConUnique 182 -- Typeables typeRepTyConKey :: Unique typeRepTyConKey = mkPreludeTyConUnique 183 ---------------- Template Haskell ------------------- -- THNames.hs: USES TyConUniques 200-299 ----------------------------------------------------- ----------------------- SIMD ------------------------ -- USES TyConUniques 300-399 ----------------------------------------------------- #include "primop-vector-uniques.hs-incl" {- ************************************************************************ * * \subsubsection[Uniques-prelude-DataCons]{@Uniques@ for wired-in @DataCons@} * * ************************************************************************ -} charDataConKey, consDataConKey, doubleDataConKey, falseDataConKey, floatDataConKey, intDataConKey, integerSDataConKey, nilDataConKey, ratioDataConKey, stableNameDataConKey, trueDataConKey, wordDataConKey, word8DataConKey, ioDataConKey, integerDataConKey, heqDataConKey, coercibleDataConKey, nothingDataConKey, justDataConKey :: Unique charDataConKey = mkPreludeDataConUnique 1 consDataConKey = mkPreludeDataConUnique 2 doubleDataConKey = mkPreludeDataConUnique 3 falseDataConKey = mkPreludeDataConUnique 4 floatDataConKey = mkPreludeDataConUnique 5 intDataConKey = mkPreludeDataConUnique 6 integerSDataConKey = mkPreludeDataConUnique 7 nothingDataConKey = mkPreludeDataConUnique 8 justDataConKey = mkPreludeDataConUnique 9 nilDataConKey = mkPreludeDataConUnique 11 ratioDataConKey = mkPreludeDataConUnique 12 word8DataConKey = mkPreludeDataConUnique 13 stableNameDataConKey = mkPreludeDataConUnique 14 trueDataConKey = mkPreludeDataConUnique 15 wordDataConKey = mkPreludeDataConUnique 16 ioDataConKey = mkPreludeDataConUnique 17 integerDataConKey = mkPreludeDataConUnique 18 heqDataConKey = mkPreludeDataConUnique 19 -- Generic data constructors crossDataConKey, inlDataConKey, inrDataConKey, genUnitDataConKey :: Unique crossDataConKey = mkPreludeDataConUnique 20 inlDataConKey = mkPreludeDataConUnique 21 inrDataConKey = mkPreludeDataConUnique 22 genUnitDataConKey = mkPreludeDataConUnique 23 -- Data constructor for parallel arrays parrDataConKey :: Unique parrDataConKey = mkPreludeDataConUnique 24 leftDataConKey, rightDataConKey :: Unique leftDataConKey = mkPreludeDataConUnique 25 rightDataConKey = mkPreludeDataConUnique 26 ltDataConKey, eqDataConKey, gtDataConKey :: Unique ltDataConKey = mkPreludeDataConUnique 27 eqDataConKey = mkPreludeDataConUnique 28 gtDataConKey = mkPreludeDataConUnique 29 coercibleDataConKey = mkPreludeDataConUnique 32 staticPtrDataConKey :: Unique staticPtrDataConKey = mkPreludeDataConUnique 33 staticPtrInfoDataConKey :: Unique staticPtrInfoDataConKey = mkPreludeDataConUnique 34 fingerprintDataConKey :: Unique fingerprintDataConKey = mkPreludeDataConUnique 35 srcLocDataConKey :: Unique srcLocDataConKey = mkPreludeDataConUnique 37 trTyConTyConKey, trTyConDataConKey, trModuleTyConKey, trModuleDataConKey, trNameTyConKey, trNameSDataConKey, trNameDDataConKey, trGhcPrimModuleKey :: Unique trTyConTyConKey = mkPreludeDataConUnique 41 trTyConDataConKey = mkPreludeDataConUnique 42 trModuleTyConKey = mkPreludeDataConUnique 43 trModuleDataConKey = mkPreludeDataConUnique 44 trNameTyConKey = mkPreludeDataConUnique 45 trNameSDataConKey = mkPreludeDataConUnique 46 trNameDDataConKey = mkPreludeDataConUnique 47 trGhcPrimModuleKey = mkPreludeDataConUnique 48 typeErrorTextDataConKey, typeErrorAppendDataConKey, typeErrorVAppendDataConKey, typeErrorShowTypeDataConKey :: Unique typeErrorTextDataConKey = mkPreludeDataConUnique 50 typeErrorAppendDataConKey = mkPreludeDataConUnique 51 typeErrorVAppendDataConKey = mkPreludeDataConUnique 52 typeErrorShowTypeDataConKey = mkPreludeDataConUnique 53 prefixIDataConKey, infixIDataConKey, leftAssociativeDataConKey, rightAssociativeDataConKey, notAssociativeDataConKey, sourceUnpackDataConKey, sourceNoUnpackDataConKey, noSourceUnpackednessDataConKey, sourceLazyDataConKey, sourceStrictDataConKey, noSourceStrictnessDataConKey, decidedLazyDataConKey, decidedStrictDataConKey, decidedUnpackDataConKey, metaDataDataConKey, metaConsDataConKey, metaSelDataConKey :: Unique prefixIDataConKey = mkPreludeDataConUnique 54 infixIDataConKey = mkPreludeDataConUnique 55 leftAssociativeDataConKey = mkPreludeDataConUnique 56 rightAssociativeDataConKey = mkPreludeDataConUnique 57 notAssociativeDataConKey = mkPreludeDataConUnique 58 sourceUnpackDataConKey = mkPreludeDataConUnique 59 sourceNoUnpackDataConKey = mkPreludeDataConUnique 60 noSourceUnpackednessDataConKey = mkPreludeDataConUnique 61 sourceLazyDataConKey = mkPreludeDataConUnique 62 sourceStrictDataConKey = mkPreludeDataConUnique 63 noSourceStrictnessDataConKey = mkPreludeDataConUnique 64 decidedLazyDataConKey = mkPreludeDataConUnique 65 decidedStrictDataConKey = mkPreludeDataConUnique 66 decidedUnpackDataConKey = mkPreludeDataConUnique 67 metaDataDataConKey = mkPreludeDataConUnique 68 metaConsDataConKey = mkPreludeDataConUnique 69 metaSelDataConKey = mkPreludeDataConUnique 70 vecRepDataConKey :: Unique vecRepDataConKey = mkPreludeDataConUnique 71 -- See Note [Wiring in RuntimeRep] in TysWiredIn runtimeRepSimpleDataConKeys :: [Unique] ptrRepLiftedDataConKey, ptrRepUnliftedDataConKey :: Unique runtimeRepSimpleDataConKeys@( ptrRepLiftedDataConKey : ptrRepUnliftedDataConKey : _) = map mkPreludeDataConUnique [72..82] -- See Note [Wiring in RuntimeRep] in TysWiredIn -- VecCount vecCountDataConKeys :: [Unique] vecCountDataConKeys = map mkPreludeDataConUnique [83..88] -- See Note [Wiring in RuntimeRep] in TysWiredIn -- VecElem vecElemDataConKeys :: [Unique] vecElemDataConKeys = map mkPreludeDataConUnique [89..98] ---------------- Template Haskell ------------------- -- THNames.hs: USES DataUniques 100-150 ----------------------------------------------------- {- ************************************************************************ * * \subsubsection[Uniques-prelude-Ids]{@Uniques@ for wired-in @Ids@ (except @DataCons@)} * * ************************************************************************ -} wildCardKey, absentErrorIdKey, augmentIdKey, appendIdKey, buildIdKey, errorIdKey, foldrIdKey, recSelErrorIdKey, seqIdKey, irrefutPatErrorIdKey, eqStringIdKey, noMethodBindingErrorIdKey, nonExhaustiveGuardsErrorIdKey, runtimeErrorIdKey, patErrorIdKey, voidPrimIdKey, realWorldPrimIdKey, recConErrorIdKey, unpackCStringUtf8IdKey, unpackCStringAppendIdKey, unpackCStringFoldrIdKey, unpackCStringIdKey, typeErrorIdKey :: Unique wildCardKey = mkPreludeMiscIdUnique 0 -- See Note [WildCard binders] absentErrorIdKey = mkPreludeMiscIdUnique 1 augmentIdKey = mkPreludeMiscIdUnique 2 appendIdKey = mkPreludeMiscIdUnique 3 buildIdKey = mkPreludeMiscIdUnique 4 errorIdKey = mkPreludeMiscIdUnique 5 foldrIdKey = mkPreludeMiscIdUnique 6 recSelErrorIdKey = mkPreludeMiscIdUnique 7 seqIdKey = mkPreludeMiscIdUnique 8 irrefutPatErrorIdKey = mkPreludeMiscIdUnique 9 eqStringIdKey = mkPreludeMiscIdUnique 10 noMethodBindingErrorIdKey = mkPreludeMiscIdUnique 11 nonExhaustiveGuardsErrorIdKey = mkPreludeMiscIdUnique 12 runtimeErrorIdKey = mkPreludeMiscIdUnique 13 patErrorIdKey = mkPreludeMiscIdUnique 14 realWorldPrimIdKey = mkPreludeMiscIdUnique 15 recConErrorIdKey = mkPreludeMiscIdUnique 16 unpackCStringUtf8IdKey = mkPreludeMiscIdUnique 17 unpackCStringAppendIdKey = mkPreludeMiscIdUnique 18 unpackCStringFoldrIdKey = mkPreludeMiscIdUnique 19 unpackCStringIdKey = mkPreludeMiscIdUnique 20 voidPrimIdKey = mkPreludeMiscIdUnique 21 typeErrorIdKey = mkPreludeMiscIdUnique 22 unsafeCoerceIdKey, concatIdKey, filterIdKey, zipIdKey, bindIOIdKey, returnIOIdKey, newStablePtrIdKey, printIdKey, failIOIdKey, nullAddrIdKey, voidArgIdKey, fstIdKey, sndIdKey, otherwiseIdKey, assertIdKey :: Unique unsafeCoerceIdKey = mkPreludeMiscIdUnique 30 concatIdKey = mkPreludeMiscIdUnique 31 filterIdKey = mkPreludeMiscIdUnique 32 zipIdKey = mkPreludeMiscIdUnique 33 bindIOIdKey = mkPreludeMiscIdUnique 34 returnIOIdKey = mkPreludeMiscIdUnique 35 newStablePtrIdKey = mkPreludeMiscIdUnique 36 printIdKey = mkPreludeMiscIdUnique 37 failIOIdKey = mkPreludeMiscIdUnique 38 nullAddrIdKey = mkPreludeMiscIdUnique 39 voidArgIdKey = mkPreludeMiscIdUnique 40 fstIdKey = mkPreludeMiscIdUnique 41 sndIdKey = mkPreludeMiscIdUnique 42 otherwiseIdKey = mkPreludeMiscIdUnique 43 assertIdKey = mkPreludeMiscIdUnique 44 mkIntegerIdKey, smallIntegerIdKey, wordToIntegerIdKey, integerToWordIdKey, integerToIntIdKey, integerToWord64IdKey, integerToInt64IdKey, word64ToIntegerIdKey, int64ToIntegerIdKey, plusIntegerIdKey, timesIntegerIdKey, minusIntegerIdKey, negateIntegerIdKey, eqIntegerPrimIdKey, neqIntegerPrimIdKey, absIntegerIdKey, signumIntegerIdKey, leIntegerPrimIdKey, gtIntegerPrimIdKey, ltIntegerPrimIdKey, geIntegerPrimIdKey, compareIntegerIdKey, quotRemIntegerIdKey, divModIntegerIdKey, quotIntegerIdKey, remIntegerIdKey, divIntegerIdKey, modIntegerIdKey, floatFromIntegerIdKey, doubleFromIntegerIdKey, encodeFloatIntegerIdKey, encodeDoubleIntegerIdKey, decodeDoubleIntegerIdKey, gcdIntegerIdKey, lcmIntegerIdKey, andIntegerIdKey, orIntegerIdKey, xorIntegerIdKey, complementIntegerIdKey, shiftLIntegerIdKey, shiftRIntegerIdKey :: Unique mkIntegerIdKey = mkPreludeMiscIdUnique 60 smallIntegerIdKey = mkPreludeMiscIdUnique 61 integerToWordIdKey = mkPreludeMiscIdUnique 62 integerToIntIdKey = mkPreludeMiscIdUnique 63 integerToWord64IdKey = mkPreludeMiscIdUnique 64 integerToInt64IdKey = mkPreludeMiscIdUnique 65 plusIntegerIdKey = mkPreludeMiscIdUnique 66 timesIntegerIdKey = mkPreludeMiscIdUnique 67 minusIntegerIdKey = mkPreludeMiscIdUnique 68 negateIntegerIdKey = mkPreludeMiscIdUnique 69 eqIntegerPrimIdKey = mkPreludeMiscIdUnique 70 neqIntegerPrimIdKey = mkPreludeMiscIdUnique 71 absIntegerIdKey = mkPreludeMiscIdUnique 72 signumIntegerIdKey = mkPreludeMiscIdUnique 73 leIntegerPrimIdKey = mkPreludeMiscIdUnique 74 gtIntegerPrimIdKey = mkPreludeMiscIdUnique 75 ltIntegerPrimIdKey = mkPreludeMiscIdUnique 76 geIntegerPrimIdKey = mkPreludeMiscIdUnique 77 compareIntegerIdKey = mkPreludeMiscIdUnique 78 quotIntegerIdKey = mkPreludeMiscIdUnique 79 remIntegerIdKey = mkPreludeMiscIdUnique 80 divIntegerIdKey = mkPreludeMiscIdUnique 81 modIntegerIdKey = mkPreludeMiscIdUnique 82 divModIntegerIdKey = mkPreludeMiscIdUnique 83 quotRemIntegerIdKey = mkPreludeMiscIdUnique 84 floatFromIntegerIdKey = mkPreludeMiscIdUnique 85 doubleFromIntegerIdKey = mkPreludeMiscIdUnique 86 encodeFloatIntegerIdKey = mkPreludeMiscIdUnique 87 encodeDoubleIntegerIdKey = mkPreludeMiscIdUnique 88 gcdIntegerIdKey = mkPreludeMiscIdUnique 89 lcmIntegerIdKey = mkPreludeMiscIdUnique 90 andIntegerIdKey = mkPreludeMiscIdUnique 91 orIntegerIdKey = mkPreludeMiscIdUnique 92 xorIntegerIdKey = mkPreludeMiscIdUnique 93 complementIntegerIdKey = mkPreludeMiscIdUnique 94 shiftLIntegerIdKey = mkPreludeMiscIdUnique 95 shiftRIntegerIdKey = mkPreludeMiscIdUnique 96 wordToIntegerIdKey = mkPreludeMiscIdUnique 97 word64ToIntegerIdKey = mkPreludeMiscIdUnique 98 int64ToIntegerIdKey = mkPreludeMiscIdUnique 99 decodeDoubleIntegerIdKey = mkPreludeMiscIdUnique 100 rootMainKey, runMainKey :: Unique rootMainKey = mkPreludeMiscIdUnique 101 runMainKey = mkPreludeMiscIdUnique 102 thenIOIdKey, lazyIdKey, assertErrorIdKey, oneShotKey, runRWKey :: Unique thenIOIdKey = mkPreludeMiscIdUnique 103 lazyIdKey = mkPreludeMiscIdUnique 104 assertErrorIdKey = mkPreludeMiscIdUnique 105 oneShotKey = mkPreludeMiscIdUnique 106 runRWKey = mkPreludeMiscIdUnique 107 breakpointIdKey, breakpointCondIdKey, breakpointAutoIdKey, breakpointJumpIdKey, breakpointCondJumpIdKey, breakpointAutoJumpIdKey :: Unique breakpointIdKey = mkPreludeMiscIdUnique 110 breakpointCondIdKey = mkPreludeMiscIdUnique 111 breakpointAutoIdKey = mkPreludeMiscIdUnique 112 breakpointJumpIdKey = mkPreludeMiscIdUnique 113 breakpointCondJumpIdKey = mkPreludeMiscIdUnique 114 breakpointAutoJumpIdKey = mkPreludeMiscIdUnique 115 inlineIdKey :: Unique inlineIdKey = mkPreludeMiscIdUnique 120 mapIdKey, groupWithIdKey, dollarIdKey :: Unique mapIdKey = mkPreludeMiscIdUnique 121 groupWithIdKey = mkPreludeMiscIdUnique 122 dollarIdKey = mkPreludeMiscIdUnique 123 coercionTokenIdKey :: Unique coercionTokenIdKey = mkPreludeMiscIdUnique 124 rationalToFloatIdKey, rationalToDoubleIdKey :: Unique rationalToFloatIdKey = mkPreludeMiscIdUnique 130 rationalToDoubleIdKey = mkPreludeMiscIdUnique 131 -- dotnet interop unmarshalObjectIdKey, marshalObjectIdKey, marshalStringIdKey, unmarshalStringIdKey, checkDotnetResNameIdKey :: Unique unmarshalObjectIdKey = mkPreludeMiscIdUnique 150 marshalObjectIdKey = mkPreludeMiscIdUnique 151 marshalStringIdKey = mkPreludeMiscIdUnique 152 unmarshalStringIdKey = mkPreludeMiscIdUnique 153 checkDotnetResNameIdKey = mkPreludeMiscIdUnique 154 undefinedKey :: Unique undefinedKey = mkPreludeMiscIdUnique 155 magicDictKey :: Unique magicDictKey = mkPreludeMiscIdUnique 156 coerceKey :: Unique coerceKey = mkPreludeMiscIdUnique 157 {- Certain class operations from Prelude classes. They get their own uniques so we can look them up easily when we want to conjure them up during type checking. -} -- Just a placeholder for unbound variables produced by the renamer: unboundKey :: Unique unboundKey = mkPreludeMiscIdUnique 158 fromIntegerClassOpKey, minusClassOpKey, fromRationalClassOpKey, enumFromClassOpKey, enumFromThenClassOpKey, enumFromToClassOpKey, enumFromThenToClassOpKey, eqClassOpKey, geClassOpKey, negateClassOpKey, failMClassOpKey_preMFP, bindMClassOpKey, thenMClassOpKey, returnMClassOpKey, fmapClassOpKey :: Unique fromIntegerClassOpKey = mkPreludeMiscIdUnique 160 minusClassOpKey = mkPreludeMiscIdUnique 161 fromRationalClassOpKey = mkPreludeMiscIdUnique 162 enumFromClassOpKey = mkPreludeMiscIdUnique 163 enumFromThenClassOpKey = mkPreludeMiscIdUnique 164 enumFromToClassOpKey = mkPreludeMiscIdUnique 165 enumFromThenToClassOpKey = mkPreludeMiscIdUnique 166 eqClassOpKey = mkPreludeMiscIdUnique 167 geClassOpKey = mkPreludeMiscIdUnique 168 negateClassOpKey = mkPreludeMiscIdUnique 169 failMClassOpKey_preMFP = mkPreludeMiscIdUnique 170 bindMClassOpKey = mkPreludeMiscIdUnique 171 -- (>>=) thenMClassOpKey = mkPreludeMiscIdUnique 172 -- (>>) fmapClassOpKey = mkPreludeMiscIdUnique 173 returnMClassOpKey = mkPreludeMiscIdUnique 174 -- Recursive do notation mfixIdKey :: Unique mfixIdKey = mkPreludeMiscIdUnique 175 -- MonadFail operations failMClassOpKey :: Unique failMClassOpKey = mkPreludeMiscIdUnique 176 -- Arrow notation arrAIdKey, composeAIdKey, firstAIdKey, appAIdKey, choiceAIdKey, loopAIdKey :: Unique arrAIdKey = mkPreludeMiscIdUnique 180 composeAIdKey = mkPreludeMiscIdUnique 181 -- >>> firstAIdKey = mkPreludeMiscIdUnique 182 appAIdKey = mkPreludeMiscIdUnique 183 choiceAIdKey = mkPreludeMiscIdUnique 184 -- ||| loopAIdKey = mkPreludeMiscIdUnique 185 fromStringClassOpKey :: Unique fromStringClassOpKey = mkPreludeMiscIdUnique 186 -- Annotation type checking toAnnotationWrapperIdKey :: Unique toAnnotationWrapperIdKey = mkPreludeMiscIdUnique 187 -- Conversion functions fromIntegralIdKey, realToFracIdKey, toIntegerClassOpKey, toRationalClassOpKey :: Unique fromIntegralIdKey = mkPreludeMiscIdUnique 190 realToFracIdKey = mkPreludeMiscIdUnique 191 toIntegerClassOpKey = mkPreludeMiscIdUnique 192 toRationalClassOpKey = mkPreludeMiscIdUnique 193 -- Monad comprehensions guardMIdKey, liftMIdKey, mzipIdKey :: Unique guardMIdKey = mkPreludeMiscIdUnique 194 liftMIdKey = mkPreludeMiscIdUnique 195 mzipIdKey = mkPreludeMiscIdUnique 196 -- GHCi ghciStepIoMClassOpKey :: Unique ghciStepIoMClassOpKey = mkPreludeMiscIdUnique 197 -- Overloaded lists isListClassKey, fromListClassOpKey, fromListNClassOpKey, toListClassOpKey :: Unique isListClassKey = mkPreludeMiscIdUnique 198 fromListClassOpKey = mkPreludeMiscIdUnique 199 fromListNClassOpKey = mkPreludeMiscIdUnique 500 toListClassOpKey = mkPreludeMiscIdUnique 501 proxyHashKey :: Unique proxyHashKey = mkPreludeMiscIdUnique 502 ---------------- Template Haskell ------------------- -- THNames.hs: USES IdUniques 200-499 ----------------------------------------------------- -- Used to make `Typeable` dictionaries mkTyConKey , mkPolyTyConAppKey , mkAppTyKey , typeNatTypeRepKey , typeSymbolTypeRepKey , typeRepIdKey :: Unique mkTyConKey = mkPreludeMiscIdUnique 503 mkPolyTyConAppKey = mkPreludeMiscIdUnique 504 mkAppTyKey = mkPreludeMiscIdUnique 505 typeNatTypeRepKey = mkPreludeMiscIdUnique 506 typeSymbolTypeRepKey = mkPreludeMiscIdUnique 507 typeRepIdKey = mkPreludeMiscIdUnique 508 -- Dynamic toDynIdKey :: Unique toDynIdKey = mkPreludeMiscIdUnique 509 bitIntegerIdKey :: Unique bitIntegerIdKey = mkPreludeMiscIdUnique 510 heqSCSelIdKey, coercibleSCSelIdKey :: Unique heqSCSelIdKey = mkPreludeMiscIdUnique 511 coercibleSCSelIdKey = mkPreludeMiscIdUnique 512 sappendClassOpKey :: Unique sappendClassOpKey = mkPreludeMiscIdUnique 513 memptyClassOpKey, mappendClassOpKey, mconcatClassOpKey :: Unique memptyClassOpKey = mkPreludeMiscIdUnique 514 mappendClassOpKey = mkPreludeMiscIdUnique 515 mconcatClassOpKey = mkPreludeMiscIdUnique 516 emptyCallStackKey, pushCallStackKey :: Unique emptyCallStackKey = mkPreludeMiscIdUnique 517 pushCallStackKey = mkPreludeMiscIdUnique 518 fromStaticPtrClassOpKey :: Unique fromStaticPtrClassOpKey = mkPreludeMiscIdUnique 519 {- ************************************************************************ * * \subsection[Class-std-groups]{Standard groups of Prelude classes} * * ************************************************************************ NOTE: @Eq@ and @Text@ do need to appear in @standardClasses@ even though every numeric class has these two as a superclass, because the list of ambiguous dictionaries hasn't been simplified. -} numericClassKeys :: [Unique] numericClassKeys = [ numClassKey , realClassKey , integralClassKey ] ++ fractionalClassKeys fractionalClassKeys :: [Unique] fractionalClassKeys = [ fractionalClassKey , floatingClassKey , realFracClassKey , realFloatClassKey ] -- The "standard classes" are used in defaulting (Haskell 98 report 4.3.4), -- and are: "classes defined in the Prelude or a standard library" standardClassKeys :: [Unique] standardClassKeys = derivableClassKeys ++ numericClassKeys ++ [randomClassKey, randomGenClassKey, functorClassKey, monadClassKey, monadPlusClassKey, monadFailClassKey, semigroupClassKey, monoidClassKey, isStringClassKey, applicativeClassKey, foldableClassKey, traversableClassKey, alternativeClassKey ] {- @derivableClassKeys@ is also used in checking \tr{deriving} constructs (@TcDeriv@). -} derivableClassKeys :: [Unique] derivableClassKeys = [ eqClassKey, ordClassKey, enumClassKey, ixClassKey, boundedClassKey, showClassKey, readClassKey ] {- ************************************************************************ * * Semi-builtin names * * ************************************************************************ The following names should be considered by GHCi to be in scope always. -} pretendNameIsInScope :: Name -> Bool pretendNameIsInScope n = any (n `hasKey`) [ starKindTyConKey, liftedTypeKindTyConKey, tYPETyConKey , unliftedTypeKindTyConKey , runtimeRepTyConKey, ptrRepLiftedDataConKey, ptrRepUnliftedDataConKey ]
oldmanmike/ghc
compiler/prelude/PrelNames.hs
bsd-3-clause
100,843
0
10
22,736
15,438
8,804
6,634
1,542
2
module Bead.View.Fay.Hooks where import Prelude import Bead.View.Fay.HookIds data EvaluationHook = EvaluationHook { evFormId :: String , evSelectionId :: String , evHiddenValueId :: String , evSelectionDivId :: String , evHelpMessageId :: String } {- createCourseHook = EvaluationHook { evFormId = hookId createCourseForm , evSelectionId = hookId evaluationTypeSelection , evHiddenValueId = hookId evaluationTypeValue , evSelectionDivId = hookId evalTypeSelectionDiv , evHelpMessageId = hookId pctHelpMessage } createGroupHook = EvaluationHook { evFormId = hookId createGroupForm , evSelectionId = hookId evaluationTypeSelection , evHiddenValueId = hookId evaluationTypeValue , evSelectionDivId = hookId evalTypeSelectionDiv , evHelpMessageId = hookId pctHelpMessage } -} assignmentEvTypeHook = EvaluationHook { evFormId = hookId assignmentForm , evSelectionId = hookId evaluationTypeSelection , evHiddenValueId = hookId evaluationTypeValue , evSelectionDivId = hookId evalTypeSelectionDiv , evHelpMessageId = hookId pctHelpMessage } data DateTimePickerHook = DateTimePickerHook { dtDivId :: String , dtHiddenInputId :: String , dtDatePickerId :: String , dtHourPickerId :: String , dtMinPickerId :: String , dtDefaultDate :: String , dtDefaultHour :: String , dtDefaultMin :: String } startDateTimeHook = DateTimePickerHook { dtDivId = hookId startDateDivId , dtHiddenInputId = hookId assignmentStartField , dtDatePickerId = hookId assignmentStartDateField , dtHourPickerId = hookId assignmentStartHourField , dtMinPickerId = hookId assignmentStartMinField , dtDefaultDate = hookId assignmentStartDefaultDate , dtDefaultHour = hookId assignmentStartDefaultHour , dtDefaultMin = hookId assignmentStartDefaultMin } endDateTimeHook = DateTimePickerHook { dtDivId = hookId endDateDivId , dtHiddenInputId = hookId assignmentEndField , dtDatePickerId = hookId assignmentEndDateField , dtHourPickerId = hookId assignmentEndHourField , dtMinPickerId = hookId assignmentEndMinField , dtDefaultDate = hookId assignmentEndDefaultDate , dtDefaultHour = hookId assignmentEndDefaultHour , dtDefaultMin = hookId assignmentEndDefaultMin } data PercentageHook = PercentageHook { ptDivId :: String , ptHiddenInputId :: String } evaluationPctHook = PercentageHook { ptDivId = hookId evaluationPercentageDiv , ptHiddenInputId = hookId evaluationResultField }
pgj/bead
snaplets/fay/src/Bead/View/Fay/Hooks.hs
bsd-3-clause
2,541
0
8
474
371
220
151
48
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} module Clang.Type ( isSameType , getTypeSpelling , getKind , getCanonicalType , getPointeeType , getResultType , getNumArgTypes , getArgType , isFunctionTypeVariadic , getTypedefDeclUnderlyingType , getEnumDeclIntegerType , getEnumConstantDeclValue , getEnumConstantDeclUnsignedValue , getFieldDeclBitWidth , isConstQualifiedType , isVolatileQualifiedType , isRestrictQualifiedType , isPODType , getElementType , getNumElements , getArrayElementType , getArraySize , getAlignOf , getSizeOf , getOffsetOf , getClassType , getCXXRefQualifier , isVirtualBase , getFunctionTypeCallingConv , getTypeKindSpelling ) where import Control.Monad.IO.Class import qualified Data.ByteString as B import Data.Int (Int64) import Data.Word (Word64) import qualified Clang.Internal.FFI as FFI import Clang.Internal.Monad isSameType :: ClangBase m => FFI.Type s' -> FFI.Type s'' -> ClangT s m Bool isSameType a b = liftIO $ FFI.equalTypes a b getTypeSpelling :: ClangBase m => FFI.Type s' -> ClangT s m (FFI.ClangString s) getTypeSpelling = FFI.getTypeSpelling getTypedefDeclUnderlyingType :: ClangBase m => FFI.Cursor s' -> ClangT s m (FFI.Type s) getTypedefDeclUnderlyingType c = liftIO $ FFI.getTypedefDeclUnderlyingType mkProxy c getEnumDeclIntegerType :: ClangBase m => FFI.Cursor s' -> ClangT s m (FFI.Type s) getEnumDeclIntegerType c = liftIO $ FFI.getEnumDeclIntegerType mkProxy c getEnumConstantDeclValue :: ClangBase m => FFI.Cursor s' -> ClangT s m Int64 getEnumConstantDeclValue c = liftIO $ FFI.getEnumConstantDeclValue c getEnumConstantDeclUnsignedValue :: ClangBase m => FFI.Cursor s' -> ClangT s m Word64 getEnumConstantDeclUnsignedValue c = liftIO $ FFI.getEnumConstantDeclUnsignedValue c getFieldDeclBitWidth :: ClangBase m => FFI.Cursor s' -> ClangT s m (Maybe Int) getFieldDeclBitWidth c = do bitWidth <- liftIO $ FFI.getFieldDeclBitWidth c return $ if bitWidth < 0 then Nothing else Just bitWidth getKind :: ClangBase m => FFI.Type s' -> ClangT s m FFI.TypeKind getKind = return . FFI.getTypeKind getCanonicalType :: ClangBase m => FFI.Type s' -> ClangT s m (FFI.Type s) getCanonicalType t = liftIO $ FFI.getCanonicalType mkProxy t getPointeeType :: ClangBase m => FFI.Type s' -> ClangT s m (FFI.Type s) getPointeeType t = liftIO $ FFI.getPointeeType mkProxy t getResultType :: ClangBase m => FFI.Type s' -> ClangT s m (FFI.Type s) getResultType t = liftIO $ FFI.getResultType mkProxy t getNumArgTypes :: ClangBase m => FFI.Type s' -> ClangT s m Int getNumArgTypes t = liftIO $ FFI.getNumArgTypes t getArgType :: ClangBase m => FFI.Type s' -> Int -> ClangT s m (FFI.Type s) getArgType t i = liftIO $ FFI.getArgType mkProxy t i isFunctionTypeVariadic :: ClangBase m => FFI.Type s' -> ClangT s m Bool isFunctionTypeVariadic t = liftIO $ FFI.isFunctionTypeVariadic t isConstQualifiedType :: ClangBase m => FFI.Type s' -> ClangT s m Bool isConstQualifiedType t = liftIO $ FFI.isConstQualifiedType t isVolatileQualifiedType :: ClangBase m => FFI.Type s' -> ClangT s m Bool isVolatileQualifiedType t = liftIO $ FFI.isVolatileQualifiedType t isRestrictQualifiedType :: ClangBase m => FFI.Type s' -> ClangT s m Bool isRestrictQualifiedType t = liftIO $ FFI.isRestrictQualifiedType t isPODType :: ClangBase m => FFI.Type s' -> ClangT s m Bool isPODType t = liftIO $ FFI.isPODType t getElementType :: ClangBase m => FFI.Type s' -> ClangT s m (FFI.Type s) getElementType t = liftIO $ FFI.getElementType mkProxy t getNumElements :: ClangBase m => FFI.Type s' -> ClangT s m Int64 getNumElements t = liftIO $ FFI.getNumElements t getArrayElementType :: ClangBase m => FFI.Type s' -> ClangT s m (FFI.Type s) getArrayElementType t = liftIO $ FFI.getArrayElementType mkProxy t getArraySize :: ClangBase m => FFI.Type s' -> ClangT s m Int64 getArraySize t = liftIO $ FFI.getArraySize t getAlignOf :: ClangBase m => FFI.Type s' -> ClangT s m (Either FFI.TypeLayoutError Int64) getAlignOf t = liftIO $ FFI.type_getAlignOf t getSizeOf :: ClangBase m => FFI.Type s' -> ClangT s m (Either FFI.TypeLayoutError Int64) getSizeOf t = liftIO $ FFI.type_getSizeOf t getOffsetOf :: ClangBase m => FFI.Type s' -> B.ByteString -> ClangT s m (Either FFI.TypeLayoutError Int64) getOffsetOf = FFI.type_getOffsetOf getClassType :: ClangBase m => FFI.Type s' -> ClangT s m (FFI.Type s) getClassType t = liftIO $ FFI.type_getClassType mkProxy t getCXXRefQualifier :: ClangBase m => FFI.Type s' -> ClangT s m FFI.RefQualifierKind getCXXRefQualifier t = liftIO $ FFI.type_getCXXRefQualifier t isVirtualBase :: ClangBase m => FFI.Cursor s' -> ClangT s m Bool isVirtualBase c = liftIO $ FFI.isVirtualBase c getFunctionTypeCallingConv :: ClangBase m => FFI.Type s' -> ClangT s m FFI.CallingConv getFunctionTypeCallingConv t = liftIO $ FFI.getFunctionTypeCallingConv t -- Typekind functions getTypeKindSpelling :: ClangBase m => FFI.TypeKind -> ClangT s m (FFI.ClangString s) getTypeKindSpelling = FFI.getTypeKindSpelling
deech/LibClang
src/Clang/Type.hs
bsd-3-clause
5,032
0
11
786
1,666
818
848
103
2
{-# LANGUAGE ExistentialQuantification #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Command -- Copyright : Duncan Coutts 2007 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : non-portable (ExistentialQuantification) -- -- This is to do with command line handling. The Cabal command line is -- organised into a number of named sub-commands (much like darcs). The -- 'CommandUI' abstraction represents one of these sub-commands, with a name, -- description, a set of flags. Commands can be associated with actions and -- run. It handles some common stuff automatically, like the @--help@ and -- command line completion flags. It is designed to allow other tools make -- derived commands. This feature is used heavily in @cabal-install@. module Distribution.Simple.Command ( -- * Command interface CommandUI(..), commandShowOptions, CommandParse(..), commandParseArgs, getNormalCommandDescriptions, helpCommandUI, -- ** Constructing commands ShowOrParseArgs(..), usageDefault, usageAlternatives, mkCommandUI, hiddenCommand, -- ** Associating actions with commands Command, commandAddAction, noExtraFlags, -- ** Building lists of commands CommandType(..), CommandSpec(..), commandFromSpec, -- ** Running commands commandsRun, -- * Option Fields OptionField(..), Name, -- ** Constructing Option Fields option, multiOption, -- ** Liftings & Projections liftOption, viewAsFieldDescr, -- * Option Descriptions OptDescr(..), Description, SFlags, LFlags, OptFlags, ArgPlaceHolder, -- ** OptDescr 'smart' constructors MkOptDescr, reqArg, reqArg', optArg, optArg', noArg, boolOpt, boolOpt', choiceOpt, choiceOptFromEnum ) where import Control.Monad import Data.Char (isAlpha, toLower) import Data.List (sortBy) import Data.Maybe import Data.Monoid as Mon import qualified Distribution.GetOpt as GetOpt import Distribution.Text ( Text(disp, parse) ) import Distribution.ParseUtils import Distribution.ReadE import Distribution.Simple.Utils (die, intercalate) import Text.PrettyPrint ( punctuate, cat, comma, text ) import Text.PrettyPrint as PP ( empty ) data CommandUI flags = CommandUI { -- | The name of the command as it would be entered on the command line. -- For example @\"build\"@. commandName :: String, -- | A short, one line description of the command to use in help texts. commandSynopsis :: String, -- | A function that maps a program name to a usage summary for this -- command. commandUsage :: String -> String, -- | Additional explanation of the command to use in help texts. commandDescription :: Maybe (String -> String), -- | Post-Usage notes and examples in help texts commandNotes :: Maybe (String -> String), -- | Initial \/ empty flags commandDefaultFlags :: flags, -- | All the Option fields for this command commandOptions :: ShowOrParseArgs -> [OptionField flags] } data ShowOrParseArgs = ShowArgs | ParseArgs type Name = String type Description = String -- | We usually have a data type for storing configuration values, where -- every field stores a configuration option, and the user sets -- the value either via command line flags or a configuration file. -- An individual OptionField models such a field, and we usually -- build a list of options associated to a configuration data type. data OptionField a = OptionField { optionName :: Name, optionDescr :: [OptDescr a] } -- | An OptionField takes one or more OptDescrs, describing the command line -- interface for the field. data OptDescr a = ReqArg Description OptFlags ArgPlaceHolder (ReadE (a->a)) (a -> [String]) | OptArg Description OptFlags ArgPlaceHolder (ReadE (a->a)) (a->a) (a -> [Maybe String]) | ChoiceOpt [(Description, OptFlags, a->a, a -> Bool)] | BoolOpt Description OptFlags{-True-} OptFlags{-False-} (Bool -> a -> a) (a-> Maybe Bool) -- | Short command line option strings type SFlags = [Char] -- | Long command line option strings type LFlags = [String] type OptFlags = (SFlags,LFlags) type ArgPlaceHolder = String -- | Create an option taking a single OptDescr. -- No explicit Name is given for the Option, the name is the first LFlag given. option :: SFlags -> LFlags -> Description -> get -> set -> MkOptDescr get set a -> OptionField a option sf lf@(n:_) d get set arg = OptionField n [arg sf lf d get set] option _ _ _ _ _ _ = error $ "Distribution.command.option: " ++ "An OptionField must have at least one LFlag" -- | Create an option taking several OptDescrs. -- You will have to give the flags and description individually to the -- OptDescr constructor. multiOption :: Name -> get -> set -> [get -> set -> OptDescr a] -- ^MkOptDescr constructors partially -- applied to flags and description. -> OptionField a multiOption n get set args = OptionField n [arg get set | arg <- args] type MkOptDescr get set a = SFlags -> LFlags -> Description -> get -> set -> OptDescr a -- | Create a string-valued command line interface. reqArg :: Monoid b => ArgPlaceHolder -> ReadE b -> (b -> [String]) -> MkOptDescr (a -> b) (b -> a -> a) a reqArg ad mkflag showflag sf lf d get set = ReqArg d (sf,lf) ad (fmap (\a b -> set (get b `mappend` a) b) mkflag) (showflag . get) -- | Create a string-valued command line interface with a default value. optArg :: Monoid b => ArgPlaceHolder -> ReadE b -> b -> (b -> [Maybe String]) -> MkOptDescr (a -> b) (b -> a -> a) a optArg ad mkflag def showflag sf lf d get set = OptArg d (sf,lf) ad (fmap (\a b -> set (get b `mappend` a) b) mkflag) (\b -> set (get b `mappend` def) b) (showflag . get) -- | (String -> a) variant of "reqArg" reqArg' :: Monoid b => ArgPlaceHolder -> (String -> b) -> (b -> [String]) -> MkOptDescr (a -> b) (b -> a -> a) a reqArg' ad mkflag showflag = reqArg ad (succeedReadE mkflag) showflag -- | (String -> a) variant of "optArg" optArg' :: Mon.Monoid b => ArgPlaceHolder -> (Maybe String -> b) -> (b -> [Maybe String]) -> MkOptDescr (a -> b) (b -> a -> a) a optArg' ad mkflag showflag = optArg ad (succeedReadE (mkflag . Just)) def showflag where def = mkflag Nothing noArg :: (Eq b) => b -> MkOptDescr (a -> b) (b -> a -> a) a noArg flag sf lf d = choiceOpt [(flag, (sf,lf), d)] sf lf d boolOpt :: (b -> Maybe Bool) -> (Bool -> b) -> SFlags -> SFlags -> MkOptDescr (a -> b) (b -> a -> a) a boolOpt g s sfT sfF _sf _lf@(n:_) d get set = BoolOpt d (sfT, ["enable-"++n]) (sfF, ["disable-"++n]) (set.s) (g.get) boolOpt _ _ _ _ _ _ _ _ _ = error "Distribution.Simple.Setup.boolOpt: unreachable" boolOpt' :: (b -> Maybe Bool) -> (Bool -> b) -> OptFlags -> OptFlags -> MkOptDescr (a -> b) (b -> a -> a) a boolOpt' g s ffT ffF _sf _lf d get set = BoolOpt d ffT ffF (set.s) (g . get) -- | create a Choice option choiceOpt :: Eq b => [(b,OptFlags,Description)] -> MkOptDescr (a -> b) (b -> a -> a) a choiceOpt aa_ff _sf _lf _d get set = ChoiceOpt alts where alts = [(d,flags, set alt, (==alt) . get) | (alt,flags,d) <- aa_ff] -- | create a Choice option out of an enumeration type. -- As long flags, the Show output is used. As short flags, the first character -- which does not conflict with a previous one is used. choiceOptFromEnum :: (Bounded b, Enum b, Show b, Eq b) => MkOptDescr (a -> b) (b -> a -> a) a choiceOptFromEnum _sf _lf d get = choiceOpt [ (x, (sf, [map toLower $ show x]), d') | (x, sf) <- sflags' , let d' = d ++ show x] _sf _lf d get where sflags' = foldl f [] [firstOne..] f prev x = let prevflags = concatMap snd prev in prev ++ take 1 [(x, [toLower sf]) | sf <- show x, isAlpha sf , toLower sf `notElem` prevflags] firstOne = minBound `asTypeOf` get undefined commandGetOpts :: ShowOrParseArgs -> CommandUI flags -> [GetOpt.OptDescr (flags -> flags)] commandGetOpts showOrParse command = concatMap viewAsGetOpt (commandOptions command showOrParse) viewAsGetOpt :: OptionField a -> [GetOpt.OptDescr (a->a)] viewAsGetOpt (OptionField _n aa) = concatMap optDescrToGetOpt aa where optDescrToGetOpt (ReqArg d (cs,ss) arg_desc set _) = [GetOpt.Option cs ss (GetOpt.ReqArg set' arg_desc) d] where set' = readEOrFail set optDescrToGetOpt (OptArg d (cs,ss) arg_desc set def _) = [GetOpt.Option cs ss (GetOpt.OptArg set' arg_desc) d] where set' Nothing = def set' (Just txt) = readEOrFail set txt optDescrToGetOpt (ChoiceOpt alts) = [GetOpt.Option sf lf (GetOpt.NoArg set) d | (d,(sf,lf),set,_) <- alts ] optDescrToGetOpt (BoolOpt d (sfT, lfT) ([], []) set _) = [ GetOpt.Option sfT lfT (GetOpt.NoArg (set True)) d ] optDescrToGetOpt (BoolOpt d ([], []) (sfF, lfF) set _) = [ GetOpt.Option sfF lfF (GetOpt.NoArg (set False)) d ] optDescrToGetOpt (BoolOpt d (sfT,lfT) (sfF, lfF) set _) = [ GetOpt.Option sfT lfT (GetOpt.NoArg (set True)) ("Enable " ++ d) , GetOpt.Option sfF lfF (GetOpt.NoArg (set False)) ("Disable " ++ d) ] -- | to view as a FieldDescr, we sort the list of interfaces (Req > Bool > -- Choice > Opt) and consider only the first one. viewAsFieldDescr :: OptionField a -> FieldDescr a viewAsFieldDescr (OptionField _n []) = error "Distribution.command.viewAsFieldDescr: unexpected" viewAsFieldDescr (OptionField n dd) = FieldDescr n get set where optDescr = head $ sortBy cmp dd cmp :: OptDescr a -> OptDescr a -> Ordering ReqArg{} `cmp` ReqArg{} = EQ ReqArg{} `cmp` _ = GT BoolOpt{} `cmp` ReqArg{} = LT BoolOpt{} `cmp` BoolOpt{} = EQ BoolOpt{} `cmp` _ = GT ChoiceOpt{} `cmp` ReqArg{} = LT ChoiceOpt{} `cmp` BoolOpt{} = LT ChoiceOpt{} `cmp` ChoiceOpt{} = EQ ChoiceOpt{} `cmp` _ = GT OptArg{} `cmp` OptArg{} = EQ OptArg{} `cmp` _ = LT -- get :: a -> Doc get t = case optDescr of ReqArg _ _ _ _ ppr -> (cat . punctuate comma . map text . ppr) t OptArg _ _ _ _ _ ppr -> case ppr t of [] -> PP.empty (Nothing : _) -> text "True" (Just a : _) -> text a ChoiceOpt alts -> fromMaybe PP.empty $ listToMaybe [ text lf | (_,(_,lf:_), _,enabled) <- alts, enabled t] BoolOpt _ _ _ _ enabled -> (maybe PP.empty disp . enabled) t -- set :: LineNo -> String -> a -> ParseResult a set line val a = case optDescr of ReqArg _ _ _ readE _ -> ($ a) `liftM` runE line n readE val -- We parse for a single value instead of a -- list, as one can't really implement -- parseList :: ReadE a -> ReadE [a] with -- the current ReadE definition ChoiceOpt{} -> case getChoiceByLongFlag optDescr val of Just f -> return (f a) _ -> syntaxError line val BoolOpt _ _ _ setV _ -> (`setV` a) `liftM` runP line n parse val OptArg _ _ _ readE _ _ -> ($ a) `liftM` runE line n readE val -- Optional arguments are parsed just like -- required arguments here; we don't -- provide a method to set an OptArg field -- to the default value. getChoiceByLongFlag :: OptDescr b -> String -> Maybe (b->b) getChoiceByLongFlag (ChoiceOpt alts) val = listToMaybe [ set | (_,(_sf,lf:_), set, _) <- alts , lf == val] getChoiceByLongFlag _ _ = error "Distribution.command.getChoiceByLongFlag: expected a choice option" getCurrentChoice :: OptDescr a -> a -> [String] getCurrentChoice (ChoiceOpt alts) a = [ lf | (_,(_sf,lf:_), _, currentChoice) <- alts, currentChoice a] getCurrentChoice _ _ = error "Command.getChoice: expected a Choice OptDescr" liftOption :: (b -> a) -> (a -> (b -> b)) -> OptionField a -> OptionField b liftOption get' set' opt = opt { optionDescr = liftOptDescr get' set' `map` optionDescr opt} liftOptDescr :: (b -> a) -> (a -> (b -> b)) -> OptDescr a -> OptDescr b liftOptDescr get' set' (ChoiceOpt opts) = ChoiceOpt [ (d, ff, liftSet get' set' set , (get . get')) | (d, ff, set, get) <- opts] liftOptDescr get' set' (OptArg d ff ad set def get) = OptArg d ff ad (liftSet get' set' `fmap` set) (liftSet get' set' def) (get . get') liftOptDescr get' set' (ReqArg d ff ad set get) = ReqArg d ff ad (liftSet get' set' `fmap` set) (get . get') liftOptDescr get' set' (BoolOpt d ffT ffF set get) = BoolOpt d ffT ffF (liftSet get' set' . set) (get . get') liftSet :: (b -> a) -> (a -> (b -> b)) -> (a -> a) -> b -> b liftSet get' set' set x = set' (set $ get' x) x -- | Show flags in the standard long option command line format commandShowOptions :: CommandUI flags -> flags -> [String] commandShowOptions command v = concat [ showOptDescr v od | o <- commandOptions command ParseArgs , od <- optionDescr o] where maybePrefix [] = [] maybePrefix (lOpt:_) = ["--" ++ lOpt] showOptDescr :: a -> OptDescr a -> [String] showOptDescr x (BoolOpt _ (_,lfTs) (_,lfFs) _ enabled) = case enabled x of Nothing -> [] Just True -> maybePrefix lfTs Just False -> maybePrefix lfFs showOptDescr x c@ChoiceOpt{} = ["--" ++ val | val <- getCurrentChoice c x] showOptDescr x (ReqArg _ (_ssff,lf:_) _ _ showflag) = [ "--"++lf++"="++flag | flag <- showflag x ] showOptDescr x (OptArg _ (_ssff,lf:_) _ _ _ showflag) = [ case flag of Just s -> "--"++lf++"="++s Nothing -> "--"++lf | flag <- showflag x ] showOptDescr _ _ = error "Distribution.Simple.Command.showOptDescr: unreachable" commandListOptions :: CommandUI flags -> [String] commandListOptions command = concatMap listOption $ addCommonFlags ShowArgs $ -- This is a slight hack, we don't want -- "--list-options" showing up in the -- list options output, so use ShowArgs commandGetOpts ShowArgs command where listOption (GetOpt.Option shortNames longNames _ _) = [ "-" ++ [name] | name <- shortNames ] ++ [ "--" ++ name | name <- longNames ] -- | The help text for this command with descriptions of all the options. commandHelp :: CommandUI flags -> String -> String commandHelp command pname = commandSynopsis command ++ "\n\n" ++ commandUsage command pname ++ ( case commandDescription command of Nothing -> "" Just desc -> '\n': desc pname) ++ "\n" ++ ( if cname == "" then "Global flags:" else "Flags for " ++ cname ++ ":" ) ++ ( GetOpt.usageInfo "" . addCommonFlags ShowArgs $ commandGetOpts ShowArgs command ) ++ ( case commandNotes command of Nothing -> "" Just notes -> '\n': notes pname) where cname = commandName command -- | Default "usage" documentation text for commands. usageDefault :: String -> String -> String usageDefault name pname = "Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n\n" ++ "Flags for " ++ name ++ ":" -- | Create "usage" documentation from a list of parameter -- configurations. usageAlternatives :: String -> [String] -> String -> String usageAlternatives name strs pname = unlines [ start ++ pname ++ " " ++ name ++ " " ++ s | let starts = "Usage: " : repeat " or: " , (start, s) <- zip starts strs ] -- | Make a Command from standard 'GetOpt' options. mkCommandUI :: String -- ^ name -> String -- ^ synopsis -> [String] -- ^ usage alternatives -> flags -- ^ initial\/empty flags -> (ShowOrParseArgs -> [OptionField flags]) -- ^ options -> CommandUI flags mkCommandUI name synopsis usages flags options = CommandUI { commandName = name , commandSynopsis = synopsis , commandDescription = Nothing , commandNotes = Nothing , commandUsage = usageAlternatives name usages , commandDefaultFlags = flags , commandOptions = options } -- | Common flags that apply to every command data CommonFlag = HelpFlag | ListOptionsFlag commonFlags :: ShowOrParseArgs -> [GetOpt.OptDescr CommonFlag] commonFlags showOrParseArgs = case showOrParseArgs of ShowArgs -> [help] ParseArgs -> [help, list] where help = GetOpt.Option helpShortFlags ["help"] (GetOpt.NoArg HelpFlag) "Show this help text" helpShortFlags = case showOrParseArgs of ShowArgs -> ['h'] ParseArgs -> ['h', '?'] list = GetOpt.Option [] ["list-options"] (GetOpt.NoArg ListOptionsFlag) "Print a list of command line flags" addCommonFlags :: ShowOrParseArgs -> [GetOpt.OptDescr a] -> [GetOpt.OptDescr (Either CommonFlag a)] addCommonFlags showOrParseArgs options = map (fmapOptDesc Left) (commonFlags showOrParseArgs) ++ map (fmapOptDesc Right) options where fmapOptDesc f (GetOpt.Option s l d m) = GetOpt.Option s l (fmapArgDesc f d) m fmapArgDesc f (GetOpt.NoArg a) = GetOpt.NoArg (f a) fmapArgDesc f (GetOpt.ReqArg s d) = GetOpt.ReqArg (f . s) d fmapArgDesc f (GetOpt.OptArg s d) = GetOpt.OptArg (f . s) d -- | Parse a bunch of command line arguments -- commandParseArgs :: CommandUI flags -> Bool -- ^ Is the command a global or subcommand? -> [String] -> CommandParse (flags -> flags, [String]) commandParseArgs command global args = let options = addCommonFlags ParseArgs $ commandGetOpts ParseArgs command order | global = GetOpt.RequireOrder | otherwise = GetOpt.Permute in case GetOpt.getOpt' order options args of (flags, _, _, _) | any listFlag flags -> CommandList (commandListOptions command) | any helpFlag flags -> CommandHelp (commandHelp command) where listFlag (Left ListOptionsFlag) = True; listFlag _ = False helpFlag (Left HelpFlag) = True; helpFlag _ = False (flags, opts, opts', []) | global || null opts' -> CommandReadyToGo (accum flags, mix opts opts') | otherwise -> CommandErrors (unrecognised opts') (_, _, _, errs) -> CommandErrors errs where -- Note: It is crucial to use reverse function composition here or to -- reverse the flags here as we want to process the flags left to right -- but data flow in function composition is right to left. accum flags = foldr (flip (.)) id [ f | Right f <- flags ] unrecognised opts = [ "unrecognized " ++ "'" ++ (commandName command) ++ "'" ++ " option `" ++ opt ++ "'\n" | opt <- opts ] -- For unrecognised global flags we put them in the position just after -- the command, if there is one. This gives us a chance to parse them -- as sub-command rather than global flags. mix [] ys = ys mix (x:xs) ys = x:ys++xs data CommandParse flags = CommandHelp (String -> String) | CommandList [String] | CommandErrors [String] | CommandReadyToGo flags instance Functor CommandParse where fmap _ (CommandHelp help) = CommandHelp help fmap _ (CommandList opts) = CommandList opts fmap _ (CommandErrors errs) = CommandErrors errs fmap f (CommandReadyToGo flags) = CommandReadyToGo (f flags) data CommandType = NormalCommand | HiddenCommand data Command action = Command String String ([String] -> CommandParse action) CommandType -- | Mark command as hidden. Hidden commands don't show up in the 'progname -- help' or 'progname --help' output. hiddenCommand :: Command action -> Command action hiddenCommand (Command name synopsys f _cmdType) = Command name synopsys f HiddenCommand commandAddAction :: CommandUI flags -> (flags -> [String] -> action) -> Command action commandAddAction command action = Command (commandName command) (commandSynopsis command) (fmap (uncurry applyDefaultArgs) . commandParseArgs command False) NormalCommand where applyDefaultArgs mkflags args = let flags = mkflags (commandDefaultFlags command) in action flags args commandsRun :: CommandUI a -> [Command action] -> [String] -> CommandParse (a, CommandParse action) commandsRun globalCommand commands args = case commandParseArgs globalCommand True args of CommandHelp help -> CommandHelp help CommandList opts -> CommandList (opts ++ commandNames) CommandErrors errs -> CommandErrors errs CommandReadyToGo (mkflags, args') -> case args' of ("help":cmdArgs) -> handleHelpCommand cmdArgs (name:cmdArgs) -> case lookupCommand name of [Command _ _ action _] -> CommandReadyToGo (flags, action cmdArgs) _ -> CommandReadyToGo (flags, badCommand name) [] -> CommandReadyToGo (flags, noCommand) where flags = mkflags (commandDefaultFlags globalCommand) where lookupCommand cname = [ cmd | cmd@(Command cname' _ _ _) <- commands' , cname' == cname ] noCommand = CommandErrors ["no command given (try --help)\n"] badCommand cname = CommandErrors ["unrecognised command: " ++ cname ++ " (try --help)\n"] commands' = commands ++ [commandAddAction helpCommandUI undefined] commandNames = [ name | (Command name _ _ NormalCommand) <- commands' ] -- A bit of a hack: support "prog help" as a synonym of "prog --help" -- furthermore, support "prog help command" as "prog command --help" handleHelpCommand cmdArgs = case commandParseArgs helpCommandUI True cmdArgs of CommandHelp help -> CommandHelp help CommandList list -> CommandList (list ++ commandNames) CommandErrors _ -> CommandHelp globalHelp CommandReadyToGo (_,[]) -> CommandHelp globalHelp CommandReadyToGo (_,(name:cmdArgs')) -> case lookupCommand name of [Command _ _ action _] -> case action ("--help":cmdArgs') of CommandHelp help -> CommandHelp help CommandList _ -> CommandList [] _ -> CommandHelp globalHelp _ -> badCommand name where globalHelp = commandHelp globalCommand -- | Utility function, many commands do not accept additional flags. This -- action fails with a helpful error message if the user supplies any extra. -- noExtraFlags :: [String] -> IO () noExtraFlags [] = return () noExtraFlags extraFlags = die $ "Unrecognised flags: " ++ intercalate ", " extraFlags --TODO: eliminate this function and turn it into a variant on commandAddAction -- instead like commandAddActionNoArgs that doesn't supply the [String] -- | Helper function for creating globalCommand description getNormalCommandDescriptions :: [Command action] -> [(String, String)] getNormalCommandDescriptions cmds = [ (name, description) | Command name description _ NormalCommand <- cmds ] helpCommandUI :: CommandUI () helpCommandUI = (mkCommandUI "help" "Help about commands." ["[FLAGS]", "COMMAND [FLAGS]"] () (const [])) { commandNotes = Just $ \pname -> "Examples:\n" ++ " " ++ pname ++ " help help\n" ++ " Oh, appararently you already know this.\n" } -- | wraps a @CommandUI@ together with a function that turns it into a @Command@. -- By hiding the type of flags for the UI allows construction of a list of all UIs at the -- top level of the program. That list can then be used for generation of manual page -- as well as for executing the selected command. data CommandSpec action = forall flags. CommandSpec (CommandUI flags) (CommandUI flags -> Command action) CommandType commandFromSpec :: CommandSpec a -> Command a commandFromSpec (CommandSpec ui action _) = action ui
trskop/cabal
Cabal/Distribution/Simple/Command.hs
bsd-3-clause
25,266
0
17
7,220
6,993
3,709
3,284
422
20
module DeepSeq2 where import qualified Control.Parallel.Strategies as CP fib t n | n <= 1 = 1 | otherwise = n1_2 + n2_2 + 1 where n1 = fib 20 (n-1) n2 = fib 20 (n-2) (n1_2, n2_2) = CP.runEval (do n1_2 <- (rpar_abs_1 `CP.dot` CP.rdeepseq) n1 n2_2 <- (rpar_abs_1 `CP.dot` CP.rdeepseq) n2 return (n1_2, n2_2)) where rpar_abs_1 | n > t = CP.rpar | otherwise = CP.rseq n1_2 = fib 20 42
RefactoringTools/HaRe
old/testing/introThreshold/DeepSeq2_TokOut.hs
bsd-3-clause
555
0
15
247
204
106
98
16
1
module DoExp2 where f x = g undefined g x = do x <- getLine putStrLn x
kmate/HaRe
old/testing/foldDef/DoExpr2_TokOut.hs
bsd-3-clause
96
0
7
42
36
17
19
5
1
import Distribution.Simple main = defaultMainWithHooks simpleUserHooks
nilcons/PrefetchFS
Setup.hs
gpl-3.0
71
0
5
6
14
7
7
2
1
module T9441b where f1 :: Integer -> Integer f1 n | n <= 1 = 1 | otherwise = go n 1 where go 0 r = r go m r = go (m - 1) (r * m) f2 :: Integer -> Integer f2 n = go n 1 where go 0 s = s go p s = go (p - 1) (s * p)
sdiehl/ghc
testsuite/tests/simplCore/should_compile/T9441b.hs
bsd-3-clause
243
0
9
97
149
75
74
11
2
{-# LANGUAGE BangPatterns #-} module Main where import qualified Data.ByteString as S import Data.IORef import Control.Monad makeBs :: Int -> S.ByteString makeBs n = S.replicate n (fromIntegral n) doStuff :: IORef [S.ByteString] -> Int -> IO () doStuff ref n = do let !bs = makeBs n modifyIORef ref (bs:) {-# NOINLINE doStuff #-} undo :: IORef [S.ByteString] -> IO () undo ref = do h <- atomicModifyIORef ref (\(x:xs) -> (xs,x)) S.length h `seq` return () main = do ref <- newIORef [S.empty] let fn n = do doStuff ref n when (rem 5 n /= 0 ) $ undo ref mapM_ fn (take 5000000 $ cycle [1..100]) var <- readIORef ref print $ length var
ezyang/ghc
testsuite/tests/perf/should_run/T7257.hs
bsd-3-clause
691
0
16
175
311
153
158
-1
-1
module T5514 where class Foo a where foo :: a -> a instance (Foo a, Foo b) => Foo (a, b) where foo = foo' () -- foo' :: () -> b -> b foo' es = const id (unitId es) unitId :: () -> () unitId = id
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/typecheck/should_compile/T5514.hs
bsd-3-clause
201
0
7
55
99
53
46
8
1
module Main where import Data.Conduit ((=$), ($$)) import Control.Monad (guard, void) import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader.Class (asks) import Data.Conduit.Find import qualified Data.Conduit.List as DCL import Data.List (isSuffixOf) import System.Environment (getArgs) import System.Posix.Process (executeFile) import Control.Monad.Trans.Resource (runResourceT) import Data.Conduit.Filesystem (sourceDirectoryDeep) main :: IO () main = do [command, dir] <- getArgs case command of "conduit" -> do putStrLn "Running sourceDirectoryDeep from conduit-extra" runResourceT $ sourceDirectoryDeep False dir =$ DCL.filter (".hs" `isSuffixOf`) =$ DCL.mapM_ (liftIO . putStrLn) $$ DCL.sinkNull "find-conduit" -> do putStrLn "Running findFiles from find-conduit" findFiles defaultFindOptions { findFollowSymlinks = False } dir $ do path <- asks entryPath void $ guard (".hs" `isSuffixOf` path) norecurse liftIO $ putStrLn path "find-conduit2" -> do putStrLn "Running findFiles from find-conduit" runResourceT $ sourceFindFiles defaultFindOptions { findFollowSymlinks = False } dir (return ()) =$ DCL.filter ((".hs" `isSuffixOf`) . entryPath . fst) =$ DCL.mapM_ (liftIO . putStrLn . entryPath . fst) $$ DCL.sinkNull "find" -> do putStrLn "Running GNU find" executeFile "find" True [dir, "-name", "*.hs", "-print"] Nothing _ -> putStrLn $ "Unknown command " ++ show command
jwiegley/find-conduit
test/find-hs.hs
mit
1,922
0
19
705
448
242
206
44
5
{-# LANGUAGE DeriveAnyClass, DeriveGeneric, FlexibleContexts, MultiParamTypeClasses #-} {- | Module : System.JBI.Commands.Common Description : How to handle build tools Copyright : (c) Ivan Lazar Miljenovic License : MIT Maintainer : [email protected] -} module System.JBI.Commands.BuildTool where import System.JBI.Commands.Tool import System.JBI.Environment import System.JBI.Tagged import Control.Applicative (liftA2) import Control.Exception (SomeException(SomeException), handle) import Control.Monad (filterM, forM) import Data.Aeson (ToJSON(toJSON)) import Data.List (span) import Data.Maybe (isJust) import Data.String (IsString(..)) import GHC.Generics (Generic) import System.Directory (doesFileExist, getCurrentDirectory, listDirectory) import System.Exit (ExitCode) import System.FilePath (dropTrailingPathSeparator, isDrive, takeDirectory, (</>)) -------------------------------------------------------------------------------- class (Tool bt) => BuildTool bt where -- | Make sure there's nothing in the environment preventing us from -- using this tool. -- -- For example, a minimum version, need another tool installed, etc. -- -- @since 0.2.0.0 canUseCommand :: Env -> Tagged bt CommandPath -> IO Bool canUseCommand _ _ = return True -- | Try and determine the root directory for this project. commandProjectRoot :: Tagged bt CommandPath -> IO (Maybe (Tagged bt ProjectRoot)) hasBuildArtifacts :: Tagged bt ProjectRoot -> IO Bool -- | Ensure's that 'hasBuildArtifacts' is 'True' afterwards; -- i.e. forces this build tool. -- -- The intent for this is \"No build tool is currently being used -- (i.e. 'hasBuildArtifacts' is 'False' for all) so start using -- the one chosen.\" This will not do the equivalent of @stack -- init@ and create project configuration. -- -- Some manual fiddling is allowed after this. -- -- Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandPrepare :: Env -> Tagged bt CommandPath -> IO ExitCode -- | Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandTargets :: Config -> Tagged bt CommandPath -> IO [Tagged bt ProjectTarget] -- | Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandBuild :: Env -> Tagged bt CommandPath -> Maybe (Tagged bt ProjectTarget) -> IO ExitCode -- | Launch a @ghci@ session within the current project. -- -- Takes a list of interpreter arguments. -- -- Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandRepl :: Env -> Tagged bt CommandPath -> Tagged bt Args -> Maybe (Tagged bt ProjectTarget) -> IO ExitCode -- | Remove /all/ build artifacts of using this build tool (that is, -- afterwards 'hasBuildArtifacts' should return 'False'). -- -- Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandClean :: Env -> Tagged bt CommandPath -> IO ExitCode -- | Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandTest :: Env -> Tagged bt CommandPath -> IO ExitCode -- | Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandBench :: Env -> Tagged bt CommandPath -> IO ExitCode -- | Run an external command within this environment. -- -- Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandExec :: Env -> Tagged bt CommandPath -> String -> Args -> IO ExitCode -- | Run an executable component within this environment (building -- it first if required). -- -- Assumes 'canUseBuildTool'. Should be run within 'ProjectRoot'. commandRun :: Env -> Tagged bt CommandPath -> Tagged bt ProjectTarget -> Args -> IO ExitCode -- | Update index of available packages. commandUpdate :: Env -> Tagged bt CommandPath -> IO ExitCode -- | This class exists because of: -- -- a) Distinguish the different Cabal variants -- -- b) Be able to use a wrapper GADT that takes a @proxy bt@ and can -- be an instance of 'BuildTool' but not this. class (BuildTool bt) => NamedTool bt where prettyName :: proxy bt -> String prettyName = nameOfCommand . proxy commandName data ToolInformation bt = ToolInformation { tool :: !String , information :: !(Maybe (BuildUsage bt)) } deriving (Eq, Show, Read, Generic, ToJSON) commandToolInformation :: (NamedTool bt) => Env -> proxy bt -> IO (ToolInformation bt) commandToolInformation env pr = ToolInformation (prettyName pr) <$> commandBuildUsage env data BuildUsage bt = BuildUsage { installation :: !(Installed bt) , usable :: !Bool , project :: !(Maybe (BuildProject bt)) } deriving (Eq, Show, Read, Generic, ToJSON) data BuildProject bt = BuildProject { projectRoot :: !(Tagged bt ProjectRoot) , artifactsPresent :: !Bool } deriving (Eq, Show, Read, Generic, ToJSON) -- | A 'Nothing' indicates that this tool cannot be used for this -- project (i.e. needs configuration). commandBuildUsage :: (BuildTool bt) => Env -> IO (Maybe (BuildUsage bt)) commandBuildUsage env = do mInst <- commandInformation (envConfig env) forM mInst $ \inst -> BuildUsage inst <$> canUseCommand env (path inst) <*> commandBuildProject (path inst) commandBuildProject :: (BuildTool bt) => Tagged bt CommandPath -> IO (Maybe (BuildProject bt)) commandBuildProject cmd = do mroot <- commandProjectRoot cmd forM mroot $ \root -> BuildProject root <$> hasBuildArtifacts root canUseBuildTool :: Maybe (BuildUsage bt) -> Bool canUseBuildTool = maybe False (liftA2 (&&) usable (isJust . project)) -------------------------------------------------------------------------------- newtype ProjectRoot = ProjectRoot { rootPath :: FilePath } deriving (Eq, Ord, Show, Read) instance IsString ProjectRoot where fromString = ProjectRoot instance ToJSON ProjectRoot where toJSON = toJSON . rootPath -- | TODO: determine if this is a library, executable, test or benchmark component. newtype ProjectTarget = ProjectTarget { projectTarget :: String } deriving (Eq, Ord, Show, Read) instance IsString ProjectTarget where fromString = ProjectTarget componentName :: Tagged bt ProjectTarget -> String componentName = safeLast . splitOn ':' . stripTag safeLast :: [[a]] -> [a] safeLast [] = [] safeLast ass = last ass splitOn :: (Eq a) => a -> [a] -> [[a]] splitOn sep = go where go [] = [] go as = case span (/= sep) as of (seg, []) -> seg : [] (seg, _:as') -> seg : go as' -------------------------------------------------------------------------------- -- | If an exception occurs, return 'Nothing' tryIO :: IO (Maybe a) -> IO (Maybe a) tryIO = handle (\SomeException{} -> return Nothing) -- | Recurse up until you find a directory containing a file that -- matches the predicate, returning that directory. recurseUpFindFile :: (FilePath -> Bool) -> IO (Maybe FilePath) recurseUpFindFile p = tryIO $ go . dropTrailingPathSeparator =<< getCurrentDirectory where go dir = do cntns <- listDirectory dir files <- filterM (doesFileExist . (dir </>)) cntns if any p files then return (Just dir) -- We do the base case check here so we can -- actually check the top level directory. else if isDrive dir then return Nothing else go (takeDirectory dir)
ivan-m/jbi
lib/System/JBI/Commands/BuildTool.hs
mit
7,701
0
13
1,783
1,608
864
744
117
3
module GHCJS.DOM.SVGFEColorMatrixElement ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGFEColorMatrixElement.hs
mit
53
0
3
7
10
7
3
1
0
{-# LANGUAGE DisambiguateRecordFields #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} module Turtle (turtleDraw, turtleSimlate, Turtle(..), Command(..)) where import Control.Arrow import GHC.Float (double2Float) import Graphics.Gloss window :: String -> Display window s = InWindow s (500,500) (30,30) turtleDraw :: String -> Turtle -> [Command] -> IO () turtleDraw s it cmds = display (window s) black $ Pictures (execCommands it cmds) turtleSimlate :: String -- title -> Turtle -> s -- initial turtle and initial state -> [Turtle -> s -> (Command, s)] -- commands -> IO () turtleSimlate title initTurtle initState cmds = display (window title) black $ Pictures (simTurtle initTurtle initState cmds) data Turtle = Turtle { _loc :: (Double, Double), _dir :: Double } forward :: Turtle -> Double -> (Double,Double) forward t d = ((*d) . cos &&& (*d) . sin) . _dir $ t floatise :: (Double,Double) -> (Float,Float) floatise (x,y) = (double2Float x, double2Float y) (+:) :: (Double,Double) -> (Double,Double) -> (Double,Double) (a,b) +: (c,d) = (a+c,b+d) data Command = Jump Double | Draw Double | Turn Double | JumpTo (Double, Double) | DrawTo (Double, Double) | SetAng Double | SetState ((Double, Double), Double) | Stay -- TODO :: Better abstraction execCommands :: Turtle -> [Command] -> [Picture] execCommands initTurtle = simTurtle initTurtle undefined . map ( \c -> (\_ _ -> (c, undefined))) -- TODO : Rewrite using State Monad simTurtle :: Turtle -> s -> [Turtle -> s -> (Command, s)] -> [Picture] simTurtle _ _ [] = [] simTurtle !t@(Turtle{..}) s (cFunc:cs) = let (c, nextState) = cFunc t s in case c of (Jump d) -> simTurtle (t{_loc = _loc +: forward t d}) nextState cs (Draw d) -> let newLoc = _loc +: forward t d in (color white . line . map floatise $ [_loc, newLoc]): simTurtle (t{_loc = newLoc}) nextState cs (Turn arg) -> simTurtle (t{_dir = _dir + arg}) nextState cs (JumpTo d) -> simTurtle (t{_loc = d}) nextState cs (DrawTo d) -> (color white . line . map floatise $ [_loc,d]): simTurtle (t{_loc=d}) nextState cs (SetAng ang) -> simTurtle (t{_dir = ang}) nextState cs (SetState (loc,ang)) -> simTurtle (t{_dir=ang, _loc=loc}) nextState cs Stay -> simTurtle t nextState cs
lesguillemets/lsyst.hs
src/Turtle.hs
mit
2,531
0
17
689
1,013
560
453
-1
-1
{-# LANGUAGE TypeFamilies #-} {-| Module : Text.ByoParser.Result Description : Class of parsing results and drivers Copyright : (c) 2016 Nicolas Godbout License : MIT Maintainer : [email protected] Stability : unstable -} module Text.ByoParser.Result ( -- * Partial results PartialResult(..), parsePartial, parsePartialM, feed, break -- Lazy results streams ) where import Control.Monad ( Monad(..) ) -- import Control.Monad.Identity ( Identity ) import Text.ByoParser.Prim ( ParserPrim(..), ResultPrim(..), ErrorPrim ) import Text.ByoParser.Stream ( ByoStream(..), endOfInput ) import Prelude ( ($), undefined, error ) {-| Data type capable of expressing a partial parse result within a 'Monad'. This data type may be used as the result @r@ type of 'ParserPrim'. -} data PartialResult i e r = PDone r | PFail (ErrorPrim e) | PMore (i -> PartialResult i e r) {-| Execute a 'ParserPrim' parser which produces a 'PartialResult' on the given input stream and initial parser state. -} parsePartial :: ParserPrim i e s (PartialResult i e r) r -> i -> s -> PartialResult i e r parsePartial p i s = case runPrim p no ok no ok i s of ResPrimFail e -> PFail e ResPrimDone r -> r where no e _ _ = ResPrimFail e ok r _ _ = ResPrimDone (PDone r) {-| Feed more input to a 'PartialResult'. -} feed :: PartialResult i e r -> i -> PartialResult i e r feed (PDone r) _ = PDone r feed (PFail e) _ = PFail e feed (PMore f) i = f i {-| Parse the given stream with the given initial parsing state, and extract a 'PartialResult' within the associated 'Monad'. -} parsePartialM :: Monad m => ParserPrim i e s (PartialResult i e r) r -> i -> s -> m (PartialResult i e r) parsePartialM = undefined {-| If the input stream is empty, escape to a 'PartialResult', allowing the caller of the parser to supply more input. Otherwise, this parser does nothing. -} break :: ByoStream i => ParserPrim i e s (PartialResult i e r) () break = Prim $ \noC okS noS okC -> runPrim endOfInput (error "unpossible! 'endOfInput' consumed input") (\_ i s -> ResPrimDone $ PMore (\i -> case okS () i s of ResPrimFail e -> PFail e ResPrimDone r -> r ) ) (\_ -> okS ()) (error "unpossible! 'endOfInput' consumed input") {-# INLINE break #-} {- Insert a monadic action into a parser. Whenever the resulting parser is run, the monadic action is executed. -} -- TODO requires the Monad to live in ParserPrim -- runM :: Monad m => m o -> ParserPrim i e s (PartialResult i e m r) o -- runM m = Prim $ \noC okS noS okC -> -- \i s -> m >>= \o -> okS o i s
DrNico/byoparser
Text/ByoParser/Result.hs
mit
2,818
0
17
772
593
319
274
44
2
module Lambency.GameSession ( TimeStep, GameSession, physicsDeltaTime, physicsDeltaUTC, mkGameSession ) where -------------------------------------------------------------------------------- import qualified Control.Wire as W import GHC.Float import Data.Time import Lambency.Types -------------------------------------------------------------------------------- -- The physics framerate in frames per second physicsDeltaTime :: Double physicsDeltaTime = 1.0 / 60.0 physicsDeltaUTC :: NominalDiffTime physicsDeltaUTC = fromRational . toRational $ physicsDeltaTime mkGameSession :: GameSession mkGameSession = W.countSession (double2Float physicsDeltaTime) W.<*> W.pure ()
Mokosha/Lambency
lib/Lambency/GameSession.hs
mit
683
0
8
71
115
68
47
13
1
module System.Himpy.Recipes.WinServices where import System.Himpy.Recipes.Utils import System.Himpy.Mib import System.Himpy.Types import System.Himpy.Logger import System.Himpy.Output.Riemann import Control.Concurrent.STM.TChan (TChan) import qualified Data.Map as M srv_rcp :: [String] -> TChan ([Metric]) -> TChan (String) -> HimpyHost -> IO () srv_rcp srvs chan logchan (Host host comm _) = do names <- snmp_walk_str host comm lanMgrServiceDescr statuses <- snmp_walk_num host comm lanMgrServiceStatus let seen = M.fromList $ zip names statuses let defaults = M.fromList $ zip srvs $ repeat 0.0 let flat = M.assocs $ M.union seen defaults riemann_send chan $ snmp_metrics host "service" flat
pyr/himpy
System/Himpy/Recipes/WinServices.hs
mit
711
0
12
106
240
126
114
16
1
module PWM where import Data.List import Data.List.Split import Numeric.Container import System.Random import Util -- | Data type for nucleotide and nucleotide sequences. data Nucleotide = A | C | G | T deriving (Bounded, Enum, Eq, Ord, Read, Show) type Sequence = [Nucleotide] -- | Accumulates a list of associations (tuple with index and value) to a matrix -- by summing up elements with the same index. assocsToMatrix :: Int -> [((Int, Int), Double)] -> Matrix Double assocsToMatrix l = accum empty (+) where dimension = fromEnum (maxBound :: Nucleotide) + 1 empty = (dimension >< l) (repeat 0) -- | Returns the weighted frequency of characters in a single sequence as a list -- of associations (tuple with index and value). weightedFrequencyToAssocs :: Double -> Sequence -> [((Int, Int), Double)] weightedFrequencyToAssocs w = zipWith f [0..] where f i c = ((fromEnum c, i), w) -- | Returns the frequency of characters in a single sequence as a list of -- associations (tuple with index and value). frequencyToAssocs :: Sequence -> [((Int, Int), Double)] frequencyToAssocs = weightedFrequencyToAssocs 1 -- | Calculates the frequency matrix for the weighted sequences. weightedFrequency :: Int -> [(Double, Sequence)] -> Matrix Double weightedFrequency l = assocsToMatrix l . concatMap (uncurry weightedFrequencyToAssocs) -- | Calculates the frequency matrix for all sequences. frequency :: Int -> [Sequence] -> Matrix Double frequency l = assocsToMatrix l . concatMap (weightedFrequencyToAssocs 1) -- | Introduces pseudocounts. Should be used on the return value of `frequency`. pseudocounts :: Vector Double -> Matrix Double -> Matrix Double pseudocounts v = fromRows . zipWith addConstant (toList v) . toRows -- | Transform a frequency matrix to a probability matrix by normalizing all the -- columns. probability :: Matrix Double -> Matrix Double probability = normalizeColumns -- | Calculates $M_rel$. relativeLog :: Vector Double -> Matrix Double -> Matrix Double relativeLog priors' = fromRows . zipWith f (toList priors') . toRows where f p v = ld (scale (recip p) v) -- | Implements the (+) operator. (<+>) :: Matrix Double -> Sequence -> Double m <+> s = foldl1' (+) $ zipWith (@>) (toColumns m) (map fromEnum s) -- | Calculates the background probability vector by counting all nucleotides. backgroundProbabilities :: [Sequence] -> Vector Double backgroundProbabilities = normalizeVector . accum (constant 0 4) (+) . concatMap toAssoc where toAssoc = map $ \c -> (fromEnum c, 1) -- | Calculates the initial M_rel for the given sequences and given starting -- positions. initialGuess :: Int -> Vector Double -> [(Int, Sequence)]-> Matrix Double initialGuess k p = relativeLog p . probability . pseudocounts p . frequency k . map (uncurry $ cut k) -- | Generates an infinite stream of random start positions. randomStartPositions :: RandomGen g => g -> Int -> Int -> Int -> [[Int]] randomStartPositions g n l k = chunksOf n $ randomRs (1, maximumIndex) g where maximumIndex = l - k + 1 -- vim: set ts=4 sts=4 sw=4 et:
fgrsnau/emgene
src/PWM.hs
mit
3,145
0
11
607
821
441
380
41
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Monad.State.Strict import qualified Control.Monad.State.Lazy as SL import Data.Function (on) import Data.List (nub, nubBy) import qualified Data.Map as Map import qualified Data.Set as Set import qualified MiniSet as MiniSet import qualified Okasaki as Okasaki import Test.QuickCheck import Test.QuickCheck.Function import Criterion.Main -- Just copied from Data.List localNub :: (Eq a) => [a] -> [a] localNub l = nub' l [] where nub' [] _ = [] nub' (x:xs) ls | x `elem` ls = nub' xs ls | otherwise = x : nub' xs (x:ls) -- Taken From Yi ordNub :: (Ord a) => [a] -> [a] ordNub l = go Set.empty l where go _ [] = [] go s (x:xs) = if x `Set.member` s then go s xs else x : go (Set.insert x s) xs -- Using a state monad ordNubState :: (Ord a) => [a] -> [a] ordNubState xs = evalState (filterM f xs) Set.empty where f x = do set <- get if Set.member x set then return False else put (Set.insert x set) >> return True -- Using a lazy state monad ordNubStateLazy :: (Ord a) => [a] -> [a] ordNubStateLazy xs = SL.evalState (filterM f xs) Set.empty where f x = do set <- SL.get if Set.member x set then return False else SL.put (Set.insert x set) >> return True -- Using a state monad with a dlist instead of filterM ordNubStateDlist :: (Ord a) => [a] -> [a] ordNubStateDlist l = evalState (f l id) Set.empty where f [] dlist = return $ dlist [] f (x:xs) dlist = do set <- get if Set.member x set then f xs dlist else put (Set.insert x set) >> f xs (dlist . (x:)) -- Using a lazy state monad with a dlist instead of filterM ordNubStateLazyDlist :: (Ord a) => [a] -> [a] ordNubStateLazyDlist l = SL.evalState (f l id) Set.empty where f [] dlist = return $ dlist [] f (x:xs) dlist = do set <- SL.get if Set.member x set then f xs dlist else SL.put (Set.insert x set) >> f xs (dlist . (x:)) -- | Fast replacement for `nub` when the list elements are only `Eq`, -- not `Ord`, but some parts of the involved data types are `Ord`. -- -- It speeds it up deduping @[a]@ by using a projection function @p :: (a -> b)@, -- where the @b@ is `Ord`erable (in contrast to the @a@), so that the expensive -- /O(n^2)/ @==@ needs to be done only among those elements -- that fall into the same @b@-bucket. -- -- @ordNubByEq p l@: When removing duplicates from @l@, -- -- * the given function @p@ assigns each input to a bucket, -- * it checks whether it is already in the bucket (linear search with @==@). -- -- Especially useful if you have a data type @a@ that for some reason cannot -- have @Ord a@ but only @Eq a@ (such as when it contains data types of -- libraries you use that do not acknowledge the importance of `Ord` for -- performance). -- -- Example: -- -- > data User = -- > User -- > { name :: Text -- > , location :: Location -- from a library that only provdes `Eq Location`, not `Ord` -- > } -- > deriving (Eq, Show) -- no `Ord` because `Location` does not permit it -- > -- > deduplicateUsers :: [User] -> [User] -- > deduplicateUsers = ordNubByEq name -- -- This way, the expensive quadratic @location@ comparison happens only among -- those users that have the same name. -- -- Note that this function serves a different use case than the @containers@ -- function -- -- > nubOrdOn :: (Ord b) => (a -> b) -> [a] -> [a] -- -- because that one removes @a@ elements even when they are different, -- as it has no @Eq a@ constraint and thus cannot fall back to comparing -- quadratic @==@ comparison. -- In the above example, @nubOrd name@ would keep only 1 user named @"Alex"@ -- even if there are multiple Alexes with different @location@. -- If you this more aggressive, projection-only based removal, then -- you must use @nubOrdOn@. ordNubByEq :: (Eq a, Ord b) => (a -> b) -> [a] -> [a] ordNubByEq p l = ordNubBy p (==) l -- | Fast replacement for `nubBy` when the list elements are -- not `Ord`, but some parts of the involved data types are `Ord`. -- -- Like `ordNubByEq`, but with a custom equality function. -- -- Removes duplicates from a list of /unorderable/ elements @[a]@ -- by using an equality function @f :: (a -> a -> Bool)@ (like `nubBy`). -- It speeds it up using a projection function @p :: (a -> b)@, -- as described in `ordNubByEq`. -- @ordNubBy p f l@: When removing duplicates from @l@, -- -- * the first function @p@ assigns the each input to a bucket, -- * the second function @f@ checks whether it is already in the bucket (linear search). -- -- If you find yourself using @ordNubBy p (==)@, use `ordNubByEq` instead. -- Also ckeck whether you want @nubOrdOn@ from containers instead -- (see the `ordNubByEq` docs for the difference). ordNubBy :: (Ord b) => (a -> b) -> (a -> a -> Bool) -> [a] -> [a] ordNubBy p f l = go Map.empty l where go _ [] = [] go m (x:xs) = let b = p x in case b `Map.lookup` m of Nothing -> x : go (Map.insert b [x] m) xs Just bucket | elem_by f x bucket -> go m xs | otherwise -> x : go (Map.insert b (x:bucket) m) xs -- From the Data.List source code. elem_by :: (a -> a -> Bool) -> a -> [a] -> Bool elem_by _ _ [] = False elem_by eq y (x:xs) = y `eq` x || elem_by eq y xs main :: IO () main = defaultMain [ bgroup "simple" [ bench "nub [1]" $ nf nub [1::Int] , bench "nub [1..10]" $ nf nub [1..10::Int] , bench "nub [1..100]" $ nf nub [1..100::Int] , bench "nub [1..1000]" $ nf nub [1..1000::Int] , bench "nub (replicate 1000 1)" $ nf nub (replicate 1000 (1::Int)) , bench "ordNub [1]" $ nf ordNub [1::Int] , bench "ordNub [1..10]" $ nf ordNub [1..10::Int] , bench "ordNub [1..100]" $ nf ordNub [1..100::Int] , bench "ordNub [1..1000]" $ nf ordNub [1..1000::Int] , bench "ordNub (replicate 1000 1)" $ nf ordNub (replicate 1000 (1::Int)) ] , bgroup "" [ bench "benchmarks:" $ nf id 'x' -- just so that I can comment out easily -- , bench "1000 nub" $ nf nub l1000 -- , bench "500 nub" $ nf nub l500 , bench "100 nub" $ nf nub l100 , bench "50 nub" $ nf nub l50 , bench "10 nub" $ nf nub l10 , bench "5 nub" $ nf nub l5 , bench "1 nub" $ nf nub l1 -- , bench "1000 localNub" $ nf localNub l1000 -- , bench "500 localNub" $ nf localNub l500 , bench "100 localNub" $ nf localNub l100 , bench "50 localNub" $ nf localNub l50 , bench "10 localNub" $ nf localNub l10 , bench "5 localNub" $ nf localNub l5 , bench "1 localNub" $ nf localNub l1 -- -- , bench "1000 ordNub" $ nf ordNub l1000 -- -- , bench "500 ordNub" $ nf ordNub l500 , bench "100 ordNub" $ nf ordNub l100 , bench "50 ordNub" $ nf ordNub l50 , bench "10 ordNub" $ nf ordNub l10 , bench "5 ordNub" $ nf ordNub l5 , bench "1 ordNub" $ nf ordNub l1 -- -- , bench "1000 ordNubState" $ nf ordNubState l1000 -- -- , bench "500 ordNubState" $ nf ordNubState l500 , bench "100 ordNubState" $ nf ordNubState l100 , bench "50 ordNubState" $ nf ordNubState l50 , bench "10 ordNubState" $ nf ordNubState l10 , bench "5 ordNubState" $ nf ordNubState l5 , bench "1 ordNubState" $ nf ordNubState l1 -- , bench "1000 ordNubStateLazy" $ nf ordNubStateLazy l1000 -- , bench "500 ordNubStateLazy" $ nf ordNubStateLazy l500 , bench "100 ordNubStateLazy" $ nf ordNubStateLazy l100 , bench "50 ordNubStateLazy" $ nf ordNubStateLazy l50 , bench "10 ordNubStateLazy" $ nf ordNubStateLazy l10 , bench "5 ordNubStateLazy" $ nf ordNubStateLazy l5 , bench "1 ordNubStateLazy" $ nf ordNubStateLazy l1 -- , bench "1000 ordNubStateDlist" $ nf ordNubStateDlist l1000 -- , bench "500 ordNubStateDlist" $ nf ordNubStateDlist l500 , bench "100 ordNubStateDlist" $ nf ordNubStateDlist l100 , bench "50 ordNubStateDlist" $ nf ordNubStateDlist l50 , bench "10 ordNubStateDlist" $ nf ordNubStateDlist l10 , bench "5 ordNubStateDlist" $ nf ordNubStateDlist l5 , bench "1 ordNubStateDlist" $ nf ordNubStateDlist l1 -- , bench "1000 ordNubStateLazyDlist" $ nf ordNubStateLazyDlist l1000 -- , bench "500 ordNubStateLazyDlist" $ nf ordNubStateLazyDlist l500 , bench "100 ordNubStateLazyDlist" $ nf ordNubStateLazyDlist l100 , bench "50 ordNubStateLazyDlist" $ nf ordNubStateLazyDlist l50 , bench "10 ordNubStateLazyDlist" $ nf ordNubStateLazyDlist l10 , bench "5 ordNubStateLazyDlist" $ nf ordNubStateLazyDlist l5 , bench "1 ordNubStateLazyDlist" $ nf ordNubStateLazyDlist l1 , bench "100 MiniSet.ordNub" $ nf MiniSet.ordNub l100 , bench "50 MiniSet.ordNub" $ nf MiniSet.ordNub l50 , bench "10 MiniSet.ordNub" $ nf MiniSet.ordNub l10 , bench "5 MiniSet.ordNub" $ nf MiniSet.ordNub l5 , bench "1 MiniSet.ordNub" $ nf MiniSet.ordNub l1 , bench "100 MiniSet.ordNubStrictAcc" $ nf MiniSet.ordNubStrictAcc l100 , bench "50 MiniSet.ordNubStrictAcc" $ nf MiniSet.ordNubStrictAcc l50 , bench "10 MiniSet.ordNubStrictAcc" $ nf MiniSet.ordNubStrictAcc l10 , bench "5 MiniSet.ordNubStrictAcc" $ nf MiniSet.ordNubStrictAcc l5 , bench "1 MiniSet.ordNubStrictAcc" $ nf MiniSet.ordNubStrictAcc l1 , bench "100 Okasaki.ordNub" $ nf Okasaki.ordNub l100 , bench "50 Okasaki.ordNub" $ nf Okasaki.ordNub l50 , bench "10 Okasaki.ordNub" $ nf Okasaki.ordNub l10 , bench "5 Okasaki.ordNub" $ nf Okasaki.ordNub l5 , bench "1 Okasaki.ordNub" $ nf Okasaki.ordNub l1 , bench "100 Okasaki.ordNubStrictAcc" $ nf Okasaki.ordNubStrictAcc l100 , bench "50 Okasaki.ordNubStrictAcc" $ nf Okasaki.ordNubStrictAcc l50 , bench "10 Okasaki.ordNubStrictAcc" $ nf Okasaki.ordNubStrictAcc l10 , bench "5 Okasaki.ordNubStrictAcc" $ nf Okasaki.ordNubStrictAcc l5 , bench "1 Okasaki.ordNubStrictAcc" $ nf Okasaki.ordNubStrictAcc l1 -- `by` functions -- , bench "1000 nubBy" $ nf (nubBy (\a b -> a `quot` 2 == b `quot` 2) (==)) l1000 -- , bench "500 nubBy" $ nf (nubBy (\a b -> a `quot` 2 == b `quot` 2) (==)) l500 , bench "100 nubBy" $ nf (nubBy (\a b -> a `quot` 2 == b `quot` 2)) l100 , bench "50 nubBy" $ nf (nubBy (\a b -> a `quot` 2 == b `quot` 2)) l50 , bench "10 nubBy" $ nf (nubBy (\a b -> a `quot` 2 == b `quot` 2)) l10 , bench "5 nubBy" $ nf (nubBy (\a b -> a `quot` 2 == b `quot` 2)) l5 , bench "1 nubBy" $ nf (nubBy (\a b -> a `quot` 2 == b `quot` 2)) l1 -- , bench "1000 ordNubBy" $ nf (ordNubBy (`quot` 2) (==)) l1000 -- , bench "500 ordNubBy" $ nf (ordNubBy (`quot` 2) (==)) l500 , bench "100 ordNubBy" $ nf (ordNubBy (`quot` 2) (==)) l100 , bench "50 ordNubBy" $ nf (ordNubBy (`quot` 2) (==)) l50 , bench "10 ordNubBy" $ nf (ordNubBy (`quot` 2) (==)) l10 , bench "5 ordNubBy" $ nf (ordNubBy (`quot` 2) (==)) l5 , bench "1 ordNubBy" $ nf (ordNubBy (`quot` 2) (==)) l1 ] -- Other benchmarks, and what people contributed , bgroup "other" [ bench "nub yitz 1" $ nf nub (2 : replicate 100000 1 ++ [3] :: [Int]) , bench "ordNub yitz 1" $ nf ordNub (2 : replicate 100000 1 ++ [3] :: [Int]) , bench "nub yitz 2" $ nf nub ([3,2,1] ++ take 100000 (cycle [3,2,1]) ++ [4] :: [Int]) , bench "ordNub yitz 2" $ nf ordNub ([3,2,1] ++ take 100000 (cycle [3,2,1]) ++ [4] :: [Int]) ] ] where -- l1000 = concat $ replicbate 10 [1..1000::Int] -- l500 = concat $ replicate 20 [1..500::Int] l100 = concat $ replicate 100 [1..100::Int] l50 = concat $ replicate 200 [1..50::Int] l10 = concat $ replicate 1000 [1..10::Int] l5 = concat $ replicate 2000 [1..5::Int] l1 = concat $ replicate 10000 [1::Int] tests :: IO () tests = mapM_ (quickCheckWith stdArgs{ maxSuccess = 1000, maxSize = 200 }) [ isLikeNub localNub , isLikeNub ordNub , isLikeNub ordNubState , isLikeNub ordNubStateDlist -- ordNubBy tests , property $ \(l :: [(Int, Int)]) -> ordNubBy fst ((>) `on` snd) l == nubBy (\(a,b) (x,y) -> a == x && b > y) l , property $ \(l :: [(Int, Int)], Fun _ f :: Fun Int (Fun Int Bool)) -> let fun x y = f x `apply` y in ordNubBy fst (\(_, b) (_, y) -> b `fun` y) l == nubBy (\(a,b) (x,y) -> a == x && b `fun` y) l ] where isLikeNub f = property (\l -> nub l == f (l :: [Int]))
nh2/haskell-ordnub
ordnub.hs
mit
12,905
0
18
3,474
3,513
1,869
1,644
167
4
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Constellation.Types where import Control.Applicative import Control.Monad.Base import Control.Monad.Error import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Resource data Environment = Environment newtype Constellation a = Constellation { unConstellation :: ResourceT (ReaderT Environment (LoggingT IO)) a } deriving ( Functor, Applicative, Monad, MonadIO, MonadThrow , MonadReader Environment , MonadBase IO , MonadResource ) runConstellation :: Environment -> Constellation a -> IO a runConstellation env = runStdoutLoggingT . flip runReaderT env . runResourceT . unConstellation class Monad m => MonadConstellation m where
ClassyCoding/constellation-server
src/Constellation/Types.hs
mit
875
0
11
221
183
101
82
-1
-1
module Test.Week10 where import Test.Tasty import Test.Tasty.HUnit import Week10 week10 :: TestTree week10 = testGroup "Week 10 - Applicative functors, Part I" [ exercise1 , exercise2 , exercise3 , exercise4 , exercise5 ] exercise1 = testGroup "Exercise 1 - Parser Functor" [ testCase "Example 1 - fmap Parser Just" $ runParser (fmap (+1) posInt) "1234 asdf" @?= Just (1235, " asdf") , testCase "Example 2 - fmap Parser Nothing" $ runParser (fmap (+1) posInt) "ah34 asdf" @?= Nothing ] exercise2 = testGroup "Exercise 2 - Parser Applicative" [] exercise3 = testGroup "Exercise 3 - Parser Applicative test" [ testCase "Example 1 - abParser valid" $ runParser abParser "abcdef" @?= Just (('a', 'b'), "cdef") , testCase "Example 2 - abParser Invalid" $ runParser abParser "aebcdf" @?= Nothing , testCase "Example 3 - abParser_ valid" $ runParser abParser_ "abcdef" @?= Just ((), "cdef") , testCase "Example 4 - abParser_ Invalid" $ runParser abParser_ "aebcdf" @?= Nothing ] exercise4 = testGroup "Exercise 4 - Parser Alternative" [] exercise5 = testGroup "Exercise 5 - intOrUppercase" [ testCase "Example 1" $ runParser intOrUppercase "342abcd" @?= Just ((), "abcd") , testCase "Example 2" $ runParser intOrUppercase "XYZ" @?= Just ((), "YZ") , testCase "Example 3" $ runParser intOrUppercase "foo" @?= Nothing ]
taylor1791/cis-194-spring
test/Test/Week10.hs
mit
1,411
0
12
306
356
185
171
37
1
module Reforest.CompressionSpec where import Test.Hspec import Reforest import qualified Data.Set as Set import Test.HUnit a `shouldBeSubsetOf` b = assertBool (show a ++ " not subset of " ++ show b) (Set.fromList a `Set.isSubsetOf` Set.fromList b) genLangSet = Set.fromList . genLang spec :: Spec spec = do describe "abbreviateNgram" $ do let Right t1 = parseTerm "f(c,c)" let Right t2 = parseTerm "f(c,d)" let g = langToGrammar [t1,t2] let g' = abbreviateNgram (Digram (Con "f" 2) 0 (Con "c" 0)) g it "adds a new production" $ length g' `shouldBe` length g + 1 it "adds a new non-terminal" $ length (nub' (map lhs g')) == 2 it "doesn't change the generated language" $ genLangSet g `shouldBe` genLangSet g'
gebner/reforest
test/Reforest/CompressionSpec.hs
mit
767
0
17
177
283
138
145
19
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE InstanceSigs #-} import Network.HTTP --import Network.HTTP.Conduit import Control.Concurrent.Async import Text.Printf import Control.Exception import System.CPUTime -- loop :: Int -> IO () -- loop i = -- if i == 0 then do -- putStrLn "ALL DONE!!!" -- return () -- else do -- res <- simpleHTTP (getRequest "http://www.jet.com/") -- body <- getResponseBody res -- putStrLn body -- loop (i - 1) loop :: String -> Int -> [IO ()] loop url i = go i [] where go i xs = case i of 0 -> xs i -> go (i - 1) ((simpleHTTP (getRequest url) >>= getResponseBody >>= putStrLn):xs) main::IO () main = do putStrLn "Starting" let url = "http://jet.com/" start <- getCPUTime let x = loop url 10 x <- mapConcurrently id x end <- getCPUTime let diff = (fromIntegral (end - start)) / (10^12) putStrLn (printf "Computation time: %0.3f sec\n" (diff :: Double)) putStrLn "Done" return () --loop 1 --res <- simpleHTTP (getRequest "http://www.jet.com/") --body <- getResponseBody res --putStrLn body
eulerfx/learnfp
http.hs
mit
1,155
0
18
273
287
150
137
25
2
{-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Handler.Models where import Cache import Import hiding (intercalate, (<>)) import Form import Data.List (nub) import SessionState import Data.Monoid import Database.Persist.Types import Database.Persist.Sql import qualified Data.Text as T getModelsR :: Text -> Handler Html getModelsR mu = do showOrNot <- lookupShowAdvices if showOrNot then do (mark' :: [Entity Mark]) <- runDB $ selectList [MarkUrl ==. mu] [LimitTo 1] c <- getCache itModels <- getEModels mu let marks = getMarks c models = getModels c generations = getGenerations c regions = getRegions c lktags = getLkTags c eGens = concat $ containedIn (fmap (lkTagGeneration . entityVal) lktags) g generations textAdvices = getTextAdvices c images = getImages c eitLinks = itModels dEitModels = divideThree eitLinks g = entityKey toMn = T.concat . map markName . map entityVal mn = T.concat $ ["ΠžΠ±Π·ΠΎΡ€Ρ‹ Π±/Ρƒ ", (toMn mark'), " с ΠΏΡ€ΠΎΠ±Π΅Π³ΠΎΠΌ"] mn :: Text (sAdvice':_) <- getRandomSimpleAdvice defaultLayout $ do setTitle $ toHtml mn toWidgetHead [hamlet|<meta name=description content="ΠŸΠΎΠ΄Π΅Ρ€ΠΆΠ°Π½Π½Ρ‹Π΅ #{toHtml $ toMn mark'}: #{modelsToString itModels} - ΠΏΠ»ΡŽΡΡ‹ ΠΈ минусы, Ρ‡Ρ‚ΠΎ ломаСтся">|] $(widgetFile "models") $(fayFile "HomeF") else redirect HomeR succTuple :: forall a b c. (a, b, c) -> (b, c) succTuple (a,b,c) = (b,c) modelsToString = T.intercalate ", " . fmap (unSingle . (\(_,_,x,_,_) -> x))
swamp-agr/carbuyer-advisor
Handler/Models.hs
mit
1,744
0
18
448
490
266
224
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE InstanceSigs #-} module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Control.Monad.Logger (LogSource) -- Used only when in "auth-dummy-login" setting is enabled. import Yesod.Auth.Dummy import Yesod.Auth.OpenId (authOpenId, IdentifierType (Claimed)) import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import qualified Yesod.Core.Unsafe as Unsafe import qualified Data.CaseInsensitive as CI import qualified Data.Text.Encoding as TE import Controllers.Game.Model.GameLobby import Controllers.Game.Model.ServerGame import Wordify.Rules.Dictionary import Wordify.Rules.LetterBag data LocalisedGameSetup = GameSetup {localisedDictionary :: Dictionary , localisedLetterBag :: LetterBag} type LocalisedGameSetups = Map Text LocalisedGameSetup -- | The foundation datatype for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger , localisedGameSetups :: LocalisedGameSetups , gameLobbies :: TVar (Map Text (TVar GameLobby)) , games :: TVar (Map Text ServerGame) } data MenuItem = MenuItem { menuItemLabel :: Text , menuItemRoute :: Route App , menuItemAccessCallback :: Bool } data MenuTypes = NavbarLeft MenuItem | NavbarRight MenuItem -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the following documentation -- for an explanation for this split: -- http://www.yesodweb.com/book/scaffolding-and-the-site-template#scaffolding-and-the-site-template_foundation_and_application_modules -- -- This function also generates the following type synonyms: -- type Handler = HandlerT App IO -- type Widget = WidgetT App IO () mkYesodData "App" $(parseRoutesFile "config/routes") -- | A convenient synonym for creating forms. type Form x = Html -> MForm (HandlerFor App) (FormResult x, Widget) appHeader = do toWidget [hamlet| <div style="padding: 5px 0px 15px 10px;border-bottom: 1px solid #e0e0e0;height: 30px;width: 100%;background: white;z-index: 1000;"> <span> <a href=@{HomeR}> Home | <span> <a href="javascript:gameGameLinkClicked()"> Create Game | <span> <a href="http://www.github.com/happy0/wordify-webapp"> Source Code |] toWidget [julius| var gameGameLinkClicked = function() { $("#create-game-lobby").modal(); }; |] $(widgetFile "game-dialog") where numPlayerOptions = [2..4] -- | A convenient synonym for database access functions. type DB a = forall (m :: * -> *). (MonadIO m) => ReaderT SqlBackend m a -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot approot :: Approot App approot = ApprootRequest $ \app req -> case appRoot $ appSettings app of Nothing -> getApprootText guessApproot app req Just root -> root -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend :: App -> IO (Maybe SessionBackend) makeSessionBackend _ = Just <$> defaultClientSessionBackend 120 -- timeout in minutes "config/client_session_key.aes" -- Yesod Middleware allows you to run code before and after each handler function. -- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks. -- Some users may also want to add the defaultCsrfMiddleware, which: -- a) Sets a cookie with a CSRF token in it. -- b) Validates that incoming write requests include that token in either a header or POST parameter. -- To add it, chain it together with the defaultMiddleware: yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware -- For details, see the CSRF documentation in the Yesod.Core.Handler module of the yesod-core package. yesodMiddleware :: ToTypedContent res => Handler res -> Handler res yesodMiddleware = defaultYesodMiddleware defaultLayout :: Widget -> Handler Html defaultLayout widget = do master <- getYesod mmsg <- getMessage muser <- maybeAuthPair mcurrentRoute <- getCurrentRoute pc <- widgetToPageContent $ do addScriptRemote "http://code.jquery.com/jquery-1.10.2.js" addScriptRemote "http://code.jquery.com/ui/1.11.4/jquery-ui.js" addScriptRemote "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" addStylesheetRemote "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" addStylesheet $ StaticR css_bootstrap_css addStylesheet $ StaticR css_common_css appHeader $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- The page to be redirected to when authentication is required. authRoute :: App -> Maybe (Route App) authRoute _ = Just $ AuthR LoginR isAuthorized :: Route App -- ^ The route the user is visiting. -> Bool -- ^ Whether or not this is a "write" request. -> Handler AuthResult -- Routes not requiring authentication. isAuthorized (AuthR _) _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized -- Default to Authorized for now. isAuthorized _ _ = return Authorized -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent :: Text -- ^ The file extension -> Text -- ^ The MIME content type -> LByteString -- ^ The contents of the file -> Handler (Maybe (Either Text (Route App, [(Text, Text)]))) addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLogIO :: App -> LogSource -> LogLevel -> IO Bool shouldLogIO app _source level = return $ appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger :: App -> IO Logger makeLogger = return . appLogger -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB :: SqlPersistT Handler a -> Handler a runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner :: Handler (DBRunner App, Handler ()) getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest :: App -> Route App loginDest _ = HomeR -- Where to send a user after logout logoutDest :: App -> Route App logoutDest _ = HomeR -- Override the above two destinations when a Referer: header is present redirectToReferer :: App -> Bool redirectToReferer _ = True authenticate :: (MonadHandler m, HandlerSite m ~ App) => Creds App -> m (AuthenticationResult App) authenticate creds = liftHandler $ runDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (Entity uid _) -> return $ Authenticated uid Nothing -> Authenticated <$> insert User { userIdent = credsIdent creds , userPassword = Nothing } -- You can add other plugins like Google Email, email or OAuth here authPlugins :: App -> [AuthPlugin App] authPlugins app = [authOpenId Claimed []] ++ extraAuthPlugins -- Enable authDummy login if enabled. where extraAuthPlugins = [authDummy | appAuthDummyLogin $ appSettings app] -- | Access function to determine if a user is logged in. isAuthenticated :: Handler AuthResult isAuthenticated = do muid <- maybeAuthId return $ case muid of Nothing -> Unauthorized "You must login to access this page" Just _ -> Authorized instance YesodAuthPersist App -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage :: App -> [Lang] -> FormMessage -> Text renderMessage _ _ = defaultFormMessage -- Useful when writing code that is re-usable outside of the Handler context. -- An example is background jobs that send email. -- This can also be useful for writing code that works across multiple Yesod applications. instance HasHttpManager App where getHttpManager :: App -> Manager getHttpManager = appHttpManager unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger -- Note: Some functionality previously present in the scaffolding has been -- moved to documentation in the Wiki. Following are some hopefully helpful -- links: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email -- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain -- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding
Happy0/liscrabble
src/Foundation.hs
gpl-2.0
11,119
0
16
2,559
1,621
876
745
-1
-1
{-# LANGUAGE CPP, MultiParamTypeClasses, TypeSynonymInstances , FlexibleInstances #-} {- | Module : $Header$ Description : Instance of class Logic for SoftFOL. Copyright : (c) Rene Wagner, Klaus Luettich, Uni Bremen 2005-2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable (imports Logic) Instance of class Logic for SoftFOL. -} module SoftFOL.Logic_SoftFOL where import Common.DefaultMorphism import Common.DocUtils import Common.ProofTree import Common.AS_Annotation (makeNamed, SenAttr(..)) import Common.ExtSign import qualified Data.Set (empty) import ATC.ProofTree () import Logic.Logic import SoftFOL.ATC_SoftFOL () import SoftFOL.Sign import SoftFOL.Print import SoftFOL.Conversions import SoftFOL.Morphism import SoftFOL.PrintTPTP () #ifdef UNI_PACKAGE import Common.ProverTools import SoftFOL.ProveSPASS import SoftFOL.ProveHyperHyper #ifndef NOHTTP import SoftFOL.ProveMathServ import SoftFOL.ProveVampire #endif import SoftFOL.ProveDarwin #endif import SoftFOL.ProveMetis instance Pretty Sign where pretty = pretty . signToSPLogicalPart {- | A dummy datatype for the LogicGraph and for identifying the right instances -} data SoftFOL = SoftFOL deriving (Show) instance Language SoftFOL where description _ = "SoftFOL - Softly typed First Order Logic for " ++ "Automated Theorem Proving Systems\n\n" ++ "This logic corresponds to the logic of SPASS, \n" ++ "but the generation of TPTP is also possible.\n" ++ "See http://spass.mpi-sb.mpg.de/\n" ++ "and http://www.cs.miami.edu/~tptp/TPTP/SyntaxBNF.html" instance Logic.Logic.Syntax SoftFOL [TPTP] SFSymbol () () -- default implementation is fine! instance Sentences SoftFOL Sentence Sign SoftFOLMorphism SFSymbol where map_sen SoftFOL _ = return sym_of SoftFOL = singletonList . symOf sym_name SoftFOL = symbolToId print_named SoftFOL = printFormula negation _ = negateSentence -- other default implementations are fine instance StaticAnalysis SoftFOL [TPTP] Sentence () () Sign SoftFOLMorphism SFSymbol () where empty_signature SoftFOL = emptySign is_subsig SoftFOL _ _ = True subsig_inclusion SoftFOL = defaultInclusion basic_analysis SoftFOL = Just (\ (sp, sg, _) -> return (sp, ExtSign sg Data.Set.empty, concatMap (\f -> case f of FormAnno _ (Name n) r t _ -> [ let sen = makeNamed n t in case r of Axiom -> sen Hypothesis -> sen Definition -> sen { isAxiom = False, isDef = True} Assumption -> sen Lemma -> sen Theorem -> sen _ -> sen { isAxiom = False } ] _ -> []) sp)) instance Logic SoftFOL () [TPTP] Sentence () () Sign SoftFOLMorphism SFSymbol () ProofTree where stability _ = Testing #ifdef UNI_PACKAGE provers SoftFOL = unsafeProverCheck "SPASS" "PATH" spassProver #ifndef NOHTTP ++ [mathServBroker, vampire] #endif ++ concatMap (\ b -> unsafeProverCheck (darwinExe b) "PATH" $ darwinProver b) tptpProvers ++ unsafeProverCheck "metis" "PATH" metisProver ++ unsafeProverCheck hyperS "PATH" hyperProver cons_checkers SoftFOL = concatMap (\ b -> unsafeProverCheck (darwinExe b) "PATH" $ darwinConsChecker b) tptpProvers ++ unsafeProverCheck hyperS "PATH" hyperConsChecker #endif
nevrenato/HetsAlloy
SoftFOL/Logic_SoftFOL.hs
gpl-2.0
3,725
0
24
1,002
728
393
335
61
0
{-# OPTIONS -O2 -Wall #-} module Editor.CodeEdit.NextArg(makeAddArgHandler) where import Data.Store.IRef (IRef) import Data.Store.Transaction (Transaction) import Editor.Anchors (ViewTag) import Editor.MonadF (MonadF) import qualified Data.Store.Property as Property import qualified Data.Store.Transaction as Transaction import qualified Editor.CodeEdit.Ancestry as A import qualified Editor.Data as Data import qualified Editor.DataOps as DataOps import qualified Editor.WidgetIds as WidgetIds import qualified Graphics.UI.Bottle.Widget as Widget -- Return the target function to add "next arg" for addNextArgTargetExpression :: MonadF m => A.ExpressionAncestry m -> Transaction.Property ViewTag m (IRef Data.Expression) -> Transaction.Property ViewTag m (IRef Data.Expression) addNextArgTargetExpression (A.AncestryItemApply (A.ApplyParent A.ApplyArg A.Prefix _ parentPtr) : _) _ = parentPtr addNextArgTargetExpression (A.AncestryItemApply (A.ApplyParent A.ApplyFunc A.InfixLeft _ parentPtr) : _) _ = parentPtr addNextArgTargetExpression _ expressionPtr = expressionPtr makeAddArgHandler :: MonadF m => A.ExpressionAncestry m -> Transaction.Property ViewTag m (IRef Data.Expression) -> Transaction ViewTag m (String, Transaction ViewTag m Widget.Id) makeAddArgHandler ancestry expressionPtr = case getNextArg ancestry of Nothing -> return addArg Just holeCandidateI -> do holeCandidate <- Property.get $ Transaction.fromIRef holeCandidateI return $ case holeCandidate of Data.ExpressionHole _ -> ("Move to next arg", return (WidgetIds.fromIRef holeCandidateI)) _ -> addArg where addArg = ("Add next arg", WidgetIds.diveIn . DataOps.callWithArg $ addNextArgTargetExpression ancestry expressionPtr) getNextArg :: A.ExpressionAncestry m -> Maybe (IRef Data.Expression) getNextArg ( A.AncestryItemApply (A.ApplyParent A.ApplyFunc _ apply _) : _) = Just $ Data.applyArg apply getNextArg ( A.AncestryItemApply (A.ApplyParent A.ApplyArg A.Prefix _ _) : A.AncestryItemApply (A.ApplyParent A.ApplyFunc _ parentApply _) : _) = Just $ Data.applyArg parentApply getNextArg _ = Nothing
nimia/bottle
codeedit/Editor/CodeEdit/NextArg.hs
gpl-3.0
2,163
0
18
324
608
322
286
46
3
{-# OPTIONS_GHC -fno-warn-type-defaults #-} module LinearForm where import Data.Ratio import Math.ExpPairs.LinearForm import Math.ExpPairs.RatioInf import Test.Tasty import Test.Tasty.SmallCheck as SC import Test.Tasty.QuickCheck as QC import Instances () extractCoeffs :: Num t => LinearForm t -> (t, t, t) extractCoeffs lf = ( evalLF (1, 0, 0) lf , evalLF (0, 1, 0) lf , evalLF (0, 0, 1) lf ) testPlus :: Rational -> Rational -> Rational -> Rational -> Rational -> Rational -> Bool testPlus a b c d e f = a+d==ad && b+e==be && c+f==cf where l1 = LinearForm a b c l2 = LinearForm d e f (ad, be, cf) = extractCoeffs (l1 + l2) testMinus :: Rational -> Rational -> Rational -> Rational -> Rational -> Rational -> Bool testMinus a b c d e f = a-d==ad && b-e==be && c-f==cf where l1 = LinearForm a b c l2 = LinearForm d e f (ad, be, cf) = extractCoeffs (l1 - l2) testFromInteger :: Integer -> Bool testFromInteger a = evalLF (0, 0, 1) (fromInteger a) == a testSubstitute1 :: LinearForm Rational -> Bool testSubstitute1 a = substituteLF (a, 0, 0) (LinearForm 1 0 0) == a && substituteLF (0, a, 0) (LinearForm 0 1 0) == a && substituteLF (0, 0, a) (LinearForm 0 0 1) == a testSubstitute2 :: LinearForm Rational -> LinearForm Rational -> LinearForm Rational -> LinearForm Rational -> LinearForm Rational -> LinearForm Rational -> LinearForm Rational -> Bool testSubstitute2 a1 a2 b1 b2 c1 c2 lf = substituteLF (a1 + a2, b1 + b2, c1 + c2) lf == substituteLF (a1, b1, c1) lf + substituteLF (a2, b2, c2) lf testNegateRF :: RationalForm Rational -> Integer -> Integer -> Integer -> Bool testNegateRF rf k l m = case evalRF (k, l, m) rf of x@Finite{} -> x == negate (evalRF (k, l, m) (negate rf)) _ -> True testNegateVarsRF :: RationalForm Rational -> Integer -> Integer -> Integer -> Bool testNegateVarsRF rf k l m = evalRF (k, l, m) rf == evalRF (-k, -l, -m) rf testFromIntegerRF :: Integer -> Bool testFromIntegerRF a = evalRF (0, 0, 1) (fromInteger a) == Finite (a % 1) testCheckConstraint :: Integer -> Integer -> Integer -> Constraint Rational -> Bool testCheckConstraint k l m c@(Constraint lf ineq) = (ineq==Strict && isZero || x || y) && (ineq==NonStrict && isZero || not (x && y)) where x = checkConstraint (k, l, m) c y = checkConstraint (k, l, m) (Constraint (negate lf) ineq) isZero = evalLF (fromInteger k, fromInteger l, fromInteger m) lf == 0 testSuite :: TestTree testSuite = testGroup "LinearForm" [ QC.testProperty "plus" testPlus , QC.testProperty "minus" testMinus , SC.testProperty "from integer LF" testFromInteger , QC.testProperty "from integer LF" testFromInteger , QC.testProperty "substitute component" testSubstitute1 , QC.testProperty "substitution is linear" testSubstitute2 , QC.testProperty "negate RF" testNegateRF , QC.testProperty "negate vars RF" testNegateVarsRF , SC.testProperty "from integer RF" testFromIntegerRF , QC.testProperty "from integer RF" testFromIntegerRF , QC.testProperty "constraint" testCheckConstraint ]
Bodigrim/exp-pairs
tests/LinearForm.hs
gpl-3.0
3,107
0
13
646
1,225
647
578
67
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.ITCH.NASDAQ.NASDAQ50.Messages where import Control.DeepSeq import Data.Word import qualified Data.Binary as S import qualified Data.Binary.Get as S import qualified Data.Binary.Put as S import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Short as BS import qualified Data.ByteString.Lazy as L import GHC.Generics type ShortByteString = BS.ShortByteString newtype TimeStamp6 = T6 Word64 deriving (Eq, Ord, Show, Generic) instance NFData TimeStamp6 instance S.Binary TimeStamp6 where get = do a <- fromIntegral <$> S.getWord16be b <- fromIntegral <$> S.getWord32be return . T6 $ (a*(2^32)) + b put (T6 x) = S.putWord16be (fromIntegral $ x `quot` (2^32)) >> S.putWord32be (fromIntegral $ x `mod` (2^32)) class MessageBasics a where stockLocate :: a -> Word16 trackingNumber :: a -> Word16 timestamp :: a -> TimeStamp6 data SystemEvent = SystemEvent { sem_stockLocate :: {-# UNPACK #-} !Word16 , sem_trackingNumber :: {-# UNPACK #-} !Word16 , sem_timestamp :: {-# UNPACK #-} !TimeStamp6 , sem_eventCode :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary SystemEvent where get = SystemEvent <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.get put (SystemEvent a b c d) = S.put a >> S.put b >> S.put c >> S.put d instance MessageBasics SystemEvent where stockLocate = sem_stockLocate trackingNumber = sem_trackingNumber timestamp = sem_timestamp data StockDirectory = StockDirectory { sdm_stockLocate :: {-# UNPACK #-} !Word16 , sdm_trackingNumber :: {-# UNPACK #-} !Word16 , sdm_timestamp :: {-# UNPACK #-} !TimeStamp6 , sdm_stock :: {-# UNPACK #-} !ShortByteString -- 8 , sdm_marketCategory :: {-# UNPACK #-} !Char , sdm_financialStatusIndicator :: {-# UNPACK #-} !Char , sdm_roundLotSize :: {-# UNPACK #-} !Word32 , sdm_roundLotsOnly :: {-# UNPACK #-} !Char , sdm_issueClassification :: {-# UNPACK #-} !Char , sdm_issueSubType :: {-# UNPACK #-} !ShortByteString -- 2 , sdm_authenticity :: {-# UNPACK #-} !Char , sdm_shortSaleThresholdIndicator :: {-# UNPACK #-} !Char , sdm_IPOFlag :: {-# UNPACK #-} !Char , sdm_LULDReferencePriceTier :: {-# UNPACK #-} !Char , sdm_ETPFlag :: {-# UNPACK #-} !Char , sdm_ETPLeverageFactor :: {-# UNPACK #-} !Word32 , sdm_inverseIndicator :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary StockDirectory where get = StockDirectory <$> S.getWord16be <*> S.getWord16be <*> S.get <*> (BS.toShort <$> S.getByteString 8) <*> S.get <*> S.get <*> S.getWord32be <*> S.get <*> S.get <*> (BS.toShort <$> S.getByteString 2) <*> S.get <*> S.get <*> S.get <*> S.get <*> S.get <*> S.getWord32be <*> S.get put = undefined instance MessageBasics StockDirectory where stockLocate = sdm_stockLocate trackingNumber = sdm_trackingNumber timestamp = sdm_timestamp data StockTradingAction = StockTradingAction { sta_stockLocate :: {-# UNPACK #-} !Word16 , sta_trackingNumber :: {-# UNPACK #-} !Word16 , sta_timestamp :: {-# UNPACK #-} !TimeStamp6 , sta_stock :: {-# UNPACK #-} !ShortByteString -- 8 , sta_tradingState :: {-# UNPACK #-} !Char , sta_reserved :: {-# UNPACK #-} !Char , sta_reason :: {-# UNPACK #-} !ShortByteString -- 4 } deriving (Eq, Ord, Show) instance S.Binary StockTradingAction where get = StockTradingAction <$> S.getWord16be <*> S.getWord16be <*> S.get <*> (BS.toShort <$> S.getByteString 8) <*> S.get <*> S.get <*> (BS.toShort <$> S.getByteString 4) put = undefined instance MessageBasics StockTradingAction where stockLocate = sta_stockLocate trackingNumber = sta_trackingNumber timestamp = sta_timestamp data REGSHORestriction = REGSHORestriction { rsr_stockLocate :: {-# UNPACK #-} !Word16 , rsr_trackingNumber :: {-# UNPACK #-} !Word16 , rsr_timestamp :: {-# UNPACK #-} !TimeStamp6 , rsr_stock :: {-# UNPACK #-} !ShortByteString -- 8 , rsr_REGSHOAction :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary REGSHORestriction where get = REGSHORestriction <$> S.getWord16be <*> S.getWord16be <*> S.get <*> (BS.toShort <$> S.getByteString 8) <*> S.get put = undefined instance MessageBasics REGSHORestriction where stockLocate = rsr_stockLocate trackingNumber = rsr_trackingNumber timestamp = rsr_timestamp data MarketParticipantPosition = MarketParticipantPosition { mpp_stockLocate :: {-# UNPACK #-} !Word16 , mpp_trackingNumber :: {-# UNPACK #-} !Word16 , mpp_timestamp :: {-# UNPACK #-} !TimeStamp6 , mpp_mpid :: {-# UNPACK #-} !Word32 , mpp_stock :: {-# UNPACK #-} !ShortByteString -- 8 , mpp_primaryMarketMaker :: {-# UNPACK #-} !Char , mpp_marketMakerMode :: {-# UNPACK #-} !Char , mpp_marketPartcipantState :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary MarketParticipantPosition where get = MarketParticipantPosition <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord32be <*> (BS.toShort <$> S.getByteString 8) <*> S.get <*> S.get <*> S.get put = undefined instance MessageBasics MarketParticipantPosition where stockLocate = mpp_stockLocate trackingNumber = mpp_trackingNumber timestamp = mpp_timestamp -------------------------------------------------------------------------------- data MWCBDeclineLevel = MWCBDeclineLevel { mdl_stockLocate :: {-# UNPACK #-} !Word16 , mdl_trackingNumber :: {-# UNPACK #-} !Word16 , mdl_timestamp :: {-# UNPACK #-} !TimeStamp6 , mdl_level1 :: {-# UNPACK #-} !Word64 -- fixed point 8 decimals , mdl_level2 :: {-# UNPACK #-} !Word64 -- fixed point 8 decimals , mdl_level3 :: {-# UNPACK #-} !Word64 -- fixed point 8 decimals } deriving (Eq, Ord, Show) instance S.Binary MWCBDeclineLevel where get = MWCBDeclineLevel <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.getWord64be <*> S.getWord64be put = undefined instance MessageBasics MWCBDeclineLevel where stockLocate = mdl_stockLocate trackingNumber = mdl_trackingNumber timestamp = mdl_timestamp -------------------------------------------------------------------------------- data MWCBBreach = MWCBBreach { mbr_stockLocate :: {-# UNPACK #-} !Word16 , mbr_trackingNumber :: {-# UNPACK #-} !Word16 , mbr_timestamp :: {-# UNPACK #-} !TimeStamp6 , mbr_breachedLevel :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary MWCBBreach where get = MWCBBreach <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.get put = undefined instance MessageBasics MWCBBreach where stockLocate = mbr_stockLocate trackingNumber = mbr_trackingNumber timestamp = mbr_timestamp -------------------------------------------------------------------------------- data IPOQuotingPeriodUpdate = IPOQuotingPeriodUpdate { qpu_stockLocate :: {-# UNPACK #-} !Word16 , qpu_trackingNumber :: {-# UNPACK #-} !Word16 , qpu_timestamp :: {-# UNPACK #-} !TimeStamp6 , qpu_stock :: {-# UNPACK #-} !ShortByteString -- 8 , qpu_quotationReleaseTime :: {-# UNPACK #-} !Word32 , qpu_quotationReleaseQualifier :: {-# UNPACK #-} !Char , qpu_price :: {-# UNPACK #-} !Word32 -- 4 decimal places } deriving (Eq, Ord, Show) instance S.Binary IPOQuotingPeriodUpdate where get = IPOQuotingPeriodUpdate <$> S.getWord16be <*> S.getWord16be <*> S.get <*> (BS.toShort <$> S.getByteString 8) <*> S.getWord32be <*> S.get <*> S.getWord32be put = undefined instance MessageBasics IPOQuotingPeriodUpdate where stockLocate = qpu_stockLocate trackingNumber = qpu_trackingNumber timestamp = qpu_timestamp -------------------------------------------------------------------------------- data AddOrder = AddOrder { ao_stockLocate :: {-# UNPACK #-} !Word16 , ao_trackingNumber :: {-# UNPACK #-} !Word16 , ao_timestamp :: {-# UNPACK #-} !TimeStamp6 , ao_orderReferenceNumber :: {-# UNPACK #-} !Word64 , ao_buySellIndicator :: {-# UNPACK #-} !Char , ao_shares :: {-# UNPACK #-} !Word32 , ao_stock :: {-# UNPACK #-} !ShortByteString -- 8 , ao_price :: {-# UNPACK #-} !Word32 -- 4 decimal places } deriving (Eq, Ord, Show) instance S.Binary AddOrder where get = AddOrder <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.get <*> S.getWord32be <*> (BS.toShort <$> S.getByteString 8) <*> S.getWord32be put = undefined instance MessageBasics AddOrder where stockLocate = ao_stockLocate trackingNumber = ao_trackingNumber timestamp = ao_timestamp -------------------------------------------------------------------------------- data AddOrderMPIDAttr = AddOrderMPIDAttr { aoa_stockLocate :: {-# UNPACK #-} !Word16 , aoa_trackingNumber :: {-# UNPACK #-} !Word16 , aoa_timestamp :: {-# UNPACK #-} !TimeStamp6 , aoa_orderReferenceNumber :: {-# UNPACK #-} !Word64 , aoa_buySellIndicator :: {-# UNPACK #-} !Char , aoa_shares :: {-# UNPACK #-} !Word32 , aoa_stock :: {-# UNPACK #-} !ShortByteString -- 8 , aoa_price :: {-# UNPACK #-} !Word32 -- 4 decimal places , aoa_attribution :: {-# UNPACK #-} !ShortByteString -- 4 } deriving (Eq, Ord, Show) instance S.Binary AddOrderMPIDAttr where get = AddOrderMPIDAttr <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.get <*> S.getWord32be <*> (BS.toShort <$> S.getByteString 8) <*> S.getWord32be <*> (BS.toShort <$> S.getByteString 4) put = undefined instance MessageBasics AddOrderMPIDAttr where stockLocate = aoa_stockLocate trackingNumber = aoa_trackingNumber timestamp = aoa_timestamp -------------------------------------------------------------------------------- data OrderExecuted = OrderExecuted { oe_stockLocate :: {-# UNPACK #-} !Word16 , oe_trackingNumber :: {-# UNPACK #-} !Word16 , oe_timestamp :: {-# UNPACK #-} !TimeStamp6 , oe_orderReferenceNumber :: {-# UNPACK #-} !Word64 , oe_executedShares :: {-# UNPACK #-} !Word32 , oe_matchNumber :: {-# UNPACK #-} !Word64 } deriving (Eq, Ord, Show) instance S.Binary OrderExecuted where get = OrderExecuted <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.getWord32be <*> S.getWord64be put = undefined instance MessageBasics OrderExecuted where stockLocate = oe_stockLocate trackingNumber = oe_trackingNumber timestamp = oe_timestamp -------------------------------------------------------------------------------- data OrderExecutedWithPrice = OrderExecutedWithPrice { oewp_stockLocate :: {-# UNPACK #-} !Word16 , oewp_trackingNumber :: {-# UNPACK #-} !Word16 , oewp_timestamp :: {-# UNPACK #-} !TimeStamp6 , oewp_orderReferenceNumber :: {-# UNPACK #-} !Word64 , oewp_executedShares :: {-# UNPACK #-} !Word32 , oewp_matchNumber :: {-# UNPACK #-} !Word64 , oewp_printable :: {-# UNPACK #-} !Char , oewp_executionPrice :: {-# UNPACK #-} !Word32 } deriving (Eq, Ord, Show) instance S.Binary OrderExecutedWithPrice where get = OrderExecutedWithPrice <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.getWord32be <*> S.getWord64be <*> S.get <*> S.getWord32be put = undefined instance MessageBasics OrderExecutedWithPrice where stockLocate = oewp_stockLocate trackingNumber = oewp_trackingNumber timestamp = oewp_timestamp -------------------------------------------------------------------------------- data OrderCancel = OrderCancel { oc_stockLocate :: {-# UNPACK #-} !Word16 , oc_trackingNumber :: {-# UNPACK #-} !Word16 , oc_timestamp :: {-# UNPACK #-} !TimeStamp6 , oc_orderReferenceNumber :: {-# UNPACK #-} !Word64 , oc_cancelledShares :: {-# UNPACK #-} !Word32 } deriving (Eq, Ord, Show) instance S.Binary OrderCancel where get = OrderCancel <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.getWord32be put = undefined instance MessageBasics OrderCancel where stockLocate = oc_stockLocate trackingNumber = oc_trackingNumber timestamp = oc_timestamp -------------------------------------------------------------------------------- data OrderDelete = OrderDelete { od_stockLocate :: {-# UNPACK #-} !Word16 , od_trackingNumber :: {-# UNPACK #-} !Word16 , od_timestamp :: {-# UNPACK #-} !TimeStamp6 , od_orderReferenceNumber :: {-# UNPACK #-} !Word64 } deriving (Eq, Ord, Show) instance S.Binary OrderDelete where get = OrderDelete <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be put = undefined instance MessageBasics OrderDelete where stockLocate = od_stockLocate trackingNumber = od_trackingNumber timestamp = od_timestamp -------------------------------------------------------------------------------- data OrderReplace = OrderReplace { or_stockLocate :: {-# UNPACK #-} !Word16 , or_trackingNumber :: {-# UNPACK #-} !Word16 , or_timestamp :: {-# UNPACK #-} !TimeStamp6 , or_originalOrderReferenceNumber :: {-# UNPACK #-} !Word64 , or_newOrderReferenceNumber :: {-# UNPACK #-} !Word64 , or_shares :: {-# UNPACK #-} !Word32 , or_price :: {-# UNPACK #-} !Word32 -- 4 decimal places } deriving (Eq, Ord, Show) instance S.Binary OrderReplace where get = OrderReplace <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.getWord64be <*> S.getWord32be <*> S.getWord32be put = undefined instance MessageBasics OrderReplace where stockLocate = or_stockLocate trackingNumber = or_trackingNumber timestamp = or_timestamp -------------------------------------------------------------------------------- data Trade = Trade { t_stockLocate :: {-# UNPACK #-} !Word16 , t_trackingNumber :: {-# UNPACK #-} !Word16 , t_timestamp :: {-# UNPACK #-} !TimeStamp6 , t_orderReferenceNumber :: {-# UNPACK #-} !Word64 , t_buySellIndicator :: {-# UNPACK #-} !Char , t_shares :: {-# UNPACK #-} !Word32 , t_stock :: {-# UNPACK #-} !ShortByteString -- 8 , t_price :: {-# UNPACK #-} !Word32 -- 4 decimal places , t_matchNumer :: {-# UNPACK #-} !Word64 } deriving (Eq, Ord, Show) instance S.Binary Trade where get = Trade <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.get <*> S.getWord32be <*> (BS.toShort <$> S.getByteString 8) <*> S.getWord32be <*> S.getWord64be put = undefined instance MessageBasics Trade where stockLocate = t_stockLocate trackingNumber = t_trackingNumber timestamp = t_timestamp -------------------------------------------------------------------------------- data CrossTrade = CrossTrade { ct_stockLocate :: {-# UNPACK #-} !Word16 , ct_trackingNumber :: {-# UNPACK #-} !Word16 , ct_timestamp :: {-# UNPACK #-} !TimeStamp6 , ct_shares :: {-# UNPACK #-} !Word64 , ct_stock :: {-# UNPACK #-} !ShortByteString -- 8 , ct_price :: {-# UNPACK #-} !Word32 -- 4 decimal places , ct_matchNumber :: {-# UNPACK #-} !Word64 , ct_crossType :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary CrossTrade where get = CrossTrade <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> (BS.toShort <$> S.getByteString 8) <*> S.getWord32be <*> S.getWord64be <*> S.get put = undefined instance MessageBasics CrossTrade where stockLocate = ct_stockLocate trackingNumber = ct_trackingNumber timestamp = ct_timestamp -------------------------------------------------------------------------------- data BrokenTrade = BrokenTrade { bt_stockLocate :: {-# UNPACK #-} !Word16 , bt_trackingNumber :: {-# UNPACK #-} !Word16 , bt_timestamp :: {-# UNPACK #-} !TimeStamp6 , bt_matchNumber :: {-# UNPACK #-} !Word64 } deriving (Eq, Ord, Show) instance S.Binary BrokenTrade where get = BrokenTrade <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be put = undefined instance MessageBasics BrokenTrade where stockLocate = bt_stockLocate trackingNumber = bt_trackingNumber timestamp = bt_timestamp -------------------------------------------------------------------------------- data NOII = NOII { noii_stockLocate :: {-# UNPACK #-} !Word16 , noii_trackingNumber :: {-# UNPACK #-} !Word16 , noii_timestamp :: {-# UNPACK #-} !TimeStamp6 , noii_paidShares :: {-# UNPACK #-} !Word64 , noii_imbalanceShares :: {-# UNPACK #-} !Word64 , noii_imbalanceDirection :: {-# UNPACK #-} !Char , noii_stock :: {-# UNPACK #-} !ShortByteString , noii_farPrice :: {-# UNPACK #-} !Word32 , noii_nearPrice :: {-# UNPACK #-} !Word32 , noii_currentReferencePrice :: {-# UNPACK #-} !Word32 , noii_crossType :: {-# UNPACK #-} !Char , noii_priceVariationIndicator :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary NOII where get = NOII <$> S.getWord16be <*> S.getWord16be <*> S.get <*> S.getWord64be <*> S.getWord64be <*> S.get <*> (BS.toShort <$> S.getByteString 8) <*> S.getWord32be <*> S.getWord32be <*> S.getWord32be <*> S.get <*> S.get put = undefined instance MessageBasics NOII where stockLocate = noii_stockLocate trackingNumber = noii_trackingNumber timestamp = noii_timestamp -------------------------------------------------------------------------------- data RPII = RPII { rpii_stockLocate :: {-# UNPACK #-} !Word16 , rpii_trackingNumber :: {-# UNPACK #-} !Word16 , rpii_timestamp :: {-# UNPACK #-} !TimeStamp6 , rpii_stock :: {-# UNPACK #-} !ShortByteString , rpii_interestFlag :: {-# UNPACK #-} !Char } deriving (Eq, Ord, Show) instance S.Binary RPII where get = RPII <$> S.getWord16be <*> S.getWord16be <*> S.get <*> (BS.toShort <$> S.getByteString 8) <*> S.get put = undefined instance MessageBasics RPII where stockLocate = rpii_stockLocate trackingNumber = rpii_trackingNumber timestamp = rpii_timestamp -------------------------------------------------------------------------------- data Other = Other { oth_content :: ShortByteString } deriving (Eq, Ord, Show) instance S.Binary Other where get = Other . BS.toShort . L.toStrict <$> S.getRemainingLazyByteString put = undefined data Message = MSystemEvent SystemEvent | MStockDirectory StockDirectory | MStockTradingAction StockTradingAction | MREGSHORestriction REGSHORestriction | MMarketParticipantPosition MarketParticipantPosition | MMWCBDeclineLevel MWCBDeclineLevel | MMWCBBreach MWCBBreach | MIPOQuotingPeriodUpdate IPOQuotingPeriodUpdate | MAddOrder AddOrder | MAddOrderMPIDAttr AddOrderMPIDAttr | MOrderExecuted OrderExecuted | MOrderExecutedWithPrice OrderExecutedWithPrice | MOrderCancel OrderCancel | MOrderDelete OrderDelete | MOrderReplace OrderReplace | MTrade Trade | MCrossTrade CrossTrade | MBrokenTrade BrokenTrade | MNOII NOII | MRPII RPII | MOther Char Other deriving (Eq, Ord, Show) instance S.Binary Message where get = do (c :: Char) <- S.get case c of 'S' -> MSystemEvent <$> S.get 'R' -> MStockDirectory <$> S.get 'H' -> MStockTradingAction <$> S.get 'Y' -> MREGSHORestriction <$> S.get 'L' -> MMarketParticipantPosition <$> S.get 'V' -> MMWCBDeclineLevel <$> S.get 'W' -> MMWCBBreach <$> S.get 'K' -> MIPOQuotingPeriodUpdate <$> S.get 'A' -> MAddOrder <$> S.get 'F' -> MAddOrderMPIDAttr <$> S.get 'E' -> MOrderExecuted <$> S.get 'C' -> MOrderExecutedWithPrice <$> S.get 'X' -> MOrderCancel <$> S.get 'D' -> MOrderDelete <$> S.get 'U' -> MOrderReplace <$> S.get 'P' -> MTrade <$> S.get 'Q' -> MCrossTrade <$> S.get 'B' -> MBrokenTrade <$> S.get 'I' -> MNOII <$> S.get 'N' -> MRPII <$> S.get _ -> MOther c <$> S.get put = undefined instance MessageBasics Message where stockLocate (MSystemEvent x) = stockLocate x stockLocate (MStockDirectory x) = stockLocate x stockLocate (MStockTradingAction x) = stockLocate x stockLocate (MREGSHORestriction x) = stockLocate x stockLocate (MMarketParticipantPosition x) = stockLocate x stockLocate (MMWCBDeclineLevel x) = stockLocate x stockLocate (MMWCBBreach x) = stockLocate x stockLocate (MIPOQuotingPeriodUpdate x) = stockLocate x stockLocate (MAddOrder x) = stockLocate x stockLocate (MAddOrderMPIDAttr x) = stockLocate x stockLocate (MOrderExecuted x) = stockLocate x stockLocate (MOrderExecutedWithPrice x) = stockLocate x stockLocate (MOrderCancel x) = stockLocate x stockLocate (MOrderDelete x) = stockLocate x stockLocate (MOrderReplace x) = stockLocate x stockLocate (MTrade x) = stockLocate x stockLocate (MCrossTrade x) = stockLocate x stockLocate (MBrokenTrade x) = stockLocate x stockLocate (MNOII x) = stockLocate x stockLocate (MRPII x) = stockLocate x trackingNumber = undefined timestamp = undefined messageType :: Message -> Char messageType (MSystemEvent _) = 'S' messageType (MStockDirectory _) = 'R' messageType (MStockTradingAction _) = 'H' messageType (MREGSHORestriction _) = 'Y' messageType (MMarketParticipantPosition _) = 'L' messageType (MMWCBDeclineLevel _) = 'V' messageType (MMWCBBreach _) = 'W' messageType (MIPOQuotingPeriodUpdate _) = 'K' messageType (MAddOrder _) = 'A' messageType (MAddOrderMPIDAttr _) = 'F' messageType (MOrderExecuted _) = 'E' messageType (MOrderExecutedWithPrice _) = 'C' messageType (MOrderCancel _) = 'X' messageType (MOrderDelete _) = 'D' messageType (MOrderReplace _) = 'U' messageType (MTrade _) = 'P' messageType (MCrossTrade _) = 'Q' messageType (MBrokenTrade _) = 'B' messageType (MNOII _) = 'I' messageType (MRPII _) = 'N'
mjansen/itch
src/Data/ITCH/NASDAQ/NASDAQ50/Messages.hs
gpl-3.0
25,112
0
23
7,404
5,028
2,774
2,254
471
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeSynonymInstances #-} -------------------------------------------------------------------------------- -- | -- Module : Tct.Method.Timeout -- Copyright : (c) Martin Avanzini <[email protected]>, -- Georg Moser <[email protected]>, -- Andreas Schnabl <[email protected]>, -- License : LGPL (see COPYING) -- -- Maintainer : Martin Avanzini <[email protected]> -- Stability : unstable -- Portability : unportable -- -- This module provides processors that may timeout. -------------------------------------------------------------------------------- module Tct.Method.Timeout ( timeout , timeoutProcessor , TOProof (..) , Timeout) where -- import Control.Concurrent.Utils (timedKill) import Control.Monad.Trans (liftIO) import qualified System.Timeout as TO import Tct.Utils.Xml as Xml import Tct.Processor.Args import qualified Tct.Processor.Args as A import qualified Tct.Processor.Standard as S import Tct.Processor.Args.Instances hiding (Processor) import Termlib.Utils (paragraph) import qualified Tct.Processor as P import Text.PrettyPrint.HughesPJ hiding (brackets) data Timeout p = Timeout -- | @timeout sec t@ -- aborts processor @t@ after @sec@ seconds. timeout :: P.Processor p => Int -> (P.InstanceOf p) -> S.ProcessorInstance (Timeout p) timeout i proc = S.StdProcessor Timeout `S.withArgs` (Nat i :+: proc) timeoutProcessor :: S.StdProcessor (Timeout P.AnyProcessor) timeoutProcessor = S.StdProcessor Timeout data TOProof p = TimedOut Int | TOProof Int (P.ProofOf p) instance P.Processor p => S.Processor (Timeout p) where type ProofOf (Timeout p) = TOProof p type ArgumentsOf (Timeout p) = Arg Nat :+: Arg (Proc p) description _ = ["The processor either returns the result of the given processor" , " or, if the timeout elapses, aborts the computation and returns MAYBE."] name Timeout = "timeout" arguments _ = arg { A.name = "timeout" , A.description = "The timeout in seconds" } :+: arg { A.name = "processor" , A.description = "The processor to apply with timeout"} instanceName tinst = P.instanceName inst ++ " (timeout of " ++ show i ++ " seconds)" where Nat i :+: inst = S.processorArgs tinst solve tinst prob = do io <- P.mkIO $ P.apply inst prob r <- liftIO $ TO.timeout (i * (10^(6 :: Int))) io return $ case r of Just p -> TOProof i (P.result p) Nothing -> TimedOut i where Nat i :+: inst = S.processorArgs tinst instance P.ComplexityProof (P.ProofOf p) => P.ComplexityProof (TOProof p) where pprintProof (TOProof _ p) mde = P.pprintProof p mde pprintProof (TimedOut i) _ = paragraph ("Computation stopped due to timeout after " ++ show (double (fromIntegral i)) ++ " seconds.") answer (TOProof _ p) = P.answer p answer (TimedOut _) = P.TimeoutAnswer toXml (TOProof i p) = Xml.elt "timeout" [] [Xml.elt "seconds" [] [Xml.text $ show (double (fromIntegral i))] , Xml.elt "subProof" [] [P.toXml p]] toXml (TimedOut i) = Xml.elt "timeout" [] [Xml.text $ show (double (fromIntegral i))]
mzini/TcT
source/Tct/Method/Timeout.hs
gpl-3.0
3,818
0
15
1,064
877
473
404
61
1
module Crepuscolo.Highlight.DSL ( (|||) , inside , region , match , keyword ) where import Crepuscolo.Highlight import Text.Regex.PCRE ((=~), getAllMatches) (|||) :: Highlighter -> Highlighter -> Highlighter a ||| b = a . b inside :: String -> Highlighter -> Highlighter inside group highlighter = undefined region :: String -> String -> String -> Highlighter region group start end = undefined match :: String -> String -> Highlighter match group regex = make where make (Group elements) = Group $ map make elements make (Content string) = Group $ map match matches where match (True, piece) = Highlight Match group (Content piece) match (False, piece) = Content piece matches = split string (getAllMatches (string =~ regex) :: [(Int, Int)]) make x = x keyword :: String -> [String] -> String -> Highlighter keyword group names keywordRegex = make where make (Group elements) = Group $ map make elements make (Content string) = Group $ map keyword pieces where keyword w = if w `elem` names then Highlight Keyword group (Content w) else Content w pieces = concat $ flip map spaced $ \s -> if s =~ "\\s" then [s] else map snd $ split s (getAllMatches (s =~ keywordRegex) :: [(Int, Int)]) where spaced = concat $ map (filter (not . null) . tail) (string =~ "(\\s+)?([^\\s]+)?(\\s+)?" :: [[String]]) make x = x -- This function splits a string based on a getAllMatches result with start and -- offset, the result is a list of tuples where the Bool indicates if the -- String was a match or not. split :: String -> [(Int, Int)] -> [(Bool, String)] split string matches = get 0 string matches where get _ "" [] = [] get _ string [] = [(False, string)] get current string ((0, length) : next) = let (this, tail) = splitAt length string in (True, this) : get length tail next get current string ((start, length) : next) = let (before, tail) = splitAt (start - current) string (this, tail') = splitAt length tail in (False, before) : (True, this) : get (start + length) tail' next
meh/crepuscolo
src/Crepuscolo/Highlight/DSL.hs
gpl-3.0
2,403
0
17
779
804
434
370
52
5
module Base.InputHandler(keyDown, keyUp, handleEvents) where import qualified SDL keyDown :: SDL.Scancode -> [SDL.Scancode] -> Bool keyDown = elem keyUp :: SDL.Scancode -> [SDL.Scancode] -> Bool keyUp = notElem press :: SDL.Scancode -> [SDL.Scancode] -> [SDL.Scancode] press sym [] = [sym] press sym (x:xs) = if x == sym then (x:xs) else x : press sym xs release :: SDL.Scancode -> [SDL.Scancode] -> [SDL.Scancode] release _ [] = [] release sym (x:xs) = if x == sym then xs else x : release sym xs handleEvents :: (MonadIO m) => [SDL.Scancode] -> m (Bool,[SDL.Scancode]) handleEvents keysDown = do event <- SDL.pollEvent case event of Nothing -> return (False,keysDown) Just ev -> case SDL.eventPayload ev of SDL.QuitEvent -> return (True,keysDown) SDL.KeyboardEvent _ SDL.KeyDown _ False (SDL.Keysym sym _ _) -> handleEvents $ press sym keysDown SDL.KeyboardEvent _ SDL.KeyUp _ False (SDL.Keysym sym _ _) -> handleEvents $ release sym keysDown _ -> handleEvents keysDown
mdietz94/asteroids
src/Base/InputHandler.hs
gpl-3.0
1,073
0
16
253
437
230
207
24
5
; Copyright (C) 2009 Bhanu Chetlapalli ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. ; ; ========================================================================= ; ; This File is a part of the Holy Cow Operating System, which is written and ; maintained by Bhanu Kalyan Chetlapalli <[email protected]>. ; ; This contains the include definitions for accessing the hard disk in ; order to load the third stage of the bootloader. ; Define the hard disk controler IDs %define HARD_DISK_PRIMARY_CONTROLER 0x01F0 %define HARD_DISK_SECONDARY_CONTROLER 0x0170 ; Note that this will read sectors without any limit %define HD_CTRLR_READ_SECTORS 0x20 %define HD_CTRLR_WRITE_SECTORS 0x30 ; List of Registers on the hard disk controller, which control what data we ; want to retrieve from the controller and which device %define PIOREG_DATA_WORD 0 %define PIOREG_SECTOR_BYTE 2 %define PIOREG_LBA_LOW_BYTE 3 %define PIOREG_LBA_MID_BYTE 4 %define PIOREG_LBA_HIGH_BYTE 5 %define PIOREG_DEVICE_BYTE 6 %define PIOREG_COMMAND_BYTE 7 ; Define the various locations that can be written to, to access the ; harddisk internal registers %define HDPC_DATA_WORD (HARD_DISK_PRIMARY_CONTROLER + PIOREG_DATA_WORD) %define HDPC_SECTOR_BYTE (HARD_DISK_PRIMARY_CONTROLER + PIOREG_SECTOR_BYTE) %define HDPC_LBA_LOW_BYTE (HARD_DISK_PRIMARY_CONTROLER + PIOREG_LBA_LOW_BYTE) %define HDPC_LBA_MID_BYTE (HARD_DISK_PRIMARY_CONTROLER + PIOREG_LBA_MID_BYTE) %define HDPC_LBA_HIGH_BYTE (HARD_DISK_PRIMARY_CONTROLER + PIOREG_LBA_HIGH_BYTE) %define HDPC_DEVICE_BYTE (HARD_DISK_PRIMARY_CONTROLER + PIOREG_DEVICE_BYTE) %define HDPC_COMMAND_BYTE (HARD_DISK_PRIMARY_CONTROLER + PIOREG_COMMAND_BYTE) %define HDSC_DATA_WORD (HARD_DISK_SECONDARY_CONTROLER + PIOREG_DATA_WORD) %define HDSC_SECTOR_BYTE (HARD_DISK_SECONDARY_CONTROLER + PIOREG_SECTOR_BYTE) %define HDSC_LBA_LOW_BYTE (HARD_DISK_SECONDARY_CONTROLER + PIOREG_LBA_LOW_BYTE) %define HDSC_LBA_MID_BYTE (HARD_DISK_SECONDARY_CONTROLER + PIOREG_LBA_MID_BYTE) %define HDSC_LBA_HIGH_BYTE (HARD_DISK_SECONDARY_CONTROLER + PIOREG_LBA_HIGH_BYTE) %define HDSC_DEVICE_BYTE (HARD_DISK_SECONDARY_CONTROLER + PIOREG_DEVICE_BYTE) %define HDSC_COMMAND_BYTE (HARD_DISK_SECONDARY_CONTROLER + PIOREG_COMMAND_BYTE)
chbhanukalyan/hcos
src/boot/harddisk.hs
gpl-3.0
2,864
158
19
395
995
535
460
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.IAM.ListGroupsForUser -- 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) -- -- Lists the groups the specified user belongs to. -- -- You can paginate the results using the 'MaxItems' and 'Marker' -- parameters. -- -- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroupsForUser.html AWS API Reference> for ListGroupsForUser. -- -- This operation returns paginated results. module Network.AWS.IAM.ListGroupsForUser ( -- * Creating a Request listGroupsForUser , ListGroupsForUser -- * Request Lenses , lgfuMarker , lgfuMaxItems , lgfuUserName -- * Destructuring the Response , listGroupsForUserResponse , ListGroupsForUserResponse -- * Response Lenses , lgfursMarker , lgfursIsTruncated , lgfursResponseStatus , lgfursGroups ) where import Network.AWS.IAM.Types import Network.AWS.IAM.Types.Product import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'listGroupsForUser' smart constructor. data ListGroupsForUser = ListGroupsForUser' { _lgfuMarker :: !(Maybe Text) , _lgfuMaxItems :: !(Maybe Nat) , _lgfuUserName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListGroupsForUser' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lgfuMarker' -- -- * 'lgfuMaxItems' -- -- * 'lgfuUserName' listGroupsForUser :: Text -- ^ 'lgfuUserName' -> ListGroupsForUser listGroupsForUser pUserName_ = ListGroupsForUser' { _lgfuMarker = Nothing , _lgfuMaxItems = Nothing , _lgfuUserName = pUserName_ } -- | Use this parameter only when paginating results and only after you -- receive a response indicating that the results are truncated. Set it to -- the value of the 'Marker' element in the response you received to inform -- the next call about where to start. lgfuMarker :: Lens' ListGroupsForUser (Maybe Text) lgfuMarker = lens _lgfuMarker (\ s a -> s{_lgfuMarker = a}); -- | Use this only when paginating results to indicate the maximum number of -- items you want in the response. If there are additional items beyond the -- maximum you specify, the 'IsTruncated' response element is 'true'. -- -- This parameter is optional. If you do not include it, it defaults to -- 100. Note that IAM might return fewer results, even when there are more -- results available. If this is the case, the 'IsTruncated' response -- element returns 'true' and 'Marker' contains a value to include in the -- subsequent call that tells the service where to continue from. lgfuMaxItems :: Lens' ListGroupsForUser (Maybe Natural) lgfuMaxItems = lens _lgfuMaxItems (\ s a -> s{_lgfuMaxItems = a}) . mapping _Nat; -- | The name of the user to list groups for. lgfuUserName :: Lens' ListGroupsForUser Text lgfuUserName = lens _lgfuUserName (\ s a -> s{_lgfuUserName = a}); instance AWSPager ListGroupsForUser where page rq rs | stop (rs ^. lgfursIsTruncated) = Nothing | isNothing (rs ^. lgfursMarker) = Nothing | otherwise = Just $ rq & lgfuMarker .~ rs ^. lgfursMarker instance AWSRequest ListGroupsForUser where type Rs ListGroupsForUser = ListGroupsForUserResponse request = postQuery iAM response = receiveXMLWrapper "ListGroupsForUserResult" (\ s h x -> ListGroupsForUserResponse' <$> (x .@? "Marker") <*> (x .@? "IsTruncated") <*> (pure (fromEnum s)) <*> (x .@? "Groups" .!@ mempty >>= parseXMLList "member")) instance ToHeaders ListGroupsForUser where toHeaders = const mempty instance ToPath ListGroupsForUser where toPath = const "/" instance ToQuery ListGroupsForUser where toQuery ListGroupsForUser'{..} = mconcat ["Action" =: ("ListGroupsForUser" :: ByteString), "Version" =: ("2010-05-08" :: ByteString), "Marker" =: _lgfuMarker, "MaxItems" =: _lgfuMaxItems, "UserName" =: _lgfuUserName] -- | Contains the response to a successful ListGroupsForUser request. -- -- /See:/ 'listGroupsForUserResponse' smart constructor. data ListGroupsForUserResponse = ListGroupsForUserResponse' { _lgfursMarker :: !(Maybe Text) , _lgfursIsTruncated :: !(Maybe Bool) , _lgfursResponseStatus :: !Int , _lgfursGroups :: ![Group] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListGroupsForUserResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lgfursMarker' -- -- * 'lgfursIsTruncated' -- -- * 'lgfursResponseStatus' -- -- * 'lgfursGroups' listGroupsForUserResponse :: Int -- ^ 'lgfursResponseStatus' -> ListGroupsForUserResponse listGroupsForUserResponse pResponseStatus_ = ListGroupsForUserResponse' { _lgfursMarker = Nothing , _lgfursIsTruncated = Nothing , _lgfursResponseStatus = pResponseStatus_ , _lgfursGroups = mempty } -- | When 'IsTruncated' is 'true', this element is present and contains the -- value to use for the 'Marker' parameter in a subsequent pagination -- request. lgfursMarker :: Lens' ListGroupsForUserResponse (Maybe Text) lgfursMarker = lens _lgfursMarker (\ s a -> s{_lgfursMarker = a}); -- | A flag that indicates whether there are more items to return. If your -- results were truncated, you can make a subsequent pagination request -- using the 'Marker' request parameter to retrieve more items. Note that -- IAM might return fewer than the 'MaxItems' number of results even when -- there are more results available. We recommend that you check -- 'IsTruncated' after every call to ensure that you receive all of your -- results. lgfursIsTruncated :: Lens' ListGroupsForUserResponse (Maybe Bool) lgfursIsTruncated = lens _lgfursIsTruncated (\ s a -> s{_lgfursIsTruncated = a}); -- | The response status code. lgfursResponseStatus :: Lens' ListGroupsForUserResponse Int lgfursResponseStatus = lens _lgfursResponseStatus (\ s a -> s{_lgfursResponseStatus = a}); -- | A list of groups. lgfursGroups :: Lens' ListGroupsForUserResponse [Group] lgfursGroups = lens _lgfursGroups (\ s a -> s{_lgfursGroups = a}) . _Coerce;
olorin/amazonka
amazonka-iam/gen/Network/AWS/IAM/ListGroupsForUser.hs
mpl-2.0
7,103
0
14
1,516
991
587
404
112
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionCommitments.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) -- -- Retrieves a list of commitments contained within the specified region. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionCommitments.list@. module Network.Google.Resource.Compute.RegionCommitments.List ( -- * REST Resource RegionCommitmentsListResource -- * Creating a Request , regionCommitmentsList , RegionCommitmentsList -- * Request Lenses , rclReturnPartialSuccess , rclOrderBy , rclProject , rclFilter , rclRegion , rclPageToken , rclMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionCommitments.list@ method which the -- 'RegionCommitmentsList' request conforms to. type RegionCommitmentsListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "commitments" :> QueryParam "returnPartialSuccess" Bool :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] CommitmentList -- | Retrieves a list of commitments contained within the specified region. -- -- /See:/ 'regionCommitmentsList' smart constructor. data RegionCommitmentsList = RegionCommitmentsList' { _rclReturnPartialSuccess :: !(Maybe Bool) , _rclOrderBy :: !(Maybe Text) , _rclProject :: !Text , _rclFilter :: !(Maybe Text) , _rclRegion :: !Text , _rclPageToken :: !(Maybe Text) , _rclMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionCommitmentsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rclReturnPartialSuccess' -- -- * 'rclOrderBy' -- -- * 'rclProject' -- -- * 'rclFilter' -- -- * 'rclRegion' -- -- * 'rclPageToken' -- -- * 'rclMaxResults' regionCommitmentsList :: Text -- ^ 'rclProject' -> Text -- ^ 'rclRegion' -> RegionCommitmentsList regionCommitmentsList pRclProject_ pRclRegion_ = RegionCommitmentsList' { _rclReturnPartialSuccess = Nothing , _rclOrderBy = Nothing , _rclProject = pRclProject_ , _rclFilter = Nothing , _rclRegion = pRclRegion_ , _rclPageToken = Nothing , _rclMaxResults = 500 } -- | Opt-in for partial success behavior which provides partial results in -- case of failure. The default value is false. rclReturnPartialSuccess :: Lens' RegionCommitmentsList (Maybe Bool) rclReturnPartialSuccess = lens _rclReturnPartialSuccess (\ s a -> s{_rclReturnPartialSuccess = a}) -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the -- \`creationTimestamp\` field in reverse chronological order (newest -- result first). Use this to sort resources like operations so that the -- newest operation is returned first. Currently, only sorting by \`name\` -- or \`creationTimestamp desc\` is supported. rclOrderBy :: Lens' RegionCommitmentsList (Maybe Text) rclOrderBy = lens _rclOrderBy (\ s a -> s{_rclOrderBy = a}) -- | Project ID for this request. rclProject :: Lens' RegionCommitmentsList Text rclProject = lens _rclProject (\ s a -> s{_rclProject = a}) -- | A filter expression that filters resources listed in the response. The -- expression must specify the field name, a comparison operator, and the -- value that you want to use for filtering. The value must be a string, a -- number, or a boolean. The comparison operator must be either \`=\`, -- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute -- Engine instances, you can exclude instances named \`example-instance\` -- by specifying \`name != example-instance\`. You can also filter nested -- fields. For example, you could specify \`scheduling.automaticRestart = -- false\` to include instances only if they are not scheduled for -- automatic restarts. You can use filtering on nested fields to filter -- based on resource labels. To filter on multiple expressions, provide -- each separate expression within parentheses. For example: \`\`\` -- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\") -- \`\`\` By default, each expression is an \`AND\` expression. However, -- you can include \`AND\` and \`OR\` expressions explicitly. For example: -- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel -- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\` rclFilter :: Lens' RegionCommitmentsList (Maybe Text) rclFilter = lens _rclFilter (\ s a -> s{_rclFilter = a}) -- | Name of the region for this request. rclRegion :: Lens' RegionCommitmentsList Text rclRegion = lens _rclRegion (\ s a -> s{_rclRegion = a}) -- | Specifies a page token to use. Set \`pageToken\` to the -- \`nextPageToken\` returned by a previous list request to get the next -- page of results. rclPageToken :: Lens' RegionCommitmentsList (Maybe Text) rclPageToken = lens _rclPageToken (\ s a -> s{_rclPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than \`maxResults\`, Compute -- Engine returns a \`nextPageToken\` that can be used to get the next page -- of results in subsequent list requests. Acceptable values are \`0\` to -- \`500\`, inclusive. (Default: \`500\`) rclMaxResults :: Lens' RegionCommitmentsList Word32 rclMaxResults = lens _rclMaxResults (\ s a -> s{_rclMaxResults = a}) . _Coerce instance GoogleRequest RegionCommitmentsList where type Rs RegionCommitmentsList = CommitmentList type Scopes RegionCommitmentsList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient RegionCommitmentsList'{..} = go _rclProject _rclRegion _rclReturnPartialSuccess _rclOrderBy _rclFilter _rclPageToken (Just _rclMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy RegionCommitmentsListResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionCommitments/List.hs
mpl-2.0
7,583
0
20
1,660
831
495
336
120
1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE GeneralizedNewtypeDeriving, TypeSynonymInstances, FlexibleInstances, UnicodeSyntax #-} module Calculator where import ExprT as E import Parser (parseExp) import StackVM as S eval ∷ ExprT β†’ Integer eval (E.Lit n) = n eval (E.Mul x y) = eval x * eval y eval (E.Add x y) = eval x + eval y evalStr ∷ String β†’ Maybe Integer evalStr = fmap eval . parseExp E.Lit E.Add E.Mul class Expr a where lit ∷ Integer β†’ a mul ∷ a β†’ a β†’ a add ∷ a β†’ a β†’ a instance Expr ExprT where lit = E.Lit add = E.Add mul = E.Mul reify ∷ ExprT β†’ ExprT reify = id instance Expr Integer where lit = id add = (+) mul = (*) instance Expr Bool where lit = (<0) add = (||) mul = (&&) newtype Mod7 = Mod7 Integer deriving (Eq, Show, Enum, Ord, Real, Integral, Num) newtype MinMax = MinMax Integer deriving (Eq, Show, Ord) instance Expr MinMax where lit = MinMax add = min mul = max instance Expr Mod7 where lit = Mod7 add i j = (i + j) `mod` 7 mul i j = (i * j) `mod` 7 testExp ∷ Expr a β‡’ Maybe a testExp = parseExp lit add mul "(3 * -4) + 5" testInteger ∷ Maybe Integer testInteger = testExp testBool ∷ Maybe Bool testBool = testExp testMM ∷ Maybe MinMax testMM = testExp testSat ∷ Maybe Mod7 testSat = testExp instance Expr Program where lit a = [S.PushI a] add a b = a ++ b ++ [S.Mul] mul a b = a ++ b ++ [S.Add] compile ∷ String β†’ Maybe S.Program compile = parseExp lit add mul evalCode ∷ String β†’ Maybe (Either String S.StackVal) evalCode = fmap stackVM . parseExp lit add mul exprTFold ∷ (Integer β†’ t) β†’ (t β†’ t β†’ t) β†’ (t β†’ t β†’ t) β†’ ExprT β†’ t exprTFold f _ _ (E.Lit i) = f i exprTFold f g h (E.Add e1 e2) = g (exprTFold f g h e1) (exprTFold f g h e2) exprTFold f g h (E.Mul e1 e2) = h (exprTFold f g h e1) (exprTFold f g h e2) eval2 ∷ ExprT β†’ Integer eval2 = exprTFold id (+) (*) numLiterals ∷ ExprT β†’ Integer numLiterals = exprTFold (const 1) (+) (+)
spanners/cis194
05-type-classes/calculator.hs
unlicense
2,051
0
10
510
886
474
412
66
1
module Main where import Control.Concurrent import AIM.OpenAuth import AIM.Client import AIM.Boss import AIM.Oscar import System.IO getScreenName :: IO (String) getScreenName = do putStr "AIM Screen Name> " hFlush stdout getLine getPassword :: IO (String) getPassword = do putStr "AIM Password> " hFlush stdout hSetEcho stdout False password <- getLine hSetEcho stdout False putChar '\n' return password getAppKey :: IO (String) getAppKey = do putStrLn "An Open AIM Developer key is required: http://developer.aim.com/manageKeys.jsp" putStr "Open AIM Key> " hFlush stdout getLine start_aim :: IO () start_aim = do putStrLn "Haskell AIM Client - OSCAR Protocol" appKey <- getAppKey screenName <- getScreenName password <- getPassword let clientInfo = AIMClientInfo 1 "HaskellClient" appKey result <- aim_open_auth clientInfo screenName password case result of Just info -> do boss_result <- aim_boss_session clientInfo info case boss_result of Just si -> aim_oscar_login si Nothing -> putStrLn "Unable to authenticate with BOSS server." Nothing -> return () main :: IO () main = do start_aim
chrismoos/haskell-aim-client
src/Main.hs
apache-2.0
1,145
8
15
211
326
150
176
45
3
{- Copyright 2010-2012 Cognimeta Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Cgm.Prelude ( counting, --module Prelude.Plus, module Control.Applicative, module Control.Arrow, module Control.Monad, module Control.Exception, module Control.Category, module Data.Traversable, module Data.Foldable, module Data.Monoid, module Data.List, module Data.Function, module Data.Ord, module Prelude, module Cgm.Control.Combinators, module Cgm.Control.InFunctor, module Cgm.Data.Tagged ) where --import Prelude () import Prelude hiding ( catch, ioError, appendFile, foldr, all, and, any, concat, concatMap, elem, foldl, foldr1, notElem, or, mapM, sequence, mapM_, sequence_, foldl1, maximum, minimum, product, sum, id,(.)) import Control.Applicative import Control.Arrow import Control.Exception import Control.Monad hiding ( mapM,sequence,forM,mapM_,sequence_,forM_,msum,Monad(..),(=<<),Functor(..)) import Data.Traversable import Data.Foldable import Data.Monoid hiding (Sum(..)) import Data.List hiding ( foldr,all,and,any,concat,concatMap,elem,foldl,foldr1 , notElem,or,foldl1,maximum,minimum,product,sum,find,foldl' , maximumBy,minimumBy,mapAccumL,mapAccumR,null , (++),map,(!!),break,cycle,drop,dropWhile,filter , head,init,iterate,last,length,lookup,repeat,replicate , reverse,scanl,scanl1,scanr,scanr1,span,splitAt,tail,take , takeWhile,unzip,unzip3,zip,zip3,zipWith,zipWith3,lines , unlines,unwords,words ) import Data.Function hiding ((.),($),const,flip,id) import Data.Ord (comparing) --import Prelude.Plus hiding (Sum, dup) import Control.Category import Cgm.Control.Combinators import Cgm.Control.InFunctor import Cgm.Data.Tagged {-# INLINE counting #-} counting :: (Num a, Enum a) => a -> [a] counting a = [0 .. pred a]
Cognimeta/cognimeta-utils
src/Cgm/Prelude.hs
apache-2.0
2,373
0
7
397
571
379
192
47
1
{- | Module : Bio.Motions.Callback.Periodic Description : Contains the Periodic callback transformer License : Apache Stability : experimental Portability : unportable -} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} module Bio.Motions.Callback.Periodic ( CallbackPeriod , Periodic(..) ) where import Bio.Motions.Callback.Class import Bio.Motions.Callback.Serialisation import Data.Proxy import GHC.TypeLits import GHC.Generics import Control.DeepSeq -- |The interval between successive recomputations of a 'Callback' 'cb', when transformed -- using the 'Periodic' callback transformer type family CallbackPeriod cb :: Nat -- |Transforms a 'Callback' 'cb' into a 'Callback' which is run every 'CallbackPeriod cb' steps. data Periodic cb = PeriodicValue { periodicValue :: !cb } -- ^The value of 'cb' is present right now | PeriodicWait { periodicWait :: !Int } -- ^The value will be computed in 'periodicWait' steps. deriving (Eq, Generic, NFData) instance Show cb => Show (Periodic cb) where show (PeriodicValue v) = show v show _ = "---" instance CallbackSerialisable cb => CallbackSerialisable (Periodic cb) where serialiseCallback name (PeriodicValue v) = serialiseCallback name v serialiseCallback _ _ = Nothing -- | Note: The leading '_' is dropped from the base callback's name, if present. instance (Callback mode cb, KnownNat (CallbackPeriod cb), CmpNat 0 (CallbackPeriod cb) ~ 'LT) => Callback mode (Periodic cb) where callbackName _ = case callbackName (Proxy :: Proxy cb) of '_' : name -> name name -> name {-# INLINEABLE callbackName #-} runCallback = fmap PeriodicValue . runCallback {-# INLINE runCallback #-} -- |Updates the value of the callback only once in 'CallbackPeriod cb' steps. updateCallback repr (PeriodicWait 1) _ = runCallback repr updateCallback _ (PeriodicWait n) _ = pure . PeriodicWait $ n - 1 updateCallback repr (PeriodicValue cb) move | period == 1 = PeriodicValue <$> updateCallback repr cb move | otherwise = pure $ PeriodicWait period where period = fromInteger $ natVal (Proxy :: Proxy (CallbackPeriod cb)) {-# INLINEABLE updateCallback #-}
Motions/motions
src/Bio/Motions/Callback/Periodic.hs
apache-2.0
2,571
0
13
539
473
256
217
46
0