code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DeriveGeneric #-} module Models.ComicList (ComicList(..)) where import BasicPrelude import Data.Aeson (FromJSON(..), ToJSON(..)) import GHC.Generics (Generic) import Models.ComicSummary (ComicSummary) data ComicList = ComicList { available :: Int , items :: [ComicSummary] } deriving (Show, Generic) instance FromJSON ComicList instance ToJSON ComicList
nicolashery/example-marvel-haskell
Models/ComicList.hs
Haskell
mit
414
module Language.UHC.JScript.Assorted where import Language.UHC.JScript.ECMA.String import Language.UHC.JScript.Types import Language.UHC.JScript.Primitives alert :: String -> IO () alert = _alert . toJS foreign import js "alert(%*)" _alert :: JSString -> IO ()
kjgorman/melchior
Language/UHC/JScript/Assorted.hs
Haskell
mit
266
module Settings.Packages.Cabal where import GHC import Expression cabalPackageArgs :: Args cabalPackageArgs = package cabal ? -- Cabal is a rather large library and quite slow to compile. Moreover, we -- build it for stage0 only so we can link ghc-pkg against it, so there is -- little reason to spend the effort to optimize it. stage0 ? builder Ghc ? arg "-O0"
izgzhen/hadrian
src/Settings/Packages/Cabal.hs
Haskell
mit
380
module Language.Brainfuck.Py2Bf.Bfprim ( Bfprim (..) , isBfprimNonIO , isBfWhile , BfState , runPrim , runPrimIO ) where import Data.Word (Word8) import Data.Functor ((<$>)) import Codec.Binary.UTF8.String (decode, encode) data Bfprim = BfIncr | BfDecr | BfNext | BfPrev | BfPut | BfGet | BfWhile [Bfprim] deriving Eq instance Show Bfprim where show BfIncr = "+" show BfDecr = "-" show BfNext = ">" show BfPrev = "<" show BfPut = "." show BfGet = "," show (BfWhile bf) = '[' : concatMap show bf ++ "]" showList = (++) . concatMap show instance Read Bfprim where readsPrec _ str = case snd (parse str) of bfprim:_ -> [(bfprim, "")] _ -> [] readList str = [(snd (parse str), "")] parse :: String -> (String, [Bfprim]) parse ('+':bf) = (BfIncr:) <$> parse bf parse ('-':bf) = (BfDecr:) <$> parse bf parse ('>':bf) = (BfNext:) <$> parse bf parse ('<':bf) = (BfPrev:) <$> parse bf parse ('.':bf) = (BfPut:) <$> parse bf parse (',':bf) = (BfGet:) <$> parse bf parse ('[':bf) = (\(s, bff) -> (BfWhile bff:) <$> parse s) (parse bf) parse (']':bf) = (bf, []) parse (_:bf) = parse bf parse [] = ("", []) isBfprimNonIO :: Bfprim -> Bool isBfprimNonIO BfPut = False isBfprimNonIO BfGet = False isBfprimNonIO (BfWhile bf) = all isBfprimNonIO bf isBfprimNonIO _ = True isBfWhile :: Bfprim -> Bool isBfWhile (BfWhile _) = True isBfWhile _ = False type BfState = ([Word8], Word8, [Word8], [Word8], [Word8]) runPrim :: [Bfprim] -> BfState -> Either String BfState runPrim (BfIncr:bf) (xs, x, ys, os, is) = runPrim bf (xs, x + 1, ys, os, is) runPrim (BfDecr:bf) (xs, x, ys, os, is) = runPrim bf (xs, x - 1, ys, os, is) runPrim (BfNext:bf) (xs, x, [], os, is) = runPrim bf (x:xs, 0, [], os, is) runPrim (BfNext:bf) (xs, x, y:ys, os, is) = runPrim bf (x:xs, y, ys, os, is) runPrim (BfPrev:_) ([], _, _, _, _) = Left negativeAddressError runPrim (BfPrev:bf) (x:xs, y, ys, os, is) = runPrim bf (xs, x, y:ys, os, is) runPrim (BfWhile _:bf) s@(_, 0, _, _, _) = runPrim bf s runPrim bf@(BfWhile bff:_) s = runPrim bff s >>= runPrim bf runPrim (BfPut:bf) (xs, x, ys, os, is) = runPrim bf (xs, x, ys, os ++ [x], is) runPrim (BfGet:bf) (xs, _, ys, os, []) = runPrim bf (xs, 0, ys, os, []) runPrim (BfGet:bf) (xs, _, ys, os, i:is) = runPrim bf (xs, i, ys, os, is) runPrim [] s = Right s runPrimIO :: [Bfprim] -> BfState -> IO BfState runPrimIO (BfIncr:bf) (xs, x, ys, os, is) = runPrimIO bf (xs, x + 1, ys, os, is) runPrimIO (BfDecr:bf) (xs, x, ys, os, is) = runPrimIO bf (xs, x - 1, ys, os, is) runPrimIO (BfNext:bf) (xs, x, [], os, is) = runPrimIO bf (x:xs, 0, [], os, is) runPrimIO (BfNext:bf) (xs, x, y:ys, os, is) = runPrimIO bf (x:xs, y, ys, os, is) runPrimIO (BfPrev:_) ([], _, _, _, _) = error negativeAddressError runPrimIO (BfPrev:bf) (x:xs, y, ys, os, is) = runPrimIO bf (xs, x, y:ys, os, is) runPrimIO (BfWhile _:bf) s@(_, 0, _, _, _) = runPrimIO bf s runPrimIO bf@(BfWhile bff:_) s = runPrimIO bff s >>= runPrimIO bf runPrimIO (BfPut:bf) (xs, x, ys, os, is) | x > 0xbf = putStr (decode os) >> runPrimIO bf (xs, x, ys, [x], is) | null os || l == 5 && 0xfb < h && h <= 0xff || l == 4 && 0xf7 < h && h <= 0xfb || l == 3 && 0xef < h && h <= 0xf7 || l == 2 && 0xdf < h && h <= 0xef || l == 1 && 0xc1 < h && h <= 0xdf = putStr str >> runPrimIO bf (xs, x, ys, [], is) | otherwise = runPrimIO bf (xs, x, ys, os ++ [x], is) where str = decode (os ++ [x]) l = length os h = head os runPrimIO (BfGet:bf) (xs, _, ys, os, []) = encode . return <$> getChar >>= \inp -> case inp of [] -> runPrimIO bf (xs, 0, ys, os, []) i:is -> runPrimIO bf (xs, i, ys, os, is) runPrimIO (BfGet:bf) (xs, _, ys, os, i:is) = runPrimIO bf (xs, i, ys, os, is) runPrimIO [] s = return s negativeAddressError :: String negativeAddressError = "negative address access"
itchyny/py2bf.hs
Language/Brainfuck/Py2Bf/Bfprim.hs
Haskell
mit
4,210
module Control.Flower.Functor ( module Control.Flower.Functor.Lazy, module Control.Flower.Functor.Strict ) where import Control.Flower.Functor.Lazy import Control.Flower.Functor.Strict
expede/flower
src/Control/Flower/Functor.hs
Haskell
mit
190
module Chattp.Relay.Config where import System.Environment (getEnv, lookupEnv) import qualified Data.ByteString.Lazy.Char8 as BS data Family = Inet | Unix deriving (Show,Eq) data RelayConfig = RelayConfig { publishHost :: String, publishPort :: Int, publishBasePath :: String, publishChanIdParam :: String, myHost :: String, myFamily :: Family, myPort :: Int, brokerHost :: String, brokerPort :: Int, nThreads :: Int, publishURL :: BS.ByteString } deriving Show publish_host_env_var, publish_port_env_var, publish_base_path_env_var :: String publish_chan_id_env_var, broker_addr_env_var, broker_port_env_var, nthreads_env_var :: String self_bind_addr_env_var, self_bind_family_env_var, self_bind_port_env_var :: String publish_host_env_var = "CHATTP_MSGRELAY_PUBLISH_HOST" publish_port_env_var = "CHATTP_MSGRELAY_PUBLISH_PORT" publish_base_path_env_var = "CHATTP_MSGRELAY_PUBLISH_BASE_PATH" publish_chan_id_env_var = "CHATTP_MSGRELAY_PUBLISH_CHAN_ID_PARAMETER" broker_addr_env_var = "CHATTP_MSGBROKER_MSGRELAY_BIND_ADDR" broker_port_env_var = "CHATTP_MSGBROKER_MSGRELAY_BIND_PORT" self_bind_addr_env_var = "CHATTP_MESG_RELAY_ADDR" self_bind_family_env_var = "CHATTP_MESG_RELAY_FAMILY" self_bind_port_env_var = "CHATTP_MESG_RELAY_PORT" nthreads_env_var = "CHATTP_MSGRELAY_NUMBER_THREADS" makeConfig :: IO RelayConfig makeConfig = do -- web server info p_host <- getEnv publish_host_env_var p_port_raw <- lookupEnv publish_port_env_var p_base <- getEnv publish_base_path_env_var p_chanid <- getEnv publish_chan_id_env_var let p_port = maybe 80 read p_port_raw -- self bind info my_family_raw <- getEnv self_bind_family_env_var let my_family = case my_family_raw of "UNIX" -> Unix "INET" -> Inet my_addr <- getEnv self_bind_addr_env_var my_port <- if my_family == Inet then fmap read (getEnv self_bind_port_env_var) else return 0 -- broker info broker_addr <- getEnv broker_addr_env_var broker_port <- if my_family == Inet then fmap read (getEnv broker_port_env_var) else return 0 -- nthreads_raw <- lookupEnv nthreads_env_var let nthreads = maybe 2 read nthreads_raw return RelayConfig { publishHost = p_host, publishPort = p_port, publishBasePath = p_base, publishChanIdParam = p_chanid, myHost = my_addr, myFamily = my_family, myPort = my_port, brokerHost = broker_addr, brokerPort = broker_port, nThreads = nthreads, publishURL = BS.pack $ "http://" ++ p_host ++ p_base ++ "/pub?" ++ p_chanid ++ "=" }
Spheniscida/cHaTTP
mesg-relay/Chattp/Relay/Config.hs
Haskell
mit
2,842
{-# LANGUAGE TemplateHaskell #-} module Parser where import Control.Monad import Control.Monad.State import Control.Lens import Data.List import Data.Map as M hiding (map) type RuleName = String type RulePair = (RuleName, Pattern) type RuleMap = M.Map RuleName Pattern data RepTime = RTInt Integer -- n-times | RTInf -- infinity deriving (Show,Eq) manyTimes :: Pattern -> Pattern manyTimes a = Repetition a (RTInt 1) RTInf -- + anyTimes :: Pattern -> Pattern anyTimes a = Repetition a (RTInt 0) RTInf -- * optional :: Pattern -> Pattern optional a = Repetition a (RTInt 0) (RTInt 1) -- ? rtZerop :: RepTime -> Bool rtZerop (RTInt 0) = True rtZerop _ = False rtPred :: RepTime -> RepTime rtPred (RTInt 0) = RTInt 0 rtPred (RTInt n) = RTInt (n - 1) rtPred RTInf = RTInf data Pattern = Atom String | Rule String | RuleX String -- rule that only do matching but ignoring the result -- TODO: RepetitionL : Lazy repetition | Repetition Pattern RepTime RepTime -- pat, minTime, maxTime | Choice [Pattern] | Sequence [Pattern] | NegativeLookahead Pattern | PositiveLookahead Pattern deriving (Eq) instance Show Pattern where show (Atom x) = show x show (Rule x) = x show (RuleX x) = "@" ++ x show (Repetition p a b) = show p ++ mark a b where mark (RTInt 0) (RTInt 1) = "?" mark (RTInt 1) RTInf = "+" mark (RTInt 0) RTInf = "*" mark (RTInt l) (RTInt u) = "{" ++ show l ++ "," ++ show u ++ "}" mark _ _ = undefined show (Choice xs) = intercalate " | " $ map show xs show (Sequence xs) = unwords $ map show xs show (NegativeLookahead p) = '!' : show p show (PositiveLookahead p) = '=' : show p data MatchData = MAtom String | MList [MatchData] | MPair (RuleName, MatchData) deriving (Eq) instance Show MatchData where show (MPair (name,md)) = "{" ++ show md ++ "}:" ++ name show (MList xs) = join $ map show xs show (MAtom x) = x isMPair :: MatchData -> Bool isMPair (MPair (_,_)) = True isMPair _ = False getMPair :: MatchData -> (RuleName, MatchData) getMPair (MPair (r,m)) = (r,m) getMPair _ = error "not a MPair" isMList :: MatchData -> Bool isMList (MList _) = True isMList _ = False getMList :: MatchData -> [MatchData] getMList (MList xs) = xs getMList _ = error "not a MList" isMAtom :: MatchData -> Bool isMAtom (MAtom _) = True isMAtom _ = False getMAtom :: MatchData -> String getMAtom (MAtom s) = s getMAtom _ = error "not a MAtom" mInspect :: MatchData -> String mInspect (MPair (n,md)) = n ++ "=>" ++ mInspect md mInspect (MList xs) = "[" ++ intercalate "/" (map mInspect xs) ++ "]" mInspect (MAtom s) = s mToString :: MatchData -> String mToString (MPair (_,md)) = mToString md mToString (MList xs) = join $ map mToString xs mToString (MAtom s) = s data ParsingState = ParsingState { _restString :: String, _ruleMap :: RuleMap } makeLenses ''ParsingState type ParseState = State ParsingState type ParseResult = ParseState (Maybe MatchData) getRestString :: ParseState String getRestString = liftM (view restString) get putRestString :: String -> ParseState () putRestString st = modify (restString .~ st) -- read only state getRuleMap :: ParseState RuleMap getRuleMap = liftM (view ruleMap) get lookupRule :: RuleName -> ParseState (Maybe Pattern) lookupRule name = liftM (M.lookup name) getRuleMap parseI :: Pattern -> ParseResult parseI (Atom x) = do rest <- getRestString let len = length x if len <= length rest && take len rest == x then do putRestString (drop len rest) return $ Just $ MAtom x else return Nothing parseI (Rule name) = do pat' <- lookupRule name case pat' of Nothing -> return Nothing Just pat -> do result <- parseI pat case result of Nothing -> return Nothing Just m -> return $ Just $ MPair (name, m) parseI (RuleX name) = do pat' <- lookupRule name case pat' of Nothing -> return Nothing Just pat -> do result <- parseI pat case result of Nothing -> return Nothing Just m -> return $ Just $ MAtom $ mToString m parseI (Repetition pat l' u') = if rtZerop u' then return $ Just $ MList [] else do oldST <- get m' <- parseI pat case m' of Nothing -> if rtZerop l' then do put oldST return (Just $ MList []) else return Nothing -- error Just m -> do ms' <- parseI (Repetition pat (rtPred l') (rtPred u')) case ms' of Nothing -> return Nothing Just (MList ms) -> return $ Just $ MList (m : ms) Just _ -> error "impossible" parseI (Choice []) = return Nothing -- impossible case parseI (Choice [p]) = do m' <- parseI p case m' of Nothing -> return Nothing Just _ -> return m' parseI (Choice (p:ps)) = do oldST <- get m' <- parseI p case m' of Just _ -> return m' Nothing -> do put oldST parseI (Choice ps) parseI (Sequence []) = return $ Just $ MList [] parseI (Sequence (p:ps)) = do m' <- parseI p case m' of Nothing -> return Nothing Just m -> do ms' <- parseI (Sequence ps) case ms' of Nothing -> return Nothing Just ms'' -> case ms'' of MList ms -> return $ Just $ MList (m:ms) _ -> error "impossible!" parseI (NegativeLookahead p) = do oldST <- get m' <- parseI p put oldST case m' of Nothing -> return $ Just $ MAtom "" Just _ -> return Nothing parseI (PositiveLookahead p) = do oldST <- get m' <- parseI p put oldST case m' of Just _ -> return $ Just $ MAtom "" Nothing -> return Nothing
shouya/gximemo
GxiMemo/Parser.hs
Haskell
mit
5,934
module Hitly.Map ( appMap, mkMap, atomicIO, newLink, getLink, getAndTickCounter ) where import BasePrelude hiding (insert, lookup, delete) import Control.Monad.IO.Class import STMContainers.Map import Hitly.Types appMap :: STM AppMap appMap = new mkMap :: MonadIO m => m AppMap mkMap = liftIO $ atomically $ appMap atomicIO :: MonadIO m => STM a -> m a atomicIO = liftIO . atomically newLink :: (Hashable k, Eq k) => v -> k -> Map k v -> STM () newLink = insert getLink :: (Hashable k, Eq k) => k -> Map k v -> STM (Maybe v) getLink urlHash smap = lookup urlHash smap getAndTickCounter :: (Hashable k, Eq k) => k -> Map k HitlyRequest -> STM (Maybe HitlyRequest) getAndTickCounter urlHash smap = do orig <- getLink urlHash smap case orig of Nothing -> return Nothing Just (HitlyRequest user' url' cnt') -> do let ticked = HitlyRequest user' url' (cnt' + 1) delete urlHash smap insert ticked urlHash smap return $ Just ticked
buckie/hitly
src/Hitly/Map.hs
Haskell
mit
1,044
{-# OPTIONS_GHC -Wall -} {- - Module to parse .emod files - - - Copyright 2013 -- name removed for blind review, all rights reserved! Please push a git request to receive author's name! -- - 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 EParser(parse,tbrfun,pGetEMOD,pGetLisp,pGetTerms,LispTree(..),TermBuilder (..) ,QueueAssignment(..),FlopAssignment(..),InputAssignment(..),OutputAssignment(..),Term(..) ,OutputWire(..),names,HasName(name),AssignmentOrWire(..)) where import LispParser (parse,pGetLisp,LispTree(..),LispPrimitive(..),SourcePos) import Terms(Term(..),(.+.)) import qualified Data.Set as Set (fromList, singleton) type EStructure = ([QueueAssignment],[FlopAssignment],[InputAssignment],[OutputAssignment],[OutputWire]) -- lisp terms without lambda functions, since we do not use lambda functions in E data LispTerm = LispTerm SourcePos String [LispTerm] | LispTermPrimitive SourcePos LispPrimitive deriving (Show) data GetTermError = GetTermError String SourcePos data QueueAssignment = QueueAssignment String -- | Queue name Int -- | Queue size Term -- | input-channel irdy [Term] -- | input-channel data Term -- | output-channel trdy deriving Show data FlopAssignment = FlopAssignment String -- | register name Term -- | register value deriving Show data InputAssignment = InputAssignment String -- | input name Term -- | trdy value deriving Show data OutputAssignment = OutputAssignment String -- | output name Term -- | irdy value [Term] -- | data value deriving Show data OutputWire = OutputWire String Term deriving Show data AssignmentOrWire = AssignQ QueueAssignment | AssignF FlopAssignment | AssignI InputAssignment | AssignO OutputAssignment | Wire OutputWire class HasName a where name :: a -> String instance HasName QueueAssignment where name (QueueAssignment n _ _ _ _) = n instance HasName FlopAssignment where name (FlopAssignment n _) = n instance HasName InputAssignment where name (InputAssignment n _) = n instance HasName OutputAssignment where name (OutputAssignment n _ _) = n instance HasName OutputWire where name (OutputWire n _) = n names :: (HasName a) => [a] -> [String] names = map name sortOutAssignments :: [AssignmentOrWire] -> ([QueueAssignment],[FlopAssignment],[InputAssignment],[OutputAssignment],[OutputWire]) sortOutAssignments xs = ([a|AssignQ a<-xs],[a|AssignF a<-xs],[a|AssignI a<-xs],[a|AssignO a<-xs],[a|Wire a<-xs]) data TermBuilder a b = TBError a | TB b Int -- .. and warnings? data TBR a b = TBR{tbrfun::(Int -> TermBuilder a b)} instance Monad (TBR a) where return b = TBR (TB b) (>>=) (TBR f1) f2 = TBR (\x -> case f1 x of {TBError a -> TBError a; TB b y -> (tbrfun (f2 b)) y}) instance Show GetTermError where show (GetTermError s p) = s ++ "\n on "++ (show p) getTermPos :: LispTerm -> SourcePos getTermPos (LispTerm p _ _) = p getTermPos (LispTermPrimitive p _) = p firstLeft :: [TBR a' a] -> TBR a' [a] firstLeft [] = return [] firstLeft (r:rs) = r >>= (\x -> tbrDo ((:) x) (firstLeft rs)) tbrDo :: (b1 -> b) -> TBR a b1 -> TBR a b tbrDo f arg = TBR (\y -> case (tbrfun arg) y of {TBError a -> TBError a;TB b i -> TB (f b) i}) firstLeftMap :: (a1 -> TBR a b) -> [a1] -> TBR a [b] firstLeftMap f xs = firstLeft (map f xs) pGetTerms :: [LispTree] -> TBR GetTermError [LispTerm] pGetTerms xs = firstLeftMap pGetTerm xs -- data LispTree = LispCons SourcePos LispTree LispTree | LispTreePrimitive SourcePos LispPrimitive deriving (Show) -- the TBR monoid takes failures on the left and return values on the right pGetTerm :: LispTree -> TBR GetTermError LispTerm pGetTerm (LispCons p a b) = do { h <- pGetSymbol a ; t' <- pGetList b ; t <- firstLeft (map pGetTerm t') ; return (LispTerm p h t) } pGetTerm (LispTreePrimitive p p') = return (LispTermPrimitive p p') pGetCons :: LispTree -> TBR GetTermError (LispTree, LispTree) pGetCons (LispCons _ a b) = return (a,b) pGetCons (LispTreePrimitive p _) = makeError p "Expecting CONS" pGetList :: LispTree -> TBR GetTermError [LispTree] pGetList (LispCons _ a b) = do {b' <-pGetList b;return$ a:b'} pGetList (LispTreePrimitive _ (LispSymbol "NIL")) = return [] pGetList (LispTreePrimitive p _) = makeError p "Expecting end of list marker NIL (perhaps you should omit the . ?)" pGetAList :: LispTree -> TBR GetTermError [(String,LispTerm)] pGetAList x = pGetList x >>= firstLeftMap pGetAssignment pGetEMOD :: LispTree -> TBR GetTermError ([QueueAssignment],[FlopAssignment],[InputAssignment],[OutputAssignment],[OutputWire]) pGetEMOD x = do { alist <- pGetAList x ; assignments <- firstLeftMap getAssignment alist ; return (sortOutAssignments assignments) } repeatN :: Int -> (TBR GetTermError a) -> (TBR GetTermError [a]) repeatN n f = if n<=0 then return [] else do{v<-f;r<-repeatN (n-1) f;return (v:r)} getAssignment :: (String,LispTerm) -> TBR GetTermError AssignmentOrWire getAssignment (name,LispTerm p "FLOP" lts) = case lts of { (clk : LispTermPrimitive _ (LispSymbol name') : val : []) -> do{ trm <- getTerm val ; _ <- getClk clk ; _ <- (if name/=name' then makeError p ("the name in the flop should be itself: "++name++" /= "++name') else return ()) ; return$ AssignF (FlopAssignment name trm) } ; _ -> makeError p "FLOP should have the arguments: |clk| name value, where name must be a symbol." } getAssignment (name,LispTerm p "GET-QUEUE-STATE" lts) = case lts of { (LispTermPrimitive _ (LispInt size) : LispTermPrimitive _ (LispInt dsize) : irdy : d : trdy : []) -> do{ irdy' <- getTerm irdy ; d' <- getData d ; trdy' <- getTerm trdy ; unknowns <- (repeatN (dsize - length d') (getTerm (LispTerm p "X" []))) ; return$ AssignQ (QueueAssignment name size irdy' (d'++unknowns) trdy') } ; _ -> makeError p "QUEUE should have the arguments: size data-size irdy data trdy, where size and data-size are integers"} getAssignment (name,LispTerm p "GET-SOURCE-STATE" lts) = case lts of { (trdy : []) -> do{ trdy' <- getTerm trdy ; return$ AssignI (InputAssignment name trdy') } ; _ -> makeError p "SOURCE should have one argument: trdy"} getAssignment (name,LispTerm p "GET-SINK-STATE" lts) = case lts of { (irdy : d : []) -> do{ d' <- getData d ; irdy' <- getTerm irdy ; return$ AssignO (OutputAssignment name irdy' d') } ; _ -> makeError p "SINK should have two argument: irdy data"} getAssignment (name,LispTerm p "OUTPUT" lts) = case lts of { (irdy : []) -> do{ irdy' <- getTerm irdy ; return$ Wire (OutputWire name irdy') } ; _ -> makeError p "OUTPUT should have one argument: the term it represents"} getAssignment (name,t) = makeError (getTermPos t) ("Not a valid assignment for "++name++",\n should be either FLOP, OUTPUT or GET-*-STATE where * = SINK, SOURCE or QUEUE") getData :: LispTerm -> TBR GetTermError [Term] getData (LispTerm _ "LIST" lst) = firstLeftMap getTerm lst getData (LispTerm _ "X" []) = return [] -- cheat a little by putting X this way getData t = makeError (getTermPos t) ("Not a valid list, lists should start with the function symbol LIST") getTerm :: LispTerm -> TBR GetTermError Term getTerm (LispTerm p "AND" lst) = do {(a,b)<-get2 p "arguments for AND" lst;a'<-getTerm a;b'<-getTerm b;return (T_AND a' b')} getTerm (LispTerm p "OR" lst) = do {(a,b)<-get2 p "arguments for OR" lst;a'<-getTerm a;b'<-getTerm b;return (T_OR a' b')} getTerm (LispTerm p "NOT" lst) = do {a<-get1 p "argument for NOT" lst;a'<-getTerm a;return (T_NOT a')} getTerm (LispTerm p "XOR" lst) = do {(a,b)<-get2 p "arguments for OR" lst;a'<-getTerm a;b'<-getTerm b;return (T_XOR a' b')} getTerm (LispTerm p "FLOPVAL" lst) = do {(a,b)<-get2 p "arguments for FLOPVAL" lst;_<-getClk a;b'<-getSymbol b;return (T_FLOPV b')} getTerm (LispTerm p "VALUE" lst) = case lst of { (LispTermPrimitive _ (LispSymbol "O.IRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_QIRDY s ; (LispTermPrimitive _ (LispSymbol "I.TRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_QTRDY s ; (LispTermPrimitive _ (LispSymbol "O.DATA") : LispTermPrimitive _ (LispInt i) : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_QDATA s i ; (LispTermPrimitive _ (LispSymbol "S.IRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_IIRDY s ; (LispTermPrimitive _ (LispSymbol "S.TRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_OTRDY s ; (LispTermPrimitive _ (LispSymbol "S.DATA") : LispTermPrimitive _ (LispInt i) : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_IDATA s i ; _ -> makeError p "VALUE should either get O.IRDY, I.TRDY or O.DATA with a queue-name (or an integer + queue name for O.DATA), or S.* similarly" } getTerm (LispTerm p "X" lst) = do {_<-get0 p "arguments for X" lst;increment (\x -> T_UNKNOWN x)} getTerm (LispTerm p "F" lst) = do {_<-get0 p "arguments for F" lst;return (T_VALUE False)} getTerm (LispTerm p "T" lst) = do {_<-get0 p "arguments for T" lst;return (T_VALUE True)} getTerm (LispTermPrimitive p p') = do {_<-getRst p p';return T_RESET} getTerm (LispTerm p "INPUT" lst) = do {a<-get1 p "argument for INPUT" lst;a'<-getSymbol a;return (T_INPUT a')} getTerm (LispTerm p s _) = makeError p ("unexpected function symbol: "++s++"\n Recognised function symbols are: AND, OR, NOT, XOR, FLOPVAL, INPUT and VALUE") -- like return, only allows for an integer too increment :: (Int -> b) -> TBR a b increment f = (TBR (\x -> TB (f x) (x + 1))) getRst :: SourcePos -> LispPrimitive -> TBR GetTermError () getRst _ (LispSymbol "rst") = return () getRst p _ = makeError p "the only free symbol allowed is the reset: |rst|" getClk :: LispTerm -> TBR GetTermError () getClk (LispTermPrimitive _ (LispSymbol "clk")) = return () getClk t = makeError (getTermPos t) "expecting clock symbol |clk|" get2 :: SourcePos -> [Char] -> [t] -> TBR GetTermError (t, t) get2 _ _ (a:b:[]) = return (a,b) get2 p s _ = makeError p ("Expecting two "++s) get1 :: SourcePos -> [Char] -> [a] -> TBR GetTermError a get1 _ _ (a:[]) = return a get1 p s _ = makeError p ("Expecting one "++s) get0 :: SourcePos -> [Char] -> [a] -> TBR GetTermError () get0 _ _ [] = return () get0 p s _ = makeError p ("Expecting no "++s) (<?>) :: TBR GetTermError b -> String -> TBR GetTermError b (<?>) tbr msg = TBR (\x -> case (tbrfun tbr) x of {TBError (GetTermError _ p) -> makeError' msg p;v -> v}) pGetAssignment :: LispTree -> TBR GetTermError (String,LispTerm) pGetAssignment x = do { (a,b) <- (pGetCons x <?> "Expecting assignment") ; s <- pGetSymbol a <?> "Assignment requires its first item to be a symbol" ; t <- pGetTerm b ; return (s,t) } makeError :: SourcePos -> String -> TBR GetTermError b makeError pos str = TBR (\_ -> makeError' str pos) makeError' :: String -> SourcePos -> TermBuilder GetTermError b makeError' str pos = TBError (GetTermError str pos) getSymbol :: LispTerm -> TBR GetTermError String getSymbol (LispTermPrimitive _ (LispSymbol p)) = return$ p getSymbol (LispTermPrimitive p _) = makeError p "Expecting primitive of Symbol type, consider putting ||'s around the primitive" getSymbol (LispTerm p _ _) = makeError p "Expecting primitive of Symbol type, got a Cons" pGetSymbol :: LispTree -> TBR GetTermError String pGetSymbol (LispTreePrimitive _ (LispSymbol p)) = return$ p pGetSymbol (LispTreePrimitive p _) = makeError p "Expecting primitive of Symbol type, consider putting ||'s around the primitive" pGetSymbol (LispCons p _ _) = makeError p "Expecting primitive of Symbol type, got a Cons"
DatePaper616/code
EParser.hs
Haskell
apache-2.0
13,249
-- | Schedule program for execution. At the moment it schedule for -- exact number of threads module DNA.Compiler.Scheduler where import Control.Monad import Data.Graph.Inductive.Graph import qualified Data.IntMap as IntMap import Data.IntMap ((!)) import DNA.AST import DNA.Actor import DNA.Compiler.Types ---------------------------------------------------------------- -- Simple scheduler ---------------------------------------------------------------- -- | Number of nodes in the cluster type CAD = Int -- | Simple scheduler. It assumes that all optimization passes are -- done and will not try to transform graph. schedule :: CAD -> DataflowGraph -> Compile DataflowGraph schedule nTotal gr = do let nMust = nMandatory gr nVar = nVarGroups gr nFree = nTotal - nMust - nVar -- We need at least 1 node per group when (nFree < 0) $ compError ["Not enough nodes to schedule algorithm"] -- Schedule for mandatory nodes. For each node we let mandSched = IntMap.fromList $ mandatoryNodes gr `zip` [0..] -- Now we should schedule remaining nodes. let varGroups = contiguosChunks nMust (splitChunks nVar (nTotal - nMust)) varSched = IntMap.fromList $ variableNodes gr `zip` varGroups -- Build schedule for every let sched i (ANode _ a@(RealActor _ act)) = case act of StateM{} -> ANode (Single n) a Producer{} -> ANode (Single n) a ScatterGather{} -> ANode (MasterSlaves n (varSched ! i)) a where n = mandSched ! i return $ gmap (\(a1, i, a, a2) -> (a1, i, sched i a, a2)) gr -- | Total number of processes that we must spawn. nMandatory :: DataflowGraph -> Int nMandatory gr = sum [ getN $ lab' $ context gr n | n <- nodes gr] where getN (ANode _ _) = 1 -- | List of all actors for which we must allocate separate cluster node. mandatoryNodes :: DataflowGraph -> [Node] mandatoryNodes gr = [ n | n <- nodes gr] variableNodes :: DataflowGraph -> [Node] variableNodes gr = [ n | n <- nodes gr , isSG (lab' $ context gr n) ] where isSG (ANode _ (RealActor _ (ScatterGather{}))) = True isSG _ = False -- | Number of groups for which we can vary number of allocated nodes nVarGroups :: DataflowGraph -> Int nVarGroups gr = sum [ get $ lab' $ context gr n | n <- nodes gr] where get (ANode _ (RealActor _ (ScatterGather{}))) = 1 get _ = 0 -- Split N items to k groups. splitChunks :: Int -> Int -> [Int] splitChunks nChunks nTot = map (+1) toIncr ++ rest where (chunk,n) = nTot `divMod` nChunks (toIncr,rest) = splitAt n (replicate nChunks chunk) contiguosChunks :: Int -> [Int] -> [[Int]] contiguosChunks off = go [off ..] where go _ [] = [] go xs (n:ns) = case splitAt n xs of (a,rest) -> a : go rest ns
SKA-ScienceDataProcessor/RC
MS1/dna/DNA/Compiler/Scheduler.hs
Haskell
apache-2.0
2,911
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} ---------------------------------------------------------------------------- -- | -- Module : Web.Skroutz.Model.Base.SkuReview -- Copyright : (c) 2016 Remous-Aris Koutsiamanis -- License : Apache License 2.0 -- Maintainer : Remous-Aris Koutsiamanis <[email protected]> -- Stability : alpha -- Portability : non-portable -- -- Provides the 'SkuReview' type, a user review of an 'Web.Skroutz.Model.Base.Sku.Sku'. ---------------------------------------------------------------------------- module Web.Skroutz.Model.Base.SkuReview where import Control.DeepSeq (NFData) import Data.Data (Data, Typeable) import Data.Text (Text) import GHC.Generics (Generic) import Web.Skroutz.Model.Base.ISO8601Time import Web.Skroutz.TH data SkuReview = SkuReview { _skuReviewId :: Int , _skuReviewUserId :: Int , _skuReviewReview :: Text , _skuReviewRating :: Int , _skuReviewCreatedAt :: ISO8601Time , _skuReviewDemoted :: Bool , _skuReviewVotesCount :: Int , _skuReviewHelpfulVotesCount :: Int } deriving (Eq, Ord, Typeable, Data, Generic, Show, NFData) makeLensesAndJSON ''SkuReview "_skuReview"
ariskou/skroutz-haskell-api
src/Web/Skroutz/Model/Base/SkuReview.hs
Haskell
apache-2.0
1,492
----------------------------------------------------------------------------- -- -- Module : Graphics.UI.Hieroglyph.Cache -- Copyright : -- License : BSD3 -- -- Maintainer : J.R. Heard -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Graphics.UI.Hieroglyph.Cache where import qualified Data.Map as Map import qualified Data.IntMap as IntMap data Cache k a = Cache { store :: Map.Map k a, times :: IntMap.IntMap k, now :: Int, maxsize :: Int, size :: Int, decimation :: Int } empty mxsz dec = Cache Map.empty IntMap.empty 0 mxsz 0 dec get :: Ord k => k -> Cache k a -> (Cache k a,Maybe a) get key cache = (cache',value) where value = Map.lookup key (store cache) cache' = maybe (cache{ now = now cache + 1 }) (\_ -> cache{ now = now cache + 1, times = IntMap.insert (now cache) key (times cache) }) value put :: Ord k => k -> a -> Cache k a -> Cache k a put key value cache | size cache < maxsize cache && (not $ Map.member key (store cache)) = cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) , size = size cache + 1 } | size cache < maxsize cache = cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) } | size cache >= maxsize cache && (Map.member key (store cache)) = cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) } | size cache >= maxsize cache = cache{ now = now cache + 1, times = IntMap.insert (now cache) key times', store = Map.insert key value store', size = size cache - decimation cache } where times' = foldr IntMap.delete (times cache) lowtimes (lowtimes,lowtimekeys) = unzip . take (decimation cache) . IntMap.toAscList . times $ cache store' = foldr Map.delete (store cache) lowtimekeys put' :: Ord k => k -> a -> Cache k a -> ([a], Cache k a) put' key value cache | size cache < maxsize cache && (not $ Map.member key (store cache)) = ([],cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) , size = size cache + 1 }) | size cache < maxsize cache = ([],cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) }) | size cache >= maxsize cache && (Map.member key (store cache)) = ([],cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) }) | size cache >= maxsize cache = (freed, cache{ now = now cache + 1, times = IntMap.insert (now cache) key times', store = Map.insert key value store', size = size cache - decimation cache }) where times' = foldr IntMap.delete (times cache) lowtimes (lowtimes,lowtimekeys) = unzip . take (decimation cache) . IntMap.toAscList . times $ cache store' = foldr Map.delete (store cache) lowtimekeys freed = map (store cache Map.!) lowtimekeys free :: Ord k => Cache k a -> ((k,a),Cache k a) free cache = ((minkey,minval),cache') where minkey = IntMap.findMin (times cache) minval = store cache Map.! minkey cache' = cache{ now = now cache + 1, times = IntMap.deleteMin (times cache), store = Map.delete minkey (store cache), size = (size cache) } member :: Ord k => k -> Cache k a -> Bool member key cache = Map.member key (store cache)
JeffHeard/Hieroglyph
Graphics/UI/Hieroglyph/Cache.hs
Haskell
bsd-2-clause
3,561
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGradient.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:16 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGradient ( QqGradient(..) ,QqGradient_nf(..) ,coordinateMode ,setColorAt ,setCoordinateMode ,setSpread ,spread ,qGradient_delete ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QGradient import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqGradient x1 where qGradient :: x1 -> IO (QGradient ()) instance QqGradient (()) where qGradient () = withQGradientResult $ qtc_QGradient foreign import ccall "qtc_QGradient" qtc_QGradient :: IO (Ptr (TQGradient ())) instance QqGradient ((QGradient t1)) where qGradient (x1) = withQGradientResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGradient1 cobj_x1 foreign import ccall "qtc_QGradient1" qtc_QGradient1 :: Ptr (TQGradient t1) -> IO (Ptr (TQGradient ())) class QqGradient_nf x1 where qGradient_nf :: x1 -> IO (QGradient ()) instance QqGradient_nf (()) where qGradient_nf () = withObjectRefResult $ qtc_QGradient instance QqGradient_nf ((QGradient t1)) where qGradient_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGradient1 cobj_x1 coordinateMode :: QGradient a -> (()) -> IO (CoordinateMode) coordinateMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_coordinateMode cobj_x0 foreign import ccall "qtc_QGradient_coordinateMode" qtc_QGradient_coordinateMode :: Ptr (TQGradient a) -> IO CLong setColorAt :: QGradient a -> ((Double, QColor t2)) -> IO () setColorAt x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGradient_setColorAt cobj_x0 (toCDouble x1) cobj_x2 foreign import ccall "qtc_QGradient_setColorAt" qtc_QGradient_setColorAt :: Ptr (TQGradient a) -> CDouble -> Ptr (TQColor t2) -> IO () setCoordinateMode :: QGradient a -> ((CoordinateMode)) -> IO () setCoordinateMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_setCoordinateMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QGradient_setCoordinateMode" qtc_QGradient_setCoordinateMode :: Ptr (TQGradient a) -> CLong -> IO () setSpread :: QGradient a -> ((Spread)) -> IO () setSpread x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_setSpread cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QGradient_setSpread" qtc_QGradient_setSpread :: Ptr (TQGradient a) -> CLong -> IO () spread :: QGradient a -> (()) -> IO (Spread) spread x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_spread cobj_x0 foreign import ccall "qtc_QGradient_spread" qtc_QGradient_spread :: Ptr (TQGradient a) -> IO CLong instance Qqtype (QGradient a) (()) (IO (QGradientType)) where qtype x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_type cobj_x0 foreign import ccall "qtc_QGradient_type" qtc_QGradient_type :: Ptr (TQGradient a) -> IO CLong qGradient_delete :: QGradient a -> IO () qGradient_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_delete cobj_x0 foreign import ccall "qtc_QGradient_delete" qtc_QGradient_delete :: Ptr (TQGradient a) -> IO ()
keera-studios/hsQt
Qtc/Gui/QGradient.hs
Haskell
bsd-2-clause
3,662
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QUdpSocket_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:31 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Network.QUdpSocket_h where import Qtc.Enums.Base import Qtc.Enums.Core.QIODevice import Qtc.Enums.Network.QAbstractSocket import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Network_h import Qtc.ClassTypes.Network import Foreign.Marshal.Array instance QunSetUserMethod (QUdpSocket ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QUdpSocket_unSetUserMethod" qtc_QUdpSocket_unSetUserMethod :: Ptr (TQUdpSocket a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QUdpSocketSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QUdpSocket ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QUdpSocketSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QUdpSocket ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QUdpSocketSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QUdpSocket ()) (QUdpSocket x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setUserMethod" qtc_QUdpSocket_setUserMethod :: Ptr (TQUdpSocket a) -> CInt -> Ptr (Ptr (TQUdpSocket x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QUdpSocket :: (Ptr (TQUdpSocket x0) -> IO ()) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QUdpSocket_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QUdpSocketSc a) (QUdpSocket x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QUdpSocket ()) (QUdpSocket x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setUserMethodVariant" qtc_QUdpSocket_setUserMethodVariant :: Ptr (TQUdpSocket a) -> CInt -> Ptr (Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QUdpSocket :: (Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QUdpSocket_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QUdpSocketSc a) (QUdpSocket x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QUdpSocket ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QUdpSocket_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QUdpSocket_unSetHandler" qtc_QUdpSocket_unSetHandler :: Ptr (TQUdpSocket a) -> CWString -> IO (CBool) instance QunSetHandler (QUdpSocketSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QUdpSocket_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler1" qtc_QUdpSocket_setHandler1 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket1 :: (Ptr (TQUdpSocket x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QatEnd_h (QUdpSocket ()) (()) where atEnd_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_atEnd cobj_x0 foreign import ccall "qtc_QUdpSocket_atEnd" qtc_QUdpSocket_atEnd :: Ptr (TQUdpSocket a) -> IO CBool instance QatEnd_h (QUdpSocketSc a) (()) where atEnd_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_atEnd cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CLLong) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCLLong rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler2" qtc_QUdpSocket_setHandler2 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> IO (CLLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket2 :: (Ptr (TQUdpSocket x0) -> IO (CLLong)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO (CLLong))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CLLong) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCLLong rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QbytesAvailable_h (QUdpSocket ()) (()) where bytesAvailable_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesAvailable cobj_x0 foreign import ccall "qtc_QUdpSocket_bytesAvailable" qtc_QUdpSocket_bytesAvailable :: Ptr (TQUdpSocket a) -> IO CLLong instance QbytesAvailable_h (QUdpSocketSc a) (()) where bytesAvailable_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesAvailable cobj_x0 instance QbytesToWrite_h (QUdpSocket ()) (()) where bytesToWrite_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesToWrite cobj_x0 foreign import ccall "qtc_QUdpSocket_bytesToWrite" qtc_QUdpSocket_bytesToWrite :: Ptr (TQUdpSocket a) -> IO CLLong instance QbytesToWrite_h (QUdpSocketSc a) (()) where bytesToWrite_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesToWrite cobj_x0 instance QcanReadLine_h (QUdpSocket ()) (()) where canReadLine_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_canReadLine cobj_x0 foreign import ccall "qtc_QUdpSocket_canReadLine" qtc_QUdpSocket_canReadLine :: Ptr (TQUdpSocket a) -> IO CBool instance QcanReadLine_h (QUdpSocketSc a) (()) where canReadLine_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_canReadLine cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler3" qtc_QUdpSocket_setHandler3 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket3 :: (Ptr (TQUdpSocket x0) -> IO ()) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qclose_h (QUdpSocket ()) (()) where close_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_close cobj_x0 foreign import ccall "qtc_QUdpSocket_close" qtc_QUdpSocket_close :: Ptr (TQUdpSocket a) -> IO () instance Qclose_h (QUdpSocketSc a) (()) where close_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_close cobj_x0 instance QisSequential_h (QUdpSocket ()) (()) where isSequential_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_isSequential cobj_x0 foreign import ccall "qtc_QUdpSocket_isSequential" qtc_QUdpSocket_isSequential :: Ptr (TQUdpSocket a) -> IO CBool instance QisSequential_h (QUdpSocketSc a) (()) where isSequential_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_isSequential cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler4" qtc_QUdpSocket_setHandler4 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> CInt -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket4 :: (Ptr (TQUdpSocket x0) -> CInt -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> CInt -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QwaitForBytesWritten_h (QUdpSocket ()) (()) where waitForBytesWritten_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten cobj_x0 foreign import ccall "qtc_QUdpSocket_waitForBytesWritten" qtc_QUdpSocket_waitForBytesWritten :: Ptr (TQUdpSocket a) -> IO CBool instance QwaitForBytesWritten_h (QUdpSocketSc a) (()) where waitForBytesWritten_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten cobj_x0 instance QwaitForBytesWritten_h (QUdpSocket ()) ((Int)) where waitForBytesWritten_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten1 cobj_x0 (toCInt x1) foreign import ccall "qtc_QUdpSocket_waitForBytesWritten1" qtc_QUdpSocket_waitForBytesWritten1 :: Ptr (TQUdpSocket a) -> CInt -> IO CBool instance QwaitForBytesWritten_h (QUdpSocketSc a) ((Int)) where waitForBytesWritten_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten1 cobj_x0 (toCInt x1) instance QwaitForReadyRead_h (QUdpSocket ()) (()) where waitForReadyRead_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead cobj_x0 foreign import ccall "qtc_QUdpSocket_waitForReadyRead" qtc_QUdpSocket_waitForReadyRead :: Ptr (TQUdpSocket a) -> IO CBool instance QwaitForReadyRead_h (QUdpSocketSc a) (()) where waitForReadyRead_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead cobj_x0 instance QwaitForReadyRead_h (QUdpSocket ()) ((Int)) where waitForReadyRead_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead1 cobj_x0 (toCInt x1) foreign import ccall "qtc_QUdpSocket_waitForReadyRead1" qtc_QUdpSocket_waitForReadyRead1 :: Ptr (TQUdpSocket a) -> CInt -> IO CBool instance QwaitForReadyRead_h (QUdpSocketSc a) ((Int)) where waitForReadyRead_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead1 cobj_x0 (toCInt x1) instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> OpenMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1flags = qFlags_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1flags rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler5" qtc_QUdpSocket_setHandler5 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket5 :: (Ptr (TQUdpSocket x0) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> CLong -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> OpenMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1flags = qFlags_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1flags rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qopen_h (QUdpSocket ()) ((OpenMode)) where open_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_open cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QUdpSocket_open" qtc_QUdpSocket_open :: Ptr (TQUdpSocket a) -> CLong -> IO CBool instance Qopen_h (QUdpSocketSc a) ((OpenMode)) where open_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_open cobj_x0 (toCLong $ qFlags_toInt x1) instance Qpos_h (QUdpSocket ()) (()) where pos_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_pos cobj_x0 foreign import ccall "qtc_QUdpSocket_pos" qtc_QUdpSocket_pos :: Ptr (TQUdpSocket a) -> IO CLLong instance Qpos_h (QUdpSocketSc a) (()) where pos_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_pos cobj_x0 instance Qreset_h (QUdpSocket ()) (()) (IO (Bool)) where reset_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_reset cobj_x0 foreign import ccall "qtc_QUdpSocket_reset" qtc_QUdpSocket_reset :: Ptr (TQUdpSocket a) -> IO CBool instance Qreset_h (QUdpSocketSc a) (()) (IO (Bool)) where reset_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_reset cobj_x0 instance Qseek_h (QUdpSocket ()) ((Int)) where seek_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_seek cobj_x0 (toCLLong x1) foreign import ccall "qtc_QUdpSocket_seek" qtc_QUdpSocket_seek :: Ptr (TQUdpSocket a) -> CLLong -> IO CBool instance Qseek_h (QUdpSocketSc a) ((Int)) where seek_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_seek cobj_x0 (toCLLong x1) instance Qqsize_h (QUdpSocket ()) (()) where qsize_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_size cobj_x0 foreign import ccall "qtc_QUdpSocket_size" qtc_QUdpSocket_size :: Ptr (TQUdpSocket a) -> IO CLLong instance Qqsize_h (QUdpSocketSc a) (()) where qsize_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_size cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler6" qtc_QUdpSocket_setHandler6 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket6 :: (Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QUdpSocket ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QUdpSocket_event cobj_x0 cobj_x1 foreign import ccall "qtc_QUdpSocket_event" qtc_QUdpSocket_event :: Ptr (TQUdpSocket a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QUdpSocketSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QUdpSocket_event cobj_x0 cobj_x1 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler7" qtc_QUdpSocket_setHandler7 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket7 :: (Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QUdpSocket ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QUdpSocket_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QUdpSocket_eventFilter" qtc_QUdpSocket_eventFilter :: Ptr (TQUdpSocket a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QUdpSocketSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QUdpSocket_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Network/QUdpSocket_h.hs
Haskell
bsd-2-clause
38,699
module Data.Drasil.Concepts.PhysicalProperties where import Language.Drasil import Utils.Drasil import Data.Drasil.Concepts.Documentation (material_, property) import Data.Drasil.Concepts.Math (centre) physicalcon :: [ConceptChunk] physicalcon = [gaseous, liquid, solid, ctrOfMass, density, specWeight, mass, len, dimension, vol, flexure] gaseous, liquid, solid, ctrOfMass, density, specWeight, mass, len, dimension, vol, flexure :: ConceptChunk gaseous = dcc "gaseous" (cn''' "gas" ) "gaseous state" liquid = dcc "liquid" (cn' "liquid" ) "liquid state" solid = dcc "solid" (cn' "solid" ) "solid state" ctrOfMass = dcc "ctrOfMass" (centre `of_''` mass ) "the mean location of the distribution of mass of the object" dimension = dcc "dimension" (cn' "dimension" ) "any of a set of basic kinds of quantity, as mass, length, and time" density = dcc "density" (cnIES "density" ) "the mass per unit volume" specWeight = dcc "specWeight" (cn' "specific weight") "the weight per unit volume" flexure = dcc "flexure" (cn' "flexure" ) "a bent or curved part" len = dcc "length" (cn' "length" ) ("the straight-line distance between two points along an object, " ++ "typically used to represent the size of an object from one end to the other") mass = dcc "mass" (cn''' "mass" ) "the quantity of matter in a body" vol = dcc "volume" (cn' "volume" ) "the amount of space that a substance or object occupies" materialProprty :: NamedChunk materialProprty = compoundNC material_ property
JacquesCarette/literate-scientific-software
code/drasil-data/Data/Drasil/Concepts/PhysicalProperties.hs
Haskell
bsd-2-clause
1,681
{-# LANGUAGE OverloadedStrings #-} module Network.WebSockets.Protocol.Hybi10.Internal ( Hybi10_ (..) , encodeFrameHybi10 ) where import Control.Applicative (pure, (<$>)) import Data.Bits ((.&.), (.|.)) import Data.Maybe (maybeToList) import Data.Monoid (mempty, mappend, mconcat) import Data.Attoparsec (anyWord8) import Data.Binary.Get (runGet, getWord16be, getWord64be) import Data.ByteString (ByteString) import Data.ByteString.Char8 () import Data.Digest.Pure.SHA (bytestringDigest, sha1) import Data.Int (Int64) import Data.Enumerator ((=$)) import qualified Blaze.ByteString.Builder as B import qualified Data.Attoparsec as A import qualified Data.Attoparsec.Enumerator as A import qualified Data.ByteString.Base64 as B64 import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import qualified Data.CaseInsensitive as CI import qualified Data.Enumerator as E import qualified Data.Enumerator.List as EL import Network.WebSockets.Handshake.Http import Network.WebSockets.Protocol import Network.WebSockets.Protocol.Hybi10.Demultiplex import Network.WebSockets.Protocol.Hybi10.Mask import Network.WebSockets.Types data Hybi10_ = Hybi10_ instance Protocol Hybi10_ where version Hybi10_ = "hybi10" headerVersions Hybi10_ = ["13", "8", "7"] encodeMessages Hybi10_ = EL.map encodeMessageHybi10 decodeMessages Hybi10_ = decodeMessagesHybi10 finishRequest Hybi10_ = handshakeHybi10 implementations = [Hybi10_] instance TextProtocol Hybi10_ instance BinaryProtocol Hybi10_ encodeMessageHybi10 :: Message p -> B.Builder encodeMessageHybi10 msg = builder where mkFrame = Frame True False False False builder = encodeFrameHybi10 $ case msg of (ControlMessage (Close pl)) -> mkFrame CloseFrame pl (ControlMessage (Ping pl)) -> mkFrame PingFrame pl (ControlMessage (Pong pl)) -> mkFrame PongFrame pl (DataMessage (Text pl)) -> mkFrame TextFrame pl (DataMessage (Binary pl)) -> mkFrame BinaryFrame pl -- | Encode a frame encodeFrameHybi10 :: Frame -> B.Builder encodeFrameHybi10 f = B.fromWord8 byte0 `mappend` B.fromWord8 byte1 `mappend` len `mappend` B.fromLazyByteString (framePayload f) where byte0 = fin .|. rsv1 .|. rsv2 .|. rsv3 .|. opcode fin = if frameFin f then 0x80 else 0x00 rsv1 = if frameRsv1 f then 0x40 else 0x00 rsv2 = if frameRsv2 f then 0x20 else 0x00 rsv3 = if frameRsv3 f then 0x10 else 0x00 opcode = case frameType f of ContinuationFrame -> 0x00 TextFrame -> 0x01 BinaryFrame -> 0x02 CloseFrame -> 0x08 PingFrame -> 0x09 PongFrame -> 0x0a byte1 = lenflag len' = BL.length (framePayload f) (lenflag, len) | len' < 126 = (fromIntegral len', mempty) | len' < 0x10000 = (126, B.fromWord16be (fromIntegral len')) | otherwise = (127, B.fromWord64be (fromIntegral len')) decodeMessagesHybi10 :: Monad m => E.Enumeratee ByteString (Message p) m a decodeMessagesHybi10 = (E.sequence (A.iterParser parseFrame) =$) . demultiplexEnum demultiplexEnum :: Monad m => E.Enumeratee Frame (Message p) m a demultiplexEnum = EL.concatMapAccum step emptyDemultiplexState where step s f = let (m, s') = demultiplex s f in (s', maybeToList m) -- | Parse a frame parseFrame :: A.Parser Frame parseFrame = do byte0 <- anyWord8 let fin = byte0 .&. 0x80 == 0x80 rsv1 = byte0 .&. 0x40 == 0x40 rsv2 = byte0 .&. 0x20 == 0x20 rsv3 = byte0 .&. 0x10 == 0x10 opcode = byte0 .&. 0x0f let ft = case opcode of 0x00 -> ContinuationFrame 0x01 -> TextFrame 0x02 -> BinaryFrame 0x08 -> CloseFrame 0x09 -> PingFrame 0x0a -> PongFrame _ -> error "Unknown opcode" byte1 <- anyWord8 let mask = byte1 .&. 0x80 == 0x80 lenflag = fromIntegral (byte1 .&. 0x7f) len <- case lenflag of 126 -> fromIntegral . runGet' getWord16be <$> A.take 2 127 -> fromIntegral . runGet' getWord64be <$> A.take 8 _ -> return lenflag masker <- maskPayload <$> if mask then Just <$> A.take 4 else pure Nothing chunks <- take64 len return $ Frame fin rsv1 rsv2 rsv3 ft (masker $ BL.fromChunks chunks) where runGet' g = runGet g . BL.fromChunks . return take64 :: Int64 -> A.Parser [ByteString] take64 n | n <= 0 = return [] | otherwise = do let n' = min intMax n chunk <- A.take (fromIntegral n') (chunk :) <$> take64 (n - n') where intMax :: Int64 intMax = fromIntegral (maxBound :: Int) handshakeHybi10 :: Monad m => RequestHttpPart -> E.Iteratee ByteString m Request handshakeHybi10 reqHttp@(RequestHttpPart path h _) = do key <- getHeader "Sec-WebSocket-Key" let hash = unlazy $ bytestringDigest $ sha1 $ lazy $ key `mappend` guid let encoded = B64.encode hash return $ Request path h $ response101 [("Sec-WebSocket-Accept", encoded)] "" where guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" lazy = BL.fromChunks . return unlazy = mconcat . BL.toChunks getHeader k = case lookup k h of Just t -> return t Nothing -> E.throwError $ MalformedRequest reqHttp $ "Header missing: " ++ BC.unpack (CI.original k)
0xfaded/websockets
src/Network/WebSockets/Protocol/Hybi10/Internal.hs
Haskell
bsd-3-clause
5,497
module Hchain.Client (start) where import qualified Control.Distributed.Backend.P2P as P2P import Control.Distributed.Process as DP import Control.Distributed.Process.Node as DPN import Data.Binary import Data.Typeable import Network.Socket import Hchain.BlockChain import Hchain.Client.Chain as Chain import Hchain.Client.CommandLineInterface as CommandLine import Control.Concurrent.MVar import Control.Distributed.Process.Extras.SystemLog start :: (Show a, Typeable a, Binary a, BContent a) => HostName -> ServiceName -> [String] -> BlockChain (Block a) -> MVar (BlockChain (Block a)) -> IO () start host port seeds chain storage = P2P.bootstrap host port (map P2P.makeNodeId seeds) initRemoteTable mainProcess where mainProcess = do _ <- systemLogFile ("log/application_" ++ host ++ port ++ ".log") Info return loopPid <- spawnLocal $ Chain.spawnProcess chain storage -- _commandLinePid <- spawnLocal $ CommandLine.spawnProcess loopPid return ()
jesuspc/hchain
src/hchain/Client.hs
Haskell
bsd-3-clause
1,163
-- | A module that implements a dictionary/hash table module Text.Regex.Deriv.Dictionary where import qualified Data.IntMap as IM import Data.Char import Prelude hiding (all, words) class Key a where hash :: a -> [Int] instance Key Int where hash i = [i] instance Key Char where hash c = [(ord c)] instance (Key a, Key b) => Key (a,b) where hash (a,b) = hash a ++ hash b instance (Key a, Key b, Key c) => Key (a,b,c) where hash (a,b,c) = hash a ++ hash b ++ hash c instance Key a => Key [a] where hash as = concatMap hash as -- an immutable dictionary newtype Dictionary a = Dictionary (Trie a) primeL :: Int primeL = 757 primeR :: Int primeR = 577 empty :: Dictionary a empty = Dictionary emptyTrie -- insert and overwrite insert :: Key k => k -> a -> Dictionary a -> Dictionary a insert key val (Dictionary trie) = let key_hash = hash key in key_hash `seq` Dictionary (insertTrie True key_hash val trie) -- insert not overwrite insertNotOverwrite :: Key k => k -> a -> Dictionary a -> Dictionary a insertNotOverwrite key val (Dictionary trie) = let key_hash = hash key in key_hash `seq` Dictionary (insertTrie False key_hash val trie) lookup :: Key k => k -> Dictionary a -> Maybe a lookup key (Dictionary trie) = let key_hash = hash key in key_hash `seq` case lookupTrie key_hash trie of Just (Trie (x:_) _) -> Just x _ -> Nothing lookupAll :: Key k => k -> Dictionary a -> [a] lookupAll key (Dictionary trie) = let key_hash = hash key in key_hash `seq` case lookupTrie key_hash trie of Just (Trie xs _) -> xs _ -> [] member :: Key k => k -> Dictionary a -> Bool member key d = case Text.Regex.Deriv.Dictionary.lookup key d of { Just _ -> True ; Nothing -> False } fromList :: Key k => [(k,a)] -> Dictionary a fromList l = foldl (\d (key,val) -> insert key val d) empty l fromListNotOverwrite :: Key k => [(k,a)] -> Dictionary a fromListNotOverwrite l = foldl (\d (key,val) -> insertNotOverwrite key val d) empty l update :: Key k => k -> a -> Dictionary a -> Dictionary a update key val (Dictionary trie) = let key_hash = hash key trie' = key_hash `seq` updateTrie key_hash val trie in Dictionary trie' -- The following are some special functions we implemented for -- an special instance of the dictionary 'Dictionary (k,a)' -- in which we store both the key k together with the actual value a, -- i.e. we map (hash k) to list of (k,a) value pairs -- ^ the dictionary (k,a) version of elem isIn :: (Key k, Eq k) => k -> Dictionary (k,a) -> Bool isIn k dict = let all = lookupAll (hash k) dict in k `elem` (map fst all) nub :: (Key k, Eq k) => [k] -> [k] nub ks = nubSub ks empty nubSub :: (Key k, Eq k) => [k] -> Dictionary (k,()) -> [k] nubSub [] _ = [] nubSub (x:xs) d | x `isIn` d = nubSub xs d | otherwise = let d' = insertNotOverwrite x (x,()) d in x:(nubSub xs d') -- An internal trie which we use to implement the dictoinar data Trie a = Trie ![a] !(IM.IntMap (Trie a)) emptyTrie :: Trie a emptyTrie = Trie [] (IM.empty) insertTrie :: Bool -> [Int] -> a -> Trie a -> Trie a insertTrie overwrite [] i (Trie is maps) | overwrite = Trie [i] maps | otherwise = Trie (i:is) maps insertTrie overwrite (word:words) i (Trie is maps) = let key = word in key `seq` case IM.lookup key maps of { Just trie -> let trie' = insertTrie overwrite words i trie maps' = trie' `seq` IM.update (\_ -> Just trie') key maps in maps' `seq` Trie is maps' ; Nothing -> let trie = emptyTrie trie' = insertTrie overwrite words i trie maps' = trie' `seq` IM.insert key trie' maps in maps' `seq` Trie is maps' } lookupTrie :: [Int] -> Trie a -> Maybe (Trie a) lookupTrie [] trie = Just trie lookupTrie (word:words) (Trie _ maps) = let key = word in case IM.lookup key maps of Just trie -> lookupTrie words trie Nothing -> Nothing -- we only update the first one, not the collided ones updateTrie :: [Int] -> a -> Trie a -> Trie a updateTrie [] y (Trie (_:xs) maps) = Trie (y:xs) maps updateTrie (word:words) v (Trie is maps) = let key = word in case IM.lookup key maps of Just trie -> let trie' = updateTrie words v trie maps' = IM.update (\_ -> Just trie') key maps in Trie is maps' Nothing -> Trie is maps
awalterschulze/xhaskell-regex-deriv
Text/Regex/Deriv/Dictionary.hs
Haskell
bsd-3-clause
4,562
module Publish where import Control.Monad.Error.Class (throwError) import qualified Data.Maybe as Maybe import qualified Bump import qualified Catalog import qualified CommandLine.Helpers as Cmd import qualified Docs import qualified Elm.Docs as Docs import qualified Elm.Package.Description as Desc import qualified Elm.Package as Package import qualified Elm.Package.Paths as P import qualified GitHub import qualified Manager publish :: Manager.Manager () publish = do description <- Desc.read P.description let name = Desc.name description let version = Desc.version description Cmd.out $ unwords [ "Verifying", Package.toString name, Package.versionToString version, "..." ] verifyMetadata description docs <- Docs.generate validity <- verifyVersion docs description newVersion <- case validity of Bump.Valid -> return version Bump.Invalid -> throwError "Cannot publish with an invalid version!" Bump.Changed v -> return v verifyTag name newVersion Catalog.register name newVersion Cmd.out "Success!" verifyMetadata :: Desc.Description -> Manager.Manager () verifyMetadata deps = case problems of [] -> return () _ -> throwError $ "Some of the fields in " ++ P.description ++ " have not been filled in yet:\n\n" ++ unlines problems ++ "\nFill these in and try to publish again!" where problems = Maybe.catMaybes [ verify Desc.repo " repository - must refer to a valid repo on GitHub" , verify Desc.summary " summary - a quick summary of your project, 80 characters or less" , verify Desc.exposed " exposed-modules - list modules your project exposes to users" ] verify getField msg = if getField deps == getField Desc.defaultDescription then Just msg else Nothing verifyVersion :: [Docs.Documentation] -> Desc.Description -> Manager.Manager Bump.Validity verifyVersion docs description = let name = Desc.name description version = Desc.version description in do maybeVersions <- Catalog.versions name case maybeVersions of Just publishedVersions -> Bump.validateVersion docs name version publishedVersions Nothing -> Bump.validateInitialVersion description verifyTag :: Package.Name -> Package.Version -> Manager.Manager () verifyTag name version = do publicVersions <- GitHub.getVersionTags name if version `elem` publicVersions then return () else throwError (tagMessage version) tagMessage :: Package.Version -> String tagMessage version = let v = Package.versionToString version in unlines [ "Libraries must be tagged in git, but tag " ++ v ++ " was not found." , "These tags make it possible to find this specific version on github." , "To tag the most recent commit and push it to github, run this:" , "" , " git tag -a " ++ v ++ " -m \"release version " ++ v ++ "\"" , " git push origin " ++ v , "" ]
laszlopandy/elm-package
src/Publish.hs
Haskell
bsd-3-clause
3,146
module Algebra.Structures.PID ( module Algebra.Structures.UFD , PID(..) ) where import Algebra.Structures.UFD class UFD a => PID a
Alex128/abstract-math
src/Algebra/Structures/PID.hs
Haskell
bsd-3-clause
148
{- Find things that are unsafe <TEST> {-# NOINLINE entries #-}; entries = unsafePerformIO newIO entries = unsafePerformIO Multimap.newIO -- {-# NOINLINE entries #-} ; entries = unsafePerformIO Multimap.newIO entries = unsafePerformIO $ f y where foo = 1 -- {-# NOINLINE entries #-} ; entries = unsafePerformIO $ f y where foo = 1 entries v = unsafePerformIO $ Multimap.newIO where foo = 1 entries v = x where x = unsafePerformIO $ Multimap.newIO entries = x where x = unsafePerformIO $ Multimap.newIO -- {-# NOINLINE entries #-} ; entries = x where x = unsafePerformIO $ Multimap.newIO entries = unsafePerformIO . bar entries = unsafePerformIO . baz $ x -- {-# NOINLINE entries #-} ; entries = unsafePerformIO . baz $ x entries = unsafePerformIO . baz $ x -- {-# NOINLINE entries #-} ; entries = unsafePerformIO . baz $ x </TEST> -} module Hint.Unsafe(unsafeHint) where import Hint.Type(DeclHint,ModuleEx(..),Severity(..),rawIdea,toSSA) import Data.List.Extra import Refact.Types hiding(Match) import Data.Generics.Uniplate.DataOnly import GHC.Hs import GHC.Types.Name.Occurrence import GHC.Types.Name.Reader import GHC.Data.FastString import GHC.Types.Basic import GHC.Types.SourceText import GHC.Types.SrcLoc import Language.Haskell.GhclibParserEx.GHC.Hs.Expr import Language.Haskell.GhclibParserEx.GHC.Utils.Outputable -- The conditions on which to fire this hint are subtle. We are -- interested exclusively in application constants involving -- 'unsafePerformIO'. For example, -- @ -- f = \x -> unsafePerformIO x -- @ -- is not such a declaration (the right hand side is a lambda, not an -- application) whereas, -- @ -- f = g where g = unsafePerformIO Multimap.newIO -- @ -- is. We advise that such constants should have a @NOINLINE@ pragma. unsafeHint :: DeclHint unsafeHint _ (ModuleEx (L _ m)) = \ld@(L loc d) -> [rawIdea Hint.Type.Warning "Missing NOINLINE pragma" (locA loc) (unsafePrettyPrint d) (Just $ trimStart (unsafePrettyPrint $ gen x) ++ "\n" ++ unsafePrettyPrint d) [] [InsertComment (toSSA ld) (unsafePrettyPrint $ gen x)] -- 'x' does not declare a new function. | d@(ValD _ FunBind {fun_id=L _ (Unqual x) , fun_matches=MG{mg_origin=FromSource,mg_alts=L _ [L _ Match {m_pats=[]}]}}) <- [d] -- 'x' is a synonym for an appliciation involing 'unsafePerformIO' , isUnsafeDecl d -- 'x' is not marked 'NOINLINE'. , x `notElem` noinline] where gen :: OccName -> LHsDecl GhcPs gen x = noLocA $ SigD noExtField (InlineSig EpAnnNotUsed (noLocA (mkRdrUnqual x)) (InlinePragma (SourceText "{-# NOINLINE") NoInline Nothing NeverActive FunLike)) noinline :: [OccName] noinline = [q | L _(SigD _ (InlineSig _ (L _ (Unqual q)) (InlinePragma _ NoInline Nothing NeverActive FunLike)) ) <- hsmodDecls m] isUnsafeDecl :: HsDecl GhcPs -> Bool isUnsafeDecl (ValD _ FunBind {fun_matches=MG {mg_origin=FromSource,mg_alts=L _ alts}}) = any isUnsafeApp (childrenBi alts) || any isUnsafeDecl (childrenBi alts) isUnsafeDecl _ = False -- Am I equivalent to @unsafePerformIO x@? isUnsafeApp :: HsExpr GhcPs -> Bool isUnsafeApp (OpApp _ (L _ l) op _ ) | isDol op = isUnsafeFun l isUnsafeApp (HsApp _ (L _ x) _) = isUnsafeFun x isUnsafeApp _ = False -- Am I equivalent to @unsafePerformIO . x@? isUnsafeFun :: HsExpr GhcPs -> Bool isUnsafeFun (HsVar _ (L _ x)) | x == mkVarUnqual (fsLit "unsafePerformIO") = True isUnsafeFun (OpApp _ (L _ l) op _) | isDot op = isUnsafeFun l isUnsafeFun _ = False
ndmitchell/hlint
src/Hint/Unsafe.hs
Haskell
bsd-3-clause
3,600
module Hhhhoard.Creds ( userEmail , userPassword) where userEmail :: String; userEmail = "[email protected]" userPassword :: String; userPassword = "password"
yan/hhhhoard
Hhhhoard/Creds.hs
Haskell
bsd-3-clause
168
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.EXT.DebugLabel -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/EXT/debug_label.txt EXT_debug_label> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.EXT.DebugLabel ( -- * Enums gl_BUFFER_OBJECT_EXT, gl_PROGRAM_OBJECT_EXT, gl_PROGRAM_PIPELINE_OBJECT_EXT, gl_QUERY_OBJECT_EXT, gl_SAMPLER, gl_SHADER_OBJECT_EXT, gl_TRANSFORM_FEEDBACK, gl_VERTEX_ARRAY_OBJECT_EXT, -- * Functions glGetObjectLabelEXT, glLabelObjectEXT ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/EXT/DebugLabel.hs
Haskell
bsd-3-clause
923
-- The Timber compiler <timber-lang.org> -- -- Copyright 2008-2009 Johan Nordlander <[email protected]> -- 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. -- -- 3. Neither the names of the copyright holder and any identified -- contributors, nor the names of their affiliations, may be used to -- endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS 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. {- ************************************************************************** ** This file is based on sources distributed as the haskell-src package ** ************************************************************************** The Glasgow Haskell Compiler License Copyright 2004, The University Court of the University of Glasgow. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 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. - Neither name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW AND THE 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 UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE 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 Lexer (Token(..), lexer, readInteger, readNumber, readRational) where import ParseMonad import Data.Char import Data.Ratio import Token import Common {- The source location, (y,x), is the coordinates of the previous token. col is the current column in the source file. If col is 0, we are somewhere at the beginning of the line before the first token. Setting col to 0 is used in two places: just after emitting a virtual close brace due to layout, so that next time through we check whether we also need to emit a semi-colon, and at the beginning of the file, to kick off the lexer. -} lexer :: (Token -> PM a) -> PM a lexer cont = PM $ \input (y,x) col -> if col == 0 then tab y x True input col else tab y col False input col -- throw away old x where -- move past whitespace and comments tab y x bol [] col = (unPM $ cont EOF) [] (y,x) col tab y x bol ('\t':s) col = tab y (nextTab x) bol s col tab y x bol ('\n':s) col = newLine s y col tab y x bol ('-':'-':s) col = newLine (drop 1 (dropWhile (/= '\n') s)) y col tab y x bol ('{':'-':s) col = nestedComment tab y x bol s col tab y x bol (c:s) col | isSpace c = tab y (x + 1) bol s col | otherwise = if bol then (unPM $ lexBOL cont) (c:s) (y,x) x else (unPM $ lexToken cont) (c:s) (y,x) x newLine s y col = tab (y + 1) 1 True s col nextTab x = x + (tab_length - (x - 1) `mod` tab_length) {- When we are lexing the first token of a line, check whether we need to insert virtual semicolons or close braces due to layout. -} lexBOL :: (Token -> PM a) -> PM a lexBOL cont = PM $ \ s loc@(y,x) col ctx -> if need_close_curly x ctx then -- tr' ("layout: inserting '}' at " ++ show loc ++ "\n") $ -- Set col to 0, indicating that we're still at the -- beginning of the line, in case we need a semi-colon too. -- Also pop the context here, so that we don't insert -- another close brace before the parser can pop it. (unPM $ cont VRightCurly) s loc 0 (tail ctx) else if need_semi_colon x ctx then -- tr' ("layout: inserting ';' at " ++ show loc ++ "\n") $ (unPM $ cont SemiColon) s loc col ctx else (unPM $ lexToken cont) s loc col ctx where need_close_curly x [] = False need_close_curly x (Layout n:Layout m:_) | n <= m = True need_close_curly x (i:_) = case i of NoLayout -> False Layout n -> x < n RecLayout n -> False need_semi_colon x [] = False need_semi_colon x (i:_) = case i of NoLayout -> False Layout n -> x == n RecLayout n -> x == n lexToken :: (Token -> PM a) -> PM a lexToken cont = PM lexToken' where lexToken' (c:s) loc@(y,x') x = -- trace ("lexer: y = " ++ show y ++ " x = " ++ show x ++ "\n") $ case c of -- First the special symbols '(' -> special LeftParen ')' -> special RightParen ',' -> special Comma ';' -> special SemiColon '[' -> special LeftSquare ']' -> special RightSquare '`' -> special BackQuote '{' -> special LeftCurly '}' -> \state -> case state of (_:ctxt) -> special RightCurly ctxt -- pop context on } [] -> (unPM $ parseError "parse error (possibly incorrect indentation)") s loc x [] '\'' -> (unPM $ lexChar cont) s loc (x + 1) '\"' -> (unPM $ lexString cont) s loc (x + 1) '_' | null s || not (isIdent (head s)) -> special Wildcard c | isDigit c -> case lexInt (c:s) of Decimal (n, rest) -> case rest of ('.':c2:rest2) | isDigit c2 -> case lexFloatRest (c2:rest2) of Nothing -> (unPM $ parseError "illegal float.") s loc x Just (n2,rest3) -> let f = n ++ ('.':n2) in forward (length f) (FloatTok f) rest3 _ -> forward (length n) (IntTok n) rest Octal (n,rest) -> forward (length n) (IntTok n) rest Hexadecimal (n,rest) -> forward (length n) (IntTok n) rest | isLower c -> lexVarId "" c s | isUpper c -> lexQualName "" c s | isSymbol c -> lexSymbol "" c s | otherwise -> (unPM $ parseError ("illegal character \'" ++ showLitChar c "" ++ "\'\n")) s loc x where special t = forward 1 t s forward n t s = (unPM $ cont t) s loc (x + n) join "" n = n join q n = q ++ '.' : n len "" n = length n len q n = length q + length n + 1 lexFloatRest r = case span isDigit r of (r2, 'e':r3) -> lexFloatExp (r2 ++ "e") r3 (r2, 'E':r3) -> lexFloatExp (r2 ++ "e") r3 f@(r2, r3) -> Just f lexFloatExp r1 ('-':r2) = lexFloatExp2 (r1 ++ "-") r2 lexFloatExp r1 ('+':r2) = lexFloatExp2 (r1 ++ "+") r2 lexFloatExp r1 r2 = lexFloatExp2 r1 r2 lexFloatExp2 r1 r2 = case span isDigit r2 of ("", _ ) -> Nothing (ds, r3) -> Just (r1++ds,r3) lexVarId q c s = let (vidtail, rest) = span isIdent s vid = c:vidtail l_vid = len q vid in case lookup vid reserved_ids of Just keyword -> case q of "" -> forward l_vid keyword rest _ -> (unPM $ parseError "illegal qualified name") s loc x Nothing -> forward l_vid (VarId (q,vid)) rest lexQualName q c s = let (contail, rest) = span isIdent s con = join q (c:contail) l_con = length con in case rest of '.': c' : rest' | isUpper c' -> lexQualName con c' rest' | isLower c' -> lexVarId con c' rest' | isSymbol c' -> lexSymbol con c' rest' | otherwise -> (unPM $ parseError "illegal qualified name") s loc x _ -> forward l_con (ConId (q,c:contail)) rest lexSymbol q c s = let (symtail, rest) = span isSymbol s sym = c:symtail l_sym = len q sym in case lookup sym reserved_ops of Just t -> case q of "" -> forward l_sym t rest _ -> (unPM $ parseError "illegal qualified name") s loc x Nothing -> case c of ':' -> forward l_sym (ConSym (q,sym)) rest _ -> forward l_sym (VarSym (q,sym)) rest lexToken' _ _ _ = internalError0 "Lexer.lexToken: empty input stream." lexInt ('0':o:d:r) | toLower o == 'o' && isOctDigit d = let (ds, rs) = span isOctDigit r in Octal ('0':'o':d:ds, rs) lexInt ('0':x:d:r) | toLower x == 'x' && isHexDigit d = let (ds, rs) = span isHexDigit r in Hexadecimal ('0':'x':d:ds, rs) lexInt r = Decimal (span isDigit r) lexChar :: (Token -> PM a) -> PM a lexChar cont = PM lexChar' where lexChar' s loc@(y,_) x = case s of '\\':s -> let (e, s2, i) = runPM (escapeChar s) "" loc x [] in charEnd e s2 loc (x + i) c:s -> charEnd c s loc (x + 1) [] -> internalError0 "Lexer.lexChar: empty list." charEnd c ('\'':s) = \loc x -> (unPM $ cont (Character c)) s loc (x + 1) charEnd c s = (unPM $ parseError "improperly terminated character constant.") s lexString :: (Token -> PM a) -> PM a lexString cont = PM lexString' where lexString' s loc@(y',_) x = loop "" s x y' where loop e s x y = case s of '\\':'&':s -> loop e s (x+2) y '\\':c:s | isSpace c -> stringGap e s (x + 2) y | otherwise -> let (e', sr, i) = runPM (escapeChar (c:s)) "" loc x [] in loop (e':e) sr (x+i) y '\"':s{-"-} -> (unPM $ cont (StringTok (reverse e))) s loc (x + 1) c:s -> loop (c:e) s (x + 1) y [] -> (unPM $ parseError "improperly terminated string.") s loc x stringGap e s x y = case s of '\n':s -> stringGap e s 1 (y + 1) '\\':s -> loop e s (x + 1) y c:s' | isSpace c -> stringGap e s' (x + 1) y | otherwise -> (unPM $ parseError "illegal character in string gap.") s loc x [] -> internalError0 "Lexer.stringGap: empty list." escapeChar :: String -> PM (Char, String, Int) escapeChar s = case s of 'a':s -> return ('\a', s, 2) 'b':s -> return ('\b', s, 2) 'f':s -> return ('\f', s, 2) 'n':s -> return ('\n', s, 2) 'r':s -> return ('\r', s, 2) 't':s -> return ('\t', s, 2) 'v':s -> return ('\v', s, 2) '\\':s -> return ('\\', s, 2) '"':s -> return ('\"', s, 2) -- " '\'':s -> return ('\'', s, 2) '^':x@(c:s) -> cntrl x 'N':'U':'L':s -> return ('\NUL', s, 4) 'S':'O':'H':s -> return ('\SOH', s, 4) 'S':'T':'X':s -> return ('\STX', s, 4) 'E':'T':'X':s -> return ('\ETX', s, 4) 'E':'O':'T':s -> return ('\EOT', s, 4) 'E':'N':'Q':s -> return ('\ENQ', s, 4) 'A':'C':'K':s -> return ('\ACK', s, 4) 'B':'E':'L':s -> return ('\BEL', s, 4) 'B':'S':s -> return ('\BS', s, 3) 'H':'T':s -> return ('\HT', s, 3) 'L':'F':s -> return ('\LF', s, 3) 'V':'T':s -> return ('\VT', s, 3) 'F':'F':s -> return ('\FF', s, 3) 'C':'R':s -> return ('\CR', s, 3) 'S':'O':s -> return ('\SO', s, 3) 'S':'I':s -> return ('\SI', s, 3) 'D':'L':'E':s -> return ('\DLE', s, 4) 'D':'C':'1':s -> return ('\DC1', s, 4) 'D':'C':'2':s -> return ('\DC2', s, 4) 'D':'C':'3':s -> return ('\DC3', s, 4) 'D':'C':'4':s -> return ('\DC4', s, 4) 'N':'A':'K':s -> return ('\NAK', s, 4) 'S':'Y':'N':s -> return ('\SYN', s, 4) 'E':'T':'B':s -> return ('\ETB', s, 4) 'C':'A':'N':s -> return ('\CAN', s, 4) 'E':'M':s -> return ('\EM', s, 3) 'S':'U':'B':s -> return ('\SUB', s, 4) 'E':'S':'C':s -> return ('\ESC', s, 4) 'F':'S':s -> return ('\FS', s, 3) 'G':'S':s -> return ('\GS', s, 3) 'R':'S':s -> return ('\RS', s, 3) 'U':'S':s -> return ('\US', s, 3) 'S':'P':s -> return ('\SP', s, 3) 'D':'E':'L':s -> return ('\DEL', s, 4) -- Depending upon the compiler/interpreter's Char type, these yield either -- just 8-bit ISO-8859-1 or 2^16 UniCode. -- Octal representation of a character 'o':s -> let (ds, s') = span isOctDigit s n = readNumber 8 ds in numberToChar n s' (length ds + 1) -- Hexadecimal representation of a character 'x':s -> let (ds, s') = span isHexDigit s n = readNumber 16 ds in numberToChar n s' (length ds + 1) -- Base 10 representation of a character d:s | isDigit d -> let (ds, s') = span isDigit s n = readNumber 10 (d:ds) in numberToChar n s' (length ds + 1) _ -> parseError "illegal escape sequence." where numberToChar n s l_n = if n < (toInteger $ fromEnum (minBound :: Char)) || n > (toInteger $ fromEnum (maxBound :: Char)) then parseError "illegal character literal (number out of range)." else return (chr $ fromInteger n, s, l_n) cntrl :: String -> PM (Char, String, Int) cntrl (c :s) | isUpper c = return (chr (ord c - ord 'A'), s, 2) cntrl ('@' :s) = return ('\^@', s, 2) cntrl ('[' :s) = return ('\^[', s, 2) cntrl ('\\':s) = return ('\^\', s, 2) cntrl (']' :s) = return ('\^]', s, 2) cntrl ('^' :s) = return ('\^^', s, 2) cntrl ('_' :s) = return ('\^_', s, 2) cntrl _ = parseError "illegal control character" nestedComment cont y x bol s col = case s of '-':'}':s -> cont y (x + 2) bol s col '{':'-':s -> nestedComment (nestedComment cont) y (x + 2) bol s col '\t':s -> nestedComment cont y (nextTab x) bol s col '\n':s -> nestedComment cont (y + 1) 1 True s col c:s -> nestedComment cont y (x + 1) bol s col [] -> compileError "Open comment at end of file" readInteger :: String -> Integer readInteger ('0':'o':ds) = readInteger2 8 isOctDigit ds readInteger ('0':'O':ds) = readInteger2 8 isOctDigit ds readInteger ('0':'x':ds) = readInteger2 16 isHexDigit ds readInteger ('0':'X':ds) = readInteger2 16 isHexDigit ds readInteger ds = readInteger2 10 isDigit ds readNumber :: Integer -> String -> Integer readNumber radix ds = readInteger2 radix (const True) ds readInteger2 :: Integer -> (Char -> Bool) -> String -> Integer readInteger2 radix isDig ds = foldl1 (\n d -> n * radix + d) (map (fromIntegral . digitToInt) (takeWhile isDig ds)) readRational :: String -> Rational readRational xs = (readInteger (i ++ m))%1 * 10^^((case e of "" -> 0 ('+':e2) -> read e2 _ -> read e) - length m) where (i, r1) = span isDigit xs (m, r2) = span isDigit (dropWhile (== '.') r1) e = dropWhile (== 'e') r2
UBMLtonGroup/timberc
src/Lexer.hs
Haskell
bsd-3-clause
18,665
{-# LANGUAGE CPP, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Array.Class -- Copyright : (C) 2011 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : type families, MPTCs -- ---------------------------------------------------------------------------- module Control.Monad.Array.Class ( MonadArray(..) , MonadUArray(..) ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Concurrent.STM import Control.Monad (liftM) import Control.Monad.ST import Control.Monad.Trans.Class import Data.Array.Base import Data.Array.IO import Data.Array.ST import Data.Array.MArray.Extras import Foreign.Ptr import Foreign.StablePtr import Data.Int import Data.Word -- | Arr m serves as a canonical choice of boxed MArray class Monad m => MonadArray m where data Arr m :: * -> * -> * getBoundsM :: Ix i => Arr m i e -> m (i, i) getNumElementsM :: Ix i => Arr m i e -> m Int newArrayM :: Ix i => (i, i) -> e -> m (Arr m i e) newArrayM_ :: Ix i => (i, i) -> m (Arr m i e) unsafeNewArrayM_ :: Ix i => (i, i) -> m (Arr m i e) unsafeReadM :: Ix i => Arr m i e -> Int -> m e unsafeWriteM :: Ix i => Arr m i e -> Int -> e -> m () instance MonadArray m => MArray (Arr m) e m where getBounds = getBoundsM getNumElements = getNumElementsM newArray = newArrayM unsafeNewArray_ = unsafeNewArrayM_ newArray_ = newArrayM_ unsafeRead = unsafeReadM unsafeWrite = unsafeWriteM instance MonadArray IO where newtype Arr IO i e = ArrIO { runArrIO :: IOArray i e } getBoundsM = getBounds . runArrIO getNumElementsM = getNumElements . runArrIO newArrayM bs e = ArrIO <$> newArray bs e newArrayM_ bs = ArrIO <$> newArray_ bs unsafeNewArrayM_ bs = ArrIO <$> unsafeNewArray_ bs unsafeReadM (ArrIO a) i = unsafeRead a i unsafeWriteM (ArrIO a) i e = unsafeWrite a i e instance MonadArray (ST s) where newtype Arr (ST s) i e = ArrST { runArrST :: STArray s i e } getBoundsM = getBounds . runArrST getNumElementsM = getNumElements . runArrST newArrayM bs e = ArrST <$> newArray bs e newArrayM_ bs = ArrST <$> newArray_ bs unsafeNewArrayM_ bs = ArrST <$> unsafeNewArray_ bs unsafeReadM (ArrST a) i = unsafeRead a i unsafeWriteM (ArrST a) i e = unsafeWrite a i e instance MonadArray STM where newtype Arr STM i e = ArrSTM { runArrSTM :: TArray i e } getBoundsM = getBounds . runArrSTM getNumElementsM = getNumElements . runArrSTM newArrayM bs e = ArrSTM <$> newArray bs e newArrayM_ bs = ArrSTM <$> newArray_ bs unsafeNewArrayM_ bs = ArrSTM <$> unsafeNewArray_ bs unsafeReadM (ArrSTM a) i = unsafeRead a i unsafeWriteM (ArrSTM a) i e = unsafeWrite a i e instance (MonadTrans t, Monad (t m), MonadArray m) => MonadArray (t m) where newtype Arr (t m) i e = ArrT { runArrT :: Arr m i e } getBoundsM = lift . getBounds . runArrT getNumElementsM = lift . getNumElements . runArrT newArrayM bs e = lift $ ArrT `liftM` newArray bs e newArrayM_ bs = lift $ ArrT `liftM` newArray_ bs unsafeNewArrayM_ bs = lift $ ArrT `liftM` unsafeNewArray_ bs unsafeReadM (ArrT a) i = lift $ unsafeRead a i unsafeWriteM (ArrT a) i e = lift $ unsafeWrite a i e -- | UArr m provides unboxed arrays, and can be used on the primitive data types: -- -- 'Bool', 'Char', 'Int', 'Word', 'Double', 'Float', 'Int8', 'Int16', 'Int32', 'Int64', 'Word8', -- 'Word16', 'Word32', and 'Word64' -- -- It can be used via 'MArray1' to store values of types @'StablePtr' a@, @'FunPtr' a@ and @'Ptr a'@ as well. class ( MonadArray m , MArray (UArr m) Bool m , MArray (UArr m) Char m , MArray (UArr m) Int m , MArray (UArr m) Word m , MArray (UArr m) Double m , MArray (UArr m) Float m , MArray (UArr m) Int8 m , MArray (UArr m) Int16 m , MArray (UArr m) Int32 m , MArray (UArr m) Int64 m , MArray (UArr m) Word8 m , MArray (UArr m) Word16 m , MArray (UArr m) Word32 m , MArray (UArr m) Word64 m , MArray1 (UArr m) StablePtr m , MArray1 (UArr m) FunPtr m , MArray1 (UArr m) Ptr m ) => MonadUArray m where data UArr m :: * -> * -> * instance MArray IOUArray e IO => MArray (UArr IO) e IO where getBounds = getBounds . runUArrIO getNumElements = getNumElements . runUArrIO newArray bs e = UArrIO <$> newArray bs e newArray_ bs = UArrIO <$> newArray_ bs unsafeNewArray_ bs = UArrIO <$> unsafeNewArray_ bs unsafeRead (UArrIO a) i = unsafeRead a i unsafeWrite (UArrIO a) i e = unsafeWrite a i e instance MArray1 IOUArray e IO => MArray1 (UArr IO) e IO where getBounds1 = getBounds1 . runUArrIO getNumElements1 = getNumElements1 . runUArrIO newArray1 bs e = UArrIO <$> newArray1 bs e newArray1_ bs = UArrIO <$> newArray1_ bs unsafeNewArray1_ bs = UArrIO <$> unsafeNewArray1_ bs unsafeRead1 (UArrIO a) i = unsafeRead1 a i unsafeWrite1 (UArrIO a) i e = unsafeWrite1 a i e instance MonadUArray IO where newtype UArr IO i e = UArrIO { runUArrIO :: IOUArray i e } instance MArray (STUArray s) e (ST s) => MArray (UArr (ST s)) e (ST s) where getBounds = getBounds . runUArrST getNumElements = getNumElements . runUArrST newArray bs e = UArrST <$> newArray bs e newArray_ bs = UArrST <$> newArray_ bs unsafeNewArray_ bs = UArrST <$> unsafeNewArray_ bs unsafeRead (UArrST a) i = unsafeRead a i unsafeWrite (UArrST a) i e = unsafeWrite a i e instance MArray1 (STUArray s) e (ST s) => MArray1 (UArr (ST s)) e (ST s) where getBounds1 = getBounds1 . runUArrST getNumElements1 = getNumElements1 . runUArrST newArray1 bs e = UArrST <$> newArray1 bs e newArray1_ bs = UArrST <$> newArray1_ bs unsafeNewArray1_ bs = UArrST <$> unsafeNewArray1_ bs unsafeRead1 (UArrST a) i = unsafeRead1 a i unsafeWrite1 (UArrST a) i e = unsafeWrite1 a i e instance MonadUArray (ST s) where newtype UArr (ST s) i e = UArrST { runUArrST :: STUArray s i e } instance (MonadTrans t, Monad (t m), MonadUArray m, MArray (UArr m) e m) => MArray (UArr (t m)) e (t m) where getBounds = lift . getBounds . runUArrT getNumElements = lift . getNumElements . runUArrT newArray bs e = lift $ UArrT `liftM` newArray bs e newArray_ bs = lift $ UArrT `liftM` newArray_ bs unsafeNewArray_ bs = lift $ UArrT `liftM` unsafeNewArray_ bs unsafeRead (UArrT a) i = lift $ unsafeRead a i unsafeWrite (UArrT a) i e = lift $ unsafeWrite a i e instance (MonadTrans t, Monad (t m), MonadUArray m, MArray1 (UArr m) f m) => MArray1 (UArr (t m)) f (t m) where getBounds1 = lift . getBounds1 . runUArrT getNumElements1 = lift . getNumElements1 . runUArrT newArray1 bs e = lift $ UArrT `liftM` newArray1 bs e newArray1_ bs = lift $ UArrT `liftM` newArray1_ bs unsafeNewArray1_ bs = lift $ UArrT `liftM` unsafeNewArray1_ bs unsafeRead1 (UArrT a) i = lift $ unsafeRead1 a i unsafeWrite1 (UArrT a) i e = lift $ unsafeWrite1 a i e instance (MonadTrans t, Monad (t m), MonadUArray m) => MonadUArray (t m) where newtype UArr (t m) i e = UArrT { runUArrT :: UArr m i e }
ekmett/monadic-arrays
Control/Monad/Array/Class.hs
Haskell
bsd-3-clause
7,851
{-# LANGUAGE CPP #-} module Language.Sh.Glob ( expandGlob, matchPattern, removePrefix, removeSuffix ) where import Control.Monad.Trans ( MonadIO, liftIO ) import Control.Monad.State ( runState, put ) import Data.Char ( ord, chr ) import Data.List ( isPrefixOf, partition ) import Data.Maybe ( isJust, listToMaybe ) import System.Directory ( getCurrentDirectory ) import System.FilePath ( pathSeparator, isPathSeparator, isExtSeparator ) import Text.Regex.PCRE.Light.Char8 ( Regex, compileM, match, ungreedy ) import Language.Sh.Syntax ( Lexeme(..), Word ) -- we might get a bit fancier if older glob libraries will support -- a subset of what we want to do...? #ifdef HAVE_GLOB import System.FilePath.Glob ( tryCompile, globDir, factorPath ) #endif expandGlob :: MonadIO m => Word -> m [FilePath] #ifdef HAVE_GLOB expandGlob w = case mkGlob w of Nothing -> return [] Just g -> case tryCompile g of Right g' -> liftIO $ do let (dir,g'') = factorPath g' liftIO $ putStrLn $ show (dir,g'') hits <- globDir [g''] dir return $ head $ fst $ hits _ -> return [] #else expandGlob = const $ return [] #endif -- By the time this is called, we should only have quotes and quoted -- literals to worry about. In the event of finding an unquoted glob -- char (and if the glob matches) we'll automatically remove quotes, etc. -- (since the next stage is, after all, quote removal). mkGlob :: Word -> Maybe String mkGlob w = case runState (mkG w) False of (s,True) -> Just s _ -> Nothing where mkG [] = return [] mkG (Literal '[':xs) = case mkClass xs of Just (g,xs') -> fmap (g++) $ mkG xs' Nothing -> fmap ((mkLit '[')++) $ mkG xs mkG (Literal '*':Literal '*':xs) = mkG $ Literal '*':xs mkG (Literal '*':xs) = put True >> fmap ('*':) (mkG xs) mkG (Literal '?':xs) = put True >> fmap ('?':) (mkG xs) mkG (Literal c:xs) = fmap (mkLit c++) $ mkG xs mkG (Quoted (Literal c):xs) = fmap (mkLit c++) $ mkG xs mkG (Quoted q:xs) = mkG $ q:xs mkG (Quote _:xs) = mkG xs mkLit c | c `elem` "[*?<" = ['[',c,']'] | otherwise = [c] -- This is basically gratuitously copied from Glob's internals. mkClass :: Word -> Maybe (String,Word) mkClass xs = let (range, rest) = break (isLit ']') xs in if null rest then Nothing else if null range then let (range', rest') = break (isLit ']') (tail rest) in if null rest' then Nothing else do x <- cr' range' return (x,tail rest') else do x <- cr' range return (x,tail rest) where cr' s = Just $ "["++movedash (filter (not . isQuot) s)++"]" isLit c x = case x of { Literal c' -> c==c'; _ -> False } isQuot x = case x of { Quote _ -> True; _ -> False } quoted c x = case x of Quoted (Quoted x) -> quoted c $ Quoted x Quoted (Literal c') -> c==c' _ -> False movedash s = let (d,nd) = partition (quoted '-') s bad = null d || (isLit '-' $ head $ reverse s) in map fromLexeme $ if bad then nd else nd++d fromLexeme x = case x of { Literal c -> c; Quoted q -> fromLexeme q } {- expandGlob :: MonadIO m => Word -> m [FilePath] expandGlob w = case mkGlob w of Nothing -> return [] Just g -> case G.unPattern g of (G.PathSeparator:_) -> liftIO $ do hits <- G.globDir [g] "/" -- unix...? let ps = [pathSeparator] return $ head $ fst $ hits _ -> liftIO $ do cwd <- getCurrentDirectory hits <- G.globDir [g] cwd let ps = [pathSeparator] return $ map (removePrefix $ cwd++ps) $ head $ fst $ hits where removePrefix pre s | pre `isPrefixOf` s = drop (length pre) s | otherwise = s -} -- Two issues: we can deal with them here... -- 1. if glob starts with a dirsep then we need to go relative to root... -- (what about in windows?) -- 2. if not, then we should remove the absolute path from the beginning of -- the results (should be easy w/ a map) {- -- This is a sort of default matcher, but needn't be used... matchGlob :: MonadIO m => Glob -> m [FilePath] matchGlob g = matchG' [] $ splitDir return $ do -- now we're in the list monad... where d = splitDir g splitDir (c:xs) | ips c = []:splitDir (dropWhile ips xs) splitDir xs = filter (not . null) $ filter (not . all ips) $ groupBy ((==) on ips) xs ips x = case x of { Lit c -> isPathSeparator c; _ -> False } -} ---------------------------------------------------------------------- -- This is copied from above, but it's used separately for non-glob -- -- pattern matching. Maybe we'll combine them someday. -- ---------------------------------------------------------------------- match' :: Regex -> String -> Maybe String match' regex s = listToMaybe =<< match regex s [] matchPattern :: Word -> String -> Bool matchPattern w s = case mkRegex False False "^" "$" w of Just r -> isJust $ match r s [] Nothing -> fromLit w == s removePrefix :: Bool -- ^greediness -> Word -- ^pattern -> String -- ^haystack -> String removePrefix g n h = case mkRegex g False "^" "" n of Just r -> case match' r h of Just m -> drop (length m) h Nothing -> h Nothing -> if l `isPrefixOf` h then drop (length l) h else h where l = fromLit n removeSuffix :: Bool -- ^greediness -> Word -- ^pattern -> String -- ^haystack -> String removeSuffix g n h = case mkRegex g True "^" "" n of Just r -> case match' r hr of Just m -> reverse $ drop (length m) hr Nothing -> h Nothing -> if l `isPrefixOf` hr then reverse $ drop (length l) hr else h where l = reverse $ fromLit n hr = reverse h mkRegex :: Bool -- ^greedy? -> Bool -- ^reverse? (before adding pre/suff) -> String -- ^prefix -> String -- ^suffix -> Word -- ^pattern -> Maybe Regex mkRegex g r pre suf w = case runState (mkG w) False of (s,True) -> mk' $ concat $ affix $ (if r then reverse else id) s _ -> Nothing where mkG [] = return [] mkG (Literal '[':xs) = case mkClass xs of Just (g,xs') -> fmap (g:) $ mkG xs' Nothing -> fmap ((mkLit '['):) $ mkG xs mkG (Literal '*':Literal '*':xs) = mkG $ Literal '*':xs mkG (Literal '*':xs) = put True >> fmap (".*":) (mkG xs) mkG (Literal '?':xs) = put True >> fmap (".":) (mkG xs) mkG (Literal c:xs) = fmap (mkLit c:) $ mkG xs mkG (Quoted (Literal c):xs) = fmap (mkLit c:) $ mkG xs mkG (Quoted q:xs) = mkG $ q:xs mkG (Quote _:xs) = mkG xs mkLit c | c `elem` "[](){}|^$.*+?\\" = ['\\',c] | otherwise = [c] affix s = pre:s++[suf] mk' s = case compileM s (if g then [] else [ungreedy]) of Left _ -> Nothing Right regex -> Just regex fromLit :: Word -> String fromLit = concatMap $ \l -> case l of Literal c -> [c] Quoted q -> fromLit [q] _ -> []
MgaMPKAy/language-sh
Language/Sh/Glob.hs
Haskell
bsd-3-clause
8,582
-- {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} -- we are deriving Monoid instance for Config type -- {-# OPTIONS_GHC -fno-warn-missing-methods #-} module System.EtCetera.Redis.V2_8 where import Control.Applicative (Alternative) import Control.Arrow (first) import Control.Category (Category, id, (.)) import Control.Error (note) import Control.Lens (DefName(..), Lens', lensField, lensRules, makeLensesWith, over, set, view, (&), (.~), (??)) import Data.List (foldl') import Data.Monoid ((<>)) import qualified Data.Set as Set import Generics.Deriving.Base (Generic) import Generics.Deriving.Monoid (gmappend, gmempty, GMonoid) import Generics.Deriving.Show (gshow, GShow) import Language.Haskell.TH (mkName, Name, nameBase) import Prelude hiding ((.), id) import Text.Boomerang.Combinators (manyl, manyr, opt, push, rCons, rList, rList1, rListSep, rNil, somel, somer) import Text.Boomerang.HStack (arg, (:-)(..)) import Text.Boomerang.Prim (Boomerang(..), Parser(..), prs, xpure) import Text.Boomerang.String (anyChar, digit, lit, int, StringBoomerang, StringError) import System.EtCetera.Internal (Optional(..), repeatableScalar, scalar, vector) import System.EtCetera.Internal.Prim (Ser(..), toPrs) import System.EtCetera.Internal.Boomerangs (eol, ignoreWhen, noneOf, oneOf, parseString, simpleSumBmg, whiteSpace, word, (<?>)) type IP = String type Port = Int data SizeUnit = K | M | G | Kb | Mb | Gb deriving (Eq, Read, Show) data Size = Size Int SizeUnit deriving (Eq, Show) sizeBmg :: StringBoomerang r (Size :- r) sizeBmg = xpure (arg (arg (:-)) Size) (\(Size i u :- r) -> Just (i :- u :- r)) . int . simpleSumBmg ["k", "m", "g", "kb", "mb", "gb"] data RenameCommand = RenameCommand String String | DisableCommand String deriving (Eq, Show) renameCommandBmg :: StringBoomerang r (RenameCommand :- r) renameCommandBmg = c . string . ws . string where c = xpure (arg (arg (:-)) (\c n -> if n == "\"\"" then DisableCommand c else RenameCommand c n)) (\case (DisableCommand c :- r) -> Just (c :- "\"\"" :- r) (RenameCommand o n :- r) -> Just (o :- n :- r)) data MemoryPolicy = VolatileLru | AllkeysLru | VolatileRandom | AllkeysRandom | VolatileTtl | Noeviction deriving (Eq, Show) memoryPolicyBmg :: StringBoomerang r (MemoryPolicy :- r) memoryPolicyBmg = xpure (arg (:-) p) (\(mp :- r) -> (Just (s mp :- r))) . (word "volatile-lru" <> word "allkeys-lru" <> word "volatile-random" <> word "allkeys-random" <> word "volatile-ttl" <> word "noeviction") where p "volatile-lru" = VolatileLru p "allkeys-lru" = AllkeysLru p "volatile-random" = VolatileRandom p "allkeys-random" = AllkeysRandom p "volatile-ttl" = VolatileTtl p "noeviction" = Noeviction s VolatileLru = "volatile-lru" s AllkeysLru = "allkeys-lru" s VolatileRandom = "volatile-random" s AllkeysRandom = "allkeys-random" s VolatileTtl = "volatile-ttl" s Noeviction = "noeviction" data LogLevel = Debug | Verbose | Notice | Warning deriving (Eq, Read, Show) logLevelBmg :: StringBoomerang r (LogLevel :- r) logLevelBmg = simpleSumBmg ["debug", "verbose", "notice", "warning"] data SyslogFacility = User | Local0 | Local1 | Local2 | Local3 | Local4 | Local5 | Local6 | Local7 deriving (Eq, Read, Show) syslogFacilityBmg :: StringBoomerang r (SyslogFacility :- r) syslogFacilityBmg = simpleSumBmg [ "user", "local0", "local1", "local2", "local3" , "local4", "local5", "local6" , "local7"] data Save = Save Int Int | SaveReset deriving (Eq, Show) saveBmg = s <> sr where s = xpure (arg (arg (:-)) Save) (\case (Save s c :- r) -> Just (s :- c :- r) otherwise -> Nothing) . int . ws . int sr = push SaveReset . lit "\"\"" string :: StringBoomerang r (String :- r) string = rList1 (noneOf "\n \t") slaveOfBmg :: StringBoomerang r ((IP, Port) :- r) slaveOfBmg = xpure (arg (arg (:-)) (\ip port -> (ip, port))) (\((ip, port) :- r) -> Just (ip :- port :- r)) . string . ws . int data AppendFsync = Always | No | Everysec deriving (Eq, Read, Show) appendFsyncBmg :: StringBoomerang r (AppendFsync :- r) appendFsyncBmg = simpleSumBmg ["always", "no", "everysec"] data KeyspaceEvnType = KeyspaceEvns | KeyeventEvns | GenericCmds | StringCmds | ListCmds | SetCmds | HashCmds | SortedSetCmds | ExpiredEvns | EvictedEvns deriving (Eq, Ord, Show) -- can be used as a A keyspaceEvnA = Set.fromList [ GenericCmds, StringCmds, ListCmds , SetCmds , HashCmds, SortedSetCmds , ExpiredEvns, EvictedEvns ] data KeyspaceEvn = SetKespaceEvns (Set.Set KeyspaceEvnType) | DisableKeyspaceEvns deriving (Eq, Show) keyspaceEvnTypeBmg :: StringBoomerang (String :- r) (Set.Set KeyspaceEvnType :- r) keyspaceEvnTypeBmg = xpure (arg (:-) parse) (\(es :- r) -> Just (serialize es :- r)) where serialize = foldl' (\r e -> s e : r) "" where s KeyspaceEvns = 'K' s KeyeventEvns = 'E' s GenericCmds = 'g' s StringCmds = '$' s ListCmds = 'l' s SetCmds = 's' s HashCmds = 'h' s SortedSetCmds = 'z' s ExpiredEvns = 'x' s EvictedEvns = 'e' parse = foldl' (flip p) Set.empty where p 'K' = Set.insert KeyspaceEvns p 'E' = Set.insert KeyeventEvns p 'g' = Set.insert GenericCmds p '$' = Set.insert StringCmds p 'l' = Set.insert ListCmds p 's' = Set.insert SetCmds p 'h' = Set.insert HashCmds p 'z' = Set.insert SortedSetCmds p 'x' = Set.insert ExpiredEvns p 'e' = Set.insert EvictedEvns p 'A' = Set.union keyspaceEvnA keyspaceEvnBmg :: StringBoomerang r (KeyspaceEvn :- r) keyspaceEvnBmg = (d . word "\"\"") <> (e . keyspaceEvnTypeBmg . rList1 (oneOf "KEg$lshzxeA")) where d = xpure (arg (:-) (const DisableKeyspaceEvns)) (\case (DisableKeyspaceEvns :- r) -> Just ("\"\"" :- r) otherwise -> Nothing) e = xpure (arg (:-) SetKespaceEvns) (\case (SetKespaceEvns s :- r) -> Just (s :- r) otherwise -> Nothing) data ClientOutputBufferLimitSize = ClientOutputBufferLimitSize { soft :: Size , hard :: Size , softSecods :: Int } deriving (Eq, Show) clientOutputBufferLimitBmg :: StringBoomerang r (ClientOutputBufferLimitSize :- r) clientOutputBufferLimitBmg = c . sizeBmg . ws . sizeBmg . ws . int where c = xpure (arg (arg (arg (:-))) ClientOutputBufferLimitSize) (\(ClientOutputBufferLimitSize s h ss :- r) -> Just (s :- h :- ss :- r)) strings :: StringBoomerang r ([String] :- r) strings = rListSep string (somer whiteSpace) bool :: StringBoomerang r (Bool :- r) bool = xpure (arg (:-) (\case "no" -> False "yes" -> True)) (\case (True :- r) -> Just ("yes" :- r) (False :- r) -> Just ("no" :- r)) . (word "yes" <> word "no") ws = somel whiteSpace data RedisConfig = RedisConfig { include :: [FilePath] , daemonize :: Optional Bool , port :: Optional Int , pidFile :: Optional FilePath , tcpBacklog :: Optional Int , bind :: [String] , unixSocket :: Optional FilePath -- XXX: add more type safety , unixSocketPerm :: Optional String , timeout :: Optional Int , tcpKeepAlive :: Optional Int , logLevel :: Optional LogLevel , logFile :: Optional FilePath , syslogEnabled :: Optional Bool , syslogIdent :: Optional String , syslogFacility :: Optional SyslogFacility , databases :: Optional Int , save :: [Save] , stopWritesOnBgsaveError :: Optional Bool , rdbCompression :: Optional Bool , rdbChecksum :: Optional Bool , dbFilename :: Optional FilePath , dir :: Optional FilePath , slaveOf :: Optional (IP, Port) , masterAuth :: Optional String , slaveServeStaleData :: Optional Bool , slaveReadOnly :: Optional Bool , replDisklessSync :: Optional Bool , replDisklessSyncDelay :: Optional Int , replPingSlavePeriod :: Optional Int , replTimeout :: Optional Int , replDisableTcpNoDelay :: Optional Bool , replBacklogSize :: Optional Size , replBacklogTtl :: Optional Int , slavePriority :: Optional Int , minSlavesToWrite :: Optional Int , minSlavesMaxLag :: Optional Int , requirePass :: Optional String , renameCommand :: [RenameCommand] , maxClients :: Optional Int , maxMemory :: Optional Int , maxMemoryPolicy :: Optional MemoryPolicy , maxMemorySamples :: Optional Int , appendOnly :: Optional Bool , appendFilename :: Optional String , appendFsync :: Optional AppendFsync , noAppendFsyncOnRewrite :: Optional Bool , autoAofRewritePercentage :: Optional Int , autoAofRewriteMinSize :: Optional Size , aofLoadTruncated :: Optional Bool , luaTimeLimit :: Optional Int , slowlogLogSlowerThan :: Optional Int , slowlogMaxLen :: Optional Int , latencyMonitorThreshold :: Optional Int , notifyKeyspaceEvents :: Optional KeyspaceEvn , hashMaxZiplistEntries :: Optional Int , hashMaxZiplistValue :: Optional Int , listMaxZiplistEntries :: Optional Int , listMaxZiplistValue :: Optional Int , setMaxIntsetEntries :: Optional Int , zsetMaxZiplistEntries :: Optional Int , zsetMaxZiplistValue :: Optional Int , hllSparseMaxBytes :: Optional Int , activeRehashing :: Optional Bool -- split client-output-buffer-limit into -- three differnet fields , clientOutputBufferLimitNormal :: Optional ClientOutputBufferLimitSize , clientOutputBufferLimitSlave :: Optional ClientOutputBufferLimitSize , clientOutputBufferLimitPubSub :: Optional ClientOutputBufferLimitSize , hz :: Optional Int , aofRewriteIncrementalFsync :: Optional Bool } deriving (Eq, Generic, Show) instance GMonoid RedisConfig instance Monoid RedisConfig where mempty = gmempty mappend = gmappend makeLensesWith ?? ''RedisConfig $ lensRules & lensField .~ \_ _ name -> [TopName (mkName $ nameBase name ++ "Lens")] emptyConfig = mempty data ParsingError = ParserError StringError deriving (Eq, Show) data SerializtionError = SerializtionError deriving (Eq, Show) optionBoomerang label valueBoomerang = lit label . ws . valueBoomerang (anyOptionParser, serializer) = repeatableScalar includeLens (optionBoomerang "include" string) . scalar daemonizeLens (optionBoomerang "daemonize" bool) . scalar portLens (optionBoomerang "port" int) . scalar pidFileLens (optionBoomerang "pidfile" string) . scalar tcpBacklogLens (optionBoomerang "tcp-backlog" int) . vector bindLens (optionBoomerang "bind" strings) . scalar unixSocketLens (optionBoomerang "unixsocket" string) . scalar unixSocketPermLens (optionBoomerang "unixsocketperm" string) . scalar timeoutLens (optionBoomerang "timeout" int) . scalar tcpKeepAliveLens (optionBoomerang "tcp-keepalive" int) . scalar logLevelLens (optionBoomerang "loglevel" logLevelBmg) . scalar logFileLens (optionBoomerang "logfile" string) . scalar syslogEnabledLens (optionBoomerang "syslog-enabled" bool) . scalar syslogIdentLens (optionBoomerang "syslog-ident" string) . scalar syslogFacilityLens (optionBoomerang "syslog-facility" syslogFacilityBmg) . scalar databasesLens (optionBoomerang "databases" int) . repeatableScalar saveLens (optionBoomerang "save" saveBmg) . scalar stopWritesOnBgsaveErrorLens (optionBoomerang "stop-writes-on-bg-save-error" bool) . scalar rdbCompressionLens (optionBoomerang "rdbcompression" bool) . scalar rdbChecksumLens (optionBoomerang "rdbchecksum" bool) . scalar dbFilenameLens (optionBoomerang "dbfilename" string) . scalar dirLens (optionBoomerang "dir" string) . scalar slaveOfLens (optionBoomerang "slaveof" slaveOfBmg) . scalar masterAuthLens (optionBoomerang "masterauth" string) . scalar slaveServeStaleDataLens (optionBoomerang "slave-serve-stale-data" bool) . scalar slaveReadOnlyLens (optionBoomerang "slave-read-only" bool) . scalar replDisklessSyncLens (optionBoomerang "repl-diskless-sync" bool) . scalar replDisklessSyncDelayLens (optionBoomerang "repl-diskless-sync-delay" int) . scalar replPingSlavePeriodLens (optionBoomerang "repl-ping-slave-period" int) . scalar replTimeoutLens (optionBoomerang "repl-timeout" int) . scalar replDisableTcpNoDelayLens (optionBoomerang "repl-disable-tcp-no-delay" bool) . scalar replBacklogSizeLens (optionBoomerang "repl-backlog-size" sizeBmg) . scalar replBacklogTtlLens (optionBoomerang "repl-backlog-ttl" int) . scalar slavePriorityLens (optionBoomerang "slave-priority" int) . scalar minSlavesToWriteLens (optionBoomerang "min-slaves-to-write" int) . scalar minSlavesMaxLagLens (optionBoomerang "min-slaves-max-lag" int) . scalar requirePassLens (optionBoomerang "requirepass" string) . repeatableScalar renameCommandLens (optionBoomerang "rename-command" renameCommandBmg) . scalar maxClientsLens (optionBoomerang "maxclients" int) . scalar maxMemoryLens (optionBoomerang "maxmemory" int) . scalar maxMemoryPolicyLens (optionBoomerang "maxmemory-policy" memoryPolicyBmg) . scalar maxMemorySamplesLens (optionBoomerang "maxmemory-samples" int) . scalar appendOnlyLens (optionBoomerang "appendonly" bool) . scalar appendFilenameLens (optionBoomerang "appendfilename" string) . scalar appendFsyncLens (optionBoomerang "appendfsync" appendFsyncBmg) . scalar noAppendFsyncOnRewriteLens (optionBoomerang "no-appendfsync-on-rewrite" bool) . scalar autoAofRewritePercentageLens (optionBoomerang "auto-aof-rewrite-percentage" int) . scalar autoAofRewriteMinSizeLens (optionBoomerang "auto-aof-rewrite-min-size" sizeBmg) . scalar aofLoadTruncatedLens (optionBoomerang "aof-load-truncated" bool) . scalar luaTimeLimitLens (optionBoomerang "lua-time-limit" int) . scalar slowlogLogSlowerThanLens (optionBoomerang "slowlog-log-slower-than" int) . scalar slowlogMaxLenLens (optionBoomerang "slowlog-max-len" int) . scalar latencyMonitorThresholdLens (optionBoomerang "latency-monitor-threshold" int) . scalar notifyKeyspaceEventsLens (optionBoomerang "notify-keyspace-events" keyspaceEvnBmg) . scalar hashMaxZiplistEntriesLens (optionBoomerang "hash-max-ziplist-entries" int) . scalar hashMaxZiplistValueLens (optionBoomerang "hash-max-ziplist-value" int) . scalar listMaxZiplistEntriesLens (optionBoomerang "list-max-ziplist-entries" int) . scalar listMaxZiplistValueLens (optionBoomerang "list-max-ziplist-value" int) . scalar setMaxIntsetEntriesLens (optionBoomerang "set-max-intset-entries" int) . scalar zsetMaxZiplistEntriesLens (optionBoomerang "zset-max-ziplist-entries" int) . scalar zsetMaxZiplistValueLens (optionBoomerang "zset-max-ziplist-value" int) . scalar hllSparseMaxBytesLens (optionBoomerang "hll-sparse-max-bytes" int) . scalar activeRehashingLens (optionBoomerang "activerehashing" bool) . scalar clientOutputBufferLimitNormalLens (optionBoomerang "client-output-buffer-limit" (lit "normal" . ws . clientOutputBufferLimitBmg)) . scalar clientOutputBufferLimitSlaveLens (optionBoomerang "client-output-buffer-limit" (lit "slave" . ws . clientOutputBufferLimitBmg)) . scalar clientOutputBufferLimitPubSubLens (optionBoomerang "client-output-buffer-limit" (lit "pubsub" . ws . clientOutputBufferLimitBmg)) . scalar hzLens (optionBoomerang "hz" int) . scalar aofRewriteIncrementalFsyncLens (optionBoomerang "aof-rewrite-incremental-fsync" bool) $ (mempty, id) parser = -- comment ((toPrs (lit "#" . manyr (ignoreWhen (/= '\n'))) -- only white characters line <> toPrs ws -- option <> anyOptionParser <?> (\t -> "can't parse any option from this line: " ++ takeWhile (/= '\n') t)) -- end of line and more options -- or optinal end of line . (id <> eol' <> (eol' . parser))) -- completely empty line (I don't want to handle this -- above with `manyl witeSpace` because always matches -- and causes errors information loss <> (eol' . (parser <> id)) where -- used only for parser generation eol' = toPrs eol parse :: String -> Either ParsingError RedisConfig parse conf = either (Left . ParserError) Right (parseString (parser . toPrs (push emptyConfig)) conf) serialize :: RedisConfig -> Either SerializtionError String serialize redisConfig = note SerializtionError . fmap (($ "") . fst) . s $ (redisConfig :- ()) where Ser s = serializer
paluh/et-cetera
src/System/EtCetera/Redis/V2_8.hs
Haskell
bsd-3-clause
17,130
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module DFAMin (minimizeDFA) where import AbsSyn import Data.Map (Map) import qualified Data.Map as Map import Data.IntSet (IntSet) import qualified Data.IntSet as IS import Data.IntMap (IntMap) import qualified Data.IntMap as IM import qualified Data.List as List -- % Hopcroft's Algorithm for DFA minimization (cut/pasted from Wikipedia): -- % X refines Y into Y1 and Y2 means -- % Y1 := Y ∩ X -- % Y2 := Y \ X -- % where both Y1 and Y2 are nonempty -- -- P := {{all accepting states}, {all nonaccepting states}}; -- Q := {{all accepting states}}; -- while (Q is not empty) do -- choose and remove a set A from Q -- for each c in ∑ do -- let X be the set of states for which a transition on c leads to a state in A -- for each set Y in P for which X refines Y into Y1 and Y2 do -- replace Y in P by the two sets Y1 and Y2 -- if Y is in Q -- replace Y in Q by the same two sets -- else -- add the smaller of the two sets to Q -- end; -- end; -- end; -- -- % X is a preimage of A under transition function. -- % observation : Q is always subset of P -- % let R = P \ Q. then following algorithm is the equivalent of the Hopcroft's Algorithm -- -- R := {{all nonaccepting states}}; -- Q := {{all accepting states}}; -- while (Q is not empty) do -- choose a set A from Q -- remove A from Q and add it to R -- for each c in ∑ do -- let X be the set of states for which a transition on c leads to a state in A -- for each set Y in R for which X refines Y into Y1 and Y2 do -- replace Y in R by the greater of the two sets Y1 and Y2 -- add the smaller of the two sets to Q -- end; -- for each set Y in Q for which X refines Y into Y1 and Y2 do -- replace Y in Q by the two sets Y1 and Y2 -- end; -- end; -- end; -- -- % The second for loop that iterates over R mutates Q, -- % but it does not affect the third for loop that iterates over Q. -- % Because once X refines Y into Y1 and Y2, Y1 and Y2 can't be more refined by X. minimizeDFA :: forall a. Ord a => DFA Int a -> DFA Int a minimizeDFA dfa@(DFA { dfa_start_states = starts, dfa_states = statemap }) = DFA { dfa_start_states = starts, dfa_states = Map.fromList states } where equiv_classes :: [EquivalenceClass] equiv_classes = groupEquivStates dfa numbered_states :: [(Int, EquivalenceClass)] numbered_states = number (length starts) equiv_classes -- assign each state in the minimized DFA a number, making -- sure that we assign the numbers [0..] to the start states. number :: Int -> [EquivalenceClass] -> [(Int, EquivalenceClass)] number _ [] = [] number n (ss:sss) = case filter (`IS.member` ss) starts of [] -> (n,ss) : number (n+1) sss starts' -> map (,ss) starts' ++ number n sss -- if one of the states of the minimized DFA corresponds -- to multiple starts states, we just have to duplicate -- that state. states :: [(Int, State Int a)] states = [ let old_states = map (lookup statemap) (IS.toList equiv) accs = map fix_acc (state_acc (head old_states)) -- accepts should all be the same out = IM.fromList [ (b, get_new old) | State _ out <- old_states, (b,old) <- IM.toList out ] in (n, State accs out) | (n, equiv) <- numbered_states ] fix_acc :: Accept a -> Accept a fix_acc acc = acc { accRightCtx = fix_rctxt (accRightCtx acc) } fix_rctxt :: RightContext SNum -> RightContext SNum fix_rctxt (RightContextRExp s) = RightContextRExp (get_new s) fix_rctxt other = other lookup :: Ord k => Map k v -> k -> v lookup m k = Map.findWithDefault (error "minimizeDFA") k m get_new :: Int -> Int get_new = lookup old_to_new old_to_new :: Map Int Int old_to_new = Map.fromList [ (s,n) | (n,ss) <- numbered_states, s <- IS.toList ss ] type EquivalenceClass = IntSet groupEquivStates :: forall a. Ord a => DFA Int a -> [EquivalenceClass] groupEquivStates DFA { dfa_states = statemap } = go init_r init_q where accepting, nonaccepting :: Map Int (State Int a) (accepting, nonaccepting) = Map.partition acc statemap where acc (State as _) = not (List.null as) nonaccepting_states :: EquivalenceClass nonaccepting_states = IS.fromList (Map.keys nonaccepting) -- group the accepting states into equivalence classes accept_map :: Map [Accept a] [Int] accept_map = {-# SCC "accept_map" #-} List.foldl' (\m (n,s) -> Map.insertWith (++) (state_acc s) [n] m) Map.empty (Map.toList accepting) accept_groups :: [EquivalenceClass] accept_groups = map IS.fromList (Map.elems accept_map) init_r, init_q :: [EquivalenceClass] init_r -- Issue #71: each EquivalenceClass needs to be a non-empty set | IS.null nonaccepting_states = [] | otherwise = [nonaccepting_states] init_q = accept_groups -- a map from token T to -- a map from state S to the set of states that transition to -- S on token T -- bigmap is an inversed transition function classified by each input token. -- the codomain of each inversed function is a set of states rather than single state -- since a transition function might not be an injective. -- This is a cache of the information needed to compute xs below bigmap :: IntMap (IntMap EquivalenceClass) bigmap = IM.fromListWith (IM.unionWith IS.union) [ (i, IM.singleton to (IS.singleton from)) | (from, state) <- Map.toList statemap, (i,to) <- IM.toList (state_out state) ] -- The outer loop: recurse on each set in R and Q go :: [EquivalenceClass] -> [EquivalenceClass] -> [EquivalenceClass] go r [] = r go r (a:q) = uncurry go $ List.foldl' go0 (a:r,q) xs where preimage :: IntMap EquivalenceClass -- inversed transition function -> EquivalenceClass -- subset of codomain of original transition function -> EquivalenceClass -- preimage of given subset #if MIN_VERSION_containers(0, 6, 0) preimage invMap a = IS.unions (IM.restrictKeys invMap a) #else preimage invMap a = IS.unions [IM.findWithDefault IS.empty s invMap | s <- IS.toList a] #endif xs :: [EquivalenceClass] xs = [ x | invMap <- IM.elems bigmap , let x = preimage invMap a , not (IS.null x) ] refineWith :: EquivalenceClass -- preimage set that bisects the input equivalence class -> EquivalenceClass -- input equivalence class -> Maybe (EquivalenceClass, EquivalenceClass) -- refined equivalence class refineWith x y = if IS.null y1 || IS.null y2 then Nothing else Just (y1, y2) where y1 = IS.intersection y x y2 = IS.difference y x go0 (r,q) x = go1 r [] [] where -- iterates over R go1 [] r' q' = (r', go2 q q') go1 (y:r) r' q' = case refineWith x y of Nothing -> go1 r (y:r') q' Just (y1, y2) | IS.size y1 <= IS.size y2 -> go1 r (y2:r') (y1:q') | otherwise -> go1 r (y1:r') (y2:q') -- iterates over Q go2 [] q' = q' go2 (y:q) q' = case refineWith x y of Nothing -> go2 q (y:q') Just (y1, y2) -> go2 q (y1:y2:q')
simonmar/alex
src/DFAMin.hs
Haskell
bsd-3-clause
8,226
module Main where eight = 1 + ( 2 * 2 ) + 3
YoshikuniJujo/toyhaskell_haskell
examples/eight.hs
Haskell
bsd-3-clause
45
{-# language CPP #-} -- | = Name -- -- VK_GOOGLE_surfaceless_query - instance extension -- -- == VK_GOOGLE_surfaceless_query -- -- [__Name String__] -- @VK_GOOGLE_surfaceless_query@ -- -- [__Extension Type__] -- Instance extension -- -- [__Registered Extension Number__] -- 434 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_surface@ -- -- [__Special Use__] -- -- - <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse OpenGL \/ ES support> -- -- [__Contact__] -- -- - Shahbaz Youssefi -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_GOOGLE_surfaceless_query] @syoussefi%0A<<Here describe the issue or question you have about the VK_GOOGLE_surfaceless_query extension>> > -- -- [__Extension Proposal__] -- <https://github.com/KhronosGroup/Vulkan-Docs/tree/main/proposals/VK_GOOGLE_surfaceless_query.asciidoc VK_GOOGLE_surfaceless_query> -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2021-12-14 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Ian Elliott, Google -- -- - Shahbaz Youssefi, Google -- -- - James Jones, NVIDIA -- -- == Description -- -- This extension allows the -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceFormatsKHR' -- and -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfacePresentModesKHR' -- functions to accept 'Vulkan.Core10.APIConstants.NULL_HANDLE' as their -- @surface@ parameter, allowing potential surface formats, colorspaces and -- present modes to be queried without providing a surface. Identically, -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceFormats2KHR' -- and -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.getPhysicalDeviceSurfacePresentModes2EXT' -- would accept 'Vulkan.Core10.APIConstants.NULL_HANDLE' in -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.PhysicalDeviceSurfaceInfo2KHR'::@surface@. -- __This can only be supported on platforms where the results of these -- queries are surface-agnostic and a single presentation engine is the -- implicit target of all present operations__. -- -- == New Enum Constants -- -- - 'GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME' -- -- - 'GOOGLE_SURFACELESS_QUERY_SPEC_VERSION' -- -- == Version History -- -- - Revision 1, 2021-12-14 (Shahbaz Youssefi) -- -- - Internal revisions -- -- == See Also -- -- No cross-references are available -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_GOOGLE_surfaceless_query Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_GOOGLE_surfaceless_query ( GOOGLE_SURFACELESS_QUERY_SPEC_VERSION , pattern GOOGLE_SURFACELESS_QUERY_SPEC_VERSION , GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME , pattern GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME ) where import Data.String (IsString) type GOOGLE_SURFACELESS_QUERY_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_GOOGLE_SURFACELESS_QUERY_SPEC_VERSION" pattern GOOGLE_SURFACELESS_QUERY_SPEC_VERSION :: forall a . Integral a => a pattern GOOGLE_SURFACELESS_QUERY_SPEC_VERSION = 1 type GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME = "VK_GOOGLE_surfaceless_query" -- No documentation found for TopLevel "VK_GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME" pattern GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME = "VK_GOOGLE_surfaceless_query"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_GOOGLE_surfaceless_query.hs
Haskell
bsd-3-clause
3,978
module Language.Asdf.Lexer ( symbol , parens , brackets , natural , naturalOrFloat , rational , stringLiteral , operator , identifier , reserved , reservedOp , whiteSpace , comma , lexer ) where import Control.Monad import Text.Parsec import Text.Parsec.Language import qualified Text.Parsec.Token as Token lexerStyle :: (Monad m) => GenLanguageDef String u m lexerStyle = Token.LanguageDef { Token.commentStart = "{-" , Token.commentEnd = "-}" , Token.commentLine = "//" , Token.nestedComments = True , Token.identStart = letter , Token.identLetter = alphaNum <|> oneOf "_'#" , Token.opStart = Token.opLetter lexerStyle , Token.opLetter = oneOf "~!@$%^&*-+/?|=<>" , Token.reservedOpNames= ["::"] , Token.reservedNames = [ "return", "struct", "union" , "for", "while", "if", "else" , "do", "var", "foreign", "def"] , Token.caseSensitive = True } lexer :: (Monad m) => Token.GenTokenParser String u m lexer = Token.makeTokenParser lexerStyle symbol :: (Monad m) => String -> ParsecT String u m String symbol = Token.symbol lexer parens, brackets :: (Monad m) => ParsecT String u m a -> ParsecT String u m a parens = Token.parens lexer brackets = Token.brackets lexer natural :: (Monad m) => ParsecT String u m Integer natural = Token.natural lexer naturalOrFloat :: (Monad m) => ParsecT String u m (Either Integer Double) naturalOrFloat = Token.naturalOrFloat lexer rational :: (Monad m) => ParsecT String u m Rational rational = liftM (either toRational toRational) naturalOrFloat stringLiteral, identifier, operator, comma :: (Monad m) => ParsecT String u m String stringLiteral = Token.stringLiteral lexer operator = Token.operator lexer identifier = Token.identifier lexer comma = Token.comma lexer reservedOp :: (Monad m) => String -> ParsecT String u m () reservedOp = Token.reservedOp lexer reserved :: (Monad m) => String -> ParsecT String u m () reserved = Token.reserved lexer whiteSpace :: (Monad m) => ParsecT String u m () whiteSpace = Token.whiteSpace lexer
sw17ch/Asdf
src/Language/Asdf/Lexer.hs
Haskell
bsd-3-clause
2,688
module Main where fibs = 0 : 1 : zipWith (+) fibs (tail fibs) fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) f :: Int -> Int f x = if fib 100 > 10 then f (x + 1) else 0 main :: IO () main = if fib 10 == fibs !! 10 then putStrLn "Yay!" else putStrLn "Boo!"
yav/sequent-core
examples/Example.hs
Haskell
bsd-3-clause
264
module NestedIO where import Data.Time.Calendar import Data.Time.Clock import System.Random huehue :: IO (Either (IO Int) (IO ())) huehue = do t <- getCurrentTime let (_, _, dayOfMonth) = toGregorian (utctDay t) case even dayOfMonth of True -> return $ Left randomIO False -> return $ Right (putStrLn "no soup for you") {- blah <- huehue either (>>= print) id blah -}
chengzh2008/hpffp
src/ch29-IO/nestedIO.hs
Haskell
bsd-3-clause
385
{-| Module : $Header$ Description : Adapter for communicating with Slack via its real time messaging API Copyright : (c) Justus Adam, 2016 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : POSIX See http://marvin.readthedocs.io/en/latest/adapters.html#real-time-messaging-api for documentation of this adapter. -} module Marvin.Adapter.Slack.RTM ( SlackAdapter, RTM , SlackUserId(..), SlackChannelId(..) , MkSlack , SlackRemoteFile(..), SlackLocalFile(..) , HasTitle(..), HasPublicPermalink(..), HasEditable(..), HasPublic(..), HasUser(..), HasPrivateUrl(..), HasComment(..) ) where import Control.Concurrent.Async.Lifted (async, link) import Control.Concurrent.Chan.Lifted import Control.Concurrent.MVar.Lifted import Control.Exception.Lifted import Control.Monad import Control.Monad.Except import Control.Monad.Logger import Data.Aeson hiding (Error) import Data.Aeson.Types hiding (Error) import qualified Data.ByteString.Lazy.Char8 as BS import Data.IORef.Lifted import Data.Maybe (fromMaybe) import qualified Data.Text as T import Lens.Micro.Platform hiding ((.=)) import Marvin.Adapter import Marvin.Adapter.Slack.Internal.Common import Marvin.Adapter.Slack.Internal.Types import Marvin.Interpolate.Text import Network.URI import Network.WebSockets import Network.Wreq import Text.Read (readMaybe) import Wuss runConnectionLoop :: Chan (InternalType RTM) -> MVar Connection -> AdapterM (SlackAdapter RTM) () runConnectionLoop eventChan connectionTracker = do messageChan <- newChan a <- async $ forever $ do msg <- readChan messageChan case eitherDecode msg >>= parseEither eventParser of -- changed it do logDebug for now as we still have events that we do not handle -- all those will show up as errors and I want to avoid polluting the log -- once we are sure that all events are handled in some way we can make this as error again -- (which it should be) Left e -> logDebugN $(isT "Error parsing json: #{e} original data: #{rawBS msg}") Right v -> writeChan eventChan v link a forever $ do token <- requireFromAdapterConfig "token" logDebugN "initializing socket" r <- liftIO $ post "https://slack.com/api/rtm.start" [ "token" := (token :: T.Text) ] case eitherDecode (r^.responseBody) of Left err -> do logErrorN $(isT "Error decoding rtm json #{err}") logDebugN $(isT "#{r^.responseBody}") Right js -> do port <- case uriPort authority_ of v@(':':rest_) -> maybe (portOnErr v) return $ readMaybe rest_ v -> portOnErr v logDebugN $(isT "connecting to socket '#{uri}'") logFn <- askLoggerIO liftIO $ runSecureClient host port path_ $ \conn -> flip runLoggingT logFn $ do logInfoN "Connection established" d <- liftIO $ receiveData conn case eitherDecode d >>= parseEither helloParser of Right True -> logDebugN "Recieved hello packet" Left _ -> error $ "Hello packet not readable: " ++ BS.unpack d _ -> error $ "First packet was not hello packet: " ++ BS.unpack d putMVar connectionTracker conn forever $ do data_ <- liftIO $ receiveData conn writeChan messageChan data_ `catch` \e -> do void $ takeMVar connectionTracker logErrorN $(isT "#{e :: ConnectionException}") where uri = url js authority_ = fromMaybe (error "URI lacks authority") (uriAuthority uri) host = uriUserInfo authority_ ++ uriRegName authority_ path_ = uriPath uri portOnErr v = do logWarnN $(isT "Port unreadable \"#{v}\", trying standard port 443") return 443 senderLoop :: MVar Connection -> AdapterM (SlackAdapter a) () senderLoop connectionTracker = do outChan <- view (adapter.outChannel) midTracker <- newIORef (0 :: Int) forever $ do (SlackChannelId sid, msg) <- readChan outChan mid <- atomicModifyIORef' midTracker (\i -> (i+1, i)) let encoded = encode $ object [ "id" .= mid , "type" .= ("message" :: T.Text) , "channel" .= sid , "text" .= msg ] tryConn = withMVar connectionTracker (liftIO . flip sendTextData encoded) `catch` \e -> do logErrorN $(isT "#{e :: ConnectionException}") throwError () either (const $ logErrorN "Connection error, quitting retry.") return =<< runExceptT (msum (replicate 3 tryConn)) -- | Recieve events by opening a websocket to the Real Time Messaging API data RTM instance MkSlack RTM where mkAdapterId = "slack-rtm" initIOConnections inChan = do connTracker <- newEmptyMVar a <- async $ runConnectionLoop inChan connTracker link a senderLoop connTracker
JustusAdam/marvin
src/Marvin/Adapter/Slack/RTM.hs
Haskell
bsd-3-clause
5,717
{-#LANGUAGE ScopedTypeVariables, NoImplicitPrelude#-} module Base ( -- Classes Eq (..), Ord (..), Bounded (..), Num (..), Real (..), Integral (..), Fractional (..), Floating (..), RealFrac (..), RealFloat (..), Enum (..), Functor (..), Monad (..), Show (..), Read (..), -- Types Bool (..), Maybe (..), Either (..), Ordering (..), Ratio (..), (%), Char, Int, String, Integer, Float, Double, IO, ShowS, ReadS, Rational, IO , -- dangerous functions asTypeOf, error, undefined, seq, ($!), -- functions on specific types -- Bool (&&), (||), not, otherwise, -- Char isSpace, isUpper, isLower, isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum, showLitChar, readLitChar, lexLitChar, -- Ratio numerator, denominator, -- Maybe maybe, -- Either either, -- overloaded functions mapM, mapM_, sequence, sequence_, (=<<), subtract, even, odd, gcd, lcm, (^), (^^), absReal, signumReal, fromIntegral, realToFrac, boundedSucc, boundedPred, boundedEnumFrom, boundedEnumFromTo, boundedEnumFromThen, boundedEnumFromThenTo, shows, showChar, showString, showParen, reads, read, lex, readParen, readSigned, readInt, readDec, readOct, readHex, readFloat, lexDigits, fromRat, -- standard functions fst, snd, curry, uncurry, id, const, (.), flip, ($), until, map, (++), concat, filter, head, last, tail, init, null, length, (!!), foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1, iterate, repeat, replicate, cycle, take, drop, splitAt, takeWhile, dropWhile, span, break, lines, words, unlines, unwords, reverse, and, or, any, all, elem, notElem, lookup, sum, product, maximum, minimum, concatMap, zip, zip3, zipWith, zipWith3, unzip, unzip3, -- standard functions for Char ord, chr, ) where import BuiltIn -------------------------------------------------------------- -- Operator precedences -------------------------------------------------------------- infixr 9 . infixl 9 !! infixr 8 ^, ^^, ** infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, % infixl 6 +, - infixr 5 ++ infix 4 ==, /=, <, <=, >=, >, `elem`, `notElem` infixr 3 && infixr 2 || infixl 1 >>, >>= infixr 1 =<< infixr 0 $, $!, `seq` -------------------------------------------------------------- -- Dangerous functions -------------------------------------------------------------- asTypeOf :: a -> a -> a asTypeOf = const seq :: a -> b -> b seq = primSeq f $! x = x `seq` f x error :: String -> a error = primError undefined :: a undefined = error "Prelude.undefined" -------------------------------------------------------------- -- class Eq, Ord, Bounded -------------------------------------------------------------- class Eq a where (==), (/=) :: a -> a -> Bool -- Minimal complete definition: (==) or (/=) x == y = not (x/=y) x /= y = not (x==y) class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a -- Minimal complete definition: (<=) or compare -- using compare can be more efficient for complex types compare x y | x==y = EQ | x<=y = LT | otherwise = GT x <= y = compare x y /= GT x < y = compare x y == LT x >= y = compare x y /= LT x > y = compare x y == GT max x y | x <= y = y | otherwise = x min x y | x <= y = x | otherwise = y class Bounded a where minBound, maxBound :: a -- Minimal complete definition: All boundedSucc, boundedPred :: (Num a, Bounded a, Enum a) => a -> a boundedSucc x | x == maxBound = error "succ: applied to maxBound" | otherwise = x+1 boundedPred x | x == minBound = error "pred: applied to minBound" | otherwise = x-1 boundedEnumFrom :: (Ord a, Bounded a, Enum a) => a -> [a] boundedEnumFromTo :: (Ord a, Bounded a, Enum a) => a -> a -> [a] boundedEnumFromThenTo :: (Ord a, Num a, Bounded a, Enum a) => a -> a -> a -> [a] boundedEnumFromThen :: (Ord a, Bounded a, Enum a) => a -> a -> [a] boundedEnumFrom n = takeWhile1 (/= maxBound) (iterate succ n) boundedEnumFromTo n m = takeWhile (<= m) (boundedEnumFrom n) boundedEnumFromThen n m = enumFromThenTo n m (if n <= m then maxBound else minBound) boundedEnumFromThenTo n n' m | n' >= n = if n <= m then takeWhile1 (<= m - delta) ns else [] | otherwise = if n >= m then takeWhile1 (>= m - delta) ns else [] where delta = n'-n ns = iterate (+delta) n -- takeWhile and one more takeWhile1 :: (a -> Bool) -> [a] -> [a] takeWhile1 p (x:xs) = x : if p x then takeWhile1 p xs else [] numericEnumFrom :: Num a => a -> [a] numericEnumFromThen :: Num a => a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFrom n = iterate (+1) n numericEnumFromThen n m = iterate (+(m-n)) n numericEnumFromTo n m = takeWhile (<= m+1/2) (numericEnumFrom n) numericEnumFromThenTo n n' m = takeWhile p (numericEnumFromThen n n') where p | n' >= n = (<= m + (n'-n)/2) | otherwise = (>= m + (n'-n)/2) -------------------------------------------------------------- -- Numeric classes: Num, Real, Integral, -- Fractional, Floating, -- RealFrac, RealFloat -------------------------------------------------------------- -- class (Eq a, Show a) => Num a where class (Eq a) => Num a where (+), (-), (*) :: a -> a -> a negate :: a -> a abs, signum :: a -> a fromInteger :: Integer -> a fromInt :: Int -> a -- Minimal complete definition: All, except negate or (-) x - y = x + negate y fromInt = fromIntegral negate x = 0 - x class (Num a, Ord a) => Real a where toRational :: a -> Rational class (Real a, Enum a) => Integral a where quot, rem, div, mod :: a -> a -> a quotRem, divMod :: a -> a -> (a,a) toInteger :: a -> Integer toInt :: a -> Int -- Minimal complete definition: quotRem and toInteger n `quot` d = q where (q,r) = quotRem n d n `rem` d = r where (q,r) = quotRem n d n `div` d = q where (q,r) = divMod n d n `mod` d = r where (q,r) = divMod n d divMod n d = if signum r == - signum d then (q-1, r+d) else qr where qr@(q,r) = quotRem n d toInt = toInt . toInteger class (Num a) => Fractional a where (/) :: a -> a -> a recip :: a -> a fromRational :: Rational -> a fromDouble :: Double -> a -- Minimal complete definition: fromRational and ((/) or recip) recip x = 1 / x fromDouble x = fromRational (fromDouble x) x / y = x * recip y class (Fractional a) => Floating a where pi :: a exp, log, sqrt :: a -> a (**), logBase :: a -> a -> a sin, cos, tan :: a -> a asin, acos, atan :: a -> a sinh, cosh, tanh :: a -> a asinh, acosh, atanh :: a -> a -- Minimal complete definition: pi, exp, log, sin, cos, sinh, cosh, -- asinh, acosh, atanh pi = 4 * atan 1 x ** y = exp (log x * y) logBase x y = log y / log x sqrt x = x ** 0.5 tan x = sin x / cos x sinh x = (exp x - exp (-x)) / 2 cosh x = (exp x + exp (-x)) / 2 tanh x = sinh x / cosh x asinh x = log (x + sqrt (x*x + 1)) acosh x = log (x + sqrt (x*x - 1)) atanh x = (log (1 + x) - log (1 - x)) / 2 class (Real a, Fractional a) => RealFrac a where properFraction :: (Integral b) => a -> (b,a) truncate, round :: (Integral b) => a -> b ceiling, floor :: (Integral b) => a -> b -- Minimal complete definition: properFraction truncate x = m where (m,_) = properFraction x round x = let (n,r) = properFraction x m = if r < 0 then n - 1 else n + 1 in case signum (abs r - 0.5) of -1 -> n 0 -> if even n then n else m 1 -> m ceiling x = if r > 0 then n + 1 else n where (n,r) = properFraction x floor x = if r < 0 then n - 1 else n where (n,r) = properFraction x {----------------------------- -- Minimal complete definition: properFraction truncate x :: xt = m where (m::xt,_) = properFraction x round x :: xt = let (n::xt,r) = properFraction x m = if r < 0 then n - 1 else n + 1 in case signum (abs r - 0.5) of -1 -> n 0 -> if even n then n else m 1 -> m ceiling x :: xt = if r > 0 then n + 1 else n where (n::xt,r) = properFraction x floor x :: xt = if r < 0 then n - 1 else n where (n::xt,r) = properFraction x -----------------------------} class (RealFrac a, Floating a) => RealFloat a where floatRadix :: a -> Integer floatDigits :: a -> Int floatRange :: a -> (Int,Int) decodeFloat :: a -> (Integer,Int) encodeFloat :: Integer -> Int -> a exponent :: a -> Int significand :: a -> a scaleFloat :: Int -> a -> a isNaN, isInfinite, isDenormalized, isNegativeZero, isIEEE :: a -> Bool atan2 :: a -> a -> a -- Minimal complete definition: All, except exponent, signficand, -- scaleFloat, atan2 exponent x = if m==0 then 0 else n + floatDigits x where (m,n) = decodeFloat x significand x = encodeFloat m (negate (floatDigits x)) where (m,_) = decodeFloat x scaleFloat k x = encodeFloat m (n+k) where (m,n) = decodeFloat x atan2 y x | x>0 = atan (y/x) | x==0 && y>0 = pi/2 | x<0 && y>0 = pi + atan (y/x) | (x<=0 && y<0) || (x<0 && isNegativeZero y) || (isNegativeZero x && isNegativeZero y) = - atan2 (-y) x | y==0 && (x<0 || isNegativeZero x) = pi -- must be after the previous test on zero y | x==0 && y==0 = y -- must be after the other double zero tests | otherwise = x + y -- x or y is a NaN, return a NaN (via +) -------------------------------------------------------------- -- Overloaded numeric functions -------------------------------------------------------------- subtract :: Num a => a -> a -> a subtract = flip (-) even, odd :: (Integral a) => a -> Bool even n = n `rem` 2 == 0 odd = not . even gcd :: Integral a => a -> a -> a gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined" gcd x y = gcd' (abs x) (abs y) where gcd' x 0 = x gcd' x y = gcd' y (x `rem` y) lcm :: (Integral a) => a -> a -> a lcm _ 0 = 0 lcm 0 _ = 0 lcm x y = abs ((x `quot` gcd x y) * y) (^) :: (Num a, Integral b) => a -> b -> a x ^ 0 = 1 x ^ n | n > 0 = f x (n-1) x where f _ 0 y = y f x n y = g x n where g x n | even n = g (x*x) (n`quot`2) | otherwise = f x (n-1) (x*y) _ ^ _ = error "Prelude.^: negative exponent" (^^) :: (Fractional a, Integral b) => a -> b -> a x ^^ n = if n >= 0 then x ^ n else recip (x^(-n)) fromIntegral :: (Integral a, Num b) => a -> b fromIntegral = fromInteger . toInteger realToFrac :: (Real a, Fractional b) => a -> b realToFrac = fromRational . toRational absReal :: (Ord a,Num a) => a -> a absReal x | x >= 0 = x | otherwise = -x signumReal :: (Ord a,Num a) => a -> a signumReal x | x == 0 = 0 | x > 0 = 1 | otherwise = -1 -------------------------------------------------------------- -- class Enum -------------------------------------------------------------- class Enum a where succ, pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] -- [n..] enumFromThen :: a -> a -> [a] -- [n,m..] enumFromTo :: a -> a -> [a] -- [n..m] enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m] -- Minimal complete definition: toEnum, fromEnum succ = toEnum . (1+) . fromEnum pred = toEnum . subtract 1 . fromEnum enumFrom x = map toEnum [ fromEnum x ..] enumFromTo x y = map toEnum [ fromEnum x .. fromEnum y ] enumFromThen x y = map toEnum [ fromEnum x, fromEnum y ..] enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y .. fromEnum z ] -------------------------------------------------------------- -- class Read, Show -------------------------------------------------------------- type ReadS a = String -> [(a,String)] type ShowS = String -> String class Read a where readsPrec :: Int -> ReadS a readList :: ReadS [a] -- Minimal complete definition: readsPrec readList :: ReadS [a] = readParen False (\r -> [pr | ("[",s) <- lex r, pr <- readl s ]) readl :: ReadS [a] readl s = [([],t) | ("]",t) <- lex s] ++ [(x:xs,u) | (x,t) <- reads s, (xs,u) <- readl' t] readl' :: ReadS [a] readl' s = [([],t) | ("]",t) <- lex s] ++ [(x:xs,v) | (",",t) <- lex s, (x,u) <- reads t, (xs,v) <- readl' u] class Show a where show :: a -> String showsPrec :: Int -> a -> ShowS showList :: [a] -> ShowS -- Minimal complete definition: show or showsPrec show x = showsPrec 0 x "" showsPrec _ x s = show x ++ s showList [] = showString "[]" showList (x:xs) = showChar '[' . shows x . showl xs where showl [] = showChar ']' showl (x:xs) = showChar ',' . shows x . showl xs -------------------------------------------------------------- -- class Functor, Monad -------------------------------------------------------------- class Functor f where fmap :: (a -> b) -> (f a -> f b) class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b fail :: String -> m a -- Minimal complete definition: (>>=), return p >> q = p >>= \ _ -> q fail s = error s sequence :: Monad m => [m a] -> m [a] sequence [] = return [] sequence (c:cs) = do x <- c xs <- sequence cs return (x:xs) -- overloaded Functor and Monad function -- sequence_ :: forall a . Monad m => [m a] -> m () sequence_ :: Monad m => [m a] -> m () sequence_ = foldr (>>) (return ()) --mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM f = sequence . map f --mapM_ :: Monad m => (a -> m b) -> [a] -> m () mapM_ :: Monad m => (a -> m b) -> [a] -> m () mapM_ f = sequence_ . map f (=<<) :: Monad m => (a -> m b) -> m a -> m b f =<< x = x >>= f -------------------------------------------------------------- -- Boolean type -------------------------------------------------------------- data Bool = False | True deriving (Eq, Ord, Enum, Show, Read) (&&), (||) :: Bool -> Bool -> Bool False && x = False True && x = x False || x = x True || x = True not :: Bool -> Bool not True = False not False = True otherwise :: Bool otherwise = True instance Bounded Bool where minBound = False maxBound = True -------------------------------------------------------------- -- Char type -------------------------------------------------------------- isUpper :: Char -> Bool isUpper = primCharIsUpper isLower :: Char -> Bool isLower = primCharIsLower instance Eq Char where (==) = primEqChar instance Ord Char where compare = primCmpChar instance Enum Char where toEnum = primIntToChar fromEnum = primCharToInt --enumFrom c = map toEnum [fromEnum c .. fromEnum (maxBound::Char)] --enumFromThen = boundedEnumFromThen instance Read Char where readsPrec p = readParen False (\r -> [(c,t) | ('\'':s,t) <- lex r, (c,"\'") <- readLitChar s ]) readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r, (l,_) <- readl s ]) where readl ('"':s) = [("",s)] readl ('\\':'&':s) = readl s readl s = [(c:cs,u) | (c ,t) <- readLitChar s, (cs,u) <- readl t ] instance Show Char where showsPrec p '\'' = showString "'\\''" showsPrec p c = showChar '\'' . showLitChar c . showChar '\'' showList cs = showChar '"' . showl cs where showl "" = showChar '"' showl ('"':cs) = showString "\\\"" . showl cs showl (c:cs) = showLitChar c . showl cs instance Bounded Char where minBound = '\0' maxBound = '\xff' -- primMaxChar isSpace :: Char -> Bool isSpace c = c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' || c == '\xa0' isDigit :: Char -> Bool isDigit c = c >= '0' && c <= '9' isAlpha :: Char -> Bool isAlpha c = isUpper c || isLower c isAlphaNum :: Char -> Bool isAlphaNum c = isAlpha c || isDigit c ord :: Char -> Int ord = fromEnum chr :: Int -> Char chr = toEnum -------------------------------------------------------------- -- Maybe type -------------------------------------------------------------- data Maybe a = Nothing | Just a deriving (Eq, Ord, Show, Read) -- TODO: Read instance Functor Maybe where fmap f Nothing = Nothing fmap f (Just x) = Just (f x) instance Monad Maybe where Just x >>= k = k x Nothing >>= k = Nothing return = Just fail s = Nothing maybe :: b -> (a -> b) -> Maybe a -> b maybe n f Nothing = n maybe n f (Just x) = f x -------------------------------------------------------------- -- Either type -------------------------------------------------------------- data Either a b = Left a | Right b deriving (Eq, Ord, Show) -- TODO: Read either :: (a -> c) -> (b -> c) -> Either a b -> c either l r (Left x) = l x either l r (Right y) = r y -------------------------------------------------------------- -- Ordering type -------------------------------------------------------------- data Ordering = LT | EQ | GT deriving (Eq, Ord, Enum, Show) -- TODO: Ix, Read, Bounded -------------------------------------------------------------- -- Lists -------------------------------------------------------------- instance Eq a => Eq [a] where [] == [] = True (x:xs) == (y:ys) = x==y && xs==ys _ == _ = False [] /= [] = False (x:xs) /= (y:ys) = x/=y || xs/=ys _ /= _ = True instance Ord a => Ord [a] where compare [] (_:_) = LT compare [] [] = EQ compare (_:_) [] = GT compare (x:xs) (y:ys) = primCompAux x y (compare xs ys) instance Functor [] where fmap = map instance Monad [] where (x:xs) >>= f = f x ++ (xs >>= f) [] >>= f = [] return x = [x] fail s = [] instance Read a => Read [a] where readsPrec p = readList instance Show a => Show [a] where showsPrec p = showList -------------------------------------------------------------- -- Int type -------------------------------------------------------------- instance Bounded Int where minBound = primMinInt maxBound = primMaxInt instance Eq Int where (==) = primEqInt instance Ord Int where (<=) = primLeInt (>=) = primGeInt instance Num Int where (+) = primPlusInt (-) = primMinusInt (*) = primMultInt negate = primNegateInt fromInteger = primIntegerToInt instance Integral Int where divMod x y = (primDivInt x y, primModInt x y) quotRem x y = (primQuotInt x y, primRemInt x y) div = primDivInt quot = primQuotInt rem = primRemInt mod = primModInt toInteger = primIntToInteger toInt x = x instance Enum Int where succ = boundedSucc pred = boundedPred toEnum = id fromEnum = id enumFrom = boundedEnumFrom enumFromTo = boundedEnumFromTo enumFromThen = boundedEnumFromThen enumFromThenTo = boundedEnumFromThenTo instance Read Int where readsPrec p = readSigned readDec instance Real Int where toRational x = x % 1 showInt :: Int -> String showInt x | x<0 = '-' : showInt(-x) | x==0 = "0" | otherwise = (map primIntToChar . map (+48) . reverse . map (`rem`10) . takeWhile (/=0) . iterate (`div`10)) x instance Show Int where show = showInt -------------------------------------------------------------- -- Integer type -------------------------------------------------------------- instance Eq Integer where (==) = primEqInteger instance Ord Integer where compare = primCmpInteger instance Num Integer where (+) = primAddInteger (-) = primSubInteger negate = primNegInteger (*) = primMulInteger abs = absReal signum = signumReal fromInteger x = x fromInt = primIntToInteger instance Real Integer where toRational x = x % 1 instance Integral Integer where divMod = primDivModInteger quotRem = primQuotRemInteger div = primDivInteger quot = primQuotInteger rem = primRemInteger mod = primModInteger toInteger x = x toInt = primIntegerToInt instance Enum Integer where succ x = x + 1 pred x = x - 1 toEnum = primIntToInteger fromEnum = primIntegerToInt enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo n m = takeWhile (<= m) (numericEnumFrom n) enumFromThenTo n n2 m = takeWhile p (numericEnumFromThen n n2) where p | n2 >= n = (<= m) | otherwise = (>= m) showInteger :: Integer -> String showInteger x | x<0 = '-' : showInteger(-x) | x==0 = "0" | otherwise = (map primIntToChar . map (+48) . reverse . map primIntegerToInt . map (`rem`10) . takeWhile (/=0) . iterate (`div`10)) x instance Show Integer where show = showInteger instance Read Integer where readsPrec p = readSigned readDec -------------------------------------------------------------- -- Float and Double type -------------------------------------------------------------- instance Eq Float where (==) = primEqFloat instance Eq Double where (==) = primEqDouble instance Ord Float where compare = primCmpFloat instance Ord Double where compare = primCmpDouble instance Num Float where (+) = primAddFloat (-) = primSubFloat negate = primNegFloat (*) = primMulFloat abs = absReal signum = signumReal fromInteger = primIntegerToFloat fromInt = primIntToFloat instance Num Double where (+) = primAddDouble (-) = primSubDouble negate = primNegDouble (*) = primMulDouble abs = absReal signum = signumReal fromInteger = primIntegerToDouble fromInt = primIntToDouble instance Real Float where toRational = floatToRational instance Real Double where toRational = doubleToRational -- TODO: Calls to these functions should be optimised when passed as arguments to fromRational floatToRational :: Float -> Rational floatToRational x = fromRat x doubleToRational :: Double -> Rational doubleToRational x = fromRat x fromRat :: RealFloat a => a -> Rational fromRat x = (m%1)*(b%1)^^n where (m,n) = decodeFloat x b = floatRadix x instance Fractional Float where (/) = primDivideFloat recip = primRecipFloat fromRational = primRationalToFloat fromDouble = primDoubleToFloat instance Fractional Double where (/) = primDivideDouble recip = primRecipDouble fromRational = primRationalToDouble fromDouble x = x instance Floating Float where exp = primExpFloat log = primLogFloat sqrt = primSqrtFloat sin = primSinFloat cos = primCosFloat tan = primTanFloat asin = primAsinFloat acos = primAcosFloat atan = primAtanFloat sinh = primSinhFloat instance Floating Double where exp = primExpDouble log = primLogDouble sqrt = primSqrtDouble sin = primSinDouble cos = primCosDouble tan = primTanDouble asin = primAsinDouble acos = primAcosDouble atan = primAtanDouble sinh = primSinhDouble cosh = primCoshDouble tanh = primTanhDouble instance RealFrac Float where properFraction = floatProperFraction instance RealFrac Double where properFraction = floatProperFraction floatProperFraction x | n >= 0 = (fromInteger m * fromInteger b ^ n, 0) | otherwise = (fromInteger w, encodeFloat r n) where (m,n) = decodeFloat x b = floatRadix x (w,r) = quotRem m (b^(-n)) instance RealFloat Float where floatRadix _ = toInteger primRadixDoubleFloat floatDigits _ = primDigitsFloat floatRange _ = (primMinExpFloat, primMaxExpFloat) encodeFloat = primEncodeFloat decodeFloat = primDecodeFloat isNaN = primIsNaNFloat isInfinite = primIsInfiniteFloat isDenormalized= primIsDenormalizedFloat isNegativeZero= primIsNegativeZeroFloat isIEEE _ = primIsIEEE atan2 = primAtan2Float instance RealFloat Double where floatRadix _ = toInteger primRadixDoubleFloat floatDigits _ = primDigitsDouble floatRange _ = (primMinExpDouble, primMaxExpDouble) encodeFloat = primEncodeDouble decodeFloat = primDecodeDouble isNaN = primIsNaNDouble isInfinite = primIsInfiniteDouble isDenormalized= primIsDenormalizedDouble isNegativeZero= primIsNegativeZeroDouble isIEEE _ = primIsIEEE atan2 = primAtan2Double instance Enum Float where succ x = x+1 pred x = x-1 toEnum = primIntToFloat fromEnum = fromInteger . truncate -- may overflow enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo instance Enum Double where succ x = x+1 pred x = x-1 toEnum = primIntToDouble fromEnum = fromInteger . truncate -- may overflow enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo instance Read Float where readsPrec p = readSigned readFloat instance Show Float where show = primShowFloat instance Read Double where readsPrec p = readSigned readFloat instance Show Double where show = primShowsDouble -------------------------------------------------------------- -- Ratio and Rational type -------------------------------------------------------------- data (Integral a) => Ratio a = !a :% !a deriving (Eq) type Rational = Ratio Integer (%) :: Integral a => a -> a -> Ratio a x % y = reduce (x * signum y) (abs y) reduce :: Integral a => a -> a -> Ratio a reduce x y | y == 0 = error "Ratio.%: zero denominator" | otherwise = (x `quot` d) :% (y `quot` d) where d = gcd x y numerator :: Integral a => Ratio a -> a numerator (x :% y) = x denominator :: Integral a => Ratio a -> a denominator (x :% y) = y instance Integral a => Ord (Ratio a) where compare (x:%y) (x':%y') = compare (x*y') (x'*y) instance Integral a => Num (Ratio a) where (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y') (x:%y) * (x':%y') = reduce (x*x') (y*y') negate (x :% y) = negate x :% y abs (x :% y) = abs x :% y signum (x :% y) = signum x :% 1 fromInteger x = fromInteger x :% 1 -- fromInt = intToRatio fromInt x = fromInt x :% 1 intToRatio :: Integral a => Int -> Ratio a -- TODO: optimise fromRational (intToRatio x) intToRatio x = fromInt x :% 1 instance Integral a => Real (Ratio a) where toRational (x:%y) = toInteger x :% toInteger y instance Integral a => Fractional (Ratio a) where (x:%y) / (x':%y') = (x*y') % (y*x') recip (x:%y) = y % x fromRational (x:%y) = fromInteger x :% fromInteger y fromDouble = doubleToRatio doubleToRatio :: Integral a => Double -> Ratio a -- TODO: optimies fromRational (doubleToRatio x) doubleToRatio x | n>=0 = (round (x / fromInteger pow) * fromInteger pow) % 1 | otherwise = fromRational (round (x * fromInteger denom) % denom) where (m,n) = decodeFloat x n_dec :: Integer n_dec = ceiling (logBase 10 (encodeFloat 1 n :: Double)) denom = 10 ^ (-n_dec) pow = 10 ^ n_dec instance Integral a => RealFrac (Ratio a) where properFraction (x:%y) = (fromIntegral q, r:%y) where (q,r) = quotRem x y instance Integral a => Enum (Ratio a) where succ x = x+1 pred x = x-1 toEnum = fromInt fromEnum = fromInteger . truncate -- may overflow enumFrom = numericEnumFrom enumFromTo = numericEnumFromTo enumFromThen = numericEnumFromThen enumFromThenTo = numericEnumFromThenTo instance (Read a, Integral a) => Read (Ratio a) where readsPrec p = readParen (p > 7) (\r -> [(x%y,u) | (x,s) <- readsPrec 8 r, ("%",t) <- lex s, (y,u) <- readsPrec 8 t ]) instance (Show a,Integral a) => Show (Ratio a) where showsPrec p (x:%y) = showParen (p > 7) (showsPrec 8 x . showString " % " . showsPrec 8 y) -------------------------------------------------------------- -- Some standard functions ------------------------------------------------------------- fst :: (a,b) -> a fst (x,_) = x snd :: (a,b) -> b snd (_,y) = y curry :: ((a,b) -> c) -> a -> b -> c curry f x y = f (x,y) uncurry :: (a -> b -> c) -> (a,b) -> c uncurry f p = f (fst p) (snd p) id :: a -> a id x = x const :: a -> b -> a const k _ = k (.) :: (b -> c) -> (a -> b) -> a -> c (f . g) x = f (g x) flip :: (a -> b -> c) -> b -> a -> c flip f x y = f y x ($) :: (a -> b) -> a -> b f $ x = f x until :: (a -> Bool) -> (a -> a) -> a -> a until p f x = if p x then x else until p f (f x) -------------------------------------------------------------- -- Standard list functions -------------------------------------------------------------- head :: [a] -> a head (x:_) = x last :: [a] -> a last [x] = x last (_:xs) = last xs tail :: [a] -> [a] tail (_:xs) = xs init :: [a] -> [a] init [x] = [] init (x:xs) = x : init xs null :: [a] -> Bool null [] = True null (_:_) = False (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) map :: (a -> b) -> [a] -> [b] map f xs = [ f x | x <- xs ] filter :: (a -> Bool) -> [a] -> [a] filter p xs = [ x | x <- xs, p x ] concat :: [[a]] -> [a] concat = foldr (++) [] length :: [a] -> Int length = foldl' (\n _ -> n + (1::Int)) (0::Int) (!!) :: [a] -> Int -> a xs !! n | n<0 = error "Prelude.!!: negative index" [] !! _ = error "Prelude.!!: index too large" (x:_) !! 0 = x (_:xs) !! n = xs !! (n-1) foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' f a [] = a foldl1 :: (a -> a -> a) -> [a] -> a foldl1 f (x:xs) = foldl f x xs scanl :: (a -> b -> a) -> a -> [b] -> [a] scanl f q xs = q : (case xs of [] -> [] x:xs -> scanl f (f q x) xs) scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 _ [] = [] scanl1 f (x:xs) = scanl f x xs foldr :: (a -> b -> b) -> b -> [a] -> b foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) foldr1 :: (a -> a -> a) -> [a] -> a foldr1 f [x] = x foldr1 f (x:xs) = f x (foldr1 f xs) scanr :: (a -> b -> b) -> b -> [a] -> [b] scanr f q0 [] = [q0] scanr f q0 (x:xs) = f x q : qs where qs@(q:_) = scanr f q0 xs scanr1 :: (a -> a -> a) -> [a] -> [a] scanr1 f [] = [] scanr1 f [x] = [x] scanr1 f (x:xs) = f x q : qs where qs@(q:_) = scanr1 f xs iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) repeat :: a -> [a] repeat x = xs where xs = x:xs replicate :: Int -> a -> [a] replicate n x = take n (repeat x) cycle :: [a] -> [a] cycle [] = error "Prelude.cycle: empty list" cycle xs = xs' where xs'=xs++xs' take :: Int -> [a] -> [a] take n _ | n <= 0 = [] take _ [] = [] take n (x:xs) = x : take (n-1) xs drop :: Int -> [a] -> [a] drop n xs | n <= 0 = xs drop _ [] = [] drop n (_:xs) = drop (n-1) xs splitAt :: Int -> [a] -> ([a], [a]) splitAt n xs | n <= 0 = ([],xs) splitAt _ [] = ([],[]) splitAt n (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile p [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile p [] = [] dropWhile p xs@(x:xs') | p x = dropWhile p xs' | otherwise = xs span, break :: (a -> Bool) -> [a] -> ([a],[a]) span p [] = ([],[]) span p xs@(x:xs') | p x = (x:ys, zs) | otherwise = ([],xs) where (ys,zs) = span p xs' break p = span (not . p) lines :: String -> [String] lines "" = [] lines s = let (l,s') = break ('\n'==) s in l : case s' of [] -> [] (_:s'') -> lines s'' words :: String -> [String] words s = case dropWhile isSpace s of "" -> [] s' -> w : words s'' where (w,s'') = break isSpace s' unlines :: [String] -> String unlines [] = [] unlines (l:ls) = l ++ '\n' : unlines ls unwords :: [String] -> String unwords [] = "" unwords [w] = w unwords (w:ws) = w ++ ' ' : unwords ws reverse :: [a] -> [a] reverse = foldl (flip (:)) [] and, or :: [Bool] -> Bool and = foldr (&&) True or = foldr (||) False any, all :: (a -> Bool) -> [a] -> Bool any p = or . map p all p = and . map p elem, notElem :: Eq a => a -> [a] -> Bool elem = any . (==) notElem = all . (/=) lookup :: Eq a => a -> [(a,b)] -> Maybe b lookup k [] = Nothing lookup k ((x,y):xys) | k==x = Just y | otherwise = lookup k xys sum, product :: Num a => [a] -> a sum = foldl' (+) 0 product = foldl' (*) 1 maximum, minimum :: Ord a => [a] -> a maximum = foldl1 max minimum = foldl1 min concatMap :: (a -> [b]) -> [a] -> [b] concatMap _ [] = [] concatMap f (x:xs) = f x ++ concatMap f xs zip :: [a] -> [b] -> [(a,b)] zip = zipWith (\a b -> (a,b)) zip3 :: [a] -> [b] -> [c] -> [(a,b,c)] zip3 = zipWith3 (\a b c -> (a,b,c)) zipWith :: (a->b->c) -> [a]->[b]->[c] zipWith z (a:as) (b:bs) = z a b : zipWith z as bs zipWith _ _ _ = [] zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d] zipWith3 z (a:as) (b:bs) (c:cs) = z a b c : zipWith3 z as bs cs zipWith3 _ _ _ _ = [] unzip :: [(a,b)] -> ([a],[b]) unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], []) unzip3 :: [(a,b,c)] -> ([a],[b],[c]) unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs)) ([],[],[]) -------------------------------------------------------------- -- PreludeText -------------------------------------------------------------- reads :: Read a => ReadS a reads = readsPrec 0 shows :: Show a => a -> ShowS shows = showsPrec 0 read :: Read a => String -> a read s = case [x | (x,t) <- reads s, ("","") <- lex t] of [x] -> x [] -> error "Prelude.read: no parse" _ -> error "Prelude.read: ambiguous parse" showChar :: Char -> ShowS showChar = (:) showString :: String -> ShowS showString = (++) showParen :: Bool -> ShowS -> ShowS showParen b p = if b then showChar '(' . p . showChar ')' else p showField :: Show a => String -> a -> ShowS showField m@(c:_) v | isAlpha c || c == '_' = showString m . showString " = " . shows v | otherwise = showChar '(' . showString m . showString ") = " . shows v readParen :: Bool -> ReadS a -> ReadS a readParen b g = if b then mandatory else optional where optional r = g r ++ mandatory r mandatory r = [(x,u) | ("(",s) <- lex r, (x,t) <- optional s, (")",u) <- lex t ] readField :: Read a => String -> ReadS a readField m s0 = [ r | (t, s1) <- readFieldName m s0, ("=",s2) <- lex s1, r <- reads s2 ] readFieldName :: String -> ReadS String readFieldName m@(c:_) s0 | isAlpha c || c == '_' = [ (f,s1) | (f,s1) <- lex s0, f == m ] | otherwise = [ (f,s3) | ("(",s1) <- lex s0, (f,s2) <- lex s1, f == m, (")",s3) <- lex s2 ] lex :: ReadS String lex "" = [("","")] lex (c:s) | isSpace c = lex (dropWhile isSpace s) lex ('\'':s) = [('\'':ch++"'", t) | (ch,'\'':t) <- lexLitChar s, -- head ch /= '\'' || not (null (tail ch)) ch /= "'" ] lex ('"':s) = [('"':str, t) | (str,t) <- lexString s] where lexString ('"':s) = [("\"",s)] lexString s = [(ch++str, u) | (ch,t) <- lexStrItem s, (str,u) <- lexString t ] lexStrItem ('\\':'&':s) = [("\\&",s)] lexStrItem ('\\':c:s) | isSpace c = [("",t) | '\\':t <- [dropWhile isSpace s]] lexStrItem s = lexLitChar s lex (c:s) | isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]] | isAlpha c = [(c:nam,t) | (nam,t) <- [span isIdChar s]] -- '_' can be the start of a single char or a name/id. | c == '_' = case span isIdChar s of ([],_) -> [([c],s)] (nm,t) -> [((c:nm),t)] | isSingle c = [([c],s)] | isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s], (fe,t) <- lexFracExp s ] | otherwise = [] -- bad character where isSingle c = c `elem` ",;()[]{}_`" isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~" isIdChar c = isAlphaNum c || c `elem` "_'" lexFracExp ('.':c:cs) | isDigit c = [('.':ds++e,u) | (ds,t) <- lexDigits (c:cs), (e,u) <- lexExp t ] lexFracExp s = lexExp s lexExp (e:s) | e `elem` "eE" = [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-", (ds,u) <- lexDigits t] ++ [(e:ds,t) | (ds,t) <- lexDigits s] lexExp s = [("",s)] lexDigits :: ReadS String lexDigits = nonnull isDigit nonnull :: (Char -> Bool) -> ReadS String nonnull p s = [(cs,t) | (cs@(_:_),t) <- [span p s]] lexLitChar :: ReadS String lexLitChar "" = [] lexLitChar (c:s) | c /= '\\' = [([c],s)] | otherwise = map (prefix '\\') (lexEsc s) where lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = [([c],s)] lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)] -- Numeric escapes lexEsc ('o':s) = [prefix 'o' (span isOctDigit s)] lexEsc ('x':s) = [prefix 'x' (span isHexDigit s)] lexEsc s@(c:_) | isDigit c = [span isDigit s] | isUpper c = case [(mne,s') | (c, mne) <- table, ([],s') <- [lexmatch mne s]] of (pr:_) -> [pr] [] -> [] lexEsc _ = [] table = ('\DEL',"DEL") : asciiTab prefix c (t,s) = (c:t, s) isOctDigit c = c >= '0' && c <= '7' isHexDigit c = isDigit c || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f' lexmatch :: (Eq a) => [a] -> [a] -> ([a],[a]) lexmatch (x:xs) (y:ys) | x == y = lexmatch xs ys lexmatch xs ys = (xs,ys) asciiTab = zip ['\NUL'..' '] (["NUL", "SOH", "STX", "ETX"]++[ "EOT", "ENQ", "ACK", "BEL"]++ [ "BS", "HT", "LF", "VT" ]++[ "FF", "CR", "SO", "SI"]++ [ "DLE", "DC1", "DC2", "DC3"]++[ "DC4", "NAK", "SYN", "ETB"]++ [ "CAN", "EM", "SUB", "ESC"]++[ "FS", "GS", "RS", "US"]++ [ "SP"]) readLitChar :: ReadS Char readLitChar ('\\':s) = readEsc s where readEsc ('a':s) = [('\a',s)] readEsc ('b':s) = [('\b',s)] readEsc ('f':s) = [('\f',s)] readEsc ('n':s) = [('\n',s)] readEsc ('r':s) = [('\r',s)] readEsc ('t':s) = [('\t',s)] readEsc ('v':s) = [('\v',s)] readEsc ('\\':s) = [('\\',s)] readEsc ('"':s) = [('"',s)] readEsc ('\'':s) = [('\'',s)] readEsc ('^':c:s) | c >= '@' && c <= '_' = [(toEnum (fromEnum c - fromEnum '@'), s)] readEsc s@(d:_) | isDigit d = [(toEnum n, t) | (n,t) <- readDec s] readEsc ('o':s) = [(toEnum n, t) | (n,t) <- readOct s] readEsc ('x':s) = [(toEnum n, t) | (n,t) <- readHex s] readEsc s@(c:_) | isUpper c = let table = ('\DEL',"DEL") : asciiTab in case [(c,s') | (c, mne) <- table, ([],s') <- [lexmatch mne s]] of (pr:_) -> [pr] [] -> [] readEsc _ = [] readLitChar (c:s) = [(c,s)] showLitChar :: Char -> ShowS showLitChar c | c > '\DEL' = showChar '\\' . protectEsc isDigit (shows (fromEnum c)) showLitChar '\DEL' = showString "\\DEL" showLitChar '\\' = showString "\\\\" showLitChar c | c >= ' ' = showChar c showLitChar '\a' = showString "\\a" showLitChar '\b' = showString "\\b" showLitChar '\f' = showString "\\f" showLitChar '\n' = showString "\\n" showLitChar '\r' = showString "\\r" showLitChar '\t' = showString "\\t" showLitChar '\v' = showString "\\v" showLitChar '\SO' = protectEsc ('H'==) (showString "\\SO") showLitChar c = showString ('\\' : snd (asciiTab!!fromEnum c)) -- the composition with cont makes CoreToGrin break the GrinModeInvariant so we forget about protecting escapes for the moment protectEsc p f = f -- . cont where cont s@(c:_) | p c = "\\&" ++ s cont s = s -- Unsigned readers for various bases readDec, readOct, readHex :: Integral a => ReadS a readDec = readInt 10 isDigit (\ d -> fromEnum d - fromEnum_0) readOct = readInt 8 isOctDigit (\ d -> fromEnum d - fromEnum_0) readHex = readInt 16 isHexDigit hex where hex d = fromEnum d - (if isDigit d then fromEnum_0 else fromEnum (if isUpper d then 'A' else 'a') - 10) fromEnum_0 :: Int fromEnum_0 = fromEnum '0' -- readInt reads a string of digits using an arbitrary base. -- Leading minus signs must be handled elsewhere. readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a readInt radix isDig digToInt s = [(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r) | (ds,r) <- nonnull isDig s ] readSigned:: Real a => ReadS a -> ReadS a readSigned readPos = readParen False read' where read' r = read'' r ++ [(-x,t) | ("-",s) <- lex r, (x,t) <- read'' s] read'' r = [(n,s) | (str,s) <- lex r, (n,"") <- readPos str] -- This floating point reader uses a less restrictive syntax for floating -- point than the Haskell lexer. The `.' is optional. readFloat :: RealFrac a => ReadS a readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r, (k,t) <- readExp s] ++ [ (0/0, t) | ("NaN",t) <- lex r] ++ [ (1/0, t) | ("Infinity",t) <- lex r] where readFix r = [(read (ds++ds'), length ds', t) | (ds, d) <- lexDigits r , (ds',t) <- lexFrac d ] lexFrac ('.':s) = lexDigits s lexFrac s = [("",s)] readExp (e:s) | e `elem` "eE" = readExp' s readExp s = [(0::Int,s)] readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s] readExp' ('+':s) = readDec s readExp' s = readDec s ---------------------------------------------------------------- -- Monadic I/O implementation ---------------------------------------------------------------- instance Functor IO where fmap f x = x >>= (return . f) instance Monad IO where (>>=) = primbindIO return = primretIO fail s = ioError (userError s) -- Primitive ordering ops primCmpChar :: Char -> Char -> Ordering primCmpInteger :: Integer -> Integer -> Ordering primCmpFloat :: Float -> Float -> Ordering -- primitive rational operat primRationalToFloat :: Rational -> Float primRationalToDouble :: Rational -> Double
rodrigogribeiro/mptc
src/Libs/Base.hs
Haskell
bsd-3-clause
50,296
-- | -- Scalpel is a web scraping library inspired by libraries like parsec and -- Perl's <http://search.cpan.org/~miyagawa/Web-Scraper-0.38/ Web::Scraper>. -- Scalpel builds on top of "Text.HTML.TagSoup" to provide a declarative and -- monadic interface. -- -- There are two general mechanisms provided by this library that are used to -- build web scrapers: Selectors and Scrapers. -- -- -- Selectors describe a location within an HTML DOM tree. The simplest selector, -- that can be written is a simple string value. For example, the selector -- @\"div\"@ matches every single div node in a DOM. Selectors can be combined -- using tag combinators. The '//' operator to define nested relationships -- within a DOM tree. For example, the selector @\"div\" \/\/ \"a\"@ matches all -- anchor tags nested arbitrarily deep within a div tag. -- -- In addition to describing the nested relationships between tags, selectors -- can also include predicates on the attributes of a tag. The '@:' operator -- creates a selector that matches a tag based on the name and various -- conditions on the tag's attributes. An attribute predicate is just a function -- that takes an attribute and returns a boolean indicating if the attribute -- matches a criteria. There are several attribute operators that can be used -- to generate common predicates. The '@=' operator creates a predicate that -- matches the name and value of an attribute exactly. For example, the selector -- @\"div\" \@: [\"id\" \@= \"article\"]@ matches div tags where the id -- attribute is equal to @\"article\"@. -- -- -- Scrapers are values that are parameterized over a selector and produce -- a value from an HTML DOM tree. The 'Scraper' type takes two type parameters. -- The first is the string like type that is used to store the text values -- within a DOM tree. Any string like type supported by "Text.StringLike" is -- valid. The second type is the type of value that the scraper produces. -- -- There are several scraper primitives that take selectors and extract content -- from the DOM. Each primitive defined by this library comes in two variants: -- singular and plural. The singular variants extract the first instance -- matching the given selector, while the plural variants match every instance. -- -- -- The following is an example that demonstrates most of the features provided -- by this library. Suppose you have the following hypothetical HTML located at -- @\"http://example.com/article.html\"@ and you would like to extract a list of -- all of the comments. -- -- > <html> -- > <body> -- > <div class='comments'> -- > <div class='comment container'> -- > <span class='comment author'>Sally</span> -- > <div class='comment text'>Woo hoo!</div> -- > </div> -- > <div class='comment container'> -- > <span class='comment author'>Bill</span> -- > <img class='comment image' src='http://example.com/cat.gif' /> -- > </div> -- > <div class='comment container'> -- > <span class='comment author'>Susan</span> -- > <div class='comment text'>WTF!?!</div> -- > </div> -- > </div> -- > </body> -- > </html> -- -- The following snippet defines a function, @allComments@, that will download -- the web page, and extract all of the comments into a list: -- -- > type Author = String -- > -- > data Comment -- > = TextComment Author String -- > | ImageComment Author URL -- > deriving (Show, Eq) -- > -- > allComments :: IO (Maybe [Comment]) -- > allComments = scrapeURL "http://example.com/article.html" comments -- > where -- > comments :: Scraper String [Comment] -- > comments = chroots ("div" @: [hasClass "container"]) comment -- > -- > comment :: Scraper String Comment -- > comment = textComment <|> imageComment -- > -- > textComment :: Scraper String Comment -- > textComment = do -- > author <- text $ "span" @: [hasClass "author"] -- > commentText <- text $ "div" @: [hasClass "text"] -- > return $ TextComment author commentText -- > -- > imageComment :: Scraper String Comment -- > imageComment = do -- > author <- text $ "span" @: [hasClass "author"] -- > imageURL <- attr "src" $ "img" @: [hasClass "image"] -- > return $ ImageComment author imageURL -- -- Complete examples can be found in the -- <https://github.com/fimad/scalpel/examples examples> folder in the scalpel -- git repository. module Text.HTML.Scalpel ( -- * Selectors Selector , Selectable (..) , AttributePredicate , AttributeName , TagName -- ** Wildcards , Any (..) -- ** Tag combinators , (//) -- ** Attribute predicates , (@:) , (@=) , (@=~) , hasClass -- ** Executing selectors , select -- * Scrapers , Scraper -- ** Primitives , attr , attrs , html , htmls , text , texts , chroot , chroots -- ** Executing scrapers , scrape , scrapeStringLike , URL , scrapeURL , scrapeURLWithOpts ) where import Text.HTML.Scalpel.Internal.Scrape import Text.HTML.Scalpel.Internal.Scrape.StringLike import Text.HTML.Scalpel.Internal.Scrape.URL import Text.HTML.Scalpel.Internal.Select import Text.HTML.Scalpel.Internal.Select.Combinators import Text.HTML.Scalpel.Internal.Select.Types
sulami/scalpel
src/Text/HTML/Scalpel.hs
Haskell
apache-2.0
5,333
module L01.Validation.Tests where import Test.Framework import Test.Framework.Providers.QuickCheck2 (testProperty) import L01.Validation import Test.QuickCheck import Test.QuickCheck.Function instance Arbitrary a => Arbitrary (Validation a) where arbitrary = fmap (either Error Value) arbitrary main :: IO () main = defaultMain [test] test :: Test test = testGroup "Validation" [ testProperty "isError is not equal to isValue" prop_isError_isValue , testProperty "valueOr produces or isValue" prop_valueOr , testProperty "errorOr produces or isError" prop_errorOr , testProperty "mapValidation maps" prop_map ] prop_isError_isValue :: Validation Int -> Bool prop_isError_isValue x = isError x /= isValue x prop_valueOr :: Validation Int -> Int -> Bool prop_valueOr x n = isValue x || valueOr x n == n prop_errorOr :: Validation Err -> Err -> Bool prop_errorOr x e = isError x || errorOr x e == e prop_map :: Validation Int -> Fun Int Int -> Int -> Bool prop_map x (Fun _ f) n = f (valueOr x n) == valueOr (mapValidation f x) (f n)
juretta/course
test/src/L01/Validation/Tests.hs
Haskell
bsd-3-clause
1,117
{-# LANGUAGE Haskell2010, CPP, Rank2Types, DeriveDataTypeable, StandaloneDeriving #-} {-# LINE 1 "lib/Data/Time/Clock/UTC.hs" #-} {-# OPTIONS -fno-warn-unused-imports #-} {-# LANGUAGE Trustworthy #-} -- #hide module Data.Time.Clock.UTC ( -- * UTC -- | UTC is time as measured by a clock, corrected to keep pace with the earth by adding or removing -- occasional seconds, known as \"leap seconds\". -- These corrections are not predictable and are announced with six month's notice. -- No table of these corrections is provided, as any program compiled with it would become -- out of date in six months. -- -- If you don't care about leap seconds, use UTCTime and NominalDiffTime for your clock calculations, -- and you'll be fine. UTCTime(..),NominalDiffTime ) where import Control.DeepSeq import Data.Time.Calendar.Days import Data.Time.Clock.Scale import Data.Fixed import Data.Typeable import Data.Data -- | This is the simplest representation of UTC. -- It consists of the day number, and a time offset from midnight. -- Note that if a day has a leap second added to it, it will have 86401 seconds. data UTCTime = UTCTime { -- | the day utctDay :: Day, -- | the time from midnight, 0 <= t < 86401s (because of leap-seconds) utctDayTime :: DiffTime } deriving (Data, Typeable) instance NFData UTCTime where rnf (UTCTime d t) = d `deepseq` t `deepseq` () instance Eq UTCTime where (UTCTime da ta) == (UTCTime db tb) = (da == db) && (ta == tb) instance Ord UTCTime where compare (UTCTime da ta) (UTCTime db tb) = case (compare da db) of EQ -> compare ta tb cmp -> cmp -- | This is a length of time, as measured by UTC. -- Conversion functions will treat it as seconds. -- It has a precision of 10^-12 s. -- It ignores leap-seconds, so it's not necessarily a fixed amount of clock time. -- For instance, 23:00 UTC + 2 hours of NominalDiffTime = 01:00 UTC (+ 1 day), -- regardless of whether a leap-second intervened. newtype NominalDiffTime = MkNominalDiffTime Pico deriving (Eq,Ord ,Data, Typeable ) -- necessary because H98 doesn't have "cunning newtype" derivation instance NFData NominalDiffTime where -- FIXME: Data.Fixed had no NFData instances yet at time of writing rnf ndt = seq ndt () instance Enum NominalDiffTime where succ (MkNominalDiffTime a) = MkNominalDiffTime (succ a) pred (MkNominalDiffTime a) = MkNominalDiffTime (pred a) toEnum = MkNominalDiffTime . toEnum fromEnum (MkNominalDiffTime a) = fromEnum a enumFrom (MkNominalDiffTime a) = fmap MkNominalDiffTime (enumFrom a) enumFromThen (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromThen a b) enumFromTo (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromTo a b) enumFromThenTo (MkNominalDiffTime a) (MkNominalDiffTime b) (MkNominalDiffTime c) = fmap MkNominalDiffTime (enumFromThenTo a b c) instance Show NominalDiffTime where show (MkNominalDiffTime t) = (showFixed True t) ++ "s" -- necessary because H98 doesn't have "cunning newtype" derivation instance Num NominalDiffTime where (MkNominalDiffTime a) + (MkNominalDiffTime b) = MkNominalDiffTime (a + b) (MkNominalDiffTime a) - (MkNominalDiffTime b) = MkNominalDiffTime (a - b) (MkNominalDiffTime a) * (MkNominalDiffTime b) = MkNominalDiffTime (a * b) negate (MkNominalDiffTime a) = MkNominalDiffTime (negate a) abs (MkNominalDiffTime a) = MkNominalDiffTime (abs a) signum (MkNominalDiffTime a) = MkNominalDiffTime (signum a) fromInteger i = MkNominalDiffTime (fromInteger i) -- necessary because H98 doesn't have "cunning newtype" derivation instance Real NominalDiffTime where toRational (MkNominalDiffTime a) = toRational a -- necessary because H98 doesn't have "cunning newtype" derivation instance Fractional NominalDiffTime where (MkNominalDiffTime a) / (MkNominalDiffTime b) = MkNominalDiffTime (a / b) recip (MkNominalDiffTime a) = MkNominalDiffTime (recip a) fromRational r = MkNominalDiffTime (fromRational r) -- necessary because H98 doesn't have "cunning newtype" derivation instance RealFrac NominalDiffTime where properFraction (MkNominalDiffTime a) = (i,MkNominalDiffTime f) where (i,f) = properFraction a truncate (MkNominalDiffTime a) = truncate a round (MkNominalDiffTime a) = round a ceiling (MkNominalDiffTime a) = ceiling a floor (MkNominalDiffTime a) = floor a {-# RULES "realToFrac/DiffTime->NominalDiffTime" realToFrac = \ dt -> MkNominalDiffTime (realToFrac dt) "realToFrac/NominalDiffTime->DiffTime" realToFrac = \ (MkNominalDiffTime ps) -> realToFrac ps "realToFrac/NominalDiffTime->Pico" realToFrac = \ (MkNominalDiffTime ps) -> ps "realToFrac/Pico->NominalDiffTime" realToFrac = MkNominalDiffTime #-}
phischu/fragnix
tests/packages/scotty/Data.Time.Clock.UTC.hs
Haskell
bsd-3-clause
4,906
{-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE CPP, UndecidableInstances, ParallelListComp #-} -- Undeciable instances only need for derived Show instance #include "fusion-phases.h" -- | Parallel array types and the PR class that works on the generic -- representation of array data. module Data.Array.Parallel.PArray.PData.Base ( -- * Parallel Array types. PArray(..) , length, takeData , PR (..) , PData(..), PDatas(..) , bpermutePR) where import Data.Array.Parallel.Pretty import GHC.Exts import SpecConstr () import Data.Vector (Vector) import Data.Array.Parallel.Base (Tag) import qualified Data.Array.Parallel.Unlifted as U import qualified Data.Vector as V import qualified Data.Typeable as T import Prelude hiding (length) -- PArray --------------------------------------------------------------------- -- | A parallel array consisting of a length field and some array data. -- IMPORTANT: -- The vectoriser requires the PArray data constructor to have this specific -- form, because it builds them explicitly. Specifically, the array length -- must be unboxed. -- -- TODO: Why do we need the NoSpecConstr annotation? -- {-# ANN type PArray NoSpecConstr #-} data PArray a = PArray Int# (PData a) deriving instance T.Typeable PArray -- | Take the length field of a `PArray`. {-# INLINE_PA length #-} length :: PArray a -> Int length (PArray n# _) = (I# n#) -- | Take the `PData` of a `PArray`. {-# INLINE_PA takeData #-} takeData :: PArray a -> PData a takeData (PArray _ d) = d -- Parallel array data -------------------------------------------------------- -- | A chunk of parallel array data with a linear index space. -- -- In contrast to a `PArray`, a `PData` may not have a fixed length, and its -- elements may have been converted to a generic representation. Whereas a -- `PArray` is the \"user view\" of an array, a `PData` is a type only -- used internally to the library. -- An example of an array with no length is PData Void. We can index this -- at an arbitrary position, and always get a 'void' element back. -- {-# ANN type PData NoSpecConstr #-} data family PData a -- | Several chunks of parallel array data. -- -- Although a `PArray` of atomic type such as `Int` only contains a -- single `PData` chunk, nested arrays may contain several, which we -- wrap up into a `PDatas`. {-# ANN type PDatas NoSpecConstr #-} data family PDatas a -- Put these here to break an import loop. data instance PData Int = PInt (U.Array Int) data instance PDatas Int = PInts (U.Arrays Int) -- PR ------------------------------------------------------------------------- -- | The PR (Parallel Representation) class holds primitive array operators that -- work on our generic representation of data. -- -- There are instances for all atomic types such as `Int` and `Double`, tuples, -- nested arrays `PData (PArray a)` and for the generic types we used to represent -- user level algebraic data, `Sum2` and `Wrap` and `Void`. All array data -- is converted to this fixed set of types. -- -- TODO: refactor to change PData Int to U.Array Int, -- there's not need to wrap an extra PData constructor around these arrays, -- and the type of bpermute is different than the others. class PR a where -- House Keeping ------------------------------ -- These methods are helpful for debugging, but we don't want their -- associated type classes as superclasses of PR. -- | (debugging) Check that an array has a well formed representation. -- This should only return `False` where there is a bug in the library. validPR :: PData a -> Bool -- | (debugging) Ensure an array is fully evaluted. nfPR :: PData a -> () -- | (debugging) Weak equality of contained elements. -- -- Returns `True` for functions of the same type. In the case of nested arrays, -- returns `True` if the array defines the same set of elements, but does not -- care about the exact form of the segement descriptors. similarPR :: a -> a -> Bool -- | (debugging) Check that an index is within an array. -- -- Arrays containing `Void` elements don't have a fixed length, and return -- `Void` for all indices. If the array does have a fixed length, and the -- flag is true, then we allow the index to be equal to this length, as -- well as less than it. coversPR :: Bool -> PData a -> Int -> Bool -- | (debugging) Pretty print the physical representation of an element. pprpPR :: a -> Doc -- | (debugging) Pretty print the physical representation of some array data. pprpDataPR :: PData a -> Doc -- | (debugging) Get the representation of this type. -- We don't use the Typeable class for this because the vectoriser -- won't handle the Typeable superclass on PR. typeRepPR :: a -> T.TypeRep -- | (debugging) Given a 'PData a' get the representation of the 'a' typeRepDataPR :: PData a -> T.TypeRep -- | (debugging) Given a 'PDatas a' get the representation of the 'a' typeRepDatasPR :: PDatas a -> T.TypeRep -- Constructors ------------------------------- -- | Produce an empty array with size zero. emptyPR :: PData a -- | O(n). Define an array of the given size, that maps all elements to the -- same value. -- -- We require the replication count to be > 0 so that it's easier to -- maintain the `validPR` invariants for nested arrays. replicatePR :: Int -> a -> PData a -- | O(sum lengths). Segmented replicate. -- -- Given a Segment Descriptor (Segd), replicate each each element in the -- array according to the length of the corrsponding segment. -- The array data must define at least as many elements as there are segments -- in the descriptor. -- TODO: This takes a whole Segd instead of just the lengths. If the Segd knew -- that there were no zero length segments then we could implement this -- more efficiently in the nested case case. If there are no zeros, then -- all psegs in the result are reachable from the vsegs, and we wouldn't -- need to pack them after the replicate. -- replicatesPR :: U.Segd -> PData a -> PData a -- | Append two arrays. appendPR :: PData a -> PData a -> PData a -- | Segmented append. -- -- The first descriptor defines the segmentation of the result, -- and the others define the segmentation of each source array. appendvsPR :: U.Segd -> U.VSegd -> PDatas a -> U.VSegd -> PDatas a -> PData a -- Projections -------------------------------- -- | O(1). Get the length of an array, if it has one. -- -- Applying this function to an array of `Void` will yield `error`, as -- these arrays have no fixed length. To check array bounds, use the -- `coversPR` method instead, as that is a total function. lengthPR :: PData a -> Int -- | O(1). Retrieve a single element from a single array. indexPR :: PData a -> Int -> a -- | O(1). Shared indexing. -- Retrieve several elements from several chunks of array data, -- given the chunkid and index in that chunk for each element. indexsPR :: PDatas a -> U.Array (Int, Int) -> PData a -- | O(1). Shared indexing indexvsPR :: PDatas a -> U.VSegd -> U.Array (Int, Int) -> PData a -- | O(slice len). Extract a slice of elements from an array, -- given the starting index and length of the slice. extractPR :: PData a -> Int -> Int -> PData a -- | O(sum seglens). Shared extract. -- Extract several slices from several source arrays. -- -- The Scattered Segment Descriptor (`SSegd`) describes where to get each -- slice, and all slices are concatenated together into the result. extractssPR :: PDatas a -> U.SSegd -> PData a -- | O(sum seglens). Shared extract. -- Extract several slices from several source arrays. -- TODO: we're refactoring the library so functions use the VSeg form directly, -- instead of going via a SSegd. extractvsPR :: PDatas a -> U.VSegd -> PData a extractvsPR pdatas vsegd = extractssPR pdatas (U.unsafeDemoteToSSegdOfVSegd vsegd) -- Pack and Combine --------------------------- -- | Select elements of an array that have their corresponding tag set to -- the given value. -- -- The data array must define at least as many elements as the length -- of the tags array. packByTagPR :: PData a -> U.Array Tag -> Tag -> PData a -- | Combine two arrays based on a selector. -- -- See the documentation for selectors in the dph-prim-seq library -- for how this works. combine2PR :: U.Sel2 -> PData a -> PData a -> PData a -- Conversions -------------------------------- -- | Convert a boxed vector to an array. fromVectorPR :: Vector a -> PData a -- | Convert an array to a boxed vector. toVectorPR :: PData a -> Vector a -- PDatas ------------------------------------- -- | O(1). Yield an empty collection of `PData`. emptydPR :: PDatas a -- | O(1). Yield a singleton collection of `PData`. singletondPR :: PData a -> PDatas a -- | O(1). Yield how many `PData` are in the collection. lengthdPR :: PDatas a -> Int -- | O(1). Lookup a `PData` from a collection. indexdPR :: PDatas a -> Int -> PData a -- | O(n). Append two collections of `PData`. appenddPR :: PDatas a -> PDatas a -> PDatas a -- | O(n). Convert a vector of `PData` to a `PDatas`. fromVectordPR :: V.Vector (PData a) -> PDatas a -- | O(n). Convert a `PDatas` to a vector of `PData`. toVectordPR :: PDatas a -> V.Vector (PData a) -- | O(len indices) Backwards permutation. -- Retrieve several elements from a single array. bpermutePR :: PR a => PData a -> U.Array Int -> PData a bpermutePR pdata ixs = indexsPR (singletondPR pdata) (U.zip (U.replicate (U.length ixs) 0) ixs) -- Pretty --------------------------------------------------------------------- instance PR a => PprPhysical (PData a) where pprp = pprpDataPR instance PR a => PprPhysical (PDatas a) where pprp pdatas = vcat $ [ int n <> colon <> text " " <> pprpDataPR pd | n <- [0..] | pd <- V.toList $ toVectordPR pdatas]
mainland/dph
dph-lifted-vseg/Data/Array/Parallel/PArray/PData/Base.hs
Haskell
bsd-3-clause
10,584
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Control/Applicative/Lift.hs" #-} {-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {-# LANGUAGE AutoDeriveTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Applicative.Lift -- Copyright : (c) Ross Paterson 2010 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Adding a new kind of pure computation to an applicative functor. ----------------------------------------------------------------------------- module Control.Applicative.Lift ( -- * Lifting an applicative Lift(..), unLift, mapLift, elimLift, -- * Collecting errors Errors, runErrors, failure, eitherToErrors ) where import Data.Functor.Classes import Control.Applicative import Data.Foldable (Foldable(foldMap)) import Data.Functor.Constant import Data.Monoid (Monoid(..)) import Data.Traversable (Traversable(traverse)) -- | Applicative functor formed by adding pure computations to a given -- applicative functor. data Lift f a = Pure a | Other (f a) instance (Eq1 f) => Eq1 (Lift f) where liftEq eq (Pure x1) (Pure x2) = eq x1 x2 liftEq _ (Pure _) (Other _) = False liftEq _ (Other _) (Pure _) = False liftEq eq (Other y1) (Other y2) = liftEq eq y1 y2 {-# INLINE liftEq #-} instance (Ord1 f) => Ord1 (Lift f) where liftCompare comp (Pure x1) (Pure x2) = comp x1 x2 liftCompare _ (Pure _) (Other _) = LT liftCompare _ (Other _) (Pure _) = GT liftCompare comp (Other y1) (Other y2) = liftCompare comp y1 y2 {-# INLINE liftCompare #-} instance (Read1 f) => Read1 (Lift f) where liftReadsPrec rp rl = readsData $ readsUnaryWith rp "Pure" Pure `mappend` readsUnaryWith (liftReadsPrec rp rl) "Other" Other instance (Show1 f) => Show1 (Lift f) where liftShowsPrec sp _ d (Pure x) = showsUnaryWith sp "Pure" d x liftShowsPrec sp sl d (Other y) = showsUnaryWith (liftShowsPrec sp sl) "Other" d y instance (Eq1 f, Eq a) => Eq (Lift f a) where (==) = eq1 instance (Ord1 f, Ord a) => Ord (Lift f a) where compare = compare1 instance (Read1 f, Read a) => Read (Lift f a) where readsPrec = readsPrec1 instance (Show1 f, Show a) => Show (Lift f a) where showsPrec = showsPrec1 instance (Functor f) => Functor (Lift f) where fmap f (Pure x) = Pure (f x) fmap f (Other y) = Other (fmap f y) {-# INLINE fmap #-} instance (Foldable f) => Foldable (Lift f) where foldMap f (Pure x) = f x foldMap f (Other y) = foldMap f y {-# INLINE foldMap #-} instance (Traversable f) => Traversable (Lift f) where traverse f (Pure x) = Pure <$> f x traverse f (Other y) = Other <$> traverse f y {-# INLINE traverse #-} -- | A combination is 'Pure' only if both parts are. instance (Applicative f) => Applicative (Lift f) where pure = Pure {-# INLINE pure #-} Pure f <*> Pure x = Pure (f x) Pure f <*> Other y = Other (f <$> y) Other f <*> Pure x = Other (($ x) <$> f) Other f <*> Other y = Other (f <*> y) {-# INLINE (<*>) #-} -- | A combination is 'Pure' only either part is. instance (Alternative f) => Alternative (Lift f) where empty = Other empty {-# INLINE empty #-} Pure x <|> _ = Pure x Other _ <|> Pure y = Pure y Other x <|> Other y = Other (x <|> y) {-# INLINE (<|>) #-} -- | Projection to the other functor. unLift :: (Applicative f) => Lift f a -> f a unLift (Pure x) = pure x unLift (Other e) = e {-# INLINE unLift #-} -- | Apply a transformation to the other computation. mapLift :: (f a -> g a) -> Lift f a -> Lift g a mapLift _ (Pure x) = Pure x mapLift f (Other e) = Other (f e) {-# INLINE mapLift #-} -- | Eliminator for 'Lift'. -- -- * @'elimLift' f g . 'pure' = f@ -- -- * @'elimLift' f g . 'Other' = g@ -- elimLift :: (a -> r) -> (f a -> r) -> Lift f a -> r elimLift f _ (Pure x) = f x elimLift _ g (Other e) = g e {-# INLINE elimLift #-} -- | An applicative functor that collects a monoid (e.g. lists) of errors. -- A sequence of computations fails if any of its components do, but -- unlike monads made with 'ExceptT' from "Control.Monad.Trans.Except", -- these computations continue after an error, collecting all the errors. -- -- * @'pure' f '<*>' 'pure' x = 'pure' (f x)@ -- -- * @'pure' f '<*>' 'failure' e = 'failure' e@ -- -- * @'failure' e '<*>' 'pure' x = 'failure' e@ -- -- * @'failure' e1 '<*>' 'failure' e2 = 'failure' (e1 '<>' e2)@ -- type Errors e = Lift (Constant e) -- | Extractor for computations with accumulating errors. -- -- * @'runErrors' ('pure' x) = 'Right' x@ -- -- * @'runErrors' ('failure' e) = 'Left' e@ -- runErrors :: Errors e a -> Either e a runErrors (Other (Constant e)) = Left e runErrors (Pure x) = Right x {-# INLINE runErrors #-} -- | Report an error. failure :: e -> Errors e a failure e = Other (Constant e) {-# INLINE failure #-} -- | Convert from 'Either' to 'Errors' (inverse of 'runErrors'). eitherToErrors :: Either e a -> Errors e a eitherToErrors = either failure Pure
phischu/fragnix
tests/packages/scotty/Control.Applicative.Lift.hs
Haskell
bsd-3-clause
5,157
-- Thanks to Bryan O'Sullivan for this test case. -- hexpat will spawn zillions of threads (which is seen as huge virtual memory -- usage in top). This is now fixed in 0.19.1. import Control.Concurrent import Control.Monad import qualified Data.ByteString as B import Text.XML.Expat.Tree import System.Environment main = do [path, threads, reads] <- getArgs let nthreads = read threads qs <- newQSem 0 replicateM_ nthreads $ do forkIO $ do replicateM_ (read reads) $ do bs <- B.readFile path case parse' defaultParseOptions bs of Left err -> print err Right p -> print (p :: UNode B.ByteString) signalQSem qs replicateM_ nthreads $ waitQSem qs putStrLn "done"
the-real-blackh/hexpat
test/hexpat-leak/Parse.hs
Haskell
bsd-3-clause
727
{-# LANGUAGE FlexibleInstances, UndecidableInstances, GADTs #-} module Bind(Fresh(..),Freshen(..),Swap(..),Name,Perm ,Bind,bind ,swapM, swapsM, swapsMf ,M,runM ,unsafeUnBind,reset,name1,name2,name3,name4,name5,name2Int,integer2Name) where import Control.Monad.Fix(MonadFix(..)) import Monads class (Monad m, HasNext m) => Fresh m where fresh :: m Name class Freshen b where freshen :: Fresh m => b -> m (b,[(Name,Name)]) unbind :: (Fresh m,Swap c) => Bind b c -> m(b,c) unbind (B x y) = do { (x',perm) <- freshen x ; return(x',swaps perm y) } class Swap b where swap :: Name -> Name -> b -> b swap a b x = swaps [(a,b)] x swaps :: [(Name ,Name )] -> b -> b swaps [] x = x swaps ((a,b):ps) x = swaps ps (swap a b x) sw :: Eq a => a -> a -> a -> a sw x y s | x==s = y | y==s = x | True = s ------------------------------------------------------- instance Freshen Int where freshen n = return(n,[]) instance Freshen b => Freshen [b] where freshen xs = do { pairs <- mapM freshen xs ; return (map fst pairs,concat(map snd pairs))} instance (Freshen a,Freshen b) => Freshen (a,b) where freshen (x,y) = do { (x',p1) <- freshen x ; (y',p2) <- freshen y ; return((x',y'),p1++p2)} ----------------------------------------------- name1 = Nm 1 name2 = Nm 2 name3 = Nm 3 name4 = Nm 4 name5 = Nm 5 type Perm = [(Name,Name)] newtype Name = Nm Integer instance Show Name where show (Nm x) = "x" ++ (show x) instance Eq Name where (Nm x) == (Nm y) = x==y instance Ord Name where compare (Nm x) (Nm y) = compare x y instance Swap Name where swap (Nm a) (Nm b) (Nm x) = Nm(sw a b x) instance Freshen Name where freshen nm = do { x <- fresh; return(x,[(nm,x)]) } instance HasNext m => Fresh m where fresh = do { n <- nextInteger; return (Nm n) } name2Int (Nm x) = x integer2Name = Nm ---------------------------------------------- data Bind a b where B :: (Freshen a,Swap b) => a -> b -> Bind a b bind :: (Freshen a,Swap b) => a -> b -> Bind a b bind a b = B a b unsafeUnBind (B a b) = (a,b) instance (Freshen a,Swap a,Swap b) => Swap (Bind a b) where swaps perm (B x y) = B (swaps perm x) (swaps perm y) ------------------------------------------------------------ swapM :: (Monad m,Swap x) => Name -> Name -> m x -> m x swapM a b x = do { z <- x; return(swap a b z)} swapsM :: (Monad m,Swap x) => [(Name,Name)] -> m x -> m x swapsM xs x = do { z <- x; return(swaps xs z)} swapsMf xs f = \ x -> swapsM xs (f (swaps xs x)) instance Swap a => Swap (M a) where swaps xs comp = do { e <- comp; return(swaps xs e) } instance Swap a => Swap (IO a) where swaps xs comp = do { e <- comp; return(swaps xs e) } instance (Swap a,Swap b) => Swap (a,b) where swaps perm (x,y)= (swaps perm x,swaps perm y) instance (Swap a,Swap b,Swap c) => Swap (a,b,c) where swaps perm (x,y,z)= (swaps perm x,swaps perm y,swaps perm z) instance Swap Bool where swaps xs x = x instance (Swap a,Swap b) => Swap (a -> b) where swaps perm f = \ x -> swaps perm (f (swaps perm x)) instance Swap a => Swap [a] where swaps perm xs = map (swaps perm) xs instance Swap Int where swap x y n = n instance Swap Integer where swap x y n = n instance Swap a => Swap (Maybe a) where swaps [] x = x swaps cs Nothing = Nothing swaps cs (Just x) = Just(swaps cs x) instance Swap Char where swaps cs c = c instance (Swap a,Swap b) => Swap (Either a b) where swaps [] x = x swaps cs (Left x) = Left (swaps cs x) swaps cs (Right x) = Right (swaps cs x) -------------------------------------- newtype M x = M (Integer -> (x,Integer)) unM (M f) = f instance Monad M where return x = M (\ n -> (x,n)) (>>=) (M h) g = M f where f n = let (a,n2) = h n M k = g a in k n2 runM (M f) = fst(f 0) instance HasNext M where nextInteger = M h where h n = (n,n+1) resetNext x = M h where h n = ((),x) instance HasOutput M where outputString = error instance MonadFix M where mfix = undefined
cartazio/omega
src/Bind.hs
Haskell
bsd-3-clause
4,137
{- main = 1; {-# ANN module ("HLint: ignore Use camelCase" :: String) #-} main = 1; {-# ANN module (1 + (2)) #-} -} module Comment00006 where
charleso/intellij-haskforce
tests/gold/parser/Comment00006.hs
Haskell
apache-2.0
143
module Docs.AST where import qualified Data.Map as Map import qualified Elm.Compiler.Type as Type import qualified Reporting.Annotation as A -- FULL DOCUMENTATION data Docs t = Docs { comment :: String , aliases :: Map.Map String (A.Located Alias) , types :: Map.Map String (A.Located Union) , values :: Map.Map String (A.Located (Value t)) } type Centralized = Docs (Maybe Type.Type) type Checked = Docs (Type.Type) -- VALUE DOCUMENTATION data Alias = Alias { aliasComment :: Maybe String , aliasArgs :: [String] , aliasType :: Type.Type } data Union = Union { unionComment :: Maybe String , unionArgs :: [String] , unionCases :: [(String, [Type.Type])] } data Value t = Value { valueComment :: Maybe String , valueType :: t , valueAssocPrec :: Maybe (String,Int) }
JoeyEremondi/elm-summer-opt
src/Docs/AST.hs
Haskell
bsd-3-clause
850
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 -} {-# LANGUAGE CPP #-} module IfaceSyn ( module IfaceType, IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..), IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec, IfaceExpr(..), IfaceAlt, IfaceLetBndr(..), IfaceBinding(..), IfaceConAlt(..), IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..), IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget, IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..), IfaceBang(..), IfaceSrcBang(..), SrcUnpackedness(..), SrcStrictness(..), IfaceAxBranch(..), IfaceTyConParent(..), -- Misc ifaceDeclImplicitBndrs, visibleIfConDecls, ifaceDeclFingerprints, -- Free Names freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst, -- Pretty printing pprIfaceExpr, pprIfaceDecl, ShowSub(..), ShowHowMuch(..) ) where #include "HsVersions.h" import IfaceType import PprCore() -- Printing DFunArgs import Demand import Class import NameSet import CoAxiom ( BranchIndex, Role ) import Name import CostCentre import Literal import ForeignCall import Annotations( AnnPayload, AnnTarget ) import BasicTypes import Outputable import FastString import Module import SrcLoc import Fingerprint import Binary import BooleanFormula ( BooleanFormula ) import HsBinds import TyCon ( Role (..), Injectivity(..) ) import StaticFlags (opt_PprStyle_Debug) import Util( filterOut, filterByList ) import InstEnv import DataCon (SrcStrictness(..), SrcUnpackedness(..)) import Control.Monad import System.IO.Unsafe import Data.Maybe (isJust) infixl 3 &&& {- ************************************************************************ * * Declarations * * ************************************************************************ -} type IfaceTopBndr = OccName -- It's convenient to have an OccName in the IfaceSyn, altough in each -- case the namespace is implied by the context. However, having an -- OccNames makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints -- very convenient. -- -- We don't serialise the namespace onto the disk though; rather we -- drop it when serialising and add it back in when deserialising. data IfaceDecl = IfaceId { ifName :: IfaceTopBndr, ifType :: IfaceType, ifIdDetails :: IfaceIdDetails, ifIdInfo :: IfaceIdInfo } | IfaceData { ifName :: IfaceTopBndr, -- Type constructor ifCType :: Maybe CType, -- C type for CAPI FFI ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifCtxt :: IfaceContext, -- The "stupid theta" ifCons :: IfaceConDecls, -- Includes new/data/data family info ifRec :: RecFlag, -- Recursive or not? ifPromotable :: Bool, -- Promotable to kind level? ifGadtSyntax :: Bool, -- True <=> declared using -- GADT syntax ifParent :: IfaceTyConParent -- The axiom, for a newtype, -- or data/newtype family instance } | IfaceSynonym { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifSynKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifSynRhs :: IfaceType } | IfaceFamily { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifResVar :: Maybe IfLclName, -- Result variable name, used -- only for pretty-printing -- with --show-iface ifFamKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifFamFlav :: IfaceFamTyConFlav, ifFamInj :: Injectivity } -- injectivity information | IfaceClass { ifCtxt :: IfaceContext, -- Superclasses ifName :: IfaceTopBndr, -- Name of the class TyCon ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifFDs :: [FunDep FastString], -- Functional dependencies ifATs :: [IfaceAT], -- Associated type families ifSigs :: [IfaceClassOp], -- Method signatures ifMinDef :: BooleanFormula IfLclName, -- Minimal complete definition ifRec :: RecFlag -- Is newtype/datatype associated -- with the class recursive? } | IfaceAxiom { ifName :: IfaceTopBndr, -- Axiom name ifTyCon :: IfaceTyCon, -- LHS TyCon ifRole :: Role, -- Role of axiom ifAxBranches :: [IfaceAxBranch] -- Branches } | IfacePatSyn { ifName :: IfaceTopBndr, -- Name of the pattern synonym ifPatIsInfix :: Bool, ifPatMatcher :: (IfExtName, Bool), ifPatBuilder :: Maybe (IfExtName, Bool), -- Everything below is redundant, -- but needed to implement pprIfaceDecl ifPatUnivTvs :: [IfaceTvBndr], ifPatExTvs :: [IfaceTvBndr], ifPatProvCtxt :: IfaceContext, ifPatReqCtxt :: IfaceContext, ifPatArgs :: [IfaceType], ifPatTy :: IfaceType } data IfaceTyConParent = IfNoParent | IfDataInstance IfExtName IfaceTyCon IfaceTcArgs data IfaceFamTyConFlav = IfaceOpenSynFamilyTyCon | IfaceClosedSynFamilyTyCon (Maybe (IfExtName, [IfaceAxBranch])) -- ^ Name of associated axiom and branches for pretty printing purposes, -- or 'Nothing' for an empty closed family without an axiom | IfaceAbstractClosedSynFamilyTyCon | IfaceBuiltInSynFamTyCon -- for pretty printing purposes only data IfaceClassOp = IfaceClassOp IfaceTopBndr DefMethSpec IfaceType -- Nothing => no default method -- Just False => ordinary polymorphic default method -- Just True => generic default method data IfaceAT = IfaceAT -- See Class.ClassATItem IfaceDecl -- The associated type declaration (Maybe IfaceType) -- Default associated type instance, if any -- This is just like CoAxBranch data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars :: [IfaceTvBndr] , ifaxbLHS :: IfaceTcArgs , ifaxbRoles :: [Role] , ifaxbRHS :: IfaceType , ifaxbIncomps :: [BranchIndex] } -- See Note [Storing compatibility] in CoAxiom data IfaceConDecls = IfAbstractTyCon Bool -- c.f TyCon.AbstractTyCon | IfDataFamTyCon -- Data family | IfDataTyCon [IfaceConDecl] -- Data type decls | IfNewTyCon IfaceConDecl -- Newtype decls data IfaceConDecl = IfCon { ifConOcc :: IfaceTopBndr, -- Constructor name ifConWrapper :: Bool, -- True <=> has a wrapper ifConInfix :: Bool, -- True <=> declared infix -- The universal type variables are precisely those -- of the type constructor of this data constructor -- This is *easy* to guarantee when creating the IfCon -- but it's not so easy for the original TyCon/DataCon -- So this guarantee holds for IfaceConDecl, but *not* for DataCon ifConExTvs :: [IfaceTvBndr], -- Existential tyvars ifConEqSpec :: IfaceEqSpec, -- Equality constraints ifConCtxt :: IfaceContext, -- Non-stupid context ifConArgTys :: [IfaceType], -- Arg types ifConFields :: [IfaceTopBndr], -- ...ditto... (field labels) ifConStricts :: [IfaceBang], -- Empty (meaning all lazy), -- or 1-1 corresp with arg tys -- See Note [Bangs on imported data constructors] in MkId ifConSrcStricts :: [IfaceSrcBang] } -- empty meaning no src stricts type IfaceEqSpec = [(IfLclName,IfaceType)] -- | This corresponds to an HsImplBang; that is, the final -- implementation decision about the data constructor arg data IfaceBang = IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion -- | This corresponds to HsSrcBang data IfaceSrcBang = IfSrcBang SrcUnpackedness SrcStrictness data IfaceClsInst = IfaceClsInst { ifInstCls :: IfExtName, -- See comments with ifInstTys :: [Maybe IfaceTyCon], -- the defn of ClsInst ifDFun :: IfExtName, -- The dfun ifOFlag :: OverlapFlag, -- Overlap flag ifInstOrph :: IsOrphan } -- See Note [Orphans] in InstEnv -- There's always a separate IfaceDecl for the DFun, which gives -- its IdInfo with its full type and version number. -- The instance declarations taken together have a version number, -- and we don't want that to wobble gratuitously -- If this instance decl is *used*, we'll record a usage on the dfun; -- and if the head does not change it won't be used if it wasn't before -- The ifFamInstTys field of IfaceFamInst contains a list of the rough -- match types data IfaceFamInst = IfaceFamInst { ifFamInstFam :: IfExtName -- Family name , ifFamInstTys :: [Maybe IfaceTyCon] -- See above , ifFamInstAxiom :: IfExtName -- The axiom , ifFamInstOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceRule = IfaceRule { ifRuleName :: RuleName, ifActivation :: Activation, ifRuleBndrs :: [IfaceBndr], -- Tyvars and term vars ifRuleHead :: IfExtName, -- Head of lhs ifRuleArgs :: [IfaceExpr], -- Args of LHS ifRuleRhs :: IfaceExpr, ifRuleAuto :: Bool, ifRuleOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceAnnotation = IfaceAnnotation { ifAnnotatedTarget :: IfaceAnnTarget, ifAnnotatedValue :: AnnPayload } type IfaceAnnTarget = AnnTarget OccName -- Here's a tricky case: -- * Compile with -O module A, and B which imports A.f -- * Change function f in A, and recompile without -O -- * When we read in old A.hi we read in its IdInfo (as a thunk) -- (In earlier GHCs we used to drop IdInfo immediately on reading, -- but we do not do that now. Instead it's discarded when the -- ModIface is read into the various decl pools.) -- * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *) -- and so gives a new version. data IfaceIdInfo = NoInfo -- When writing interface file without -O | HasInfo [IfaceInfoItem] -- Has info, and here it is data IfaceInfoItem = HsArity Arity | HsStrictness StrictSig | HsInline InlinePragma | HsUnfold Bool -- True <=> isStrongLoopBreaker is true IfaceUnfolding -- See Note [Expose recursive functions] | HsNoCafRefs -- NB: Specialisations and rules come in separately and are -- only later attached to the Id. Partial reason: some are orphans. data IfaceUnfolding = IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding -- Possibly could eliminate the Bool here, the information -- is also in the InlinePragma. | IfCompulsory IfaceExpr -- Only used for default methods, in fact | IfInlineRule Arity -- INLINE pragmas Bool -- OK to inline even if *un*-saturated Bool -- OK to inline even if context is boring IfaceExpr | IfDFunUnfold [IfaceBndr] [IfaceExpr] -- We only serialise the IdDetails of top-level Ids, and even then -- we only need a very limited selection. Notably, none of the -- implicit ones are needed here, because they are not put it -- interface files data IfaceIdDetails = IfVanillaId | IfRecSelId IfaceTyCon Bool | IfDFunId {- Note [Versioning of instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances] ************************************************************************ * * Functions over declarations * * ************************************************************************ -} visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl] visibleIfConDecls (IfAbstractTyCon {}) = [] visibleIfConDecls IfDataFamTyCon = [] visibleIfConDecls (IfDataTyCon cs) = cs visibleIfConDecls (IfNewTyCon c) = [c] ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName] -- *Excludes* the 'main' name, but *includes* the implicitly-bound names -- Deeply revolting, because it has to predict what gets bound, -- especially the question of whether there's a wrapper for a datacon -- See Note [Implicit TyThings] in HscTypes -- N.B. the set of names returned here *must* match the set of -- TyThings returned by HscTypes.implicitTyThings, in the sense that -- TyThing.getOccName should define a bijection between the two lists. -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop]) -- The order of the list does not matter. ifaceDeclImplicitBndrs IfaceData {ifCons = IfAbstractTyCon {}} = [] -- Newtype ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ, ifCons = IfNewTyCon ( IfCon { ifConOcc = con_occ })}) = -- implicit newtype coercion (mkNewTyCoOcc tc_occ) : -- JPM: newtype coercions shouldn't be implicit -- data constructor and worker (newtypes don't have a wrapper) [con_occ, mkDataConWorkerOcc con_occ] ifaceDeclImplicitBndrs (IfaceData {ifName = _tc_occ, ifCons = IfDataTyCon cons }) = -- for each data constructor in order, -- data constructor, worker, and (possibly) wrapper concatMap dc_occs cons where dc_occs con_decl | has_wrapper = [con_occ, work_occ, wrap_occ] | otherwise = [con_occ, work_occ] where con_occ = ifConOcc con_decl -- DataCon namespace wrap_occ = mkDataConWrapperOcc con_occ -- Id namespace work_occ = mkDataConWorkerOcc con_occ -- Id namespace has_wrapper = ifConWrapper con_decl -- This is the reason for -- having the ifConWrapper field! ifaceDeclImplicitBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_tc_occ, ifSigs = sigs, ifATs = ats }) = -- (possibly) newtype coercion co_occs ++ -- data constructor (DataCon namespace) -- data worker (Id namespace) -- no wrapper (class dictionaries never have a wrapper) [dc_occ, dcww_occ] ++ -- associated types [ifName at | IfaceAT at _ <- ats ] ++ -- superclass selectors [mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++ -- operation selectors [op | IfaceClassOp op _ _ <- sigs] where n_ctxt = length sc_ctxt n_sigs = length sigs co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ] | otherwise = [] dcww_occ = mkDataConWorkerOcc dc_occ dc_occ = mkClassDataConOcc cls_tc_occ is_newtype = n_sigs + n_ctxt == 1 -- Sigh ifaceDeclImplicitBndrs _ = [] -- ----------------------------------------------------------------------------- -- The fingerprints of an IfaceDecl -- We better give each name bound by the declaration a -- different fingerprint! So we calculate the fingerprint of -- each binder by combining the fingerprint of the whole -- declaration with the name of the binder. (#5614, #7215) ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)] ifaceDeclFingerprints hash decl = (ifName decl, hash) : [ (occ, computeFingerprint' (hash,occ)) | occ <- ifaceDeclImplicitBndrs decl ] where computeFingerprint' = unsafeDupablePerformIO . computeFingerprint (panic "ifaceDeclFingerprints") {- ************************************************************************ * * Expressions * * ************************************************************************ -} data IfaceExpr = IfaceLcl IfLclName | IfaceExt IfExtName | IfaceType IfaceType | IfaceCo IfaceCoercion | IfaceTuple TupleSort [IfaceExpr] -- Saturated; type arguments omitted | IfaceLam IfaceLamBndr IfaceExpr | IfaceApp IfaceExpr IfaceExpr | IfaceCase IfaceExpr IfLclName [IfaceAlt] | IfaceECase IfaceExpr IfaceType -- See Note [Empty case alternatives] | IfaceLet IfaceBinding IfaceExpr | IfaceCast IfaceExpr IfaceCoercion | IfaceLit Literal | IfaceFCall ForeignCall IfaceType | IfaceTick IfaceTickish IfaceExpr -- from Tick tickish E data IfaceTickish = IfaceHpcTick Module Int -- from HpcTick x | IfaceSCC CostCentre Bool Bool -- from ProfNote | IfaceSource RealSrcSpan String -- from SourceNote -- no breakpoints: we never export these into interface files type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr) -- Note: IfLclName, not IfaceBndr (and same with the case binder) -- We reconstruct the kind/type of the thing from the context -- thus saving bulk in interface files data IfaceConAlt = IfaceDefault | IfaceDataAlt IfExtName | IfaceLitAlt Literal data IfaceBinding = IfaceNonRec IfaceLetBndr IfaceExpr | IfaceRec [(IfaceLetBndr, IfaceExpr)] -- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too -- It's used for *non-top-level* let/rec binders -- See Note [IdInfo on nested let-bindings] data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo {- Note [Empty case alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In IfaceSyn an IfaceCase does not record the types of the alternatives, unlike CorSyn Case. But we need this type if the alternatives are empty. Hence IfaceECase. See Note [Empty case alternatives] in CoreSyn. Note [Expose recursive functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For supercompilation we want to put *all* unfoldings in the interface file, even for functions that are recursive (or big). So we need to know when an unfolding belongs to a loop-breaker so that we can refrain from inlining it (except during supercompilation). Note [IdInfo on nested let-bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Occasionally we want to preserve IdInfo on nested let bindings. The one that came up was a NOINLINE pragma on a let-binding inside an INLINE function. The user (Duncan Coutts) really wanted the NOINLINE control to cross the separate compilation boundary. In general we retain all info that is left by CoreTidy.tidyLetBndr, since that is what is seen by importing module with --make ************************************************************************ * * Printing IfaceDecl * * ************************************************************************ -} pprAxBranch :: SDoc -> IfaceAxBranch -> SDoc -- The TyCon might be local (just an OccName), or this might -- be a branch for an imported TyCon, so it would be an ExtName -- So it's easier to take an SDoc here pprAxBranch pp_tc (IfaceAxBranch { ifaxbTyVars = tvs , ifaxbLHS = pat_tys , ifaxbRHS = rhs , ifaxbIncomps = incomps }) = hang (pprUserIfaceForAll tvs) 2 (hang pp_lhs 2 (equals <+> ppr rhs)) $+$ nest 2 maybe_incomps where pp_lhs = hang pp_tc 2 (pprParendIfaceTcArgs pat_tys) maybe_incomps = ppUnless (null incomps) $ parens $ ptext (sLit "incompatible indices:") <+> ppr incomps instance Outputable IfaceAnnotation where ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value instance HasOccName IfaceClassOp where occName (IfaceClassOp n _ _) = n instance HasOccName IfaceConDecl where occName = ifConOcc instance HasOccName IfaceDecl where occName = ifName instance Outputable IfaceDecl where ppr = pprIfaceDecl showAll data ShowSub = ShowSub { ss_ppr_bndr :: OccName -> SDoc -- Pretty-printer for binders in IfaceDecl -- See Note [Printing IfaceDecl binders] , ss_how_much :: ShowHowMuch } data ShowHowMuch = ShowHeader -- Header information only, not rhs | ShowSome [OccName] -- [] <=> Print all sub-components -- (n:ns) <=> print sub-component 'n' with ShowSub=ns -- elide other sub-components to "..." -- May 14: the list is max 1 element long at the moment | ShowIface -- Everything including GHC-internal information (used in --show-iface) showAll :: ShowSub showAll = ShowSub { ss_how_much = ShowIface, ss_ppr_bndr = ppr } ppShowIface :: ShowSub -> SDoc -> SDoc ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc ppShowIface _ _ = Outputable.empty ppShowRhs :: ShowSub -> SDoc -> SDoc ppShowRhs (ShowSub { ss_how_much = ShowHeader }) _ = Outputable.empty ppShowRhs _ doc = doc showSub :: HasOccName n => ShowSub -> n -> Bool showSub (ShowSub { ss_how_much = ShowHeader }) _ = False showSub (ShowSub { ss_how_much = ShowSome (n:_) }) thing = n == occName thing showSub (ShowSub { ss_how_much = _ }) _ = True {- Note [Printing IfaceDecl binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The binders in an IfaceDecl are just OccNames, so we don't know what module they come from. But when we pretty-print a TyThing by converting to an IfaceDecl (see PprTyThing), the TyThing may come from some other module so we really need the module qualifier. We solve this by passing in a pretty-printer for the binders. When printing an interface file (--show-iface), we want to print everything unqualified, so we can just print the OccName directly. -} ppr_trim :: [Maybe SDoc] -> [SDoc] -- Collapse a group of Nothings to a single "..." ppr_trim xs = snd (foldr go (False, []) xs) where go (Just doc) (_, so_far) = (False, doc : so_far) go Nothing (True, so_far) = (True, so_far) go Nothing (False, so_far) = (True, ptext (sLit "...") : so_far) isIfaceDataInstance :: IfaceTyConParent -> Bool isIfaceDataInstance IfNoParent = False isIfaceDataInstance _ = True pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc -- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi -- See Note [Pretty-printing TyThings] in PprTyThing pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype, ifCtxt = context, ifTyVars = tc_tyvars, ifRoles = roles, ifCons = condecls, ifParent = parent, ifRec = isrec, ifGadtSyntax = gadt, ifPromotable = is_prom }) | gadt_style = vcat [ pp_roles , pp_nd <+> pp_lhs <+> pp_where , nest 2 (vcat pp_cons) , nest 2 $ ppShowIface ss pp_extra ] | otherwise = vcat [ pp_roles , hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons) , nest 2 $ ppShowIface ss pp_extra ] where is_data_instance = isIfaceDataInstance parent gadt_style = gadt || any (not . isVanillaIfaceConDecl) cons cons = visibleIfConDecls condecls pp_where = ppWhen (gadt_style && not (null cons)) $ ptext (sLit "where") pp_cons = ppr_trim (map show_con cons) :: [SDoc] pp_lhs = case parent of IfNoParent -> pprIfaceDeclHead context ss tycon tc_tyvars _ -> ptext (sLit "instance") <+> pprIfaceTyConParent parent pp_roles | is_data_instance = Outputable.empty | otherwise = pprRoles (== Representational) (pprPrefixIfDeclBndr ss tycon) tc_tyvars roles -- Don't display roles for data family instances (yet) -- See discussion on Trac #8672. add_bars [] = Outputable.empty add_bars (c:cs) = sep ((equals <+> c) : map (char '|' <+>) cs) ok_con dc = showSub ss dc || any (showSub ss) (ifConFields dc) show_con dc | ok_con dc = Just $ pprIfaceConDecl ss gadt_style mk_user_con_res_ty dc | otherwise = Nothing mk_user_con_res_ty :: IfaceEqSpec -> ([IfaceTvBndr], SDoc) -- See Note [Result type of a data family GADT] mk_user_con_res_ty eq_spec | IfDataInstance _ tc tys <- parent = (con_univ_tvs, pprIfaceType (IfaceTyConApp tc (substIfaceTcArgs gadt_subst tys))) | otherwise = (con_univ_tvs, sdocWithDynFlags (ppr_tc_app gadt_subst)) where gadt_subst = mkFsEnv eq_spec done_univ_tv (tv,_) = isJust (lookupFsEnv gadt_subst tv) con_univ_tvs = filterOut done_univ_tv tc_tyvars ppr_tc_app gadt_subst dflags = pprPrefixIfDeclBndr ss tycon <+> sep [ pprParendIfaceType (substIfaceTyVar gadt_subst tv) | (tv,_kind) <- stripIfaceKindVars dflags tc_tyvars ] pp_nd = case condecls of IfAbstractTyCon d -> ptext (sLit "abstract") <> ppShowIface ss (parens (ppr d)) IfDataFamTyCon -> ptext (sLit "data family") IfDataTyCon _ -> ptext (sLit "data") IfNewTyCon _ -> ptext (sLit "newtype") pp_extra = vcat [pprCType ctype, pprRec isrec, pp_prom] pp_prom | is_prom = ptext (sLit "Promotable") | otherwise = Outputable.empty pprIfaceDecl ss (IfaceClass { ifATs = ats, ifSigs = sigs, ifRec = isrec , ifCtxt = context, ifName = clas , ifTyVars = tyvars, ifRoles = roles , ifFDs = fds }) = vcat [ pprRoles (== Nominal) (pprPrefixIfDeclBndr ss clas) tyvars roles , ptext (sLit "class") <+> pprIfaceDeclHead context ss clas tyvars <+> pprFundeps fds <+> pp_where , nest 2 (vcat [vcat asocs, vcat dsigs, pprec])] where pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (ptext (sLit "where")) asocs = ppr_trim $ map maybeShowAssoc ats dsigs = ppr_trim $ map maybeShowSig sigs pprec = ppShowIface ss (pprRec isrec) maybeShowAssoc :: IfaceAT -> Maybe SDoc maybeShowAssoc asc@(IfaceAT d _) | showSub ss d = Just $ pprIfaceAT ss asc | otherwise = Nothing maybeShowSig :: IfaceClassOp -> Maybe SDoc maybeShowSig sg | showSub ss sg = Just $ pprIfaceClassOp ss sg | otherwise = Nothing pprIfaceDecl ss (IfaceSynonym { ifName = tc , ifTyVars = tv , ifSynRhs = mono_ty }) = hang (ptext (sLit "type") <+> pprIfaceDeclHead [] ss tc tv <+> equals) 2 (sep [pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau]) where (tvs, theta, tau) = splitIfaceSigmaTy mono_ty pprIfaceDecl ss (IfaceFamily { ifName = tycon, ifTyVars = tyvars , ifFamFlav = rhs, ifFamKind = kind , ifResVar = res_var, ifFamInj = inj }) = vcat [ hang (text "type family" <+> pprIfaceDeclHead [] ss tycon tyvars) 2 (pp_inj res_var inj <+> ppShowRhs ss (pp_rhs rhs)) , ppShowRhs ss (nest 2 (pp_branches rhs)) ] where pp_inj Nothing _ = dcolon <+> ppr kind pp_inj (Just res) inj | Injective injectivity <- inj = hsep [ equals, ppr res, dcolon, ppr kind , pp_inj_cond res injectivity] | otherwise = hsep [ equals, ppr res, dcolon, ppr kind ] pp_inj_cond res inj = case filterByList inj tyvars of [] -> empty tvs -> hsep [text "|", ppr res, text "->", interppSP (map fst tvs)] pp_rhs IfaceOpenSynFamilyTyCon = ppShowIface ss (ptext (sLit "open")) pp_rhs IfaceAbstractClosedSynFamilyTyCon = ppShowIface ss (ptext (sLit "closed, abstract")) pp_rhs (IfaceClosedSynFamilyTyCon _) = ptext (sLit "where") pp_rhs IfaceBuiltInSynFamTyCon = ppShowIface ss (ptext (sLit "built-in")) pp_branches (IfaceClosedSynFamilyTyCon (Just (ax, brs))) = vcat (map (pprAxBranch (pprPrefixIfDeclBndr ss tycon)) brs) $$ ppShowIface ss (ptext (sLit "axiom") <+> ppr ax) pp_branches _ = Outputable.empty pprIfaceDecl _ (IfacePatSyn { ifName = name, ifPatBuilder = builder, ifPatUnivTvs = univ_tvs, ifPatExTvs = ex_tvs, ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt, ifPatArgs = arg_tys, ifPatTy = pat_ty} ) = pprPatSynSig name is_bidirectional (pprUserIfaceForAll tvs) (pprIfaceContextMaybe prov_ctxt) (pprIfaceContextMaybe req_ctxt) (pprIfaceType ty) where is_bidirectional = isJust builder tvs = univ_tvs ++ ex_tvs ty = foldr IfaceFunTy pat_ty arg_tys pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty, ifIdDetails = details, ifIdInfo = info }) = vcat [ hang (pprPrefixIfDeclBndr ss var <+> dcolon) 2 (pprIfaceSigmaType ty) , ppShowIface ss (ppr details) , ppShowIface ss (ppr info) ] pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon , ifAxBranches = branches }) = hang (ptext (sLit "axiom") <+> ppr name <> dcolon) 2 (vcat $ map (pprAxBranch (ppr tycon)) branches) pprCType :: Maybe CType -> SDoc pprCType Nothing = Outputable.empty pprCType (Just cType) = ptext (sLit "C type:") <+> ppr cType -- if, for each role, suppress_if role is True, then suppress the role -- output pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTvBndr] -> [Role] -> SDoc pprRoles suppress_if tyCon tyvars roles = sdocWithDynFlags $ \dflags -> let froles = suppressIfaceKinds dflags tyvars roles in ppUnless (all suppress_if roles || null froles) $ ptext (sLit "type role") <+> tyCon <+> hsep (map ppr froles) pprRec :: RecFlag -> SDoc pprRec NonRecursive = Outputable.empty pprRec Recursive = ptext (sLit "RecFlag: Recursive") pprInfixIfDeclBndr, pprPrefixIfDeclBndr :: ShowSub -> OccName -> SDoc pprInfixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = pprInfixVar (isSymOcc occ) (ppr_bndr occ) pprPrefixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = parenSymOcc occ (ppr_bndr occ) instance Outputable IfaceClassOp where ppr = pprIfaceClassOp showAll pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc pprIfaceClassOp ss (IfaceClassOp n dm ty) = hang opHdr 2 (pprIfaceSigmaType ty) where opHdr = pprPrefixIfDeclBndr ss n <+> ppShowIface ss (ppr dm) <+> dcolon instance Outputable IfaceAT where ppr = pprIfaceAT showAll pprIfaceAT :: ShowSub -> IfaceAT -> SDoc pprIfaceAT ss (IfaceAT d mb_def) = vcat [ pprIfaceDecl ss d , case mb_def of Nothing -> Outputable.empty Just rhs -> nest 2 $ ptext (sLit "Default:") <+> ppr rhs ] instance Outputable IfaceTyConParent where ppr p = pprIfaceTyConParent p pprIfaceTyConParent :: IfaceTyConParent -> SDoc pprIfaceTyConParent IfNoParent = Outputable.empty pprIfaceTyConParent (IfDataInstance _ tc tys) = sdocWithDynFlags $ \dflags -> let ftys = stripKindArgs dflags tys in pprIfaceTypeApp tc ftys pprIfaceDeclHead :: IfaceContext -> ShowSub -> OccName -> [IfaceTvBndr] -> SDoc pprIfaceDeclHead context ss tc_occ tv_bndrs = sdocWithDynFlags $ \ dflags -> sep [ pprIfaceContextArr context , pprPrefixIfDeclBndr ss tc_occ <+> pprIfaceTvBndrs (stripIfaceKindVars dflags tv_bndrs) ] isVanillaIfaceConDecl :: IfaceConDecl -> Bool isVanillaIfaceConDecl (IfCon { ifConExTvs = ex_tvs , ifConEqSpec = eq_spec , ifConCtxt = ctxt }) = (null ex_tvs) && (null eq_spec) && (null ctxt) pprIfaceConDecl :: ShowSub -> Bool -> (IfaceEqSpec -> ([IfaceTvBndr], SDoc)) -> IfaceConDecl -> SDoc pprIfaceConDecl ss gadt_style mk_user_con_res_ty (IfCon { ifConOcc = name, ifConInfix = is_infix, ifConExTvs = ex_tvs, ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys, ifConStricts = stricts, ifConFields = labels }) | gadt_style = pp_prefix_con <+> dcolon <+> ppr_ty | otherwise = ppr_fields tys_w_strs where tys_w_strs :: [(IfaceBang, IfaceType)] tys_w_strs = zip stricts arg_tys pp_prefix_con = pprPrefixIfDeclBndr ss name (univ_tvs, pp_res_ty) = mk_user_con_res_ty eq_spec ppr_ty = pprIfaceForAllPart (univ_tvs ++ ex_tvs) ctxt pp_tau -- A bit gruesome this, but we can't form the full con_tau, and ppr it, -- because we don't have a Name for the tycon, only an OccName pp_tau = case map pprParendIfaceType arg_tys ++ [pp_res_ty] of (t:ts) -> fsep (t : map (arrow <+>) ts) [] -> panic "pp_con_taus" ppr_bang IfNoBang = ppWhen opt_PprStyle_Debug $ char '_' ppr_bang IfStrict = char '!' ppr_bang IfUnpack = ptext (sLit "{-# UNPACK #-}") ppr_bang (IfUnpackCo co) = ptext (sLit "! {-# UNPACK #-}") <> pprParendIfaceCoercion co pprParendBangTy (bang, ty) = ppr_bang bang <> pprParendIfaceType ty pprBangTy (bang, ty) = ppr_bang bang <> ppr ty maybe_show_label (lbl,bty) | showSub ss lbl = Just (pprPrefixIfDeclBndr ss lbl <+> dcolon <+> pprBangTy bty) | otherwise = Nothing ppr_fields [ty1, ty2] | is_infix && null labels = sep [pprParendBangTy ty1, pprInfixIfDeclBndr ss name, pprParendBangTy ty2] ppr_fields fields | null labels = pp_prefix_con <+> sep (map pprParendBangTy fields) | otherwise = pp_prefix_con <+> (braces $ sep $ punctuate comma $ ppr_trim $ map maybe_show_label (zip labels fields)) instance Outputable IfaceRule where ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs, ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs }) = sep [hsep [pprRuleName name, ppr act, ptext (sLit "forall") <+> pprIfaceBndrs bndrs], nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args), ptext (sLit "=") <+> ppr rhs]) ] instance Outputable IfaceClsInst where ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag , ifInstCls = cls, ifInstTys = mb_tcs}) = hang (ptext (sLit "instance") <+> ppr flag <+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs)) 2 (equals <+> ppr dfun_id) instance Outputable IfaceFamInst where ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs , ifFamInstAxiom = tycon_ax}) = hang (ptext (sLit "family instance") <+> ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs) 2 (equals <+> ppr tycon_ax) ppr_rough :: Maybe IfaceTyCon -> SDoc ppr_rough Nothing = dot ppr_rough (Just tc) = ppr tc {- Note [Result type of a data family GADT] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family T a data instance T (p,q) where T1 :: T (Int, Maybe c) T2 :: T (Bool, q) The IfaceDecl actually looks like data TPr p q where T1 :: forall p q. forall c. (p~Int,q~Maybe c) => TPr p q T2 :: forall p q. (p~Bool) => TPr p q To reconstruct the result types for T1 and T2 that we want to pretty print, we substitute the eq-spec [p->Int, q->Maybe c] in the arg pattern (p,q) to give T (Int, Maybe c) Remember that in IfaceSyn, the TyCon and DataCon share the same universal type variables. ----------------------------- Printing IfaceExpr ------------------------------------ -} instance Outputable IfaceExpr where ppr e = pprIfaceExpr noParens e noParens :: SDoc -> SDoc noParens pp = pp pprParendIfaceExpr :: IfaceExpr -> SDoc pprParendIfaceExpr = pprIfaceExpr parens -- | Pretty Print an IfaceExpre -- -- The first argument should be a function that adds parens in context that need -- an atomic value (e.g. function args) pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc pprIfaceExpr _ (IfaceLcl v) = ppr v pprIfaceExpr _ (IfaceExt v) = ppr v pprIfaceExpr _ (IfaceLit l) = ppr l pprIfaceExpr _ (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty) pprIfaceExpr _ (IfaceType ty) = char '@' <+> pprParendIfaceType ty pprIfaceExpr _ (IfaceCo co) = text "@~" <+> pprParendIfaceCoercion co pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app []) pprIfaceExpr _ (IfaceTuple c as) = tupleParens c (pprWithCommas ppr as) pprIfaceExpr add_par i@(IfaceLam _ _) = add_par (sep [char '\\' <+> sep (map pprIfaceLamBndr bndrs) <+> arrow, pprIfaceExpr noParens body]) where (bndrs,body) = collect [] i collect bs (IfaceLam b e) = collect (b:bs) e collect bs e = (reverse bs, e) pprIfaceExpr add_par (IfaceECase scrut ty) = add_par (sep [ ptext (sLit "case") <+> pprIfaceExpr noParens scrut , ptext (sLit "ret_ty") <+> pprParendIfaceType ty , ptext (sLit "of {}") ]) pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)]) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow, pprIfaceExpr noParens rhs <+> char '}']) pprIfaceExpr add_par (IfaceCase scrut bndr alts) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{', nest 2 (sep (map ppr_alt alts)) <+> char '}']) pprIfaceExpr _ (IfaceCast expr co) = sep [pprParendIfaceExpr expr, nest 2 (ptext (sLit "`cast`")), pprParendIfaceCoercion co] pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body) = add_par (sep [ptext (sLit "let {"), nest 2 (ppr_bind (b, rhs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body) = add_par (sep [ptext (sLit "letrec {"), nest 2 (sep (map ppr_bind pairs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceTick tickish e) = add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e) ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs, arrow <+> pprIfaceExpr noParens rhs] ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc ppr_con_bs con bs = ppr con <+> hsep (map ppr bs) ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc ppr_bind (IfLetBndr b ty info, rhs) = sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr info), equals <+> pprIfaceExpr noParens rhs] ------------------ pprIfaceTickish :: IfaceTickish -> SDoc pprIfaceTickish (IfaceHpcTick m ix) = braces (text "tick" <+> ppr m <+> ppr ix) pprIfaceTickish (IfaceSCC cc tick scope) = braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope) pprIfaceTickish (IfaceSource src _names) = braces (pprUserRealSpan True src) ------------------ pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $ nest 2 (pprParendIfaceExpr arg) : args pprIfaceApp fun args = sep (pprParendIfaceExpr fun : args) ------------------ instance Outputable IfaceConAlt where ppr IfaceDefault = text "DEFAULT" ppr (IfaceLitAlt l) = ppr l ppr (IfaceDataAlt d) = ppr d ------------------ instance Outputable IfaceIdDetails where ppr IfVanillaId = Outputable.empty ppr (IfRecSelId tc b) = ptext (sLit "RecSel") <+> ppr tc <+> if b then ptext (sLit "<naughty>") else Outputable.empty ppr IfDFunId = ptext (sLit "DFunId") instance Outputable IfaceIdInfo where ppr NoInfo = Outputable.empty ppr (HasInfo is) = ptext (sLit "{-") <+> pprWithCommas ppr is <+> ptext (sLit "-}") instance Outputable IfaceInfoItem where ppr (HsUnfold lb unf) = ptext (sLit "Unfolding") <> ppWhen lb (ptext (sLit "(loop-breaker)")) <> colon <+> ppr unf ppr (HsInline prag) = ptext (sLit "Inline:") <+> ppr prag ppr (HsArity arity) = ptext (sLit "Arity:") <+> int arity ppr (HsStrictness str) = ptext (sLit "Strictness:") <+> pprIfaceStrictSig str ppr HsNoCafRefs = ptext (sLit "HasNoCafRefs") instance Outputable IfaceUnfolding where ppr (IfCompulsory e) = ptext (sLit "<compulsory>") <+> parens (ppr e) ppr (IfCoreUnfold s e) = (if s then ptext (sLit "<stable>") else Outputable.empty) <+> parens (ppr e) ppr (IfInlineRule a uok bok e) = sep [ptext (sLit "InlineRule") <+> ppr (a,uok,bok), pprParendIfaceExpr e] ppr (IfDFunUnfold bs es) = hang (ptext (sLit "DFun:") <+> sep (map ppr bs) <> dot) 2 (sep (map pprParendIfaceExpr es)) {- ************************************************************************ * * Finding the Names in IfaceSyn * * ************************************************************************ This is used for dependency analysis in MkIface, so that we fingerprint a declaration before the things that depend on it. It is specific to interface-file fingerprinting in the sense that we don't collect *all* Names: for example, the DFun of an instance is recorded textually rather than by its fingerprint when fingerprinting the instance, so DFuns are not dependencies. -} freeNamesIfDecl :: IfaceDecl -> NameSet freeNamesIfDecl (IfaceId _s t d i) = freeNamesIfType t &&& freeNamesIfIdInfo i &&& freeNamesIfIdDetails d freeNamesIfDecl d@IfaceData{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfaceTyConParent (ifParent d) &&& freeNamesIfContext (ifCtxt d) &&& freeNamesIfConDecls (ifCons d) freeNamesIfDecl d@IfaceSynonym{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfType (ifSynRhs d) &&& freeNamesIfKind (ifSynKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceFamily{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfFamFlav (ifFamFlav d) &&& freeNamesIfKind (ifFamKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceClass{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfContext (ifCtxt d) &&& fnList freeNamesIfAT (ifATs d) &&& fnList freeNamesIfClsSig (ifSigs d) freeNamesIfDecl d@IfaceAxiom{} = freeNamesIfTc (ifTyCon d) &&& fnList freeNamesIfAxBranch (ifAxBranches d) freeNamesIfDecl d@IfacePatSyn{} = unitNameSet (fst (ifPatMatcher d)) &&& maybe emptyNameSet (unitNameSet . fst) (ifPatBuilder d) &&& freeNamesIfTvBndrs (ifPatUnivTvs d) &&& freeNamesIfTvBndrs (ifPatExTvs d) &&& freeNamesIfContext (ifPatProvCtxt d) &&& freeNamesIfContext (ifPatReqCtxt d) &&& fnList freeNamesIfType (ifPatArgs d) &&& freeNamesIfType (ifPatTy d) freeNamesIfAxBranch :: IfaceAxBranch -> NameSet freeNamesIfAxBranch (IfaceAxBranch { ifaxbTyVars = tyvars , ifaxbLHS = lhs , ifaxbRHS = rhs }) = freeNamesIfTvBndrs tyvars &&& freeNamesIfTcArgs lhs &&& freeNamesIfType rhs freeNamesIfIdDetails :: IfaceIdDetails -> NameSet freeNamesIfIdDetails (IfRecSelId tc _) = freeNamesIfTc tc freeNamesIfIdDetails _ = emptyNameSet -- All other changes are handled via the version info on the tycon freeNamesIfFamFlav :: IfaceFamTyConFlav -> NameSet freeNamesIfFamFlav IfaceOpenSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon (Just (ax, br))) = unitNameSet ax &&& fnList freeNamesIfAxBranch br freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon Nothing) = emptyNameSet freeNamesIfFamFlav IfaceAbstractClosedSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav IfaceBuiltInSynFamTyCon = emptyNameSet freeNamesIfContext :: IfaceContext -> NameSet freeNamesIfContext = fnList freeNamesIfType freeNamesIfAT :: IfaceAT -> NameSet freeNamesIfAT (IfaceAT decl mb_def) = freeNamesIfDecl decl &&& case mb_def of Nothing -> emptyNameSet Just rhs -> freeNamesIfType rhs freeNamesIfClsSig :: IfaceClassOp -> NameSet freeNamesIfClsSig (IfaceClassOp _n _dm ty) = freeNamesIfType ty freeNamesIfConDecls :: IfaceConDecls -> NameSet freeNamesIfConDecls (IfDataTyCon c) = fnList freeNamesIfConDecl c freeNamesIfConDecls (IfNewTyCon c) = freeNamesIfConDecl c freeNamesIfConDecls _ = emptyNameSet freeNamesIfConDecl :: IfaceConDecl -> NameSet freeNamesIfConDecl c = freeNamesIfTvBndrs (ifConExTvs c) &&& freeNamesIfContext (ifConCtxt c) &&& fnList freeNamesIfType (ifConArgTys c) &&& fnList freeNamesIfType (map snd (ifConEqSpec c)) -- equality constraints freeNamesIfKind :: IfaceType -> NameSet freeNamesIfKind = freeNamesIfType freeNamesIfTcArgs :: IfaceTcArgs -> NameSet freeNamesIfTcArgs (ITC_Type t ts) = freeNamesIfType t &&& freeNamesIfTcArgs ts freeNamesIfTcArgs (ITC_Kind k ks) = freeNamesIfKind k &&& freeNamesIfTcArgs ks freeNamesIfTcArgs ITC_Nil = emptyNameSet freeNamesIfType :: IfaceType -> NameSet freeNamesIfType (IfaceTyVar _) = emptyNameSet freeNamesIfType (IfaceAppTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceTyConApp tc ts) = freeNamesIfTc tc &&& freeNamesIfTcArgs ts freeNamesIfType (IfaceTupleTy _ _ ts) = freeNamesIfTcArgs ts freeNamesIfType (IfaceLitTy _) = emptyNameSet freeNamesIfType (IfaceForAllTy tv t) = freeNamesIfTvBndr tv &&& freeNamesIfType t freeNamesIfType (IfaceFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceDFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfCoercion :: IfaceCoercion -> NameSet freeNamesIfCoercion (IfaceReflCo _ t) = freeNamesIfType t freeNamesIfCoercion (IfaceFunCo _ c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceTyConAppCo _ tc cos) = freeNamesIfTc tc &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceAppCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceForAllCo tv co) = freeNamesIfTvBndr tv &&& freeNamesIfCoercion co freeNamesIfCoercion (IfaceCoVarCo _) = emptyNameSet freeNamesIfCoercion (IfaceAxiomInstCo ax _ cos) = unitNameSet ax &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceUnivCo _ _ t1 t2) = freeNamesIfType t1 &&& freeNamesIfType t2 freeNamesIfCoercion (IfaceSymCo c) = freeNamesIfCoercion c freeNamesIfCoercion (IfaceTransCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceNthCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceLRCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceInstCo co ty) = freeNamesIfCoercion co &&& freeNamesIfType ty freeNamesIfCoercion (IfaceSubCo co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceAxiomRuleCo _ax tys cos) -- the axiom is just a string, so we don't count it as a name. = fnList freeNamesIfType tys &&& fnList freeNamesIfCoercion cos freeNamesIfTvBndrs :: [IfaceTvBndr] -> NameSet freeNamesIfTvBndrs = fnList freeNamesIfTvBndr freeNamesIfBndr :: IfaceBndr -> NameSet freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b freeNamesIfLetBndr :: IfaceLetBndr -> NameSet -- Remember IfaceLetBndr is used only for *nested* bindings -- The IdInfo can contain an unfolding (in the case of -- local INLINE pragmas), so look there too freeNamesIfLetBndr (IfLetBndr _name ty info) = freeNamesIfType ty &&& freeNamesIfIdInfo info freeNamesIfTvBndr :: IfaceTvBndr -> NameSet freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k -- kinds can have Names inside, because of promotion freeNamesIfIdBndr :: IfaceIdBndr -> NameSet freeNamesIfIdBndr = freeNamesIfTvBndr freeNamesIfIdInfo :: IfaceIdInfo -> NameSet freeNamesIfIdInfo NoInfo = emptyNameSet freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i freeNamesItem :: IfaceInfoItem -> NameSet freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u freeNamesItem _ = emptyNameSet freeNamesIfUnfold :: IfaceUnfolding -> NameSet freeNamesIfUnfold (IfCoreUnfold _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfCompulsory e) = freeNamesIfExpr e freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfDFunUnfold bs es) = fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es freeNamesIfExpr :: IfaceExpr -> NameSet freeNamesIfExpr (IfaceExt v) = unitNameSet v freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty freeNamesIfExpr (IfaceType ty) = freeNamesIfType ty freeNamesIfExpr (IfaceCo co) = freeNamesIfCoercion co freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as freeNamesIfExpr (IfaceLam (b,_) body) = freeNamesIfBndr b &&& freeNamesIfExpr body freeNamesIfExpr (IfaceApp f a) = freeNamesIfExpr f &&& freeNamesIfExpr a freeNamesIfExpr (IfaceCast e co) = freeNamesIfExpr e &&& freeNamesIfCoercion co freeNamesIfExpr (IfaceTick _ e) = freeNamesIfExpr e freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty freeNamesIfExpr (IfaceCase s _ alts) = freeNamesIfExpr s &&& fnList fn_alt alts &&& fn_cons alts where fn_alt (_con,_bs,r) = freeNamesIfExpr r -- Depend on the data constructors. Just one will do! -- Note [Tracking data constructors] fn_cons [] = emptyNameSet fn_cons ((IfaceDefault ,_,_) : xs) = fn_cons xs fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con fn_cons (_ : _ ) = emptyNameSet freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body freeNamesIfExpr (IfaceLet (IfaceRec as) x) = fnList fn_pair as &&& freeNamesIfExpr x where fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs freeNamesIfExpr _ = emptyNameSet freeNamesIfTc :: IfaceTyCon -> NameSet freeNamesIfTc tc = unitNameSet (ifaceTyConName tc) -- ToDo: shouldn't we include IfaceIntTc & co.? freeNamesIfRule :: IfaceRule -> NameSet freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f , ifRuleArgs = es, ifRuleRhs = rhs }) = unitNameSet f &&& fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es &&& freeNamesIfExpr rhs freeNamesIfFamInst :: IfaceFamInst -> NameSet freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName , ifFamInstAxiom = axName }) = unitNameSet famName &&& unitNameSet axName freeNamesIfaceTyConParent :: IfaceTyConParent -> NameSet freeNamesIfaceTyConParent IfNoParent = emptyNameSet freeNamesIfaceTyConParent (IfDataInstance ax tc tys) = unitNameSet ax &&& freeNamesIfTc tc &&& freeNamesIfTcArgs tys -- helpers (&&&) :: NameSet -> NameSet -> NameSet (&&&) = unionNameSet fnList :: (a -> NameSet) -> [a] -> NameSet fnList f = foldr (&&&) emptyNameSet . map f {- Note [Tracking data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a case expression case e of { C a -> ...; ... } You might think that we don't need to include the datacon C in the free names, because its type will probably show up in the free names of 'e'. But in rare circumstances this may not happen. Here's the one that bit me: module DynFlags where import {-# SOURCE #-} Packages( PackageState ) data DynFlags = DF ... PackageState ... module Packages where import DynFlags data PackageState = PS ... lookupModule (df :: DynFlags) = case df of DF ...p... -> case p of PS ... -> ... Now, lookupModule depends on DynFlags, but the transitive dependency on the *locally-defined* type PackageState is not visible. We need to take account of the use of the data constructor PS in the pattern match. ************************************************************************ * * Binary instances * * ************************************************************************ -} instance Binary IfaceDecl where put_ bh (IfaceId name ty details idinfo) = do putByte bh 0 put_ bh (occNameFS name) put_ bh ty put_ bh details put_ bh idinfo put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 2 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 put_ bh (IfaceSynonym a1 a2 a3 a4 a5) = do putByte bh 3 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh (IfaceFamily a1 a2 a3 a4 a5 a6) = do putByte bh 4 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh (IfaceClass a1 a2 a3 a4 a5 a6 a7 a8 a9) = do putByte bh 5 put_ bh a1 put_ bh (occNameFS a2) put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh (IfaceAxiom a1 a2 a3 a4) = do putByte bh 6 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh (IfacePatSyn name a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 7 put_ bh (occNameFS name) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 get bh = do h <- getByte bh case h of 0 -> do name <- get bh ty <- get bh details <- get bh idinfo <- get bh occ <- return $! mkVarOccFS name return (IfaceId occ ty details idinfo) 1 -> error "Binary.get(TyClDecl): ForeignType" 2 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceData occ a2 a3 a4 a5 a6 a7 a8 a9 a10) 3 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceSynonym occ a2 a3 a4 a5) 4 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceFamily occ a2 a3 a4 a5 a6) 5 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh occ <- return $! mkClsOccFS a2 return (IfaceClass a1 occ a3 a4 a5 a6 a7 a8 a9) 6 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceAxiom occ a2 a3 a4) 7 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkDataOccFS a1 return (IfacePatSyn occ a2 a3 a4 a5 a6 a7 a8 a9 a10) _ -> panic (unwords ["Unknown IfaceDecl tag:", show h]) instance Binary IfaceFamTyConFlav where put_ bh IfaceOpenSynFamilyTyCon = putByte bh 0 put_ bh (IfaceClosedSynFamilyTyCon mb) = putByte bh 1 >> put_ bh mb put_ bh IfaceAbstractClosedSynFamilyTyCon = putByte bh 2 put_ _ IfaceBuiltInSynFamTyCon = pprPanic "Cannot serialize IfaceBuiltInSynFamTyCon, used for pretty-printing only" Outputable.empty get bh = do { h <- getByte bh ; case h of 0 -> return IfaceOpenSynFamilyTyCon 1 -> do { mb <- get bh ; return (IfaceClosedSynFamilyTyCon mb) } _ -> return IfaceAbstractClosedSynFamilyTyCon } instance Binary IfaceClassOp where put_ bh (IfaceClassOp n def ty) = do put_ bh (occNameFS n) put_ bh def put_ bh ty get bh = do n <- get bh def <- get bh ty <- get bh occ <- return $! mkVarOccFS n return (IfaceClassOp occ def ty) instance Binary IfaceAT where put_ bh (IfaceAT dec defs) = do put_ bh dec put_ bh defs get bh = do dec <- get bh defs <- get bh return (IfaceAT dec defs) instance Binary IfaceAxBranch where put_ bh (IfaceAxBranch a1 a2 a3 a4 a5) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh return (IfaceAxBranch a1 a2 a3 a4 a5) instance Binary IfaceConDecls where put_ bh (IfAbstractTyCon d) = putByte bh 0 >> put_ bh d put_ bh IfDataFamTyCon = putByte bh 1 put_ bh (IfDataTyCon cs) = putByte bh 2 >> put_ bh cs put_ bh (IfNewTyCon c) = putByte bh 3 >> put_ bh c get bh = do h <- getByte bh case h of 0 -> liftM IfAbstractTyCon $ get bh 1 -> return IfDataFamTyCon 2 -> liftM IfDataTyCon $ get bh _ -> liftM IfNewTyCon $ get bh instance Binary IfaceConDecl where put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) instance Binary IfaceBang where put_ bh IfNoBang = putByte bh 0 put_ bh IfStrict = putByte bh 1 put_ bh IfUnpack = putByte bh 2 put_ bh (IfUnpackCo co) = putByte bh 3 >> put_ bh co get bh = do h <- getByte bh case h of 0 -> do return IfNoBang 1 -> do return IfStrict 2 -> do return IfUnpack _ -> do { a <- get bh; return (IfUnpackCo a) } instance Binary IfaceSrcBang where put_ bh (IfSrcBang a1 a2) = do put_ bh a1 put_ bh a2 get bh = do a1 <- get bh a2 <- get bh return (IfSrcBang a1 a2) instance Binary IfaceClsInst where put_ bh (IfaceClsInst cls tys dfun flag orph) = do put_ bh cls put_ bh tys put_ bh dfun put_ bh flag put_ bh orph get bh = do cls <- get bh tys <- get bh dfun <- get bh flag <- get bh orph <- get bh return (IfaceClsInst cls tys dfun flag orph) instance Binary IfaceFamInst where put_ bh (IfaceFamInst fam tys name orph) = do put_ bh fam put_ bh tys put_ bh name put_ bh orph get bh = do fam <- get bh tys <- get bh name <- get bh orph <- get bh return (IfaceFamInst fam tys name orph) instance Binary IfaceRule where put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh return (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) instance Binary IfaceAnnotation where put_ bh (IfaceAnnotation a1 a2) = do put_ bh a1 put_ bh a2 get bh = do a1 <- get bh a2 <- get bh return (IfaceAnnotation a1 a2) instance Binary IfaceIdDetails where put_ bh IfVanillaId = putByte bh 0 put_ bh (IfRecSelId a b) = putByte bh 1 >> put_ bh a >> put_ bh b put_ bh IfDFunId = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> return IfVanillaId 1 -> do { a <- get bh; b <- get bh; return (IfRecSelId a b) } _ -> return IfDFunId instance Binary IfaceIdInfo where put_ bh NoInfo = putByte bh 0 put_ bh (HasInfo i) = putByte bh 1 >> lazyPut bh i -- NB lazyPut get bh = do h <- getByte bh case h of 0 -> return NoInfo _ -> liftM HasInfo $ lazyGet bh -- NB lazyGet instance Binary IfaceInfoItem where put_ bh (HsArity aa) = putByte bh 0 >> put_ bh aa put_ bh (HsStrictness ab) = putByte bh 1 >> put_ bh ab put_ bh (HsUnfold lb ad) = putByte bh 2 >> put_ bh lb >> put_ bh ad put_ bh (HsInline ad) = putByte bh 3 >> put_ bh ad put_ bh HsNoCafRefs = putByte bh 4 get bh = do h <- getByte bh case h of 0 -> liftM HsArity $ get bh 1 -> liftM HsStrictness $ get bh 2 -> do lb <- get bh ad <- get bh return (HsUnfold lb ad) 3 -> liftM HsInline $ get bh _ -> return HsNoCafRefs instance Binary IfaceUnfolding where put_ bh (IfCoreUnfold s e) = do putByte bh 0 put_ bh s put_ bh e put_ bh (IfInlineRule a b c d) = do putByte bh 1 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfDFunUnfold as bs) = do putByte bh 2 put_ bh as put_ bh bs put_ bh (IfCompulsory e) = do putByte bh 3 put_ bh e get bh = do h <- getByte bh case h of 0 -> do s <- get bh e <- get bh return (IfCoreUnfold s e) 1 -> do a <- get bh b <- get bh c <- get bh d <- get bh return (IfInlineRule a b c d) 2 -> do as <- get bh bs <- get bh return (IfDFunUnfold as bs) _ -> do e <- get bh return (IfCompulsory e) instance Binary IfaceExpr where put_ bh (IfaceLcl aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceType ab) = do putByte bh 1 put_ bh ab put_ bh (IfaceCo ab) = do putByte bh 2 put_ bh ab put_ bh (IfaceTuple ac ad) = do putByte bh 3 put_ bh ac put_ bh ad put_ bh (IfaceLam (ae, os) af) = do putByte bh 4 put_ bh ae put_ bh os put_ bh af put_ bh (IfaceApp ag ah) = do putByte bh 5 put_ bh ag put_ bh ah put_ bh (IfaceCase ai aj ak) = do putByte bh 6 put_ bh ai put_ bh aj put_ bh ak put_ bh (IfaceLet al am) = do putByte bh 7 put_ bh al put_ bh am put_ bh (IfaceTick an ao) = do putByte bh 8 put_ bh an put_ bh ao put_ bh (IfaceLit ap) = do putByte bh 9 put_ bh ap put_ bh (IfaceFCall as at) = do putByte bh 10 put_ bh as put_ bh at put_ bh (IfaceExt aa) = do putByte bh 11 put_ bh aa put_ bh (IfaceCast ie ico) = do putByte bh 12 put_ bh ie put_ bh ico put_ bh (IfaceECase a b) = do putByte bh 13 put_ bh a put_ bh b get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceLcl aa) 1 -> do ab <- get bh return (IfaceType ab) 2 -> do ab <- get bh return (IfaceCo ab) 3 -> do ac <- get bh ad <- get bh return (IfaceTuple ac ad) 4 -> do ae <- get bh os <- get bh af <- get bh return (IfaceLam (ae, os) af) 5 -> do ag <- get bh ah <- get bh return (IfaceApp ag ah) 6 -> do ai <- get bh aj <- get bh ak <- get bh return (IfaceCase ai aj ak) 7 -> do al <- get bh am <- get bh return (IfaceLet al am) 8 -> do an <- get bh ao <- get bh return (IfaceTick an ao) 9 -> do ap <- get bh return (IfaceLit ap) 10 -> do as <- get bh at <- get bh return (IfaceFCall as at) 11 -> do aa <- get bh return (IfaceExt aa) 12 -> do ie <- get bh ico <- get bh return (IfaceCast ie ico) 13 -> do a <- get bh b <- get bh return (IfaceECase a b) _ -> panic ("get IfaceExpr " ++ show h) instance Binary IfaceTickish where put_ bh (IfaceHpcTick m ix) = do putByte bh 0 put_ bh m put_ bh ix put_ bh (IfaceSCC cc tick push) = do putByte bh 1 put_ bh cc put_ bh tick put_ bh push put_ bh (IfaceSource src name) = do putByte bh 2 put_ bh (srcSpanFile src) put_ bh (srcSpanStartLine src) put_ bh (srcSpanStartCol src) put_ bh (srcSpanEndLine src) put_ bh (srcSpanEndCol src) put_ bh name get bh = do h <- getByte bh case h of 0 -> do m <- get bh ix <- get bh return (IfaceHpcTick m ix) 1 -> do cc <- get bh tick <- get bh push <- get bh return (IfaceSCC cc tick push) 2 -> do file <- get bh sl <- get bh sc <- get bh el <- get bh ec <- get bh let start = mkRealSrcLoc file sl sc end = mkRealSrcLoc file el ec name <- get bh return (IfaceSource (mkRealSrcSpan start end) name) _ -> panic ("get IfaceTickish " ++ show h) instance Binary IfaceConAlt where put_ bh IfaceDefault = putByte bh 0 put_ bh (IfaceDataAlt aa) = putByte bh 1 >> put_ bh aa put_ bh (IfaceLitAlt ac) = putByte bh 2 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> return IfaceDefault 1 -> liftM IfaceDataAlt $ get bh _ -> liftM IfaceLitAlt $ get bh instance Binary IfaceBinding where put_ bh (IfaceNonRec aa ab) = putByte bh 0 >> put_ bh aa >> put_ bh ab put_ bh (IfaceRec ac) = putByte bh 1 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> do { aa <- get bh; ab <- get bh; return (IfaceNonRec aa ab) } _ -> do { ac <- get bh; return (IfaceRec ac) } instance Binary IfaceLetBndr where put_ bh (IfLetBndr a b c) = do put_ bh a put_ bh b put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (IfLetBndr a b c) instance Binary IfaceTyConParent where put_ bh IfNoParent = putByte bh 0 put_ bh (IfDataInstance ax pr ty) = do putByte bh 1 put_ bh ax put_ bh pr put_ bh ty get bh = do h <- getByte bh case h of 0 -> return IfNoParent _ -> do ax <- get bh pr <- get bh ty <- get bh return $ IfDataInstance ax pr ty
wxwxwwxxx/ghc
compiler/iface/IfaceSyn.hs
Haskell
bsd-3-clause
71,979
module A4 where import B4 import C4 import D4 main :: (Tree Int) -> Bool main t = isSameOrNot (sumSquares (fringe t)) ((sumSquares (B4.myFringe t)) + (sumSquares (C4.myFringe t)))
kmate/HaRe
old/testing/renaming/A4_AstOut.hs
Haskell
bsd-3-clause
197
module SPARC.AddrMode ( AddrMode(..), addrOffset ) where import GhcPrelude import SPARC.Imm import SPARC.Base import Reg -- addressing modes ------------------------------------------------------------ -- | Represents a memory address in an instruction. -- Being a RISC machine, the SPARC addressing modes are very regular. -- data AddrMode = AddrRegReg Reg Reg -- addr = r1 + r2 | AddrRegImm Reg Imm -- addr = r1 + imm -- | Add an integer offset to the address in an AddrMode. -- addrOffset :: AddrMode -> Int -> Maybe AddrMode addrOffset addr off = case addr of AddrRegImm r (ImmInt n) | fits13Bits n2 -> Just (AddrRegImm r (ImmInt n2)) | otherwise -> Nothing where n2 = n + off AddrRegImm r (ImmInteger n) | fits13Bits n2 -> Just (AddrRegImm r (ImmInt (fromInteger n2))) | otherwise -> Nothing where n2 = n + toInteger off AddrRegReg r (RegReal (RealRegSingle 0)) | fits13Bits off -> Just (AddrRegImm r (ImmInt off)) | otherwise -> Nothing _ -> Nothing
ezyang/ghc
compiler/nativeGen/SPARC/AddrMode.hs
Haskell
bsd-3-clause
1,120
{-# OPTIONS -fwarn-incomplete-patterns #-} -- Test for incomplete-pattern warnings -- None should cause a warning module ShouldCompile where -- These ones gave bogus warnings in 6.2 data D = D1 { f1 :: Int } | D2 -- Use pattern matching in the argument f :: D -> D f d1@(D1 {f1 = n}) = d1 { f1 = f1 d1 + n } -- Warning here f d = d -- Use case pattern matching g :: D -> D g d1 = case d1 of D1 { f1 = n } -> d1 { f1 = n + 1 } -- Warning here also D2 -> d1 -- These ones were from Neil Mitchell -- no warning ex1 x = ss where (_s:ss) = x -- no warning ex2 x = let (_s:ss) = x in ss -- Warning: Pattern match(es) are non-exhaustive -- In a case alternative: Patterns not matched: [] ex3 x = case x of ~(_s:ss) -> ss
urbanslug/ghc
testsuite/tests/deSugar/should_compile/ds059.hs
Haskell
bsd-3-clause
778
{-# LANGUAGE OverloadedStrings #-} module Cirrus.Deploy (runDeploy) where import Cirrus.Encode (encode) import Control.Exception.Lens (catching_) import Control.Lens ((&), (?~), (.~)) import Control.Monad (void) import Data.ByteString.Lazy (toStrict) import Data.Text.Encoding (decodeUtf8) import Data.Text (Text) import Network.AWS import Network.AWS.CloudFormation import System.IO (stdout) import qualified Cirrus.Types as C (Stack(..)) create :: C.Stack -> CreateStack create s = createStack (C.stackName s) & csTemplateBody ?~ templateBody s update :: C.Stack -> UpdateStack update s = updateStack (C.stackName s) & usTemplateBody ?~ templateBody s templateBody :: C.Stack -> Text templateBody = decodeUtf8 . toStrict . encode . C.stackTemplate -- TODO return an Either? deploy :: C.Stack -> AWS () deploy s = catching_ _AlreadyExistsException (run create) (run update) where run f = void . send $ f s runDeploy :: C.Stack -> IO () runDeploy s = do env <- newEnv NorthVirginia Discover logger <- newLogger Debug stdout runResourceT . runAWS (env & envLogger .~ logger) $ deploy s
ags/cirrus
src/Cirrus/Deploy.hs
Haskell
mit
1,101
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Protop.Logic.Builder ( M , evalM' , evalM , popM , lftM , objM , morM , prfM , lamSM , sgmSM , varM , lamM , appM , sgmM ) where import qualified Control.Monad.Identity as I import qualified Control.Monad.State as S import Protop.Logic.Simple newtype M m a = M { runM :: S.StateT Scope m a } deriving (Functor, Applicative, Monad, S.MonadState Scope) evalM' :: Monad m => M m a -> m a evalM' m = do (x, sc) <- S.runStateT (runM m) empty if sc == empty then return x else error "scope not empty" evalM :: M I.Identity a -> a evalM = I.runIdentity . evalM' varM :: Monad m => Sig -> M m Entity varM s = do sc <- S.get S.when (sc /= scope s) $ fail $ show s ++ " has scope " ++ show (scope s) ++ ", expecting scope " ++ show sc S.put $ cons s return $ var s popM :: Monad m => M m () popM = do sc <- S.get case headTail sc of Nothing -> fail "can't pop empty scope" Just (_, sc') -> S.put sc' lftM :: (Monad m, Liftable a, HasScope a, Show a) => a -> M m a lftM x = do sc <- S.get return $ lft' sc x objM :: Monad m => M m Sig objM = objS <$> S.get morM :: Monad m => Entity -> Entity -> M m Sig morM x y = morS <$> lftM x <*> lftM y prfM :: Monad m => Entity -> Entity -> M m Sig prfM f g = prfS <$> lftM f <*> lftM g lamSM :: Monad m => Sig -> M m Sig lamSM s = do s' <- lftM s popM return $ lamS s' sgmSM :: Monad m => Sig -> M m Sig sgmSM s = do s' <- lftM s popM return $ sgmS s' lamM :: Monad m => Entity -> M m Entity lamM e = do e' <- lftM e popM return $ lam e' appM :: Monad m => Entity -> Entity -> M m Entity appM e f = app <$> lftM e <*> lftM f sgmM :: Monad m => Sig -> Entity -> Entity -> M m Entity sgmM s e f = sgm <$> lftM s <*> lftM e <*> lftM f
brunjlar/protop
src/Protop/Logic/Builder.hs
Haskell
mit
1,983
module LasmConverter where import Control.Monad.State import Data.Map hiding (map, foldr) import Prelude hiding (lookup) import Debug.Trace import AbsLasm import AbsJavalette --Environment monad data LEnv = Env Integer Integer Integer [Context] Context type EnvState = State LEnv data Pointer = Val Integer | Ref Integer deriving (Eq, Ord, Show) type Context = Map AbsLasm.Ident Pointer newEnv :: LEnv newEnv = Env 0 0 0 [empty] empty getFreshLabel :: EnvState Label getFreshLabel = do (Env l c t r s) <- get put (Env (l+1) c t r s) return (Label ("label" ++ (show l))) countStringRegs :: EnvState Integer countStringRegs = do (Env _ _ _ _ s) <- get return (fromIntegral(size s)) getReg :: AbsJavalette.Ident -> EnvState (Register, Bool) getReg i = do (Env _ _ _ rs _) <- get return (getReg' (cIdentL i) rs) getReg' :: AbsLasm.Ident -> [Context] -> (Register, Bool) getReg' i [] = error $ "[getReg] Register not found " ++ (show i) getReg' i (r:rs) = case (lookup i r) of Just reg -> case reg of Val x -> (Register ("reg" ++ (show x)), True) Ref x -> (Register ("reg" ++ (show x)), False) Nothing -> getReg' i rs openScope :: EnvState() openScope = do (Env l c t r s) <- get put (Env l c t (empty:r) s) closeScope :: EnvState() closeScope = do (Env l c t (_:rs) s) <- get put (Env l c t rs s) getFreshReg :: AbsJavalette.Ident -> Bool -> EnvState Register getFreshReg i byVal = do (Env l c t (r:rs) s) <- get put (Env l (c+1) t ((insert (cIdentL i) (createPointer (c+1) byVal) r):rs) s) return (Register ("reg" ++ (show (c+1)))) createPointer :: Integer -> Bool -> Pointer createPointer x byVal = case byVal of True -> Val x False -> Ref x getFreshTmpReg :: EnvState Register getFreshTmpReg = do (Env l c t r s) <- get put (Env l c (t+1) r s) return (Register ("tmp"++(show (t)))) getFreshString :: String -> EnvState Register getFreshString s = do (Env l c t r sc) <- get case (lookup (AbsLasm.Ident s) sc) of Just (Ref x) -> return (Register ("string" ++ (show x))) _ -> do cs <- countStringRegs put (Env l c t r (insert (AbsLasm.Ident s) (createPointer (cs+1) False) sc)) return (Register ("string" ++ (show (cs+1)))) getStrings :: EnvState Context getStrings = do (Env _ _ _ _ sc) <- get return (sc) --Converter cASTL :: Program -> LProgram cASTL (Program defs) = AbsLasm.Prog (defsL) where defsL = evalState (combineGlobals defs) newEnv combineGlobals :: [Def] -> EnvState [LTop] combineGlobals ds = do ds' <- cDefsL ds ss <- findStrings return (ss ++ ds') cDefsL :: [Def] -> EnvState [LTop] cDefsL [] = return [] cDefsL ((Def t i as (Block ss)):ds) = do openScope as' <- cArgsL as ss' <- (cStmsL ss) ds' <- cDefsL ds closeScope return ((AbsLasm.Fun (cTypeL t) (cIdentL i) as' ([SLabel (Label "entry")] ++ ss')):ds') cStmsL :: [Stm] -> EnvState [LStm] cStmsL [] = return [] cStmsL (s:ss) = case s of SRet _ -> cStmL s SVRet -> cStmL s _ -> do s' <- cStmL s ss' <- cStmsL ss return (s' ++ ss') cStmL :: Stm -> EnvState [LStm] cStmL s = case s of SEmpty -> return [] SBlock (Block ss) -> do openScope ss' <- cStmsL ss closeScope return ss' SDecl t is -> cDeclVarsL is (cTypeL t) SAss i e -> do (o, ss) <- cExpL e (addr, _) <- getReg i return (ss ++ [SStore o addr]) SRefAss i e1 e2 -> do (e1', ss) <- cExpL e1 (ptr, _) <- getReg i tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg (e2', ss') <- cExpL e2 return (ss ++ ss' ++ [SGEPtr tmp1 (TPtr(TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cExpTypeL e2))])) ptr [(Const (VInt 0)),(Const (VInt 1))], SLoad tmp2 (TPtr (AbsLasm.TArray (cExpTypeL e2))) tmp1, SGEPtr addr (TPtr (AbsLasm.TArray (cExpTypeL e2))) tmp2 [(Const (VInt 0)), e1'], SStore e2' addr]) SIncr i -> do (reg, byVal) <- getReg i case byVal of True -> return [SAdd reg AbsLasm.TInt (Var AbsLasm.TInt reg) (Const (VInt 1))] False -> do val <- getFreshTmpReg return [SLoad val AbsLasm.TInt reg, SAdd val AbsLasm.TInt (Var AbsLasm.TInt val) (Const (VInt 1))] SDecr i -> do (reg, byVal) <- getReg i case byVal of True -> return [SSub reg AbsLasm.TInt (Var AbsLasm.TInt reg) (Const (VInt 1))] False -> do val <- getFreshTmpReg return [SLoad val AbsLasm.TInt reg, SSub val AbsLasm.TInt (Var AbsLasm.TInt val) (Const (VInt 1))] SRet e -> do (o, ss) <- cExpL e return (ss ++ [SReturn (cExpTypeL e) o]) SVRet -> return [SVReturn] SIf e s1 -> case e of EType ETrue _ -> cStmL s1 EType EFalse _ -> return [] _ -> do true <- getFreshLabel false <- getFreshLabel (cmp, ss) <- cExpL e ss' <- cStmL s1 return (ss ++ [SBr (getRegister cmp) true false] ++ [SLabel (true)] ++ ss' ++ [SJmp (false)] ++ [SLabel (false)]) SIfElse e s1 s2 -> case e of EType ETrue _ -> cStmL s1 EType EFalse _ -> cStmL s2 _ -> do true <- getFreshLabel false <- getFreshLabel end <- getFreshLabel (cmp, ss) <- cExpL e ss1 <- cStmL s1 ss2 <- cStmL s2 return (ss ++ [SBr (getRegister cmp) true false] ++ [SLabel (true)] ++ ss1 ++ [SJmp (end)] ++ [SLabel (false)] ++ ss2 ++ [SJmp (end)] ++ [SLabel (end)]) SWhile e s1 -> case e of EType ETrue _ -> do into <- getFreshLabel ss1 <- cStmL s1 return ([SJmp (into)] ++ [SLabel (into)] ++ ss1 ++ [SJmp (into)]) EType EFalse _ -> return [] _ -> do into <- getFreshLabel test <- getFreshLabel out <- getFreshLabel (cmp, ss) <- cExpL e ss1 <- cStmL s1 return ([SJmp (into)] ++ [SLabel (into)] ++ ss1 ++ [SJmp (test)] ++ [SLabel (test)] ++ ss ++ [SBr (getRegister cmp) into out] ++ [SLabel (out)]) SFor t i e s -> do into <- getFreshLabel test <- getFreshLabel body <- getFreshLabel out <- getFreshLabel (ldarr, ss) <- cExpL e array <- getFreshTmpReg var <- getFreshReg i False j <- getFreshTmpReg len <- getFreshTmpReg tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg tmp3 <- getFreshTmpReg tmp4 <- getFreshTmpReg tmp5 <- getFreshTmpReg tmp6 <- getFreshTmpReg tmp7 <- getFreshTmpReg tmp8 <- getFreshTmpReg tmp9 <- getFreshTmpReg s' <- cStmL s return ([SJmp (into), SLabel (into), SAlloc j AbsLasm.TInt, SStore (Const (VInt 0)) j] ++ ss ++ [SAlloc array (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]), SStore ldarr array, SExtStruct len (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]) (getRegister ldarr) 0, SJmp (test), SLabel (test), SLoad tmp3 (AbsLasm.TInt) j, SCmp tmp4 BNeq AbsLasm.TInt (Var AbsLasm.TInt tmp3) (Var AbsLasm.TInt len), SBr tmp4 body out, SLabel (body), SGEPtr tmp5 (TPtr(TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray t')])) array [(Const (VInt 0)),(Const (VInt 1))], SLoad tmp6 (TPtr (AbsLasm.TArray t')) tmp5, SLoad tmp7 (AbsLasm.TInt) j, SGEPtr var (TPtr (AbsLasm.TArray t')) tmp6 [(Const (VInt 0)), (Var (AbsLasm.TInt) tmp7)]] ++ s' ++ [SLoad tmp8 (AbsLasm.TInt) j, SAdd tmp9 AbsLasm.TInt (Var AbsLasm.TInt tmp8) (Const (VInt 1)), SStore (Var AbsLasm.TInt tmp9) j, SJmp (test), SLabel (out)]) where t' = cTypeL t SExp e -> do (_, ss) <- cExpL e return ss cExpL :: Exp -> EnvState (Operand, [LStm]) cExpL et@(EType e t) = case e of EVar i -> do (reg, byVal) <- getReg i case byVal of True -> return ((Var (cTypeL t) reg), []) False -> do val <- getFreshTmpReg return ((Var (cTypeL t) val), [SLoad val (cTypeL t) reg]) EInt n -> return (Const (VInt n), []) EDbl d -> return (Const (VDbl d), []) ETrue -> return (Const (VBool 1), []) EFalse -> return (Const (VBool 0), []) EApp i es -> case t of AbsJavalette.TVoid -> do (os, ss) <- cAppArgsL es [] [] return (Const (VInt 0), ss ++ [SVCall (cIdentL i) os]) _ -> do (os, ss) <- cAppArgsL es [] [] reg <- getFreshTmpReg return (Var (cTypeL t) reg, ss ++ [SCall reg (cIdentL i) (cTypeL t) os]) EString s -> do reg <- getFreshString s return (Const (VString reg (fromIntegral (length s)+1)), []) ERef i e1 -> do (e1', ss) <- cExpL e1 (ptr, _) <- getReg i tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg val <- getFreshTmpReg return (Var (cTypeL t) val, ss ++ [SGEPtr tmp1 (TPtr(TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cTypeL t))])) ptr [(Const (VInt 0)),(Const (VInt 1))], SLoad tmp2 (TPtr (AbsLasm.TArray (cTypeL t))) tmp1, SGEPtr addr (TPtr (AbsLasm.TArray (cTypeL t))) tmp2 [(Const (VInt 0)), e1'], SLoad val (cTypeL t) addr]) ENew t'' e1 -> do (e1', ss) <- cExpL e1 tmp0 <- getFreshTmpReg tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg tmp3 <- getFreshTmpReg tmp4 <- getFreshTmpReg tmp5 <- getFreshTmpReg tmp6 <- getFreshTmpReg reg <- getFreshTmpReg return (Var t' reg, [SAlloc tmp0 t', SLoad tmp1 t' tmp0] ++ ss ++ [SCalloc tmp2 tmp3 (cTypeL t'') e1' tmp4, SInsStruct tmp6 t' tmp1 e1' 0, SInsStruct reg t' tmp6 (Var (TPtr (AbsLasm.TArray (cTypeL t''))) tmp4) 1]) where t' = cTypeL t EALen i -> do (addr, _) <- getReg i tmp <- getFreshTmpReg reg <- getFreshTmpReg return (Var (AbsLasm.TInt) reg, [SLoad tmp (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]) addr, SExtStruct reg (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]) tmp 0]) ENeg e1 -> do (e1', ss) <- cExpL e1 reg <- getFreshTmpReg return (case t of AbsJavalette.TInt -> ((Var (cTypeL t) reg), (ss ++ [SMul reg (cTypeL t) e1' (Const (VInt (-1)))])) AbsJavalette.TDbl -> ((Var (cTypeL t) reg), (ss ++ [SMul reg (cTypeL t) e1' (Const (VDbl (-1.0)))]))) ENot e1 -> do (e1', ss) <- cExpL e1 reg <- getFreshTmpReg return ((Var (cTypeL t) reg), (ss ++ [SXor reg (cTypeL t) e1' (Const (VInt (1)))])) EMul e1 op e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 reg <- getFreshTmpReg return (case op of OTimes -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SMul reg (cTypeL t) e1' e2'])) ODiv -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SDiv reg (cTypeL t) e1' e2'])) OMod -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SMod reg (cTypeL t) e1' e2']))) EAdd e1 op e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 reg <- getFreshTmpReg return (case op of OPlus -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SAdd reg (cTypeL t) e1' e2'])) OMinus -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SSub reg (cTypeL t) e1' e2']))) ERel e1 op e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 reg <- getFreshTmpReg return ((Var (cTypeL t) reg), (ss ++ ss' ++ [SCmp reg (cRelOpL op) (cExpTypeL e1) e1' e2'])) EAnd e1 e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg reg <- getFreshTmpReg true <- getFreshLabel false <- getFreshLabel end <- getFreshLabel return ((Var AbsLasm.TBool reg), ([SAlloc addr AbsLasm.TBool] ++ ss ++ [SCmp tmp1 BNeq AbsLasm.TBool e1' (Const (VBool 0))] ++ [SBr tmp1 true false, SLabel true] ++ ss' ++ [SAnd tmp2 AbsLasm.TBool e1' e2', SStore (Var AbsLasm.TBool tmp2) addr, SJmp end] ++ [SLabel false, SStore (Const (VBool 0)) addr, SJmp end] ++ [SLabel end, SLoad reg AbsLasm.TBool addr])) EOr e1 e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg reg <- getFreshTmpReg true <- getFreshLabel false <- getFreshLabel end <- getFreshLabel return ((Var AbsLasm.TBool reg), ([SAlloc addr AbsLasm.TBool] ++ ss ++ [SCmp tmp1 BNeq AbsLasm.TBool e1' (Const (VBool 1))] ++ [SBr tmp1 true false, SLabel true] ++ ss' ++ [SOr tmp2 AbsLasm.TBool e1' e2', SStore (Var AbsLasm.TBool tmp2) addr, SJmp end] ++ [SLabel false, SStore (Const (VBool 1)) addr, SJmp end] ++ [SLabel end, SLoad reg AbsLasm.TBool addr])) EType e t -> error $ "[cExpL] Should not try to convert a EType " ++ (show e) cAppArgsL :: [Exp] -> [Operand] -> [LStm] -> EnvState ([Operand], [LStm]) cAppArgsL [] os ss = return (os, ss) cAppArgsL (e:es) os ss = do (o, ss') <- cExpL e case o of Var (TStruct ts) r -> do tmp <- getFreshTmpReg cAppArgsL es (os++[Var (TPtr (TStruct ts)) tmp]) (ss++ss'++[SAlloc tmp (TStruct ts), SStore o tmp]) _ -> cAppArgsL es (os++[o]) (ss++ss') cDeclVarsL :: [Item] -> LType -> EnvState [LStm] cDeclVarsL [] _ = return [] cDeclVarsL (it:its) t = case it of INoInit i -> case t of AbsLasm.TInt -> do newreg <- getFreshReg i False ss <- (cDeclVarsL its t) return ([SAlloc newreg t, SStore (Const (VInt 0)) newreg] ++ ss) AbsLasm.TDbl -> do newreg <- getFreshReg i False ss <- (cDeclVarsL its t) return ([SAlloc newreg t, SStore (Const (VDbl 0.0)) newreg] ++ ss) AbsLasm.TArray t' -> do newreg <- getFreshReg i False ss <- (cDeclVarsL its t) return ([SAlloc newreg t] ++ ss) IInit i e -> do (o, ss) <- cExpL e newreg <- getFreshReg i False ss' <- (cDeclVarsL its t) return ([SAlloc newreg t] ++ ss ++ [SStore o newreg] ++ ss') cExpTypeL :: Exp -> LType cExpTypeL (EType _ t) = cTypeL t cExpTypeL e = error $ "[cExpTypeL] not an EType, instead: " ++ show e cArgsL :: [Arg] -> EnvState [LArg] cArgsL [] = return [] cArgsL ((AbsJavalette.Arg t i):as) = do (Register s) <- getFreshReg i byVal as' <- (cArgsL as) return ((AbsLasm.Arg t' (AbsLasm.Ident s)):as') where t' = case t of AbsJavalette.TArray t'' -> TPtr (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cTypeL t''))]) _ -> cTypeL t byVal = case t of AbsJavalette.TArray _ -> False _ -> True cTypeL :: Type -> LType cTypeL t = case t of AbsJavalette.TInt -> AbsLasm.TInt AbsJavalette.TDbl -> AbsLasm.TDbl AbsJavalette.TBool -> AbsLasm.TBool AbsJavalette.TVoid -> AbsLasm.TVoid (AbsJavalette.TArray t') -> TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cTypeL t'))] cArrayTypeL :: Type -> LType cArrayTypeL t = case t of (AbsJavalette.TArray t') -> cTypeL t' _ -> error $ "[cTypeArray] Input type is not array but " ++ show t cRelOpL :: RelOp -> LBrType cRelOpL op = case op of OLt -> BLt OLeq -> BLEq OGt -> BGt OGeq -> BGEq OEq -> BEq ONEq -> BNeq cIdentL :: AbsJavalette.Ident -> AbsLasm.Ident cIdentL (AbsJavalette.Ident s) = AbsLasm.Ident s getRegister :: Operand -> Register getRegister (Var t reg) = reg getRegister op = error $ "[getRegister] Operand not register: " ++ (show op) findStrings :: EnvState [LTop] findStrings = do sc <- getStrings return (cGlobalsL (toList sc)) cGlobalsL :: [(AbsLasm.Ident, Pointer)]-> [LTop] cGlobalsL [] = [] cGlobalsL ((AbsLasm.Ident s, Ref x):ss) = (Global (Register ("string"++show x)) s):(cGlobalsL ss)
davidsundelius/JLC
src/LasmConverter.hs
Haskell
mit
21,425
-- | A data type representing the game map at a particular frame, and functions that operate on it. module Hlt.GameMap where import qualified Data.Either as Either import qualified Data.Maybe as Maybe import qualified Data.Map as Map import Hlt.Entity -- | A GameMap contains the current frame of a Halite game. data GameMap = GameMap { myId :: PlayerId , width :: Int , height :: Int , allPlayers :: Map.Map PlayerId Player , allPlanets :: Map.Map PlanetId Planet } deriving (Show) -- | Return a list of all Planets. listAllPlanets :: GameMap -> [Planet] listAllPlanets g = Map.elems $ allPlanets g -- | Return a list of all Ships. listAllShips :: GameMap -> [Ship] listAllShips g = concat $ map (Map.elems . ships) (Map.elems $ allPlayers g) -- | Return a list of my Ships. listMyShips :: GameMap -> [Ship] listMyShips g = Map.elems $ ships $ Maybe.fromJust $ Map.lookup (myId g) (allPlayers g) -- | Checks if any of the given Entities are in between two Entities. entitiesBetweenList :: Entity a => Entity b => Entity c => [a] -> b -> c -> Bool entitiesBetweenList l e0 e1 = any (\e -> isSegmentCircleCollision e0 e1 e) $ filter (\e -> notEqual e e0 && notEqual e e1) l -- | Checks if there are any Entities between two Entities. entitiesBetween :: Entity a => Entity b => GameMap -> Bool -> a -> b -> Bool entitiesBetween g c a b = entitiesBetweenList (listAllPlanets g) a b || (c && entitiesBetweenList (listAllShips g) a b)
HaliteChallenge/Halite-II
airesources/Haskell/Hlt/GameMap.hs
Haskell
mit
1,567
{- Problem 19 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? -} euler19 = length $ filter (\d -> d `mod` 7 == 5) -- 1/1/1901 is Tuesday so 5 days after is Sunday $ [getDaysSince1901 y m | y <- [1901..2000], m <- [0..11]] getDaysSince1901 :: Int -> Int -> Int getDaysSince1901 year month = foldl (+) 0 $ [if leapYear y then 366 else 365 | y <- [1901..(year - 1)]] ++ (map (days) $ take month monthDays) where days = if leapYear year then fst else snd leapYear n = n `mod` 4 == 0 && (n `mod` 400 == 0 || n `mod` 100 /= 0) monthDays = [(31, 31), (29, 28), (31, 31), (30, 30), (31, 31), (30, 30), (31, 31), (31, 31), (30, 30), (31, 31), (30, 30), (31, 31) ]
RossMeikleham/Project-Euler-Haskell
19.hs
Haskell
mit
1,266
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Sound.PortAudio.Base import Sound.PortAudio import qualified Sound.File.Sndfile as SF import qualified Sound.File.Sndfile.Buffer as BSF import qualified Sound.File.Sndfile.Buffer.Vector as VSF import Data.List (transpose) import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as MV import Control.Monad (foldM, foldM_, forM_, when, unless, zipWithM_) import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent (threadDelay, forkIO) import Text.Printf import Foreign.C.Types import Foreign.Storable import Foreign.ForeignPtr import Foreign.Marshal.Alloc import Foreign.Ptr import qualified UI.HSCurses.Curses as Curses (move, refresh, scrSize, endWin) import qualified UI.HSCurses.CursesHelper as CursesH (gotoTop, drawLine, start, end) import System.Environment (getArgs) import Transform ( kPointFFT ) data TimedBuffer = TimedBuffer { dataPoints :: V.Vector Float, timeStamp :: Double } framesPerBuffer :: Int framesPerBuffer = 300 type FFTPrintFunc = MVar [ Float ] -> IO () rawPrintFunc :: FFTPrintFunc rawPrintFunc mvar = do dta <- takeMVar mvar unless (null dta) $ do print dta rawPrintFunc mvar cursesRawPrintFunc :: FFTPrintFunc cursesRawPrintFunc mvar = CursesH.start >> workerFunc >> CursesH.end where workerFunc = do dta <- takeMVar mvar unless (null dta) $ do (maxRows, maxCols) <- Curses.scrSize let compressed = transpose $ take maxCols $ asciiDisplayRaw maxRows 5 (0, 25) (take maxCols dta) '*' asciiDisplayRaw :: Int -> Int -> (Float, Float) -> [Float] -> Char -> [String] asciiDisplayRaw height barWidth (x,y) points symbol = result where result = concatMap (\str -> replicate barWidth str) pure pure = map (\p -> let req = (func p) in (replicate (height - req) ' ') ++ (replicate req symbol)) points func pnt | pnt > y = height | pnt < x = 0 | otherwise = ceiling $ (realToFrac height) * (pnt - x) / spanning spanning = y - x len = length points displayBars :: Int -> [String] -> IO () displayBars width items = zipWithM_ (\row string -> Curses.move row 0 >> CursesH.drawLine width string) [0..] items displayBars (maxCols - 1) compressed >> Curses.refresh workerFunc processFourierData :: Chan TimedBuffer -> Int -> Int -> IO () processFourierData readChannel channels pointsFFT = do fourierDrawing <- newMVar (U.fromList []) toPrinter <- newEmptyMVar fftVec <- MV.new pointsFFT forkIO $ defaultPrintFunc toPrinter let workerFunc pos lastTime mutVec fftUpdate = do if pos == pointsFFT then do frozen <- U.freeze mutVec swapMVar fourierDrawing (kPointFFT frozen) workerFunc 0 lastTime mutVec True else do TimedBuffer pnts ts <- readChan readChannel if (V.null pnts) then (putMVar toPrinter [] >> putStrLn "Ending!") else do let numPoints = V.length pnts fftPrint = (ts - lastTime >= updateInterval && fftUpdate) slotsAvail = pointsFFT - pos toFourier = V.take slotsAvail pnts newFFTUpdate = if fftPrint then False else fftUpdate newTime = if fftPrint then ts else lastTime forM_ [0..(V.length toFourier - 1)] $ \i -> MV.unsafeWrite mutVec (pos + i) (toFourier V.! i) when fftPrint $ do drawData <- readMVar fourierDrawing putMVar toPrinter (U.toList drawData) workerFunc (pos + V.length toFourier) newTime mutVec newFFTUpdate workerFunc 0 0 fftVec False runFunc :: MVar (V.Vector Float) -> Chan TimedBuffer -> Int -> Int -> ForeignPtr CFloat -> Stream CFloat CFloat -> IO () runFunc fileData fourierChannel frames channels out strm = do pnts <- modifyMVar fileData (\vec -> let (x, y) = V.splitAt (fromIntegral frames * channels) vec in return (y, x)) if (V.null pnts) then (writeChan fourierChannel (TimedBuffer (V.fromList []) 0)) else do let totalLen = V.length pnts withForeignPtr out $ \p -> V.foldM_ (\i val -> pokeElemOff p i (realToFrac val) >> return (i + 1)) 0 pnts (Right (PaTime tme)) <- getStreamTime strm writeStream strm (fromIntegral $ totalLen `div` channels) out writeChan fourierChannel (TimedBuffer pnts (realToFrac tme)) runFunc fileData fourierChannel frames channels out strm withBlockingIO :: SF.Info -> MVar (V.Vector Float) -> IO (Either Error ()) withBlockingIO info fileData = do let channels = SF.channels info fourierChannel <- newChan forkIO $ processFourierData fourierChannel channels pointsPerTransform outInfo <- getDefaultOutputInfo case outInfo of Left err -> return $ Left err Right (devIndex, devInfo) -> do let outInfo = Just $ StreamParameters devIndex 2 (defaultHighOutputLatency devInfo) withStream Nothing outInfo (realToFrac $ SF.samplerate info) (Just framesPerBuffer) [ClipOff] Nothing Nothing $ \strm -> do allocaBytes (framesPerBuffer * channels) $ \out -> do out' <- newForeignPtr_ out startStream strm runFunc fileData fourierChannel framesPerBuffer channels out' strm stopStream strm return $ Right () updateInterval :: Double updateInterval = 0.5 pointsPerTransform :: Int pointsPerTransform = 1024 defaultPrintFunc :: FFTPrintFunc defaultPrintFunc = cursesRawPrintFunc main :: IO () main = do [inFile] <- getArgs (info, Just (x :: VSF.Buffer Float)) <- SF.readFile inFile let vecData = V.convert $ VSF.fromBuffer x channels = SF.channels info fileData <- newMVar vecData withPortAudio $ withBlockingIO info fileData return ()
sw17ch/portaudio
examples/Example3.hs
Haskell
mit
6,545
import Samba import System.Process (createProcess, shell) import Control.Monad (when) main = do putStrLn $ unlines [ "################################################################" , "Instructions: " , "" , "Firstly, ensure your smb.conf have this section:" , "[homes]" , " comment = Home Directories" , " browseable = yes" , " writable = yes" , " read only = no" , " valid users = %S" , "" , "----------------------------------------------------------------" , "To use this program, just enter the names you want to add and the" , "whole process of adding a new user to the system and then to Samba" , "will be done for you. Also the passwords will be generated " , "automatically" , "" , "*Note: remember to restart Samba after changes" , "*Note: remember to add permision to a newSambaUser.bash" , "################################################################" ] createUser createUser :: IO () createUser = do putStrLn "Insert a username" user <- getLine when (user /= "") $ do let pass = dpass user putStrLn $ "The password of the user " ++ user ++ " will be " ++ pass putStrLn "Creating user..." callCommand $ "./newSambaUser.bash \"" ++ user ++ "\" \"" ++ pass ++ "\"" createUser callCommand = createProcess . shell
felipexpert/sambaHaskell
defineSambaUser.hs
Haskell
mit
1,353
module Main where import Barcode import System.Environment import qualified Data.Vector as V import qualified Data.List as DL main :: IO () main = do -- get input arg [inFile, maxSnps'] <- getArgs >>= return . take 2 let maxSnps = read maxSnps' :: Int samples <- parseBarcode inFile let samples' = uniquify $ V.toList $ V.filter validBarcode samples putStrLn $ show $ DL.sort $ map (+1) $ take maxSnps $ chooseSnps samples' [0..23] -- :load Barcode -- samples <- parseBarcode "2013-test.csv" -- let samples' = uniquify $ V.toList $ V.filter validBarcode samples -- let ids = map (\x -> x - 1) [1, 9, 10, 11, 12, 14, 15, 18] -- putStrLn $ unlines $ reportDuplicates samples' ids -- let ids = map (\x -> x - 1) [19,15,6,4,3,20,5,12,8,13,14,22,18,17,7,16,10,11,21,2]
ndaniels/strain-assay-minimization
Main.hs
Haskell
mit
788
------------- --LIBRARIES-- ------------- import Graphics.UI.WXCore import GUI_Player import GUI_Cpu ----------- --METHODS-- ----------- main :: IO() main = do putStrLn "Enter game mode (player or cpu): " gameMode <- getLine case gameMode of "player" -> run createPlayerWindow "cpu" -> run createCpuWindow otherwise -> skipCurrentEvent
BrunoAltadill/Bloxorz_2D
code/Main.hs
Haskell
mit
372
#!/usr/bin/env runhaskell {-# LANGUAGE FlexibleInstances #-} import Control.Monad.Reader hiding (when) import Data.Decimal import qualified Data.List as L hiding (and) import DSL import FinancialArithmetic import Models import Graphics.EasyPlot ------------------------------------------------------------------------------ main = do let payments1 = [] let u1 = Contract "1" $ when (at $ 3 Months) (Give $ One $ 100 USD) let u2 = Contract "2" $ american (1 Month, 3 Months) (One $ 10 NZD) print $ u1 .+ u2 -- let timeline = map Model [0..11] -- print $ {- EXAMPLE 1: ------------------------------------------------------------ Over the timeframe of 12 months, get and compare performance figures for two contracts. First contract: Pay 100 NZD at the beginning of the third month, get 105 NZD at the end of the 10th month. Second contract: Pay 100 USD at the beginning of the third month, get 103 USD at the end of the 10th month. -} let c1 = Contract "C1" $ (when (at $ 2 Months) (Give $ One $ 100 NZD)) `And` (when (at $ 10 Months) (One $ 105 NZD)) let c2 = Contract "C2" $ And (when (at $ 2 Months) (Give $ One $ 100 USD)) (when (at $ 10 Months) (One $ 103 USD)) {- Information provided: Main currency Highest deposit rates for each month Lowest loan rates for each month Defined in Models.hs -} let m = m_nzakl_2015_baseline -- Schedule of payments let s1 = contractToSchedule m c1 let s2 = contractToSchedule m c2 -- Print actions for each period of the whole term print $ name c1 ++ ": " ++ (show s1) print $ name c2 ++ ": " ++ (show s2) {- Questions asked: * Calculate NPV, NFV for each contract * Calculate equivalent deposit rate for each contract -} let npv :: Contract -> Reader (Model, Time) Contract npv c = do (m, t) <- ask return $ npv' m t c print $ runReader (npv c1) (m, 1 Month)
AlexanderAA/haskell-contract-valuation
Examples.hs
Haskell
mit
2,230
-- -- This code was created by Jeff Molofee '99 (ported to Haskell GHC 2005) -- module Main where import qualified Graphics.UI.GLFW as GLFW -- everything from here starts with gl or GL import Graphics.Rendering.OpenGL.Raw import Graphics.Rendering.GLU.Raw ( gluPerspective ) import Data.Bits ( (.|.) ) import System.Exit ( exitWith, ExitCode(..) ) import Control.Monad ( forever ) import Data.IORef ( IORef, newIORef, readIORef, writeIORef ) increment :: GLfloat increment = 1.5 initGL :: GLFW.Window -> IO () initGL win = do glShadeModel gl_SMOOTH -- enables smooth color shading glClearColor 0 0 0 0 -- Clear the background color to black glClearDepth 1 -- enables clearing of the depth buffer glEnable gl_DEPTH_TEST glDepthFunc gl_LEQUAL -- type of depth test glHint gl_PERSPECTIVE_CORRECTION_HINT gl_NICEST (w,h) <- GLFW.getFramebufferSize win resizeScene win w h resizeScene :: GLFW.WindowSizeCallback resizeScene win w 0 = resizeScene win w 1 -- prevent divide by zero resizeScene _ width height = do glViewport 0 0 (fromIntegral width) (fromIntegral height) glMatrixMode gl_PROJECTION glLoadIdentity gluPerspective 45 (fromIntegral width/fromIntegral height) 0.1 100 glMatrixMode gl_MODELVIEW glLoadIdentity glFlush drawScene :: IORef GLfloat -> IORef GLfloat -> GLFW.Window -> IO () drawScene rtri rquad _ = do -- clear the screen and the depth buffer glClear $ fromIntegral $ gl_COLOR_BUFFER_BIT .|. gl_DEPTH_BUFFER_BIT glLoadIdentity -- reset view glTranslatef (-1.5) 0 (-6.0) --Move left 1.5 Units and into the screen 6.0 rt <- readIORef rtri glRotatef rt 0 1 0 -- Rotate the triangle on the Y axis -- draw a triangle (in smooth coloring mode) glBegin gl_TRIANGLES -- start drawing a polygon glColor3f 1 0 0 -- set the color to Red glVertex3f 0 1 0 -- top glColor3f 0 1 0 -- set the color to Green glVertex3f 1 (-1) 0 -- bottom right glColor3f 0 0 1 -- set the color to Blue glVertex3f (-1) (-1) 0 -- bottom left glEnd glLoadIdentity glTranslatef 1.5 0 (-6) -- move right three units rq <- readIORef rquad glRotatef rq 1 0 0 -- rotate the quad on the x axis glColor3f 0.5 0.5 1 -- set color to a blue shade glBegin gl_QUADS -- start drawing a polygon (4 sided) glVertex3f (-1) 1 0 -- top left glVertex3f 1 1 0 -- top right glVertex3f 1 (-1) 0 -- bottom right glVertex3f (-1) (-1) 0 -- bottom left glEnd -- increase the rotation angle for the triangle writeIORef rtri $! rt + increment -- increase the rotation angle for the quad writeIORef rquad $! rq + increment glFlush shutdown :: GLFW.WindowCloseCallback shutdown win = do GLFW.destroyWindow win GLFW.terminate _ <- exitWith ExitSuccess return () keyPressed :: GLFW.KeyCallback keyPressed win GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = shutdown win keyPressed _ _ _ _ _ = return () main :: IO () main = do True <- GLFW.init -- select type of display mode: -- Double buffer -- RGBA color -- Alpha components supported -- Depth buffer GLFW.defaultWindowHints -- open a window Just win <- GLFW.createWindow 800 600 "Lesson 4" Nothing Nothing GLFW.makeContextCurrent (Just win) -- register the function to do all our OpenGL drawing rt <- newIORef 0 rq <- newIORef 0 GLFW.setWindowRefreshCallback win (Just (drawScene rt rq)) -- register the funciton called when our window is resized GLFW.setFramebufferSizeCallback win (Just resizeScene) -- register the function called when the keyboard is pressed. GLFW.setKeyCallback win (Just keyPressed) GLFW.setWindowCloseCallback win (Just shutdown) -- initialize our window. initGL win -- start event processing engine forever $ do GLFW.pollEvents drawScene rt rq win GLFW.swapBuffers win
spetz911/progames
nehe-tuts-master/lesson04.hs
Haskell
mit
3,972
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Network.Network ( Network(..) ) where import Network.Layer import Numeric.LinearAlgebra import System.Random -- | A network is class Network a where type Parameters :: * predict :: Vector Double -> a -> Vector Double createNetwork :: (RandomGen g) => RandomTransform -> g -> Parameters -> a
mckeankylej/hwRecog
Network/Network.hs
Haskell
mit
490
module Data.IntSet.Data where import qualified Data.IntSet as I isetTo :: Int -> I.IntSet isetTo n = I.fromList [1..n] iset1 :: I.IntSet iset1 = isetTo 10 iset2 :: I.IntSet iset2 = isetTo 20 iset3 :: I.IntSet iset3 = isetTo 30 iset4 :: I.IntSet iset4 = isetTo 40 iset5 :: I.IntSet iset5 = isetTo 50
athanclark/sets
bench/Data/IntSet/Data.hs
Haskell
mit
307
import Criterion.Main import Control.DeepSeq import qualified Data.Maybe as B import qualified MapMaybe as F main = do rnf ints `seq` return () defaultMain [ bgroup "simple" [ bench "base" $ nf (B.mapMaybe half) ints , bench "fold" $ nf (F.mapMaybe half) ints ] , bgroup "after map" [ bench "base" $ nf (B.mapMaybe half . map (+1)) ints , bench "fold" $ nf (F.mapMaybe half . map (+1)) ints ] , bgroup "after filter" [ bench "base" $ nf (B.mapMaybe half . filter seven) ints , bench "fold" $ nf (F.mapMaybe half . filter seven) ints ] , bgroup "before map" [ bench "base" $ nf (map (+1) . B.mapMaybe half) ints , bench "fold" $ nf (map (+1) . F.mapMaybe half) ints ] ] ints :: [Int] ints = [-2 .. 8000] half :: Int -> Maybe Int half n = if even n then Just $! div n 2 else Nothing seven :: Int -> Bool seven x = quot x 10 == 7
takano-akio/mapmaybe-benchmarks
main.hs
Haskell
cc0-1.0
928
{-# LANGUAGE OverloadedStrings, CPP #-} module FormStructure.Chapter7 (ch7Roles) where #ifndef __HASTE__ --import Data.Text.Lazy (pack) #endif import FormEngine.FormItem import FormStructure.Common ch7Roles :: FormItem ch7Roles = Chapter { chDescriptor = defaultFIDescriptor { iLabel = Just "7.Roles " } , chItems = [roles, remark] } where roles :: FormItem roles = SimpleGroup { sgDescriptor = defaultFIDescriptor { iLabel = Just "Employed roles" , iMandatory = True } , sgLevel = 0 , sgItems = [ NumberFI { nfiDescriptor = defaultFIDescriptor { iLabel = Just "Data producer" , iTags = [Tag "box_1"] , iLink = Just "Haste['toRoles']()" } , nfiUnit = SingleUnit "Full-time equivalent" } , NumberFI { nfiDescriptor = defaultFIDescriptor { iLabel = Just "Data expert" , iTags = fmap Tag ["box_2", "box_3", "box_4_1"] , iLink = Just "Haste['toRoles']()" } , nfiUnit = SingleUnit "Full-time equivalent" } , NumberFI { nfiDescriptor = defaultFIDescriptor { iLabel = Just "Data consumer" , iTags = [Tag "box_3"] , iLink = Just "Haste['toRoles']()" } , nfiUnit = SingleUnit "Full-time equivalent" } , NumberFI { nfiDescriptor = defaultFIDescriptor { iLabel = Just "Data curator" , iTags = fmap Tag ["box_2", "box_3", "box_4_1", "box_5_i", "box_5_e", "box_6"] , iLink = Just "Haste['toRoles']()" } , nfiUnit = SingleUnit "Full-time equivalent" } , NumberFI { nfiDescriptor = defaultFIDescriptor { iLabel = Just "Data custodian" , iTags = fmap Tag ["box_4_1", "box_5_i", "box_5_e"] , iLink = Just "Haste['toRoles']()" } , nfiUnit = SingleUnit "Full-time equivalent" } , NumberFI { nfiDescriptor = defaultFIDescriptor { iLabel = Just "Data steward" , iTags = fmap Tag ["box_1", "box_2", "box_3", "box_4_1", "box_5_i", "box_5_e", "box_6"] , iLink = Just "Haste['toRoles']()" } , nfiUnit = SingleUnit "Full-time equivalent" } , NumberFI { nfiDescriptor = defaultFIDescriptor { iLabel = Just "Data manager" , iTags = fmap Tag ["box_1", "box_2", "box_4_1", "box_5_i", "box_5_e", "box_6"] , iLink = Just "Haste['toRoles']()" } , nfiUnit = SingleUnit "Full-time equivalent" } ] }
DataStewardshipPortal/ds-elixir-cz
FormStructure/Chapter7.hs
Haskell
apache-2.0
3,323
import Data.Matrix (matrix, inverse, nrows, multStd, toList) import Data.Ratio ((%)) recursionMatrix n integerSequence = matrix n n (\(i,j) -> integerSequence !! (i + j - 2) % 1) solutionMatrix n integerSequence = matrix n 1 (\(i,_) -> integerSequence !! (i + n - 1) % 1) targetInverse integerSequence = (case biggestInverse of Right m -> m) where biggestInverse = last $ takeWhile isRight allInverses where allInverses = map (\n -> inverse $ recursionMatrix n integerSequence) [1..] allSolutions = map (`solutionMatrix` integerSequence) [1..] recursion integerSequence = toList $ multStd inverseMatrix (solutionMatrix matrixSize integerSequence) where inverseMatrix = targetInverse integerSequence matrixSize = nrows inverseMatrix isRight (Right _) = True isRight (Left _) = False -- Conjecture: -- A320099 -- 103*a(n-1) + 1063*a(n-2) - 1873*a(n-3) - 20274*a(n-4) + 44071*a(n-5) - 10365*a(n-6) - 20208*a(n-7) + 5959*a(n-8) + 2300*a(n-9) - 500*a(n-10) # for n > 10
peterokagey/haskellOEIS
src/Sandbox/RecursionFinder.hs
Haskell
apache-2.0
984
import Data.Char (toUpper) main :: IO Bool main = putStrLn "Is green your favorite color?" >> getLine >>= (\input -> return ((toUpper . head $ input) == 'Y'))
EricYT/Haskell
src/real_haskell/chapter-7/return1.hs
Haskell
apache-2.0
174
module Data.GitParser (module Data.GitParser.Parser ,module Data.GitParser.Types ,module Data.GitParser.Repo) where import Data.GitParser.Repo import Data.GitParser.Types import Data.GitParser.Parser
jamessanders/gitparser
src/Data/GitParser.hs
Haskell
bsd-2-clause
212
-- -- Copyright (c) 2013, Carl Joachim Svenn -- 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 Game.Run.Iteration ( iterationShowFont, ) where import MyPrelude import Game import Game.Run.RunWorld import Font import OpenGL import OpenGL.Helpers -------------------------------------------------------------------------------- -- demonstrate Font iterationShowFont :: Iteration' RunWorld iterationShowFont = makeIteration' $ \run -> do -- output run' <- outputShowFont run let s = (0.5, 0.3) iteration' (iterationShowFont' s) run' iterationShowFont' :: (Float, Float) -> Iteration' RunWorld iterationShowFont' s = defaultIteration s outputShowFont' $ defaultStep noDo $ \s run b -> do keysTouchHandlePointTouched (run, b, [iterationShowFont' s]) $ \s' -> (run, b, [iterationShowFont' s']) -------------------------------------------------------------------------------- -- output outputShowFont :: RunWorld -> MEnv' RunWorld outputShowFont run = do io $ putStrLn "iterationShowFont" return run outputShowFont' :: (Float, Float) -> RunWorld -> () -> MEnv' ((Float, Float), RunWorld, ()) outputShowFont' pos@(x, y) run b = do -- setup Scene run' <- beginRunScene run fontshade <- resourceFontShade fontdata <- resourceFontData io $ do glDisable gl_CULL_FACE -- draw text to Screen let proj2D = sceneProj2D $ runScene run' fontShade fontshade 1.0 proj2D fontDrawDefault fontshade fontdata (valueFontSize * shapeHth (sceneShape (runScene run))) valueFontColor fontDraw2DCentered fontshade fontdata x y valueFontText glEnable gl_CULL_FACE return (pos, run', b) where valueFontSize = 0.04 valueFontColor = makeFontColorFloat 1.0 1.0 1.0 1.0 valueFontText = "Haskell inside!" beginRunScene :: RunWorld -> MEnv' RunWorld beginRunScene run = do (wth, hth) <- screenSize fbo <- screenFBO io $ do -- setup GL glBindFramebuffer gl_FRAMEBUFFER fbo glViewport 0 0 (fI wth) (fI hth) glClear $ gl_COLOR_BUFFER_BIT .|. gl_DEPTH_BUFFER_BIT .|. gl_STENCIL_BUFFER_BIT -- update Scene return run { runScene = makeScene wth hth }
karamellpelle/MEnv
source/Game/Run/Iteration.hs
Haskell
bsd-2-clause
3,701
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Text (pack, strip) import STC main :: IO () main = do token <- readFile "telegram.token" telegramBotServer . strip $ pack token
EleDiaz/StoryTellerChat
app/Main.hs
Haskell
bsd-3-clause
220
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Antialiasing -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- This module corresponds to section 3.2 (Antialiasing) of the OpenGL 1.5 -- specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Antialiasing ( sampleBuffers, samples, multisample, subpixelBits ) where import Graphics.Rendering.OpenGL.GL.Capability ( EnableCap(CapMultisample), makeCapability ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLsizei, Capability ) import Graphics.Rendering.OpenGL.GL.QueryUtils ( GetPName(GetSampleBuffers,GetSamples,GetSubpixelBits), getSizei1 ) import Graphics.Rendering.OpenGL.GL.StateVar ( GettableStateVar, makeGettableStateVar, StateVar ) -------------------------------------------------------------------------------- sampleBuffers :: GettableStateVar GLsizei sampleBuffers = antialiasingInfo GetSampleBuffers samples :: GettableStateVar GLsizei samples = antialiasingInfo GetSamples multisample :: StateVar Capability multisample = makeCapability CapMultisample subpixelBits :: GettableStateVar GLsizei subpixelBits = antialiasingInfo GetSubpixelBits antialiasingInfo :: GetPName -> GettableStateVar GLsizei antialiasingInfo = makeGettableStateVar . getSizei1 id
FranklinChen/hugs98-plus-Sep2006
packages/OpenGL/Graphics/Rendering/OpenGL/GL/Antialiasing.hs
Haskell
bsd-3-clause
1,563
{-# LANGUAGE TypeOperators #-} -- | -- Module : Data.OI.IO -- Copyright : (c) Nobuo Yamashita 2011-2016 -- License : BSD3 -- Author : Nobuo Yamashita -- Maintainer : [email protected] -- Stability : experimental -- module Data.OI.IO ( -- * Interaction enable to handle I/O error (:~>) -- * I/O oprations ,openFile ,hIsClosed ,hIsEOF ,hGetLine ,hClose ,hPutStrLn ,isEOF ,getLine ,putStrLn ) where import Data.OI.Internal import System.IO (IOMode(..),Handle) import qualified System.IO as IO import System.FilePath import Prelude hiding (getLine,putStrLn) type a :~> b = OI (IOResult a) -> IOResult b infixr 0 :~> openFile :: FilePath -> IOMode -> Handle :~> Handle openFile = (iooi' .) . IO.openFile hIsClosed :: IO.Handle -> Bool :~> Bool hIsClosed = iooi' . IO.hIsClosed hIsEOF :: IO.Handle -> Bool :~> Bool hIsEOF = iooi' . IO.hIsEOF hGetLine :: IO.Handle -> String :~> String hGetLine = iooi' . IO.hGetLine hClose :: IO.Handle -> () :~> () hClose = iooi' . IO.hClose hPutStrLn :: IO.Handle -> String -> () :~> () hPutStrLn = (iooi' .) . IO.hPutStrLn isEOF :: Bool :~> Bool isEOF = iooi' IO.isEOF getLine :: String :~> String getLine = iooi' IO.getLine putStrLn :: String -> () :~> () putStrLn = iooi' . IO.putStrLn
nobsun/oi
src/Data/OI/IO.hs
Haskell
bsd-3-clause
1,278
{-# LANGUAGE UnicodeSyntax #-} module DB.Create where import Database.HDBC (run, commit) import DB.Base createDb ∷ FilePath → IO () createDb dbName = do conn ← connect dbName run conn ("CREATE TABLE IF NOT EXISTS tags " ++ "(id INTEGER PRIMARY KEY," ++ " name VARCHAR NOT NULL UNIQUE)") [] -- length -- mtime, ctime, atime -- inode (int) run conn ("CREATE TABLE IF NOT EXISTS files " ++ "(id INTEGER PRIMARY KEY," ++ " name VARCHAR NOT NULL UNIQUE," ++ " contents BLOB NOT NULL)") [] run conn ("CREATE TABLE IF NOT EXISTS files_tags " ++ "(id INTEGER PRIMARY KEY," ++ " file_id INTEGER NOT NULL REFERENCES files," ++ " tag_id INTEGER NOT NULL REFERENCES tags," ++ " CONSTRAINT unique_file_tag UNIQUE (file_id, tag_id))") [] commit conn disconnect conn {- dbStuff ∷ String → IO () dbStuff dbFileName = do createDb dbFileName conn ← connectSqlite3 dbFileName -- addSomeData conn -- viewData conn disconnect conn -}
marklar/TagFS
src/DB/Create.hs
Haskell
bsd-3-clause
1,115
{-# LANGUAGE FlexibleContexts #-} module DataAnalysis04 where import Data.Convertible (Convertible) import Data.List (genericIndex, genericLength, genericTake) import Database.HDBC (SqlValue, disconnect, fromSql, quickQuery') import Database.HDBC.Sqlite3 (connectSqlite3) import DataAnalysis02 (average) readSqlColumn :: Convertible SqlValue a => [[SqlValue]] -> Integer -> [a] readSqlColumn sqlResult index = map (fromSql . (`genericIndex` index)) sqlResult queryDatabase :: FilePath -> String -> IO [[SqlValue]] queryDatabase databaseFile sqlQuery = do conn <- connectSqlite3 databaseFile result <- quickQuery' conn sqlQuery [] disconnect conn return result pullStockClosingPrices :: FilePath -> String -> IO [(Double, Double)] pullStockClosingPrices databaseFile database = do sqlResult <- queryDatabase databaseFile ("SELECT rowid, adjclose FROM " ++ database) return $ zip (reverse $ readSqlColumn sqlResult 0) (readSqlColumn sqlResult 1) percentChange :: Double -> Double -> Double percentChange value first = 100 * (value - first) / first applyPercentChangeToData :: [(Double, Double)] -> [(Double, Double)] applyPercentChangeToData dataset = zip indices scaledData where (_, first) = last dataset indices = reverse [1.0 .. genericLength dataset] scaledData = map (\(_, value) -> percentChange value first) dataset movingAverage :: [Double] -> Integer -> [Double] movingAverage values window | window >= genericLength values = [average values] | otherwise = average (genericTake window values) : movingAverage (tail values) window applyMovingAverageToData :: [(Double, Double)] -> Integer -> [(Double, Double)] applyMovingAverageToData dataset window = zip [fromIntegral window..] (movingAverage (map snd (reverse dataset)) window) pullLatitudeLongitude :: FilePath -> String -> IO [(Double, Double)] pullLatitudeLongitude databaseFile database = do sqlResult <- queryDatabase databaseFile ("SELECT latitude, longitude FROM " ++ database) return $ zip (readSqlColumn sqlResult 1) (readSqlColumn sqlResult 0)
mrordinaire/data-analysis
src/DataAnalysis04.hs
Haskell
bsd-3-clause
2,145
module Graphics.UI.Font ( module Graphics.UI.Font.TextureAtlas , module Graphics.UI.Font.TextureFont , module Graphics.UI.Font.TextureGlyph , module Graphics.UI.Font.Markup , module Graphics.UI.Font.FontManager ) where import Graphics.UI.Font.TextureAtlas import Graphics.UI.Font.TextureFont import Graphics.UI.Font.TextureGlyph import Graphics.UI.Font.Markup import Graphics.UI.Font.FontManager
christiaanb/glfont
src/Graphics/UI/Font.hs
Haskell
bsd-3-clause
423
{-# LANGUAGE ForeignFunctionInterface, CPP #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.EXT.DirectStateAccess -- Copyright : (c) Sven Panne 2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- All raw functions and tokens from the EXT_direct_state_access extension not -- already in the OpenGL 3.1 core, see -- <http://www.opengl.org/registry/specs/EXT/direct_state_access.txt>. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.EXT.DirectStateAccess ( -- * Functions glClientAttribDefault, glPushClientAttribDefault, glMatrixLoadf, glMatrixLoadd, glMatrixMultf, glMatrixMultd, glMatrixLoadIdentity, glMatrixRotatef, glMatrixRotated, glMatrixScalef, glMatrixScaled, glMatrixTranslatef, glMatrixTranslated, glMatrixOrtho, glMatrixFrustum, glMatrixPush, glMatrixPop, glTextureParameteri, glTextureParameteriv, glTextureParameterf, glTextureParameterfv, glTextureImage1D, glTextureImage2D, glTextureSubImage1D, glTextureSubImage2D, glCopyTextureImage1D, glCopyTextureImage2D, glCopyTextureSubImage1D, glCopyTextureSubImage2D, glGetTextureImage, glGetTextureParameterfv, glGetTextureParameteriv, glGetTextureLevelParameterfv, glGetTextureLevelParameteriv, glTextureImage3D, glTextureSubImage3D, glCopyTextureSubImage3D, glBindMultiTexture, glMultiTexCoordPointer, glMultiTexEnvf, glMultiTexEnvfv, glMultiTexEnvi, glMultiTexEnviv, glMultiTexGend, glMultiTexGendv, glMultiTexGenf, glMultiTexGenfv, glMultiTexGeni, glMultiTexGeniv, glGetMultiTexEnvfv, glGetMultiTexEnviv, glGetMultiTexGendv, glGetMultiTexGenfv, glGetMultiTexGeniv, glMultiTexParameteri, glMultiTexParameteriv, glMultiTexParameterf, glMultiTexParameterfv, glMultiTexImage1D, glMultiTexImage2D, glMultiTexSubImage1D, glMultiTexSubImage2D, glCopyMultiTexImage1D, glCopyMultiTexImage2D, glCopyMultiTexSubImage1D, glCopyMultiTexSubImage2D, glGetMultiTexImage, glGetMultiTexParameterfv, glGetMultiTexParameteriv, glGetMultiTexLevelParameterfv, glGetMultiTexLevelParameteriv, glMultiTexImage3D, glMultiTexSubImage3D, glCopyMultiTexSubImage3D, glEnableClientStateIndexed, glDisableClientStateIndexed, glGetFloatIndexedv, glGetDoubleIndexedv, glGetPointerIndexedv, glEnableIndexed, glDisableIndexed, glIsEnabledIndexed, glGetIntegerIndexedv, glGetBooleanIndexedv, glNamedProgramString, glNamedProgramLocalParameter4d, glNamedProgramLocalParameter4dv, glNamedProgramLocalParameter4f, glNamedProgramLocalParameter4fv, glGetNamedProgramLocalParameterdv, glGetNamedProgramLocalParameterfv, glGetNamedProgramiv, glGetNamedProgramString, glCompressedTextureImage3D, glCompressedTextureImage2D, glCompressedTextureImage1D, glCompressedTextureSubImage3D, glCompressedTextureSubImage2D, glCompressedTextureSubImage1D, glGetCompressedTextureImage, glCompressedMultiTexImage3D, glCompressedMultiTexImage2D, glCompressedMultiTexImage1D, glCompressedMultiTexSubImage3D, glCompressedMultiTexSubImage2D, glCompressedMultiTexSubImage1D, glGetCompressedMultiTexImage, glMatrixLoadTransposef, glMatrixLoadTransposed, glMatrixMultTransposef, glMatrixMultTransposed, glNamedBufferData, glNamedBufferSubData, glMapNamedBuffer, glUnmapNamedBuffer, glGetNamedBufferParameteriv, glGetNamedBufferPointerv, glGetNamedBufferSubData, glProgramUniform1f, glProgramUniform2f, glProgramUniform3f, glProgramUniform4f, glProgramUniform1i, glProgramUniform2i, glProgramUniform3i, glProgramUniform4i, glProgramUniform1fv, glProgramUniform2fv, glProgramUniform3fv, glProgramUniform4fv, glProgramUniform1iv, glProgramUniform2iv, glProgramUniform3iv, glProgramUniform4iv, glProgramUniformMatrix2fv, glProgramUniformMatrix3fv, glProgramUniformMatrix4fv, glProgramUniformMatrix2x3fv, glProgramUniformMatrix3x2fv, glProgramUniformMatrix2x4fv, glProgramUniformMatrix4x2fv, glProgramUniformMatrix3x4fv, glProgramUniformMatrix4x3fv, glTextureBuffer, glMultiTexBuffer, glTextureParameterIiv, glTextureParameterIuiv, glGetTextureParameterIiv, glGetTextureParameterIuiv, glMultiTexParameterIiv, glMultiTexParameterIuiv, glGetMultiTexParameterIiv, glGetMultiTexParameterIuiv, glProgramUniform1ui, glProgramUniform2ui, glProgramUniform3ui, glProgramUniform4ui, glProgramUniform1uiv, glProgramUniform2uiv, glProgramUniform3uiv, glProgramUniform4uiv, glNamedProgramLocalParameters4fv, glNamedProgramLocalParameterI4i, glNamedProgramLocalParameterI4iv, glNamedProgramLocalParametersI4iv, glNamedProgramLocalParameterI4ui, glNamedProgramLocalParameterI4uiv, glNamedProgramLocalParametersI4uiv, glGetNamedProgramLocalParameterIiv, glGetNamedProgramLocalParameterIuiv, glNamedRenderbufferStorage, glGetNamedRenderbufferParameteriv, glNamedRenderbufferStorageMultisample, glNamedRenderbufferStorageMultisampleCoverage, glCheckNamedFramebufferStatus, glNamedFramebufferTexture1D, glNamedFramebufferTexture2D, glNamedFramebufferTexture3D, glNamedFramebufferRenderbuffer, glGetNamedFramebufferAttachmentParameteriv, glGenerateTextureMipmap, glGenerateMultiTexMipmap, glFramebufferDrawBuffer, glFramebufferDrawBuffers, glFramebufferReadBuffer, glGetFramebufferParameteriv, glNamedFramebufferTexture, glNamedFramebufferTextureLayer, glNamedFramebufferTextureFace, glTextureRenderbuffer, glMultiTexRenderbuffer, -- * Tokens gl_PROGRAM_MATRIX, gl_TRANSPOSE_PROGRAM_MATRIX, gl_PROGRAM_MATRIX_STACK_DEPTH ) where import Foreign.C.Types import Foreign.Ptr import Graphics.Rendering.OpenGL.Raw.ARB.FramebufferNoAttachments import Graphics.Rendering.OpenGL.Raw.ARB.SeparateShaderObjects import Graphics.Rendering.OpenGL.Raw.Core31.Types import Graphics.Rendering.OpenGL.Raw.Extensions #include "HsOpenGLRaw.h" extensionNameString :: String extensionNameString = "GL_EXT_direct_state_access" EXTENSION_ENTRY(dyn_glClientAttribDefault,ptr_glClientAttribDefault,"glClientAttribDefault",glClientAttribDefault,GLbitfield -> IO ()) EXTENSION_ENTRY(dyn_glPushClientAttribDefault,ptr_glPushClientAttribDefault,"glPushClientAttribDefault",glPushClientAttribDefault,GLbitfield -> IO ()) EXTENSION_ENTRY(dyn_glMatrixLoadf,ptr_glMatrixLoadf,"glMatrixLoadf",glMatrixLoadf,GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMatrixLoadd,ptr_glMatrixLoadd,"glMatrixLoadd",glMatrixLoadd,GLenum -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixMultf,ptr_glMatrixMultf,"glMatrixMultf",glMatrixMultf,GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMatrixMultd,ptr_glMatrixMultd,"glMatrixMultd",glMatrixMultd,GLenum -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixLoadIdentity,ptr_glMatrixLoadIdentity,"glMatrixLoadIdentity",glMatrixLoadIdentity,GLenum -> IO ()) EXTENSION_ENTRY(dyn_glMatrixRotatef,ptr_glMatrixRotatef,"glMatrixRotatef",glMatrixRotatef,GLenum -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMatrixRotated,ptr_glMatrixRotated,"glMatrixRotated",glMatrixRotated,GLenum -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixScalef,ptr_glMatrixScalef,"glMatrixScalef",glMatrixScalef,GLenum -> GLfloat -> GLfloat -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMatrixScaled,ptr_glMatrixScaled,"glMatrixScaled",glMatrixScaled,GLenum -> GLdouble -> GLdouble -> GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixTranslatef,ptr_glMatrixTranslatef,"glMatrixTranslatef",glMatrixTranslatef,GLenum -> GLfloat -> GLfloat -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMatrixTranslated,ptr_glMatrixTranslated,"glMatrixTranslated",glMatrixTranslated,GLenum -> GLdouble -> GLdouble -> GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixOrtho,ptr_glMatrixOrtho,"glMatrixOrtho",glMatrixOrtho,GLenum -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixFrustum,ptr_glMatrixFrustum,"glMatrixFrustum",glMatrixFrustum,GLenum -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixPush,ptr_glMatrixPush,"glMatrixPush",glMatrixPush,GLenum -> IO ()) EXTENSION_ENTRY(dyn_glMatrixPop,ptr_glMatrixPop,"glMatrixPop",glMatrixPop,GLenum -> IO ()) EXTENSION_ENTRY(dyn_glTextureParameteri,ptr_glTextureParameteri,"glTextureParameteri",glTextureParameteri,GLuint -> GLenum -> GLenum -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glTextureParameteriv,ptr_glTextureParameteriv,"glTextureParameteriv",glTextureParameteriv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glTextureParameterf,ptr_glTextureParameterf,"glTextureParameterf",glTextureParameterf,GLuint -> GLenum -> GLenum -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glTextureParameterfv,ptr_glTextureParameterfv,"glTextureParameterfv",glTextureParameterfv,GLuint -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glTextureImage1D,ptr_glTextureImage1D,"glTextureImage1D",glTextureImage1D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glTextureImage2D,ptr_glTextureImage2D,"glTextureImage2D",glTextureImage2D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glTextureSubImage1D,ptr_glTextureSubImage1D,"glTextureSubImage1D",glTextureSubImage1D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glTextureSubImage2D,ptr_glTextureSubImage2D,"glTextureSubImage2D",glTextureSubImage2D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCopyTextureImage1D,ptr_glCopyTextureImage1D,"glCopyTextureImage1D",glCopyTextureImage1D,GLuint -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glCopyTextureImage2D,ptr_glCopyTextureImage2D,"glCopyTextureImage2D",glCopyTextureImage2D,GLuint -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glCopyTextureSubImage1D,ptr_glCopyTextureSubImage1D,"glCopyTextureSubImage1D",glCopyTextureSubImage1D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glCopyTextureSubImage2D,ptr_glCopyTextureSubImage2D,"glCopyTextureSubImage2D",glCopyTextureSubImage2D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glGetTextureImage,ptr_glGetTextureImage,"glGetTextureImage",glGetTextureImage,GLuint -> GLenum -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glGetTextureParameterfv,ptr_glGetTextureParameterfv,"glGetTextureParameterfv",glGetTextureParameterfv,GLuint -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetTextureParameteriv,ptr_glGetTextureParameteriv,"glGetTextureParameteriv",glGetTextureParameteriv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetTextureLevelParameterfv,ptr_glGetTextureLevelParameterfv,"glGetTextureLevelParameterfv",glGetTextureLevelParameterfv,GLuint -> GLenum -> GLint -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetTextureLevelParameteriv,ptr_glGetTextureLevelParameteriv,"glGetTextureLevelParameteriv",glGetTextureLevelParameteriv,GLuint -> GLenum -> GLint -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glTextureImage3D,ptr_glTextureImage3D,"glTextureImage3D",glTextureImage3D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glTextureSubImage3D,ptr_glTextureSubImage3D,"glTextureSubImage3D",glTextureSubImage3D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCopyTextureSubImage3D,ptr_glCopyTextureSubImage3D,"glCopyTextureSubImage3D",glCopyTextureSubImage3D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glBindMultiTexture,ptr_glBindMultiTexture,"glBindMultiTexture",glBindMultiTexture,GLenum -> GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexCoordPointer,ptr_glMultiTexCoordPointer,"glMultiTexCoordPointer",glMultiTexCoordPointer,GLenum -> GLint -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexEnvf,ptr_glMultiTexEnvf,"glMultiTexEnvf",glMultiTexEnvf,GLenum -> GLenum -> GLenum -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexEnvfv,ptr_glMultiTexEnvfv,"glMultiTexEnvfv",glMultiTexEnvfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexEnvi,ptr_glMultiTexEnvi,"glMultiTexEnvi",glMultiTexEnvi,GLenum -> GLenum -> GLenum -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexEnviv,ptr_glMultiTexEnviv,"glMultiTexEnviv",glMultiTexEnviv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexGend,ptr_glMultiTexGend,"glMultiTexGend",glMultiTexGend,GLenum -> GLenum -> GLenum -> GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexGendv,ptr_glMultiTexGendv,"glMultiTexGendv",glMultiTexGendv,GLenum -> GLenum -> GLenum -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexGenf,ptr_glMultiTexGenf,"glMultiTexGenf",glMultiTexGenf,GLenum -> GLenum -> GLenum -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexGenfv,ptr_glMultiTexGenfv,"glMultiTexGenfv",glMultiTexGenfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexGeni,ptr_glMultiTexGeni,"glMultiTexGeni",glMultiTexGeni,GLenum -> GLenum -> GLenum -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexGeniv,ptr_glMultiTexGeniv,"glMultiTexGeniv",glMultiTexGeniv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexEnvfv,ptr_glGetMultiTexEnvfv,"glGetMultiTexEnvfv",glGetMultiTexEnvfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexEnviv,ptr_glGetMultiTexEnviv,"glGetMultiTexEnviv",glGetMultiTexEnviv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexGendv,ptr_glGetMultiTexGendv,"glGetMultiTexGendv",glGetMultiTexGendv,GLenum -> GLenum -> GLenum -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexGenfv,ptr_glGetMultiTexGenfv,"glGetMultiTexGenfv",glGetMultiTexGenfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexGeniv,ptr_glGetMultiTexGeniv,"glGetMultiTexGeniv",glGetMultiTexGeniv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexParameteri,ptr_glMultiTexParameteri,"glMultiTexParameteri",glMultiTexParameteri,GLenum -> GLenum -> GLenum -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexParameteriv,ptr_glMultiTexParameteriv,"glMultiTexParameteriv",glMultiTexParameteriv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexParameterf,ptr_glMultiTexParameterf,"glMultiTexParameterf",glMultiTexParameterf,GLenum -> GLenum -> GLenum -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexParameterfv,ptr_glMultiTexParameterfv,"glMultiTexParameterfv",glMultiTexParameterfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexImage1D,ptr_glMultiTexImage1D,"glMultiTexImage1D",glMultiTexImage1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexImage2D,ptr_glMultiTexImage2D,"glMultiTexImage2D",glMultiTexImage2D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexSubImage1D,ptr_glMultiTexSubImage1D,"glMultiTexSubImage1D",glMultiTexSubImage1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexSubImage2D,ptr_glMultiTexSubImage2D,"glMultiTexSubImage2D",glMultiTexSubImage2D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCopyMultiTexImage1D,ptr_glCopyMultiTexImage1D,"glCopyMultiTexImage1D",glCopyMultiTexImage1D,GLenum -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glCopyMultiTexImage2D,ptr_glCopyMultiTexImage2D,"glCopyMultiTexImage2D",glCopyMultiTexImage2D,GLenum -> GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glCopyMultiTexSubImage1D,ptr_glCopyMultiTexSubImage1D,"glCopyMultiTexSubImage1D",glCopyMultiTexSubImage1D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glCopyMultiTexSubImage2D,ptr_glCopyMultiTexSubImage2D,"glCopyMultiTexSubImage2D",glCopyMultiTexSubImage2D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexImage,ptr_glGetMultiTexImage,"glGetMultiTexImage",glGetMultiTexImage,GLenum -> GLenum -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexParameterfv,ptr_glGetMultiTexParameterfv,"glGetMultiTexParameterfv",glGetMultiTexParameterfv,GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexParameteriv,ptr_glGetMultiTexParameteriv,"glGetMultiTexParameteriv",glGetMultiTexParameteriv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexLevelParameterfv,ptr_glGetMultiTexLevelParameterfv,"glGetMultiTexLevelParameterfv",glGetMultiTexLevelParameterfv,GLenum -> GLenum -> GLint -> GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexLevelParameteriv,ptr_glGetMultiTexLevelParameteriv,"glGetMultiTexLevelParameteriv",glGetMultiTexLevelParameteriv,GLenum -> GLenum -> GLint -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexImage3D,ptr_glMultiTexImage3D,"glMultiTexImage3D",glMultiTexImage3D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexSubImage3D,ptr_glMultiTexSubImage3D,"glMultiTexSubImage3D",glMultiTexSubImage3D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCopyMultiTexSubImage3D,ptr_glCopyMultiTexSubImage3D,"glCopyMultiTexSubImage3D",glCopyMultiTexSubImage3D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glEnableClientStateIndexed,ptr_glEnableClientStateIndexed,"glEnableClientStateIndexed",glEnableClientStateIndexed,GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glDisableClientStateIndexed,ptr_glDisableClientStateIndexed,"glDisableClientStateIndexed",glDisableClientStateIndexed,GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glGetFloatIndexedv,ptr_glGetFloatIndexedv,"glGetFloatIndexedv",glGetFloatIndexedv,GLenum -> GLuint -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetDoubleIndexedv,ptr_glGetDoubleIndexedv,"glGetDoubleIndexedv",glGetDoubleIndexedv,GLenum -> GLuint -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glGetPointerIndexedv,ptr_glGetPointerIndexedv,"glGetPointerIndexedv",glGetPointerIndexedv,GLenum -> GLuint -> Ptr (Ptr a) -> IO ()) EXTENSION_ENTRY(dyn_glEnableIndexed,ptr_glEnableIndexed,"glEnableIndexed",glEnableIndexed,GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glDisableIndexed,ptr_glDisableIndexed,"glDisableIndexed",glDisableIndexed,GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glIsEnabledIndexed,ptr_glIsEnabledIndexed,"glIsEnabledIndexed",glIsEnabledIndexed,GLenum -> GLuint -> IO GLboolean) EXTENSION_ENTRY(dyn_glGetIntegerIndexedv,ptr_glGetIntegerIndexedv,"glGetIntegerIndexedv",glGetIntegerIndexedv,GLenum -> GLuint -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetBooleanIndexedv,ptr_glGetBooleanIndexedv,"glGetBooleanIndexedv",glGetBooleanIndexedv,GLenum -> GLuint -> Ptr GLboolean -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramString,ptr_glNamedProgramString,"glNamedProgramString",glNamedProgramString,GLuint -> GLenum -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4d,ptr_glNamedProgramLocalParameter4d,"glNamedProgramLocalParameter4d",glNamedProgramLocalParameter4d,GLuint -> GLenum -> GLuint -> GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4dv,ptr_glNamedProgramLocalParameter4dv,"glNamedProgramLocalParameter4dv",glNamedProgramLocalParameter4dv,GLuint -> GLenum -> GLuint -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4f,ptr_glNamedProgramLocalParameter4f,"glNamedProgramLocalParameter4f",glNamedProgramLocalParameter4f,GLuint -> GLenum -> GLuint -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameter4fv,ptr_glNamedProgramLocalParameter4fv,"glNamedProgramLocalParameter4fv",glNamedProgramLocalParameter4fv,GLuint -> GLenum -> GLuint -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterdv,ptr_glGetNamedProgramLocalParameterdv,"glGetNamedProgramLocalParameterdv",glGetNamedProgramLocalParameterdv,GLuint -> GLenum -> GLuint -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterfv,ptr_glGetNamedProgramLocalParameterfv,"glGetNamedProgramLocalParameterfv",glGetNamedProgramLocalParameterfv,GLuint -> GLenum -> GLuint -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedProgramiv,ptr_glGetNamedProgramiv,"glGetNamedProgramiv",glGetNamedProgramiv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedProgramString,ptr_glGetNamedProgramString,"glGetNamedProgramString",glGetNamedProgramString,GLuint -> GLenum -> GLenum -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedTextureImage3D,ptr_glCompressedTextureImage3D,"glCompressedTextureImage3D",glCompressedTextureImage3D,GLuint -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedTextureImage2D,ptr_glCompressedTextureImage2D,"glCompressedTextureImage2D",glCompressedTextureImage2D,GLuint -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedTextureImage1D,ptr_glCompressedTextureImage1D,"glCompressedTextureImage1D",glCompressedTextureImage1D,GLuint -> GLenum -> GLint -> GLenum -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedTextureSubImage3D,ptr_glCompressedTextureSubImage3D,"glCompressedTextureSubImage3D",glCompressedTextureSubImage3D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedTextureSubImage2D,ptr_glCompressedTextureSubImage2D,"glCompressedTextureSubImage2D",glCompressedTextureSubImage2D,GLuint -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedTextureSubImage1D,ptr_glCompressedTextureSubImage1D,"glCompressedTextureSubImage1D",glCompressedTextureSubImage1D,GLuint -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glGetCompressedTextureImage,ptr_glGetCompressedTextureImage,"glGetCompressedTextureImage",glGetCompressedTextureImage,GLuint -> GLenum -> GLint -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedMultiTexImage3D,ptr_glCompressedMultiTexImage3D,"glCompressedMultiTexImage3D",glCompressedMultiTexImage3D,GLenum -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedMultiTexImage2D,ptr_glCompressedMultiTexImage2D,"glCompressedMultiTexImage2D",glCompressedMultiTexImage2D,GLenum -> GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedMultiTexImage1D,ptr_glCompressedMultiTexImage1D,"glCompressedMultiTexImage1D",glCompressedMultiTexImage1D,GLenum -> GLenum -> GLint -> GLenum -> GLsizei -> GLint -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedMultiTexSubImage3D,ptr_glCompressedMultiTexSubImage3D,"glCompressedMultiTexSubImage3D",glCompressedMultiTexSubImage3D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedMultiTexSubImage2D,ptr_glCompressedMultiTexSubImage2D,"glCompressedMultiTexSubImage2D",glCompressedMultiTexSubImage2D,GLenum -> GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glCompressedMultiTexSubImage1D,ptr_glCompressedMultiTexSubImage1D,"glCompressedMultiTexSubImage1D",glCompressedMultiTexSubImage1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLenum -> GLsizei -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glGetCompressedMultiTexImage,ptr_glGetCompressedMultiTexImage,"glGetCompressedMultiTexImage",glGetCompressedMultiTexImage,GLenum -> GLenum -> GLint -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glMatrixLoadTransposef,ptr_glMatrixLoadTransposef,"glMatrixLoadTransposef",glMatrixLoadTransposef,GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMatrixLoadTransposed,ptr_glMatrixLoadTransposed,"glMatrixLoadTransposed",glMatrixLoadTransposed,GLenum -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glMatrixMultTransposef,ptr_glMatrixMultTransposef,"glMatrixMultTransposef",glMatrixMultTransposef,GLenum -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glMatrixMultTransposed,ptr_glMatrixMultTransposed,"glMatrixMultTransposed",glMatrixMultTransposed,GLenum -> Ptr GLdouble -> IO ()) EXTENSION_ENTRY(dyn_glNamedBufferData,ptr_glNamedBufferData,"glNamedBufferData",glNamedBufferData,GLuint -> GLsizeiptr -> Ptr a -> GLenum -> IO ()) EXTENSION_ENTRY(dyn_glNamedBufferSubData,ptr_glNamedBufferSubData,"glNamedBufferSubData",glNamedBufferSubData,GLuint -> GLintptr -> GLsizeiptr -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glMapNamedBuffer,ptr_glMapNamedBuffer,"glMapNamedBuffer",glMapNamedBuffer,GLuint -> GLenum -> IO ()) EXTENSION_ENTRY(dyn_glUnmapNamedBuffer,ptr_glUnmapNamedBuffer,"glUnmapNamedBuffer",glUnmapNamedBuffer,GLuint -> IO GLboolean) EXTENSION_ENTRY(dyn_glGetNamedBufferParameteriv,ptr_glGetNamedBufferParameteriv,"glGetNamedBufferParameteriv",glGetNamedBufferParameteriv,GLuint -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedBufferPointerv,ptr_glGetNamedBufferPointerv,"glGetNamedBufferPointerv",glGetNamedBufferPointerv,GLuint -> GLenum -> Ptr (Ptr a) -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedBufferSubData,ptr_glGetNamedBufferSubData,"glGetNamedBufferSubData",glGetNamedBufferSubData,GLuint -> GLintptr -> GLsizeiptr -> Ptr a -> IO ()) EXTENSION_ENTRY(dyn_glTextureBuffer,ptr_glTextureBuffer,"glTextureBuffer",glTextureBuffer,GLuint -> GLenum -> GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexBuffer,ptr_glMultiTexBuffer,"glMultiTexBuffer",glMultiTexBuffer,GLenum -> GLenum -> GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glTextureParameterIiv,ptr_glTextureParameterIiv,"glTextureParameterIiv",glTextureParameterIiv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glTextureParameterIuiv,ptr_glTextureParameterIuiv,"glTextureParameterIuiv",glTextureParameterIuiv,GLuint -> GLenum -> GLenum -> Ptr GLuint -> IO ()) EXTENSION_ENTRY(dyn_glGetTextureParameterIiv,ptr_glGetTextureParameterIiv,"glGetTextureParameterIiv",glGetTextureParameterIiv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetTextureParameterIuiv,ptr_glGetTextureParameterIuiv,"glGetTextureParameterIuiv",glGetTextureParameterIuiv,GLuint -> GLenum -> GLenum -> Ptr GLuint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexParameterIiv,ptr_glMultiTexParameterIiv,"glMultiTexParameterIiv",glMultiTexParameterIiv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexParameterIuiv,ptr_glMultiTexParameterIuiv,"glMultiTexParameterIuiv",glMultiTexParameterIuiv,GLenum -> GLenum -> GLenum -> Ptr GLuint -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexParameterIiv,ptr_glGetMultiTexParameterIiv,"glGetMultiTexParameterIiv",glGetMultiTexParameterIiv,GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetMultiTexParameterIuiv,ptr_glGetMultiTexParameterIuiv,"glGetMultiTexParameterIuiv",glGetMultiTexParameterIuiv,GLenum -> GLenum -> GLenum -> Ptr GLuint -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameters4fv,ptr_glNamedProgramLocalParameters4fv,"glNamedProgramLocalParameters4fv",glNamedProgramLocalParameters4fv,GLuint -> GLenum -> GLuint -> GLsizei -> Ptr GLfloat -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4i,ptr_glNamedProgramLocalParameterI4i,"glNamedProgramLocalParameterI4i",glNamedProgramLocalParameterI4i,GLuint -> GLenum -> GLuint -> GLint -> GLint -> GLint -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4iv,ptr_glNamedProgramLocalParameterI4iv,"glNamedProgramLocalParameterI4iv",glNamedProgramLocalParameterI4iv,GLuint -> GLenum -> GLuint -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParametersI4iv,ptr_glNamedProgramLocalParametersI4iv,"glNamedProgramLocalParametersI4iv",glNamedProgramLocalParametersI4iv,GLuint -> GLenum -> GLuint -> GLsizei -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4ui,ptr_glNamedProgramLocalParameterI4ui,"glNamedProgramLocalParameterI4ui",glNamedProgramLocalParameterI4ui,GLuint -> GLenum -> GLuint -> GLuint -> GLuint -> GLuint -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParameterI4uiv,ptr_glNamedProgramLocalParameterI4uiv,"glNamedProgramLocalParameterI4uiv",glNamedProgramLocalParameterI4uiv,GLuint -> GLenum -> GLuint -> Ptr GLuint -> IO ()) EXTENSION_ENTRY(dyn_glNamedProgramLocalParametersI4uiv,ptr_glNamedProgramLocalParametersI4uiv,"glNamedProgramLocalParametersI4uiv",glNamedProgramLocalParametersI4uiv,GLuint -> GLenum -> GLuint -> GLsizei -> Ptr GLuint -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterIiv,ptr_glGetNamedProgramLocalParameterIiv,"glGetNamedProgramLocalParameterIiv",glGetNamedProgramLocalParameterIiv,GLuint -> GLenum -> GLuint -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedProgramLocalParameterIuiv,ptr_glGetNamedProgramLocalParameterIuiv,"glGetNamedProgramLocalParameterIuiv",glGetNamedProgramLocalParameterIuiv,GLuint -> GLenum -> GLuint -> Ptr GLuint -> IO ()) EXTENSION_ENTRY(dyn_glNamedRenderbufferStorage,ptr_glNamedRenderbufferStorage,"glNamedRenderbufferStorage",glNamedRenderbufferStorage,GLuint -> GLenum -> GLsizei -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedRenderbufferParameteriv,ptr_glGetNamedRenderbufferParameteriv,"glGetNamedRenderbufferParameteriv",glGetNamedRenderbufferParameteriv,GLuint -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedRenderbufferStorageMultisample,ptr_glNamedRenderbufferStorageMultisample,"glNamedRenderbufferStorageMultisample",glNamedRenderbufferStorageMultisample,GLuint -> GLsizei -> GLenum -> GLsizei -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glNamedRenderbufferStorageMultisampleCoverage,ptr_glNamedRenderbufferStorageMultisampleCoverage,"glNamedRenderbufferStorageMultisampleCoverage",glNamedRenderbufferStorageMultisampleCoverage,GLuint -> GLsizei -> GLsizei -> GLenum -> GLsizei -> GLsizei -> IO ()) EXTENSION_ENTRY(dyn_glCheckNamedFramebufferStatus,ptr_glCheckNamedFramebufferStatus,"glCheckNamedFramebufferStatus",glCheckNamedFramebufferStatus,GLuint -> GLenum -> IO GLenum) EXTENSION_ENTRY(dyn_glNamedFramebufferTexture1D,ptr_glNamedFramebufferTexture1D,"glNamedFramebufferTexture1D",glNamedFramebufferTexture1D,GLuint -> GLenum -> GLenum -> GLuint -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedFramebufferTexture2D,ptr_glNamedFramebufferTexture2D,"glNamedFramebufferTexture2D",glNamedFramebufferTexture2D,GLuint -> GLenum -> GLenum -> GLuint -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedFramebufferTexture3D,ptr_glNamedFramebufferTexture3D,"glNamedFramebufferTexture3D",glNamedFramebufferTexture3D,GLuint -> GLenum -> GLenum -> GLuint -> GLint -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedFramebufferRenderbuffer,ptr_glNamedFramebufferRenderbuffer,"glNamedFramebufferRenderbuffer",glNamedFramebufferRenderbuffer,GLuint -> GLenum -> GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glGetNamedFramebufferAttachmentParameteriv,ptr_glGetNamedFramebufferAttachmentParameteriv,"glGetNamedFramebufferAttachmentParameteriv",glGetNamedFramebufferAttachmentParameteriv,GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) EXTENSION_ENTRY(dyn_glGenerateTextureMipmap,ptr_glGenerateTextureMipmap,"glGenerateTextureMipmap",glGenerateTextureMipmap,GLuint -> GLenum -> IO ()) EXTENSION_ENTRY(dyn_glGenerateMultiTexMipmap,ptr_glGenerateMultiTexMipmap,"glGenerateMultiTexMipmap",glGenerateMultiTexMipmap,GLenum -> GLenum -> IO ()) EXTENSION_ENTRY(dyn_glFramebufferDrawBuffer,ptr_glFramebufferDrawBuffer,"glFramebufferDrawBuffer",glFramebufferDrawBuffer,GLuint -> GLenum -> IO ()) EXTENSION_ENTRY(dyn_glFramebufferDrawBuffers,ptr_glFramebufferDrawBuffers,"glFramebufferDrawBuffers",glFramebufferDrawBuffers,GLuint -> GLsizei -> Ptr GLenum -> IO ()) EXTENSION_ENTRY(dyn_glFramebufferReadBuffer,ptr_glFramebufferReadBuffer,"glFramebufferReadBuffer",glFramebufferReadBuffer,GLuint -> GLenum -> IO ()) EXTENSION_ENTRY(dyn_glNamedFramebufferTexture,ptr_glNamedFramebufferTexture,"glNamedFramebufferTexture",glNamedFramebufferTexture,GLuint -> GLenum -> GLuint -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedFramebufferTextureLayer,ptr_glNamedFramebufferTextureLayer,"glNamedFramebufferTextureLayer",glNamedFramebufferTextureLayer,GLuint -> GLenum -> GLuint -> GLint -> GLint -> IO ()) EXTENSION_ENTRY(dyn_glNamedFramebufferTextureFace,ptr_glNamedFramebufferTextureFace,"glNamedFramebufferTextureFace",glNamedFramebufferTextureFace,GLuint -> GLenum -> GLuint -> GLint -> GLenum -> IO ()) EXTENSION_ENTRY(dyn_glTextureRenderbuffer,ptr_glTextureRenderbuffer,"glTextureRenderbuffer",glTextureRenderbuffer,GLuint -> GLenum -> GLuint -> IO ()) EXTENSION_ENTRY(dyn_glMultiTexRenderbuffer,ptr_glMultiTexRenderbuffer,"glMultiTexRenderbuffer",glMultiTexRenderbuffer,GLenum -> GLenum -> GLuint -> IO ()) gl_PROGRAM_MATRIX :: GLenum gl_PROGRAM_MATRIX = 0x8E2D gl_TRANSPOSE_PROGRAM_MATRIX :: GLenum gl_TRANSPOSE_PROGRAM_MATRIX = 0x8E2E gl_PROGRAM_MATRIX_STACK_DEPTH :: GLenum gl_PROGRAM_MATRIX_STACK_DEPTH = 0x8E2F
mfpi/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/EXT/DirectStateAccess.hs
Haskell
bsd-3-clause
34,735
module Plots ( -- * Core Library -- | Definitions of bounds, axis scale, orientation, -- legend, generic plot ,plot spec and so on. module Plots.Types -- | Definitions of theme, plots style, common themes, -- marker shapes, colour maps and sample maps. , module Plots.Themes -- * API -- | Data types and classes, definitions of -- plotable, bounds, axis labels, legends, -- diagram essentials and so on. , module Plots.API -- * Axis Library -- | Axis definition (r2Axis & polarAxis), aspect -- ratio and scaling. , module Plots.Axis -- | Grid lines and styles. , module Plots.Axis.Grid -- | Axis labels and tick labels . , module Plots.Axis.Labels -- | Rendering system for polar and r2 axis, and system -- for calculating bounds and scale. , module Plots.Axis.Render -- | Ticks properties and placement. , module Plots.Axis.Ticks -- | Colour bars. , module Plots.Axis.ColourBar -- * Plot Types -- | Scatter and bubble. -- Scatter and bubble plot api. , module Plots.Types.Scatter -- | Line, trail and path. -- Line plot, steps plot api & api for trail and path. , module Plots.Types.Line -- | Ribbon and area. -- Ribbon and area plot api. , module Plots.Types.Ribbon -- | Histogram. -- API for histogram. , module Plots.Types.Histogram -- | Parametric functions and vectors. -- Parametric plot and vectors api. , module Plots.Types.Function -- | Boxplot. -- Boxplot api. , module Plots.Types.Boxplot -- | Density fucntion. -- Density plot api. , module Plots.Types.Density -- | Smooth. -- Smooth plot api. , module Plots.Types.Smooth -- | Text. -- API for text plot. , module Plots.Types.Text -- | Wedge and annular wedge. -- API for wedge, annular wegde and pie. , module Plots.Types.Pie -- | Scatter plot for polar co-ordinates. -- API for polar scatter plot. , module Plots.Types.Points -- | API using multiple types. , module Plots.Types.Others -- , module Plots.Types.Heatmap ) where import Plots.Axis import Plots.Axis.Grid import Plots.Axis.Labels import Plots.Axis.Render import Plots.Axis.Ticks import Plots.Axis.ColourBar import Plots.Types import Plots.Themes import Plots.API import Plots.Types.Scatter import Plots.Types.Line import Plots.Types.Ribbon import Plots.Types.Histogram import Plots.Types.Function import Plots.Types.Boxplot import Plots.Types.Density import Plots.Types.Smooth import Plots.Types.Text import Plots.Types.Pie import Plots.Types.Points import Plots.Types.Others -- import Plots.Types.Heatmap
bergey/plots
src/Plots.hs
Haskell
bsd-3-clause
2,909
module Diag.Util.Timer where import System.CPUTime import Text.Printf timeItMsg :: String -> IO a -> IO a timeItMsg msg ioa = do t1 <- getCPUTime a <- ioa t2 <- getCPUTime let t :: Double t = fromIntegral (t2-t1) * 1e-12 printf "CPU time for %s: %6.5fs\n" msg t return a
marcmo/hsDiagnosis
src/Diag/Util/Timer.hs
Haskell
bsd-3-clause
293
module Ivory.Language.Sint where import Ivory.Language.BoundedInteger import Ivory.Language.Type import qualified Ivory.Language.Syntax as I import Data.Int (Int8,Int16,Int32,Int64) -- Signed Types ---------------------------------------------------------------- -- | 8-bit integers. newtype Sint8 = Sint8 { getSint8 :: I.Expr } deriving Show instance IvoryType Sint8 where ivoryType _ = I.TyInt I.Int8 instance IvoryVar Sint8 where wrapVar = wrapVarExpr unwrapExpr = getSint8 instance IvoryExpr Sint8 where wrapExpr = Sint8 instance Num Sint8 where (*) = exprBinop (*) (+) = exprBinop (+) (-) = exprBinop (-) abs = exprUnary abs signum = exprUnary signum negate = exprUnary negate fromInteger = boundedFromInteger Sint8 (0 :: Int8) instance Bounded Sint8 where minBound = wrapExpr (I.ExpMaxMin False) maxBound = wrapExpr (I.ExpMaxMin True) -- | 16-bit integers. newtype Sint16 = Sint16 { getSint16 :: I.Expr } deriving Show instance IvoryType Sint16 where ivoryType _ = I.TyInt I.Int16 instance IvoryVar Sint16 where wrapVar = wrapVarExpr unwrapExpr = getSint16 instance IvoryExpr Sint16 where wrapExpr = Sint16 instance Num Sint16 where (*) = exprBinop (*) (+) = exprBinop (+) (-) = exprBinop (-) abs = exprUnary abs signum = exprUnary signum negate = exprUnary negate fromInteger = boundedFromInteger Sint16 (0 :: Int16) instance Bounded Sint16 where minBound = wrapExpr (I.ExpMaxMin False) maxBound = wrapExpr (I.ExpMaxMin True) -- | 32-bit integers. newtype Sint32 = Sint32 { getSint32 :: I.Expr } deriving Show instance IvoryType Sint32 where ivoryType _ = I.TyInt I.Int32 instance IvoryVar Sint32 where wrapVar = wrapVarExpr unwrapExpr = getSint32 instance IvoryExpr Sint32 where wrapExpr = Sint32 instance Num Sint32 where (*) = exprBinop (*) (+) = exprBinop (+) (-) = exprBinop (-) abs = exprUnary abs signum = exprUnary signum negate = exprUnary negate fromInteger = boundedFromInteger Sint32 (0 :: Int32) instance Bounded Sint32 where minBound = wrapExpr (I.ExpMaxMin False) maxBound = wrapExpr (I.ExpMaxMin True) -- | 64-bit integers. newtype Sint64 = Sint64 { getSint64 :: I.Expr } deriving Show instance IvoryType Sint64 where ivoryType _ = I.TyInt I.Int64 instance IvoryVar Sint64 where wrapVar = wrapVarExpr unwrapExpr = getSint64 instance IvoryExpr Sint64 where wrapExpr = Sint64 instance Num Sint64 where (*) = exprBinop (*) (+) = exprBinop (+) (-) = exprBinop (-) abs = exprUnary abs signum = exprUnary signum negate = exprUnary negate fromInteger = boundedFromInteger Sint64 (0 :: Int64) instance Bounded Sint64 where minBound = wrapExpr (I.ExpMaxMin False) maxBound = wrapExpr (I.ExpMaxMin True)
GaloisInc/ivory
ivory/src/Ivory/Language/Sint.hs
Haskell
bsd-3-clause
2,936
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction, ViewPatterns, FlexibleInstances #-} module Language.Lisk.Parser where import Data.List import Data.Either import Control.Monad.Reader import Control.Monad.Error import Control.Arrow import Control.Applicative import Control.Monad.Identity import Data.Char import Text.Parsec hiding ((<|>),many,token) import Text.Parsec.Combinator import Language.Haskell.Exts.Syntax import Language.Haskell.Exts.Pretty import qualified Language.Haskell.Exts.Parser as P (parseExp,parse,ParseResult(..)) data LiskExpr = LSym SrcLoc String | LTCM SrcLoc String | LList SrcLoc [LiskExpr] deriving Show type LP = Parsec String () printLiskToHaskell = prettyPrint parseLisk = parse (spaces *> liskModule <* spaces) printLiskFragment p = either (putStrLn.show) (putStrLn.prettyPrint) . parse p "" printLisk str = case parse liskModule "" str of Left e -> error $ show e ++ suggest Right ex -> putStrLn $ prettyPrint ex liskModule = parens $ do loc <- getLoc symbolOf "module" <?> "module" spaces1 name <- liskModuleName spaces importDecls <- liskImportDecl spaces decls <- sepBy liskDecl spaces return $ Module loc name [] Nothing Nothing importDecls decls symbolOf = string liskDecl = try liskTypeSig <|> try liskFunBind <|> liskPatBind liskTypeSig = parens $ do loc <- getLoc symbolOf "::" <?> "type signature e.g. (:: x :string)" spaces1 idents <- pure <$> liskIdent <|> parens (sepBy1 liskIdent spaces1) spaces1 typ <- liskType return $ TypeSig loc idents typ liskType = try liskTyCon <|> try liskTyVar <|> liskTyApp liskTyApp = parens $ do op <- liskType spaces1 args <- sepBy1 liskType spaces1 let op' = case op of TyCon (Special (TupleCon b n)) -> TyCon $ Special $ TupleCon b $ length args _ -> op return $ foldl TyApp op' args liskTyCon = TyCon <$> liskQName liskTyVar = TyVar <$> liskName liskPatBind = parens $ do loc <- getLoc symbolOf "=" <?> "pattern binding e.g. (= x \"Hello, World!\")" spaces1 pat <- liskPat typ <- return Nothing -- liskType -- TODO spaces1 rhs <- liskRhs binds <- liskBinds return $ PatBind loc pat Nothing rhs binds liskFunBind = FunBind <$> sepBy1 liskMatch spaces1 liskMatch = parens $ do loc <- getLoc symbolOf "=" <?> "pattern binding e.g. (= x \"Hello, World!\")" spaces1 name <- liskName spaces1 pats <- (pure <$> liskPat) <|> parens (sepBy1 liskPat spaces1) typ <- return Nothing -- liskType -- TODO spaces1 rhs <- liskRhs binds <- liskBinds return $ Match loc name pats typ rhs binds liskBinds = try liskBDecls <|> liskIPBinds liskBDecls = BDecls <$> pure [] -- TODO liskIPBinds = IPBinds <$> pure [] -- TODO liskPat = liskPVar -- TODO liskRhs = liskUnguardedRhs liskUnguardedRhs = UnGuardedRhs <$> liskExp -- TODO liskExp = try liskVar <|> try liskLit <|> try liskApp liskApp = try liskTupleApp <|> try liskOpApp <|> try liskIdentApp <|> liskOpPartial liskTupleApp = parens $ do string "," args <- (spaces1 *> sepBy1 liskExp spaces1) <|> pure [] let op = Var $ Special $ TupleCon Boxed $ max 2 (length args) paren | null args = id | otherwise = Paren return $ paren $ foldl App op $ args liskIdentApp = parens $ do op <- liskExp spaces1 args <- sepBy1 liskExp spaces1 return $ Paren $ foldl App op $ args liskOpApp = parens $ do op <- QVarOp <$> liskOp spaces1 args <- (:) <$> (liskExp <* spaces) <*> sepBy1 liskExp spaces1 return $ Paren $ foldl1 (flip InfixApp op) args liskOpPartial = parens $ do op <- Var <$> liskOp spaces1 e <- liskExp return $ App op e liskOp = UnQual . Symbol <$> many1 (oneOf ".*-+/\\=<>") liskLit = Lit <$> (liskChar <|> try liskString <|> liskInt) liskChar = Char <$> (string "\\" *> (space <|> newline <|> noneOf "\n \t")) where space = const ' ' <$> string "Space" <|> const '\n' <$> string "Newline" liskString = do strRep <- char '\"' *> (concat <$> many liskStringSeq) <* char '\"' case P.parseExp $ "\"" ++ strRep ++ "\"" of P.ParseOk (Lit s@String{}) -> return s P.ParseFailed _ msg -> parserFail msg where liskStringSeq = ("\\"++) <$> (char '\\' *> (pure <$> noneOf "\n")) <|> pure <$> noneOf "\n\"" liskInt = Int <$> (read <$> many1 digit) liskPVar = PVar <$> liskName liskQName = try liskSpecial <|> try liskQual <|> try liskUnQual liskQual = mzero -- TODO liskUnQual = UnQual <$> liskName liskSpecial = Special <$> spec where spec = string "()" *> pure UnitCon <|> string "[]" *> pure ListCon <|> string "->" *> pure FunCon <|> string "," *> pure (TupleCon Boxed{-TODO:boxed-} 0) liskName = try liskIdent <|> liskSymbol liskVar = Var <$> liskUnQual liskIdent = Ident . hyphenToCamelCase . colonToConsTyp <$> ident where ident = ((++) <$> (string ":" <|> pure "") <*> many1 liskIdentifierToken) colonToConsTyp (':':x:xs) = toUpper x : xs colonToConsTyp xs = xs liskSymbol = Symbol <$> many1 liskIdentifierToken liskList = mzero -- TODO liskImportDecl = parens $ do symbolOf "import" <?> "import" spaces1 sepBy1 liskImportDeclModule spaces1 liskImportDeclModule = liskImportDeclModuleName <|> liskImportDeclModuleSpec liskImportDeclModuleSpec = parens $ do imp <- liskImportDeclModuleSpec return imp liskImportDeclModuleName = do loc <- getLoc name <- liskModuleName return $ ImportDecl { importLoc = loc , importModule = name , importQualified = False , importSrc = False , importPkg = Nothing , importAs = Nothing , importSpecs = Nothing } liskModuleName = (<?> "module name (e.g. `:module.some-name')") $ do parts <- sepBy1 modulePart (string ".") return $ ModuleName $ intercalate "." parts where modulePart = format <$> many1 liskIdentifierToken format = hyphenToCamelCase . upperize upperize (x:xs) = toUpper x : xs liskDefIdentifier = do ident <- many1 liskIdentifierToken return $ Ident ident liskIdentifierToken = letter <|> digit <|> oneOf "-" hyphenToCamelCase ('-':'-':xs) = hyphenToCamelCase ('-':xs) hyphenToCamelCase ('-':x:xs) = toUpper x : hyphenToCamelCase xs hyphenToCamelCase ('-':xs) = hyphenToCamelCase xs hyphenToCamelCase (x:xs) = x : hyphenToCamelCase xs hyphenToCamelCase [] = [] getLoc = posToLoc <$> getPosition where posToLoc pos = SrcLoc { srcFilename = sourceName pos , srcLine = sourceLine pos , srcColumn = sourceColumn pos } parens = between (char '(') (char ')') suggest = "\n(are you trying to use not-currently-supported syntax?)" bi f g = f . g . f spaces1 = many1 space
aculich/lisk
src/Language/Lisk/Parser.hs
Haskell
bsd-3-clause
6,812
module Chap7Arith4 where --id :: a -> a --id x = x roundTrip :: (Show a, Read a) => a -> a roundTrip a = read (show a) -- 5. roundTrip' :: (Show a, Read a) => a -> a roundTrip' = read . show -- 6. -- Probably not be what the exercise is looking for roundTrip'' :: (Show a, Read b, Integral b) => a -> b roundTrip'' = read . show main = do print (roundTrip 4) print (id 4) print (roundTrip' 4) print (roundTrip'' 4)
tkasu/haskellbook-adventure
app/Chap7Arith4.hs
Haskell
bsd-3-clause
431
import Test.Hspec import System.Directory import Lib main :: IO () main = hspec $ do describe "Foo" $ do it "Return a foo file" $ do m res <- doesFileExist "foo" res `shouldBe` True
lpaulmp/shake-ansible
test/Spec.hs
Haskell
bsd-3-clause
208
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP #-} module VarSet ( -- * Var, Id and TyVar set types VarSet, IdSet, TyVarSet, CoVarSet, TyCoVarSet, -- ** Manipulating these sets emptyVarSet, unitVarSet, mkVarSet, extendVarSet, extendVarSetList, extendVarSet_C, elemVarSet, varSetElems, subVarSet, unionVarSet, unionVarSets, mapUnionVarSet, intersectVarSet, intersectsVarSet, disjointVarSet, isEmptyVarSet, delVarSet, delVarSetList, delVarSetByKey, minusVarSet, filterVarSet, varSetAny, varSetAll, transCloVarSet, fixVarSet, lookupVarSet, lookupVarSetByName, sizeVarSet, seqVarSet, elemVarSetByKey, partitionVarSet, pluralVarSet, pprVarSet, -- * Deterministic Var set types DVarSet, DIdSet, DTyVarSet, DTyCoVarSet, -- ** Manipulating these sets emptyDVarSet, unitDVarSet, mkDVarSet, extendDVarSet, extendDVarSetList, elemDVarSet, dVarSetElems, subDVarSet, unionDVarSet, unionDVarSets, mapUnionDVarSet, intersectDVarSet, intersectsDVarSet, disjointDVarSet, isEmptyDVarSet, delDVarSet, delDVarSetList, minusDVarSet, foldDVarSet, filterDVarSet, dVarSetMinusVarSet, transCloDVarSet, sizeDVarSet, seqDVarSet, partitionDVarSet, dVarSetToVarSet, ) where #include "HsVersions.h" import Var ( Var, TyVar, CoVar, TyCoVar, Id ) import Unique import Name ( Name ) import UniqSet import UniqDSet import UniqFM( disjointUFM, pluralUFM, pprUFM ) import UniqDFM( disjointUDFM, udfmToUfm ) import Outputable (SDoc) -- | A non-deterministic set of variables. -- See Note [Deterministic UniqFM] in UniqDFM for explanation why it's not -- deterministic and why it matters. Use DVarSet if the set eventually -- gets converted into a list or folded over in a way where the order -- changes the generated code, for example when abstracting variables. type VarSet = UniqSet Var type IdSet = UniqSet Id type TyVarSet = UniqSet TyVar type CoVarSet = UniqSet CoVar type TyCoVarSet = UniqSet TyCoVar emptyVarSet :: VarSet intersectVarSet :: VarSet -> VarSet -> VarSet unionVarSet :: VarSet -> VarSet -> VarSet unionVarSets :: [VarSet] -> VarSet mapUnionVarSet :: (a -> VarSet) -> [a] -> VarSet -- ^ map the function over the list, and union the results varSetElems :: VarSet -> [Var] unitVarSet :: Var -> VarSet extendVarSet :: VarSet -> Var -> VarSet extendVarSetList:: VarSet -> [Var] -> VarSet elemVarSet :: Var -> VarSet -> Bool delVarSet :: VarSet -> Var -> VarSet delVarSetList :: VarSet -> [Var] -> VarSet minusVarSet :: VarSet -> VarSet -> VarSet isEmptyVarSet :: VarSet -> Bool mkVarSet :: [Var] -> VarSet lookupVarSet :: VarSet -> Var -> Maybe Var -- Returns the set element, which may be -- (==) to the argument, but not the same as lookupVarSetByName :: VarSet -> Name -> Maybe Var sizeVarSet :: VarSet -> Int filterVarSet :: (Var -> Bool) -> VarSet -> VarSet extendVarSet_C :: (Var->Var->Var) -> VarSet -> Var -> VarSet delVarSetByKey :: VarSet -> Unique -> VarSet elemVarSetByKey :: Unique -> VarSet -> Bool partitionVarSet :: (Var -> Bool) -> VarSet -> (VarSet, VarSet) emptyVarSet = emptyUniqSet unitVarSet = unitUniqSet extendVarSet = addOneToUniqSet extendVarSetList= addListToUniqSet intersectVarSet = intersectUniqSets intersectsVarSet:: VarSet -> VarSet -> Bool -- True if non-empty intersection disjointVarSet :: VarSet -> VarSet -> Bool -- True if empty intersection subVarSet :: VarSet -> VarSet -> Bool -- True if first arg is subset of second -- (s1 `intersectsVarSet` s2) doesn't compute s2 if s1 is empty; -- ditto disjointVarSet, subVarSet unionVarSet = unionUniqSets unionVarSets = unionManyUniqSets varSetElems = uniqSetToList elemVarSet = elementOfUniqSet minusVarSet = minusUniqSet delVarSet = delOneFromUniqSet delVarSetList = delListFromUniqSet isEmptyVarSet = isEmptyUniqSet mkVarSet = mkUniqSet lookupVarSet = lookupUniqSet lookupVarSetByName = lookupUniqSet sizeVarSet = sizeUniqSet filterVarSet = filterUniqSet extendVarSet_C = addOneToUniqSet_C delVarSetByKey = delOneFromUniqSet_Directly elemVarSetByKey = elemUniqSet_Directly partitionVarSet = partitionUniqSet mapUnionVarSet get_set xs = foldr (unionVarSet . get_set) emptyVarSet xs -- See comments with type signatures intersectsVarSet s1 s2 = not (s1 `disjointVarSet` s2) disjointVarSet s1 s2 = disjointUFM s1 s2 subVarSet s1 s2 = isEmptyVarSet (s1 `minusVarSet` s2) varSetAny :: (Var -> Bool) -> VarSet -> Bool varSetAny = uniqSetAny varSetAll :: (Var -> Bool) -> VarSet -> Bool varSetAll = uniqSetAll -- There used to exist mapVarSet, see Note [Unsound mapUniqSet] in UniqSet for -- why it got removed. fixVarSet :: (VarSet -> VarSet) -- Map the current set to a new set -> VarSet -> VarSet -- (fixVarSet f s) repeatedly applies f to the set s, -- until it reaches a fixed point. fixVarSet fn vars | new_vars `subVarSet` vars = vars | otherwise = fixVarSet fn new_vars where new_vars = fn vars transCloVarSet :: (VarSet -> VarSet) -- Map some variables in the set to -- extra variables that should be in it -> VarSet -> VarSet -- (transCloVarSet f s) repeatedly applies f to new candidates, adding any -- new variables to s that it finds thereby, until it reaches a fixed point. -- -- The function fn could be (Var -> VarSet), but we use (VarSet -> VarSet) -- for efficiency, so that the test can be batched up. -- It's essential that fn will work fine if given new candidates -- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2 -- Use fixVarSet if the function needs to see the whole set all at once transCloVarSet fn seeds = go seeds seeds where go :: VarSet -- Accumulating result -> VarSet -- Work-list; un-processed subset of accumulating result -> VarSet -- Specification: go acc vs = acc `union` transClo fn vs go acc candidates | isEmptyVarSet new_vs = acc | otherwise = go (acc `unionVarSet` new_vs) new_vs where new_vs = fn candidates `minusVarSet` acc seqVarSet :: VarSet -> () seqVarSet s = sizeVarSet s `seq` () -- | Determines the pluralisation suffix appropriate for the length of a set -- in the same way that plural from Outputable does for lists. pluralVarSet :: VarSet -> SDoc pluralVarSet = pluralUFM -- | Pretty-print a non-deterministic set. -- The order of variables is non-deterministic and for pretty-printing that -- shouldn't be a problem. -- Having this function helps contain the non-determinism created with -- varSetElems. -- Passing a list to the pretty-printing function allows the caller -- to decide on the order of Vars (eg. toposort them) without them having -- to use varSetElems at the call site. This prevents from let-binding -- non-deterministically ordered lists and reusing them where determinism -- matters. pprVarSet :: VarSet -- ^ The things to be pretty printed -> ([Var] -> SDoc) -- ^ The pretty printing function to use on the -- elements -> SDoc -- ^ 'SDoc' where the things have been pretty -- printed pprVarSet = pprUFM -- Deterministic VarSet -- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need -- DVarSet. type DVarSet = UniqDSet Var type DIdSet = UniqDSet Id type DTyVarSet = UniqDSet TyVar type DTyCoVarSet = UniqDSet TyCoVar emptyDVarSet :: DVarSet emptyDVarSet = emptyUniqDSet unitDVarSet :: Var -> DVarSet unitDVarSet = unitUniqDSet mkDVarSet :: [Var] -> DVarSet mkDVarSet = mkUniqDSet extendDVarSet :: DVarSet -> Var -> DVarSet extendDVarSet = addOneToUniqDSet elemDVarSet :: Var -> DVarSet -> Bool elemDVarSet = elementOfUniqDSet dVarSetElems :: DVarSet -> [Var] dVarSetElems = uniqDSetToList subDVarSet :: DVarSet -> DVarSet -> Bool subDVarSet s1 s2 = isEmptyDVarSet (s1 `minusDVarSet` s2) unionDVarSet :: DVarSet -> DVarSet -> DVarSet unionDVarSet = unionUniqDSets unionDVarSets :: [DVarSet] -> DVarSet unionDVarSets = unionManyUniqDSets -- | Map the function over the list, and union the results mapUnionDVarSet :: (a -> DVarSet) -> [a] -> DVarSet mapUnionDVarSet get_set xs = foldr (unionDVarSet . get_set) emptyDVarSet xs intersectDVarSet :: DVarSet -> DVarSet -> DVarSet intersectDVarSet = intersectUniqDSets -- | True if empty intersection disjointDVarSet :: DVarSet -> DVarSet -> Bool disjointDVarSet s1 s2 = disjointUDFM s1 s2 -- | True if non-empty intersection intersectsDVarSet :: DVarSet -> DVarSet -> Bool intersectsDVarSet s1 s2 = not (s1 `disjointDVarSet` s2) isEmptyDVarSet :: DVarSet -> Bool isEmptyDVarSet = isEmptyUniqDSet delDVarSet :: DVarSet -> Var -> DVarSet delDVarSet = delOneFromUniqDSet minusDVarSet :: DVarSet -> DVarSet -> DVarSet minusDVarSet = minusUniqDSet dVarSetMinusVarSet :: DVarSet -> VarSet -> DVarSet dVarSetMinusVarSet = uniqDSetMinusUniqSet foldDVarSet :: (Var -> a -> a) -> a -> DVarSet -> a foldDVarSet = foldUniqDSet filterDVarSet :: (Var -> Bool) -> DVarSet -> DVarSet filterDVarSet = filterUniqDSet sizeDVarSet :: DVarSet -> Int sizeDVarSet = sizeUniqDSet -- | Partition DVarSet according to the predicate given partitionDVarSet :: (Var -> Bool) -> DVarSet -> (DVarSet, DVarSet) partitionDVarSet = partitionUniqDSet -- | Delete a list of variables from DVarSet delDVarSetList :: DVarSet -> [Var] -> DVarSet delDVarSetList = delListFromUniqDSet seqDVarSet :: DVarSet -> () seqDVarSet s = sizeDVarSet s `seq` () -- | Add a list of variables to DVarSet extendDVarSetList :: DVarSet -> [Var] -> DVarSet extendDVarSetList = addListToUniqDSet -- | Convert a DVarSet to a VarSet by forgeting the order of insertion dVarSetToVarSet :: DVarSet -> VarSet dVarSetToVarSet = udfmToUfm -- | transCloVarSet for DVarSet transCloDVarSet :: (DVarSet -> DVarSet) -- Map some variables in the set to -- extra variables that should be in it -> DVarSet -> DVarSet -- (transCloDVarSet f s) repeatedly applies f to new candidates, adding any -- new variables to s that it finds thereby, until it reaches a fixed point. -- -- The function fn could be (Var -> DVarSet), but we use (DVarSet -> DVarSet) -- for efficiency, so that the test can be batched up. -- It's essential that fn will work fine if given new candidates -- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2 transCloDVarSet fn seeds = go seeds seeds where go :: DVarSet -- Accumulating result -> DVarSet -- Work-list; un-processed subset of accumulating result -> DVarSet -- Specification: go acc vs = acc `union` transClo fn vs go acc candidates | isEmptyDVarSet new_vs = acc | otherwise = go (acc `unionDVarSet` new_vs) new_vs where new_vs = fn candidates `minusDVarSet` acc
vikraman/ghc
compiler/basicTypes/VarSet.hs
Haskell
bsd-3-clause
11,246
module System.Win32.DHCP.SUBNET_ELEMENT_INFO_ARRAY_V4 ( SUBNET_ELEMENT_INFO_ARRAY_V4 (..) , infoArray ) where import System.Win32.DHCP.DhcpStructure import System.Win32.DHCP.LengthBuffer import System.Win32.DHCP.SUBNET_ELEMENT_DATA_V4 -- typedef struct _DHCP_SUBNET_ELEMENT_INFO_ARRAY_V4 { -- DWORD NumElements; -- LPDHCP_SUBNET_ELEMENT_DATA_V4 Elements; -- } DHCP_SUBNET_ELEMENT_INFO_ARRAY_V4, *LPDHCP_SUBNET_ELEMENT_INFO_ARRAY_V4; newtype SUBNET_ELEMENT_INFO_ARRAY_V4 = SUBNET_ELEMENT_INFO_ARRAY_V4 (LengthBuffer SUBNET_ELEMENT_DATA_V4) unwrap :: SUBNET_ELEMENT_INFO_ARRAY_V4 -> LengthBuffer SUBNET_ELEMENT_DATA_V4 unwrap (SUBNET_ELEMENT_INFO_ARRAY_V4 ia) = ia infoArray :: DhcpStructure SUBNET_ELEMENT_INFO_ARRAY_V4 infoArray = newtypeDhcpStructure SUBNET_ELEMENT_INFO_ARRAY_V4 unwrap $ lengthBuffer (baseDhcpArray subnetElementData)
mikesteele81/Win32-dhcp-server
src/System/Win32/DHCP/SUBNET_ELEMENT_INFO_ARRAY_V4.hs
Haskell
bsd-3-clause
883
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RankNTypes #-} module Text.Markdown ( -- * Functions markdown -- * Settings , MarkdownSettings , msXssProtect , msStandaloneHtml , msFencedHandlers , msBlockCodeRenderer , msLinkNewTab , msBlankBeforeBlockquote , msBlockFilter , msAddHeadingId -- * Newtype , Markdown (..) -- * Fenced handlers , FencedHandler (..) , codeFencedHandler , htmlFencedHandler -- * Convenience re-exports , def ) where import Control.Arrow ((&&&)) import Text.Markdown.Inline import Text.Markdown.Block import Text.Markdown.Types import Prelude hiding (sequence, takeWhile) import Data.Char (isAlphaNum) import Data.Default (Default (..)) import Data.List (intercalate, isInfixOf) import Data.Text (Text) import qualified Data.Text.Lazy as TL import Text.Blaze (toValue) import Text.Blaze.Html (ToMarkup (..), Html) import Text.Blaze.Html.Renderer.Text (renderHtml) import Data.Conduit import qualified Data.Conduit.List as CL import Data.Monoid (Monoid (mappend, mempty, mconcat)) import Data.Functor.Identity (runIdentity) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as HA import Text.HTML.SanitizeXSS (sanitizeBalance) import qualified Data.Map as Map import Data.String (IsString) -- | A newtype wrapper providing a @ToHtml@ instance. newtype Markdown = Markdown TL.Text deriving(Eq, Ord, Monoid, IsString, Show) instance ToMarkup Markdown where toMarkup (Markdown t) = markdown def t -- | Convert the given textual markdown content to HTML. -- -- >>> :set -XOverloadedStrings -- >>> import Text.Blaze.Html.Renderer.Text -- >>> renderHtml $ markdown def "# Hello World!" -- "<h1>Hello World!</h1>" -- -- >>> renderHtml $ markdown def { msXssProtect = False } "<script>alert('evil')</script>" -- "<script>alert('evil')</script>" markdown :: MarkdownSettings -> TL.Text -> Html markdown ms tl = sanitize $ runIdentity $ CL.sourceList blocksH $= toHtmlB ms $$ CL.fold mappend mempty where sanitize | msXssProtect ms = preEscapedToMarkup . sanitizeBalance . TL.toStrict . renderHtml | otherwise = id blocksH :: [Block Html] blocksH = processBlocks blocks blocks :: [Block Text] blocks = runIdentity $ CL.sourceList (TL.toChunks tl) $$ toBlocks ms =$ CL.consume processBlocks :: [Block Text] -> [Block Html] processBlocks = map (fmap $ toHtmlI ms) . msBlockFilter ms . map (fmap $ intercalate [InlineHtml "<br>"]) . map (fmap $ map $ toInline refs) . map toBlockLines refs = Map.unions $ map toRef blocks where toRef (BlockReference x y) = Map.singleton x y toRef _ = Map.empty data MState = NoState | InList ListType toHtmlB :: Monad m => MarkdownSettings -> Conduit (Block Html) m Html toHtmlB ms = loop NoState where loop state = await >>= maybe (closeState state) (\x -> do state' <- getState state x yield $ go x loop state') closeState NoState = return () closeState (InList Unordered) = yield $ escape "</ul>" closeState (InList Ordered) = yield $ escape "</ol>" getState NoState (BlockList ltype _) = do yield $ escape $ case ltype of Unordered -> "<ul>" Ordered -> "<ol>" return $ InList ltype getState NoState _ = return NoState getState state@(InList lt1) b@(BlockList lt2 _) | lt1 == lt2 = return state | otherwise = closeState state >> getState NoState b getState state@(InList _) _ = closeState state >> return NoState go (BlockPara h) = H.p h go (BlockPlainText h) = h go (BlockList _ (Left h)) = H.li h go (BlockList _ (Right bs)) = H.li $ blocksToHtml bs go (BlockHtml t) = escape t go (BlockCode a b) = msBlockCodeRenderer ms a (id &&& toMarkup $ b) go (BlockQuote bs) = H.blockquote $ blocksToHtml bs go BlockRule = H.hr go (BlockHeading level h) | msAddHeadingId ms = wrap level H.! HA.id (clean h) $ h | otherwise = wrap level h where wrap 1 = H.h1 wrap 2 = H.h2 wrap 3 = H.h3 wrap 4 = H.h4 wrap 5 = H.h5 wrap _ = H.h6 isValidChar c = isAlphaNum c || isInfixOf [c] "-_:." clean = toValue . TL.filter isValidChar . (TL.replace " " "-") . TL.toLower . renderHtml go BlockReference{} = return () blocksToHtml bs = runIdentity $ mapM_ yield bs $$ toHtmlB ms =$ CL.fold mappend mempty escape :: Text -> Html escape = preEscapedToMarkup toHtmlI :: MarkdownSettings -> [Inline] -> Html toHtmlI ms is0 | msXssProtect ms = escape $ sanitizeBalance $ TL.toStrict $ renderHtml final | otherwise = final where final = gos is0 gos = mconcat . map go go (InlineText t) = toMarkup t go (InlineItalic is) = H.i $ gos is go (InlineBold is) = H.b $ gos is go (InlineCode t) = H.code $ toMarkup t go (InlineLink url Nothing content) | msLinkNewTab ms = H.a H.! HA.href (H.toValue url) H.! HA.target "_blank" $ gos content | otherwise = H.a H.! HA.href (H.toValue url) $ gos content go (InlineLink url (Just title) content) | msLinkNewTab ms = H.a H.! HA.href (H.toValue url) H.! HA.title (H.toValue title) H.! HA.target "_blank" $ gos content | otherwise = H.a H.! HA.href (H.toValue url) H.! HA.title (H.toValue title) $ gos content go (InlineImage url Nothing content) = H.img H.! HA.src (H.toValue url) H.! HA.alt (H.toValue content) go (InlineImage url (Just title) content) = H.img H.! HA.src (H.toValue url) H.! HA.alt (H.toValue content) H.! HA.title (H.toValue title) go (InlineHtml t) = escape t go (InlineFootnoteRef x) = let ishown = TL.pack (show x) (<>) = mappend in H.a H.! HA.href (H.toValue $ "#footnote-" <> ishown) H.! HA.id (H.toValue $ "ref-" <> ishown) $ H.toHtml $ "[" <> ishown <> "]" go (InlineFootnote x) = let ishown = TL.pack (show x) (<>) = mappend in H.a H.! HA.href (H.toValue $ "#ref-" <> ishown) H.! HA.id (H.toValue $ "footnote-" <> ishown) $ H.toHtml $ "[" <> ishown <> "]"
thefalconfeat/markdown
Text/Markdown.hs
Haskell
bsd-3-clause
6,541
<?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="ko-KR"> <title>Tips and Tricks | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/tips/src/main/javahelp/org/zaproxy/zap/extension/tips/resources/help_ko_KR/helpset_ko_KR.hs
Haskell
apache-2.0
977
{-# OPTIONS_GHC -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Dotnet -- Copyright : (c) sof, 2003 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- Primitive operations and types for doing .NET interop -- ----------------------------------------------------------------------------- module GHC.Dotnet ( Object , unmarshalObject , marshalObject , unmarshalString , marshalString , checkResult ) where import GHC.Prim import GHC.Base import GHC.IO import GHC.IOBase import GHC.Ptr import Foreign.Marshal.Array import Foreign.Marshal.Alloc import Foreign.Storable import Foreign.C.String data Object a = Object Addr# checkResult :: (State# RealWorld -> (# State# RealWorld, a, Addr# #)) -> IO a checkResult fun = IO $ \ st -> case fun st of (# st1, res, err #) | err `eqAddr#` nullAddr# -> (# st1, res #) | otherwise -> throw (IOException (raiseError err)) st1 -- ToDo: attach finaliser. unmarshalObject :: Addr# -> Object a unmarshalObject x = Object x marshalObject :: Object a -> (Addr# -> IO b) -> IO b marshalObject (Object x) cont = cont x -- dotnet interop support passing and returning -- strings. marshalString :: String -> (Addr# -> IO a) -> IO a marshalString str cont = withCString str (\ (Ptr x) -> cont x) -- char** received back from a .NET interop layer. unmarshalString :: Addr# -> String unmarshalString p = unsafePerformIO $ do let ptr = Ptr p str <- peekCString ptr free ptr return str -- room for improvement.. raiseError :: Addr# -> IOError raiseError p = userError (".NET error: " ++ unmarshalString p)
FranklinChen/hugs98-plus-Sep2006
packages/base/GHC/Dotnet.hs
Haskell
bsd-3-clause
1,819
-- | -- Module : Crypto.ConstructHash.MiyaguchiPreneel -- License : BSD-style -- Maintainer : Kei Hibino <[email protected]> -- Stability : experimental -- Portability : unknown -- -- Provide the hash function construction method from block cipher -- <https://en.wikipedia.org/wiki/One-way_compression_function> -- {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Crypto.ConstructHash.MiyaguchiPreneel ( compute, compute' , MiyaguchiPreneel ) where import Data.List (foldl') import Crypto.Data.Padding (pad, Format (ZERO)) import Crypto.Cipher.Types import Crypto.Error (throwCryptoError) import Crypto.Internal.ByteArray (ByteArrayAccess, ByteArray, Bytes) import qualified Crypto.Internal.ByteArray as B newtype MiyaguchiPreneel a = MP Bytes deriving (ByteArrayAccess) instance Eq (MiyaguchiPreneel a) where MP b1 == MP b2 = B.constEq b1 b2 -- | Compute Miyaguchi-Preneel one way compress using the supplied block cipher. compute' :: (ByteArrayAccess bin, BlockCipher cipher) => (Bytes -> cipher) -- ^ key build function to compute Miyaguchi-Preneel. care about block-size and key-size -> bin -- ^ input message -> MiyaguchiPreneel cipher -- ^ output tag compute' g = MP . foldl' (step $ g) (B.replicate bsz 0) . chunks . pad (ZERO bsz) . B.convert where bsz = blockSize ( g B.empty {- dummy to get block size -} ) chunks msg | B.null msg = [] | otherwise = (hd :: Bytes) : chunks tl where (hd, tl) = B.splitAt bsz msg -- | Compute Miyaguchi-Preneel one way compress using the inferred block cipher. -- Only safe when KEY-SIZE equals to BLOCK-SIZE. -- -- Simple usage /mp' msg :: MiyaguchiPreneel AES128/ compute :: (ByteArrayAccess bin, BlockCipher cipher) => bin -- ^ input message -> MiyaguchiPreneel cipher -- ^ output tag compute = compute' $ throwCryptoError . cipherInit -- | computation step of Miyaguchi-Preneel step :: (ByteArray ba, BlockCipher k) => (ba -> k) -> ba -> ba -> ba step g iv msg = ecbEncrypt k msg `bxor` iv `bxor` msg where k = g iv bxor :: ByteArray ba => ba -> ba -> ba bxor = B.xor
vincenthz/cryptonite
Crypto/ConstructHash/MiyaguchiPreneel.hs
Haskell
bsd-3-clause
2,286
module Control.Concurrent.Timer.Types ( Timer(..) , TimerImmutable(..) ) where ------------------------------------------------------------------------------ import Control.Concurrent (ThreadId) import Control.Concurrent.MVar (MVar) import Control.Concurrent.Suspend (Delay) ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | The data type representing the timer. -- For now, the action and delay are fixed for the lifetime of the Timer. data Timer m = Timer { timerImmutable :: MVar (Maybe (TimerImmutable m)) -- ^ If the MVar is empty, someone if mutating the timer. If the MVar contains Nothing, the timer was not started/initialized. } data TimerImmutable m = TimerImmutable { timerAction :: m () , timerDelay :: Delay , timerThreadID :: ThreadId }
Palmik/timers
src/Control/Concurrent/Timer/Types.hs
Haskell
bsd-3-clause
938
-- | -- Module: Network.FastIRC.Users -- Copyright: (c) 2010 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <[email protected]> -- Stability: alpha -- -- This module includes parsers for IRC users. module Network.FastIRC.Users ( UserSpec(..), userIsServer, showUserSpec, userParser ) where import qualified Data.ByteString.Char8 as B import Control.Applicative import Data.Attoparsec.Char8 as P import Network.FastIRC.ServerSet import Network.FastIRC.Types import Network.FastIRC.Utils -- | IRC user or server. data UserSpec -- | Nickname. = Nick NickName -- | Nickname, username and hostname. | User NickName UserName HostName deriving (Eq, Read, Show) -- | Check whether a given nickname is a server. userIsServer :: UserSpec -> ServerSet -> Bool userIsServer (User _ _ _) _ = False userIsServer (Nick nick) servers = isServer nick servers -- | Turn a 'UserSpec' into a 'B.ByteString' in a format suitable to be -- sent to the IRC server. showUserSpec :: UserSpec -> MsgString showUserSpec (Nick n) = n showUserSpec (User n u h) = B.concat [ n, B.cons '!' u, B.cons '@' h ] -- | A 'Parser' for IRC users and servers. userParser :: Parser UserSpec userParser = try full <|> nickOnly where full :: Parser UserSpec full = User <$> P.takeWhile1 isNickChar <* char '!' <*> P.takeWhile1 isUserChar <* char '@' <*> P.takeWhile1 isHostChar nickOnly :: Parser UserSpec nickOnly = Nick <$> P.takeWhile1 isNickChar
chrisdone/hulk
fastirc-0.2.0/Network/FastIRC/Users.hs
Haskell
bsd-3-clause
1,522
{-# LANGUAGE DeriveFunctor #-} module Distribution.Solver.Modular.Flag ( FInfo(..) , Flag , FlagInfo , FN(..) , QFN , QSN , SN(..) , WeakOrTrivial(..) , mkFlag , showFBool , showQFN , showQFNBool , showQSN , showQSNBool ) where import Data.Map as M import Prelude hiding (pi) import Distribution.PackageDescription hiding (Flag) -- from Cabal import Distribution.Solver.Modular.Package import Distribution.Solver.Types.OptionalStanza import Distribution.Solver.Types.PackagePath -- | Flag name. Consists of a package instance and the flag identifier itself. data FN qpn = FN (PI qpn) Flag deriving (Eq, Ord, Show, Functor) -- | Flag identifier. Just a string. type Flag = FlagName unFlag :: Flag -> String unFlag (FlagName fn) = fn mkFlag :: String -> Flag mkFlag fn = FlagName fn -- | Flag info. Default value, whether the flag is manual, and -- whether the flag is weak. Manual flags can only be set explicitly. -- Weak flags are typically deferred by the solver. data FInfo = FInfo { fdefault :: Bool, fmanual :: Bool, fweak :: WeakOrTrivial } deriving (Eq, Ord, Show) -- | Flag defaults. type FlagInfo = Map Flag FInfo -- | Qualified flag name. type QFN = FN QPN -- | Stanza name. Paired with a package name, much like a flag. data SN qpn = SN (PI qpn) OptionalStanza deriving (Eq, Ord, Show, Functor) -- | Qualified stanza name. type QSN = SN QPN -- | A property of flag and stanza choices that determines whether the -- choice should be deferred in the solving process. -- -- A choice is called weak if we do want to defer it. This is the -- case for flags that should be implied by what's currently installed on -- the system, as opposed to flags that are used to explicitly enable or -- disable some functionality. -- -- A choice is called trivial if it clearly does not matter. The -- special case of triviality we actually consider is if there are no new -- dependencies introduced by the choice. newtype WeakOrTrivial = WeakOrTrivial { unWeakOrTrivial :: Bool } deriving (Eq, Ord, Show) unStanza :: OptionalStanza -> String unStanza TestStanzas = "test" unStanza BenchStanzas = "bench" showQFNBool :: QFN -> Bool -> String showQFNBool qfn@(FN pi _f) b = showPI pi ++ ":" ++ showFBool qfn b showQSNBool :: QSN -> Bool -> String showQSNBool qsn@(SN pi _f) b = showPI pi ++ ":" ++ showSBool qsn b showFBool :: FN qpn -> Bool -> String showFBool (FN _ f) True = "+" ++ unFlag f showFBool (FN _ f) False = "-" ++ unFlag f showSBool :: SN qpn -> Bool -> String showSBool (SN _ s) True = "*" ++ unStanza s showSBool (SN _ s) False = "!" ++ unStanza s showQFN :: QFN -> String showQFN (FN pi f) = showPI pi ++ ":" ++ unFlag f showQSN :: QSN -> String showQSN (SN pi f) = showPI pi ++ ":" ++ unStanza f
kolmodin/cabal
cabal-install/Distribution/Solver/Modular/Flag.hs
Haskell
bsd-3-clause
2,796
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -O -funbox-strict-fields #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- -- (c) The University of Glasgow 2002-2006 -- -- Binary I/O library, with special tweaks for GHC -- -- Based on the nhc98 Binary library, which is copyright -- (c) Malcolm Wallace and Colin Runciman, University of York, 1998. -- Under the terms of the license for that software, we must tell you -- where you can obtain the original version of the Binary library, namely -- http://www.cs.york.ac.uk/fp/nhc98/ module Binary ( {-type-} Bin, {-class-} Binary(..), {-type-} BinHandle, SymbolTable, Dictionary, openBinMem, -- closeBin, seekBin, seekBy, tellBin, castBin, writeBinMem, readBinMem, fingerprintBinMem, computeFingerprint, isEOFBin, putAt, getAt, -- for writing instances: putByte, getByte, -- lazy Bin I/O lazyGet, lazyPut, UserData(..), getUserData, setUserData, newReadState, newWriteState, putDictionary, getDictionary, putFS, ) where #include "HsVersions.h" -- The *host* architecture version: #include "../includes/MachDeps.h" import {-# SOURCE #-} Name (Name) import FastString import Panic import UniqFM import FastMutInt import Fingerprint import BasicTypes import SrcLoc import Foreign import Data.Array import Data.ByteString (ByteString) import qualified Data.ByteString.Internal as BS import qualified Data.ByteString.Unsafe as BS import Data.IORef import Data.Char ( ord, chr ) import Data.Time import Data.Typeable import Control.Monad ( when ) import System.IO as IO import System.IO.Unsafe ( unsafeInterleaveIO ) import System.IO.Error ( mkIOError, eofErrorType ) import GHC.Real ( Ratio(..) ) type BinArray = ForeignPtr Word8 --------------------------------------------------------------- -- BinHandle --------------------------------------------------------------- data BinHandle = BinMem { -- binary data stored in an unboxed array bh_usr :: UserData, -- sigh, need parameterized modules :-) _off_r :: !FastMutInt, -- the current offset _sz_r :: !FastMutInt, -- size of the array (cached) _arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1)) } -- XXX: should really store a "high water mark" for dumping out -- the binary data to a file. getUserData :: BinHandle -> UserData getUserData bh = bh_usr bh setUserData :: BinHandle -> UserData -> BinHandle setUserData bh us = bh { bh_usr = us } --------------------------------------------------------------- -- Bin --------------------------------------------------------------- newtype Bin a = BinPtr Int deriving (Eq, Ord, Show, Bounded) castBin :: Bin a -> Bin b castBin (BinPtr i) = BinPtr i --------------------------------------------------------------- -- class Binary --------------------------------------------------------------- class Binary a where put_ :: BinHandle -> a -> IO () put :: BinHandle -> a -> IO (Bin a) get :: BinHandle -> IO a -- define one of put_, put. Use of put_ is recommended because it -- is more likely that tail-calls can kick in, and we rarely need the -- position return value. put_ bh a = do _ <- put bh a; return () put bh a = do p <- tellBin bh; put_ bh a; return p putAt :: Binary a => BinHandle -> Bin a -> a -> IO () putAt bh p x = do seekBin bh p; put_ bh x; return () getAt :: Binary a => BinHandle -> Bin a -> IO a getAt bh p = do seekBin bh p; get bh openBinMem :: Int -> IO BinHandle openBinMem size | size <= 0 = error "Data.Binary.openBinMem: size must be >= 0" | otherwise = do arr <- mallocForeignPtrBytes size arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r size return (BinMem noUserData ix_r sz_r arr_r) tellBin :: BinHandle -> IO (Bin a) tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix) seekBin :: BinHandle -> Bin a -> IO () seekBin h@(BinMem _ ix_r sz_r _) (BinPtr p) = do sz <- readFastMutInt sz_r if (p >= sz) then do expandBin h p; writeFastMutInt ix_r p else writeFastMutInt ix_r p seekBy :: BinHandle -> Int -> IO () seekBy h@(BinMem _ ix_r sz_r _) off = do sz <- readFastMutInt sz_r ix <- readFastMutInt ix_r let ix' = ix + off if (ix' >= sz) then do expandBin h ix'; writeFastMutInt ix_r ix' else writeFastMutInt ix_r ix' isEOFBin :: BinHandle -> IO Bool isEOFBin (BinMem _ ix_r sz_r _) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r return (ix >= sz) writeBinMem :: BinHandle -> FilePath -> IO () writeBinMem (BinMem _ ix_r _ arr_r) fn = do h <- openBinaryFile fn WriteMode arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \p -> hPutBuf h p ix hClose h readBinMem :: FilePath -> IO BinHandle -- Return a BinHandle with a totally undefined State readBinMem filename = do h <- openBinaryFile filename ReadMode filesize' <- hFileSize h let filesize = fromIntegral filesize' arr <- mallocForeignPtrBytes (filesize*2) count <- withForeignPtr arr $ \p -> hGetBuf h p filesize when (count /= filesize) $ error ("Binary.readBinMem: only read " ++ show count ++ " bytes") hClose h arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r filesize return (BinMem noUserData ix_r sz_r arr_r) fingerprintBinMem :: BinHandle -> IO Fingerprint fingerprintBinMem (BinMem _ ix_r _ arr_r) = do arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \p -> fingerprintData p ix computeFingerprint :: Binary a => (BinHandle -> Name -> IO ()) -> a -> IO Fingerprint computeFingerprint put_name a = do bh <- openBinMem (3*1024) -- just less than a block bh <- return $ setUserData bh $ newWriteState put_name putFS put_ bh a fingerprintBinMem bh -- expand the size of the array to include a specified offset expandBin :: BinHandle -> Int -> IO () expandBin (BinMem _ _ sz_r arr_r) off = do sz <- readFastMutInt sz_r let sz' = head (dropWhile (<= off) (iterate (* 2) sz)) arr <- readIORef arr_r arr' <- mallocForeignPtrBytes sz' withForeignPtr arr $ \old -> withForeignPtr arr' $ \new -> copyBytes new old sz writeFastMutInt sz_r sz' writeIORef arr_r arr' -- ----------------------------------------------------------------------------- -- Low-level reading/writing of bytes putWord8 :: BinHandle -> Word8 -> IO () putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r -- double the size of the array if it overflows if (ix >= sz) then do expandBin h ix putWord8 h w else do arr <- readIORef arr_r withForeignPtr arr $ \p -> pokeByteOff p ix w writeFastMutInt ix_r (ix+1) return () getWord8 :: BinHandle -> IO Word8 getWord8 (BinMem _ ix_r sz_r arr_r) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r when (ix >= sz) $ ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing) arr <- readIORef arr_r w <- withForeignPtr arr $ \p -> peekByteOff p ix writeFastMutInt ix_r (ix+1) return w putByte :: BinHandle -> Word8 -> IO () putByte bh w = put_ bh w getByte :: BinHandle -> IO Word8 getByte = getWord8 -- ----------------------------------------------------------------------------- -- Primitve Word writes instance Binary Word8 where put_ = putWord8 get = getWord8 instance Binary Word16 where put_ h w = do -- XXX too slow.. inline putWord8? putByte h (fromIntegral (w `shiftR` 8)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2) instance Binary Word32 where put_ h w = do putByte h (fromIntegral (w `shiftR` 24)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 24) .|. (fromIntegral w2 `shiftL` 16) .|. (fromIntegral w3 `shiftL` 8) .|. (fromIntegral w4)) instance Binary Word64 where put_ h w = do putByte h (fromIntegral (w `shiftR` 56)) putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h w5 <- getWord8 h w6 <- getWord8 h w7 <- getWord8 h w8 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 56) .|. (fromIntegral w2 `shiftL` 48) .|. (fromIntegral w3 `shiftL` 40) .|. (fromIntegral w4 `shiftL` 32) .|. (fromIntegral w5 `shiftL` 24) .|. (fromIntegral w6 `shiftL` 16) .|. (fromIntegral w7 `shiftL` 8) .|. (fromIntegral w8)) -- ----------------------------------------------------------------------------- -- Primitve Int writes instance Binary Int8 where put_ h w = put_ h (fromIntegral w :: Word8) get h = do w <- get h; return $! (fromIntegral (w::Word8)) instance Binary Int16 where put_ h w = put_ h (fromIntegral w :: Word16) get h = do w <- get h; return $! (fromIntegral (w::Word16)) instance Binary Int32 where put_ h w = put_ h (fromIntegral w :: Word32) get h = do w <- get h; return $! (fromIntegral (w::Word32)) instance Binary Int64 where put_ h w = put_ h (fromIntegral w :: Word64) get h = do w <- get h; return $! (fromIntegral (w::Word64)) -- ----------------------------------------------------------------------------- -- Instances for standard types instance Binary () where put_ _ () = return () get _ = return () instance Binary Bool where put_ bh b = putByte bh (fromIntegral (fromEnum b)) get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x)) instance Binary Char where put_ bh c = put_ bh (fromIntegral (ord c) :: Word32) get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word32))) instance Binary Int where put_ bh i = put_ bh (fromIntegral i :: Int64) get bh = do x <- get bh return $! (fromIntegral (x :: Int64)) instance Binary a => Binary [a] where put_ bh l = do let len = length l if (len < 0xff) then putByte bh (fromIntegral len :: Word8) else do putByte bh 0xff; put_ bh (fromIntegral len :: Word32) mapM_ (put_ bh) l get bh = do b <- getByte bh len <- if b == 0xff then get bh else return (fromIntegral b :: Word32) let loop 0 = return [] loop n = do a <- get bh; as <- loop (n-1); return (a:as) loop len instance (Binary a, Binary b) => Binary (a,b) where put_ bh (a,b) = do put_ bh a; put_ bh b get bh = do a <- get bh b <- get bh return (a,b) instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (a,b,c) instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d get bh = do a <- get bh b <- get bh c <- get bh d <- get bh return (a,b,c,d) instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d, e) where put_ bh (a,b,c,d, e) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh return (a,b,c,d,e) instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f) => Binary (a,b,c,d, e, f) where put_ bh (a,b,c,d, e, f) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; put_ bh f; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh f <- get bh return (a,b,c,d,e,f) instance Binary a => Binary (Maybe a) where put_ bh Nothing = putByte bh 0 put_ bh (Just a) = do putByte bh 1; put_ bh a get bh = do h <- getWord8 bh case h of 0 -> return Nothing _ -> do x <- get bh; return (Just x) instance (Binary a, Binary b) => Binary (Either a b) where put_ bh (Left a) = do putByte bh 0; put_ bh a put_ bh (Right b) = do putByte bh 1; put_ bh b get bh = do h <- getWord8 bh case h of 0 -> do a <- get bh ; return (Left a) _ -> do b <- get bh ; return (Right b) instance Binary UTCTime where put_ bh u = do put_ bh (utctDay u) put_ bh (utctDayTime u) get bh = do day <- get bh dayTime <- get bh return $ UTCTime { utctDay = day, utctDayTime = dayTime } instance Binary Day where put_ bh d = put_ bh (toModifiedJulianDay d) get bh = do i <- get bh return $ ModifiedJulianDay { toModifiedJulianDay = i } instance Binary DiffTime where put_ bh dt = put_ bh (toRational dt) get bh = do r <- get bh return $ fromRational r --to quote binary-0.3 on this code idea, -- -- TODO This instance is not architecture portable. GMP stores numbers as -- arrays of machine sized words, so the byte format is not portable across -- architectures with different endianess and word size. -- -- This makes it hard (impossible) to make an equivalent instance -- with code that is compilable with non-GHC. Do we need any instance -- Binary Integer, and if so, does it have to be blazing fast? Or can -- we just change this instance to be portable like the rest of the -- instances? (binary package has code to steal for that) -- -- yes, we need Binary Integer and Binary Rational in basicTypes/Literal.hs instance Binary Integer where -- XXX This is hideous put_ bh i = put_ bh (show i) get bh = do str <- get bh case reads str of [(i, "")] -> return i _ -> fail ("Binary Integer: got " ++ show str) {- -- This code is currently commented out. -- See https://ghc.haskell.org/trac/ghc/ticket/3379#comment:10 for -- discussion. put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#) put_ bh (J# s# a#) = do putByte bh 1 put_ bh (I# s#) let sz# = sizeofByteArray# a# -- in *bytes* put_ bh (I# sz#) -- in *bytes* putByteArray bh a# sz# get bh = do b <- getByte bh case b of 0 -> do (I# i#) <- get bh return (S# i#) _ -> do (I# s#) <- get bh sz <- get bh (BA a#) <- getByteArray bh sz return (J# s# a#) putByteArray :: BinHandle -> ByteArray# -> Int# -> IO () putByteArray bh a s# = loop 0# where loop n# | n# ==# s# = return () | otherwise = do putByte bh (indexByteArray a n#) loop (n# +# 1#) getByteArray :: BinHandle -> Int -> IO ByteArray getByteArray bh (I# sz) = do (MBA arr) <- newByteArray sz let loop n | n ==# sz = return () | otherwise = do w <- getByte bh writeByteArray arr n w loop (n +# 1#) loop 0# freezeByteArray arr -} {- data ByteArray = BA ByteArray# data MBA = MBA (MutableByteArray# RealWorld) newByteArray :: Int# -> IO MBA newByteArray sz = IO $ \s -> case newByteArray# sz s of { (# s, arr #) -> (# s, MBA arr #) } freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray freezeByteArray arr = IO $ \s -> case unsafeFreezeByteArray# arr s of { (# s, arr #) -> (# s, BA arr #) } writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO () writeByteArray arr i (W8# w) = IO $ \s -> case writeWord8Array# arr i w s of { s -> (# s, () #) } indexByteArray :: ByteArray# -> Int# -> Word8 indexByteArray a# n# = W8# (indexWord8Array# a# n#) -} instance (Binary a) => Binary (Ratio a) where put_ bh (a :% b) = do put_ bh a; put_ bh b get bh = do a <- get bh; b <- get bh; return (a :% b) instance Binary (Bin a) where put_ bh (BinPtr i) = put_ bh (fromIntegral i :: Int32) get bh = do i <- get bh; return (BinPtr (fromIntegral (i :: Int32))) -- ----------------------------------------------------------------------------- -- Instances for Data.Typeable stuff instance Binary TyCon where put_ bh tc = do put_ bh (tyConPackage tc) put_ bh (tyConModule tc) put_ bh (tyConName tc) get bh = do p <- get bh m <- get bh n <- get bh return (mkTyCon3 p m n) instance Binary TypeRep where put_ bh type_rep = do let (ty_con, child_type_reps) = splitTyConApp type_rep put_ bh ty_con put_ bh child_type_reps get bh = do ty_con <- get bh child_type_reps <- get bh return (mkTyConApp ty_con child_type_reps) -- ----------------------------------------------------------------------------- -- Lazy reading/writing lazyPut :: Binary a => BinHandle -> a -> IO () lazyPut bh a = do -- output the obj with a ptr to skip over it: pre_a <- tellBin bh put_ bh pre_a -- save a slot for the ptr put_ bh a -- dump the object q <- tellBin bh -- q = ptr to after object putAt bh pre_a q -- fill in slot before a with ptr to q seekBin bh q -- finally carry on writing at q lazyGet :: Binary a => BinHandle -> IO a lazyGet bh = do p <- get bh -- a BinPtr p_a <- tellBin bh a <- unsafeInterleaveIO $ do -- NB: Use a fresh off_r variable in the child thread, for thread -- safety. off_r <- newFastMutInt getAt bh { _off_r = off_r } p_a seekBin bh p -- skip over the object for now return a -- ----------------------------------------------------------------------------- -- UserData -- ----------------------------------------------------------------------------- data UserData = UserData { -- for *deserialising* only: ud_get_name :: BinHandle -> IO Name, ud_get_fs :: BinHandle -> IO FastString, -- for *serialising* only: ud_put_name :: BinHandle -> Name -> IO (), ud_put_fs :: BinHandle -> FastString -> IO () } newReadState :: (BinHandle -> IO Name) -> (BinHandle -> IO FastString) -> UserData newReadState get_name get_fs = UserData { ud_get_name = get_name, ud_get_fs = get_fs, ud_put_name = undef "put_name", ud_put_fs = undef "put_fs" } newWriteState :: (BinHandle -> Name -> IO ()) -> (BinHandle -> FastString -> IO ()) -> UserData newWriteState put_name put_fs = UserData { ud_get_name = undef "get_name", ud_get_fs = undef "get_fs", ud_put_name = put_name, ud_put_fs = put_fs } noUserData :: a noUserData = undef "UserData" undef :: String -> a undef s = panic ("Binary.UserData: no " ++ s) --------------------------------------------------------- -- The Dictionary --------------------------------------------------------- type Dictionary = Array Int FastString -- The dictionary -- Should be 0-indexed putDictionary :: BinHandle -> Int -> UniqFM (Int,FastString) -> IO () putDictionary bh sz dict = do put_ bh sz mapM_ (putFS bh) (elems (array (0,sz-1) (eltsUFM dict))) getDictionary :: BinHandle -> IO Dictionary getDictionary bh = do sz <- get bh elems <- sequence (take sz (repeat (getFS bh))) return (listArray (0,sz-1) elems) --------------------------------------------------------- -- The Symbol Table --------------------------------------------------------- -- On disk, the symbol table is an array of IfaceExtName, when -- reading it in we turn it into a SymbolTable. type SymbolTable = Array Int Name --------------------------------------------------------- -- Reading and writing FastStrings --------------------------------------------------------- putFS :: BinHandle -> FastString -> IO () putFS bh fs = putBS bh $ fastStringToByteString fs getFS :: BinHandle -> IO FastString getFS bh = do bs <- getBS bh return $! mkFastStringByteString bs putBS :: BinHandle -> ByteString -> IO () putBS bh bs = BS.unsafeUseAsCStringLen bs $ \(ptr, l) -> do put_ bh l let go n | n == l = return () | otherwise = do b <- peekElemOff (castPtr ptr) n putByte bh b go (n+1) go 0 {- -- possible faster version, not quite there yet: getBS bh@BinMem{} = do (I# l) <- get bh arr <- readIORef (arr_r bh) off <- readFastMutInt (off_r bh) return $! (mkFastSubBytesBA# arr off l) -} getBS :: BinHandle -> IO ByteString getBS bh = do l <- get bh fp <- mallocForeignPtrBytes l withForeignPtr fp $ \ptr -> do let go n | n == l = return $ BS.fromForeignPtr fp 0 l | otherwise = do b <- getByte bh pokeElemOff ptr n b go (n+1) -- go 0 instance Binary ByteString where put_ bh f = putBS bh f get bh = getBS bh instance Binary FastString where put_ bh f = case getUserData bh of UserData { ud_put_fs = put_fs } -> put_fs bh f get bh = case getUserData bh of UserData { ud_get_fs = get_fs } -> get_fs bh -- Here to avoid loop instance Binary Fingerprint where put_ h (Fingerprint w1 w2) = do put_ h w1; put_ h w2 get h = do w1 <- get h; w2 <- get h; return (Fingerprint w1 w2) instance Binary FunctionOrData where put_ bh IsFunction = putByte bh 0 put_ bh IsData = putByte bh 1 get bh = do h <- getByte bh case h of 0 -> return IsFunction 1 -> return IsData _ -> panic "Binary FunctionOrData" instance Binary TupleSort where put_ bh BoxedTuple = putByte bh 0 put_ bh UnboxedTuple = putByte bh 1 put_ bh ConstraintTuple = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return BoxedTuple 1 -> do return UnboxedTuple _ -> do return ConstraintTuple instance Binary Activation where put_ bh NeverActive = do putByte bh 0 put_ bh AlwaysActive = do putByte bh 1 put_ bh (ActiveBefore aa) = do putByte bh 2 put_ bh aa put_ bh (ActiveAfter ab) = do putByte bh 3 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do return NeverActive 1 -> do return AlwaysActive 2 -> do aa <- get bh return (ActiveBefore aa) _ -> do ab <- get bh return (ActiveAfter ab) instance Binary InlinePragma where put_ bh (InlinePragma s a b c d) = do put_ bh s put_ bh a put_ bh b put_ bh c put_ bh d get bh = do s <- get bh a <- get bh b <- get bh c <- get bh d <- get bh return (InlinePragma s a b c d) instance Binary RuleMatchInfo where put_ bh FunLike = putByte bh 0 put_ bh ConLike = putByte bh 1 get bh = do h <- getByte bh if h == 1 then return ConLike else return FunLike instance Binary InlineSpec where put_ bh EmptyInlineSpec = putByte bh 0 put_ bh Inline = putByte bh 1 put_ bh Inlinable = putByte bh 2 put_ bh NoInline = putByte bh 3 get bh = do h <- getByte bh case h of 0 -> return EmptyInlineSpec 1 -> return Inline 2 -> return Inlinable _ -> return NoInline instance Binary DefMethSpec where put_ bh NoDM = putByte bh 0 put_ bh VanillaDM = putByte bh 1 put_ bh GenericDM = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> return NoDM 1 -> return VanillaDM _ -> return GenericDM instance Binary RecFlag where put_ bh Recursive = do putByte bh 0 put_ bh NonRecursive = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return Recursive _ -> do return NonRecursive instance Binary OverlapMode where put_ bh (NoOverlap s) = putByte bh 0 >> put_ bh s put_ bh (Overlaps s) = putByte bh 1 >> put_ bh s put_ bh (Incoherent s) = putByte bh 2 >> put_ bh s put_ bh (Overlapping s) = putByte bh 3 >> put_ bh s put_ bh (Overlappable s) = putByte bh 4 >> put_ bh s get bh = do h <- getByte bh case h of 0 -> (get bh) >>= \s -> return $ NoOverlap s 1 -> (get bh) >>= \s -> return $ Overlaps s 2 -> (get bh) >>= \s -> return $ Incoherent s 3 -> (get bh) >>= \s -> return $ Overlapping s 4 -> (get bh) >>= \s -> return $ Overlappable s _ -> panic ("get OverlapMode" ++ show h) instance Binary OverlapFlag where put_ bh flag = do put_ bh (overlapMode flag) put_ bh (isSafeOverlap flag) get bh = do h <- get bh b <- get bh return OverlapFlag { overlapMode = h, isSafeOverlap = b } instance Binary FixityDirection where put_ bh InfixL = do putByte bh 0 put_ bh InfixR = do putByte bh 1 put_ bh InfixN = do putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return InfixL 1 -> do return InfixR _ -> do return InfixN instance Binary Fixity where put_ bh (Fixity aa ab) = do put_ bh aa put_ bh ab get bh = do aa <- get bh ab <- get bh return (Fixity aa ab) instance Binary WarningTxt where put_ bh (WarningTxt s w) = do putByte bh 0 put_ bh s put_ bh w put_ bh (DeprecatedTxt s d) = do putByte bh 1 put_ bh s put_ bh d get bh = do h <- getByte bh case h of 0 -> do s <- get bh w <- get bh return (WarningTxt s w) _ -> do s <- get bh d <- get bh return (DeprecatedTxt s d) instance Binary StringLiteral where put_ bh (StringLiteral st fs) = do put_ bh st put_ bh fs get bh = do st <- get bh fs <- get bh return (StringLiteral st fs) instance Binary a => Binary (GenLocated SrcSpan a) where put_ bh (L l x) = do put_ bh l put_ bh x get bh = do l <- get bh x <- get bh return (L l x) instance Binary SrcSpan where put_ bh (RealSrcSpan ss) = do putByte bh 0 put_ bh (srcSpanFile ss) put_ bh (srcSpanStartLine ss) put_ bh (srcSpanStartCol ss) put_ bh (srcSpanEndLine ss) put_ bh (srcSpanEndCol ss) put_ bh (UnhelpfulSpan s) = do putByte bh 1 put_ bh s get bh = do h <- getByte bh case h of 0 -> do f <- get bh sl <- get bh sc <- get bh el <- get bh ec <- get bh return (mkSrcSpan (mkSrcLoc f sl sc) (mkSrcLoc f el ec)) _ -> do s <- get bh return (UnhelpfulSpan s)
AlexanderPankiv/ghc
compiler/utils/Binary.hs
Haskell
bsd-3-clause
29,290
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ {-# LANGUAGE MagicHash #-} #endif #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.BitUtil -- Copyright : (c) Clark Gaebel 2012 -- (c) Johan Tibel 2012 -- License : BSD-style -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable ----------------------------------------------------------------------------- module Data.BitUtil ( highestBitMask ) where -- On GHC, include MachDeps.h to get WORD_SIZE_IN_BITS macro. #if defined(__GLASGOW_HASKELL__) # include "MachDeps.h" #endif import Data.Bits ((.|.), xor) #if __GLASGOW_HASKELL__ import GHC.Exts (Word(..), Int(..)) import GHC.Prim (uncheckedShiftRL#) #else import Data.Word (shiftL, shiftR) #endif -- The highestBitMask implementation is based on -- http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 -- which has been put in the public domain. -- | Return a word where only the highest bit is set. highestBitMask :: Word -> Word highestBitMask x1 = let x2 = x1 .|. x1 `shiftRL` 1 x3 = x2 .|. x2 `shiftRL` 2 x4 = x3 .|. x3 `shiftRL` 4 x5 = x4 .|. x4 `shiftRL` 8 x6 = x5 .|. x5 `shiftRL` 16 #if !(defined(__GLASGOW_HASKELL__) && WORD_SIZE_IN_BITS==32) x7 = x6 .|. x6 `shiftRL` 32 in x7 `xor` (x7 `shiftRL` 1) #else in x6 `xor` (x6 `shiftRL` 1) #endif {-# INLINE highestBitMask #-} -- Right and left logical shifts. shiftRL :: Word -> Int -> Word #if __GLASGOW_HASKELL__ {-------------------------------------------------------------------- GHC: use unboxing to get @shiftRL@ inlined. --------------------------------------------------------------------} shiftRL (W# x) (I# i) = W# (uncheckedShiftRL# x i) #else shiftRL x i = shiftR x i #endif {-# INLINE shiftRL #-}
ariep/psqueues
src/Data/BitUtil.hs
Haskell
bsd-3-clause
2,071
yes = mapMaybe id
mpickering/hlint-refactor
tests/examples/Default72.hs
Haskell
bsd-3-clause
17
<?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="sr-CS"> <title>Encode/Decode/Hash Add-on</title> <maps> <homeID>encoder</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/encoder/src/main/javahelp/org/zaproxy/addon/encoder/resources/help_sr_CS/helpset_sr_CS.hs
Haskell
apache-2.0
974
module Options.Phases where import Types phaseOptions :: [Flag] phaseOptions = [ flag { flagName = "-F" , flagDescription = "Enable the use of a :ref:`pre-processor <pre-processor>` "++ "(set with ``-pgmF``)" , flagType = DynamicFlag } , flag { flagName = "-E" , flagDescription = "Stop after preprocessing (``.hspp`` file)" , flagType = ModeFlag } , flag { flagName = "-C" , flagDescription = "Stop after generating C (``.hc`` file)" , flagType = ModeFlag } , flag { flagName = "-S" , flagDescription = "Stop after generating assembly (``.s`` file)" , flagType = ModeFlag } , flag { flagName = "-c" , flagDescription = "Stop after generating object (``.o``) file" , flagType = ModeFlag } , flag { flagName = "-x⟨suffix⟩" , flagDescription = "Override default behaviour for source files" , flagType = DynamicFlag } ]
ml9951/ghc
utils/mkUserGuidePart/Options/Phases.hs
Haskell
bsd-3-clause
1,021
{-# LANGUAGE Unsafe #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.ForeignPtr -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- The 'ForeignPtr' type and operations. This module is part of the -- Foreign Function Interface (FFI) and will usually be imported via -- the "Foreign" module. -- ----------------------------------------------------------------------------- module Foreign.ForeignPtr ( -- * Finalised data pointers ForeignPtr , FinalizerPtr , FinalizerEnvPtr -- ** Basic operations , newForeignPtr , newForeignPtr_ , addForeignPtrFinalizer , newForeignPtrEnv , addForeignPtrFinalizerEnv , withForeignPtr , finalizeForeignPtr -- ** Low-level operations , touchForeignPtr , castForeignPtr -- ** Allocating managed memory , mallocForeignPtr , mallocForeignPtrBytes , mallocForeignPtrArray , mallocForeignPtrArray0 ) where import Foreign.ForeignPtr.Safe
lukexi/ghc
libraries/base/Foreign/ForeignPtr.hs
Haskell
bsd-3-clause
1,306
{-# LANGUAGE FunctionalDependencies, PolyKinds, FlexibleInstances #-} module T10570 where import Data.Proxy class ConsByIdx2 x a m cls | x -> m where consByIdx2 :: x -> a -> m cls instance ConsByIdx2 Int a Proxy cls where consByIdx2 _ _ = Proxy
urbanslug/ghc
testsuite/tests/polykinds/T10570.hs
Haskell
bsd-3-clause
257
{-# LANGUAGE NamedWildCards, ScopedTypeVariables #-} module WildcardsInPatternAndExprSig where bar (Just ([x :: _a] :: _) :: Maybe [_b]) (z :: _c) = [x, z] :: [_d]
urbanslug/ghc
testsuite/tests/partial-sigs/should_fail/WildcardsInPatternAndExprSig.hs
Haskell
bsd-3-clause
165
{-# LANGUAGE UnicodeSyntax #-} module Pixs.Operations.PointOperations where import Pixs.Information.Histogram (colorCount) import Codec.Picture (Image, PixelRGBA8(..), pixelAt, generateImage, imageWidth, imageHeight) import Pixs.Types (Color(..)) import qualified Data.Map as M -- | Thresholds an image by pixel intensity. We define the intensity of a given -- pixel (PixelRGBA8 r g b a)¹ to be the sum of the number of pixels with the -- components r, g, b, and a. @threshold@ sifts out all pixels that have -- intensity greater than the given threshold `n`. This is useful for things -- like separating the backfground from the foreground. A complete explanation -- of thresholding is given at: -- http://homepages.inf.ed.ac.uk/rbf/HIPR2/threshld.htm -- -- <<docs/example.png>> <<docs/example-thresholded.png>> -- -- ¹: If that's not clear, I'm doing destructuring in the English language. threshold ∷ Int → Image PixelRGBA8 → Image PixelRGBA8 threshold n img = let black = PixelRGBA8 0 0 0 0xFF white = PixelRGBA8 0xFF 0xFF 0xFF 0XFF [redMap, greenMap, blueMap] = colorCount img <$> [Red, Green, Blue] -- Dictionary meaning of "to thresh": separate grain from (a plant), -- typically with a flail or by the action of a revolving mechanism: -- machinery that can reap and thresh corn in the same process | (as noun -- threshing) : farm workers started the afternoon's threshing. thresh x y = let (PixelRGBA8 r g b _) = pixelAt img x y (■) = zipWith id intensity = (sum $ (M.findWithDefault 0 <$> [r, g, b]) ■ [redMap, greenMap, blueMap]) `div` 3 in if (intensity > n) then black else white in generateImage thresh (imageWidth img) (imageHeight img)
ayberkt/pixs
src/Pixs/Operations/PointOperations.hs
Haskell
mit
2,041
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module LDAP.Classy.Types where import Control.Lens import Data.String (IsString) import Data.Text (Text) import Prelude (Eq, Int, Num, Show) newtype Uid = Uid Text deriving (Show,IsString,Eq) makeWrapped ''Uid newtype UidNumber = UidNumber Int deriving (Show,Num,Eq) makeWrapped ''UidNumber newtype GidNumber = GidNumber Int deriving (Show,Num,Eq) makeWrapped ''GidNumber
benkolera/haskell-ldap-classy
LDAP/Classy/Types.hs
Haskell
mit
689
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE CPP #-} -- | Various utilities used in the scaffolded site. module Yesod.Default.Util ( addStaticContentExternal , globFile , widgetFileNoReload , widgetFileReload , TemplateLanguage (..) , defaultTemplateLanguages , WidgetFileSettings , wfsLanguages , wfsHamletSettings ) where import qualified Data.ByteString.Lazy as L import Data.Text (Text, pack, unpack) import Yesod.Core -- purposely using complete import so that Haddock will see addStaticContent import Control.Monad (when, unless) import Control.Monad.Trans.Resource (runResourceT) import Data.Conduit (($$)) import Data.Conduit.Binary (sourceLbs, sinkFileCautious) import System.Directory (doesFileExist, createDirectoryIfMissing) import Language.Haskell.TH.Syntax import Text.Lucius (luciusFile, luciusFileReload) import Text.Julius (juliusFile, juliusFileReload) import Text.Cassius (cassiusFile, cassiusFileReload) import Text.Hamlet (HamletSettings, defaultHamletSettings) import Data.Maybe (catMaybes) import Data.Default.Class (Default (def)) -- | An implementation of 'addStaticContent' which stores the contents in an -- external file. Files are created in the given static folder with names 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. addStaticContentExternal :: (L.ByteString -> Either a L.ByteString) -- ^ javascript minifier -> (L.ByteString -> String) -- ^ hash function to determine file name -> FilePath -- ^ location of static directory. files will be placed within a "tmp" subfolder -> ([Text] -> Route master) -- ^ route constructor, taking a list of pieces -> Text -- ^ filename extension -> Text -- ^ mime type -> L.ByteString -- ^ file contents -> HandlerT master IO (Maybe (Either Text (Route master, [(Text, Text)]))) addStaticContentExternal minify hash staticDir toRoute ext' _ content = do liftIO $ createDirectoryIfMissing True statictmp exists <- liftIO $ doesFileExist fn' unless exists $ liftIO $ runResourceT $ sourceLbs content' $$ sinkFileCautious fn' return $ Just $ Right (toRoute ["tmp", pack fn], []) where fn, statictmp, fn' :: FilePath -- by basing the hash off of the un-minified content, we avoid a costly -- minification if the file already exists fn = hash content ++ '.' : unpack ext' statictmp = staticDir ++ "/tmp/" fn' = statictmp ++ fn content' :: L.ByteString content' | ext' == "js" = either (const content) id $ minify content | otherwise = content -- | expects a file extension for each type, e.g: hamlet lucius julius globFile :: String -> String -> FilePath globFile kind x = "templates/" ++ x ++ "." ++ kind data TemplateLanguage = TemplateLanguage { tlRequiresToWidget :: Bool , tlExtension :: String , tlNoReload :: FilePath -> Q Exp , tlReload :: FilePath -> Q Exp } defaultTemplateLanguages :: HamletSettings -> [TemplateLanguage] defaultTemplateLanguages hset = [ TemplateLanguage False "hamlet" whamletFile' whamletFile' , TemplateLanguage True "cassius" cassiusFile cassiusFileReload , TemplateLanguage True "julius" juliusFile juliusFileReload , TemplateLanguage True "lucius" luciusFile luciusFileReload ] where whamletFile' = whamletFileWithSettings hset data WidgetFileSettings = WidgetFileSettings { wfsLanguages :: HamletSettings -> [TemplateLanguage] , wfsHamletSettings :: HamletSettings } instance Default WidgetFileSettings where def = WidgetFileSettings defaultTemplateLanguages defaultHamletSettings widgetFileNoReload :: WidgetFileSettings -> FilePath -> Q Exp widgetFileNoReload wfs x = combine "widgetFileNoReload" x False $ wfsLanguages wfs $ wfsHamletSettings wfs widgetFileReload :: WidgetFileSettings -> FilePath -> Q Exp widgetFileReload wfs x = combine "widgetFileReload" x True $ wfsLanguages wfs $ wfsHamletSettings wfs combine :: String -> String -> Bool -> [TemplateLanguage] -> Q Exp combine func file isReload tls = do mexps <- qmexps case catMaybes mexps of [] -> error $ concat [ "Called " , func , " on " , show file , ", but no templates were found." ] exps -> return $ DoE $ map NoBindS exps where qmexps :: Q [Maybe Exp] qmexps = mapM go tls go :: TemplateLanguage -> Q (Maybe Exp) go tl = whenExists file (tlRequiresToWidget tl) (tlExtension tl) ((if isReload then tlReload else tlNoReload) tl) whenExists :: String -> Bool -- ^ requires toWidget wrap -> String -> (FilePath -> Q Exp) -> Q (Maybe Exp) whenExists = warnUnlessExists False warnUnlessExists :: Bool -> String -> Bool -- ^ requires toWidget wrap -> String -> (FilePath -> Q Exp) -> Q (Maybe Exp) warnUnlessExists shouldWarn x wrap glob f = do let fn = globFile glob x e <- qRunIO $ doesFileExist fn when (shouldWarn && not e) $ qRunIO $ putStrLn $ "widget file not found: " ++ fn if e then do ex <- f fn if wrap then do tw <- [|toWidget|] return $ Just $ tw `AppE` ex else return $ Just ex else return Nothing
tolysz/yesod
yesod/Yesod/Default/Util.hs
Haskell
mit
5,460