code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE TemplateHaskell #-} {-| Implementation of the Ganeti LUXI interface. -} {- Copyright (C) 2009, 2010, 2011, 2012 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Luxi ( LuxiOp(..) , LuxiReq(..) , Client , JobId , fromJobId , makeJobId , RecvResult(..) , strOfOp , getClient , getServer , acceptClient , closeClient , closeServer , callMethod , submitManyJobs , queryJobsStatus , buildCall , buildResponse , validateCall , decodeCall , recvMsg , recvMsgExt , sendMsg , allLuxiCalls ) where import Control.Exception (catch) import Data.IORef import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.ByteString.Lazy.UTF8 as UTF8L import Data.Word (Word8) import Control.Monad import Text.JSON (encodeStrict, decodeStrict) import qualified Text.JSON as J import Text.JSON.Pretty (pp_value) import Text.JSON.Types import System.Directory (removeFile) import System.IO (hClose, hFlush, hWaitForInput, Handle, IOMode(..)) import System.IO.Error (isEOFError) import System.Timeout import qualified Network.Socket as S import Ganeti.BasicTypes import Ganeti.Constants import Ganeti.Errors import Ganeti.JSON import Ganeti.OpParams (pTagsObject) import Ganeti.OpCodes import Ganeti.Runtime import qualified Ganeti.Query.Language as Qlang import Ganeti.THH import Ganeti.Types import Ganeti.Utils -- * Utility functions -- | Wrapper over System.Timeout.timeout that fails in the IO monad. withTimeout :: Int -> String -> IO a -> IO a withTimeout secs descr action = do result <- timeout (secs * 1000000) action case result of Nothing -> fail $ "Timeout in " ++ descr Just v -> return v -- * Generic protocol functionality -- | Result of receiving a message from the socket. data RecvResult = RecvConnClosed -- ^ Connection closed | RecvError String -- ^ Any other error | RecvOk String -- ^ Successfull receive deriving (Show, Eq) -- | Currently supported Luxi operations and JSON serialization. $(genLuxiOp "LuxiOp" [ (luxiReqQuery, [ simpleField "what" [t| Qlang.ItemType |] , simpleField "fields" [t| [String] |] , simpleField "qfilter" [t| Qlang.Filter Qlang.FilterField |] ]) , (luxiReqQueryFields, [ simpleField "what" [t| Qlang.ItemType |] , simpleField "fields" [t| [String] |] ]) , (luxiReqQueryNodes, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryGroups, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryNetworks, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryInstances, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryJobs, [ simpleField "ids" [t| [JobId] |] , simpleField "fields" [t| [String] |] ]) , (luxiReqQueryExports, [ simpleField "nodes" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryConfigValues, [ simpleField "fields" [t| [String] |] ] ) , (luxiReqQueryClusterInfo, []) , (luxiReqQueryTags, [ pTagsObject ]) , (luxiReqSubmitJob, [ simpleField "job" [t| [MetaOpCode] |] ] ) , (luxiReqSubmitManyJobs, [ simpleField "ops" [t| [[MetaOpCode]] |] ] ) , (luxiReqWaitForJobChange, [ simpleField "job" [t| JobId |] , simpleField "fields" [t| [String]|] , simpleField "prev_job" [t| JSValue |] , simpleField "prev_log" [t| JSValue |] , simpleField "tmout" [t| Int |] ]) , (luxiReqArchiveJob, [ simpleField "job" [t| JobId |] ] ) , (luxiReqAutoArchiveJobs, [ simpleField "age" [t| Int |] , simpleField "tmout" [t| Int |] ]) , (luxiReqCancelJob, [ simpleField "job" [t| JobId |] ] ) , (luxiReqChangeJobPriority, [ simpleField "job" [t| JobId |] , simpleField "priority" [t| Int |] ] ) , (luxiReqSetDrainFlag, [ simpleField "flag" [t| Bool |] ] ) , (luxiReqSetWatcherPause, [ simpleField "duration" [t| Double |] ] ) ]) $(makeJSONInstance ''LuxiReq) -- | List of all defined Luxi calls. $(genAllConstr (drop 3) ''LuxiReq "allLuxiCalls") -- | The serialisation of LuxiOps into strings in messages. $(genStrOfOp ''LuxiOp "strOfOp") -- | Type holding the initial (unparsed) Luxi call. data LuxiCall = LuxiCall LuxiReq JSValue -- | The end-of-message separator. eOM :: Word8 eOM = 3 -- | The end-of-message encoded as a ByteString. bEOM :: B.ByteString bEOM = B.singleton eOM -- | Valid keys in the requests and responses. data MsgKeys = Method | Args | Success | Result -- | The serialisation of MsgKeys into strings in messages. $(genStrOfKey ''MsgKeys "strOfKey") -- | Luxi client encapsulation. data Client = Client { socket :: Handle -- ^ The socket of the client , rbuf :: IORef B.ByteString -- ^ Already received buffer } -- | Connects to the master daemon and returns a luxi Client. getClient :: String -> IO Client getClient path = do s <- S.socket S.AF_UNIX S.Stream S.defaultProtocol withTimeout luxiDefCtmo "creating luxi connection" $ S.connect s (S.SockAddrUnix path) rf <- newIORef B.empty h <- S.socketToHandle s ReadWriteMode return Client { socket=h, rbuf=rf } -- | Creates and returns a server endpoint. getServer :: Bool -> FilePath -> IO S.Socket getServer setOwner path = do s <- S.socket S.AF_UNIX S.Stream S.defaultProtocol S.bindSocket s (S.SockAddrUnix path) when setOwner . setOwnerAndGroupFromNames path GanetiLuxid $ ExtraGroup DaemonsGroup S.listen s 5 -- 5 is the max backlog return s -- | Closes a server endpoint. -- FIXME: this should be encapsulated into a nicer type. closeServer :: FilePath -> S.Socket -> IO () closeServer path sock = do S.sClose sock removeFile path -- | Accepts a client acceptClient :: S.Socket -> IO Client acceptClient s = do -- second return is the address of the client, which we ignore here (client_socket, _) <- S.accept s new_buffer <- newIORef B.empty handle <- S.socketToHandle client_socket ReadWriteMode return Client { socket=handle, rbuf=new_buffer } -- | Closes the client socket. closeClient :: Client -> IO () closeClient = hClose . socket -- | Sends a message over a luxi transport. sendMsg :: Client -> String -> IO () sendMsg s buf = withTimeout luxiDefRwto "sending luxi message" $ do let encoded = UTF8L.fromString buf handle = socket s BL.hPut handle encoded B.hPut handle bEOM hFlush handle -- | Given a current buffer and the handle, it will read from the -- network until we get a full message, and it will return that -- message and the leftover buffer contents. recvUpdate :: Handle -> B.ByteString -> IO (B.ByteString, B.ByteString) recvUpdate handle obuf = do nbuf <- withTimeout luxiDefRwto "reading luxi response" $ do _ <- hWaitForInput handle (-1) B.hGetNonBlocking handle 4096 let (msg, remaining) = B.break (eOM ==) nbuf newbuf = B.append obuf msg if B.null remaining then recvUpdate handle newbuf else return (newbuf, B.tail remaining) -- | Waits for a message over a luxi transport. recvMsg :: Client -> IO String recvMsg s = do cbuf <- readIORef $ rbuf s let (imsg, ibuf) = B.break (eOM ==) cbuf (msg, nbuf) <- if B.null ibuf -- if old buffer didn't contain a full message then recvUpdate (socket s) cbuf -- then we read from network else return (imsg, B.tail ibuf) -- else we return data from our buffer writeIORef (rbuf s) nbuf return $ UTF8.toString msg -- | Extended wrapper over recvMsg. recvMsgExt :: Client -> IO RecvResult recvMsgExt s = Control.Exception.catch (liftM RecvOk (recvMsg s)) $ \e -> return $ if isEOFError e then RecvConnClosed else RecvError (show e) -- | Serialize a request to String. buildCall :: LuxiOp -- ^ The method -> String -- ^ The serialized form buildCall lo = let ja = [ (strOfKey Method, J.showJSON $ strOfOp lo) , (strOfKey Args, opToArgs lo) ] jo = toJSObject ja in encodeStrict jo -- | Serialize the response to String. buildResponse :: Bool -- ^ Success -> JSValue -- ^ The arguments -> String -- ^ The serialized form buildResponse success args = let ja = [ (strOfKey Success, JSBool success) , (strOfKey Result, args)] jo = toJSObject ja in encodeStrict jo -- | Check that luxi request contains the required keys and parse it. validateCall :: String -> Result LuxiCall validateCall s = do arr <- fromJResult "parsing top-level luxi message" $ decodeStrict s::Result (JSObject JSValue) let aobj = fromJSObject arr call <- fromObj aobj (strOfKey Method)::Result LuxiReq args <- fromObj aobj (strOfKey Args) return (LuxiCall call args) -- | Converts Luxi call arguments into a 'LuxiOp' data structure. -- -- This is currently hand-coded until we make it more uniform so that -- it can be generated using TH. decodeCall :: LuxiCall -> Result LuxiOp decodeCall (LuxiCall call args) = case call of ReqQueryJobs -> do (jids, jargs) <- fromJVal args jids' <- case jids of JSNull -> return [] _ -> fromJVal jids return $ QueryJobs jids' jargs ReqQueryInstances -> do (names, fields, locking) <- fromJVal args return $ QueryInstances names fields locking ReqQueryNodes -> do (names, fields, locking) <- fromJVal args return $ QueryNodes names fields locking ReqQueryGroups -> do (names, fields, locking) <- fromJVal args return $ QueryGroups names fields locking ReqQueryClusterInfo -> return QueryClusterInfo ReqQueryNetworks -> do (names, fields, locking) <- fromJVal args return $ QueryNetworks names fields locking ReqQuery -> do (what, fields, qfilter) <- fromJVal args return $ Query what fields qfilter ReqQueryFields -> do (what, fields) <- fromJVal args fields' <- case fields of JSNull -> return [] _ -> fromJVal fields return $ QueryFields what fields' ReqSubmitJob -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitJob ops2 ReqSubmitManyJobs -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitManyJobs ops2 ReqWaitForJobChange -> do (jid, fields, pinfo, pidx, wtmout) <- -- No instance for 5-tuple, code copied from the -- json sources and adapted fromJResult "Parsing WaitForJobChange message" $ case args of JSArray [a, b, c, d, e] -> (,,,,) `fmap` J.readJSON a `ap` J.readJSON b `ap` J.readJSON c `ap` J.readJSON d `ap` J.readJSON e _ -> J.Error "Not enough values" return $ WaitForJobChange jid fields pinfo pidx wtmout ReqArchiveJob -> do [jid] <- fromJVal args return $ ArchiveJob jid ReqAutoArchiveJobs -> do (age, tmout) <- fromJVal args return $ AutoArchiveJobs age tmout ReqQueryExports -> do (nodes, lock) <- fromJVal args return $ QueryExports nodes lock ReqQueryConfigValues -> do [fields] <- fromJVal args return $ QueryConfigValues fields ReqQueryTags -> do (kind, name) <- fromJVal args item <- tagObjectFrom kind name return $ QueryTags item ReqCancelJob -> do [jid] <- fromJVal args return $ CancelJob jid ReqChangeJobPriority -> do (jid, priority) <- fromJVal args return $ ChangeJobPriority jid priority ReqSetDrainFlag -> do [flag] <- fromJVal args return $ SetDrainFlag flag ReqSetWatcherPause -> do [duration] <- fromJVal args return $ SetWatcherPause duration -- | Check that luxi responses contain the required keys and that the -- call was successful. validateResult :: String -> ErrorResult JSValue validateResult s = do when (UTF8.replacement_char `elem` s) $ fail "Failed to decode UTF-8, detected replacement char after decoding" oarr <- fromJResult "Parsing LUXI response" (decodeStrict s) let arr = J.fromJSObject oarr status <- fromObj arr (strOfKey Success) result <- fromObj arr (strOfKey Result) if status then return result else decodeError result -- | Try to decode an error from the server response. This function -- will always fail, since it's called only on the error path (when -- status is False). decodeError :: JSValue -> ErrorResult JSValue decodeError val = case fromJVal val of Ok e -> Bad e Bad msg -> Bad $ GenericError msg -- | Generic luxi method call. callMethod :: LuxiOp -> Client -> IO (ErrorResult JSValue) callMethod method s = do sendMsg s $ buildCall method result <- recvMsg s let rval = validateResult result return rval -- | Parse job submission result. parseSubmitJobResult :: JSValue -> ErrorResult JobId parseSubmitJobResult (JSArray [JSBool True, v]) = case J.readJSON v of J.Error msg -> Bad $ LuxiError msg J.Ok v' -> Ok v' parseSubmitJobResult (JSArray [JSBool False, JSString x]) = Bad . LuxiError $ fromJSString x parseSubmitJobResult v = Bad . LuxiError $ "Unknown result from the master daemon: " ++ show (pp_value v) -- | Specialized submitManyJobs call. submitManyJobs :: Client -> [[MetaOpCode]] -> IO (ErrorResult [JobId]) submitManyJobs s jobs = do rval <- callMethod (SubmitManyJobs jobs) s -- map each result (status, payload) pair into a nice Result ADT return $ case rval of Bad x -> Bad x Ok (JSArray r) -> mapM parseSubmitJobResult r x -> Bad . LuxiError $ "Cannot parse response from Ganeti: " ++ show x -- | Custom queryJobs call. queryJobsStatus :: Client -> [JobId] -> IO (ErrorResult [JobStatus]) queryJobsStatus s jids = do rval <- callMethod (QueryJobs jids ["status"]) s return $ case rval of Bad x -> Bad x Ok y -> case J.readJSON y::(J.Result [[JobStatus]]) of J.Ok vals -> if any null vals then Bad $ LuxiError "Missing job status field" else Ok (map head vals) J.Error x -> Bad $ LuxiError x
narurien/ganeti-ceph
src/Ganeti/Luxi.hs
gpl-2.0
16,121
0
21
4,451
3,998
2,125
1,873
354
23
{-# LANGUAGE PatternGuards #-} module StackMachine.SMAssembler ( assembleAndLoadFile -- testing , assemble ) where import Control.Monad.State import Data.Char (isSpace) import System.IO import StackMachine.Emulator data AssState = Init | Label | SingleByteOp | MultiByteIntOp | MultiByteStringOp | Address | Comment | Invalid deriving (Show) type Code = [Int] type Literals = [Int] -- returns codelen, base pointer, mem assembleAndLoadFile :: String -> IO (Int,Int,[Int]) assembleAndLoadFile fn = do hdl <- openFile fn ReadMode sourceCode <- hGetContents hdl let (c,l) = assemble sourceCode codelen = length c bp = memSize - length l return (codelen, bp, c ++ replicate (memSize - codelen - (length l)) 0 ++ l) assemble :: String -> (Code,Literals) assemble = foldl (\(cagg,lagg) x -> let (c,l) = fst $ runState (foldM assembleLine ([],lagg) $ tokenize x) Init in (cagg++(reverse $ c), l)) ([],[0]) . lines assembleLine :: (Code,Literals) -> String -> State AssState (Code,Literals) assembleLine (c,l) word = state $ \s -> transition (c,l) word s transition :: (Code,Literals) -> String -> AssState -> ((Code,Literals), AssState) transition (c,l) word Init | [(_,"")] <- tryRead word = ((c,l),Label) | word == ";" = ((c,l),Comment) | otherwise = ((c,l),Invalid) where tryRead w = reads w :: [(Int,String)] transition (c,l) word Label | [(Prs,"")] <- tryRead word = (((fromEnum Prs):c,l),MultiByteStringOp) | [(oc,"")] <- tryRead word = let ocNum = fromEnum oc in if oc `elem` multiByteInstructions then ((ocNum:c,l),MultiByteIntOp) else ((ocNum:c,l),SingleByteOp) | otherwise = ((c,l),Invalid) where tryRead w = reads w :: [(Opcode,String)] transition (c,l) word SingleByteOp | word == ";" = ((c,l),Comment) | otherwise = ((c,l),Invalid) transition (c,l) word MultiByteIntOp | [(n,"")] <- reads word = ((n:c,l),Address) | otherwise = ((c,l),Invalid) transition (c,l) word Address | word == ";" = ((c,l),Comment) | otherwise = ((c,l),Invalid) transition (c,l) word MultiByteStringOp | not $ null word = (((memSize - 1 - length l):c, 0:(map fromEnum rw)++l),Comment) | otherwise = ((c,l),Invalid) where rw = reverse word transition (c,l) _ Comment = ((c,l),Comment) transition (c,l) _ Invalid = ((c,l), Invalid) tokenize :: String -> [String] tokenize s = case dropWhile isSpace s of "" -> [] ('\'':s') -> w : tokenize s'' where (w, ('\'':s'')) = break (=='\'') s' s' -> w : tokenize s'' where (w, s'') = break isSpace s'
zebbo/stack-machine
src/StackMachine/SMAssembler.hs
gpl-3.0
2,659
0
19
607
1,254
697
557
59
3
module Main where import Common import Common.IO import Infix import Lexer import Parser import Pretty import Renamer import Syntax import Text.Show.Pretty runPhase :: (MonadIO m) => (i -> FM String) -> i -> m () runPhase f xs = liftIO . mapM_ putStrLn $ maybeToList out ++ map ppShow errs where (out, errs) = runFM . f $ xs lexPhase = mapM (uncurry tokenize) parsePhase = lexPhase' >=> mapM (uncurry parse) where lexPhase' xs = fmap (zip $ map fst xs) . lexPhase $ xs renamePhase = parsePhase >=> rename . mkRecord infixPhase = renamePhase >=> eliminateInfix phases = [ ("lex", runPhase $ lexPhase >=> return . concatMap ppShow) , ("parse", runPhase $ parsePhase >=> return . concatMap pretty) , ("rename", runPhase $ renamePhase >=> return . pretty) , ("infix", runPhase $ infixPhase >=> return . pretty) ] getInput xs = fmap (xs,) $ case xs of "-" -> getContents _ -> readFile xs main = do (phase : files) <- getArgs case lookup phase phases of Nothing -> putStrLn $ "Unknown phase: " ++ phase Just fn -> mapM getInput files >>= fn
ktvoelker/FLang
src/Main.hs
gpl-3.0
1,086
0
12
235
411
216
195
-1
-1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} module Fp14SimpleLens where {- {- Линза - инструмент для манипулирования элементом типа a некоторой структуры данных типа s, находящимся в фокусе этой линзы. Технически линза - это АТД составленный из пары геттер-сеттер lens :: (s -> a) -> (s -> a -> s) -> Lens s a Законы: 1) You get back what you put in: view l (set l v s) = v 2) Putting back what you got doesn't change anything: set l (view l s) s = s 3) Setting twice is the same as setting once: set l v' (set l v s) = set l v' s Наивный подход: -} data LensNaive s a = MkLens (s -> a) (s -> a -> s) _1Naive :: LensNaive (a,b) a _1Naive = MkLens (\(x,_) -> x) (\(_,y) v -> (v,y)) viewNaive :: LensNaive s a -> s -> a viewNaive (MkLens get _) s = get s {- GHCi> viewNaive _1Naive (5,7) 5 Это работает, но (1) неэффективно (конструктор данных MkLens дает дополнительный барьер во время исполнения); (2) имеет проблемы с расширением и обобщением (например, хотелось бы, чтобы композиция линз была линзой). мы пишем сеттер и геттер вручную, но для записей с метками полей туда вкладываются непосредственно эти метки (в случае сеттера в синтаксисе обновления). -} ---------------------------------------------- {- van Laarhoven lenses (Functor transformer lenses) Линзы ван Ларховена Линза --- это функция, которая превращает вложение a в функтор f во вложение s в этот функтор. -} type Lens s a = forall f. Functor f => (a -> f a) -> s -> f s {- NB Композиция в обратном порядке происходит отсюда!!! l1 :: Lens t s -- (s -> f s) -> t -> f t l2 :: Lens s a -- (a -> f a) -> s -> f s l1 . l2 :: Lens t a Как упаковать в такую конструкцию геттер и сеттер? -} -- (s -> a) -> (s -> a -> s) -> (a -> f a) -> s -> f s lens :: (s -> a) -> (s -> a -> s) -> Lens s a lens get set = \ret s -> fmap (set s) (ret $ get s) {- get s :: a ret $ get s :: f a set s :: a -> s -} -- Пример для пар: s == (a,b) {- -- (a -> f a) -> (a,b) -> f (a,b) _1 :: Lens (a,b) a _1 = lens (\(x,_) -> x) -- get (\(_,y) v -> (v,y)) -- set -- (b -> f b) -> (a,b) -> f (a,b) _2 :: Lens (a,b) b -- _2 = lens (\(_,y) -> y) (\(x,_) v -> (x,v)) -- _2 = \ret (x,y) -> fmap ((\(x,_) v -> (x,v)) (x,y)) (ret $ (\(_,y) -> y) (x,y)) -- _2 = \ret (x,y) -> fmap (\v -> (x,v)) (ret $ y) _2 ret (x,y) = fmap ((,) x) (ret y) -} {- Как вынуть из линзы геттер и сеттер? Использовать вместо f подходящий функтор! -} -- Геттер (x - фантомный параметр тпа) newtype Const a x = Const {getConst :: a} {- Const :: a -> Const a x getConst :: Const a x -> a -} instance Functor (Const a) where -- fmap :: (x -> y) -> Const a x -> Const a y fmap _ (Const v) = Const v -- игнорирует функцию! -- ((a -> Const a a) -> s -> Const a s) -> s -> a view :: Lens s a -> s -> a view lns s = getConst (lns Const s) -- lns Const :: s -> Const a s -- lns Const s :: Const a s -- getConst :: Const a s -> a {- GHCi> view _1 (5,7) 5 GHCi> view _2 (5,7) 7 GHCi> view (_2 . _1) (5,(6,7)) 6 -} {- view _2 (5,7) ~> getConst $ _2 Const (5,7) ~> getConst $ (\f (x,y) -> fmap ((,) x) (f y)) Const (5,7) ~> getConst $ fmap ((,) 5) (Const 7)) ~> getConst (Const 7) ~> 7 -} -- Сеттер newtype Identity a = Identity {runIdentity :: a} {- Identity :: a -> Identity a runIdentity :: Identity a -> a -} instance Functor Identity where fmap f (Identity x) = Identity (f x) -- ((a -> Identity a) -> s -> Identity s) -> (a -> a) -> s -> s over :: Lens s a -> (a -> a) -> s -> s over lns fn s = runIdentity $ lns (Identity . fn) s {- GHCi> over _1 (+5) (5,7) (10,7) GHCi> over _2 (+5) (5,7) (5,12) GHCi> over (_2 . _1) (+5) ("abc",(6,True)) ("abc",(11,True)) -} {- over _2 (+5) (5,7) ~> runIdentity $ _2 (Identity . (+5)) (5,7) ~> runIdentity $ (\f (x,y) -> fmap ((,) x) (f y)) (Identity . (+5)) (5,7) ~> runIdentity $ fmap ((,) 5) ((Identity . (+5)) 7) ~> runIdentity $ fmap ((,) 5) ((Identity 12) ~> runIdentity $ ((Identity (5,12)) ~> (5,12) -} -- ((a -> Identity a) -> s -> Identity s) -> a -> s -> s set :: Lens s a -> a -> s -> s set lns a s = over lns (const a) s --set lns a s = runIdentity $ lns (Identity . const a) s {- GHCi> set _2 42 (5,7) (5,42) GHCi> set (_2 . _1) 33 ("abc",(6,True)) ("abc",(33,True)) -} data Tree a = Empty | Node (Tree a) a (Tree a) deriving (Show, Eq) type TreeZ a = (a, CntxT a) data CntxT a = CntxT (Tree a) (Tree a) [(Dir, a, Tree a)] deriving (Eq, Show) data Dir = L | R deriving (Eq, Show) mktz :: Tree a -> TreeZ a mktz (Node tl a tr) = (a, CntxT tl tr []) left :: TreeZ a -> TreeZ a left (v, CntxT (Node son1 new_v son2) tr lst) = (new_v, CntxT son1 son2 ((L, v, tr):lst)) right :: TreeZ a -> TreeZ a right (v, CntxT tl (Node son1 new_v son2) lst) = (new_v, CntxT son1 son2 ((R, v, tl):lst)) up :: TreeZ a -> TreeZ a up (val, CntxT tl tr ((dir, root_val, other_son):lst)) | dir == L = (root_val, CntxT (Node tl val tr) other_son lst) | dir == R = (root_val, CntxT other_son (Node tl val tr) lst) untz :: TreeZ a -> Tree a untz (root_val, CntxT tl tr []) = Node tl root_val tr untz x = untz $ up x updTZ :: a -> TreeZ a -> TreeZ a updTZ new_v (v, ctx) = (new_v, ctx) class Field1 s a | s -> a where _1 :: Lens s a class Field2 s a | s -> a where _2 :: Lens s a class Field3 s a | s -> a where _3 :: Lens s a instance Field1 (a,b) a where _1 = lens (\(x, y) -> x) (\(x, y) v -> (v, y)) instance Field2 (b, a) a where _2 = lens (\(x, y) -> y) (\(x, y) v -> (x, v)) instance Field1 (a, b, c) a where _1 = lens (\(x, y, z) -> x) (\(x, y, z) v -> (v, y, z)) instance Field2 (a, b, c) b where _2 = lens (\(x, y, z) -> y) (\(x, y, z) v -> (x, v, z)) instance Field3 (a, b, c) c where _3 = lens (\(x, y, z) -> z) (\(x, y, z) v -> (x, y, v)) -} newtype Const a x = Const {getConst :: a} instance Functor (Const a) where fmap _ (Const v) = Const v newtype Identity a = Identity {runIdentity :: a} instance Functor Identity where fmap f (Identity x) = Identity (f x) class Field1 s t a b | s a b -> t, s -> a, t -> b where _1 :: Lens s t a b class Field2 s t a b | s a b -> t, s -> a, t -> b where _2 :: Lens s t a b class Field3 s t a b | s a b -> t, s -> a, t -> b where _3 :: Lens s t a b type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b lens get set = \ret s -> fmap (set s) (ret $ get s) set :: Lens s t a b -> b -> s -> t set lns a s = over lns (const a) s view :: Lens s t a b -> s -> a view lns s = getConst (lns Const s) over :: Lens s t a b -> (a -> b) -> s -> t over lns fn s = runIdentity $ lns (Identity . fn) s instance Field1 (a,b) (c, b) a c where _1 = lens (\(x, y) -> x) (\(x, y) v -> (v, y)) instance Field2 (a,b) (a, c) b c where _2 = lens (\(x, y) -> y) (\(x, y) v -> (x, v)) instance Field1 (a, b, c) (x, b, c) a x where _1 = lens (\(x, y, z) -> x) (\(x, y, z) v -> (v, y, z)) instance Field2 (a, b, c) (a, x, c) b x where _2 = lens (\(x, y, z) -> y) (\(x, y, z) v -> (x, v, z)) instance Field3 (a, b, c) (a, b, x) c x where _3 = lens (\(x, y, z) -> z) (\(x, y, z) v -> (x, y, v))
ItsLastDay/academic_university_2016-2018
subjects/Haskell/14/fp14SimpleLens.hs
gpl-3.0
8,713
0
10
2,541
927
532
395
43
1
import Data.List( permutations, sortBy ) import Data.Ord( comparing ) import Control.Monad( forM_ ) combinations :: Eq a => Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations n (x:xs) = map (x:) (combinations (n-1) xs) ++ combinations n xs {-| Problem 46 (**) Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. A logical expression in two variables can then be written as in the following example: and(or(A,B),nand(A,B)). Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables. Example: (table A B (and A (or A B))) true true true true fail true fail true fail fail fail fail Example in Haskell: > table (\a b -> (and' a (or' a b))) True True True True False True False True False False False False -} table f = forM_ [[True,True],[True,False],[False,True],[False,False]] $ \[a,b] -> putStrLn $ show a ++ " " ++ show b ++ " " ++ (show $ f a b) and' a b = a && b or' a b = a || b nand' a b = not (and' a b) nor' a b = not (or' a b) xor' :: Bool -> Bool -> Bool xor' a b = (a /= b) impl' True False = False impl' _ _ = True equ' a b = not (xor' a b) {-| Problem 47 (*) Truth tables for logical expressions (2). Continue problem P46 by defining and/2, or/2, etc as being operators. This allows to write the logical expression in the more natural way, as in the example: A and (A or not B). Define operator precedence as usual; i.e. as in Java. Example: * (table A B (A and (A or not B))) true true true true fail true fail true fail fail fail fail Example in Haskell: > table2 (\a b -> a `and'` (a `or'` not b)) True True True True False True False True False False False False -} infixl 6 `or'` infixl 7 `and'` infixl 3 `equ'` {-| Problem 48 (**) Truth tables for logical expressions (3). Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table/2 in a way that table(List,Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List. Example: * (table (A,B,C) (A and (B or C) equ A and B or A and C)) true true true true true true fail true true fail true true true fail fail true fail true true true fail true fail true fail fail true true fail fail fail true Example in Haskell: > tablen 3 (\[a,b,c] -> a `and'` (b `or'` c) `equ'` a `and'` b `or'` a `and'` c) -- infixl 3 `equ'` True True True True True True False True True False True True True False False True False True True True False True False True False False True True False False False True -- infixl 7 `equ'` True True True True True True False True True False True True True False False False False True True False False True False False False False True False False False False False -} gen :: Int -> [a] -> [[a]] gen 1 xs = map (\x -> [x]) xs gen n xs = [x:ys | x <- xs, ys <- gen (n-1) xs] tablen n ff = do forM_ (gen n [True,False]) $ \xs -> do forM_ xs $ \x -> do putStr $ show x ++ " " putStrLn $ show $ ff xs {-| Problem 49 (**) Gray codes. An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example, n = 1: C(1) = ['0','1']. n = 2: C(2) = ['00','01','11','10']. n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´]. Find out the construction rules and write a predicate with the following specification: % gray(N,C) :- C is the N-bit Gray code Can you apply the method of "result caching" in order to make the predicate more efficient, when it is to be used repeatedly? Example in Haskell: P49> gray 3 ["000","001","011","010","110","111","101","100"] -} gray :: Int -> [String] gray 1 = ["0", "1"] gray n = (map ('0':) xs) ++ (map ('1':) $ reverse xs) where xs = gray (n-1) {-| Problem 50 (***) Huffman codes. We suppose a set of symbols with their frequencies, given as a list of fr(S,F) terms. Example: [fr(a,45),fr(b,13),fr(c,12),fr(d,16),fr(e,9),fr(f,5)]. Our objective is to construct a list hc(S,C) terms, where C is the Huffman code word for the symbol S. In our example, the result could be Hs = [hc(a,'0'), hc(b,'101'), hc(c,'100'), hc(d,'111'), hc(e,'1101'), hc(f,'1100')] [hc(a,'01'),...etc.]. The task shall be performed by the predicate huffman/2 defined as follows: % huffman(Fs,Hs) :- Hs is the Huffman code table for the frequency table Fs Example in Haskell: *Exercises> huffman [('a',45),('b',13),('c',12),('d',16),('e',9),('f',5)] [('a',"0"),('b',"101"),('c',"100"),('d',"111"),('e',"1101"),('f',"1100")] -} data HuffmanTree = TreeElem (Char,Int) | TreeNode Int HuffmanTree HuffmanTree deriving( Show ) huffman :: [(Char,Int)] -> [(Char,String)] huffman xs = sortBy (comparing fst) . fff "" . mkTree . map TreeElem . sortBy (comparing snd) $ xs mkTree [x] = x mkTree (x:y:xs) = mkTree . sortBy (comparing freq) $ (TreeNode (freq x + freq y) x y : xs) where freq (TreeElem (_,a)) = a freq (TreeNode a _ _) = a fff xs (TreeElem (a,_)) = [(a,xs)] fff xs (TreeNode _ x y) = (fff (xs ++ "0") x) ++ (fff (xs ++ "1") y)
zhensydow/ljcsandbox
lang/haskell/99problems/46-50logic.hs
gpl-3.0
5,354
0
17
1,142
988
522
466
47
2
{- Author: Michal Gerard Parusinski Maintainer: TBD Email: TBD License: GPL 3.0 File: Proof.hs Description: provides a framework to build and handle description logic proofs -} module Proof where import Signature import Data.List -- TODO: Add somehow knowledge base -- TODO: Build up the proof rules -- The last concept in the tuple is the concept that the rule is applied to type Rule = String type ProofStep = ([Concept], Rule, Concept) data ProofTree = NodeZero ProofStep | NodeOne ProofStep ProofTree | NodeTwo ProofStep ProofTree ProofTree deriving (Show, Eq)
j5b/ps-pc
Proof.hs
gpl-3.0
649
0
6
173
76
48
28
9
0
module Types where import Data.Word (Word32) {-# LANGUAGE BangPatterns #-} data Point = P !Int !Int deriving Eq type Stage = [Point] type Item = Maybe Point -- North, South, East, West data Direction = N | S | E | W data GameMode = Game | End | Save GameMode | Load GameMode | Editor | Scoreboard deriving Eq data Snake = Snake { alive :: Bool , direction :: Direction , points :: [Point] } data World = World { snake :: Snake , stage :: Stage , speed :: Word32 , score :: Int , scores :: [Int] , fscores :: [Int] , item :: Item , mode :: (Bool, GameMode) -- whether the help menu is open and the current game mode }
mikeplus64/Level-0
src/Types.hs
gpl-3.0
719
0
9
229
195
123
72
-1
-1
module Main where import Codec.Image.LibPNG spectrum :: [[Pixel]] spectrum = replicate 40 $ map (\g -> colorPixel 255 255 g 0) [0..255] ++ map (\r -> colorPixel 255 r 255 0) [254,253..1] ++ map (\b -> colorPixel 255 0 255 b) [0..255] ++ map (\g -> colorPixel 255 0 g 255) [254,253..0] halfSize :: [[a]] -> [[a]] halfSize = map half . half where half (x:_:xs) = x : half xs half xs = xs waterColor :: Double -> Double -> Pixel waterColor x y = colorPixel 255 r 130 60 where r = round $ sin ( x * y / 3000 :: Double ) ^ (2::Int) * 255 water :: [[Pixel]] water = [ [ waterColor x y | x <- [-256..255] ] | y <- [-256..255] ] waterLarge :: Double -> [[Pixel]] waterLarge scale = [ [ waterColor (scale*x) (scale*y) | x <- [-1280..1279] ] | y <- [-512..511] ] main :: IO () main = do writePNGFromPixelss "Water.png" water image <- imageFromPixelss spectrum writePNGImage "Spectrum.png" image pixelss <- readPixelssFromPNG "Water.png" writePNGFromPixelss "Water-small.png" $ halfSize pixelss writePNGFromPixelss "Water-large.png" $ waterLarge 0.5
waterret/LibPNG-haskell
src/Main.hs
gpl-3.0
1,172
0
13
317
514
269
245
26
2
-- Based on another answer very heavily -- Problem being that it repeats same letters import Data.List main = do words <- slowChange <$> getLine <*> getLine putStrLn . unlines $ words where slowChange xs ys = zipWith (++) (inits ys) (tails xs)
jandersen7/Daily
src/295e/hs/LbyL.hs
gpl-3.0
258
0
9
57
72
37
35
5
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Container.Projects.Locations.Clusters.SetMonitoring -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the monitoring service for a specific cluster. -- -- /See:/ <https://cloud.google.com/container-engine/ Kubernetes Engine API Reference> for @container.projects.locations.clusters.setMonitoring@. module Network.Google.Resource.Container.Projects.Locations.Clusters.SetMonitoring ( -- * REST Resource ProjectsLocationsClustersSetMonitoringResource -- * Creating a Request , projectsLocationsClustersSetMonitoring , ProjectsLocationsClustersSetMonitoring -- * Request Lenses , plcsmXgafv , plcsmUploadProtocol , plcsmAccessToken , plcsmUploadType , plcsmPayload , plcsmName , plcsmCallback ) where import Network.Google.Container.Types import Network.Google.Prelude -- | A resource alias for @container.projects.locations.clusters.setMonitoring@ method which the -- 'ProjectsLocationsClustersSetMonitoring' request conforms to. type ProjectsLocationsClustersSetMonitoringResource = "v1" :> CaptureMode "name" "setMonitoring" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetMonitoringServiceRequest :> Post '[JSON] Operation -- | Sets the monitoring service for a specific cluster. -- -- /See:/ 'projectsLocationsClustersSetMonitoring' smart constructor. data ProjectsLocationsClustersSetMonitoring = ProjectsLocationsClustersSetMonitoring' { _plcsmXgafv :: !(Maybe Xgafv) , _plcsmUploadProtocol :: !(Maybe Text) , _plcsmAccessToken :: !(Maybe Text) , _plcsmUploadType :: !(Maybe Text) , _plcsmPayload :: !SetMonitoringServiceRequest , _plcsmName :: !Text , _plcsmCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsClustersSetMonitoring' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plcsmXgafv' -- -- * 'plcsmUploadProtocol' -- -- * 'plcsmAccessToken' -- -- * 'plcsmUploadType' -- -- * 'plcsmPayload' -- -- * 'plcsmName' -- -- * 'plcsmCallback' projectsLocationsClustersSetMonitoring :: SetMonitoringServiceRequest -- ^ 'plcsmPayload' -> Text -- ^ 'plcsmName' -> ProjectsLocationsClustersSetMonitoring projectsLocationsClustersSetMonitoring pPlcsmPayload_ pPlcsmName_ = ProjectsLocationsClustersSetMonitoring' { _plcsmXgafv = Nothing , _plcsmUploadProtocol = Nothing , _plcsmAccessToken = Nothing , _plcsmUploadType = Nothing , _plcsmPayload = pPlcsmPayload_ , _plcsmName = pPlcsmName_ , _plcsmCallback = Nothing } -- | V1 error format. plcsmXgafv :: Lens' ProjectsLocationsClustersSetMonitoring (Maybe Xgafv) plcsmXgafv = lens _plcsmXgafv (\ s a -> s{_plcsmXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plcsmUploadProtocol :: Lens' ProjectsLocationsClustersSetMonitoring (Maybe Text) plcsmUploadProtocol = lens _plcsmUploadProtocol (\ s a -> s{_plcsmUploadProtocol = a}) -- | OAuth access token. plcsmAccessToken :: Lens' ProjectsLocationsClustersSetMonitoring (Maybe Text) plcsmAccessToken = lens _plcsmAccessToken (\ s a -> s{_plcsmAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plcsmUploadType :: Lens' ProjectsLocationsClustersSetMonitoring (Maybe Text) plcsmUploadType = lens _plcsmUploadType (\ s a -> s{_plcsmUploadType = a}) -- | Multipart request metadata. plcsmPayload :: Lens' ProjectsLocationsClustersSetMonitoring SetMonitoringServiceRequest plcsmPayload = lens _plcsmPayload (\ s a -> s{_plcsmPayload = a}) -- | The name (project, location, cluster) of the cluster to set monitoring. -- Specified in the format \`projects\/*\/locations\/*\/clusters\/*\`. plcsmName :: Lens' ProjectsLocationsClustersSetMonitoring Text plcsmName = lens _plcsmName (\ s a -> s{_plcsmName = a}) -- | JSONP plcsmCallback :: Lens' ProjectsLocationsClustersSetMonitoring (Maybe Text) plcsmCallback = lens _plcsmCallback (\ s a -> s{_plcsmCallback = a}) instance GoogleRequest ProjectsLocationsClustersSetMonitoring where type Rs ProjectsLocationsClustersSetMonitoring = Operation type Scopes ProjectsLocationsClustersSetMonitoring = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsClustersSetMonitoring'{..} = go _plcsmName _plcsmXgafv _plcsmUploadProtocol _plcsmAccessToken _plcsmUploadType _plcsmCallback (Just AltJSON) _plcsmPayload containerService where go = buildClient (Proxy :: Proxy ProjectsLocationsClustersSetMonitoringResource) mempty
brendanhay/gogol
gogol-container/gen/Network/Google/Resource/Container/Projects/Locations/Clusters/SetMonitoring.hs
mpl-2.0
5,878
0
16
1,241
779
455
324
119
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.DirectConnect.DescribeInterconnects -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns a list of interconnects owned by the AWS account. -- -- If an interconnect ID is provided, it will only return this particular -- interconnect. -- -- <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeInterconnects.html> module Network.AWS.DirectConnect.DescribeInterconnects ( -- * Request DescribeInterconnects -- ** Request constructor , describeInterconnects -- ** Request lenses , diInterconnectId -- * Response , DescribeInterconnectsResponse -- ** Response constructor , describeInterconnectsResponse -- ** Response lenses , dirInterconnects ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.DirectConnect.Types import qualified GHC.Exts newtype DescribeInterconnects = DescribeInterconnects { _diInterconnectId :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'DescribeInterconnects' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'diInterconnectId' @::@ 'Maybe' 'Text' -- describeInterconnects :: DescribeInterconnects describeInterconnects = DescribeInterconnects { _diInterconnectId = Nothing } diInterconnectId :: Lens' DescribeInterconnects (Maybe Text) diInterconnectId = lens _diInterconnectId (\s a -> s { _diInterconnectId = a }) newtype DescribeInterconnectsResponse = DescribeInterconnectsResponse { _dirInterconnects :: List "interconnects" Interconnect } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeInterconnectsResponse where type Item DescribeInterconnectsResponse = Interconnect fromList = DescribeInterconnectsResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _dirInterconnects -- | 'DescribeInterconnectsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dirInterconnects' @::@ ['Interconnect'] -- describeInterconnectsResponse :: DescribeInterconnectsResponse describeInterconnectsResponse = DescribeInterconnectsResponse { _dirInterconnects = mempty } -- | A list of interconnects. dirInterconnects :: Lens' DescribeInterconnectsResponse [Interconnect] dirInterconnects = lens _dirInterconnects (\s a -> s { _dirInterconnects = a }) . _List instance ToPath DescribeInterconnects where toPath = const "/" instance ToQuery DescribeInterconnects where toQuery = const mempty instance ToHeaders DescribeInterconnects instance ToJSON DescribeInterconnects where toJSON DescribeInterconnects{..} = object [ "interconnectId" .= _diInterconnectId ] instance AWSRequest DescribeInterconnects where type Sv DescribeInterconnects = DirectConnect type Rs DescribeInterconnects = DescribeInterconnectsResponse request = post "DescribeInterconnects" response = jsonResponse instance FromJSON DescribeInterconnectsResponse where parseJSON = withObject "DescribeInterconnectsResponse" $ \o -> DescribeInterconnectsResponse <$> o .:? "interconnects" .!= mempty
dysinger/amazonka
amazonka-directconnect/gen/Network/AWS/DirectConnect/DescribeInterconnects.hs
mpl-2.0
4,100
0
10
773
496
299
197
58
1
{-# LANGUAGE GADTs, RankNTypes, TypeOperators, FlexibleInstances #-} module Walk where import Test.QuickCheck import Data.List import Control.Monad import Control.Applicative import Induction.Structural import Trace import EnvTypes import Env import Util construct :: VarMap -> Hyp -> Gen [Repr'] construct vm (hyps,tms) = mapM (construct1 hyps vm) tms construct1 :: [(String,Ty')] -> VarMap -> Tm -> Gen Repr' construct1 hyps vm tm = case tm of Var s -> case lookup s vm of Just u -> return u Nothing -> case lookup s hyps of Just t -> arbFromType' t -- ^ if this is missing, generate a new one with arbitrary!! Nothing -> error $ show s ++ " missing!" ++ show vm ++ "," ++ show hyps Con s tms -> mkCon s <$> mapM (construct1 hyps vm) tms Fun{} -> error "exponentials not supported" -- | We can only pick 1-2 hyps, otherwise we get crazy exponential behaviour pickHyps :: [a] -> Gen [a] pickHyps [] = return [] pickHyps hs = do let n = length hs - 1 i <- choose (0,n) i' <- choose (0,n) two <- arbitrary return $ if two && i /= i' then [hs !! i,hs !! i'] else [hs !! i] -- TODO: Can this be reorganized so we get an efficient unrolling? makeTracer :: [Repr'] -> [Oblig] -> Gen (Trace [Repr']) makeTracer args parts = go parts where go p = case p of Obligation _ hyps conc:is | length args == length conc -> case zipWithM match args conc of Nothing -> go is Just vms -> halfSize $ \ _ -> do -- Throw away some hypotheses hyps' <- pickHyps hyps argss' <- mapM (construct (concat vms)) hyps' forks <- mapM (`makeTracer` parts) argss' return (Fork args forks) | otherwise -> mk_error $ "Unequal lengths (conc=" ++ intercalate "," (map (render . linTerm style) conc) ++ ")" _ -> mk_error "No case" where mk_error msg = error $ "makeTracer " ++ show args ++ " : " ++ msg ++ "!" ++ "\nDetails: args = (" ++ intercalate " , " (map showRepr' args) ++ ")" ++ "\nCheck Env.match and EnvTypes.==?, or case is missing from schema:" ++ "\n" ++ showOblig parts
danr/structural-induction
test/Walk.hs
lgpl-3.0
2,297
0
23
714
736
365
371
49
5
module Freshen where import TrmX import qualified Data.List as L import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Char as C -------------------------------------------------------------------------------------------- {-Wrappers-} {-Function that genenerates new freshness constraints from old ones-} frshGen ::Set Atm -> FreshAtms frshGen atms = (atms, testSize atms (newNames atms)) frshAtmGen :: TrmCtx -> S.Set Atm frshAtmGen t = testSize (atmsTrmCtx t) (newNames (atmsTrmCtx t)) frshVarGen :: Trm -> S.Set Var frshVarGen t = testSize (varsTrm t) (newNames (varsTrm t)) --parses an atom f an atmSet and adds a number: returns dif set from original atms newNames:: S.Set String -> S.Set String newNames atms = S.map aNewName atms S.\\ atms --testSize checks newAtms enough size else acts on itself growing at least size +1 testSize:: S.Set String -> S.Set String -> S.Set String testSize atms nwAtms = if nwAtms < atms || any (\a-> S.singleton a `S.isSubsetOf` atms) (S.toList nwAtms) then testSize atms $ S.union nwAtms (newNames nwAtms) else nwAtms --add +1 function aNewName :: String -> String aNewName a = if C.isDigit l then d ++ [x] else a ++ "0" where l = last a d = init a x = C.intToDigit . (1 +) $ C.digitToInt l --pick an atom from set of avail ones else create new ones pickAtm::FreshAtms -> (FreshAtms,Atm) pickAtm (old,new) = if S.null new then pickAtm (frshGen old) else ((S.insert atm old,S.delete atm new),atm) where atm=if S.size new `mod` 2 == 0 then S.elemAt (S.size new -1) new else S.elemAt 0 new --maybe do a pickAtmWith::atm->freshAtms --theres a chance of repetition in tuples but not clashing of binders unionFrshAtms:: FreshAtms -> FreshAtms -> FreshAtms unionFrshAtms (old1, new1) (old2, new2) = let olds= old1 `S.union` old2 news= new1 `S.union` new2 in (olds, news S.\\ olds) unionsFrshAtms= foldr unionFrshAtms (S.empty,S.empty) --------------------------------------------------------------------------- --Freshen rules and Terms --freshen rule w/respect to itself and trmCtx, but trmCtx is untouched freshenRnT:: Rule -> TrmCtx -> Rule freshenRnT (fc, l ,r) (ctx, t) = let atmPairs = zip (S.toList $ atmsTrmCtx (S.union ctx fc,TplTrm [l,r,t])) (S.toList $ frshAtmGen ( ctx `S.union` fc,TplTrm [l,r,t])) varPairs = zip (S.toList $ varsTrm (TplTrm [l,r,t])) (S.toList $ frshVarGen (TplTrm [l,r,t])) in (freshCtx atmPairs varPairs fc, freshT atmPairs varPairs l,freshT atmPairs varPairs r ) freshenR:: Rule -> Rule freshenR (fc, l ,r) = let atmPairs = zip (S.toList $ atmsTrmCtx ( fc,TplTrm [l,r])) (S.toList $ frshAtmGen (fc,TplTrm [l,r])) varPairs = zip (S.toList $ varsTrm (TplTrm [l,r])) (S.toList $ frshVarGen (TplTrm [l,r])) in (freshCtx atmPairs varPairs fc, freshT atmPairs varPairs l,freshT atmPairs varPairs r ) freshenTFc:: TrmCtx -> TrmCtx freshenTFc s = let atmPairs = zip (S.toList $ atmsTrmCtx s) (S.toList $ frshAtmGen s) varPairs = zip (S.toList . varsTrm $ snd s) (S.toList . frshVarGen $ snd s) in (freshCtx atmPairs varPairs Control.Arrow.*** freshT atmPairs varPairs) freshenT:: Trm -> Trm freshenT s = let atmPairs = zip (S.toList $ atmsTrm s) (S.toList $ frshAtmGen (S.empty,s)) varPairs = zip (S.toList $ varsTrm s) (S.toList $ frshVarGen s) in freshT atmPairs varPairs s --rename Vars in rules before matching.needed for standard rewriting.context not added->RuleValidity freshenVars:: Rule -> Trm -> Rule freshenVars (fc, l ,r) t = let varPairs = zip (S.toList $ varsTrm (TplTrm [l,r,t])) (S.toList $ frshVarGen (TplTrm [l,r,t])) in (freshCtx [] varPairs fc, freshT [] varPairs l,freshT [] varPairs r ) ------------------------------------- -- Renaming fun. input as follows: atmPairs varPairs Trm freshT :: [(Atm,Atm)] -> [(Var,Var)]-> Trm -> Trm freshT as vrs t = foldr renameAtmTrm (foldr renameVarTrm t vrs) as freshCtx :: [(Atm,Atm)] -> [(Var,Var)]-> Ctx -> Ctx freshCtx as vrs fc = foldr renameAtmCtx (foldr renameVarCtx fc vrs) as
susoDominguez/eNominalTerms-Alpha
Freshen.hs
unlicense
4,702
0
15
1,365
1,542
825
717
59
3
--Мамылин Дмитрий, группа: МТ-202. Задача на зачет по КН: Master Mind. {-Очень хотелось реализовать ввод/вывод с минимумом нажатий клавиши Enter, но под Windows GHC не позволяет: https://ghc.haskell.org/trac/ghc/ticket/2189 Вспомнилась очень удобная библиотека (только под Windows, к сожалению), из языка C - <conio.h>. В связке с расширением FFI задача разрешилась.-} {-# LANGUAGE ForeignFunctionInterface #-} import Foreign.C import System.Cmd(system) import System.IO import Data.Char(chr, isDigit) import System.Random(randomRIO) foreign import ccall unsafe "conio.h getch" c_getch :: IO Int ---------"Ресурсы" игры:--------- resStrAbout = "Author: Mamylin Dmitry, IMCS URFU, 2013" resStrInit = "Welcome to Master Mind!" resStrHelp = "Mastermind or Master Mind is a code-breaking \ \game for two players. \nThe modern game with \ \pegs was invented in 1970 by Mordecai Meirowitz,\ \an Israeli postmaster and telecommunications expert.\n\n\ \In this realisation, your goal - break code that was \ \generated by computer -\nthe first player." resStrGetLen = "Enter length of sequence (positive integer): " resStrEnter = "Your turn: " resStrWin = "Victory!" resStrGen = "Sequence generated seccessfully." resStrMenuMain = "Press buttons (1) - (4) to:\n1. Start\n2. Help\n3. About\n4. Exit" resStrMenuBack = "1. Back to menu" resStrExit = "Goodbye!" ---------"Чистые" функции:--------- valueError :: Show a => a -> String valueError val = "Bad value: " ++ show val ++ " Try again!" showAnswer :: (Int, Int) -> String showAnswer (matched, inSeq) = "Matched: " ++ show matched ++ "; in sequence: " ++ show inSeq isNumber :: String -> Bool isNumber = and . map isDigit matchSeq :: String -> String -> (Int, Int) {-Принимает 2 строки (последовательности). s1 - загаданная, s2 - ранее введенная пользователем. Формирует пару (a, b), где a - количество совпавших символов s1 и s2, b - количество присутствующих символов из s2 в s1 без учета совпавших.-} matchSeq s1 s2 = (matched, sum $ map add a2) where (a1, a2, matched) = foldl merge ("", "", 0) $ zipWith intersect s1 s2 add x = if x `elem` a1 then 1 else 0 intersect a b = if a == b then ("", "", 1) else ([a], [b], 0) merge (x1, x2, x3) (y1, y2, y3) = (x1 ++ y1, x2 ++ y2, x3 + y3) ---------Функции ввода/вывода:--------- getCh :: IO Char getCh = do --"Обертка" для сишного getch(). code <- c_getch return $ chr code getSeqLen :: IO Int getSeqLen = do --Запрашивает у пользователя длину последовательности. putStr resStrGetLen len <- getLine if isNumber len && (read len :: Int) > 0 then return $ (read len :: Int) else do { putStrLn $ valueError len; getSeqLen } genSeq :: Int -> IO String --Генерирует последовательность заданной длины. genSeq len = mapM randomRIO $ replicate len ('0', '9') getSeq :: Int -> IO String getSeq len = do --Запрашивает у пользователя последовательность. putStr resStrEnter sq <- getLine if isNumber sq && len == length sq then return sq else do putStrLn $ (valueError sq) ++ " Expected length: " ++ show len getSeq len gameLoop :: Int -> String -> IO () gameLoop len seq = do --"Зацикливает" ввод/вывод результата. input <- getSeq len if seq == input then do backKeyMenu $ resStrWin ++ " Sequence = " ++ seq else do putStrLn $ showAnswer $ matchSeq seq input gameLoop len seq backKeyMenu :: String -> IO () backKeyMenu info = do --Удобный шаблон для создания "однокнопочных" меню. system "cls" putStrLn info putStrLn resStrMenuBack checkAnswer where checkAnswer = do key <- getCh case key of '1' -> do { system "cls"; menuMain } _ -> checkAnswer menuMain :: IO () menuMain = do putStrLn resStrMenuMain checkAnswer where checkAnswer = do key <- getCh case key of '1' -> do system "cls"; len <- getSeqLen seq <- genSeq len putStrLn resStrGen gameLoop len seq '2' -> backKeyMenu resStrHelp '3' -> backKeyMenu resStrAbout '4' -> putStrLn resStrExit _ -> checkAnswer --Самая неприметная - главная функция; чистит экран, вызывает меню. main = do system "cls" putStrLn resStrInit menuMain
dmamylin/MasterMind
masterMind.hs
unlicense
5,247
0
15
1,240
998
511
487
90
5
module SAML2.XML.Schema ( ns , module SAML2.XML.Schema.Datatypes ) where import SAML2.XML.Types import SAML2.XML.Schema.Datatypes ns :: Namespace ns = mkNamespace "xs" $ httpURI "www.w3.org" "/2001/XMLSchema" "" ""
dylex/hsaml2
SAML2/XML/Schema.hs
apache-2.0
224
0
6
35
59
36
23
7
1
module Minecraft.A328446 (a328446, a328446_list, a328446_row) where import Math.NumberTheory.Powers (integerRoot) a328446 :: Int -> Int a328446 n = a328446_list !! (n - 1) a328446_list :: [Int] a328446_list = concatMap a328446_row [1..] a328446_row :: Int -> [Int] a328446_row 0 = [] a328446_row 1 = [0] a328446_row 2 = [1] a328446_row n | even n = recurse [n `div` 2, n - 1] 2 | odd n = recurse [n - 1] 2 where recurse c k | m == 1 = c | n == m + m^k = recurse (m:c) (k+1) | otherwise = recurse c (k+1) where m = integerRoot k n
peterokagey/haskellOEIS
src/Minecraft/A328446.hs
apache-2.0
560
0
12
132
278
145
133
18
1
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-} {-# LANGUAGE OverloadedStrings, MultiParamTypeClasses #-} {-# LANGUAGE CPP #-} module Foundation ( TierList (..) , TierListRoute (..) , TierListMessage (..) , resourcesTierList , Handler , Widget , maybeAuth , requireAuth , module Yesod , module Settings , module Model , StaticRoute (..) , AuthRoute (..) ) where import Yesod import Yesod.Static (Static, base64md5, StaticRoute(..)) import Settings.StaticFiles import Yesod.Auth import Yesod.Auth.OpenId import Yesod.Form.Jquery import Yesod.Default.Config import Yesod.Default.Util (addStaticContentExternal) import Yesod.Logger (Logger, logLazyText) import qualified Settings import qualified Data.ByteString.Lazy as L import qualified Database.Persist.Base import Database.Persist.MongoDB import Settings (widgetFile) import Model import Text.Jasmine (minifym) import Web.ClientSession (getKey) import Text.Hamlet (hamletFile) #if PRODUCTION import Network.Mail.Mime (sendmail) #else import qualified Data.Text.Lazy.Encoding #endif -- | The site argument for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data TierList = TierList { settings :: AppConfig DefaultEnv , getLogger :: Logger , getStatic :: Static -- ^ Settings for static file serving. , connPool :: Database.Persist.Base.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool. } -- Set up i18n messages. See the message folder. mkMessage "TierList" "messages" "en" -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/handler -- -- This function does three things: -- -- * Creates the route datatype TierListRoute. Every valid URL in your -- application can be represented as a value of this type. -- * Creates the associated type: -- type instance Route TierList = TierListRoute -- * Creates the value resourcesTierList which contains information on the -- resources declared below. This is used in Handler.hs by the call to -- mkYesodDispatch -- -- What this function does *not* do is create a YesodSite instance for -- TierList. Creating that instance requires all of the handler functions -- for our application to be in scope. However, the handler functions -- usually require access to the TierListRoute datatype. Therefore, we -- split these actions into two functions and place them in separate files. mkYesodData "TierList" $(parseRoutesFile "config/routes") -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod TierList where approot = appRoot . settings -- Place the session key file in the config folder encryptKey _ = fmap Just $ getKey "config/client_session_key.aes" defaultLayout widget = do mmsg <- getMessage -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do $(widgetFile "normalize") $(widgetFile "default-layout") hamletToRepHtml $(hamletFile "hamlet/default-layout-wrapper.hamlet") -- This is done to provide an optimization for serving static files from -- a separate domain. Please see the staticRoot setting in Settings.hs urlRenderOverride y (StaticR s) = Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s urlRenderOverride _ _ = Nothing -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR messageLogger y loc level msg = formatLogMessage loc level msg >>= logLazyText (getLogger y) -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute []) -- Enable Javascript async loading yepnopeJs _ = Just $ Right $ StaticR js_modernizr_js -- How to run database actions. instance YesodPersist TierList where type YesodPersistBackend TierList = Action runDB f = liftIOHandler $ fmap connPool getYesod >>= Database.Persist.Base.runPool (undefined :: Settings.PersistConfig) f instance YesodAuth TierList where type AuthId TierList = UserId -- Where to send a user after successful login loginDest _ = RootR -- Where to send a user after logout logoutDest _ = RootR getAuthId creds = runDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (uid, _) -> return $ Just uid Nothing -> do fmap Just $ insert $ User (credsIdent creds) Nothing -- You can add other plugins like BrowserID, email or OAuth here authPlugins = [authOpenId] -- Sends off your mail. Requires sendmail in production! deliver :: TierList -> L.ByteString -> IO () #ifdef PRODUCTION deliver _ = sendmail #else deliver y = logLazyText (getLogger y) . Data.Text.Lazy.Encoding.decodeUtf8 #endif -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage TierList FormMessage where renderMessage _ _ = defaultFormMessage instance YesodJquery TierList
periodic/Simple-Yesod-ToDo
Foundation.hs
bsd-2-clause
5,961
0
17
1,206
842
480
362
80
1
{-# LANGUAGE GADTs #-} module Control.Monad.Shmonad.Conditional where class Boolean b class CondCommand c data If b where If :: (Boolean b) => b -> If b data PartialCond b c where Then :: (Boolean b, CondCommand c) => If b -> c -> PartialCond b c ElifThen :: (Boolean b, CondCommand c) => PartialCond b c -> b -> c -> PartialCond b c data Cond b c where ElseFi :: (Boolean b, CondCommand c) => PartialCond b c -> c -> Cond b c Fi :: (Boolean b, CondCommand c) => PartialCond b c -> Cond b c ifThen :: (Boolean b, CondCommand c) => b -> c -> (PartialCond b c -> Cond b c) -> Cond b c ifThen b c f = f (Then (If b) c) elifThen :: (Boolean b, CondCommand c) => b -> c -> (PartialCond b c -> Cond b c) -> PartialCond b c -> Cond b c elifThen b c f i = f (ElifThen i b c) elseFi :: (Boolean b, CondCommand c) => c -> PartialCond b c -> Cond b c elseFi = flip ElseFi fi :: (Boolean b, CondCommand c) => PartialCond b c -> Cond b c fi = Fi
corajr/shmonad
src/Control/Monad/Shmonad/Conditional.hs
bsd-2-clause
951
0
11
223
469
241
228
-1
-1
module Data.Strict.Tuple where import Data.Bifunctor data Pair a b = Pair !a !b data Triple a b c = Triple !a !b !c data Quadruple a b c d = Quadruple !a !b !c !d instance Functor (Pair a) where fmap f (Pair a b) = Pair a (f b) {-# INLINE fmap #-} instance Bifunctor Pair where bimap f g (Pair a b) = Pair (f a) (g b) {-# INLINE bimap #-} instance Monoid a => Applicative (Pair a) where pure = Pair mempty {-# INLINE pure #-} Pair x1 g <*> Pair x2 y = Pair (x1 `mappend` x2) (g y) {-# INLINE (<*>) #-} instance Functor (Triple a b) where fmap f (Triple a b c) = Triple a b (f c) {-# INLINE fmap #-} instance Bifunctor (Triple a) where bimap f g (Triple a b c) = Triple a (f b) (g c) {-# INLINE bimap #-} instance Functor (Quadruple a b c) where fmap f (Quadruple a b c d) = Quadruple a b c (f d) {-# INLINE fmap #-} instance Bifunctor (Quadruple a b) where bimap f g (Quadruple a b c d) = Quadruple a b (f c) (g d) {-# INLINE bimap #-} fstp :: Pair a b -> a fstp (Pair a b) = a {-# INLINE fstp #-} sndp :: Pair a b -> b sndp (Pair a b) = b {-# INLINE sndp #-} fromPair :: Pair a b -> (a, b) fromPair (Pair a b) = (a, b) {-# INLINE fromPair #-} toPair :: (a, b) -> Pair a b toPair (a, b) = Pair a b {-# INLINE toPair #-} fstt :: Triple a b c -> a fstt (Triple a b c) = a {-# INLINE fstt #-} sndt :: Triple a b c -> b sndt (Triple a b c) = b {-# INLINE sndt #-} thdt :: Triple a b c -> c thdt (Triple a b c) = c {-# INLINE thdt #-} fstq :: Quadruple a b c d -> a fstq (Quadruple a b c d) = a {-# INLINE fstq #-} sndq :: Quadruple a b c d -> b sndq (Quadruple a b c d) = b {-# INLINE sndq #-} thdq :: Quadruple a b c d -> c thdq (Quadruple a b c d) = c {-# INLINE thdq #-} fthq :: Quadruple a b c d -> d fthq (Quadruple a b c d) = d {-# INLINE fthq #-}
effectfully/prefolds
src/Data/Strict/Tuple.hs
bsd-3-clause
1,825
0
8
492
861
443
418
79
1
print_list [] = return() print_list x = do print (head x) print_list (tail x) main = do let a = [i | i <- [1..100], (mod i 5) == 0] print_list a
yuncliu/Learn
haskell/list_comprehension.hs
bsd-3-clause
162
0
14
49
100
47
53
7
1
{-# LANGUAGE NoImplicitPrelude #-} {- | Imports used in the whole codebase. (All modules import this one instead of the "Prelude".) -} module Imports ( module X, LByteString ) where import BasePrelude as X hiding (Category, GeneralCategory, lazy, Handler, diff, option) -- Lists import Data.List.Extra as X (dropEnd, takeEnd) import Data.List.Index as X -- Lenses import Lens.Micro.Platform as X -- Monads and monad transformers import Control.Monad.Reader as X import Control.Monad.State as X import Control.Monad.Except as X -- Common types import Data.ByteString as X (ByteString) import Data.Map as X (Map) import Data.Set as X (Set) import Data.Text.All as X (LText, Text) -- Time import Data.Time as X -- Files import System.Directory as X import System.FilePath as X -- Deepseq import Control.DeepSeq as X -- Hashable import Data.Hashable as X -- Lazy bytestring import qualified Data.ByteString.Lazy as BSL -- Formatting import Fmt as X type LByteString = BSL.ByteString -- LText is already provided by Data.Text.All
aelve/hslibs
src/Imports.hs
bsd-3-clause
1,349
0
5
477
217
157
60
25
0
{-# LANGUAGE DeriveDataTypeable #-} module Allegro.Timer ( -- * Operations Timer , createTimer , startTimer , stopTimer , isTimerStarted , getTimerCount , setTimerCount , addTimerCount , getTimerSpeed , setTimerSpeed -- * Events , TimerEvent , evTimer , evCount -- * Exceptions , FailedToCreateTimer(..) ) where import Allegro.Types import Allegro.C.Types import Allegro.C.Timer import Allegro.C.Event import qualified Control.Exception as X import Data.Int( Int64 ) import Data.IORef ( readIORef ) import Control.Applicative ( (<$>), (<*>) ) import Control.Monad ( when ) import Data.Typeable ( Typeable ) import Foreign ( ForeignPtr, newForeignPtr, castForeignPtr , withForeignPtr , Ptr, nullPtr, castPtr ) import Foreign.ForeignPtr.Unsafe ( unsafeForeignPtrToPtr ) newtype Timer = Timer (ForeignPtr TIMER) deriving Eq withTimer :: Timer -> (Ptr TIMER -> IO a) -> IO a withTimer (Timer x) = withForeignPtr x instance EventSource Timer where eventSource t = withTimer t al_get_timer_event_source foreignClient (Timer t) = Just (castForeignPtr t) createTimer :: Double -- ^ Timer speed -> IO Timer createTimer sp = do ptr <- al_create_timer (realToFrac sp) when (ptr == nullPtr) $ X.throwIO FailedToCreateTimer Timer `fmap` newForeignPtr al_destroy_timer_addr ptr data FailedToCreateTimer = FailedToCreateTimer deriving (Typeable,Show) instance X.Exception FailedToCreateTimer startTimer :: Timer -> IO () startTimer t = withTimer t al_start_timer stopTimer :: Timer -> IO () stopTimer t = withTimer t al_stop_timer isTimerStarted :: Timer -> IO Bool isTimerStarted t = withTimer t al_get_timer_started getTimerCount :: Timer -> IO Int64 getTimerCount t = withTimer t al_get_timer_count setTimerCount :: Timer -> Int64 -> IO () setTimerCount t x = withTimer t $ \p -> al_set_timer_count p x addTimerCount :: Timer -> Int64 -> IO () addTimerCount t x = withTimer t $ \p -> al_add_timer_count p x getTimerSpeed :: Timer -> IO Double getTimerSpeed t = fmap realToFrac (withTimer t al_get_timer_speed) setTimerSpeed :: Timer -> Double -> IO () setTimerSpeed t x = withTimer t $ \p -> al_set_timer_speed p (realToFrac x) -------------------------------------------------------------------------------- -- Events data TimerEvent = EvTimer { tiSuper' :: {-# UNPACK #-} !SomeEvent , evTimer :: !Timer -- strict to avoid holding on to clients of -- event queue. , evCount :: !Int64 } instance ParseEvent TimerEvent where eventDetails q p = EvTimer <$> eventDetails q p <*> (getTimer =<< event_timer_source p) <*> event_timer_count p where getTimer t = findMe (castPtr t) <$> readIORef (eqReg q) findMe :: Ptr () -> [ForeignPtr ()] -> Timer findMe x (y:_) | x == unsafeForeignPtrToPtr y = Timer (castForeignPtr y) findMe x (_:ys) = findMe x ys findMe _ [] = error "Allegro bug: received event from unregistered timer." instance HasType TimerEvent where evType = evType' . tiSuper' instance HasTimestamp TimerEvent where evTimestamp = evTimestamp' . tiSuper'
yav/allegro
src/Allegro/Timer.hs
bsd-3-clause
3,329
0
12
813
919
485
434
80
1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE Safe #-} {- | Module : Physics.Learn.Mechanics Copyright : (c) Scott N. Walck 2014-2019 License : BSD3 (see LICENSE) Maintainer : Scott N. Walck <[email protected]> Stability : experimental Newton's second law and all that -} module Physics.Learn.Mechanics ( TheTime , TimeStep , Velocity -- * Simple one-particle state , SimpleState , SimpleAccelerationFunction , simpleStateDeriv , simpleRungeKuttaStep -- * One-particle state , St(..) , DSt(..) , OneParticleSystemState , OneParticleAccelerationFunction , oneParticleStateDeriv , oneParticleRungeKuttaStep , oneParticleRungeKuttaSolution -- * Two-particle state , TwoParticleSystemState , TwoParticleAccelerationFunction , twoParticleStateDeriv , twoParticleRungeKuttaStep -- * Many-particle state , ManyParticleSystemState , ManyParticleAccelerationFunction , manyParticleStateDeriv , manyParticleRungeKuttaStep ) where import Data.VectorSpace ( AdditiveGroup(..) , VectorSpace(..) ) import Physics.Learn.StateSpace ( StateSpace(..) , Diff , DifferentialEquation ) import Physics.Learn.RungeKutta ( rungeKutta4 , integrateSystem ) import Physics.Learn.Position ( Position ) import Physics.Learn.CarrotVec ( Vec ) -- | Time (in s). type TheTime = Double -- | A time step (in s). type TimeStep = Double -- | Velocity of a particle (in m/s). type Velocity = Vec ------------------------------- -- Simple one-particle state -- ------------------------------- -- | A simple one-particle state, -- to get started quickly with mechanics of one particle. type SimpleState = (TheTime,Position,Velocity) -- | An acceleration function gives the particle's acceleration as -- a function of the particle's state. -- The specification of this function is what makes one single-particle -- mechanics problem different from another. -- In order to write this function, add all of the forces -- that act on the particle, and divide this net force by the particle's mass. -- (Newton's second law). type SimpleAccelerationFunction = SimpleState -> Vec -- | Time derivative of state for a single particle -- with a constant mass. simpleStateDeriv :: SimpleAccelerationFunction -- ^ acceleration function for the particle -> DifferentialEquation SimpleState -- ^ differential equation simpleStateDeriv a (t, r, v) = (1, v, a(t, r, v)) -- | Single Runge-Kutta step simpleRungeKuttaStep :: SimpleAccelerationFunction -- ^ acceleration function for the particle -> TimeStep -- ^ time step -> SimpleState -- ^ initial state -> SimpleState -- ^ state after one time step simpleRungeKuttaStep = rungeKutta4 . simpleStateDeriv ------------------------ -- One-particle state -- ------------------------ -- | The state of a single particle is given by -- the position of the particle and the velocity of the particle. data St = St { position :: Position , velocity :: Velocity } deriving (Show) -- | The associated vector space for the -- state of a single particle. data DSt = DSt Vec Vec deriving (Show) instance AdditiveGroup DSt where zeroV = DSt zeroV zeroV negateV (DSt dr dv) = DSt (negateV dr) (negateV dv) DSt dr1 dv1 ^+^ DSt dr2 dv2 = DSt (dr1 ^+^ dr2) (dv1 ^+^ dv2) instance VectorSpace DSt where type Scalar DSt = Double c *^ DSt dr dv = DSt (c*^dr) (c*^dv) instance StateSpace St where type Diff St = DSt St r1 v1 .-. St r2 v2 = DSt (r1 .-. r2) (v1 .-. v2) St r1 v1 .+^ DSt dr dv = St (r1 .+^ dr) (v1 .+^ dv) -- | The state of a system of one particle is given by the current time, -- the position of the particle, and the velocity of the particle. -- Including time in the state like this allows us to -- have time-dependent forces. type OneParticleSystemState = (TheTime,St) -- | An acceleration function gives the particle's acceleration as -- a function of the particle's state. type OneParticleAccelerationFunction = OneParticleSystemState -> Vec -- | Time derivative of state for a single particle -- with a constant mass. oneParticleStateDeriv :: OneParticleAccelerationFunction -- ^ acceleration function for the particle -> DifferentialEquation OneParticleSystemState -- ^ differential equation oneParticleStateDeriv a st@(_t, St _r v) = (1, DSt v (a st)) -- | Single Runge-Kutta step oneParticleRungeKuttaStep :: OneParticleAccelerationFunction -- ^ acceleration function for the particle -> TimeStep -- ^ time step -> OneParticleSystemState -- ^ initial state -> OneParticleSystemState -- ^ state after one time step oneParticleRungeKuttaStep = rungeKutta4 . oneParticleStateDeriv -- | List of system states oneParticleRungeKuttaSolution :: OneParticleAccelerationFunction -- ^ acceleration function for the particle -> TimeStep -- ^ time step -> OneParticleSystemState -- ^ initial state -> [OneParticleSystemState] -- ^ state after one time step oneParticleRungeKuttaSolution = integrateSystem . oneParticleStateDeriv ------------------------ -- Two-particle state -- ------------------------ -- | The state of a system of two particles is given by the current time, -- the position and velocity of particle 1, -- and the position and velocity of particle 2. type TwoParticleSystemState = (TheTime,St,St) -- | An acceleration function gives a pair of accelerations -- (one for particle 1, one for particle 2) as -- a function of the system's state. type TwoParticleAccelerationFunction = TwoParticleSystemState -> (Vec,Vec) -- | Time derivative of state for two particles -- with constant mass. twoParticleStateDeriv :: TwoParticleAccelerationFunction -- ^ acceleration function for two particles -> DifferentialEquation TwoParticleSystemState -- ^ differential equation twoParticleStateDeriv af2 st2@(_t, St _r1 v1, St _r2 v2) = (1, DSt v1 a1, DSt v2 a2) where (a1,a2) = af2 st2 -- | Single Runge-Kutta step for two-particle system twoParticleRungeKuttaStep :: TwoParticleAccelerationFunction -- ^ acceleration function -> TimeStep -- ^ time step -> TwoParticleSystemState -- ^ initial state -> TwoParticleSystemState -- ^ state after one time step twoParticleRungeKuttaStep = rungeKutta4 . twoParticleStateDeriv ------------------------- -- Many-particle state -- ------------------------- -- | The state of a system of many particles is given by the current time -- and a list of one-particle states. type ManyParticleSystemState = (TheTime,[St]) -- | An acceleration function gives a list of accelerations -- (one for each particle) as -- a function of the system's state. type ManyParticleAccelerationFunction = ManyParticleSystemState -> [Vec] -- | Time derivative of state for many particles -- with constant mass. manyParticleStateDeriv :: ManyParticleAccelerationFunction -- ^ acceleration function for many particles -> DifferentialEquation ManyParticleSystemState -- ^ differential equation manyParticleStateDeriv af st@(_t, sts) = (1, [DSt v a | (v,a) <- zip vs as]) where vs = map velocity sts as = af st -- | Single Runge-Kutta step for many-particle system manyParticleRungeKuttaStep :: ManyParticleAccelerationFunction -- ^ acceleration function -> TimeStep -- ^ time step -> ManyParticleSystemState -- ^ initial state -> ManyParticleSystemState -- ^ state after one time step manyParticleRungeKuttaStep = rungeKutta4 . manyParticleStateDeriv -- Can we automatically incorporate Newton's third law?
walck/learn-physics
src/Physics/Learn/Mechanics.hs
bsd-3-clause
8,111
0
9
1,927
1,068
643
425
107
1
{- - The Pee Shell, an interactive environment for evaluating pure untyped pee terms. - Copyright (C) 2005-2007, Robert Dockins - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} module Language.PiEtaEpsilon.Interactive.CmdLine ( peeCmdLine ) where import Data.IORef import Numeric import Data.Maybe import Data.List import Data.Char import qualified Data.Map as Map import System.IO import System.Exit import System.Console.GetOpt import Text.ParserCombinators.Parsec (runParser) import Language.PiEtaEpsilon.Interactive.Shell import Language.PiEtaEpsilon.Interactive.Version import Language.PiEtaEpsilon.Interactive.StatementParser import Language.PiEtaEpsilon.Syntax hiding (Left, Right) import Language.PiEtaEpsilon.Evaluator import Language.PiEtaEpsilon.Pretty.REPL import Language.PiEtaEpsilon.Pretty.Class ----------------------------------------------------------------------- -- Main entry point for the command line tool main = peeCmdLine [] -- | Parse command line options and run the pee shell peeCmdLine :: [String] -> IO () peeCmdLine argv = do st <- parseCmdLine argv case (cmd_print st) of PrintNothing -> doCmdLine st PrintHelp -> putStr (printUsage usageNotes) PrintVersion -> putStr versionInfo PrintNoWarranty -> putStr noWarranty PrintGPL -> putStr gpl doCmdLine :: PeeCmdLineState -> IO () doCmdLine st = case (cmd_input st) of Just expr -> evalInput st expr Nothing -> if (cmd_stdin st) then evalStdin st else runShell st -------------------------------------------------------------- -- Holds important values parsed from the command line data PeeCmdLineState = PeeCmdLineState { cmd_reverse :: Bool , cmd_stdin :: Bool , cmd_input :: Maybe String , cmd_binds :: Bindings , cmd_print :: PrintWhat , cmd_history :: Maybe String } initialCmdLineState = PeeCmdLineState { cmd_reverse = True , cmd_stdin = False , cmd_input = Nothing , cmd_binds = Map.empty , cmd_print = PrintNothing , cmd_history = Just "pee.history" } data PrintWhat = PrintNothing | PrintVersion | PrintHelp | PrintNoWarranty | PrintGPL ------------------------------------------------------------- -- Set up the command line options data PeeCmdLineArgs = Reverse | ReadStdIn | Program String | Print PrintWhat | History String | NoHistory options :: [OptDescr PeeCmdLineArgs] options = [ Option ['r'] ["reverse"] (NoArg Reverse) "perform evaluation in reverse" , Option ['s'] ["stdin"] (NoArg ReadStdIn) "read from standard in" , Option ['e'] ["program"] (ReqArg Program "PROGRAM") "evaluate statements from command line" , Option ['h','?'] ["help"] (NoArg (Print PrintHelp)) "print this message" , Option ['v'] ["version"] (NoArg (Print PrintVersion)) "print version information" , Option ['g'] ["gpl"] (NoArg (Print PrintGPL)) "print the GNU GPLv2, under which this software is licensed" , Option ['w'] ["nowarranty"] (NoArg (Print PrintNoWarranty)) "print the warranty disclamer" , Option ['w'] ["history"] (ReqArg History "HISTORY_FILE") "set the command history file (default: 'pee.history')" , Option ['q'] ["nohistory"] (NoArg NoHistory) "disable command history file" ] ----------------------------------------------------------------- -- Parser for the command line -- yeah, I know its ugly parseCmdLine :: [String] -> IO PeeCmdLineState parseCmdLine argv = case getOpt RequireOrder options argv of (opts,files,[]) -> (foldl (>>=) (return initialCmdLineState) $ map applyFlag opts) >>= \st -> (foldl (>>=) (return st) $ map loadDefs files) (_,_,errs) -> fail (errMsg errs) where errMsg errs = printUsage (concat (intersperse "\n" errs)) applyFlag :: PeeCmdLineArgs -> PeeCmdLineState -> IO PeeCmdLineState applyFlag Reverse st = return st{ cmd_reverse = True } applyFlag ReadStdIn st = return st{ cmd_stdin = True } applyFlag NoHistory st = return st{ cmd_history = Nothing } applyFlag (History nm) st = return st{ cmd_history = Just nm } applyFlag (Print printWhat) st = return st{ cmd_print = printWhat } applyFlag (Program pgm) st = case cmd_input st of Nothing -> return st{ cmd_input = Just pgm } _ -> fail (errMsg ["'-e' option may only occur once"]) ----------------------------------------------------------------------- -- Actually run the shell mapToShellState :: PeeCmdLineState -> PeeShellState mapToShellState st = initialShellState { letBindings = cmd_binds st , forwards = cmd_reverse st , histFile = cmd_history st } runShell :: PeeCmdLineState -> IO () runShell st = do -- putStrLn versionInfo -- putStrLn shellMessage peeShell (mapToShellState st) return () -------------------------------------------------------------------------- -- For dealing with input from stdin or the command line evalStdin :: PeeCmdLineState -> IO () evalStdin st = hGetContents stdin >>= evalInput st evalInput :: PeeCmdLineState -> String -> IO () evalInput st expr = do exitCode <- newIORef ExitSuccess case pStatement expr of Left msg -> fail (show msg) Right stmt -> evalStmt exitCode st stmt code <- readIORef exitCode exitWith code setSucc :: IORef ExitCode -> IO () setSucc ec = writeIORef ec ExitSuccess setFail :: IORef ExitCode -> IO () setFail ec = writeIORef ec (ExitFailure 100) evalStmt :: IORef ExitCode -> PeeCmdLineState -> Statement -> IO PeeCmdLineState evalStmt ec st (Stmt_eval t v) = evalTerm st t v >> setSucc ec >> return st --evalStmt ec st (Stmt_isEq t1 t2) = compareTerms ec st t1 t2 >> return st evalStmt ec st (Stmt_let name t) = setSucc ec >> return st{ cmd_binds = Map.insert name t (cmd_binds st) } evalStmt ec st (Stmt_empty) = setSucc ec >> return st evalTerm :: PeeCmdLineState -> Term -> UValue -> IO () evalTerm st t v = putStrLn . ppr $ topLevelWithState (cmdLineStateToMachineState st) t v cmdLineStateToMachineState = error "cmdLineStateToMachineState" compareTerms :: IORef ExitCode -> PeeCmdLineState -> Term -> Term -> IO () compareTerms = error "compareTerms" --compareTerms ec st t1 t2 = do -- if normalEq (cmd_binds st) t1 t2 -- then putStrLn "equal" >> setSucc ec -- else putStrLn "not equal" >> setFail ec ------------------------------------------------------------------------- -- Read definitions from a file loadDefs :: FilePath -> PeeCmdLineState -> IO PeeCmdLineState loadDefs = error "loadDefs not defined" --loadDefs path st = do -- let parseSt = PeeParseState (cmd_cps st) (cmd_extsyn st) -- binds <- readDefinitionFile parseSt (cmd_binds st) path -- return st{ cmd_binds = Map.union binds (cmd_binds st) } ----------------------------------------------------------------------- -- Printing stuff printUsage :: String -> String printUsage str = unlines [ "" , "" , usageInfo "usage: peeShell {<option>} [{<file>}]\n" options , "" , "" ,str , "" ] usageNotes :: String usageNotes = unlines [ "Any files listed after the options will be parsed as a series of" , "\"let\" definitions, which will be in scope when the shell starts" , "(or when the -e expression is evaluated)" ]
dmwit/pi-eta-epsilon
src/Language/PiEtaEpsilon/Interactive/CmdLine.hs
bsd-3-clause
8,430
0
14
2,026
1,723
918
805
147
8
{-# LANGUAGE CPP, StandaloneDeriving, DeriveFoldable, DeriveTraversable #-} module Data.PairMonad where import Control.Applicative -- #ifdef __HAS_LENS__ import Control.Lens() -- #endif __HAS_LENS__ import Data.Monoid import Data.Foldable import Data.Traversable -- Equivalent to the Monad Writer instance. instance Monoid o => Monad ((,) o) where return = pure (o,a) >>= f = (o `mappend` o', a') where (o',a') = f a -- #ifndef __HAS_LENS__ -- deriving instance Foldable ((,) o) -- deriving instance Traversable ((,) o) -- #endif __HAS_LENS__
FranklinChen/music-score
src/Data/PairMonad.hs
bsd-3-clause
575
0
8
107
117
70
47
14
0
module CountingFilter ( empty, insert, insertMany, CountingFilter) where import qualified Data.Map type CountingFilter a = Data.Map.Map a Integer -- | Produce an empty counting filter. empty :: (Ord a) => CountingFilter a empty = Data.Map.empty -- | Increment the value in the given filter once. insert :: (Ord a) => a -> CountingFilter a -> CountingFilter a insert val cFilter = Data.Map.insertWith (+) val 1 cFilter -- | Increment the value in the given filter the given number of times. insertMany :: (Ord a) => a -> Integer -> CountingFilter a -> CountingFilter a insertMany val count cFilter = Data.Map.insertWith (+) val count cFilter
TinnedTuna/shannon-entropy-estimator
src/CountingFilter.hs
bsd-3-clause
660
8
9
123
185
103
82
15
1
module Instances where import Control.Applicative import Test.QuickCheck import Rainbow.Types import qualified Data.Text as X newtype ChunkA = ChunkA Chunk deriving (Eq, Ord, Show) newtype TextA = TextA X.Text deriving (Eq, Ord, Show) instance Arbitrary TextA where arbitrary = (TextA . X.pack) <$> listOf arbitrary instance Arbitrary Chunk where arbitrary = undefined
massysett/prednote
tests/Instances.hs
bsd-3-clause
382
0
9
64
117
67
50
13
0
{-# LANGUAGE FlexibleContexts #-} module NinetyNine.Problem27 where import Data.List (zipWith, permutations) -- import Test.Hspec -- Group the elements of a set into disjoint subsets. -- cde = zipWith (+) [1,2] [3, 4] -- zipWith take [12, 3, 4] (permutations ["aldo","beat","carla","david","evi","flip","gary","hugo","ida"]) -- group2 :: [a] -> [b] -> [[b]] -- group2 xs ys = take 5 (zipWith (\a b -> take a b) xs (permutations ys) -- group [2,3,4] ["aldo","beat","carla","david","evi","flip","gary","hugo","ida"] combination :: Int -> [a] -> [([a], [a])] combination 0 xs = [([], xs)] combination n [] = [] combination n (x:xs) = ts ++ ds where ts = [(x:ys, zs) | (ys, zs) <- combination (n - 1) xs] ds = [(ys, x:zs) | (ys, zs) <- combination n xs]
chemouna/99Haskell
src/problem27.hs
bsd-3-clause
770
0
12
140
197
116
81
9
1
{-# LANGUAGE RecordWildCards, BangPatterns #-} module Main where import System.Exit (ExitCode(..)) import System.Console.ANSI import System.Process (readProcessWithExitCode) import System.Timeout (timeout) import Control.Concurrent import Control.Monad import Data.Monoid import Data.Time.Clock import Data.String.Utils import Text.Printf import Options.Applicative data Task = Task { taskHost :: String , taskCmd :: [String] } deriving Show data Result = Result { resHost :: String , resPayload :: Either String String , resTime :: NominalDiffTime } deriving Show -- | time the given IO action (clock time) and return a tuple -- of the execution time and the result timeIO :: IO a -> IO (NominalDiffTime, a) timeIO ioa = do t1 <- getCurrentTime !a <- ioa t2 <- getCurrentTime return (diffUTCTime t2 t1, a) runTasks :: [Task] -> Int -> (Result -> IO a) -> IO () runTasks ts tmout handler = do out <- newChan forM_ ts $ run out replicateM_ (length ts) (readChan out >>= handler) where run ch t = forkIO $ do !res <- runTask t tmout writeChan ch res runTask :: Task -> Int -> IO Result runTask Task{..} tmout = do (time, res) <- timeIO . timeout tmout $ readProcessWithExitCode "ssh" args [] case res of Nothing -> output time $ Left "timed out\n" Just (code, stdout', stderr') -> output time $ case code of ExitSuccess -> Right stdout' ExitFailure _ -> Left stderr' where args = "-T" : taskHost : taskCmd output time payload = return $ Result taskHost payload time mkTasks :: [String] -> [String] -> [Task] mkTasks hosts cmd = map f hosts where f h = Task h cmd ---------------- -- PRINTING ---------------- putColorLn :: ColorIntensity -> Color -> String -> IO () putColorLn intensity color s = do setSGR [SetColor Foreground intensity color] putStrLn s setSGR [] printResult :: Result -> IO () printResult Result{..} = do putColorLn Dull Blue (resHost ++ t) case resPayload of Left s -> putColorLn Vivid Red s Right s -> putStrLn s where t = printf " (%.1fs)" (realToFrac resTime :: Double) printShortResult :: Result -> IO () printShortResult Result{..} = case resPayload of Left s -> putColorLn Vivid Red $ resHost ++ ": " ++ rstrip s Right s -> putStrLn $ resHost ++ ": " ++ rstrip s ---------------- -- ARGS ---------------- data Options = Options { oFile :: FilePath , oCommand :: String , oTimeout :: Int , oShort :: Bool } deriving Show options :: Parser Options options = Options <$> argument str (metavar "FILE") <*> argument str (metavar "COMMAND") <*> option ( short 't' <> metavar "TIMEOUT" <> help "ssh timout in seconds" <> showDefault <> value 10 ) <*> switch ( short 's' <> metavar "SHORT" <> help "display results in short format" ) main :: IO () main = execParser (info (helper <*> options) fullDesc) >>= go go :: Options -> IO () go Options{..} = do hosts <- readHosts runTasks (mkTasks hosts cmd) tmout handler where readHosts = filter ((not . null) . strip) . lines <$> readFile oFile handler = if oShort then printShortResult else printResult tmout = oTimeout * 1000000 cmd = words oCommand
jhickner/minions
minions.hs
bsd-3-clause
3,570
0
14
1,069
1,123
569
554
96
3
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Error-checking and other utilities for @deriving@ clauses or declarations. -} {-# LANGUAGE TypeFamilies #-} module TcDerivUtils ( DerivM, DerivEnv(..), DerivSpec(..), pprDerivSpec, DerivSpecMechanism(..), isDerivSpecStock, isDerivSpecNewtype, isDerivSpecAnyClass, DerivContext, DerivStatus(..), PredOrigin(..), ThetaOrigin(..), mkPredOrigin, mkThetaOrigin, mkThetaOriginFromPreds, substPredOrigin, checkSideConditions, hasStockDeriving, canDeriveAnyClass, std_class_via_coercible, non_coercible_class, newDerivClsInst, extendLocalInstEnv ) where import GhcPrelude import Bag import BasicTypes import Class import DataCon import DynFlags import ErrUtils import HscTypes (lookupFixity, mi_fix) import HsSyn import Inst import InstEnv import LoadIface (loadInterfaceForName) import Module (getModule) import Name import Outputable import PrelNames import SrcLoc import TcGenDeriv import TcGenFunctor import TcGenGenerics import TcRnMonad import TcType import THNames (liftClassKey) import TyCon import Type import Util import VarSet import Control.Monad.Trans.Reader import qualified GHC.LanguageExtensions as LangExt import ListSetOps (assocMaybe) -- | To avoid having to manually plumb everything in 'DerivEnv' throughout -- various functions in @TcDeriv@ and @TcDerivInfer@, we use 'DerivM', which -- is a simple reader around 'TcRn'. type DerivM = ReaderT DerivEnv TcRn -- | Contains all of the information known about a derived instance when -- determining what its @EarlyDerivSpec@ should be. data DerivEnv = DerivEnv { denv_overlap_mode :: Maybe OverlapMode -- ^ Is this an overlapping instance? , denv_tvs :: [TyVar] -- ^ Universally quantified type variables in the instance , denv_cls :: Class -- ^ Class for which we need to derive an instance , denv_cls_tys :: [Type] -- ^ Other arguments to the class except the last , denv_tc :: TyCon -- ^ Type constructor for which the instance is requested -- (last arguments to the type class) , denv_tc_args :: [Type] -- ^ Arguments to the type constructor , denv_rep_tc :: TyCon -- ^ The representation tycon for 'denv_tc' -- (for data family instances) , denv_rep_tc_args :: [Type] -- ^ The representation types for 'denv_tc_args' -- (for data family instances) , denv_mtheta :: DerivContext -- ^ 'Just' the context of the instance, for standalone deriving. -- 'Nothing' for @deriving@ clauses. , denv_strat :: Maybe DerivStrategy -- ^ 'Just' if user requests a particular deriving strategy. -- Otherwise, 'Nothing'. } instance Outputable DerivEnv where ppr (DerivEnv { denv_overlap_mode = overlap_mode , denv_tvs = tvs , denv_cls = cls , denv_cls_tys = cls_tys , denv_tc = tc , denv_tc_args = tc_args , denv_rep_tc = rep_tc , denv_rep_tc_args = rep_tc_args , denv_mtheta = mtheta , denv_strat = mb_strat }) = hang (text "DerivEnv") 2 (vcat [ text "denv_overlap_mode" <+> ppr overlap_mode , text "denv_tvs" <+> ppr tvs , text "denv_cls" <+> ppr cls , text "denv_cls_tys" <+> ppr cls_tys , text "denv_tc" <+> ppr tc , text "denv_tc_args" <+> ppr tc_args , text "denv_rep_tc" <+> ppr rep_tc , text "denv_rep_tc_args" <+> ppr rep_tc_args , text "denv_mtheta" <+> ppr mtheta , text "denv_strat" <+> ppr mb_strat ]) data DerivSpec theta = DS { ds_loc :: SrcSpan , ds_name :: Name -- DFun name , ds_tvs :: [TyVar] , ds_theta :: theta , ds_cls :: Class , ds_tys :: [Type] , ds_tc :: TyCon , ds_overlap :: Maybe OverlapMode , ds_mechanism :: DerivSpecMechanism } -- This spec implies a dfun declaration of the form -- df :: forall tvs. theta => C tys -- The Name is the name for the DFun we'll build -- The tyvars bind all the variables in the theta -- For type families, the tycon in -- in ds_tys is the *family* tycon -- in ds_tc is the *representation* type -- For non-family tycons, both are the same -- the theta is either the given and final theta, in standalone deriving, -- or the not-yet-simplified list of constraints together with their origin -- ds_mechanism specifies the means by which GHC derives the instance. -- See Note [Deriving strategies] in TcDeriv {- Example: newtype instance T [a] = MkT (Tree a) deriving( C s ) ==> axiom T [a] = :RTList a axiom :RTList a = Tree a DS { ds_tvs = [a,s], ds_cls = C, ds_tys = [s, T [a]] , ds_tc = :RTList, ds_mechanism = DerivSpecNewtype (Tree a) } -} pprDerivSpec :: Outputable theta => DerivSpec theta -> SDoc pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs, ds_cls = c, ds_tys = tys, ds_theta = rhs, ds_mechanism = mech }) = hang (text "DerivSpec") 2 (vcat [ text "ds_loc =" <+> ppr l , text "ds_name =" <+> ppr n , text "ds_tvs =" <+> ppr tvs , text "ds_cls =" <+> ppr c , text "ds_tys =" <+> ppr tys , text "ds_theta =" <+> ppr rhs , text "ds_mechanism =" <+> ppr mech ]) instance Outputable theta => Outputable (DerivSpec theta) where ppr = pprDerivSpec -- What action to take in order to derive a class instance. -- See Note [Deriving strategies] in TcDeriv data DerivSpecMechanism = DerivSpecStock -- "Standard" classes (SrcSpan -> TyCon -> [Type] -> TcM (LHsBinds GhcPs, BagDerivStuff, [Name])) -- This function returns three things: -- -- 1. @LHsBinds GhcPs@: The derived instance's function bindings -- (e.g., @compare (T x) (T y) = compare x y@) -- 2. @BagDerivStuff@: Auxiliary bindings needed to support the derived -- instance. As examples, derived 'Generic' instances require -- associated type family instances, and derived 'Eq' and 'Ord' -- instances require top-level @con2tag@ functions. -- See Note [Auxiliary binders] in TcGenDeriv. -- 3. @[Name]@: A list of Names for which @-Wunused-binds@ should be -- suppressed. This is used to suppress unused warnings for record -- selectors when deriving 'Read', 'Show', or 'Generic'. -- See Note [Deriving and unused record selectors]. | DerivSpecNewtype -- -XGeneralizedNewtypeDeriving Type -- The newtype rep type | DerivSpecAnyClass -- -XDeriveAnyClass isDerivSpecStock, isDerivSpecNewtype, isDerivSpecAnyClass :: DerivSpecMechanism -> Bool isDerivSpecStock (DerivSpecStock{}) = True isDerivSpecStock _ = False isDerivSpecNewtype (DerivSpecNewtype{}) = True isDerivSpecNewtype _ = False isDerivSpecAnyClass (DerivSpecAnyClass{}) = True isDerivSpecAnyClass _ = False -- A DerivSpecMechanism can be losslessly converted to a DerivStrategy. mechanismToStrategy :: DerivSpecMechanism -> DerivStrategy mechanismToStrategy (DerivSpecStock{}) = StockStrategy mechanismToStrategy (DerivSpecNewtype{}) = NewtypeStrategy mechanismToStrategy (DerivSpecAnyClass{}) = AnyclassStrategy instance Outputable DerivSpecMechanism where ppr = ppr . mechanismToStrategy type DerivContext = Maybe ThetaType -- Nothing <=> Vanilla deriving; infer the context of the instance decl -- Just theta <=> Standalone deriving: context supplied by programmer data DerivStatus = CanDerive -- Stock class, can derive | DerivableClassError SDoc -- Stock class, but can't do it | DerivableViaInstance -- See Note [Deriving any class] | NonDerivableClass SDoc -- Non-stock class -- A stock class is one either defined in the Haskell report or for which GHC -- otherwise knows how to generate code for (possibly requiring the use of a -- language extension), such as Eq, Ord, Ix, Data, Generic, etc. -- | A 'PredType' annotated with the origin of the constraint 'CtOrigin', -- and whether or the constraint deals in types or kinds. data PredOrigin = PredOrigin PredType CtOrigin TypeOrKind -- | A list of wanted 'PredOrigin' constraints ('to_wanted_origins') alongside -- any corresponding given constraints ('to_givens') and locally quantified -- type variables ('to_tvs'). -- -- In most cases, 'to_givens' will be empty, as most deriving mechanisms (e.g., -- stock and newtype deriving) do not require given constraints. The exception -- is @DeriveAnyClass@, which can involve given constraints. For example, -- if you tried to derive an instance for the following class using -- @DeriveAnyClass@: -- -- @ -- class Foo a where -- bar :: a -> b -> String -- default bar :: (Show a, Ix b) => a -> b -> String -- bar = show -- -- baz :: Eq a => a -> a -> Bool -- default baz :: Ord a => a -> a -> Bool -- baz x y = compare x y == EQ -- @ -- -- Then it would generate two 'ThetaOrigin's, one for each method: -- -- @ -- [ ThetaOrigin { to_tvs = [b] -- , to_givens = [] -- , to_wanted_origins = [Show a, Ix b] } -- , ThetaOrigin { to_tvs = [] -- , to_givens = [Eq a] -- , to_wanted_origins = [Ord a] } -- ] -- @ data ThetaOrigin = ThetaOrigin { to_tvs :: [TyVar] , to_givens :: ThetaType , to_wanted_origins :: [PredOrigin] } instance Outputable PredOrigin where ppr (PredOrigin ty _ _) = ppr ty -- The origin is not so interesting when debugging instance Outputable ThetaOrigin where ppr (ThetaOrigin { to_tvs = tvs , to_givens = givens , to_wanted_origins = wanted_origins }) = hang (text "ThetaOrigin") 2 (vcat [ text "to_tvs =" <+> ppr tvs , text "to_givens =" <+> ppr givens , text "to_wanted_origins =" <+> ppr wanted_origins ]) mkPredOrigin :: CtOrigin -> TypeOrKind -> PredType -> PredOrigin mkPredOrigin origin t_or_k pred = PredOrigin pred origin t_or_k mkThetaOrigin :: CtOrigin -> TypeOrKind -> [TyVar] -> ThetaType -> ThetaType -> ThetaOrigin mkThetaOrigin origin t_or_k tvs givens = ThetaOrigin tvs givens . map (mkPredOrigin origin t_or_k) -- A common case where the ThetaOrigin only contains wanted constraints, with -- no givens or locally scoped type variables. mkThetaOriginFromPreds :: [PredOrigin] -> ThetaOrigin mkThetaOriginFromPreds = ThetaOrigin [] [] substPredOrigin :: HasCallStack => TCvSubst -> PredOrigin -> PredOrigin substPredOrigin subst (PredOrigin pred origin t_or_k) = PredOrigin (substTy subst pred) origin t_or_k {- ************************************************************************ * * Class deriving diagnostics * * ************************************************************************ Only certain blessed classes can be used in a deriving clause (without the assistance of GeneralizedNewtypeDeriving or DeriveAnyClass). These classes are listed below in the definition of hasStockDeriving. The sideConditions function determines the criteria that needs to be met in order for a particular class to be able to be derived successfully. A class might be able to be used in a deriving clause if -XDeriveAnyClass is willing to support it. The canDeriveAnyClass function checks if this is the case. -} hasStockDeriving :: Class -> Maybe (SrcSpan -> TyCon -> [Type] -> TcM (LHsBinds GhcPs, BagDerivStuff, [Name])) hasStockDeriving clas = assocMaybe gen_list (getUnique clas) where gen_list :: [(Unique, SrcSpan -> TyCon -> [Type] -> TcM (LHsBinds GhcPs, BagDerivStuff, [Name]))] gen_list = [ (eqClassKey, simpleM gen_Eq_binds) , (ordClassKey, simpleM gen_Ord_binds) , (enumClassKey, simpleM gen_Enum_binds) , (boundedClassKey, simple gen_Bounded_binds) , (ixClassKey, simpleM gen_Ix_binds) , (showClassKey, read_or_show gen_Show_binds) , (readClassKey, read_or_show gen_Read_binds) , (dataClassKey, simpleM gen_Data_binds) , (functorClassKey, simple gen_Functor_binds) , (foldableClassKey, simple gen_Foldable_binds) , (traversableClassKey, simple gen_Traversable_binds) , (liftClassKey, simple gen_Lift_binds) , (genClassKey, generic (gen_Generic_binds Gen0)) , (gen1ClassKey, generic (gen_Generic_binds Gen1)) ] simple gen_fn loc tc _ = let (binds, deriv_stuff) = gen_fn loc tc in return (binds, deriv_stuff, []) simpleM gen_fn loc tc _ = do { (binds, deriv_stuff) <- gen_fn loc tc ; return (binds, deriv_stuff, []) } read_or_show gen_fn loc tc _ = do { fix_env <- getDataConFixityFun tc ; let (binds, deriv_stuff) = gen_fn fix_env loc tc field_names = all_field_names tc ; return (binds, deriv_stuff, field_names) } generic gen_fn _ tc inst_tys = do { (binds, faminst) <- gen_fn tc inst_tys ; let field_names = all_field_names tc ; return (binds, unitBag (DerivFamInst faminst), field_names) } -- See Note [Deriving and unused record selectors] all_field_names = map flSelector . concatMap dataConFieldLabels . tyConDataCons {- Note [Deriving and unused record selectors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this (see Trac #13919): module Main (main) where data Foo = MkFoo {bar :: String} deriving Show main :: IO () main = print (Foo "hello") Strictly speaking, the record selector `bar` is unused in this module, since neither `main` nor the derived `Show` instance for `Foo` mention `bar`. However, the behavior of `main` is affected by the presence of `bar`, since it will print different output depending on whether `MkFoo` is defined using record selectors or not. Therefore, we do not to issue a "Defined but not used: ‘bar’" warning for this module, since removing `bar` changes the program's behavior. This is the reason behind the [Name] part of the return type of `hasStockDeriving`—it tracks all of the record selector `Name`s for which -Wunused-binds should be suppressed. Currently, the only three stock derived classes that require this are Read, Show, and Generic, as their derived code all depend on the record selectors of the derived data type's constructors. See also Note [Newtype deriving and unused constructors] in TcDeriv for another example of a similar trick. -} getDataConFixityFun :: TyCon -> TcM (Name -> Fixity) -- If the TyCon is locally defined, we want the local fixity env; -- but if it is imported (which happens for standalone deriving) -- we need to get the fixity env from the interface file -- c.f. RnEnv.lookupFixity, and Trac #9830 getDataConFixityFun tc = do { this_mod <- getModule ; if nameIsLocalOrFrom this_mod name then do { fix_env <- getFixityEnv ; return (lookupFixity fix_env) } else do { iface <- loadInterfaceForName doc name -- Should already be loaded! ; return (mi_fix iface . nameOccName) } } where name = tyConName tc doc = text "Data con fixities for" <+> ppr name ------------------------------------------------------------------ -- Check side conditions that dis-allow derivability for particular classes -- This is *apart* from the newtype-deriving mechanism -- -- Here we get the representation tycon in case of family instances as it has -- the data constructors - but we need to be careful to fall back to the -- family tycon (with indexes) in error messages. checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -- tycon -> DerivStatus checkSideConditions dflags mtheta cls cls_tys rep_tc | Just cond <- sideConditions mtheta cls = case (cond dflags rep_tc) of NotValid err -> DerivableClassError err -- Class-specific error IsValid | null (filterOutInvisibleTypes (classTyCon cls) cls_tys) -> CanDerive -- All stock derivable classes are unary in the sense that -- there should be not types in cls_tys (i.e., no type args -- other than last). Note that cls_types can contain -- invisible types as well (e.g., for Generic1, which is -- poly-kinded), so make sure those are not counted. | otherwise -> DerivableClassError (classArgsErr cls cls_tys) -- e.g. deriving( Eq s ) | NotValid err <- canDeriveAnyClass dflags = NonDerivableClass err -- DeriveAnyClass does not work | otherwise = DerivableViaInstance -- DeriveAnyClass should work classArgsErr :: Class -> [Type] -> SDoc classArgsErr cls cls_tys = quotes (ppr (mkClassPred cls cls_tys)) <+> text "is not a class" -- Side conditions (whether the datatype must have at least one constructor, -- required language extensions, etc.) for using GHC's stock deriving -- mechanism on certain classes (as opposed to classes that require -- GeneralizedNewtypeDeriving or DeriveAnyClass). Returns Nothing for a -- class for which stock deriving isn't possible. sideConditions :: DerivContext -> Class -> Maybe Condition sideConditions mtheta cls | cls_key == eqClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == ordClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == showClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == readClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration) | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct cls) | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct cls) | cls_key == dataClassKey = Just (checkFlag LangExt.DeriveDataTypeable `andCond` cond_vanilla `andCond` cond_args cls) | cls_key == functorClassKey = Just (checkFlag LangExt.DeriveFunctor `andCond` cond_vanilla `andCond` cond_functorOK True False) | cls_key == foldableClassKey = Just (checkFlag LangExt.DeriveFoldable `andCond` cond_vanilla `andCond` cond_functorOK False True) -- Functor/Fold/Trav works ok -- for rank-n types | cls_key == traversableClassKey = Just (checkFlag LangExt.DeriveTraversable `andCond` cond_vanilla `andCond` cond_functorOK False False) | cls_key == genClassKey = Just (checkFlag LangExt.DeriveGeneric `andCond` cond_vanilla `andCond` cond_RepresentableOk) | cls_key == gen1ClassKey = Just (checkFlag LangExt.DeriveGeneric `andCond` cond_vanilla `andCond` cond_Representable1Ok) | cls_key == liftClassKey = Just (checkFlag LangExt.DeriveLift `andCond` cond_vanilla `andCond` cond_args cls) | otherwise = Nothing where cls_key = getUnique cls cond_std = cond_stdOK mtheta False -- Vanilla data constructors, at least one, -- and monotype arguments cond_vanilla = cond_stdOK mtheta True -- Vanilla data constructors but -- allow no data cons or polytype arguments canDeriveAnyClass :: DynFlags -> Validity -- IsValid: we can (try to) derive it via an empty instance declaration -- NotValid s: we can't, reason s canDeriveAnyClass dflags | not (xopt LangExt.DeriveAnyClass dflags) = NotValid (text "Try enabling DeriveAnyClass") | otherwise = IsValid -- OK! type Condition = DynFlags -> TyCon -> Validity -- TyCon is the *representation* tycon if the data type is an indexed one -- Nothing => OK orCond :: Condition -> Condition -> Condition orCond c1 c2 dflags tc = case (c1 dflags tc, c2 dflags tc) of (IsValid, _) -> IsValid -- c1 succeeds (_, IsValid) -> IsValid -- c21 succeeds (NotValid x, NotValid y) -> NotValid (x $$ text " or" $$ y) -- Both fail andCond :: Condition -> Condition -> Condition andCond c1 c2 dflags tc = c1 dflags tc `andValid` c2 dflags tc cond_stdOK :: DerivContext -- Says whether this is standalone deriving or not; -- if standalone, we just say "yes, go for it" -> Bool -- True <=> permissive: allow higher rank -- args and no data constructors -> Condition cond_stdOK (Just _) _ _ _ = IsValid -- Don't check these conservative conditions for -- standalone deriving; just generate the code -- and let the typechecker handle the result cond_stdOK Nothing permissive dflags rep_tc | null data_cons , not permissive = checkFlag LangExt.EmptyDataDeriving dflags rep_tc `orValid` NotValid (no_cons_why rep_tc $$ empty_data_suggestion) | not (null con_whys) = NotValid (vcat con_whys $$ standalone_suggestion) | otherwise = IsValid where empty_data_suggestion = text "Use EmptyDataDeriving to enable deriving for empty data types" standalone_suggestion = text "Possible fix: use a standalone deriving declaration instead" data_cons = tyConDataCons rep_tc con_whys = getInvalids (map check_con data_cons) check_con :: DataCon -> Validity check_con con | not (null eq_spec) = bad "is a GADT" | not (null ex_tvs) = bad "has existential type variables in its type" | not (null theta) = bad "has constraints in its type" | not (permissive || all isTauTy (dataConOrigArgTys con)) = bad "has a higher-rank type" | otherwise = IsValid where (_, ex_tvs, eq_spec, theta, _, _) = dataConFullSig con bad msg = NotValid (badCon con (text msg)) no_cons_why :: TyCon -> SDoc no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+> text "must have at least one data constructor" cond_RepresentableOk :: Condition cond_RepresentableOk _ tc = canDoGenerics tc cond_Representable1Ok :: Condition cond_Representable1Ok _ tc = canDoGenerics1 tc cond_enumOrProduct :: Class -> Condition cond_enumOrProduct cls = cond_isEnumeration `orCond` (cond_isProduct `andCond` cond_args cls) cond_args :: Class -> Condition -- For some classes (eg Eq, Ord) we allow unlifted arg types -- by generating specialised code. For others (eg Data) we don't. cond_args cls _ tc = case bad_args of [] -> IsValid (ty:_) -> NotValid (hang (text "Don't know how to derive" <+> quotes (ppr cls)) 2 (text "for type" <+> quotes (ppr ty))) where bad_args = [ arg_ty | con <- tyConDataCons tc , arg_ty <- dataConOrigArgTys con , isUnliftedType arg_ty , not (ok_ty arg_ty) ] cls_key = classKey cls ok_ty arg_ty | cls_key == eqClassKey = check_in arg_ty ordOpTbl | cls_key == ordClassKey = check_in arg_ty ordOpTbl | cls_key == showClassKey = check_in arg_ty boxConTbl | cls_key == liftClassKey = check_in arg_ty litConTbl | otherwise = False -- Read, Ix etc check_in :: Type -> [(Type,a)] -> Bool check_in arg_ty tbl = any (eqType arg_ty . fst) tbl cond_isEnumeration :: Condition cond_isEnumeration _ rep_tc | isEnumerationTyCon rep_tc = IsValid | otherwise = NotValid why where why = sep [ quotes (pprSourceTyCon rep_tc) <+> text "must be an enumeration type" , text "(an enumeration consists of one or more nullary, non-GADT constructors)" ] -- See Note [Enumeration types] in TyCon cond_isProduct :: Condition cond_isProduct _ rep_tc | isProductTyCon rep_tc = IsValid | otherwise = NotValid why where why = quotes (pprSourceTyCon rep_tc) <+> text "must have precisely one constructor" cond_functorOK :: Bool -> Bool -> Condition -- OK for Functor/Foldable/Traversable class -- Currently: (a) at least one argument -- (b) don't use argument contravariantly -- (c) don't use argument in the wrong place, e.g. data T a = T (X a a) -- (d) optionally: don't use function types -- (e) no "stupid context" on data type cond_functorOK allowFunctions allowExQuantifiedLastTyVar _ rep_tc | null tc_tvs = NotValid (text "Data type" <+> quotes (ppr rep_tc) <+> text "must have some type parameters") | not (null bad_stupid_theta) = NotValid (text "Data type" <+> quotes (ppr rep_tc) <+> text "must not have a class context:" <+> pprTheta bad_stupid_theta) | otherwise = allValid (map check_con data_cons) where tc_tvs = tyConTyVars rep_tc Just (_, last_tv) = snocView tc_tvs bad_stupid_theta = filter is_bad (tyConStupidTheta rep_tc) is_bad pred = last_tv `elemVarSet` exactTyCoVarsOfType pred -- See Note [Check that the type variable is truly universal] data_cons = tyConDataCons rep_tc check_con con = allValid (check_universal con : foldDataConArgs (ft_check con) con) check_universal :: DataCon -> Validity check_universal con | allowExQuantifiedLastTyVar = IsValid -- See Note [DeriveFoldable with ExistentialQuantification] -- in TcGenFunctor | Just tv <- getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con))) , tv `elem` dataConUnivTyVars con , not (tv `elemVarSet` exactTyCoVarsOfTypes (dataConTheta con)) = IsValid -- See Note [Check that the type variable is truly universal] | otherwise = NotValid (badCon con existential) ft_check :: DataCon -> FFoldType Validity ft_check con = FT { ft_triv = IsValid, ft_var = IsValid , ft_co_var = NotValid (badCon con covariant) , ft_fun = \x y -> if allowFunctions then x `andValid` y else NotValid (badCon con functions) , ft_tup = \_ xs -> allValid xs , ft_ty_app = \_ x -> x , ft_bad_app = NotValid (badCon con wrong_arg) , ft_forall = \_ x -> x } existential = text "must be truly polymorphic in the last argument of the data type" covariant = text "must not use the type variable in a function argument" functions = text "must not contain function types" wrong_arg = text "must use the type variable only as the last argument of a data type" checkFlag :: LangExt.Extension -> Condition checkFlag flag dflags _ | xopt flag dflags = IsValid | otherwise = NotValid why where why = text "You need " <> text flag_str <+> text "to derive an instance for this class" flag_str = case [ flagSpecName f | f <- xFlags , flagSpecFlag f == flag ] of [s] -> s other -> pprPanic "checkFlag" (ppr other) std_class_via_coercible :: Class -> Bool -- These standard classes can be derived for a newtype -- using the coercible trick *even if no -XGeneralizedNewtypeDeriving -- because giving so gives the same results as generating the boilerplate std_class_via_coercible clas = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey] -- Not Read/Show because they respect the type -- Not Enum, because newtypes are never in Enum non_coercible_class :: Class -> Bool -- *Never* derive Read, Show, Typeable, Data, Generic, Generic1, Lift -- by Coercible, even with -XGeneralizedNewtypeDeriving -- Also, avoid Traversable, as the Coercible-derived instance and the "normal"-derived -- instance behave differently if there's a non-lawful Applicative out there. -- Besides, with roles, Coercible-deriving Traversable is ill-roled. non_coercible_class cls = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey , genClassKey, gen1ClassKey, typeableClassKey , traversableClassKey, liftClassKey ]) badCon :: DataCon -> SDoc -> SDoc badCon con msg = text "Constructor" <+> quotes (ppr con) <+> msg ------------------------------------------------------------------ newDerivClsInst :: ThetaType -> DerivSpec theta -> TcM ClsInst newDerivClsInst theta (DS { ds_name = dfun_name, ds_overlap = overlap_mode , ds_tvs = tvs, ds_cls = clas, ds_tys = tys }) = newClsInst overlap_mode dfun_name tvs theta clas tys extendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a -- Add new locally-defined instances; don't bother to check -- for functional dependency errors -- that'll happen in TcInstDcls extendLocalInstEnv dfuns thing_inside = do { env <- getGblEnv ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns env' = env { tcg_inst_env = inst_env' } ; setGblEnv env' thing_inside } {- Note [Deriving any class] ~~~~~~~~~~~~~~~~~~~~~~~~~ Classic uses of a deriving clause, or a standalone-deriving declaration, are for: * a stock class like Eq or Show, for which GHC knows how to generate the instance code * a newtype, via the mechanism enabled by GeneralizedNewtypeDeriving The DeriveAnyClass extension adds a third way to derive instances, based on empty instance declarations. The canonical use case is in combination with GHC.Generics and default method signatures. These allow us to have instance declarations being empty, but still useful, e.g. data T a = ...blah..blah... deriving( Generic ) instance C a => C (T a) -- No 'where' clause where C is some "random" user-defined class. This boilerplate code can be replaced by the more compact data T a = ...blah..blah... deriving( Generic, C ) if DeriveAnyClass is enabled. This is not restricted to Generics; any class can be derived, simply giving rise to an empty instance. Unfortunately, it is not clear how to determine the context (when using a deriving clause; in standalone deriving, the user provides the context). GHC uses the same heuristic for figuring out the class context that it uses for Eq in the case of *-kinded classes, and for Functor in the case of * -> *-kinded classes. That may not be optimal or even wrong. But in such cases, standalone deriving can still be used. Note [Check that the type variable is truly universal] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For Functor and Traversable instances, we must check that the *last argument* of the type constructor is used truly universally quantified. Example data T a b where T1 :: a -> b -> T a b -- Fine! Vanilla H-98 T2 :: b -> c -> T a b -- Fine! Existential c, but we can still map over 'b' T3 :: b -> T Int b -- Fine! Constraint 'a', but 'b' is still polymorphic T4 :: Ord b => b -> T a b -- No! 'b' is constrained T5 :: b -> T b b -- No! 'b' is constrained T6 :: T a (b,b) -- No! 'b' is constrained Notice that only the first of these constructors is vanilla H-98. We only need to take care about the last argument (b in this case). See Trac #8678. Eg. for T1-T3 we can write fmap f (T1 a b) = T1 a (f b) fmap f (T2 b c) = T2 (f b) c fmap f (T3 x) = T3 (f x) We need not perform these checks for Foldable instances, however, since functions in Foldable can only consume existentially quantified type variables, rather than produce them (as is the case in Functor and Traversable functions.) As a result, T can have a derived Foldable instance: foldr f z (T1 a b) = f b z foldr f z (T2 b c) = f b z foldr f z (T3 x) = f x z foldr f z (T4 x) = f x z foldr f z (T5 x) = f x z foldr _ z T6 = z See Note [DeriveFoldable with ExistentialQuantification] in TcGenFunctor. For Functor and Traversable, we must take care not to let type synonyms unfairly reject a type for not being truly universally quantified. An example of this is: type C (a :: Constraint) b = a data T a b = C (Show a) b => MkT b Here, the existential context (C (Show a) b) does technically mention the last type variable b. But this is OK, because expanding the type synonym C would give us the context (Show a), which doesn't mention b. Therefore, we must make sure to expand type synonyms before performing this check. Not doing so led to Trac #13813. -}
ezyang/ghc
compiler/typecheck/TcDerivUtils.hs
bsd-3-clause
34,510
0
17
10,018
5,100
2,745
2,355
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.Compatibility44 -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.Compatibility44 ( -- * Types GLDEBUGPROC, GLDEBUGPROCFunc, GLbitfield, GLboolean, GLbyte, GLchar, GLclampd, GLclampf, GLdouble, GLenum, GLfloat, GLhalf, GLint, GLint64, GLintptr, GLshort, GLsizei, GLsizeiptr, GLsync, GLubyte, GLuint, GLuint64, GLushort, GLvoid, makeGLDEBUGPROC, -- * Enums gl_2D, gl_2_BYTES, gl_3D, gl_3D_COLOR, gl_3D_COLOR_TEXTURE, gl_3_BYTES, gl_4D_COLOR_TEXTURE, gl_4_BYTES, gl_ACCUM, gl_ACCUM_ALPHA_BITS, gl_ACCUM_BLUE_BITS, gl_ACCUM_BUFFER_BIT, gl_ACCUM_CLEAR_VALUE, gl_ACCUM_GREEN_BITS, gl_ACCUM_RED_BITS, gl_ACTIVE_ATOMIC_COUNTER_BUFFERS, gl_ACTIVE_ATTRIBUTES, gl_ACTIVE_ATTRIBUTE_MAX_LENGTH, gl_ACTIVE_PROGRAM, gl_ACTIVE_RESOURCES, gl_ACTIVE_SUBROUTINES, gl_ACTIVE_SUBROUTINE_MAX_LENGTH, gl_ACTIVE_SUBROUTINE_UNIFORMS, gl_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS, gl_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH, gl_ACTIVE_TEXTURE, gl_ACTIVE_UNIFORMS, gl_ACTIVE_UNIFORM_BLOCKS, gl_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH, gl_ACTIVE_UNIFORM_MAX_LENGTH, gl_ACTIVE_VARIABLES, gl_ADD, gl_ADD_SIGNED, gl_ALIASED_LINE_WIDTH_RANGE, gl_ALIASED_POINT_SIZE_RANGE, gl_ALL_ATTRIB_BITS, gl_ALL_BARRIER_BITS, gl_ALL_SHADER_BITS, gl_ALPHA, gl_ALPHA12, gl_ALPHA16, gl_ALPHA4, gl_ALPHA8, gl_ALPHA_BIAS, gl_ALPHA_BITS, gl_ALPHA_INTEGER, gl_ALPHA_SCALE, gl_ALPHA_TEST, gl_ALPHA_TEST_FUNC, gl_ALPHA_TEST_REF, gl_ALREADY_SIGNALED, gl_ALWAYS, gl_AMBIENT, gl_AMBIENT_AND_DIFFUSE, gl_AND, gl_AND_INVERTED, gl_AND_REVERSE, gl_ANY_SAMPLES_PASSED, gl_ANY_SAMPLES_PASSED_CONSERVATIVE, gl_ARRAY_BUFFER, gl_ARRAY_BUFFER_BINDING, gl_ARRAY_SIZE, gl_ARRAY_STRIDE, gl_ATOMIC_COUNTER_BARRIER_BIT, gl_ATOMIC_COUNTER_BUFFER, gl_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS, gl_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES, gl_ATOMIC_COUNTER_BUFFER_BINDING, gl_ATOMIC_COUNTER_BUFFER_DATA_SIZE, gl_ATOMIC_COUNTER_BUFFER_INDEX, gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER, gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER, gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER, gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER, gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER, gl_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER, gl_ATOMIC_COUNTER_BUFFER_SIZE, gl_ATOMIC_COUNTER_BUFFER_START, gl_ATTACHED_SHADERS, gl_ATTRIB_STACK_DEPTH, gl_AUTO_GENERATE_MIPMAP, gl_AUTO_NORMAL, gl_AUX0, gl_AUX1, gl_AUX2, gl_AUX3, gl_AUX_BUFFERS, gl_BACK, gl_BACK_LEFT, gl_BACK_RIGHT, gl_BGR, gl_BGRA, gl_BGRA_INTEGER, gl_BGR_INTEGER, gl_BITMAP, gl_BITMAP_TOKEN, gl_BLEND, gl_BLEND_DST, gl_BLEND_DST_ALPHA, gl_BLEND_DST_RGB, gl_BLEND_EQUATION_ALPHA, gl_BLEND_EQUATION_RGB, gl_BLEND_SRC, gl_BLEND_SRC_ALPHA, gl_BLEND_SRC_RGB, gl_BLOCK_INDEX, gl_BLUE, gl_BLUE_BIAS, gl_BLUE_BITS, gl_BLUE_INTEGER, gl_BLUE_SCALE, gl_BOOL, gl_BOOL_VEC2, gl_BOOL_VEC3, gl_BOOL_VEC4, gl_BUFFER, gl_BUFFER_ACCESS, gl_BUFFER_ACCESS_FLAGS, gl_BUFFER_BINDING, gl_BUFFER_DATA_SIZE, gl_BUFFER_IMMUTABLE_STORAGE, gl_BUFFER_MAPPED, gl_BUFFER_MAP_LENGTH, gl_BUFFER_MAP_OFFSET, gl_BUFFER_MAP_POINTER, gl_BUFFER_SIZE, gl_BUFFER_STORAGE_FLAGS, gl_BUFFER_UPDATE_BARRIER_BIT, gl_BUFFER_USAGE, gl_BUFFER_VARIABLE, gl_BYTE, gl_C3F_V3F, gl_C4F_N3F_V3F, gl_C4UB_V2F, gl_C4UB_V3F, gl_CAVEAT_SUPPORT, gl_CCW, gl_CLAMP, gl_CLAMP_FRAGMENT_COLOR, gl_CLAMP_READ_COLOR, gl_CLAMP_TO_BORDER, gl_CLAMP_TO_EDGE, gl_CLAMP_VERTEX_COLOR, gl_CLEAR, gl_CLEAR_BUFFER, gl_CLEAR_TEXTURE, gl_CLIENT_ACTIVE_TEXTURE, gl_CLIENT_ALL_ATTRIB_BITS, gl_CLIENT_ATTRIB_STACK_DEPTH, gl_CLIENT_MAPPED_BUFFER_BARRIER_BIT, gl_CLIENT_PIXEL_STORE_BIT, gl_CLIENT_STORAGE_BIT, gl_CLIENT_VERTEX_ARRAY_BIT, gl_CLIP_DISTANCE0, gl_CLIP_DISTANCE1, gl_CLIP_DISTANCE2, gl_CLIP_DISTANCE3, gl_CLIP_DISTANCE4, gl_CLIP_DISTANCE5, gl_CLIP_DISTANCE6, gl_CLIP_DISTANCE7, gl_CLIP_PLANE0, gl_CLIP_PLANE1, gl_CLIP_PLANE2, gl_CLIP_PLANE3, gl_CLIP_PLANE4, gl_CLIP_PLANE5, gl_COEFF, gl_COLOR, gl_COLOR_ARRAY, gl_COLOR_ARRAY_BUFFER_BINDING, gl_COLOR_ARRAY_POINTER, gl_COLOR_ARRAY_SIZE, gl_COLOR_ARRAY_STRIDE, gl_COLOR_ARRAY_TYPE, gl_COLOR_ATTACHMENT0, gl_COLOR_ATTACHMENT1, gl_COLOR_ATTACHMENT10, gl_COLOR_ATTACHMENT11, gl_COLOR_ATTACHMENT12, gl_COLOR_ATTACHMENT13, gl_COLOR_ATTACHMENT14, gl_COLOR_ATTACHMENT15, gl_COLOR_ATTACHMENT2, gl_COLOR_ATTACHMENT3, gl_COLOR_ATTACHMENT4, gl_COLOR_ATTACHMENT5, gl_COLOR_ATTACHMENT6, gl_COLOR_ATTACHMENT7, gl_COLOR_ATTACHMENT8, gl_COLOR_ATTACHMENT9, gl_COLOR_BUFFER_BIT, gl_COLOR_CLEAR_VALUE, gl_COLOR_COMPONENTS, gl_COLOR_ENCODING, gl_COLOR_INDEX, gl_COLOR_INDEXES, gl_COLOR_LOGIC_OP, gl_COLOR_MATERIAL, gl_COLOR_MATERIAL_FACE, gl_COLOR_MATERIAL_PARAMETER, gl_COLOR_RENDERABLE, gl_COLOR_SUM, gl_COLOR_WRITEMASK, gl_COMBINE, gl_COMBINE_ALPHA, gl_COMBINE_RGB, gl_COMMAND_BARRIER_BIT, gl_COMPARE_REF_TO_TEXTURE, gl_COMPARE_R_TO_TEXTURE, gl_COMPATIBLE_SUBROUTINES, gl_COMPILE, gl_COMPILE_AND_EXECUTE, gl_COMPILE_STATUS, gl_COMPRESSED_ALPHA, gl_COMPRESSED_INTENSITY, gl_COMPRESSED_LUMINANCE, gl_COMPRESSED_LUMINANCE_ALPHA, gl_COMPRESSED_R11_EAC, gl_COMPRESSED_RED, gl_COMPRESSED_RED_RGTC1, gl_COMPRESSED_RG, gl_COMPRESSED_RG11_EAC, gl_COMPRESSED_RGB, gl_COMPRESSED_RGB8_ETC2, gl_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, gl_COMPRESSED_RGBA, gl_COMPRESSED_RGBA8_ETC2_EAC, gl_COMPRESSED_RGBA_BPTC_UNORM, gl_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, gl_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, gl_COMPRESSED_RG_RGTC2, gl_COMPRESSED_SIGNED_R11_EAC, gl_COMPRESSED_SIGNED_RED_RGTC1, gl_COMPRESSED_SIGNED_RG11_EAC, gl_COMPRESSED_SIGNED_RG_RGTC2, gl_COMPRESSED_SLUMINANCE, gl_COMPRESSED_SLUMINANCE_ALPHA, gl_COMPRESSED_SRGB, gl_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, gl_COMPRESSED_SRGB8_ETC2, gl_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, gl_COMPRESSED_SRGB_ALPHA, gl_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, gl_COMPRESSED_TEXTURE_FORMATS, gl_COMPUTE_SHADER, gl_COMPUTE_SHADER_BIT, gl_COMPUTE_SUBROUTINE, gl_COMPUTE_SUBROUTINE_UNIFORM, gl_COMPUTE_TEXTURE, gl_COMPUTE_WORK_GROUP_SIZE, gl_CONDITION_SATISFIED, gl_CONSTANT, gl_CONSTANT_ALPHA, gl_CONSTANT_ATTENUATION, gl_CONSTANT_COLOR, gl_CONTEXT_COMPATIBILITY_PROFILE_BIT, gl_CONTEXT_CORE_PROFILE_BIT, gl_CONTEXT_FLAGS, gl_CONTEXT_FLAG_DEBUG_BIT, gl_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT, gl_CONTEXT_PROFILE_MASK, gl_COORD_REPLACE, gl_COPY, gl_COPY_INVERTED, gl_COPY_PIXEL_TOKEN, gl_COPY_READ_BUFFER, gl_COPY_READ_BUFFER_BINDING, gl_COPY_WRITE_BUFFER, gl_COPY_WRITE_BUFFER_BINDING, gl_CULL_FACE, gl_CULL_FACE_MODE, gl_CURRENT_BIT, gl_CURRENT_COLOR, gl_CURRENT_FOG_COORD, gl_CURRENT_FOG_COORDINATE, gl_CURRENT_INDEX, gl_CURRENT_NORMAL, gl_CURRENT_PROGRAM, gl_CURRENT_QUERY, gl_CURRENT_RASTER_COLOR, gl_CURRENT_RASTER_DISTANCE, gl_CURRENT_RASTER_INDEX, gl_CURRENT_RASTER_POSITION, gl_CURRENT_RASTER_POSITION_VALID, gl_CURRENT_RASTER_SECONDARY_COLOR, gl_CURRENT_RASTER_TEXTURE_COORDS, gl_CURRENT_SECONDARY_COLOR, gl_CURRENT_TEXTURE_COORDS, gl_CURRENT_VERTEX_ATTRIB, gl_CW, gl_DEBUG_CALLBACK_FUNCTION, gl_DEBUG_CALLBACK_USER_PARAM, gl_DEBUG_GROUP_STACK_DEPTH, gl_DEBUG_LOGGED_MESSAGES, gl_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH, gl_DEBUG_OUTPUT, gl_DEBUG_OUTPUT_SYNCHRONOUS, gl_DEBUG_SEVERITY_HIGH, gl_DEBUG_SEVERITY_LOW, gl_DEBUG_SEVERITY_MEDIUM, gl_DEBUG_SEVERITY_NOTIFICATION, gl_DEBUG_SOURCE_API, gl_DEBUG_SOURCE_APPLICATION, gl_DEBUG_SOURCE_OTHER, gl_DEBUG_SOURCE_SHADER_COMPILER, gl_DEBUG_SOURCE_THIRD_PARTY, gl_DEBUG_SOURCE_WINDOW_SYSTEM, gl_DEBUG_TYPE_DEPRECATED_BEHAVIOR, gl_DEBUG_TYPE_ERROR, gl_DEBUG_TYPE_MARKER, gl_DEBUG_TYPE_OTHER, gl_DEBUG_TYPE_PERFORMANCE, gl_DEBUG_TYPE_POP_GROUP, gl_DEBUG_TYPE_PORTABILITY, gl_DEBUG_TYPE_PUSH_GROUP, gl_DEBUG_TYPE_UNDEFINED_BEHAVIOR, gl_DECAL, gl_DECR, gl_DECR_WRAP, gl_DELETE_STATUS, gl_DEPTH, gl_DEPTH24_STENCIL8, gl_DEPTH32F_STENCIL8, gl_DEPTH_ATTACHMENT, gl_DEPTH_BIAS, gl_DEPTH_BITS, gl_DEPTH_BUFFER_BIT, gl_DEPTH_CLAMP, gl_DEPTH_CLEAR_VALUE, gl_DEPTH_COMPONENT, gl_DEPTH_COMPONENT16, gl_DEPTH_COMPONENT24, gl_DEPTH_COMPONENT32, gl_DEPTH_COMPONENT32F, gl_DEPTH_COMPONENTS, gl_DEPTH_FUNC, gl_DEPTH_RANGE, gl_DEPTH_RENDERABLE, gl_DEPTH_SCALE, gl_DEPTH_STENCIL, gl_DEPTH_STENCIL_ATTACHMENT, gl_DEPTH_STENCIL_TEXTURE_MODE, gl_DEPTH_TEST, gl_DEPTH_TEXTURE_MODE, gl_DEPTH_WRITEMASK, gl_DIFFUSE, gl_DISPATCH_INDIRECT_BUFFER, gl_DISPATCH_INDIRECT_BUFFER_BINDING, gl_DISPLAY_LIST, gl_DITHER, gl_DOMAIN, gl_DONT_CARE, gl_DOT3_RGB, gl_DOT3_RGBA, gl_DOUBLE, gl_DOUBLEBUFFER, gl_DOUBLE_MAT2, gl_DOUBLE_MAT2x3, gl_DOUBLE_MAT2x4, gl_DOUBLE_MAT3, gl_DOUBLE_MAT3x2, gl_DOUBLE_MAT3x4, gl_DOUBLE_MAT4, gl_DOUBLE_MAT4x2, gl_DOUBLE_MAT4x3, gl_DOUBLE_VEC2, gl_DOUBLE_VEC3, gl_DOUBLE_VEC4, gl_DRAW_BUFFER, gl_DRAW_BUFFER0, gl_DRAW_BUFFER1, gl_DRAW_BUFFER10, gl_DRAW_BUFFER11, gl_DRAW_BUFFER12, gl_DRAW_BUFFER13, gl_DRAW_BUFFER14, gl_DRAW_BUFFER15, gl_DRAW_BUFFER2, gl_DRAW_BUFFER3, gl_DRAW_BUFFER4, gl_DRAW_BUFFER5, gl_DRAW_BUFFER6, gl_DRAW_BUFFER7, gl_DRAW_BUFFER8, gl_DRAW_BUFFER9, gl_DRAW_FRAMEBUFFER, gl_DRAW_FRAMEBUFFER_BINDING, gl_DRAW_INDIRECT_BUFFER, gl_DRAW_INDIRECT_BUFFER_BINDING, gl_DRAW_PIXEL_TOKEN, gl_DST_ALPHA, gl_DST_COLOR, gl_DYNAMIC_COPY, gl_DYNAMIC_DRAW, gl_DYNAMIC_READ, gl_DYNAMIC_STORAGE_BIT, gl_EDGE_FLAG, gl_EDGE_FLAG_ARRAY, gl_EDGE_FLAG_ARRAY_BUFFER_BINDING, gl_EDGE_FLAG_ARRAY_POINTER, gl_EDGE_FLAG_ARRAY_STRIDE, gl_ELEMENT_ARRAY_BARRIER_BIT, gl_ELEMENT_ARRAY_BUFFER, gl_ELEMENT_ARRAY_BUFFER_BINDING, gl_EMISSION, gl_ENABLE_BIT, gl_EQUAL, gl_EQUIV, gl_EVAL_BIT, gl_EXP, gl_EXP2, gl_EXTENSIONS, gl_EYE_LINEAR, gl_EYE_PLANE, gl_FALSE, gl_FASTEST, gl_FEEDBACK, gl_FEEDBACK_BUFFER_POINTER, gl_FEEDBACK_BUFFER_SIZE, gl_FEEDBACK_BUFFER_TYPE, gl_FILL, gl_FILTER, gl_FIRST_VERTEX_CONVENTION, gl_FIXED, gl_FIXED_ONLY, gl_FLAT, gl_FLOAT, gl_FLOAT_32_UNSIGNED_INT_24_8_REV, gl_FLOAT_MAT2, gl_FLOAT_MAT2x3, gl_FLOAT_MAT2x4, gl_FLOAT_MAT3, gl_FLOAT_MAT3x2, gl_FLOAT_MAT3x4, gl_FLOAT_MAT4, gl_FLOAT_MAT4x2, gl_FLOAT_MAT4x3, gl_FLOAT_VEC2, gl_FLOAT_VEC3, gl_FLOAT_VEC4, gl_FOG, gl_FOG_BIT, gl_FOG_COLOR, gl_FOG_COORD, gl_FOG_COORDINATE, gl_FOG_COORDINATE_ARRAY, gl_FOG_COORDINATE_ARRAY_BUFFER_BINDING, gl_FOG_COORDINATE_ARRAY_POINTER, gl_FOG_COORDINATE_ARRAY_STRIDE, gl_FOG_COORDINATE_ARRAY_TYPE, gl_FOG_COORDINATE_SOURCE, gl_FOG_COORD_ARRAY, gl_FOG_COORD_ARRAY_BUFFER_BINDING, gl_FOG_COORD_ARRAY_POINTER, gl_FOG_COORD_ARRAY_STRIDE, gl_FOG_COORD_ARRAY_TYPE, gl_FOG_COORD_SRC, gl_FOG_DENSITY, gl_FOG_END, gl_FOG_HINT, gl_FOG_INDEX, gl_FOG_MODE, gl_FOG_START, gl_FRACTIONAL_EVEN, gl_FRACTIONAL_ODD, gl_FRAGMENT_DEPTH, gl_FRAGMENT_INTERPOLATION_OFFSET_BITS, gl_FRAGMENT_SHADER, gl_FRAGMENT_SHADER_BIT, gl_FRAGMENT_SHADER_DERIVATIVE_HINT, gl_FRAGMENT_SUBROUTINE, gl_FRAGMENT_SUBROUTINE_UNIFORM, gl_FRAGMENT_TEXTURE, gl_FRAMEBUFFER, gl_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, gl_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, gl_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, gl_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, gl_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, gl_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, gl_FRAMEBUFFER_ATTACHMENT_LAYERED, gl_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, gl_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, gl_FRAMEBUFFER_ATTACHMENT_RED_SIZE, gl_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, gl_FRAMEBUFFER_BARRIER_BIT, gl_FRAMEBUFFER_BINDING, gl_FRAMEBUFFER_BLEND, gl_FRAMEBUFFER_COMPLETE, gl_FRAMEBUFFER_DEFAULT, gl_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS, gl_FRAMEBUFFER_DEFAULT_HEIGHT, gl_FRAMEBUFFER_DEFAULT_LAYERS, gl_FRAMEBUFFER_DEFAULT_SAMPLES, gl_FRAMEBUFFER_DEFAULT_WIDTH, gl_FRAMEBUFFER_INCOMPLETE_ATTACHMENT, gl_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER, gl_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS, gl_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT, gl_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE, gl_FRAMEBUFFER_INCOMPLETE_READ_BUFFER, gl_FRAMEBUFFER_RENDERABLE, gl_FRAMEBUFFER_RENDERABLE_LAYERED, gl_FRAMEBUFFER_SRGB, gl_FRAMEBUFFER_UNDEFINED, gl_FRAMEBUFFER_UNSUPPORTED, gl_FRONT, gl_FRONT_AND_BACK, gl_FRONT_FACE, gl_FRONT_LEFT, gl_FRONT_RIGHT, gl_FULL_SUPPORT, gl_FUNC_ADD, gl_FUNC_REVERSE_SUBTRACT, gl_FUNC_SUBTRACT, gl_GENERATE_MIPMAP, gl_GENERATE_MIPMAP_HINT, gl_GEOMETRY_INPUT_TYPE, gl_GEOMETRY_OUTPUT_TYPE, gl_GEOMETRY_SHADER, gl_GEOMETRY_SHADER_BIT, gl_GEOMETRY_SHADER_INVOCATIONS, gl_GEOMETRY_SUBROUTINE, gl_GEOMETRY_SUBROUTINE_UNIFORM, gl_GEOMETRY_TEXTURE, gl_GEOMETRY_VERTICES_OUT, gl_GEQUAL, gl_GET_TEXTURE_IMAGE_FORMAT, gl_GET_TEXTURE_IMAGE_TYPE, gl_GREATER, gl_GREEN, gl_GREEN_BIAS, gl_GREEN_BITS, gl_GREEN_INTEGER, gl_GREEN_SCALE, gl_HALF_FLOAT, gl_HIGH_FLOAT, gl_HIGH_INT, gl_HINT_BIT, gl_IMAGE_1D, gl_IMAGE_1D_ARRAY, gl_IMAGE_2D, gl_IMAGE_2D_ARRAY, gl_IMAGE_2D_MULTISAMPLE, gl_IMAGE_2D_MULTISAMPLE_ARRAY, gl_IMAGE_2D_RECT, gl_IMAGE_3D, gl_IMAGE_BINDING_ACCESS, gl_IMAGE_BINDING_FORMAT, gl_IMAGE_BINDING_LAYER, gl_IMAGE_BINDING_LAYERED, gl_IMAGE_BINDING_LEVEL, gl_IMAGE_BINDING_NAME, gl_IMAGE_BUFFER, gl_IMAGE_CLASS_10_10_10_2, gl_IMAGE_CLASS_11_11_10, gl_IMAGE_CLASS_1_X_16, gl_IMAGE_CLASS_1_X_32, gl_IMAGE_CLASS_1_X_8, gl_IMAGE_CLASS_2_X_16, gl_IMAGE_CLASS_2_X_32, gl_IMAGE_CLASS_2_X_8, gl_IMAGE_CLASS_4_X_16, gl_IMAGE_CLASS_4_X_32, gl_IMAGE_CLASS_4_X_8, gl_IMAGE_COMPATIBILITY_CLASS, gl_IMAGE_CUBE, gl_IMAGE_CUBE_MAP_ARRAY, gl_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS, gl_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE, gl_IMAGE_FORMAT_COMPATIBILITY_TYPE, gl_IMAGE_PIXEL_FORMAT, gl_IMAGE_PIXEL_TYPE, gl_IMAGE_TEXEL_SIZE, gl_IMPLEMENTATION_COLOR_READ_FORMAT, gl_IMPLEMENTATION_COLOR_READ_TYPE, gl_INCR, gl_INCR_WRAP, gl_INDEX, gl_INDEX_ARRAY, gl_INDEX_ARRAY_BUFFER_BINDING, gl_INDEX_ARRAY_POINTER, gl_INDEX_ARRAY_STRIDE, gl_INDEX_ARRAY_TYPE, gl_INDEX_BITS, gl_INDEX_CLEAR_VALUE, gl_INDEX_LOGIC_OP, gl_INDEX_MODE, gl_INDEX_OFFSET, gl_INDEX_SHIFT, gl_INDEX_WRITEMASK, gl_INFO_LOG_LENGTH, gl_INT, gl_INTENSITY, gl_INTENSITY12, gl_INTENSITY16, gl_INTENSITY4, gl_INTENSITY8, gl_INTERLEAVED_ATTRIBS, gl_INTERNALFORMAT_ALPHA_SIZE, gl_INTERNALFORMAT_ALPHA_TYPE, gl_INTERNALFORMAT_BLUE_SIZE, gl_INTERNALFORMAT_BLUE_TYPE, gl_INTERNALFORMAT_DEPTH_SIZE, gl_INTERNALFORMAT_DEPTH_TYPE, gl_INTERNALFORMAT_GREEN_SIZE, gl_INTERNALFORMAT_GREEN_TYPE, gl_INTERNALFORMAT_PREFERRED, gl_INTERNALFORMAT_RED_SIZE, gl_INTERNALFORMAT_RED_TYPE, gl_INTERNALFORMAT_SHARED_SIZE, gl_INTERNALFORMAT_STENCIL_SIZE, gl_INTERNALFORMAT_STENCIL_TYPE, gl_INTERNALFORMAT_SUPPORTED, gl_INTERPOLATE, gl_INT_2_10_10_10_REV, gl_INT_IMAGE_1D, gl_INT_IMAGE_1D_ARRAY, gl_INT_IMAGE_2D, gl_INT_IMAGE_2D_ARRAY, gl_INT_IMAGE_2D_MULTISAMPLE, gl_INT_IMAGE_2D_MULTISAMPLE_ARRAY, gl_INT_IMAGE_2D_RECT, gl_INT_IMAGE_3D, gl_INT_IMAGE_BUFFER, gl_INT_IMAGE_CUBE, gl_INT_IMAGE_CUBE_MAP_ARRAY, gl_INT_SAMPLER_1D, gl_INT_SAMPLER_1D_ARRAY, gl_INT_SAMPLER_2D, gl_INT_SAMPLER_2D_ARRAY, gl_INT_SAMPLER_2D_MULTISAMPLE, gl_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, gl_INT_SAMPLER_2D_RECT, gl_INT_SAMPLER_3D, gl_INT_SAMPLER_BUFFER, gl_INT_SAMPLER_CUBE, gl_INT_SAMPLER_CUBE_MAP_ARRAY, gl_INT_VEC2, gl_INT_VEC3, gl_INT_VEC4, gl_INVALID_ENUM, gl_INVALID_FRAMEBUFFER_OPERATION, gl_INVALID_INDEX, gl_INVALID_OPERATION, gl_INVALID_VALUE, gl_INVERT, gl_ISOLINES, gl_IS_PER_PATCH, gl_IS_ROW_MAJOR, gl_KEEP, gl_LAST_VERTEX_CONVENTION, gl_LAYER_PROVOKING_VERTEX, gl_LEFT, gl_LEQUAL, gl_LESS, gl_LIGHT0, gl_LIGHT1, gl_LIGHT2, gl_LIGHT3, gl_LIGHT4, gl_LIGHT5, gl_LIGHT6, gl_LIGHT7, gl_LIGHTING, gl_LIGHTING_BIT, gl_LIGHT_MODEL_AMBIENT, gl_LIGHT_MODEL_COLOR_CONTROL, gl_LIGHT_MODEL_LOCAL_VIEWER, gl_LIGHT_MODEL_TWO_SIDE, gl_LINE, gl_LINEAR, gl_LINEAR_ATTENUATION, gl_LINEAR_MIPMAP_LINEAR, gl_LINEAR_MIPMAP_NEAREST, gl_LINES, gl_LINES_ADJACENCY, gl_LINE_BIT, gl_LINE_LOOP, gl_LINE_RESET_TOKEN, gl_LINE_SMOOTH, gl_LINE_SMOOTH_HINT, gl_LINE_STIPPLE, gl_LINE_STIPPLE_PATTERN, gl_LINE_STIPPLE_REPEAT, gl_LINE_STRIP, gl_LINE_STRIP_ADJACENCY, gl_LINE_TOKEN, gl_LINE_WIDTH, gl_LINE_WIDTH_GRANULARITY, gl_LINE_WIDTH_RANGE, gl_LINK_STATUS, gl_LIST_BASE, gl_LIST_BIT, gl_LIST_INDEX, gl_LIST_MODE, gl_LOAD, gl_LOCATION, gl_LOCATION_COMPONENT, gl_LOCATION_INDEX, gl_LOGIC_OP, gl_LOGIC_OP_MODE, gl_LOWER_LEFT, gl_LOW_FLOAT, gl_LOW_INT, gl_LUMINANCE, gl_LUMINANCE12, gl_LUMINANCE12_ALPHA12, gl_LUMINANCE12_ALPHA4, gl_LUMINANCE16, gl_LUMINANCE16_ALPHA16, gl_LUMINANCE4, gl_LUMINANCE4_ALPHA4, gl_LUMINANCE6_ALPHA2, gl_LUMINANCE8, gl_LUMINANCE8_ALPHA8, gl_LUMINANCE_ALPHA, gl_MAJOR_VERSION, gl_MANUAL_GENERATE_MIPMAP, gl_MAP1_COLOR_4, gl_MAP1_GRID_DOMAIN, gl_MAP1_GRID_SEGMENTS, gl_MAP1_INDEX, gl_MAP1_NORMAL, gl_MAP1_TEXTURE_COORD_1, gl_MAP1_TEXTURE_COORD_2, gl_MAP1_TEXTURE_COORD_3, gl_MAP1_TEXTURE_COORD_4, gl_MAP1_VERTEX_3, gl_MAP1_VERTEX_4, gl_MAP2_COLOR_4, gl_MAP2_GRID_DOMAIN, gl_MAP2_GRID_SEGMENTS, gl_MAP2_INDEX, gl_MAP2_NORMAL, gl_MAP2_TEXTURE_COORD_1, gl_MAP2_TEXTURE_COORD_2, gl_MAP2_TEXTURE_COORD_3, gl_MAP2_TEXTURE_COORD_4, gl_MAP2_VERTEX_3, gl_MAP2_VERTEX_4, gl_MAP_COHERENT_BIT, gl_MAP_COLOR, gl_MAP_FLUSH_EXPLICIT_BIT, gl_MAP_INVALIDATE_BUFFER_BIT, gl_MAP_INVALIDATE_RANGE_BIT, gl_MAP_PERSISTENT_BIT, gl_MAP_READ_BIT, gl_MAP_STENCIL, gl_MAP_UNSYNCHRONIZED_BIT, gl_MAP_WRITE_BIT, gl_MATRIX_MODE, gl_MATRIX_STRIDE, gl_MAX, gl_MAX_3D_TEXTURE_SIZE, gl_MAX_ARRAY_TEXTURE_LAYERS, gl_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS, gl_MAX_ATOMIC_COUNTER_BUFFER_SIZE, gl_MAX_ATTRIB_STACK_DEPTH, gl_MAX_CLIENT_ATTRIB_STACK_DEPTH, gl_MAX_CLIP_DISTANCES, gl_MAX_CLIP_PLANES, gl_MAX_COLOR_ATTACHMENTS, gl_MAX_COLOR_TEXTURE_SAMPLES, gl_MAX_COMBINED_ATOMIC_COUNTERS, gl_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS, gl_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS, gl_MAX_COMBINED_DIMENSIONS, gl_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS, gl_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS, gl_MAX_COMBINED_IMAGE_UNIFORMS, gl_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS, gl_MAX_COMBINED_SHADER_OUTPUT_RESOURCES, gl_MAX_COMBINED_SHADER_STORAGE_BLOCKS, gl_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS, gl_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS, gl_MAX_COMBINED_TEXTURE_IMAGE_UNITS, gl_MAX_COMBINED_UNIFORM_BLOCKS, gl_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS, gl_MAX_COMPUTE_ATOMIC_COUNTERS, gl_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS, gl_MAX_COMPUTE_IMAGE_UNIFORMS, gl_MAX_COMPUTE_SHADER_STORAGE_BLOCKS, gl_MAX_COMPUTE_SHARED_MEMORY_SIZE, gl_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, gl_MAX_COMPUTE_UNIFORM_BLOCKS, gl_MAX_COMPUTE_UNIFORM_COMPONENTS, gl_MAX_COMPUTE_WORK_GROUP_COUNT, gl_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, gl_MAX_COMPUTE_WORK_GROUP_SIZE, gl_MAX_CUBE_MAP_TEXTURE_SIZE, gl_MAX_DEBUG_GROUP_STACK_DEPTH, gl_MAX_DEBUG_LOGGED_MESSAGES, gl_MAX_DEBUG_MESSAGE_LENGTH, gl_MAX_DEPTH, gl_MAX_DEPTH_TEXTURE_SAMPLES, gl_MAX_DRAW_BUFFERS, gl_MAX_DUAL_SOURCE_DRAW_BUFFERS, gl_MAX_ELEMENTS_INDICES, gl_MAX_ELEMENTS_VERTICES, gl_MAX_ELEMENT_INDEX, gl_MAX_EVAL_ORDER, gl_MAX_FRAGMENT_ATOMIC_COUNTERS, gl_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS, gl_MAX_FRAGMENT_IMAGE_UNIFORMS, gl_MAX_FRAGMENT_INPUT_COMPONENTS, gl_MAX_FRAGMENT_INTERPOLATION_OFFSET, gl_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS, gl_MAX_FRAGMENT_UNIFORM_BLOCKS, gl_MAX_FRAGMENT_UNIFORM_COMPONENTS, gl_MAX_FRAGMENT_UNIFORM_VECTORS, gl_MAX_FRAMEBUFFER_HEIGHT, gl_MAX_FRAMEBUFFER_LAYERS, gl_MAX_FRAMEBUFFER_SAMPLES, gl_MAX_FRAMEBUFFER_WIDTH, gl_MAX_GEOMETRY_ATOMIC_COUNTERS, gl_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS, gl_MAX_GEOMETRY_IMAGE_UNIFORMS, gl_MAX_GEOMETRY_INPUT_COMPONENTS, gl_MAX_GEOMETRY_OUTPUT_COMPONENTS, gl_MAX_GEOMETRY_OUTPUT_VERTICES, gl_MAX_GEOMETRY_SHADER_INVOCATIONS, gl_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS, gl_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, gl_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS, gl_MAX_GEOMETRY_UNIFORM_BLOCKS, gl_MAX_GEOMETRY_UNIFORM_COMPONENTS, gl_MAX_HEIGHT, gl_MAX_IMAGE_SAMPLES, gl_MAX_IMAGE_UNITS, gl_MAX_INTEGER_SAMPLES, gl_MAX_LABEL_LENGTH, gl_MAX_LAYERS, gl_MAX_LIGHTS, gl_MAX_LIST_NESTING, gl_MAX_MODELVIEW_STACK_DEPTH, gl_MAX_NAME_LENGTH, gl_MAX_NAME_STACK_DEPTH, gl_MAX_NUM_ACTIVE_VARIABLES, gl_MAX_NUM_COMPATIBLE_SUBROUTINES, gl_MAX_PATCH_VERTICES, gl_MAX_PIXEL_MAP_TABLE, gl_MAX_PROGRAM_TEXEL_OFFSET, gl_MAX_PROGRAM_TEXTURE_GATHER_OFFSET, gl_MAX_PROJECTION_STACK_DEPTH, gl_MAX_RECTANGLE_TEXTURE_SIZE, gl_MAX_RENDERBUFFER_SIZE, gl_MAX_SAMPLES, gl_MAX_SAMPLE_MASK_WORDS, gl_MAX_SERVER_WAIT_TIMEOUT, gl_MAX_SHADER_STORAGE_BLOCK_SIZE, gl_MAX_SHADER_STORAGE_BUFFER_BINDINGS, gl_MAX_SUBROUTINES, gl_MAX_SUBROUTINE_UNIFORM_LOCATIONS, gl_MAX_TESS_CONTROL_ATOMIC_COUNTERS, gl_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS, gl_MAX_TESS_CONTROL_IMAGE_UNIFORMS, gl_MAX_TESS_CONTROL_INPUT_COMPONENTS, gl_MAX_TESS_CONTROL_OUTPUT_COMPONENTS, gl_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS, gl_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS, gl_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS, gl_MAX_TESS_CONTROL_UNIFORM_BLOCKS, gl_MAX_TESS_CONTROL_UNIFORM_COMPONENTS, gl_MAX_TESS_EVALUATION_ATOMIC_COUNTERS, gl_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS, gl_MAX_TESS_EVALUATION_IMAGE_UNIFORMS, gl_MAX_TESS_EVALUATION_INPUT_COMPONENTS, gl_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS, gl_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS, gl_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS, gl_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, gl_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS, gl_MAX_TESS_GEN_LEVEL, gl_MAX_TESS_PATCH_COMPONENTS, gl_MAX_TEXTURE_BUFFER_SIZE, gl_MAX_TEXTURE_COORDS, gl_MAX_TEXTURE_IMAGE_UNITS, gl_MAX_TEXTURE_LOD_BIAS, gl_MAX_TEXTURE_SIZE, gl_MAX_TEXTURE_STACK_DEPTH, gl_MAX_TEXTURE_UNITS, gl_MAX_TRANSFORM_FEEDBACK_BUFFERS, gl_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, gl_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, gl_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, gl_MAX_UNIFORM_BLOCK_SIZE, gl_MAX_UNIFORM_BUFFER_BINDINGS, gl_MAX_UNIFORM_LOCATIONS, gl_MAX_VARYING_COMPONENTS, gl_MAX_VARYING_FLOATS, gl_MAX_VARYING_VECTORS, gl_MAX_VERTEX_ATOMIC_COUNTERS, gl_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS, gl_MAX_VERTEX_ATTRIBS, gl_MAX_VERTEX_ATTRIB_BINDINGS, gl_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET, gl_MAX_VERTEX_ATTRIB_STRIDE, gl_MAX_VERTEX_IMAGE_UNIFORMS, gl_MAX_VERTEX_OUTPUT_COMPONENTS, gl_MAX_VERTEX_SHADER_STORAGE_BLOCKS, gl_MAX_VERTEX_STREAMS, gl_MAX_VERTEX_TEXTURE_IMAGE_UNITS, gl_MAX_VERTEX_UNIFORM_BLOCKS, gl_MAX_VERTEX_UNIFORM_COMPONENTS, gl_MAX_VERTEX_UNIFORM_VECTORS, gl_MAX_VIEWPORTS, gl_MAX_VIEWPORT_DIMS, gl_MAX_WIDTH, gl_MEDIUM_FLOAT, gl_MEDIUM_INT, gl_MIN, gl_MINOR_VERSION, gl_MIN_FRAGMENT_INTERPOLATION_OFFSET, gl_MIN_MAP_BUFFER_ALIGNMENT, gl_MIN_PROGRAM_TEXEL_OFFSET, gl_MIN_PROGRAM_TEXTURE_GATHER_OFFSET, gl_MIN_SAMPLE_SHADING_VALUE, gl_MIPMAP, gl_MIRRORED_REPEAT, gl_MIRROR_CLAMP_TO_EDGE, gl_MODELVIEW, gl_MODELVIEW_MATRIX, gl_MODELVIEW_STACK_DEPTH, gl_MODULATE, gl_MULT, gl_MULTISAMPLE, gl_MULTISAMPLE_BIT, gl_N3F_V3F, gl_NAME_LENGTH, gl_NAME_STACK_DEPTH, gl_NAND, gl_NEAREST, gl_NEAREST_MIPMAP_LINEAR, gl_NEAREST_MIPMAP_NEAREST, gl_NEVER, gl_NICEST, gl_NONE, gl_NOOP, gl_NOR, gl_NORMALIZE, gl_NORMAL_ARRAY, gl_NORMAL_ARRAY_BUFFER_BINDING, gl_NORMAL_ARRAY_POINTER, gl_NORMAL_ARRAY_STRIDE, gl_NORMAL_ARRAY_TYPE, gl_NORMAL_MAP, gl_NOTEQUAL, gl_NO_ERROR, gl_NUM_ACTIVE_VARIABLES, gl_NUM_COMPATIBLE_SUBROUTINES, gl_NUM_COMPRESSED_TEXTURE_FORMATS, gl_NUM_EXTENSIONS, gl_NUM_PROGRAM_BINARY_FORMATS, gl_NUM_SAMPLE_COUNTS, gl_NUM_SHADER_BINARY_FORMATS, gl_NUM_SHADING_LANGUAGE_VERSIONS, gl_OBJECT_LINEAR, gl_OBJECT_PLANE, gl_OBJECT_TYPE, gl_OFFSET, gl_ONE, gl_ONE_MINUS_CONSTANT_ALPHA, gl_ONE_MINUS_CONSTANT_COLOR, gl_ONE_MINUS_DST_ALPHA, gl_ONE_MINUS_DST_COLOR, gl_ONE_MINUS_SRC1_ALPHA, gl_ONE_MINUS_SRC1_COLOR, gl_ONE_MINUS_SRC_ALPHA, gl_ONE_MINUS_SRC_COLOR, gl_OPERAND0_ALPHA, gl_OPERAND0_RGB, gl_OPERAND1_ALPHA, gl_OPERAND1_RGB, gl_OPERAND2_ALPHA, gl_OPERAND2_RGB, gl_OR, gl_ORDER, gl_OR_INVERTED, gl_OR_REVERSE, gl_OUT_OF_MEMORY, gl_PACK_ALIGNMENT, gl_PACK_COMPRESSED_BLOCK_DEPTH, gl_PACK_COMPRESSED_BLOCK_HEIGHT, gl_PACK_COMPRESSED_BLOCK_SIZE, gl_PACK_COMPRESSED_BLOCK_WIDTH, gl_PACK_IMAGE_HEIGHT, gl_PACK_LSB_FIRST, gl_PACK_ROW_LENGTH, gl_PACK_SKIP_IMAGES, gl_PACK_SKIP_PIXELS, gl_PACK_SKIP_ROWS, gl_PACK_SWAP_BYTES, gl_PASS_THROUGH_TOKEN, gl_PATCHES, gl_PATCH_DEFAULT_INNER_LEVEL, gl_PATCH_DEFAULT_OUTER_LEVEL, gl_PATCH_VERTICES, gl_PERSPECTIVE_CORRECTION_HINT, gl_PIXEL_BUFFER_BARRIER_BIT, gl_PIXEL_MAP_A_TO_A, gl_PIXEL_MAP_A_TO_A_SIZE, gl_PIXEL_MAP_B_TO_B, gl_PIXEL_MAP_B_TO_B_SIZE, gl_PIXEL_MAP_G_TO_G, gl_PIXEL_MAP_G_TO_G_SIZE, gl_PIXEL_MAP_I_TO_A, gl_PIXEL_MAP_I_TO_A_SIZE, gl_PIXEL_MAP_I_TO_B, gl_PIXEL_MAP_I_TO_B_SIZE, gl_PIXEL_MAP_I_TO_G, gl_PIXEL_MAP_I_TO_G_SIZE, gl_PIXEL_MAP_I_TO_I, gl_PIXEL_MAP_I_TO_I_SIZE, gl_PIXEL_MAP_I_TO_R, gl_PIXEL_MAP_I_TO_R_SIZE, gl_PIXEL_MAP_R_TO_R, gl_PIXEL_MAP_R_TO_R_SIZE, gl_PIXEL_MAP_S_TO_S, gl_PIXEL_MAP_S_TO_S_SIZE, gl_PIXEL_MODE_BIT, gl_PIXEL_PACK_BUFFER, gl_PIXEL_PACK_BUFFER_BINDING, gl_PIXEL_UNPACK_BUFFER, gl_PIXEL_UNPACK_BUFFER_BINDING, gl_POINT, gl_POINTS, gl_POINT_BIT, gl_POINT_DISTANCE_ATTENUATION, gl_POINT_FADE_THRESHOLD_SIZE, gl_POINT_SIZE, gl_POINT_SIZE_GRANULARITY, gl_POINT_SIZE_MAX, gl_POINT_SIZE_MIN, gl_POINT_SIZE_RANGE, gl_POINT_SMOOTH, gl_POINT_SMOOTH_HINT, gl_POINT_SPRITE, gl_POINT_SPRITE_COORD_ORIGIN, gl_POINT_TOKEN, gl_POLYGON, gl_POLYGON_BIT, gl_POLYGON_MODE, gl_POLYGON_OFFSET_FACTOR, gl_POLYGON_OFFSET_FILL, gl_POLYGON_OFFSET_LINE, gl_POLYGON_OFFSET_POINT, gl_POLYGON_OFFSET_UNITS, gl_POLYGON_SMOOTH, gl_POLYGON_SMOOTH_HINT, gl_POLYGON_STIPPLE, gl_POLYGON_STIPPLE_BIT, gl_POLYGON_TOKEN, gl_POSITION, gl_PREVIOUS, gl_PRIMARY_COLOR, gl_PRIMITIVES_GENERATED, gl_PRIMITIVE_RESTART, gl_PRIMITIVE_RESTART_FIXED_INDEX, gl_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED, gl_PRIMITIVE_RESTART_INDEX, gl_PROGRAM, gl_PROGRAM_BINARY_FORMATS, gl_PROGRAM_BINARY_LENGTH, gl_PROGRAM_BINARY_RETRIEVABLE_HINT, gl_PROGRAM_INPUT, gl_PROGRAM_OUTPUT, gl_PROGRAM_PIPELINE, gl_PROGRAM_PIPELINE_BINDING, gl_PROGRAM_POINT_SIZE, gl_PROGRAM_SEPARABLE, gl_PROJECTION, gl_PROJECTION_MATRIX, gl_PROJECTION_STACK_DEPTH, gl_PROVOKING_VERTEX, gl_PROXY_TEXTURE_1D, gl_PROXY_TEXTURE_1D_ARRAY, gl_PROXY_TEXTURE_2D, gl_PROXY_TEXTURE_2D_ARRAY, gl_PROXY_TEXTURE_2D_MULTISAMPLE, gl_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY, gl_PROXY_TEXTURE_3D, gl_PROXY_TEXTURE_CUBE_MAP, gl_PROXY_TEXTURE_CUBE_MAP_ARRAY, gl_PROXY_TEXTURE_RECTANGLE, gl_Q, gl_QUADRATIC_ATTENUATION, gl_QUADS, gl_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION, gl_QUAD_STRIP, gl_QUERY, gl_QUERY_BUFFER, gl_QUERY_BUFFER_BARRIER_BIT, gl_QUERY_BUFFER_BINDING, gl_QUERY_BY_REGION_NO_WAIT, gl_QUERY_BY_REGION_WAIT, gl_QUERY_COUNTER_BITS, gl_QUERY_NO_WAIT, gl_QUERY_RESULT, gl_QUERY_RESULT_AVAILABLE, gl_QUERY_RESULT_NO_WAIT, gl_QUERY_WAIT, gl_R, gl_R11F_G11F_B10F, gl_R16, gl_R16F, gl_R16I, gl_R16UI, gl_R16_SNORM, gl_R32F, gl_R32I, gl_R32UI, gl_R3_G3_B2, gl_R8, gl_R8I, gl_R8UI, gl_R8_SNORM, gl_RASTERIZER_DISCARD, gl_READ_BUFFER, gl_READ_FRAMEBUFFER, gl_READ_FRAMEBUFFER_BINDING, gl_READ_ONLY, gl_READ_PIXELS, gl_READ_PIXELS_FORMAT, gl_READ_PIXELS_TYPE, gl_READ_WRITE, gl_RED, gl_RED_BIAS, gl_RED_BITS, gl_RED_INTEGER, gl_RED_SCALE, gl_REFERENCED_BY_COMPUTE_SHADER, gl_REFERENCED_BY_FRAGMENT_SHADER, gl_REFERENCED_BY_GEOMETRY_SHADER, gl_REFERENCED_BY_TESS_CONTROL_SHADER, gl_REFERENCED_BY_TESS_EVALUATION_SHADER, gl_REFERENCED_BY_VERTEX_SHADER, gl_REFLECTION_MAP, gl_RENDER, gl_RENDERBUFFER, gl_RENDERBUFFER_ALPHA_SIZE, gl_RENDERBUFFER_BINDING, gl_RENDERBUFFER_BLUE_SIZE, gl_RENDERBUFFER_DEPTH_SIZE, gl_RENDERBUFFER_GREEN_SIZE, gl_RENDERBUFFER_HEIGHT, gl_RENDERBUFFER_INTERNAL_FORMAT, gl_RENDERBUFFER_RED_SIZE, gl_RENDERBUFFER_SAMPLES, gl_RENDERBUFFER_STENCIL_SIZE, gl_RENDERBUFFER_WIDTH, gl_RENDERER, gl_RENDER_MODE, gl_REPEAT, gl_REPLACE, gl_RESCALE_NORMAL, gl_RETURN, gl_RG, gl_RG16, gl_RG16F, gl_RG16I, gl_RG16UI, gl_RG16_SNORM, gl_RG32F, gl_RG32I, gl_RG32UI, gl_RG8, gl_RG8I, gl_RG8UI, gl_RG8_SNORM, gl_RGB, gl_RGB10, gl_RGB10_A2, gl_RGB10_A2UI, gl_RGB12, gl_RGB16, gl_RGB16F, gl_RGB16I, gl_RGB16UI, gl_RGB16_SNORM, gl_RGB32F, gl_RGB32I, gl_RGB32UI, gl_RGB4, gl_RGB5, gl_RGB565, gl_RGB5_A1, gl_RGB8, gl_RGB8I, gl_RGB8UI, gl_RGB8_SNORM, gl_RGB9_E5, gl_RGBA, gl_RGBA12, gl_RGBA16, gl_RGBA16F, gl_RGBA16I, gl_RGBA16UI, gl_RGBA16_SNORM, gl_RGBA2, gl_RGBA32F, gl_RGBA32I, gl_RGBA32UI, gl_RGBA4, gl_RGBA8, gl_RGBA8I, gl_RGBA8UI, gl_RGBA8_SNORM, gl_RGBA_INTEGER, gl_RGBA_MODE, gl_RGB_INTEGER, gl_RGB_SCALE, gl_RG_INTEGER, gl_RIGHT, gl_S, gl_SAMPLER, gl_SAMPLER_1D, gl_SAMPLER_1D_ARRAY, gl_SAMPLER_1D_ARRAY_SHADOW, gl_SAMPLER_1D_SHADOW, gl_SAMPLER_2D, gl_SAMPLER_2D_ARRAY, gl_SAMPLER_2D_ARRAY_SHADOW, gl_SAMPLER_2D_MULTISAMPLE, gl_SAMPLER_2D_MULTISAMPLE_ARRAY, gl_SAMPLER_2D_RECT, gl_SAMPLER_2D_RECT_SHADOW, gl_SAMPLER_2D_SHADOW, gl_SAMPLER_3D, gl_SAMPLER_BINDING, gl_SAMPLER_BUFFER, gl_SAMPLER_CUBE, gl_SAMPLER_CUBE_MAP_ARRAY, gl_SAMPLER_CUBE_MAP_ARRAY_SHADOW, gl_SAMPLER_CUBE_SHADOW, gl_SAMPLES, gl_SAMPLES_PASSED, gl_SAMPLE_ALPHA_TO_COVERAGE, gl_SAMPLE_ALPHA_TO_ONE, gl_SAMPLE_BUFFERS, gl_SAMPLE_COVERAGE, gl_SAMPLE_COVERAGE_INVERT, gl_SAMPLE_COVERAGE_VALUE, gl_SAMPLE_MASK, gl_SAMPLE_MASK_VALUE, gl_SAMPLE_POSITION, gl_SAMPLE_SHADING, gl_SCISSOR_BIT, gl_SCISSOR_BOX, gl_SCISSOR_TEST, gl_SECONDARY_COLOR_ARRAY, gl_SECONDARY_COLOR_ARRAY_BUFFER_BINDING, gl_SECONDARY_COLOR_ARRAY_POINTER, gl_SECONDARY_COLOR_ARRAY_SIZE, gl_SECONDARY_COLOR_ARRAY_STRIDE, gl_SECONDARY_COLOR_ARRAY_TYPE, gl_SELECT, gl_SELECTION_BUFFER_POINTER, gl_SELECTION_BUFFER_SIZE, gl_SEPARATE_ATTRIBS, gl_SEPARATE_SPECULAR_COLOR, gl_SET, gl_SHADER, gl_SHADER_BINARY_FORMATS, gl_SHADER_COMPILER, gl_SHADER_IMAGE_ACCESS_BARRIER_BIT, gl_SHADER_IMAGE_ATOMIC, gl_SHADER_IMAGE_LOAD, gl_SHADER_IMAGE_STORE, gl_SHADER_SOURCE_LENGTH, gl_SHADER_STORAGE_BARRIER_BIT, gl_SHADER_STORAGE_BLOCK, gl_SHADER_STORAGE_BUFFER, gl_SHADER_STORAGE_BUFFER_BINDING, gl_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT, gl_SHADER_STORAGE_BUFFER_SIZE, gl_SHADER_STORAGE_BUFFER_START, gl_SHADER_TYPE, gl_SHADE_MODEL, gl_SHADING_LANGUAGE_VERSION, gl_SHININESS, gl_SHORT, gl_SIGNALED, gl_SIGNED_NORMALIZED, gl_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST, gl_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE, gl_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST, gl_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE, gl_SINGLE_COLOR, gl_SLUMINANCE, gl_SLUMINANCE8, gl_SLUMINANCE8_ALPHA8, gl_SLUMINANCE_ALPHA, gl_SMOOTH, gl_SMOOTH_LINE_WIDTH_GRANULARITY, gl_SMOOTH_LINE_WIDTH_RANGE, gl_SMOOTH_POINT_SIZE_GRANULARITY, gl_SMOOTH_POINT_SIZE_RANGE, gl_SOURCE0_ALPHA, gl_SOURCE0_RGB, gl_SOURCE1_ALPHA, gl_SOURCE1_RGB, gl_SOURCE2_ALPHA, gl_SOURCE2_RGB, gl_SPECULAR, gl_SPHERE_MAP, gl_SPOT_CUTOFF, gl_SPOT_DIRECTION, gl_SPOT_EXPONENT, gl_SRC0_ALPHA, gl_SRC0_RGB, gl_SRC1_ALPHA, gl_SRC1_COLOR, gl_SRC1_RGB, gl_SRC2_ALPHA, gl_SRC2_RGB, gl_SRC_ALPHA, gl_SRC_ALPHA_SATURATE, gl_SRC_COLOR, gl_SRGB, gl_SRGB8, gl_SRGB8_ALPHA8, gl_SRGB_ALPHA, gl_SRGB_READ, gl_SRGB_WRITE, gl_STACK_OVERFLOW, gl_STACK_UNDERFLOW, gl_STATIC_COPY, gl_STATIC_DRAW, gl_STATIC_READ, gl_STENCIL, gl_STENCIL_ATTACHMENT, gl_STENCIL_BACK_FAIL, gl_STENCIL_BACK_FUNC, gl_STENCIL_BACK_PASS_DEPTH_FAIL, gl_STENCIL_BACK_PASS_DEPTH_PASS, gl_STENCIL_BACK_REF, gl_STENCIL_BACK_VALUE_MASK, gl_STENCIL_BACK_WRITEMASK, gl_STENCIL_BITS, gl_STENCIL_BUFFER_BIT, gl_STENCIL_CLEAR_VALUE, gl_STENCIL_COMPONENTS, gl_STENCIL_FAIL, gl_STENCIL_FUNC, gl_STENCIL_INDEX, gl_STENCIL_INDEX1, gl_STENCIL_INDEX16, gl_STENCIL_INDEX4, gl_STENCIL_INDEX8, gl_STENCIL_PASS_DEPTH_FAIL, gl_STENCIL_PASS_DEPTH_PASS, gl_STENCIL_REF, gl_STENCIL_RENDERABLE, gl_STENCIL_TEST, gl_STENCIL_VALUE_MASK, gl_STENCIL_WRITEMASK, gl_STEREO, gl_STREAM_COPY, gl_STREAM_DRAW, gl_STREAM_READ, gl_SUBPIXEL_BITS, gl_SUBTRACT, gl_SYNC_CONDITION, gl_SYNC_FENCE, gl_SYNC_FLAGS, gl_SYNC_FLUSH_COMMANDS_BIT, gl_SYNC_GPU_COMMANDS_COMPLETE, gl_SYNC_STATUS, gl_T, gl_T2F_C3F_V3F, gl_T2F_C4F_N3F_V3F, gl_T2F_C4UB_V3F, gl_T2F_N3F_V3F, gl_T2F_V3F, gl_T4F_C4F_N3F_V4F, gl_T4F_V4F, gl_TESS_CONTROL_OUTPUT_VERTICES, gl_TESS_CONTROL_SHADER, gl_TESS_CONTROL_SHADER_BIT, gl_TESS_CONTROL_SUBROUTINE, gl_TESS_CONTROL_SUBROUTINE_UNIFORM, gl_TESS_CONTROL_TEXTURE, gl_TESS_EVALUATION_SHADER, gl_TESS_EVALUATION_SHADER_BIT, gl_TESS_EVALUATION_SUBROUTINE, gl_TESS_EVALUATION_SUBROUTINE_UNIFORM, gl_TESS_EVALUATION_TEXTURE, gl_TESS_GEN_MODE, gl_TESS_GEN_POINT_MODE, gl_TESS_GEN_SPACING, gl_TESS_GEN_VERTEX_ORDER, gl_TEXTURE, gl_TEXTURE0, gl_TEXTURE1, gl_TEXTURE10, gl_TEXTURE11, gl_TEXTURE12, gl_TEXTURE13, gl_TEXTURE14, gl_TEXTURE15, gl_TEXTURE16, gl_TEXTURE17, gl_TEXTURE18, gl_TEXTURE19, gl_TEXTURE2, gl_TEXTURE20, gl_TEXTURE21, gl_TEXTURE22, gl_TEXTURE23, gl_TEXTURE24, gl_TEXTURE25, gl_TEXTURE26, gl_TEXTURE27, gl_TEXTURE28, gl_TEXTURE29, gl_TEXTURE3, gl_TEXTURE30, gl_TEXTURE31, gl_TEXTURE4, gl_TEXTURE5, gl_TEXTURE6, gl_TEXTURE7, gl_TEXTURE8, gl_TEXTURE9, gl_TEXTURE_1D, gl_TEXTURE_1D_ARRAY, gl_TEXTURE_2D, gl_TEXTURE_2D_ARRAY, gl_TEXTURE_2D_MULTISAMPLE, gl_TEXTURE_2D_MULTISAMPLE_ARRAY, gl_TEXTURE_3D, gl_TEXTURE_ALPHA_SIZE, gl_TEXTURE_ALPHA_TYPE, gl_TEXTURE_BASE_LEVEL, gl_TEXTURE_BINDING_1D, gl_TEXTURE_BINDING_1D_ARRAY, gl_TEXTURE_BINDING_2D, gl_TEXTURE_BINDING_2D_ARRAY, gl_TEXTURE_BINDING_2D_MULTISAMPLE, gl_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY, gl_TEXTURE_BINDING_3D, gl_TEXTURE_BINDING_BUFFER, gl_TEXTURE_BINDING_CUBE_MAP, gl_TEXTURE_BINDING_CUBE_MAP_ARRAY, gl_TEXTURE_BINDING_RECTANGLE, gl_TEXTURE_BIT, gl_TEXTURE_BLUE_SIZE, gl_TEXTURE_BLUE_TYPE, gl_TEXTURE_BORDER, gl_TEXTURE_BORDER_COLOR, gl_TEXTURE_BUFFER, gl_TEXTURE_BUFFER_BINDING, gl_TEXTURE_BUFFER_DATA_STORE_BINDING, gl_TEXTURE_BUFFER_OFFSET, gl_TEXTURE_BUFFER_OFFSET_ALIGNMENT, gl_TEXTURE_BUFFER_SIZE, gl_TEXTURE_COMPARE_FUNC, gl_TEXTURE_COMPARE_MODE, gl_TEXTURE_COMPONENTS, gl_TEXTURE_COMPRESSED, gl_TEXTURE_COMPRESSED_BLOCK_HEIGHT, gl_TEXTURE_COMPRESSED_BLOCK_SIZE, gl_TEXTURE_COMPRESSED_BLOCK_WIDTH, gl_TEXTURE_COMPRESSED_IMAGE_SIZE, gl_TEXTURE_COMPRESSION_HINT, gl_TEXTURE_COORD_ARRAY, gl_TEXTURE_COORD_ARRAY_BUFFER_BINDING, gl_TEXTURE_COORD_ARRAY_POINTER, gl_TEXTURE_COORD_ARRAY_SIZE, gl_TEXTURE_COORD_ARRAY_STRIDE, gl_TEXTURE_COORD_ARRAY_TYPE, gl_TEXTURE_CUBE_MAP, gl_TEXTURE_CUBE_MAP_ARRAY, gl_TEXTURE_CUBE_MAP_NEGATIVE_X, gl_TEXTURE_CUBE_MAP_NEGATIVE_Y, gl_TEXTURE_CUBE_MAP_NEGATIVE_Z, gl_TEXTURE_CUBE_MAP_POSITIVE_X, gl_TEXTURE_CUBE_MAP_POSITIVE_Y, gl_TEXTURE_CUBE_MAP_POSITIVE_Z, gl_TEXTURE_CUBE_MAP_SEAMLESS, gl_TEXTURE_DEPTH, gl_TEXTURE_DEPTH_SIZE, gl_TEXTURE_DEPTH_TYPE, gl_TEXTURE_ENV, gl_TEXTURE_ENV_COLOR, gl_TEXTURE_ENV_MODE, gl_TEXTURE_FETCH_BARRIER_BIT, gl_TEXTURE_FILTER_CONTROL, gl_TEXTURE_FIXED_SAMPLE_LOCATIONS, gl_TEXTURE_GATHER, gl_TEXTURE_GATHER_SHADOW, gl_TEXTURE_GEN_MODE, gl_TEXTURE_GEN_Q, gl_TEXTURE_GEN_R, gl_TEXTURE_GEN_S, gl_TEXTURE_GEN_T, gl_TEXTURE_GREEN_SIZE, gl_TEXTURE_GREEN_TYPE, gl_TEXTURE_HEIGHT, gl_TEXTURE_IMAGE_FORMAT, gl_TEXTURE_IMAGE_TYPE, gl_TEXTURE_IMMUTABLE_FORMAT, gl_TEXTURE_IMMUTABLE_LEVELS, gl_TEXTURE_INTENSITY_SIZE, gl_TEXTURE_INTENSITY_TYPE, gl_TEXTURE_INTERNAL_FORMAT, gl_TEXTURE_LOD_BIAS, gl_TEXTURE_LUMINANCE_SIZE, gl_TEXTURE_LUMINANCE_TYPE, gl_TEXTURE_MAG_FILTER, gl_TEXTURE_MATRIX, gl_TEXTURE_MAX_LEVEL, gl_TEXTURE_MAX_LOD, gl_TEXTURE_MIN_FILTER, gl_TEXTURE_MIN_LOD, gl_TEXTURE_PRIORITY, gl_TEXTURE_RECTANGLE, gl_TEXTURE_RED_SIZE, gl_TEXTURE_RED_TYPE, gl_TEXTURE_RESIDENT, gl_TEXTURE_SAMPLES, gl_TEXTURE_SHADOW, gl_TEXTURE_SHARED_SIZE, gl_TEXTURE_STACK_DEPTH, gl_TEXTURE_STENCIL_SIZE, gl_TEXTURE_SWIZZLE_A, gl_TEXTURE_SWIZZLE_B, gl_TEXTURE_SWIZZLE_G, gl_TEXTURE_SWIZZLE_R, gl_TEXTURE_SWIZZLE_RGBA, gl_TEXTURE_UPDATE_BARRIER_BIT, gl_TEXTURE_VIEW, gl_TEXTURE_VIEW_MIN_LAYER, gl_TEXTURE_VIEW_MIN_LEVEL, gl_TEXTURE_VIEW_NUM_LAYERS, gl_TEXTURE_VIEW_NUM_LEVELS, gl_TEXTURE_WIDTH, gl_TEXTURE_WRAP_R, gl_TEXTURE_WRAP_S, gl_TEXTURE_WRAP_T, gl_TIMEOUT_EXPIRED, gl_TIMEOUT_IGNORED, gl_TIMESTAMP, gl_TIME_ELAPSED, gl_TOP_LEVEL_ARRAY_SIZE, gl_TOP_LEVEL_ARRAY_STRIDE, gl_TRANSFORM_BIT, gl_TRANSFORM_FEEDBACK, gl_TRANSFORM_FEEDBACK_ACTIVE, gl_TRANSFORM_FEEDBACK_BARRIER_BIT, gl_TRANSFORM_FEEDBACK_BINDING, gl_TRANSFORM_FEEDBACK_BUFFER, gl_TRANSFORM_FEEDBACK_BUFFER_ACTIVE, gl_TRANSFORM_FEEDBACK_BUFFER_BINDING, gl_TRANSFORM_FEEDBACK_BUFFER_INDEX, gl_TRANSFORM_FEEDBACK_BUFFER_MODE, gl_TRANSFORM_FEEDBACK_BUFFER_PAUSED, gl_TRANSFORM_FEEDBACK_BUFFER_SIZE, gl_TRANSFORM_FEEDBACK_BUFFER_START, gl_TRANSFORM_FEEDBACK_BUFFER_STRIDE, gl_TRANSFORM_FEEDBACK_PAUSED, gl_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, gl_TRANSFORM_FEEDBACK_VARYING, gl_TRANSFORM_FEEDBACK_VARYINGS, gl_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH, gl_TRANSPOSE_COLOR_MATRIX, gl_TRANSPOSE_MODELVIEW_MATRIX, gl_TRANSPOSE_PROJECTION_MATRIX, gl_TRANSPOSE_TEXTURE_MATRIX, gl_TRIANGLES, gl_TRIANGLES_ADJACENCY, gl_TRIANGLE_FAN, gl_TRIANGLE_STRIP, gl_TRIANGLE_STRIP_ADJACENCY, gl_TRUE, gl_TYPE, gl_UNDEFINED_VERTEX, gl_UNIFORM, gl_UNIFORM_ARRAY_STRIDE, gl_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX, gl_UNIFORM_BARRIER_BIT, gl_UNIFORM_BLOCK, gl_UNIFORM_BLOCK_ACTIVE_UNIFORMS, gl_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, gl_UNIFORM_BLOCK_BINDING, gl_UNIFORM_BLOCK_DATA_SIZE, gl_UNIFORM_BLOCK_INDEX, gl_UNIFORM_BLOCK_NAME_LENGTH, gl_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER, gl_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER, gl_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER, gl_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER, gl_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER, gl_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER, gl_UNIFORM_BUFFER, gl_UNIFORM_BUFFER_BINDING, gl_UNIFORM_BUFFER_OFFSET_ALIGNMENT, gl_UNIFORM_BUFFER_SIZE, gl_UNIFORM_BUFFER_START, gl_UNIFORM_IS_ROW_MAJOR, gl_UNIFORM_MATRIX_STRIDE, gl_UNIFORM_NAME_LENGTH, gl_UNIFORM_OFFSET, gl_UNIFORM_SIZE, gl_UNIFORM_TYPE, gl_UNPACK_ALIGNMENT, gl_UNPACK_COMPRESSED_BLOCK_DEPTH, gl_UNPACK_COMPRESSED_BLOCK_HEIGHT, gl_UNPACK_COMPRESSED_BLOCK_SIZE, gl_UNPACK_COMPRESSED_BLOCK_WIDTH, gl_UNPACK_IMAGE_HEIGHT, gl_UNPACK_LSB_FIRST, gl_UNPACK_ROW_LENGTH, gl_UNPACK_SKIP_IMAGES, gl_UNPACK_SKIP_PIXELS, gl_UNPACK_SKIP_ROWS, gl_UNPACK_SWAP_BYTES, gl_UNSIGNALED, gl_UNSIGNED_BYTE, gl_UNSIGNED_BYTE_2_3_3_REV, gl_UNSIGNED_BYTE_3_3_2, gl_UNSIGNED_INT, gl_UNSIGNED_INT_10F_11F_11F_REV, gl_UNSIGNED_INT_10_10_10_2, gl_UNSIGNED_INT_24_8, gl_UNSIGNED_INT_2_10_10_10_REV, gl_UNSIGNED_INT_5_9_9_9_REV, gl_UNSIGNED_INT_8_8_8_8, gl_UNSIGNED_INT_8_8_8_8_REV, gl_UNSIGNED_INT_ATOMIC_COUNTER, gl_UNSIGNED_INT_IMAGE_1D, gl_UNSIGNED_INT_IMAGE_1D_ARRAY, gl_UNSIGNED_INT_IMAGE_2D, gl_UNSIGNED_INT_IMAGE_2D_ARRAY, gl_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE, gl_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY, gl_UNSIGNED_INT_IMAGE_2D_RECT, gl_UNSIGNED_INT_IMAGE_3D, gl_UNSIGNED_INT_IMAGE_BUFFER, gl_UNSIGNED_INT_IMAGE_CUBE, gl_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY, gl_UNSIGNED_INT_SAMPLER_1D, gl_UNSIGNED_INT_SAMPLER_1D_ARRAY, gl_UNSIGNED_INT_SAMPLER_2D, gl_UNSIGNED_INT_SAMPLER_2D_ARRAY, gl_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, gl_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, gl_UNSIGNED_INT_SAMPLER_2D_RECT, gl_UNSIGNED_INT_SAMPLER_3D, gl_UNSIGNED_INT_SAMPLER_BUFFER, gl_UNSIGNED_INT_SAMPLER_CUBE, gl_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY, gl_UNSIGNED_INT_VEC2, gl_UNSIGNED_INT_VEC3, gl_UNSIGNED_INT_VEC4, gl_UNSIGNED_NORMALIZED, gl_UNSIGNED_SHORT, gl_UNSIGNED_SHORT_1_5_5_5_REV, gl_UNSIGNED_SHORT_4_4_4_4, gl_UNSIGNED_SHORT_4_4_4_4_REV, gl_UNSIGNED_SHORT_5_5_5_1, gl_UNSIGNED_SHORT_5_6_5, gl_UNSIGNED_SHORT_5_6_5_REV, gl_UPPER_LEFT, gl_V2F, gl_V3F, gl_VALIDATE_STATUS, gl_VENDOR, gl_VERSION, gl_VERTEX_ARRAY, gl_VERTEX_ARRAY_BINDING, gl_VERTEX_ARRAY_BUFFER_BINDING, gl_VERTEX_ARRAY_POINTER, gl_VERTEX_ARRAY_SIZE, gl_VERTEX_ARRAY_STRIDE, gl_VERTEX_ARRAY_TYPE, gl_VERTEX_ATTRIB_ARRAY_BARRIER_BIT, gl_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, gl_VERTEX_ATTRIB_ARRAY_DIVISOR, gl_VERTEX_ATTRIB_ARRAY_ENABLED, gl_VERTEX_ATTRIB_ARRAY_INTEGER, gl_VERTEX_ATTRIB_ARRAY_LONG, gl_VERTEX_ATTRIB_ARRAY_NORMALIZED, gl_VERTEX_ATTRIB_ARRAY_POINTER, gl_VERTEX_ATTRIB_ARRAY_SIZE, gl_VERTEX_ATTRIB_ARRAY_STRIDE, gl_VERTEX_ATTRIB_ARRAY_TYPE, gl_VERTEX_ATTRIB_BINDING, gl_VERTEX_ATTRIB_RELATIVE_OFFSET, gl_VERTEX_BINDING_BUFFER, gl_VERTEX_BINDING_DIVISOR, gl_VERTEX_BINDING_OFFSET, gl_VERTEX_BINDING_STRIDE, gl_VERTEX_PROGRAM_POINT_SIZE, gl_VERTEX_PROGRAM_TWO_SIDE, gl_VERTEX_SHADER, gl_VERTEX_SHADER_BIT, gl_VERTEX_SUBROUTINE, gl_VERTEX_SUBROUTINE_UNIFORM, gl_VERTEX_TEXTURE, gl_VIEWPORT, gl_VIEWPORT_BIT, gl_VIEWPORT_BOUNDS_RANGE, gl_VIEWPORT_INDEX_PROVOKING_VERTEX, gl_VIEWPORT_SUBPIXEL_BITS, gl_VIEW_CLASS_128_BITS, gl_VIEW_CLASS_16_BITS, gl_VIEW_CLASS_24_BITS, gl_VIEW_CLASS_32_BITS, gl_VIEW_CLASS_48_BITS, gl_VIEW_CLASS_64_BITS, gl_VIEW_CLASS_8_BITS, gl_VIEW_CLASS_96_BITS, gl_VIEW_CLASS_BPTC_FLOAT, gl_VIEW_CLASS_BPTC_UNORM, gl_VIEW_CLASS_RGTC1_RED, gl_VIEW_CLASS_RGTC2_RG, gl_VIEW_CLASS_S3TC_DXT1_RGB, gl_VIEW_CLASS_S3TC_DXT1_RGBA, gl_VIEW_CLASS_S3TC_DXT3_RGBA, gl_VIEW_CLASS_S3TC_DXT5_RGBA, gl_VIEW_COMPATIBILITY_CLASS, gl_WAIT_FAILED, gl_WEIGHT_ARRAY_BUFFER_BINDING, gl_WRITE_ONLY, gl_XOR, gl_ZERO, gl_ZOOM_X, gl_ZOOM_Y, -- * Functions glAccum, glActiveShaderProgram, glActiveTexture, glAlphaFunc, glAreTexturesResident, glArrayElement, glAttachShader, glBegin, glBeginConditionalRender, glBeginQuery, glBeginQueryIndexed, glBeginTransformFeedback, glBindAttribLocation, glBindBuffer, glBindBufferBase, glBindBufferRange, glBindBuffersBase, glBindBuffersRange, glBindFragDataLocation, glBindFragDataLocationIndexed, glBindFramebuffer, glBindImageTexture, glBindImageTextures, glBindProgramPipeline, glBindRenderbuffer, glBindSampler, glBindSamplers, glBindTexture, glBindTextures, glBindTransformFeedback, glBindVertexArray, glBindVertexBuffer, glBindVertexBuffers, glBitmap, glBlendColor, glBlendEquation, glBlendEquationSeparate, glBlendEquationSeparatei, glBlendEquationi, glBlendFunc, glBlendFuncSeparate, glBlendFuncSeparatei, glBlendFunci, glBlitFramebuffer, glBufferData, glBufferStorage, glBufferSubData, glCallList, glCallLists, glCheckFramebufferStatus, glClampColor, glClear, glClearAccum, glClearBufferData, glClearBufferSubData, glClearBufferfi, glClearBufferfv, glClearBufferiv, glClearBufferuiv, glClearColor, glClearDepth, glClearDepthf, glClearIndex, glClearStencil, glClearTexImage, glClearTexSubImage, glClientActiveTexture, glClientWaitSync, glClipPlane, glColor3b, glColor3bv, glColor3d, glColor3dv, glColor3f, glColor3fv, glColor3i, glColor3iv, glColor3s, glColor3sv, glColor3ub, glColor3ubv, glColor3ui, glColor3uiv, glColor3us, glColor3usv, glColor4b, glColor4bv, glColor4d, glColor4dv, glColor4f, glColor4fv, glColor4i, glColor4iv, glColor4s, glColor4sv, glColor4ub, glColor4ubv, glColor4ui, glColor4uiv, glColor4us, glColor4usv, glColorMask, glColorMaski, glColorMaterial, glColorP3ui, glColorP3uiv, glColorP4ui, glColorP4uiv, glColorPointer, glCompileShader, glCompressedTexImage1D, glCompressedTexImage2D, glCompressedTexImage3D, glCompressedTexSubImage1D, glCompressedTexSubImage2D, glCompressedTexSubImage3D, glCopyBufferSubData, glCopyImageSubData, glCopyPixels, glCopyTexImage1D, glCopyTexImage2D, glCopyTexSubImage1D, glCopyTexSubImage2D, glCopyTexSubImage3D, glCreateProgram, glCreateShader, glCreateShaderProgramv, glCullFace, glDebugMessageCallback, glDebugMessageControl, glDebugMessageInsert, glDeleteBuffers, glDeleteFramebuffers, glDeleteLists, glDeleteProgram, glDeleteProgramPipelines, glDeleteQueries, glDeleteRenderbuffers, glDeleteSamplers, glDeleteShader, glDeleteSync, glDeleteTextures, glDeleteTransformFeedbacks, glDeleteVertexArrays, glDepthFunc, glDepthMask, glDepthRange, glDepthRangeArrayv, glDepthRangeIndexed, glDepthRangef, glDetachShader, glDisable, glDisableClientState, glDisableVertexAttribArray, glDisablei, glDispatchCompute, glDispatchComputeIndirect, glDrawArrays, glDrawArraysIndirect, glDrawArraysInstanced, glDrawArraysInstancedBaseInstance, glDrawBuffer, glDrawBuffers, glDrawElements, glDrawElementsBaseVertex, glDrawElementsIndirect, glDrawElementsInstanced, glDrawElementsInstancedBaseInstance, glDrawElementsInstancedBaseVertex, glDrawElementsInstancedBaseVertexBaseInstance, glDrawPixels, glDrawRangeElements, glDrawRangeElementsBaseVertex, glDrawTransformFeedback, glDrawTransformFeedbackInstanced, glDrawTransformFeedbackStream, glDrawTransformFeedbackStreamInstanced, glEdgeFlag, glEdgeFlagPointer, glEdgeFlagv, glEnable, glEnableClientState, glEnableVertexAttribArray, glEnablei, glEnd, glEndConditionalRender, glEndList, glEndQuery, glEndQueryIndexed, glEndTransformFeedback, glEvalCoord1d, glEvalCoord1dv, glEvalCoord1f, glEvalCoord1fv, glEvalCoord2d, glEvalCoord2dv, glEvalCoord2f, glEvalCoord2fv, glEvalMesh1, glEvalMesh2, glEvalPoint1, glEvalPoint2, glFeedbackBuffer, glFenceSync, glFinish, glFlush, glFlushMappedBufferRange, glFogCoordPointer, glFogCoordd, glFogCoorddv, glFogCoordf, glFogCoordfv, glFogf, glFogfv, glFogi, glFogiv, glFramebufferParameteri, glFramebufferRenderbuffer, glFramebufferTexture, glFramebufferTexture1D, glFramebufferTexture2D, glFramebufferTexture3D, glFramebufferTextureLayer, glFrontFace, glFrustum, glGenBuffers, glGenFramebuffers, glGenLists, glGenProgramPipelines, glGenQueries, glGenRenderbuffers, glGenSamplers, glGenTextures, glGenTransformFeedbacks, glGenVertexArrays, glGenerateMipmap, glGetActiveAtomicCounterBufferiv, glGetActiveAttrib, glGetActiveSubroutineName, glGetActiveSubroutineUniformName, glGetActiveSubroutineUniformiv, glGetActiveUniform, glGetActiveUniformBlockName, glGetActiveUniformBlockiv, glGetActiveUniformName, glGetActiveUniformsiv, glGetAttachedShaders, glGetAttribLocation, glGetBooleani_v, glGetBooleanv, glGetBufferParameteri64v, glGetBufferParameteriv, glGetBufferPointerv, glGetBufferSubData, glGetClipPlane, glGetCompressedTexImage, glGetDebugMessageLog, glGetDoublei_v, glGetDoublev, glGetError, glGetFloati_v, glGetFloatv, glGetFragDataIndex, glGetFragDataLocation, glGetFramebufferAttachmentParameteriv, glGetFramebufferParameteriv, glGetInteger64i_v, glGetInteger64v, glGetIntegeri_v, glGetIntegerv, glGetInternalformati64v, glGetInternalformativ, glGetLightfv, glGetLightiv, glGetMapdv, glGetMapfv, glGetMapiv, glGetMaterialfv, glGetMaterialiv, glGetMultisamplefv, glGetObjectLabel, glGetObjectPtrLabel, glGetPixelMapfv, glGetPixelMapuiv, glGetPixelMapusv, glGetPointerv, glGetPolygonStipple, glGetProgramBinary, glGetProgramInfoLog, glGetProgramInterfaceiv, glGetProgramPipelineInfoLog, glGetProgramPipelineiv, glGetProgramResourceIndex, glGetProgramResourceLocation, glGetProgramResourceLocationIndex, glGetProgramResourceName, glGetProgramResourceiv, glGetProgramStageiv, glGetProgramiv, glGetQueryIndexediv, glGetQueryObjecti64v, glGetQueryObjectiv, glGetQueryObjectui64v, glGetQueryObjectuiv, glGetQueryiv, glGetRenderbufferParameteriv, glGetSamplerParameterIiv, glGetSamplerParameterIuiv, glGetSamplerParameterfv, glGetSamplerParameteriv, glGetShaderInfoLog, glGetShaderPrecisionFormat, glGetShaderSource, glGetShaderiv, glGetString, glGetStringi, glGetSubroutineIndex, glGetSubroutineUniformLocation, glGetSynciv, glGetTexEnvfv, glGetTexEnviv, glGetTexGendv, glGetTexGenfv, glGetTexGeniv, glGetTexImage, glGetTexLevelParameterfv, glGetTexLevelParameteriv, glGetTexParameterIiv, glGetTexParameterIuiv, glGetTexParameterfv, glGetTexParameteriv, glGetTransformFeedbackVarying, glGetUniformBlockIndex, glGetUniformIndices, glGetUniformLocation, glGetUniformSubroutineuiv, glGetUniformdv, glGetUniformfv, glGetUniformiv, glGetUniformuiv, glGetVertexAttribIiv, glGetVertexAttribIuiv, glGetVertexAttribLdv, glGetVertexAttribPointerv, glGetVertexAttribdv, glGetVertexAttribfv, glGetVertexAttribiv, glHint, glIndexMask, glIndexPointer, glIndexd, glIndexdv, glIndexf, glIndexfv, glIndexi, glIndexiv, glIndexs, glIndexsv, glIndexub, glIndexubv, glInitNames, glInterleavedArrays, glInvalidateBufferData, glInvalidateBufferSubData, glInvalidateFramebuffer, glInvalidateSubFramebuffer, glInvalidateTexImage, glInvalidateTexSubImage, glIsBuffer, glIsEnabled, glIsEnabledi, glIsFramebuffer, glIsList, glIsProgram, glIsProgramPipeline, glIsQuery, glIsRenderbuffer, glIsSampler, glIsShader, glIsSync, glIsTexture, glIsTransformFeedback, glIsVertexArray, glLightModelf, glLightModelfv, glLightModeli, glLightModeliv, glLightf, glLightfv, glLighti, glLightiv, glLineStipple, glLineWidth, glLinkProgram, glListBase, glLoadIdentity, glLoadMatrixd, glLoadMatrixf, glLoadName, glLoadTransposeMatrixd, glLoadTransposeMatrixf, glLogicOp, glMap1d, glMap1f, glMap2d, glMap2f, glMapBuffer, glMapBufferRange, glMapGrid1d, glMapGrid1f, glMapGrid2d, glMapGrid2f, glMaterialf, glMaterialfv, glMateriali, glMaterialiv, glMatrixMode, glMemoryBarrier, glMinSampleShading, glMultMatrixd, glMultMatrixf, glMultTransposeMatrixd, glMultTransposeMatrixf, glMultiDrawArrays, glMultiDrawArraysIndirect, glMultiDrawElements, glMultiDrawElementsBaseVertex, glMultiDrawElementsIndirect, glMultiTexCoord1d, glMultiTexCoord1dv, glMultiTexCoord1f, glMultiTexCoord1fv, glMultiTexCoord1i, glMultiTexCoord1iv, glMultiTexCoord1s, glMultiTexCoord1sv, glMultiTexCoord2d, glMultiTexCoord2dv, glMultiTexCoord2f, glMultiTexCoord2fv, glMultiTexCoord2i, glMultiTexCoord2iv, glMultiTexCoord2s, glMultiTexCoord2sv, glMultiTexCoord3d, glMultiTexCoord3dv, glMultiTexCoord3f, glMultiTexCoord3fv, glMultiTexCoord3i, glMultiTexCoord3iv, glMultiTexCoord3s, glMultiTexCoord3sv, glMultiTexCoord4d, glMultiTexCoord4dv, glMultiTexCoord4f, glMultiTexCoord4fv, glMultiTexCoord4i, glMultiTexCoord4iv, glMultiTexCoord4s, glMultiTexCoord4sv, glMultiTexCoordP1ui, glMultiTexCoordP1uiv, glMultiTexCoordP2ui, glMultiTexCoordP2uiv, glMultiTexCoordP3ui, glMultiTexCoordP3uiv, glMultiTexCoordP4ui, glMultiTexCoordP4uiv, glNewList, glNormal3b, glNormal3bv, glNormal3d, glNormal3dv, glNormal3f, glNormal3fv, glNormal3i, glNormal3iv, glNormal3s, glNormal3sv, glNormalP3ui, glNormalP3uiv, glNormalPointer, glObjectLabel, glObjectPtrLabel, glOrtho, glPassThrough, glPatchParameterfv, glPatchParameteri, glPauseTransformFeedback, glPixelMapfv, glPixelMapuiv, glPixelMapusv, glPixelStoref, glPixelStorei, glPixelTransferf, glPixelTransferi, glPixelZoom, glPointParameterf, glPointParameterfv, glPointParameteri, glPointParameteriv, glPointSize, glPolygonMode, glPolygonOffset, glPolygonStipple, glPopAttrib, glPopClientAttrib, glPopDebugGroup, glPopMatrix, glPopName, glPrimitiveRestartIndex, glPrioritizeTextures, glProgramBinary, glProgramParameteri, glProgramUniform1d, glProgramUniform1dv, glProgramUniform1f, glProgramUniform1fv, glProgramUniform1i, glProgramUniform1iv, glProgramUniform1ui, glProgramUniform1uiv, glProgramUniform2d, glProgramUniform2dv, glProgramUniform2f, glProgramUniform2fv, glProgramUniform2i, glProgramUniform2iv, glProgramUniform2ui, glProgramUniform2uiv, glProgramUniform3d, glProgramUniform3dv, glProgramUniform3f, glProgramUniform3fv, glProgramUniform3i, glProgramUniform3iv, glProgramUniform3ui, glProgramUniform3uiv, glProgramUniform4d, glProgramUniform4dv, glProgramUniform4f, glProgramUniform4fv, glProgramUniform4i, glProgramUniform4iv, glProgramUniform4ui, glProgramUniform4uiv, glProgramUniformMatrix2dv, glProgramUniformMatrix2fv, glProgramUniformMatrix2x3dv, glProgramUniformMatrix2x3fv, glProgramUniformMatrix2x4dv, glProgramUniformMatrix2x4fv, glProgramUniformMatrix3dv, glProgramUniformMatrix3fv, glProgramUniformMatrix3x2dv, glProgramUniformMatrix3x2fv, glProgramUniformMatrix3x4dv, glProgramUniformMatrix3x4fv, glProgramUniformMatrix4dv, glProgramUniformMatrix4fv, glProgramUniformMatrix4x2dv, glProgramUniformMatrix4x2fv, glProgramUniformMatrix4x3dv, glProgramUniformMatrix4x3fv, glProvokingVertex, glPushAttrib, glPushClientAttrib, glPushDebugGroup, glPushMatrix, glPushName, glQueryCounter, glRasterPos2d, glRasterPos2dv, glRasterPos2f, glRasterPos2fv, glRasterPos2i, glRasterPos2iv, glRasterPos2s, glRasterPos2sv, glRasterPos3d, glRasterPos3dv, glRasterPos3f, glRasterPos3fv, glRasterPos3i, glRasterPos3iv, glRasterPos3s, glRasterPos3sv, glRasterPos4d, glRasterPos4dv, glRasterPos4f, glRasterPos4fv, glRasterPos4i, glRasterPos4iv, glRasterPos4s, glRasterPos4sv, glReadBuffer, glReadPixels, glRectd, glRectdv, glRectf, glRectfv, glRecti, glRectiv, glRects, glRectsv, glReleaseShaderCompiler, glRenderMode, glRenderbufferStorage, glRenderbufferStorageMultisample, glResumeTransformFeedback, glRotated, glRotatef, glSampleCoverage, glSampleMaski, glSamplerParameterIiv, glSamplerParameterIuiv, glSamplerParameterf, glSamplerParameterfv, glSamplerParameteri, glSamplerParameteriv, glScaled, glScalef, glScissor, glScissorArrayv, glScissorIndexed, glScissorIndexedv, glSecondaryColor3b, glSecondaryColor3bv, glSecondaryColor3d, glSecondaryColor3dv, glSecondaryColor3f, glSecondaryColor3fv, glSecondaryColor3i, glSecondaryColor3iv, glSecondaryColor3s, glSecondaryColor3sv, glSecondaryColor3ub, glSecondaryColor3ubv, glSecondaryColor3ui, glSecondaryColor3uiv, glSecondaryColor3us, glSecondaryColor3usv, glSecondaryColorP3ui, glSecondaryColorP3uiv, glSecondaryColorPointer, glSelectBuffer, glShadeModel, glShaderBinary, glShaderSource, glShaderStorageBlockBinding, glStencilFunc, glStencilFuncSeparate, glStencilMask, glStencilMaskSeparate, glStencilOp, glStencilOpSeparate, glTexBuffer, glTexBufferRange, glTexCoord1d, glTexCoord1dv, glTexCoord1f, glTexCoord1fv, glTexCoord1i, glTexCoord1iv, glTexCoord1s, glTexCoord1sv, glTexCoord2d, glTexCoord2dv, glTexCoord2f, glTexCoord2fv, glTexCoord2i, glTexCoord2iv, glTexCoord2s, glTexCoord2sv, glTexCoord3d, glTexCoord3dv, glTexCoord3f, glTexCoord3fv, glTexCoord3i, glTexCoord3iv, glTexCoord3s, glTexCoord3sv, glTexCoord4d, glTexCoord4dv, glTexCoord4f, glTexCoord4fv, glTexCoord4i, glTexCoord4iv, glTexCoord4s, glTexCoord4sv, glTexCoordP1ui, glTexCoordP1uiv, glTexCoordP2ui, glTexCoordP2uiv, glTexCoordP3ui, glTexCoordP3uiv, glTexCoordP4ui, glTexCoordP4uiv, glTexCoordPointer, glTexEnvf, glTexEnvfv, glTexEnvi, glTexEnviv, glTexGend, glTexGendv, glTexGenf, glTexGenfv, glTexGeni, glTexGeniv, glTexImage1D, glTexImage2D, glTexImage2DMultisample, glTexImage3D, glTexImage3DMultisample, glTexParameterIiv, glTexParameterIuiv, glTexParameterf, glTexParameterfv, glTexParameteri, glTexParameteriv, glTexStorage1D, glTexStorage2D, glTexStorage2DMultisample, glTexStorage3D, glTexStorage3DMultisample, glTexSubImage1D, glTexSubImage2D, glTexSubImage3D, glTextureView, glTransformFeedbackVaryings, glTranslated, glTranslatef, glUniform1d, glUniform1dv, glUniform1f, glUniform1fv, glUniform1i, glUniform1iv, glUniform1ui, glUniform1uiv, glUniform2d, glUniform2dv, glUniform2f, glUniform2fv, glUniform2i, glUniform2iv, glUniform2ui, glUniform2uiv, glUniform3d, glUniform3dv, glUniform3f, glUniform3fv, glUniform3i, glUniform3iv, glUniform3ui, glUniform3uiv, glUniform4d, glUniform4dv, glUniform4f, glUniform4fv, glUniform4i, glUniform4iv, glUniform4ui, glUniform4uiv, glUniformBlockBinding, glUniformMatrix2dv, glUniformMatrix2fv, glUniformMatrix2x3dv, glUniformMatrix2x3fv, glUniformMatrix2x4dv, glUniformMatrix2x4fv, glUniformMatrix3dv, glUniformMatrix3fv, glUniformMatrix3x2dv, glUniformMatrix3x2fv, glUniformMatrix3x4dv, glUniformMatrix3x4fv, glUniformMatrix4dv, glUniformMatrix4fv, glUniformMatrix4x2dv, glUniformMatrix4x2fv, glUniformMatrix4x3dv, glUniformMatrix4x3fv, glUniformSubroutinesuiv, glUnmapBuffer, glUseProgram, glUseProgramStages, glValidateProgram, glValidateProgramPipeline, glVertex2d, glVertex2dv, glVertex2f, glVertex2fv, glVertex2i, glVertex2iv, glVertex2s, glVertex2sv, glVertex3d, glVertex3dv, glVertex3f, glVertex3fv, glVertex3i, glVertex3iv, glVertex3s, glVertex3sv, glVertex4d, glVertex4dv, glVertex4f, glVertex4fv, glVertex4i, glVertex4iv, glVertex4s, glVertex4sv, glVertexAttrib1d, glVertexAttrib1dv, glVertexAttrib1f, glVertexAttrib1fv, glVertexAttrib1s, glVertexAttrib1sv, glVertexAttrib2d, glVertexAttrib2dv, glVertexAttrib2f, glVertexAttrib2fv, glVertexAttrib2s, glVertexAttrib2sv, glVertexAttrib3d, glVertexAttrib3dv, glVertexAttrib3f, glVertexAttrib3fv, glVertexAttrib3s, glVertexAttrib3sv, glVertexAttrib4Nbv, glVertexAttrib4Niv, glVertexAttrib4Nsv, glVertexAttrib4Nub, glVertexAttrib4Nubv, glVertexAttrib4Nuiv, glVertexAttrib4Nusv, glVertexAttrib4bv, glVertexAttrib4d, glVertexAttrib4dv, glVertexAttrib4f, glVertexAttrib4fv, glVertexAttrib4iv, glVertexAttrib4s, glVertexAttrib4sv, glVertexAttrib4ubv, glVertexAttrib4uiv, glVertexAttrib4usv, glVertexAttribBinding, glVertexAttribDivisor, glVertexAttribFormat, glVertexAttribI1i, glVertexAttribI1iv, glVertexAttribI1ui, glVertexAttribI1uiv, glVertexAttribI2i, glVertexAttribI2iv, glVertexAttribI2ui, glVertexAttribI2uiv, glVertexAttribI3i, glVertexAttribI3iv, glVertexAttribI3ui, glVertexAttribI3uiv, glVertexAttribI4bv, glVertexAttribI4i, glVertexAttribI4iv, glVertexAttribI4sv, glVertexAttribI4ubv, glVertexAttribI4ui, glVertexAttribI4uiv, glVertexAttribI4usv, glVertexAttribIFormat, glVertexAttribIPointer, glVertexAttribL1d, glVertexAttribL1dv, glVertexAttribL2d, glVertexAttribL2dv, glVertexAttribL3d, glVertexAttribL3dv, glVertexAttribL4d, glVertexAttribL4dv, glVertexAttribLFormat, glVertexAttribLPointer, glVertexAttribP1ui, glVertexAttribP1uiv, glVertexAttribP2ui, glVertexAttribP2uiv, glVertexAttribP3ui, glVertexAttribP3uiv, glVertexAttribP4ui, glVertexAttribP4uiv, glVertexAttribPointer, glVertexBindingDivisor, glVertexP2ui, glVertexP2uiv, glVertexP3ui, glVertexP3uiv, glVertexP4ui, glVertexP4uiv, glVertexPointer, glViewport, glViewportArrayv, glViewportIndexedf, glViewportIndexedfv, glWaitSync, glWindowPos2d, glWindowPos2dv, glWindowPos2f, glWindowPos2fv, glWindowPos2i, glWindowPos2iv, glWindowPos2s, glWindowPos2sv, glWindowPos3d, glWindowPos3dv, glWindowPos3f, glWindowPos3fv, glWindowPos3i, glWindowPos3iv, glWindowPos3s, glWindowPos3sv ) where import Graphics.Rendering.OpenGL.Raw.Types import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/Compatibility44.hs
bsd-3-clause
62,395
0
4
8,126
8,092
5,402
2,690
2,685
0
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE NoMonoLocalBinds #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} module Yesod.Squealer.Handler.Version ( getVersionR , putVersionR , deleteVersionR , getPredecessorR , getSuccessorR , sirenVersion , VersionData ( VersionData , attributes , references , revocation , table , timestamp , version ) ) where import Control.Applicative (pure) import Control.Arrow.Unicode ((⁂)) import Control.Category.Unicode ((∘)) import Control.Lens.Fold (hasn't) import Control.Lens.Lens ((&), (<&>)) import Control.Lens.Setter ((%~)) import Control.Monad (mzero, void) import Control.Monad.Unicode ((=≪)) import Data.Aeson.Types ((.=), object) import Data.Eq.Unicode ((≡)) import Data.Foldable (find, foldl') import Data.Function (($)) import Data.Functor ((<$), (<$>), fmap) import Data.List (length, null, partition, splitAt, zip) import Data.Map (delete, empty, fromList, lookup) import Data.Maybe (Maybe(Just), catMaybes, fromMaybe, maybe) import Data.Monoid.Unicode ((⊕)) import Data.Siren ((⤠), RenderLink, Entity(entityActions, entityLinks, entityProperties, entitySubEntities), Field(Field, fieldName, fieldTitle, fieldType, fieldValue), FieldType(FieldType), actionFields, actionMethod, actionTitle, embedLink, mkAction, mkEntity) import Data.Text (Text, unpack) import Data.Text.Lens (unpacked) import Data.Traversable (sequence) import Data.Tuple (fst) import Database.HsSqlPpp.Annotation (emptyAnnotation) import Database.HsSqlPpp.Ast (Distinct(Dupes), Name(Name), NameComponent(Nmc), QueryExpr(Select), SelectItem(SelExp), SelectList(SelectList), SetClause(SetClause), Statement(Delete, QueryStatement, Update), TableAlias(NoAlias), TableRef(Tref)) import Database.HsSqlPpp.Quote (sqlExpr) import Database.PostgreSQL.Simple (execute_, query_) import Database.Squealer.Types (Column(Reference, colname, target), Database(Database, dbname, tables), Table(Table, columns, key, tablename), _Reference, colname, escapeIdentifier, unIdentifier) import Network.HTTP.Types.Status (seeOther303) import Yesod.Core (Route) import Yesod.Core.Content (TypedContent) import Yesod.Core.Handler (getYesod, notFound, provideRep, redirectWith, runRequestBody, selectRep) import Yesod.Squealer.Handler (escape, escapeFieldName, handleParameters, runSQL, runSQLDebug) import Yesod.Squealer.Routes import Prelude (error) -- FIXME: remove this once everything is implemented data VersionData = VersionData { table ∷ Table , version ∷ Text , timestamp ∷ Text , revocation ∷ Maybe Text , attributes ∷ [(Column, Maybe Text)] , references ∷ [(Column, Maybe Text)] } sirenVersion ∷ RenderLink (Route Squealer) ⇒ VersionData → Entity sirenVersion VersionData {..} = (mkEntity $ ?render self) -- TODO: use lenses { entityProperties , entitySubEntities , entityLinks , entityActions } where Table {..} = table tablename' = unIdentifier tablename self = (VersionR tablename' version, empty) entityProperties = [ "attributes" .= object (attributes <&> \ (l, v) → unIdentifier (colname l) .= v) , "metadata" .= metadata ] where metadata = object [ "timestamp" .= timestamp , "revocation" .= revocation ] entitySubEntities = referenceLink <$> (catMaybes $ sequence <$> references) where referenceLink (column, targetVersion) = embedLink ["reference"] $ [?render (ColumnR tablename' $ unIdentifier colname, empty)] ⤠ VersionR (unIdentifier target) targetVersion where Reference {..} = column entityLinks = [ ["collection" ] ⤠ RowsR tablename' , ["profile" ] ⤠ TableR tablename' , ["predecessor-version"] ⤠ PredecessorR tablename' version , ["successor-version" ] ⤠ SuccessorR tablename' version ] entityActions = fromMaybe actions $ [] <$ revocation where actions = [ deleteAction , updateAction ] where updateAction = (mkAction "update" href) { actionTitle = pure "Update" , actionMethod = "PUT" , actionFields } where href = ?render self actionFields = toField <$> attributes ⊕ references where toField (column, value) = Field {..} where colname' = unIdentifier $ colname column fieldName = colname' & unpacked %~ escapeFieldName fieldType = FieldType $ ?render (ColumnR tablename' colname', empty) -- TODO: maybe this should use predefined types in some cases? fieldValue = value fieldTitle = pure colname' deleteAction = (mkAction "delete" href) { actionTitle = pure "Delete" , actionMethod = "DELETE" } where href = ?render self getVersionR ∷ Text → Text → SquealerHandler TypedContent getVersionR tablename' version = handleParameters adjustParameters respond where adjustParameters = delete "embedding" respond squealer _parameters = maybe notFound found $ find my tables where Squealer {..} = squealer Database {..} = database my = (tablename' ≡) ∘ unIdentifier ∘ tablename found table @ Table {..} = do [Just timestamp : revocation : versionData] ← runSQL query_ versionSQL let (attributes, references) = zip attributeColumns ⁂ zip referenceColumns $ splitAt (length attributeColumns) versionData toView VersionData {..} where (attributeColumns, referenceColumns) = partition (hasn't _Reference) $ key ⊕ columns versionSQL = QueryStatement emptyAnnotation $ Select emptyAnnotation distinct projection relation condition grouping groupCondition order limit offset where distinct = Dupes projection = SelectList emptyAnnotation ∘ fmap qname $ [ "journal timestamp" , "end timestamp" ] ⊕ (attributeColumns <&> unIdentifier ∘ colname) ⊕ (referenceColumns <&> unIdentifier ∘ (⊕ " version") ∘ colname) where qname column = SelExp emptyAnnotation [sqlExpr|$i(column_sql) :: text|] where column_sql = table_sql ⊕ "." ⊕ escape "version" ⊕ "." ⊕ escape column relation = pure $ Tref emptyAnnotation versionTable alias where versionTable = Name emptyAnnotation $ Nmc <$> [table_sql, escape "version"] alias = NoAlias emptyAnnotation condition = pure [sqlExpr|$i(entry_column_sql) = $s(entry_sql)|] where entry_column_sql = version_view_sql ⊕ "." ⊕ escape "entry" entry_sql = unpack version grouping = mzero groupCondition = mzero order = mzero limit = mzero offset = mzero table_sql = escape tablename' version_view_sql = table_sql ⊕ "." ⊕ escape "version" toView versionData = selectRep $ do provideRep ∘ pure $ sirenVersion versionData putVersionR ∷ Text → Text → SquealerHandler () putVersionR tablename' version = do squealer ← getYesod bodyParameters ← fromList ∘ fst <$> runRequestBody respond squealer bodyParameters where respond squealer bodyParameters = maybe notFound found $ find my tables where Squealer {..} = squealer Database {..} = database my = (tablename' ≡) ∘ unIdentifier ∘ tablename found Table {..} = do void $ runSQLDebug execute_ sql redirectWith seeOther303 $ VersionR tablename' version -- TODO: catch exceptions and respond accordingly. -- if a column was specified but the table doesn’t have it, -- respond invalidArgs. -- FIXME: perhaps this should redirect at the new version -- instead of the now revoked current version. where sql = Update emptyAnnotation targetTable setClauses extraTables condition returning where targetTable = Name emptyAnnotation ∘ pure $ Nmc table_sql setClauses = toSetClause <$> key ⊕ columns where toSetClause column = SetClause emptyAnnotation name ∘ maybe [sqlExpr|NULL|] toExpression $ lookup fieldName bodyParameters where name = Nmc ∘ unpack ∘ escapeIdentifier $ columnName toExpression value = [sqlExpr|$s(value_sql)|] where value_sql = unpack value fieldName = (unpacked %~ escapeFieldName) ∘ unIdentifier $ columnName columnName = colname column extraTables = pure $ Tref emptyAnnotation name alias where name = Name emptyAnnotation [Nmc version_view_sql] alias = NoAlias emptyAnnotation condition = pure ∘ foldl' (∧) versionEntry $ if null key then pure "identity" else keyLabels where keyLabels = unIdentifier ∘ colname <$> key versionEntry = [sqlExpr|$i(entry_column_sql) = $s(entry_sql)|] where entry_column_sql = version_view_sql ⊕ "." ⊕ escape "entry" entry_sql = unpack version acc ∧ column = [sqlExpr|$(acc) and $i(table_column_sql) = $i(version_column_sql)|] where table_column_sql = table_sql ⊕ "." ⊕ column_sql version_column_sql = version_view_sql ⊕ "." ⊕ column_sql column_sql = escape column returning = mzero table_sql = escape tablename' version_view_sql = table_sql ⊕ "." ⊕ escape "version" deleteVersionR ∷ Text → Text → SquealerHandler () deleteVersionR tablename' version = respond =≪ getYesod where respond squealer = maybe notFound found $ find my tables where Squealer {..} = squealer Database {..} = database my = (tablename' ≡) ∘ unIdentifier ∘ tablename found Table {..} = do void $ runSQLDebug execute_ sql -- FIXME: handle errors. Breaking a foreign key constraint with ON DELETE RESTRICT should not cause a 500 Internal Server Error. also, think about 404s. redirectWith seeOther303 $ VersionR tablename' version where sql = Delete emptyAnnotation targetTable relation condition returning where targetTable = Name emptyAnnotation ∘ pure $ Nmc table_sql relation = pure ∘ Tref emptyAnnotation versionTable $ NoAlias emptyAnnotation where versionTable = Name emptyAnnotation $ Nmc <$> [table_sql, escape "version"] condition = pure ∘ foldl' (∧) versionEntry $ if null key then pure "identity" else keyLabels where keyLabels = unIdentifier ∘ colname <$> key versionEntry = [sqlExpr|$i(entry_column_sql) = $s(entry_sql)|] where entry_column_sql = version_view_sql ⊕ "." ⊕ escape "entry" entry_sql = unpack version acc ∧ column = [sqlExpr|$(acc) and $i(table_column_sql) = $i(version_column_sql)|] where table_column_sql = table_sql ⊕ "." ⊕ column_sql version_column_sql = version_view_sql ⊕ "." ⊕ column_sql column_sql = escape column returning = mzero table_sql = escape tablename' version_view_sql = table_sql ⊕ "." ⊕ escape "version" getPredecessorR ∷ Text → Text → SquealerHandler TypedContent getPredecessorR = error "unimplemented" -- TODO getSuccessorR ∷ Text → Text → SquealerHandler TypedContent getSuccessorR _ _ = error "unimplemented" -- TODO
mgomezch/yesod-squealer
source/Yesod/Squealer/Handler/Version.hs
bsd-3-clause
15,974
1
20
6,951
2,852
1,610
1,242
-1
-1
module Lists (module Lists, module List) where import OpTypes import List import Products mergeOrd :: OrdOp a -> [a] -> [a] -> [a] merge :: Ord a => [a] -> [a] -> [a] unionMany :: Eq a => [[a]] -> [a] mapFst :: (a -> x) -> [(a,b)] -> [(x,b)] mapSnds :: (b -> y) -> [(a, [b])] -> [(a, [y])] mapFstSnds :: (a -> x) -> (b -> y) -> [(a, [b])] -> [(x, [y])] subset :: Eq a => [a] -> [a] -> Bool infixl 1 |$| (|$|) :: [a -> b] -> [a] -> [b] (\\\) :: Eq a => [a] -> [a] -> [a] -- property srtedOrd leq xs = (m `leq` n) ==> (xs !! m) `leq` (xs !! n) -- property sorted = sortedOrd (<=) -- property noDuplEq eq xs = (xs !! m) `eq` (xs !! n) ==> m === n -- property noDupl = noDupl (==) -- property mergeOrd = sortedOrd leq xs /\ sortedOrd leq ys -- ==> sortedOrd leq (mergeOrd leq xs ys) mergeOrd leq [] ys = ys mergeOrd leq xs [] = xs mergeOrd leq a@(x:xs) b@(y:ys) | x `leq` y = x : mergeOrd leq xs b | otherwise = y : mergeOrd leq a ys -- property merge = mergeOrd (<=) merge = mergeOrd (<=) singleton [_] = True singleton _ = False xs `subset` ys = all (`elem` ys) xs unionMany = nub . concat mapFst f = map (f >< id) mapSnds g = map (id >< map g) mapFstSnds f g = map (f >< map g) (|$|) = zipWith ($) xs \\\ ys = filter (`notElem` ys) xs --elemBy,notElemBy :: (a->a->Bool) -> a -> [a] -> Bool elemBy eq x = not . notElemBy eq x notElemBy eq x = null . filter (eq x)
forste/haReFork
tools/base/lib/Lists.hs
bsd-3-clause
1,583
0
10
524
644
362
282
31
1
{-# LANGUAGE MultiParamTypeClasses,FunctionalDependencies,FlexibleInstances #-} module Data.AtomContainer (AtomContainer(..) ,ExprOrdering(..)) where import Data.Map as Map -- | Represents data structures which can store atomic expressions class Ord b => AtomContainer a b | a -> b where atomsTrue :: a -- ^ The container representing all possible values atomSingleton :: Bool -> b -> a -- ^ A container containing just a single restriction on the values. compareAtoms :: a -> a -> ExprOrdering -- ^ Compare the value spaces defined by the containers mergeAtoms :: a -> a -> Maybe a -- ^ Merge the containers together, resulting in a container which represents the intersection between the two. -- | Represents the relations in which two expressions can stand data ExprOrdering = EEQ -- ^ Both expressions define the same value space | ENEQ -- ^ The expressions define non-overlapping value spaces | EGT -- ^ The value space of the second expression is contained by the first | ELT -- ^ The value space of the first expression is contained by the second | EUNK -- ^ The expressions have overlapping value spaces or the relation isn't known deriving (Show,Eq,Ord) instance Ord a => AtomContainer (Map a Bool) a where atomsTrue = Map.empty atomSingleton t p = Map.singleton p t compareAtoms x y | x == y = EEQ | Map.isSubmapOf x y = EGT | Map.isSubmapOf y x = ELT | otherwise = ENEQ mergeAtoms = mergeAlphabet mergeAlphabet :: Ord a => Map a Bool -> Map a Bool -> Maybe (Map a Bool) mergeAlphabet a1 a2 = if confl then Nothing else Just nmp where (confl,nmp) = Map.mapAccum (\hasC (x,y) -> (hasC || x/=y,x)) False $ Map.unionWith (\(x1,_) (y1,_) -> (x1,y1)) (fmap (\x -> (x,x)) a1) (fmap (\x -> (x,x)) a2)
hguenther/gtl
lib/Data/AtomContainer.hs
bsd-3-clause
1,920
0
13
509
459
252
207
33
2
module Main where import Graphics.X11.Turtle import System.Environment import Control.Concurrent import Control.Monad import Data.Word type Color = String main :: IO () main = do n <- fmap (read . head) getArgs f <- openField onkeypress f $ return . (/= 'q') t <- newTurtle f penup t speed t "slowest" threadDelay 1000000 h <- windowHeight t w <- windowWidth t hideturtle t goto t (- w / 2) (h / 2) mapM_ (turtleWrite t h) $ fizzBuzz n threadDelay 5000000 replicateM_ (n * 5) $ undo t waitField f turtleWrite :: Turtle -> Double -> (Color, String) -> IO () turtleWrite t h (c, s) = do pencolor t c setheading t $ - 90 forward t 10 (_, y) <- position t when (y < - h / 2) $ do sety t $ h / 2 - 10 setheading t 0 forward t 50 write t "" 8 s fizzBuzz :: Int -> [(Color, String)] fizzBuzz n = map fizzBuzzOne [1 .. n] fizzBuzzOne :: Int -> (Color, String) fizzBuzzOne n | n `mod` 5 /= 0 && n `mod` 3 /= 0 = ("black", show n) | n `mod` 5 /= 0 = ("red", "Fizz") | n `mod` 3 /= 0 = ("blue", "Buzz") | otherwise = ("violet", "FizzBuzz")
YoshikuniJujo/xturtle_haskell
tests/fizzBuzzColorName.hs
bsd-3-clause
1,066
0
13
249
553
273
280
43
1
{-# LANGUAGE CPP #-} module Language.Java.Parser ( parser, compilationUnit, packageDecl, importDecl, typeDecl, classDecl, interfaceDecl, memberDecl, fieldDecl, methodDecl, constrDecl, interfaceMemberDecl, absMethodDecl, formalParams, formalParam, modifier, varDecls, varDecl, block, blockStmt, stmt, stmtExp, exp, primary, literal, ttype, primType, refType, classType, resultType, typeParams, typeParam, name, ident, empty, list, list1, seplist, seplist1, opt, bopt, lopt, comma, semiColon, period, colon ) where import Language.Java.Lexer ( L(..), Token(..), lexer) import Language.Java.Syntax import Text.Parsec hiding ( Empty ) import Text.Parsec.Pos import Prelude hiding ( exp, catch, (>>), (>>=) ) import qualified Prelude as P ( (>>), (>>=) ) import Data.Maybe ( isJust, catMaybes ) import Control.Monad ( ap ) #if __GLASGOW_HASKELL__ < 707 import Control.Applicative ( (<$>), (<$), (<*) ) -- Since I cba to find the instance Monad m => Applicative m declaration. (<*>) :: Monad m => m (a -> b) -> m a -> m b (<*>) = ap infixl 4 <*> #else import Control.Applicative ( (<$>), (<$), (<*), (<*>) ) #endif type P = Parsec [L Token] () -- A trick to allow >> and >>=, normally infixr 1, to be -- used inside branches of <|>, which is declared as infixl 1. -- There are no clashes with other operators of precedence 2. (>>) = (P.>>) (>>=) = (P.>>=) infixr 2 >>, >>= -- Note also when reading that <$> is infixl 4 and thus has -- lower precedence than all the others (>>, >>=, and <|>). ---------------------------------------------------------------------------- -- Top-level parsing parseCompilationUnit :: String -> Either ParseError CompilationUnit parseCompilationUnit inp = runParser compilationUnit () "" (lexer inp) parser p = runParser p () "" . lexer --class Parse a where -- parse :: String -> a ---------------------------------------------------------------------------- -- Packages and compilation units compilationUnit :: P CompilationUnit compilationUnit = do mpd <- opt packageDecl ids <- list importDecl tds <- list typeDecl eof return $ CompilationUnit mpd ids (catMaybes tds) packageDecl :: P PackageDecl packageDecl = do tok KW_Package n <- name semiColon return $ PackageDecl n importDecl :: P ImportDecl importDecl = do tok KW_Import st <- bopt $ tok KW_Static n <- name ds <- bopt $ period >> tok Op_Star semiColon return $ ImportDecl st n ds typeDecl :: P (Maybe TypeDecl) typeDecl = Just <$> classOrInterfaceDecl <|> const Nothing <$> semiColon ---------------------------------------------------------------------------- -- Declarations -- Class declarations classOrInterfaceDecl :: P TypeDecl classOrInterfaceDecl = do ms <- list modifier de <- (do cd <- classDecl return $ \ms -> ClassTypeDecl (cd ms)) <|> (do id <- interfaceDecl return $ \ms -> InterfaceTypeDecl (id ms)) return $ de ms classDecl :: P (Mod ClassDecl) classDecl = normalClassDecl <|> enumClassDecl normalClassDecl :: P (Mod ClassDecl) normalClassDecl = do tok KW_Class i <- ident tps <- lopt typeParams mex <- opt extends imp <- lopt implements bod <- classBody return $ \ms -> ClassDecl ms i tps ((fmap head) mex) imp bod extends :: P [RefType] extends = tok KW_Extends >> refTypeList implements :: P [RefType] implements = tok KW_Implements >> refTypeList enumClassDecl :: P (Mod ClassDecl) enumClassDecl = do tok KW_Enum i <- ident imp <- lopt implements bod <- enumBody return $ \ms -> EnumDecl ms i imp bod classBody :: P ClassBody classBody = ClassBody <$> braces classBodyStatements enumBody :: P EnumBody enumBody = braces $ do ecs <- seplist enumConst comma optional comma eds <- lopt enumBodyDecls return $ EnumBody ecs eds enumConst :: P EnumConstant enumConst = do id <- ident as <- lopt args mcb <- opt classBody return $ EnumConstant id as mcb enumBodyDecls :: P [Decl] enumBodyDecls = semiColon >> classBodyStatements classBodyStatements :: P [Decl] classBodyStatements = catMaybes <$> list classBodyStatement -- Interface declarations interfaceDecl :: P (Mod InterfaceDecl) interfaceDecl = do tok KW_Interface id <- ident tps <- lopt typeParams exs <- lopt extends bod <- interfaceBody return $ \ms -> InterfaceDecl ms id tps exs bod interfaceBody :: P InterfaceBody interfaceBody = InterfaceBody . catMaybes <$> braces (list interfaceBodyDecl) -- Declarations classBodyStatement :: P (Maybe Decl) classBodyStatement = (try $ do list1 semiColon return Nothing) <|> (try $ do mst <- bopt (tok KW_Static) blk <- block return $ Just $ InitDecl mst blk) <|> (do ms <- list modifier dec <- memberDecl return $ Just $ MemberDecl (dec ms)) memberDecl :: P (Mod MemberDecl) memberDecl = (try $ do cd <- classDecl return $ \ms -> MemberClassDecl (cd ms)) <|> (try $ do id <- interfaceDecl return $ \ms -> MemberInterfaceDecl (id ms)) <|> try fieldDecl <|> try methodDecl <|> constrDecl fieldDecl :: P (Mod MemberDecl) fieldDecl = endSemi $ do typ <- ttype vds <- varDecls return $ \ms -> FieldDecl ms typ vds methodDecl :: P (Mod MemberDecl) methodDecl = do tps <- lopt typeParams rt <- resultType id <- ident fps <- formalParams thr <- lopt throws bod <- methodBody return $ \ms -> MethodDecl ms tps rt id fps thr bod methodBody :: P MethodBody methodBody = MethodBody <$> (const Nothing <$> semiColon <|> Just <$> block) constrDecl :: P (Mod MemberDecl) constrDecl = do tps <- lopt typeParams id <- ident fps <- formalParams thr <- lopt throws bod <- constrBody return $ \ms -> ConstructorDecl ms tps id fps thr bod constrBody :: P ConstructorBody constrBody = braces $ do mec <- opt (try explConstrInv) bss <- list blockStmt return $ ConstructorBody mec bss explConstrInv :: P ExplConstrInv explConstrInv = endSemi $ (try $ do tas <- lopt refTypeArgs tok KW_This as <- args return $ ThisInvoke tas as) <|> (try $ do tas <- lopt refTypeArgs tok KW_Super as <- args return $ SuperInvoke tas as) <|> (do pri <- primary period tas <- lopt refTypeArgs tok KW_Super as <- args return $ PrimarySuperInvoke pri tas as) -- TODO: This should be parsed like class bodies, and post-checked. -- That would give far better error messages. interfaceBodyDecl :: P (Maybe MemberDecl) interfaceBodyDecl = semiColon >> return Nothing <|> do ms <- list modifier imd <- interfaceMemberDecl return $ Just (imd ms) interfaceMemberDecl :: P (Mod MemberDecl) interfaceMemberDecl = (do cd <- classDecl return $ \ms -> MemberClassDecl (cd ms)) <|> (do id <- interfaceDecl return $ \ms -> MemberInterfaceDecl (id ms)) <|> try fieldDecl <|> absMethodDecl absMethodDecl :: P (Mod MemberDecl) absMethodDecl = do tps <- lopt typeParams rt <- resultType id <- ident fps <- formalParams thr <- lopt throws semiColon return $ \ms -> MethodDecl ms tps rt id fps thr (MethodBody Nothing) throws :: P [RefType] throws = tok KW_Throws >> refTypeList -- Formal parameters formalParams :: P [FormalParam] formalParams = parens $ do fps <- seplist formalParam comma if validateFPs fps then return fps else fail "Only the last formal parameter may be of variable arity" where validateFPs :: [FormalParam] -> Bool validateFPs [] = True validateFPs [_] = True validateFPs (FormalParam _ _ b _ :xs) = not b formalParam :: P FormalParam formalParam = do ms <- list modifier typ <- ttype var <- bopt ellipsis vid <- varDeclId return $ FormalParam ms typ var vid ellipsis :: P () ellipsis = period >> period >> period -- Modifiers modifier :: P Modifier modifier = tok KW_Public >> return Public <|> tok KW_Protected >> return Protected <|> tok KW_Private >> return Private <|> tok KW_Abstract >> return Abstract <|> tok KW_Static >> return Static <|> tok KW_Strictfp >> return StrictFP <|> tok KW_Final >> return Final <|> tok KW_Native >> return Native <|> tok KW_Transient >> return Transient <|> tok KW_Volatile >> return Volatile <|> tok KW_Synchronized >> return Synchronised <|> Annotation <$> annotation annotation :: P Annotation annotation = flip ($) <$ tok Op_AtSign <*> name <*> ( try (flip NormalAnnotation <$> parens evlist) <|> try (flip SingleElementAnnotation <$> parens elementValue) <|> try (MarkerAnnotation <$ return ()) ) evlist :: P [(Ident, ElementValue)] evlist = seplist1 elementValuePair comma elementValuePair :: P (Ident, ElementValue) elementValuePair = (,) <$> ident <* tok Op_Equal <*> elementValue elementValue :: P ElementValue elementValue = EVVal <$> ( InitArray <$> arrayInit <|> InitExp <$> condExp ) <|> EVAnn <$> annotation ---------------------------------------------------------------------------- -- Variable declarations varDecls :: P [VarDecl] varDecls = seplist1 varDecl comma varDecl :: P VarDecl varDecl = do vid <- varDeclId mvi <- opt $ tok Op_Equal >> varInit return $ VarDecl vid mvi varDeclId :: P VarDeclId varDeclId = do id <- ident abs <- list arrBrackets return $ foldl (\f _ -> VarDeclArray . f) VarId abs id arrBrackets :: P () arrBrackets = brackets $ return () localVarDecl :: P ([Modifier], Type, [VarDecl]) localVarDecl = do ms <- list modifier typ <- ttype vds <- varDecls return (ms, typ, vds) varInit :: P VarInit varInit = InitArray <$> arrayInit <|> InitExp <$> exp arrayInit :: P ArrayInit arrayInit = braces $ do vis <- seplist varInit comma opt comma return $ ArrayInit vis ---------------------------------------------------------------------------- -- Statements block :: P Block block = braces $ Block <$> list blockStmt blockStmt :: P BlockStmt blockStmt = (try $ do ms <- list modifier cd <- classDecl return $ LocalClass (cd ms)) <|> (try $ do (m,t,vds) <- endSemi $ localVarDecl return $ LocalVars m t vds) <|> BlockStmt <$> stmt stmt :: P Stmt stmt = ifStmt <|> whileStmt <|> forStmt <|> labeledStmt <|> stmtNoTrail where ifStmt = do tok KW_If e <- parens exp (try $ do th <- stmtNSI tok KW_Else el <- stmt return $ IfThenElse e th el) <|> (do th <- stmt return $ IfThen e th) whileStmt = do tok KW_While e <- parens exp s <- stmt return $ While e s forStmt = do tok KW_For f <- parens $ (try $ do fi <- opt forInit semiColon e <- opt exp semiColon fu <- opt forUp return $ BasicFor fi e fu) <|> (do ms <- list modifier t <- ttype i <- ident colon e <- exp return $ EnhancedFor ms t i e) s <- stmt return $ f s labeledStmt = try $ do lbl <- ident colon s <- stmt return $ Labeled lbl s stmtNSI :: P Stmt stmtNSI = ifStmt <|> whileStmt <|> forStmt <|> labeledStmt <|> stmtNoTrail where ifStmt = do tok KW_If e <- parens exp th <- stmtNSI tok KW_Else el <- stmtNSI return $ IfThenElse e th el whileStmt = do tok KW_While e <- parens exp s <- stmtNSI return $ While e s forStmt = do tok KW_For f <- parens $ (try $ do fi <- opt forInit semiColon e <- opt exp semiColon fu <- opt forUp return $ BasicFor fi e fu) <|> (do ms <- list modifier t <- ttype i <- ident colon e <- exp return $ EnhancedFor ms t i e) s <- stmtNSI return $ f s labeledStmt = try $ do i <- ident colon s <- stmtNSI return $ Labeled i s stmtNoTrail :: P Stmt stmtNoTrail = -- empty statement const Empty <$> semiColon <|> -- inner block StmtBlock <$> block <|> -- assertions (endSemi $ do tok KW_Assert e <- exp me2 <- opt $ colon >> exp return $ Assert e me2) <|> -- switch stmts (do tok KW_Switch e <- parens exp sb <- switchBlock return $ Switch e sb) <|> -- do-while loops (endSemi $ do tok KW_Do s <- stmt tok KW_While e <- parens exp return $ Do s e) <|> -- break (endSemi $ do tok KW_Break mi <- opt ident return $ Break mi) <|> -- continue (endSemi $ do tok KW_Continue mi <- opt ident return $ Continue mi) <|> -- return (endSemi $ do tok KW_Return me <- opt exp return $ Return me) <|> -- synchronized (do tok KW_Synchronized e <- parens exp b <- block return $ Synchronized e b) <|> -- throw (endSemi $ do tok KW_Throw e <- exp return $ Throw e) <|> -- try-catch, both with and without a finally clause (do tok KW_Try b <- block c <- list catch mf <- opt $ tok KW_Finally >> block -- TODO: here we should check that there exists at -- least one catch or finally clause return $ Try b c mf) <|> -- expressions as stmts ExpStmt <$> endSemi stmtExp -- For loops forInit :: P ForInit forInit = (do try (do (m,t,vds) <- localVarDecl return $ ForLocalVars m t vds)) <|> (seplist1 stmtExp comma >>= return . ForInitExps) forUp :: P [Exp] forUp = seplist1 stmtExp comma -- Switches switchBlock :: P [SwitchBlock] switchBlock = braces $ list switchStmt switchStmt :: P SwitchBlock switchStmt = do lbl <- switchLabel bss <- list blockStmt return $ SwitchBlock lbl bss switchLabel :: P SwitchLabel switchLabel = (tok KW_Default >> colon >> return Default) <|> (do tok KW_Case e <- exp colon return $ SwitchCase e) -- Try-catch clauses catch :: P Catch catch = do tok KW_Catch fp <- parens formalParam b <- block return $ Catch fp b ---------------------------------------------------------------------------- -- Expressions stmtExp :: P Exp stmtExp = try preIncDec <|> try postIncDec <|> try assignment -- There are sharing gains to be made by unifying these two <|> try methodInvocationExp <|> instanceCreation preIncDec :: P Exp preIncDec = do op <- preIncDecOp e <- unaryExp return $ op e postIncDec :: P Exp postIncDec = do e <- postfixExpNES ops <- list1 postfixOp return $ foldl (\a s -> s a) e ops assignment :: P Exp assignment = do lh <- lhs op <- assignOp e <- assignExp return $ Assign lh op e lhs :: P Lhs lhs = try (FieldLhs <$> fieldAccess) <|> try (ArrayLhs <$> arrayAccess) <|> NameLhs <$> name exp :: P Exp exp = assignExp assignExp :: P Exp assignExp = try assignment <|> condExp condExp :: P Exp condExp = do ie <- infixExp ces <- list condExpSuffix return $ foldl (\a s -> s a) ie ces condExpSuffix :: P (Exp -> Exp) condExpSuffix = do tok Op_Query th <- exp colon el <- condExp return $ \ce -> Cond ce th el infixExp :: P Exp infixExp = do ue <- unaryExp ies <- list infixExpSuffix return $ foldl (\a s -> s a) ue ies infixExpSuffix :: P (Exp -> Exp) infixExpSuffix = (do op <- infixOp e2 <- unaryExp return $ \e1 -> BinOp e1 op e2) <|> (do tok KW_Instanceof t <- refType return $ \e1 -> InstanceOf e1 t) unaryExp :: P Exp unaryExp = try preIncDec <|> try (do op <- prefixOp ue <- unaryExp return $ op ue) <|> try (do t <- parens ttype e <- unaryExp return $ Cast t e) <|> postfixExp postfixExpNES :: P Exp postfixExpNES = -- try postIncDec <|> try primary <|> ExpName <$> name postfixExp :: P Exp postfixExp = do pe <- postfixExpNES ops <- list postfixOp return $ foldl (\a s -> s a) pe ops primary :: P Exp primary = primaryNPS |>> primarySuffix primaryNPS :: P Exp primaryNPS = try arrayCreation <|> primaryNoNewArrayNPS primaryNoNewArray = startSuff primaryNoNewArrayNPS primarySuffix primaryNoNewArrayNPS :: P Exp primaryNoNewArrayNPS = Lit <$> getPosition <*> literal <|> (tok KW_This >> (This <$> getPosition)) <|> parens exp <|> -- TODO: These two following should probably be merged more (try $ do pos <- getPosition rt <- resultType period >> tok KW_Class return $ ClassLit pos rt) <|> (try $ do n <- name period >> tok KW_This return $ ThisClass n) <|> try instanceCreationNPS <|> try (MethodInv <$> methodInvocationNPS) <|> try (FieldAccess <$> fieldAccessNPS) <|> ArrayAccess <$> arrayAccessNPS primarySuffix :: P (Exp -> Exp) primarySuffix = try instanceCreationSuffix <|> try ((ArrayAccess .) <$> arrayAccessSuffix) <|> try ((MethodInv .) <$> methodInvocationSuffix) <|> (FieldAccess .) <$> fieldAccessSuffix instanceCreationNPS :: P Exp instanceCreationNPS = do tok KW_New tas <- lopt typeArgs ct <- classType as <- args mcb <- opt classBody return $ InstanceCreation tas ct as mcb instanceCreationSuffix :: P (Exp -> Exp) instanceCreationSuffix = do period >> tok KW_New tas <- lopt typeArgs i <- ident as <- args mcb <- opt classBody return $ \p -> QualInstanceCreation p tas i as mcb instanceCreation :: P Exp instanceCreation = try instanceCreationNPS <|> do p <- primaryNPS ss <- list primarySuffix let icp = foldl (\a s -> s a) p ss case icp of QualInstanceCreation {} -> return icp _ -> fail "" {- instanceCreation = (do tok KW_New tas <- lopt typeArgs ct <- classType as <- args mcb <- opt classBody return $ InstanceCreation tas ct as mcb) <|> (do p <- primary period >> tok KW_New tas <- lopt typeArgs i <- ident as <- args mcb <- opt classBody return $ QualInstanceCreation p tas i as mcb) -} fieldAccessNPS :: P FieldAccess fieldAccessNPS = (do tok KW_Super >> period i <- ident return $ SuperFieldAccess i) <|> (do n <- name period >> tok KW_Super >> period i <- ident return $ ClassFieldAccess n i) fieldAccessSuffix :: P (Exp -> FieldAccess) fieldAccessSuffix = do period i <- ident return $ \p -> PrimaryFieldAccess p i fieldAccess :: P FieldAccess fieldAccess = try fieldAccessNPS <|> do p <- primaryNPS ss <- list primarySuffix let fap = foldl (\a s -> s a) p ss case fap of FieldAccess fa -> return fa _ -> fail "" {- fieldAccess :: P FieldAccess fieldAccess = try fieldAccessNPS <|> do p <- primary fs <- fieldAccessSuffix return (fs p) -} {- fieldAccess :: P FieldAccess fieldAccess = (do tok KW_Super >> period i <- ident return $ SuperFieldAccess i) <|> (try $ do n <- name period >> tok KW_Super >> period i <- ident return $ ClassFieldAccess n i) <|> (do p <- primary period i <- ident return $ PrimaryFieldAccess p i) -} methodInvocationNPS :: P MethodInvocation methodInvocationNPS = (do tok KW_Super >> period rts <- lopt refTypeArgs i <- ident as <- args return $ SuperMethodCall rts i as) <|> (do n <- name f <- (do as <- args return $ \n -> MethodCall n as) <|> (period >> do msp <- opt (tok KW_Super >> period) rts <- lopt refTypeArgs i <- ident as <- args let mc = maybe TypeMethodCall (const ClassMethodCall) msp return $ \n -> mc n rts i as) return $ f n) methodInvocationSuffix :: P (Exp -> MethodInvocation) methodInvocationSuffix = do period rts <- lopt refTypeArgs i <- ident as <- args return $ \p -> PrimaryMethodCall p [] i as methodInvocationExp :: P Exp methodInvocationExp = try (do p <- primaryNPS ss <- list primarySuffix let mip = foldl (\a s -> s a) p ss case mip of MethodInv _ -> return mip _ -> fail "") <|> (MethodInv <$> methodInvocationNPS) {- methodInvocation :: P MethodInvocation methodInvocation = (do tok KW_Super >> period rts <- lopt refTypeArgs i <- ident as <- args return $ SuperMethodCall rts i as) <|> (do p <- primary period rts <- lopt refTypeArgs i <- ident as <- args return $ PrimaryMethodCall p rts i as) <|> (do n <- name f <- (do as <- args return $ \n -> MethodCall n as) <|> (period >> do msp <- opt (tok KW_Super >> period) rts <- lopt refTypeArgs i <- ident as <- args let mc = maybe TypeMethodCall (const ClassMethodCall) msp return $ \n -> mc n rts i as) return $ f n) -} args :: P [Argument] args = parens $ seplist exp comma -- Arrays arrayAccessNPS :: P ArrayIndex arrayAccessNPS = do n <- name e <- list1 $ brackets exp return $ ArrayIndex (ExpName n) e arrayAccessSuffix :: P (Exp -> ArrayIndex) arrayAccessSuffix = do e <- list1 $ brackets exp return $ \ref -> ArrayIndex ref e arrayAccess = try arrayAccessNPS <|> do p <- primaryNoNewArrayNPS ss <- list primarySuffix let aap = foldl (\a s -> s a) p ss case aap of ArrayAccess ain -> return ain _ -> fail "" {- arrayAccess :: P (Exp, Exp) arrayAccess = do ref <- arrayRef e <- brackets exp return (ref, e) arrayRef :: P Exp arrayRef = ExpName <$> name <|> primaryNoNewArray -} arrayCreation :: P Exp arrayCreation = do tok KW_New t <- nonArrayType f <- (try $ do ds <- list1 $ brackets empty ai <- arrayInit return $ \t -> ArrayCreateInit t (length ds) ai) <|> (do des <- list1 $ try $ brackets exp ds <- list $ brackets empty return $ \t -> ArrayCreate t des (length ds)) return $ f t literal :: P Literal literal = javaToken $ \t -> case t of IntTok i -> Just (Int i) LongTok l -> Just (Word l) DoubleTok d -> Just (Double d) FloatTok f -> Just (Float f) CharTok c -> Just (Char c) StringTok s -> Just (String s) BoolTok b -> Just (Boolean b) NullTok -> Just Null _ -> Nothing -- Operators preIncDecOp, prefixOp, postfixOp :: P (Exp -> Exp) preIncDecOp = (tok Op_PPlus >> return PreIncrement) <|> (tok Op_MMinus >> return PreDecrement) prefixOp = (tok Op_Bang >> return PreNot ) <|> (tok Op_Tilde >> return PreBitCompl ) <|> (tok Op_Plus >> return PrePlus ) <|> (tok Op_Minus >> return PreMinus ) postfixOp = (tok Op_PPlus >> return PostIncrement) <|> (tok Op_MMinus >> return PostDecrement) assignOp :: P AssignOp assignOp = (tok Op_Equal >> return EqualA ) <|> (tok Op_StarE >> return MultA ) <|> (tok Op_SlashE >> return DivA ) <|> (tok Op_PercentE >> return RemA ) <|> (tok Op_PlusE >> return AddA ) <|> (tok Op_MinusE >> return SubA ) <|> (tok Op_LShiftE >> return LShiftA ) <|> (tok Op_RShiftE >> return RShiftA ) <|> (tok Op_RRShiftE >> return RRShiftA ) <|> (tok Op_AndE >> return AndA ) <|> (tok Op_CaretE >> return XorA ) <|> (tok Op_OrE >> return OrA ) infixOp :: P Op infixOp = (tok Op_Star >> return Mult ) <|> (tok Op_Slash >> return Div ) <|> (tok Op_Percent >> return Rem ) <|> (tok Op_Plus >> return Add ) <|> (tok Op_Minus >> return Sub ) <|> (tok Op_LShift >> return LShift ) <|> (tok Op_LThan >> return LThan ) <|> (try $ do tok Op_GThan tok Op_GThan tok Op_GThan return RRShift ) <|> (try $ do tok Op_GThan tok Op_GThan return RShift ) <|> (tok Op_GThan >> return GThan ) <|> (tok Op_LThanE >> return LThanE ) <|> (tok Op_GThanE >> return GThanE ) <|> (tok Op_Equals >> return Equal ) <|> (tok Op_BangE >> return NotEq ) <|> (tok Op_And >> return And ) <|> (tok Op_Caret >> return Xor ) <|> (tok Op_Or >> return Or ) <|> (tok Op_AAnd >> return CAnd ) <|> (tok Op_OOr >> return COr ) ---------------------------------------------------------------------------- -- Types ttype :: P Type ttype = try (RefType <$> refType) <|> PrimType <$> primType primType :: P PrimType primType = tok KW_Boolean >> return BooleanT <|> tok KW_Byte >> return ByteT <|> tok KW_Short >> return ShortT <|> tok KW_Int >> return IntT <|> tok KW_Long >> return LongT <|> tok KW_Char >> return CharT <|> tok KW_Float >> return FloatT <|> tok KW_Double >> return DoubleT refType :: P RefType refType = (do pt <- primType (_:bs) <- list1 arrBrackets return $ foldl (\f _ -> ArrayType . RefType . f) (ArrayType . PrimType) bs pt) <|> (do ct <- classType bs <- list arrBrackets return $ foldl (\f _ -> ArrayType . RefType . f) ClassRefType bs ct) <?> "refType" nonArrayType :: P Type nonArrayType = PrimType <$> primType <|> RefType <$> ClassRefType <$> classType classType :: P ClassType classType = ClassType <$> seplist1 classTypeSpec period classTypeSpec :: P (Ident, [TypeArgument]) classTypeSpec = do i <- ident tas <- lopt typeArgs return (i, tas) resultType :: P (Maybe Type) resultType = tok KW_Void >> return Nothing <|> Just <$> ttype <?> "resultType" refTypeList :: P [RefType] refTypeList = seplist1 refType comma ---------------------------------------------------------------------------- -- Type parameters and arguments typeParams :: P [TypeParam] typeParams = angles $ seplist1 typeParam comma typeParam :: P TypeParam typeParam = do i <- ident bs <- lopt bounds return $ TypeParam i bs bounds :: P [RefType] bounds = tok KW_Extends >> seplist1 refType (tok Op_And) typeArgs :: P [TypeArgument] typeArgs = angles $ seplist1 typeArg comma typeArg :: P TypeArgument typeArg = tok Op_Query >> Wildcard <$> opt wildcardBound <|> ActualType <$> refType wildcardBound :: P WildcardBound wildcardBound = tok KW_Extends >> ExtendsBound <$> refType <|> tok KW_Super >> SuperBound <$> refType refTypeArgs :: P [RefType] refTypeArgs = angles refTypeList ---------------------------------------------------------------------------- -- Names name :: P Name name = do pos <- getPosition a <- seplist1 ident period return $ Name a ident :: P Ident ident = do pos <- getPosition javaToken $ \t -> case t of IdentTok s -> Just $ Ident pos s _ -> Nothing ------------------------------------------------------------ empty :: P () empty = return () opt :: P a -> P (Maybe a) opt = optionMaybe bopt :: P a -> P Bool bopt p = opt p >>= \ma -> return $ isJust ma lopt :: P [a] -> P [a] lopt p = do mas <- opt p case mas of Nothing -> return [] Just as -> return as list :: P a -> P [a] list = option [] . list1 list1 :: P a -> P [a] list1 = many1 seplist :: P a -> P sep -> P [a] --seplist = sepBy seplist p sep = option [] $ seplist1 p sep seplist1 :: P a -> P sep -> P [a] --seplist1 = sepBy1 seplist1 p sep = p >>= \a -> try (do sep as <- seplist1 p sep return (a:as)) <|> return [a] startSuff, (|>>) :: P a -> P (a -> a) -> P a startSuff start suffix = do x <- start ss <- list suffix return $ foldl (\a s -> s a) x ss (|>>) = startSuff ------------------------------------------------------------ javaToken :: (Token -> Maybe a) -> P a javaToken test = token showT posT testT where showT (L _ t) = show t posT (L p _) = pos2sourcePos p testT (L _ t) = test t tok, matchToken :: Token -> P () tok = matchToken matchToken t = javaToken (\r -> if r == t then Just () else Nothing) pos2sourcePos :: (Int, Int) -> SourcePos pos2sourcePos (l,c) = newPos "" l c type Mod a = [Modifier] -> a parens, braces, brackets, angles :: P a -> P a parens = between (tok OpenParen) (tok CloseParen) braces = between (tok OpenCurly) (tok CloseCurly) brackets = between (tok OpenSquare) (tok CloseSquare) angles = between (tok Op_LThan) (tok Op_GThan) endSemi :: P a -> P a endSemi p = p >>= \a -> semiColon >> return a comma, colon, semiColon, period :: P () comma = tok Comma colon = tok Op_Colon semiColon = tok SemiColon period = tok Period
karshan/language-java
Language/Java/Parser.hs
bsd-3-clause
29,991
0
28
9,239
9,497
4,592
4,905
849
9
{-| Module : Data.Relational.RelationalMapping Description : Mapping to Relational types. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ConstraintKinds #-} module Data.Relational.RelationalMapping ( RelationalMapping(..) , makeSelect , makeInsert , makeUpdate , makeDelete , select , insert , delete , update , SelectConstraint , InsertConstraint , DeleteConstraint , UpdateConstraint ) where import GHC.TypeLits (Symbol, KnownSymbol) import GHC.Exts (Constraint) import Data.Bijection import Data.Proxy import Data.Relational import Data.Relational.Universe import Data.Relational.Interpreter -- | Instances of this class can be pushed to / pulled from a relational -- interpreter. class ( Eq d , KnownSymbol (RelationalTableName d) , IsSubset (RelationalSchema d) (RelationalSchema d) , IsSubsetUnique (RelationalSchema d) (RelationalSchema d) ) => RelationalMapping d where type RelationalTableName d :: Symbol type RelationalSchema d :: [(Symbol, *)] relationalSchema :: Proxy d -> Schema (RelationalSchema d) relationalTable :: Proxy d -> Table '(RelationalTableName d, RelationalSchema d) relationalTable proxy = Table Proxy (relationalSchema proxy) rowBijection :: d :<->: Row (RelationalSchema d) makeSelect :: forall d condition . ( RelationalMapping d , IsSubset (Concat condition) (RelationalSchema d) ) => Proxy d -> Condition condition -> Select '(RelationalTableName d, RelationalSchema d) (RelationalSchema d) condition makeSelect proxy condition = Select (relationalTable proxy) (fullProjection (relationalSchema proxy)) condition type family SelectConstraint datatype interpreter condition :: Constraint where SelectConstraint d i c = ( RelationalMapping d , RelationalInterpreter i , Functor (InterpreterMonad i) , IsSubset (Concat c) (RelationalSchema d) , Every (InUniverse (Universe i)) (Snds (RelationalSchema d)) , Every (InUniverse (Universe i)) (Snds (Concat c)) , InterpreterSelectConstraint i (RelationalSchema d) (RelationalSchema d) c , ConvertToRow (Universe i) (RelationalSchema d) ) select :: SelectConstraint d t conditioned => Proxy d -> Proxy t -> Condition conditioned -> (InterpreterMonad t) [Maybe d] select proxyD proxyI condition = let selectTerm = makeSelect proxyD condition in (fmap . fmap . fmap) (biFrom rowBijection) (interpretSelect' proxyI selectTerm) -- ^ three fmaps, for the monad, the list, and the maybe. makeInsert :: forall d . ( RelationalMapping d ) => d -> Insert '(RelationalTableName d, RelationalSchema d) makeInsert d = Insert (relationalTable (Proxy :: Proxy d)) (biTo rowBijection d) type family InsertConstraint datatype interpreter :: Constraint where InsertConstraint d i = ( RelationalMapping d , RelationalInterpreter i , InterpreterInsertConstraint i (RelationalSchema d) , Every (InUniverse (Universe i)) (Snds (RelationalSchema d)) ) insert :: InsertConstraint d interpreter => d -> Proxy interpreter -> (InterpreterMonad interpreter) () insert d proxyI = let insertTerm = makeInsert d in interpretInsert proxyI insertTerm makeDelete :: forall d c . ( RelationalMapping d , IsSubset (Concat c) (RelationalSchema d) ) => Proxy d -> Condition c -> Delete '(RelationalTableName d, RelationalSchema d) c makeDelete proxyD condition = Delete (relationalTable proxyD) (condition) type family DeleteConstraint datatype interpreter condition :: Constraint where DeleteConstraint d i condition = ( RelationalMapping d , RelationalInterpreter i , Every (InUniverse (Universe i)) (Snds (Concat (condition))) , InterpreterDeleteConstraint i (RelationalSchema d) (condition) , IsSubset (Concat condition) (RelationalSchema d) ) delete :: DeleteConstraint d interpreter c => Proxy interpreter -> Proxy d -> Condition c -> (InterpreterMonad interpreter) () delete proxyI proxyD condition = let deleteTerm = makeDelete proxyD condition in interpretDelete proxyI deleteTerm makeUpdate :: forall d c . ( RelationalMapping d , IsSubset (Concat c) (RelationalSchema d) ) => d -> Condition c -> Update '(RelationalTableName d, RelationalSchema d) (RelationalSchema d) c makeUpdate d condition = Update (relationalTable proxyD) (fullProjection (relationalSchema proxyD)) (condition) (biTo rowBijection d) where proxyD :: Proxy d proxyD = Proxy type family UpdateConstraint datatype interpreter condition :: Constraint where UpdateConstraint d i condition = ( RelationalMapping d , RelationalInterpreter i , Every (InUniverse (Universe i)) (Snds (RelationalSchema d)) , Every (InUniverse (Universe i)) (Snds (Concat (condition))) , InterpreterUpdateConstraint i (RelationalSchema d) (RelationalSchema d) (condition) , IsSubset (Concat condition) (RelationalSchema d) ) update :: UpdateConstraint d interpreter c => Proxy interpreter -> d -> Condition c -> (InterpreterMonad interpreter) () update proxyI d condition = let updateTerm = makeUpdate d condition in interpretUpdate proxyI updateTerm
avieth/RelationalMapping
Data/Relational/RelationalMapping.hs
bsd-3-clause
5,824
0
12
1,173
1,578
820
758
152
1
{-# LANGUAGE NoImplicitPrelude, TypeFamilies, TypeOperators, FlexibleInstances, StandaloneDeriving, ScopedTypeVariables, MultiParamTypeClasses, GeneralizedNewtypeDeriving #-} {-| Module: Alt.Arrow.Kleisli Description: Arrow encapsulating a Haskell-style Monad Copyright: (c) 2015 Nicolas Godbout Licence: BSD-3 Stability: experimental -} module Alt.Arrow.Kleisli ( KleisliArrow(..) ) where -- alt-base modules import Alt.Abstract.Arrow import Alt.Abstract.Category -- base modules import Control.Monad (Monad(..), join) import Data.Typeable ((:~:)(..), Proxy(..)) -- alt-base Prelude import Alt.Prelude {- | Kleisli arrow, encapsulating a Haskell-type Monad -} newtype KleisliArrow m f a b = KleisliArrow { kleisliArrow :: f a (m b) } instance (Monad m) => Haskell (KleisliArrow m (->)) where id = KleisliArrow return (KleisliArrow g) . (KleisliArrow f) = KleisliArrow $ \x -> f x >>= g -- arr join . . f {-# INLINE id #-} {-# INLINE (.) #-} instance (Monad m) => Category (KleisliArrow m (->)) where type EqC (KleisliArrow m (->)) a b = a :~: b type Obj (KleisliArrow m (->)) a = Proxy a source (KleisliArrow (f :: a -> m b)) = Proxy :: Proxy a target (KleisliArrow (f :: a -> m b)) = Proxy :: Proxy b idC Proxy = id dotW Refl = (.) {-# INLINE source #-} {-# INLINE target #-} {-# INLINE idC #-} {-# INLINE dotW #-} {- deriving instance CatHaskell f => CatHaskell (IdentityArrow f) deriving instance Arrow f => Arrow (IdentityArrow f) deriving instance ArrowProd f => ArrowProd (IdentityArrow f) deriving instance ArrowSum f => ArrowSum (IdentityArrow f) -- deriving instance ArrowApply f => ArrowApply (IdentityArrow f) deriving instance ArrowLoop f => ArrowLoop (IdentityArrow f) -} -- instance (Arrow f, CatHaskell f, Monad m) => ArrowTrans (KleisliArrow m) f where -- liftA f = KleisliArrow $ arr return . f
DrNico/alt-base
Alt/Arrow/Kleisli.hs
bsd-3-clause
2,011
0
12
477
359
208
151
35
0
----------------------------------------------------------------------------- -- | -- Module : Control.Monad.ST.Persistent -- Copyright : (c) Adam C. Foltzer 2013 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (requires rank-2 types for runST) -- -- This library provides support for a persistent version of the -- 'Control.Monad.ST.ST' monad. Internally, references are backed by a -- 'Data.IntMap.IntMap', rather than being mutable variables on the -- heap. This decreases performance, but can be useful in certain -- settings, particularly those involving backtracking. -- ----------------------------------------------------------------------------- module Control.Monad.ST.Persistent ( -- * The Persistent 'ST' Monad ST , runST -- * The Persistent 'ST' Monad transformer , STT , runSTT ) where import Control.Monad.ST.Persistent.Internal
acfoltzer/persistent-refs
src/Control/Monad/ST/Persistent.hs
bsd-3-clause
954
0
4
156
49
40
9
6
0
----------------------------------------------------------------------------- -- | -- Module : Miso.Effect.DOM -- Copyright : (C) 2016-2018 David M. Johnson -- License : BSD3-style (see the file LICENSE) -- Maintainer : David M. Johnson <[email protected]> -- Stability : experimental -- Portability : non-portable ---------------------------------------------------------------------------- module Miso.Effect.DOM ( focus , blur , scrollIntoView , alert ) where import Miso.FFI
dmjio/miso
src/Miso/Effect/DOM.hs
bsd-3-clause
513
0
4
84
35
26
9
6
0
{-# LANGUAGE OverloadedStrings #-} module WebsocketServer ( ServerState, acceptConnection, processUpdates ) where import Control.Concurrent (modifyMVar_, readMVar) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TBQueue (readTBQueue) import Control.Exception (SomeAsyncException, SomeException, finally, fromException, catch, throwIO) import Control.Monad (forever) import Data.Aeson (Value) import Data.Text (Text) import Data.UUID import System.Random (randomIO) import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy as LBS import qualified Data.Time.Clock.POSIX as Clock import qualified Network.WebSockets as WS import qualified Network.HTTP.Types.Header as HttpHeader import qualified Network.HTTP.Types.URI as Uri import Config (Config (..)) import Core (Core (..), ServerState, Updated (..), getCurrentValue, withCoreMetrics) import Store (Path) import AccessControl (AccessMode(..)) import JwtMiddleware (AuthResult (..), isRequestAuthorized, errorResponseBody) import qualified Metrics import qualified Subscription newUUID :: IO UUID newUUID = randomIO -- send the updated data to all subscribers to the path broadcast :: [Text] -> Value -> ServerState -> IO () broadcast = let send :: WS.Connection -> Value -> IO () send conn value = WS.sendTextData conn (Aeson.encode value) `catch` sendFailed sendFailed :: SomeException -> IO () sendFailed exc -- Rethrow async exceptions, they are meant for inter-thread communication -- (e.g. ThreadKilled) and we don't expect them at this point. | Just asyncExc <- fromException exc = throwIO (asyncExc :: SomeAsyncException) -- We want to catch all other errors in order to prevent them from -- bubbling up and disrupting the broadcasts to other clients. | otherwise = pure () in Subscription.broadcast send -- Called for each new client that connects. acceptConnection :: Core -> WS.PendingConnection -> IO () acceptConnection core pending = do -- printRequest pending -- TODO: Validate the path and headers of the pending request authResult <- authorizePendingConnection core pending case authResult of AuthRejected err -> WS.rejectRequestWith pending $ WS.RejectRequest { WS.rejectCode = 401 , WS.rejectMessage = "Unauthorized" , WS.rejectHeaders = [(HttpHeader.hContentType, "application/json")] , WS.rejectBody = LBS.toStrict $ errorResponseBody err } AuthAccepted -> do let path = fst $ Uri.decodePath $ WS.requestPath $ WS.pendingRequest pending connection <- WS.acceptRequest pending -- Fork a pinging thread, for each client, to keep idle connections open and to detect -- closed connections. Sends a ping message every 30 seconds. -- Note: The thread dies silently if the connection crashes or is closed. WS.withPingThread connection 30 (pure ()) $ handleClient connection path core -- * Authorization authorizePendingConnection :: Core -> WS.PendingConnection -> IO AuthResult authorizePendingConnection core conn | configEnableJwtAuth (coreConfig core) = do now <- Clock.getPOSIXTime let req = WS.pendingRequest conn (path, query) = Uri.decodePath $ WS.requestPath req headers = WS.requestHeaders req return $ isRequestAuthorized headers query now (configJwtSecret (coreConfig core)) path ModeRead | otherwise = pure AuthAccepted -- * Client handling handleClient :: WS.Connection -> Path -> Core -> IO () handleClient conn path core = do uuid <- newUUID let state = coreClients core onConnect = do modifyMVar_ state (pure . Subscription.subscribe path uuid conn) withCoreMetrics core Metrics.incrementSubscribers onDisconnect = do modifyMVar_ state (pure . Subscription.unsubscribe path uuid) withCoreMetrics core Metrics.decrementSubscribers sendInitialValue = do currentValue <- getCurrentValue core path WS.sendTextData conn (Aeson.encode currentValue) -- simply ignore connection errors, otherwise, warp handles the exception -- and sends a 500 response in the middle of a websocket connection, and -- that violates the websocket protocol. -- Note that subscribers are still properly removed by the finally below handleConnectionError :: WS.ConnectionException -> IO () handleConnectionError _ = pure () -- Put the client in the subscription tree and keep the connection open. -- Remove it when the connection is closed. finally (onConnect >> sendInitialValue >> keepTalking conn) onDisconnect `catch` handleConnectionError -- We don't send any messages here; sending is done by the update -- loop; it finds the client in the set of subscriptions. But we do -- need to keep the thread running, otherwise the connection will be -- closed. So we go into an infinite loop here. keepTalking :: WS.Connection -> IO () keepTalking conn = forever $ do -- Note: WS.receiveDataMessage will handle control messages automatically and e.g. -- do the closing handshake of the websocket protocol correctly WS.receiveDataMessage conn -- loop that is called for every update and that broadcasts the values to all -- subscribers of the updated path processUpdates :: Core -> IO () processUpdates core = go where go = do maybeUpdate <- atomically $ readTBQueue (coreUpdates core) case maybeUpdate of Just (Updated path value) -> do clients <- readMVar (coreClients core) broadcast path value clients go -- Stop the loop when we receive a Nothing. Nothing -> pure ()
channable/icepeak
server/src/WebsocketServer.hs
bsd-3-clause
5,677
0
18
1,141
1,174
628
546
96
2
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ViewPatterns #-} -- | Operations pertaining to Constraint Generation module Language.Rsc.Liquid.CGMonad ( -- * Constraint Generation Monad CGM , cgTickAST , getCgBinds , getCgRevBinds , setCgBinds , setCgRevBinds , getCgOpts , getCgInvs , getCons , getWFCons , execute -- * Constraint Information , CGInfo (..) , cgStateCInfo -- * Throw Errors , cgError -- * Freshable , Freshable (..) , resolveTypeM , envAddGuard, envPopGuard -- * Add Subtyping Constraints , subType, wellFormed -- , safeExtends -- * Add Type Annotations , addAnnot -- * Function Types , cgFunTys, substNoCapture , unqualifyThis ) where import Control.Arrow ((***)) import Control.Exception (throw) import Control.Monad.State import Control.Monad.Trans.Except import qualified Data.HashMap.Strict as HM import qualified Data.List as L import Language.Fixpoint.Misc import qualified Language.Fixpoint.Types as F import Language.Fixpoint.Types.Errors import Language.Fixpoint.Types.Names (symbolString) import Language.Fixpoint.Types.Visitor (SymConsts (..)) import qualified Language.Fixpoint.Types.Visitor as V import Language.Rsc.Annotations import Language.Rsc.CmdLine import Language.Rsc.Constraints import Language.Rsc.Core.Env import Language.Rsc.Environment import Language.Rsc.Errors import Language.Rsc.Liquid.Qualifiers import Language.Rsc.Liquid.Refinements import Language.Rsc.Locations import Language.Rsc.Names import Language.Rsc.Pretty import Language.Rsc.Program import Language.Rsc.Symbols import qualified Language.Rsc.SystemUtils as S import Language.Rsc.Transformations import Language.Rsc.Typecheck.Types import Language.Rsc.Types import Language.Rsc.TypeUtilities import Text.PrettyPrint.HughesPJ -------------------------------------------------------------------------------- -- | Top level type returned after Constraint Generation -------------------------------------------------------------------------------- data CGInfo = CGI { cgi_finfo :: F.FInfo Cinfo , cgi_annot :: S.UAnnInfo RefType } -- Dump the refinement subtyping constraints instance PP CGInfo where pp (CGI finfo _) = cat (map pp (HM.elems $ F.cm finfo)) -------------------------------------------------------------------------------- -- | Constraint Generation Monad -------------------------------------------------------------------------------- data CGState = CGS { -- -- ^ global list of fixpoint binders -- cg_binds :: F.BindEnv -- -- ^ reverse mapping of fixpoint symbols -- (to ensure unique bindings) -- , cg_rev_binds :: F.SEnv F.BindId -- -- ^ subtyping constraints -- , cg_cs :: ![SubC] -- -- ^ well-formedness constraints -- , cg_ws :: ![WfC] -- -- ^ freshness counter -- , cg_cnt :: !Integer -- -- ^ recorded annotations -- , cg_ann :: S.UAnnInfo RefType -- -- ^ type constructor invariants -- , cg_invs :: TConInv -- -- ^ configuration options -- , cg_opts :: Config -- -- ^ AST Counter -- , cg_ast_cnt :: NodeId } -- | Aliases -- type CGM = ExceptT Error (State CGState) type TConInv = HM.HashMap TPrim (Located RefType) cgTickAST = do n <- cg_ast_cnt <$> get modify $ \st -> st {cg_ast_cnt = 1 + n} return $ n getCgBinds = cg_binds <$> get getCgRevBinds = cg_rev_binds <$> get setCgBinds b = modify $ \st -> st { cg_binds = b } setCgRevBinds b = modify $ \st -> st { cg_rev_binds = b } getCgOpts = cg_opts <$> get getCgInvs = cg_invs <$> get getCons = cg_cs <$> get getWFCons = cg_ws <$> get -------------------------------------------------------------------------------- execute :: Config -> RefScript -> CGM a -> (a, CGState) -------------------------------------------------------------------------------- execute cfg pgm act = case runState (runExceptT act) $ initState cfg pgm of (Left e, _) -> throw e (Right x, st) -> (x, st) -------------------------------------------------------------------------------- initState :: Config -> RefScript -> CGState -------------------------------------------------------------------------------- initState c p = CGS F.emptyBindEnv F.emptySEnv [] [] 0 mempty invars c (maxId p) where invars = HM.fromList [(pr, t) | t@(Loc _ (TPrim pr _)) <- invts p] -------------------------------------------------------------------------------- cgStateCInfo :: FilePath -> RefScript -> (([F.SubC Cinfo], [F.WfC Cinfo]), CGState) -> CGInfo -------------------------------------------------------------------------------- cgStateCInfo f pgm ((fcs, fws), cg) = CGI finfo (cg_ann cg) where quals = pQuals pgm ++ scrapeQuals pgm finfo = F.fi fcs fws bs lits mempty quals mempty f False bs = cg_binds cg lits = lits1 `mappend` lits2 lits1 = F.sr_sort <$> measureEnv pgm lits2 = cgLits bs fcs cgLits :: F.BindEnv -> [F.SubC a] -> F.SEnv F.Sort cgLits bs cs = F.fromListSEnv cts where cts = [ (F.symbol c, F.strSort) | c <- csLits ++ bsLits ] csLits = concatMap symConsts cs bsLits = symConsts bs -- | Get binding from object type -------------------------------------------------------------------------------- measureEnv :: RefScript -> F.SEnv F.SortedReft -------------------------------------------------------------------------------- measureEnv = fmap rTypeSortedReft . envSEnv . consts -------------------------------------------------------------------------------- cgError :: Error -> CGM b -------------------------------------------------------------------------------- cgError = throwE -------------------------------------------------------------------------------- -- | Environment API -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- addAnnot :: (IsLocated l, F.Symbolic x) => l -> x -> RefType -> CGM () -------------------------------------------------------------------------------- addAnnot l x t = modify $ \st -> st {cg_ann = S.addAnnot (srcPos l) x t (cg_ann st)} -------------------------------------------------------------------------------- envAddGuard :: (F.Symbolic x, IsLocated x) => x -> Bool -> CGEnv -> CGEnv -------------------------------------------------------------------------------- envAddGuard x b g = g { cge_guards = guard b x : cge_guards g } where guard True = F.eProp guard False = F.PNot . F.eProp -------------------------------------------------------------------------------- envPopGuard :: CGEnv -> CGEnv -------------------------------------------------------------------------------- envPopGuard g = g { cge_guards = grdPop $ cge_guards g } where grdPop (_:xs) = xs grdPop [] = [] instance F.Expression a => F.Expression (Located a) where expr (Loc _ a) = F.expr a instance F.Expression TVar where expr (TV a _) = F.expr a -------------------------------------------------------------------------------- -- | Adding Subtyping Constraints -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- subType :: AnnLq -> Maybe Error -> CGEnv -> RefType -> RefType -> CGM () -------------------------------------------------------------------------------- subType l (Just err) g t1 t2 = modify $ \st -> st { cg_cs = Sub g (ci err l) t1 t2 : cg_cs st } subType l Nothing g t1 t2 = subType l (Just (mkErr l msg)) g t1 t2 where msg = text "Liquid Type Error" $+$ text "LHS" $+$ nest 2 (pp t1) $+$ text "RHS" $+$ nest 2 (pp t2) -- TODO: KVar subst -- instance F.Subable a => F.Subable (Env a) where substa f = envFromList . map ((***) (F.substa f . F.symbol) (F.substa f)) . envToList substf f = envFromList . map ((***) (F.substf f . F.symbol) (F.substf f)) . envToList subst su = envFromList . map ((***) (F.subst su . F.symbol) (F.subst su)) . envToList syms x = concat [ F.syms (F.symbol x) ++ F.syms t | (x, t) <- envToList x ] instance (PP r, F.Reftable r, F.Subable r) => F.Subable (SymInfo r) where substa f (SI x l a t) = SI x l a $ F.substa f t substf f (SI x l a t) = SI x l a $ F.substf f t subst su (SI x l a t) = SI x l a $ F.subst su t syms (SI _ _ _ t) = F.syms t -- errorLiquid l g t1 t2 = mkErr k $ printf "Liquid Type Error" where k = srcPos l -- TODO: Restore this check !!! -- -------------------------------------------------------------------------------- -- safeExtends :: SrcSpan -> CGEnv -> IfaceDef F.Reft -> CGM () -- -------------------------------------------------------------------------------- -- safeExtends l g (ID _ _ _ (Just (p, ts)) es) = zipWithM_ sub t1s t2s -- where -- sub t1 t2 = subType l g (zipType δ t1 t2) t2 -- (t1s, t2s) = unzip [ (t1,t2) | pe <- expand True δ (findSymOrDie p δ, ts) -- , ee <- es -- , sameBinder pe ee -- , let t1 = eltType ee -- , let t2 = eltType pe ] -- safeExtends _ _ _ (ID _ _ _ Nothing _) = return () -------------------------------------------------------------------------------- -- | Adding Well-Formedness Constraints -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- wellFormed :: (IsLocated l) => l -> CGEnv -> RefType -> CGM RefType -------------------------------------------------------------------------------- wellFormed l g t = do modify $ \st -> st { cg_ws = (W g (ci err l) t) : cg_ws st } return t where err = errorWellFormed (srcPos l) -------------------------------------------------------------------------------- -- | Generating Fresh Values -------------------------------------------------------------------------------- class Freshable a where fresh :: CGM a true :: a -> CGM a true = return . id refresh :: a -> CGM a refresh = return . id instance Freshable Integer where fresh = do modify $ \st -> st { cg_cnt = 1 + (cg_cnt st) } cg_cnt <$> get instance Freshable F.Symbol where fresh = F.tempSymbol (F.symbol "rsc") <$> fresh instance Freshable String where fresh = symbolString <$> fresh -- OLD CODE -- instance Freshable F.Refa where -- OLD CODE -- fresh = F.Refa . (`F.PKVar` mempty) . F.intKvar <$> fresh -- OLD CODE -- -- OLD CODE -- instance Freshable [F.Refa] where -- OLD CODE -- fresh = single <$> fresh instance Freshable F.Expr where fresh = kv <$> fresh where kv = (`F.PKVar` mempty) . F.intKvar instance Freshable F.Reft where fresh = errorstar "fresh F.Reft" true (F.Reft (v,_)) = return $ F.Reft (v, mempty) refresh (F.Reft (_,_)) = curry F.Reft <$> freshVV <*> fresh where freshVV = F.vv . Just <$> fresh instance Freshable F.SortedReft where fresh = errorstar "fresh F.Reft" true (F.RR so r) = F.RR so <$> true r refresh (F.RR so r) = F.RR so <$> refresh r instance Freshable RefType where fresh = errorstar "fresh RefType" refresh = mapReftM refresh true = trueRefType trueRefType :: RefType -> CGM RefType trueRefType = mapReftM true -------------------------------------------------------------------------------- cgFunTys :: (IsLocated l, F.Symbolic b, PP x, PP [b]) => l -> x -> [b] -> RefType -> CGM [IOverloadSig F.Reft] -------------------------------------------------------------------------------- cgFunTys l f xs ft | Just ts <- bkFuns ft = zip [0..] <$> mapM fTy (concatMap expandOpts ts) | otherwise = cgError $ errorNonFunction (srcPos l) f ft where fTy (αs, yts, t) | Just yts' <- padUndefineds xs yts = uncurry (αs,,) <$> substNoCapture xs (yts', t) | otherwise = cgError $ errorArgMismatch (srcPos l) f ft (length yts) (length xs) -- | `substNoCapture xs (yts,t)` substitutes formal parameters in `yts` with -- actual parameters passed as bindings in `xs`. -- -- Avoids capture of function binders by existing value variables -------------------------------------------------------------------------------- substNoCapture :: F.Symbolic a => [a] -> ([Bind F.Reft], RefType) -> CGM ([Bind F.Reft], RefType) -------------------------------------------------------------------------------- substNoCapture xs (yts, rt) | length yts /= length xs = error "substNoCapture - length test failed" | otherwise = (,) <$> mapM (onT (mapReftM ff)) yts <*> mapReftM ff rt where -- If the symbols we are about to introduce are already captured by some vv: -- (1) create a fresh vv., and -- (2) proceed with the substitution after replacing with the new vv. ff r@(F.Reft (v,ras)) | v `L.elem` xss = do v' <- freshVV return $ F.subst su $ F.Reft . (v',) $ F.subst (F.mkSubst [(v, F.expr v')]) ras | otherwise = return $ F.subst su r freshVV = F.vv . Just <$> fresh xss = F.symbol <$> xs su = F.mkSubst $ safeZipWith "substNoCapture" fSub yts xs fSub = curry $ (***) b_sym F.eVar onT f (B s o t) = B s o <$> f t -- | Substitute occurences of `offset(this, "f")` in type @t'@, with 'f' -------------------------------------------------------------------------------- unqualifyThis :: RefType -> RefType -------------------------------------------------------------------------------- unqualifyThis = emapReft (\_ -> V.trans vis () ()) [] where vis :: V.Visitor () () vis = V.defaultVisitor { V.txExpr = tExpr } tExpr _ (F.splitEApp -> (F.EVar o , [F.EVar th, F.ESym (F.SL c)])) | o == offsetSym, th == thisSym = F.eVar c tExpr _ e = e -- Local Variables: -- flycheck-disabled-checkers: (haskell-liquid) -- End:
UCSD-PL/RefScript
src/Language/Rsc/Liquid/CGMonad.hs
bsd-3-clause
15,034
0
17
3,569
3,560
1,935
1,625
223
2
module Main where import System.FSWatch (watchMain) main :: IO () main = watchMain
kelemzol/watch
src/Main.hs
bsd-3-clause
87
0
6
17
29
17
12
4
1
{-| Module : Idris.Coverage Description : Clause generation for coverage checking Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} module Idris.Coverage(genClauses, validCoverageCase, recoverableCoverage, mkPatTm) where import Idris.AbsSyntax import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT import Idris.Delaborate import Idris.Error import Idris.Output (iWarn, iputStrLn) import Control.Monad.State.Strict import Data.Char import Data.Either import Data.List import Data.Maybe import Debug.Trace -- | Generate a pattern from an 'impossible' LHS. -- -- We need this to eliminate the pattern clauses which have been -- provided explicitly from new clause generation. mkPatTm :: PTerm -> Idris Term mkPatTm t = do i <- getIState let timp = addImpl' True [] [] [] i t evalStateT (toTT (mapPT deNS timp)) 0 where toTT (PRef _ _ n) = do i <- lift getIState case lookupNameDef n (tt_ctxt i) of [(n', TyDecl nt _)] -> return $ P nt n' Erased _ -> return $ P Ref n Erased toTT (PApp _ t args) = do t' <- toTT t args' <- mapM (toTT . getTm) args return $ mkApp t' args' toTT (PDPair _ _ _ l _ r) = do l' <- toTT l r' <- toTT r return $ mkApp (P Ref sigmaCon Erased) [Erased, Erased, l', r'] toTT (PPair _ _ _ l r) = do l' <- toTT l r' <- toTT r return $ mkApp (P Ref pairCon Erased) [Erased, Erased, l', r'] -- For alternatives, pick the first and drop the namespaces. It doesn't -- really matter which is taken since matching will ignore the namespace. toTT (PAlternative _ _ (a : as)) = toTT a toTT _ = do v <- get put (v + 1) return (P Bound (sMN v "imp") Erased) deNS (PRef f hl (NS n _)) = PRef f hl n deNS t = t -- | Given a list of LHSs, generate a extra clauses which cover the remaining -- cases. The ones which haven't been provided are marked 'absurd' so -- that the checker will make sure they can't happen. -- -- This will only work after the given clauses have been typechecked and the -- names are fully explicit! genClauses :: FC -> Name -> [([Name], Term)] -> -- (Argument names, LHS) [PTerm] -> Idris [PTerm] -- No clauses (only valid via elab reflection). We should probably still do -- a check here somehow, e.g. that one of the arguments is an obviously -- empty type. In practice, this should only really be used for Void elimination. genClauses fc n lhs_tms [] = return [] genClauses fc n lhs_tms given = do i <- getIState let lhs_given = zipWith removePlaceholders lhs_tms (map (stripUnmatchable i) (map flattenArgs given)) logCoverage 5 $ "Building coverage tree for:\n" ++ showSep "\n" (map show (lhs_given)) let givenpos = mergePos (map getGivenPos given) (cns, ctree_in) <- case simpleCase False (UnmatchedCase "Undefined") False (CoverageCheck givenpos) emptyFC [] [] lhs_given (const []) of OK (CaseDef cns ctree_in _) -> return (cns, ctree_in) Error e -> tclift $ tfail $ At fc e let ctree = trimOverlapping (addMissingCons i ctree_in) let (coveredas, missingas) = mkNewClauses (tt_ctxt i) n cns ctree let covered = map (\t -> delab' i t True True) coveredas let missing = filter (\x -> x `notElem` covered) $ map (\t -> delab' i t True True) missingas logCoverage 5 $ "Coverage from case tree for " ++ show n ++ ": " ++ show ctree logCoverage 2 $ show (length missing) ++ " missing clauses for " ++ show n logCoverage 3 $ "Missing clauses:\n" ++ showSep "\n" (map showTmImpls missing) logCoverage 10 $ "Covered clauses:\n" ++ showSep "\n" (map showTmImpls covered) return missing where flattenArgs (PApp fc (PApp _ f as) as') = flattenArgs (PApp fc f (as ++ as')) flattenArgs t = t getGivenPos :: PTerm -> [Int] getGivenPos (PApp _ _ pargs) = getGiven 0 (map getTm pargs) where getGiven i (Placeholder : tms) = getGiven (i + 1) tms getGiven i (_ : tms) = i : getGiven (i + 1) tms getGiven i [] = [] getGivenPos _ = [] -- Return a list of Ints which are in every list mergePos :: [[Int]] -> [Int] mergePos [] = [] mergePos [x] = x mergePos (x : xs) = intersect x (mergePos xs) removePlaceholders :: ([Name], Term) -> PTerm -> ([Name], Term, Term) removePlaceholders (ns, tm) ptm = (ns, rp tm ptm, Erased) where rp Erased Placeholder = Erased rp tm Placeholder = Inferred tm rp tm (PApp _ pf pargs) | (tf, targs) <- unApply tm = let tf' = rp tf pf targs' = zipWith rp targs (map getTm pargs) in mkApp tf' targs' rp tm (PPair _ _ _ pl pr) | (tf, [tyl, tyr, tl, tr]) <- unApply tm = let tl' = rp tl pl tr' = rp tr pr in mkApp tf [Erased, Erased, tl', tr'] rp tm (PDPair _ _ _ pl pt pr) | (tf, [tyl, tyr, tl, tr]) <- unApply tm = let tl' = rp tl pl tr' = rp tr pr in mkApp tf [Erased, Erased, tl', tr'] rp tm _ = tm mkNewClauses :: Context -> Name -> [Name] -> SC -> ([Term], [Term]) mkNewClauses ctxt fn ns sc = (map (mkPlApp (P Ref fn Erased)) $ mkFromSC True (map (\n -> P Ref n Erased) ns) sc, map (mkPlApp (P Ref fn Erased)) $ mkFromSC False (map (\n -> P Ref n Erased) ns) sc) where mkPlApp f args = mkApp f (map erasePs args) erasePs ap@(App t f a) | (f, args) <- unApply ap = mkApp f (map erasePs args) erasePs (P _ n _) | not (isConName n ctxt) = Erased erasePs tm = tm mkFromSC cov args sc = evalState (mkFromSC' cov args sc) [] mkFromSC' :: Bool -> [Term] -> SC -> State [[Term]] [[Term]] mkFromSC' cov args (STerm _) = if cov then return [args] else return [] -- leaf of provided case mkFromSC' cov args (UnmatchedCase _) = if cov then return [] else return [args] -- leaf of missing case mkFromSC' cov args ImpossibleCase = return [] mkFromSC' cov args (Case _ x alts) = do done <- get if (args `elem` done) then return [] else do alts' <- mapM (mkFromAlt cov args x) alts put (args : done) return (concat alts') mkFromSC' cov args _ = return [] -- Should never happen mkFromAlt :: Bool -> [Term] -> Name -> CaseAlt -> State [[Term]] [[Term]] mkFromAlt cov args x (ConCase c t conargs sc) = let argrep = mkApp (P (DCon t (length args) False) c Erased) (map (\n -> P Ref n Erased) conargs) args' = map (subst x argrep) args in mkFromSC' cov args' sc mkFromAlt cov args x (ConstCase c sc) = let argrep = Constant c args' = map (subst x argrep) args in mkFromSC' cov args' sc mkFromAlt cov args x (DefaultCase sc) = mkFromSC' cov args sc mkFromAlt cov _ _ _ = return [] -- Modify the generated case tree (the case tree builder doesn't have access -- to the context, so can't do this itself). -- Replaces any missing cases with explicit cases for the missing constructors addMissingCons :: IState -> SC -> SC addMissingCons ist sc = evalState (addMissingConsSt ist sc) 0 addMissingConsSt :: IState -> SC -> State Int SC addMissingConsSt ist (Case t n alts) = liftM (Case t n) (addMissingAlts n alts) where addMissingAlt :: CaseAlt -> State Int CaseAlt addMissingAlt (ConCase n i ns sc) = liftM (ConCase n i ns) (addMissingConsSt ist sc) addMissingAlt (FnCase n ns sc) = liftM (FnCase n ns) (addMissingConsSt ist sc) addMissingAlt (ConstCase c sc) = liftM (ConstCase c) (addMissingConsSt ist sc) addMissingAlt (SucCase n sc) = liftM (SucCase n) (addMissingConsSt ist sc) addMissingAlt (DefaultCase sc) = liftM DefaultCase (addMissingConsSt ist sc) addMissingAlts argn as -- | any hasDefault as = map addMissingAlt as | cons@(n:_) <- mapMaybe collectCons as, Just tyn <- getConType n, Just ti <- lookupCtxtExact tyn (idris_datatypes ist) -- If we've fallen through on this argument earlier, then the -- things which were matched in other cases earlier can't be missing -- cases now = let missing = con_names ti \\ cons in do as' <- addCases missing as mapM addMissingAlt as' | consts@(n:_) <- mapMaybe collectConsts as = let missing = nub (map nextConst consts) \\ consts in mapM addMissingAlt (addCons missing as) addMissingAlts n as = mapM addMissingAlt as addCases missing [] = return [] addCases missing (DefaultCase rhs : rest) = do missing' <- mapM (genMissingAlt rhs) missing return (mapMaybe id missing' ++ rest) addCases missing (c : rest) = liftM (c :) $ addCases missing rest addCons missing [] = [] addCons missing (DefaultCase rhs : rest) = map (genMissingConAlt rhs) missing ++ rest addCons missing (c : rest) = c : addCons missing rest genMissingAlt rhs n | Just (TyDecl (DCon tag arity _) ty) <- lookupDefExact n (tt_ctxt ist) = do name <- get put (name + arity) let args = map (name +) [0..arity-1] return $ Just $ ConCase n tag (map (\i -> sMN i "m") args) rhs | otherwise = return Nothing genMissingConAlt rhs n = ConstCase n rhs collectCons (ConCase n i args sc) = Just n collectCons _ = Nothing collectConsts (ConstCase c sc) = Just c collectConsts _ = Nothing hasDefault (DefaultCase (UnmatchedCase _)) = False hasDefault (DefaultCase _) = True hasDefault _ = False getConType n = do ty <- lookupTyExact n (tt_ctxt ist) case unApply (getRetTy (normalise (tt_ctxt ist) [] ty)) of (P _ tyn _, _) -> Just tyn _ -> Nothing -- for every constant in a term (at any level) take next one to make sure -- that constants which are not explicitly handled are covered nextConst (I c) = I (c + 1) nextConst (BI c) = BI (c + 1) nextConst (Fl c) = Fl (c + 1) nextConst (B8 c) = B8 (c + 1) nextConst (B16 c) = B16 (c + 1) nextConst (B32 c) = B32 (c + 1) nextConst (B64 c) = B64 (c + 1) nextConst (Ch c) = Ch (chr $ ord c + 1) nextConst (Str c) = Str (c ++ "'") nextConst o = o addMissingConsSt ist sc = return sc trimOverlapping :: SC -> SC trimOverlapping sc = trim [] [] sc where trim :: [(Name, (Name, [Name]))] -> -- Variable - constructor+args already matched [(Name, [Name])] -> -- Variable - constructors which it can't be SC -> SC trim mustbes nots (Case t vn alts) | Just (c, args) <- lookup vn mustbes = Case t vn (trimAlts mustbes nots vn (substMatch (c, args) alts)) | Just cantbe <- lookup vn nots = let alts' = filter (notConMatch cantbe) alts in Case t vn (trimAlts mustbes nots vn alts') | otherwise = Case t vn (trimAlts mustbes nots vn alts) trim cs nots sc = sc trimAlts cs nots vn [] = [] trimAlts cs nots vn (ConCase cn t args sc : rest) = ConCase cn t args (trim (addMatch vn (cn, args) cs) nots sc) : trimAlts cs (addCantBe vn cn nots) vn rest trimAlts cs nots vn (FnCase n ns sc : rest) = FnCase n ns (trim cs nots sc) : trimAlts cs nots vn rest trimAlts cs nots vn (ConstCase c sc : rest) = ConstCase c (trim cs nots sc) : trimAlts cs nots vn rest trimAlts cs nots vn (SucCase n sc : rest) = SucCase n (trim cs nots sc) : trimAlts cs nots vn rest trimAlts cs nots vn (DefaultCase sc : rest) = DefaultCase (trim cs nots sc) : trimAlts cs nots vn rest isConMatch c (ConCase cn t args sc) = c == cn isConMatch _ _ = False substMatch :: (Name, [Name]) -> [CaseAlt] -> [CaseAlt] substMatch ca [] = [] substMatch (c,args) (ConCase cn t args' sc : _) | c == cn = [ConCase c t args (substNames (zip args' args) sc)] substMatch ca (_:cs) = substMatch ca cs substNames [] sc = sc substNames ((n, n') : ns) sc = substNames ns (substSC n n' sc) notConMatch cs (ConCase cn t args sc) = cn `notElem` cs notConMatch cs _ = True addMatch vn cn cs = (vn, cn) : cs addCantBe :: Name -> Name -> [(Name, [Name])] -> [(Name, [Name])] addCantBe vn cn [] = [(vn, [cn])] addCantBe vn cn ((n, cbs) : nots) | vn == n = ((n, nub (cn : cbs)) : nots) | otherwise = ((n, cbs) : addCantBe vn cn nots) -- | Does this error result rule out a case as valid when coverage checking? validCoverageCase :: Context -> Err -> Bool validCoverageCase ctxt (CantUnify _ (topx, _) (topy, _) e _ _) = let topx' = normalise ctxt [] topx topy' = normalise ctxt [] topy in not (sameFam topx' topy' || not (validCoverageCase ctxt e)) where sameFam topx topy = case (unApply topx, unApply topy) of ((P _ x _, _), (P _ y _, _)) -> x == y _ -> False validCoverageCase ctxt (InfiniteUnify _ _ _) = False validCoverageCase ctxt (CantConvert _ _ _) = False validCoverageCase ctxt (At _ e) = validCoverageCase ctxt e validCoverageCase ctxt (Elaborating _ _ _ e) = validCoverageCase ctxt e validCoverageCase ctxt (ElaboratingArg _ _ _ e) = validCoverageCase ctxt e validCoverageCase ctxt _ = True -- | Check whether an error is recoverable in the sense needed for -- coverage checking. recoverableCoverage :: Context -> Err -> Bool recoverableCoverage ctxt (CantUnify r (topx, _) (topy, _) e _ _) = let topx' = normalise ctxt [] topx topy' = normalise ctxt [] topy in checkRec topx' topy' where -- different notion of recoverable than in unification, since we -- have no metavars -- just looking to see if a constructor is failing -- to unify with a function that may be reduced later checkRec (App _ f a) p@(P _ _ _) = checkRec f p checkRec p@(P _ _ _) (App _ f a) = checkRec p f checkRec fa@(App _ _ _) fa'@(App _ _ _) | (f, as) <- unApply fa, (f', as') <- unApply fa' = if (length as /= length as') then checkRec f f' else checkRec f f' && and (zipWith checkRec as as') checkRec (P xt x _) (P yt y _) = x == y || ntRec xt yt checkRec _ _ = False ntRec x y | Ref <- x = True | Ref <- y = True | (Bound, Bound) <- (x, y) = True | otherwise = False -- name is different, unrecoverable recoverableCoverage ctxt (At _ e) = recoverableCoverage ctxt e recoverableCoverage ctxt (Elaborating _ _ _ e) = recoverableCoverage ctxt e recoverableCoverage ctxt (ElaboratingArg _ _ _ e) = recoverableCoverage ctxt e recoverableCoverage _ _ = False
eklavya/Idris-dev
src/Idris/Coverage.hs
bsd-3-clause
15,746
0
17
5,120
5,718
2,871
2,847
287
24
{- Problem 99: Largest exponential Comparing two numbers written in index form like 2^11 and 3^7 is not difficult, as any calculator would confirm that 2^11 = 2048 < 3^7 = 2187. However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as both numbers contain over three million digits. Using base_exp.txt (right click and 'Save Link/Target As...'), a 22K text file containing one thousand lines with a base/exponent pair on each line, determine which line number has the greatest numerical value. NOTE: The first two lines in the file represent the numbers in the example given above. -} module Problem99 where import ListUtils (splitOn) maxExponentPair = maxExponentPair' (0, 0, 1) 1 where maxExponentPair' result ln [] = result maxExponentPair' (ln, b1, e1) n ([b2,e2]:lst) = if b1^e1 > b2^e2 then maxExponentPair' (ln, b1, e1) (n + 1) lst else maxExponentPair' (n, b2, e2) (n + 1) lst doit = do source <- readFile "p099_base_exp.txt" putStrLn $ "Solution: " ++ show (maxExponentPair $ parse source) where parse s = [map (\t -> read t :: Integer) inputs | inputs<-(tokenize s)] tokenize = (map (splitOn ',')) . lines
ajsmith/project-euler-solutions
src/Problem99.hs
gpl-2.0
1,197
0
11
238
254
138
116
13
3
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} module CO4.Thesis.WCB_Matrix where import Prelude hiding (sequence) import qualified Satchmo.Core.SAT.Minisat import qualified Satchmo.Core.Decode import CO4 import CO4.Prelude.Nat import CO4.Thesis.WCB_MatrixStandalone import CO4.Prelude $( compileFile [ ImportPrelude, InstantiationDepth 20 ] "test/CO4/Thesis/WCB_MatrixStandalone.hs" ) uBase = unions [knownA, knownC, knownG, knownU] uParen = unions [knownOpen, knownClose, knownBlank] uEnergy = unions [knownMinusInfinity, knownFinite $ uNat 8] uMatrix xs ys f = let row xs g = case xs of [] -> knownNill x:xs' -> knownConss (g x) (row xs' g) in row xs $ \ x -> row ys $ \ y -> f x y uTriagGap delta n = uMatrix [1 .. n] [1 .. n] $ \ i j -> if i + delta <= j then knownFinite (uNat 8) else knownMinusInfinity kList' 0 _ = knownNill kList' i x = knownConss x (kList' (i-1) x) toList :: [a] -> List a toList = foldr Conss Nill ex1 = toList [ Open , Open , Open , Open , Open , Blank, Blank, Blank, Open , Open , Open , Open , Open , Blank, Blank , Blank, Blank, Blank, Blank, Close , Close, Close, Close, Close, Blank , Close, Close, Close, Close, Close ] ex0 = toList [ Open, Open , Blank, Close, Open , Close , Close, Blank ] {- result :: List Paren -> IO (Maybe (Pair (List Base) Energy)) result sec = do let n = foldr' (const succ) 0 sec out <- solveAndTestP sec (knownPair (kList' n uBase) (uTriagGap 1 (n+1)) ) encConstraint constraint return $ case out of Nothing -> Nothing Just (Pair p m) -> Just (Pair p (upright m)) -} resultInverse :: List Base -> IO (Maybe (Pair (List Paren) Energy)) resultInverse prim = do let n = foldr' (const succ) 0 prim out <- solveAndTestP prim (knownPair (kList' n uParen) (uTriagGap 1 (n+1)) ) encConstraint constraint return $ case out of Nothing -> Nothing Just (Pair s m) -> Just (Pair s (upright m))
apunktbau/co4
test/CO4/Thesis/WCB_Matrix.hs
gpl-3.0
2,322
0
15
649
656
361
295
48
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Route53.ChangeResourceRecordSets -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Use this action to create or change your authoritative DNS information. -- To use this action, send a 'POST' request to the -- '2013-04-01\/hostedzone\/hosted Zone ID\/rrset' resource. The request -- body must include an XML document with a -- 'ChangeResourceRecordSetsRequest' element. -- -- Changes are a list of change items and are considered transactional. For -- more information on transactional changes, also known as change batches, -- see -- <http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/RRSchanges.html#RRSchanges_API Creating, Changing, and Deleting Resource Record Sets Using the Route 53 API> -- in the /Amazon Route 53 Developer Guide/. -- -- Due to the nature of transactional changes, you cannot delete the same -- resource record set more than once in a single change batch. If you -- attempt to delete the same change batch more than once, Route 53 returns -- an 'InvalidChangeBatch' error. -- -- In response to a 'ChangeResourceRecordSets' request, your DNS data is -- changed on all Route 53 DNS servers. Initially, the status of a change -- is 'PENDING'. This means the change has not yet propagated to all the -- authoritative Route 53 DNS servers. When the change is propagated to all -- hosts, the change returns a status of 'INSYNC'. -- -- Note the following limitations on a 'ChangeResourceRecordSets' request: -- -- - A request cannot contain more than 100 Change elements. -- -- - A request cannot contain more than 1000 ResourceRecord elements. -- -- The sum of the number of characters (including spaces) in all 'Value' -- elements in a request cannot exceed 32,000 characters. -- -- /See:/ <http://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html AWS API Reference> for ChangeResourceRecordSets. module Network.AWS.Route53.ChangeResourceRecordSets ( -- * Creating a Request changeResourceRecordSets , ChangeResourceRecordSets -- * Request Lenses , crrsHostedZoneId , crrsChangeBatch -- * Destructuring the Response , changeResourceRecordSetsResponse , ChangeResourceRecordSetsResponse -- * Response Lenses , crrsrsResponseStatus , crrsrsChangeInfo ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.Route53.Types import Network.AWS.Route53.Types.Product -- | A complex type that contains a change batch. -- -- /See:/ 'changeResourceRecordSets' smart constructor. data ChangeResourceRecordSets = ChangeResourceRecordSets' { _crrsHostedZoneId :: !Text , _crrsChangeBatch :: !ChangeBatch } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ChangeResourceRecordSets' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'crrsHostedZoneId' -- -- * 'crrsChangeBatch' changeResourceRecordSets :: Text -- ^ 'crrsHostedZoneId' -> ChangeBatch -- ^ 'crrsChangeBatch' -> ChangeResourceRecordSets changeResourceRecordSets pHostedZoneId_ pChangeBatch_ = ChangeResourceRecordSets' { _crrsHostedZoneId = pHostedZoneId_ , _crrsChangeBatch = pChangeBatch_ } -- | The ID of the hosted zone that contains the resource record sets that -- you want to change. crrsHostedZoneId :: Lens' ChangeResourceRecordSets Text crrsHostedZoneId = lens _crrsHostedZoneId (\ s a -> s{_crrsHostedZoneId = a}); -- | A complex type that contains an optional comment and the 'Changes' -- element. crrsChangeBatch :: Lens' ChangeResourceRecordSets ChangeBatch crrsChangeBatch = lens _crrsChangeBatch (\ s a -> s{_crrsChangeBatch = a}); instance AWSRequest ChangeResourceRecordSets where type Rs ChangeResourceRecordSets = ChangeResourceRecordSetsResponse request = postXML route53 response = receiveXML (\ s h x -> ChangeResourceRecordSetsResponse' <$> (pure (fromEnum s)) <*> (x .@ "ChangeInfo")) instance ToElement ChangeResourceRecordSets where toElement = mkElement "{https://route53.amazonaws.com/doc/2013-04-01/}ChangeResourceRecordSetsRequest" instance ToHeaders ChangeResourceRecordSets where toHeaders = const mempty instance ToPath ChangeResourceRecordSets where toPath ChangeResourceRecordSets'{..} = mconcat ["/2013-04-01/hostedzone/", toBS _crrsHostedZoneId, "/rrset/"] instance ToQuery ChangeResourceRecordSets where toQuery = const mempty instance ToXML ChangeResourceRecordSets where toXML ChangeResourceRecordSets'{..} = mconcat ["ChangeBatch" @= _crrsChangeBatch] -- | A complex type containing the response for the request. -- -- /See:/ 'changeResourceRecordSetsResponse' smart constructor. data ChangeResourceRecordSetsResponse = ChangeResourceRecordSetsResponse' { _crrsrsResponseStatus :: !Int , _crrsrsChangeInfo :: !ChangeInfo } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ChangeResourceRecordSetsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'crrsrsResponseStatus' -- -- * 'crrsrsChangeInfo' changeResourceRecordSetsResponse :: Int -- ^ 'crrsrsResponseStatus' -> ChangeInfo -- ^ 'crrsrsChangeInfo' -> ChangeResourceRecordSetsResponse changeResourceRecordSetsResponse pResponseStatus_ pChangeInfo_ = ChangeResourceRecordSetsResponse' { _crrsrsResponseStatus = pResponseStatus_ , _crrsrsChangeInfo = pChangeInfo_ } -- | The response status code. crrsrsResponseStatus :: Lens' ChangeResourceRecordSetsResponse Int crrsrsResponseStatus = lens _crrsrsResponseStatus (\ s a -> s{_crrsrsResponseStatus = a}); -- | A complex type that contains information about changes made to your -- hosted zone. -- -- This element contains an ID that you use when performing a GetChange -- action to get detailed information about the change. crrsrsChangeInfo :: Lens' ChangeResourceRecordSetsResponse ChangeInfo crrsrsChangeInfo = lens _crrsrsChangeInfo (\ s a -> s{_crrsrsChangeInfo = a});
fmapfmapfmap/amazonka
amazonka-route53/gen/Network/AWS/Route53/ChangeResourceRecordSets.hs
mpl-2.0
6,920
0
14
1,260
674
415
259
88
1
module FP.Test.DerivingPretty where import FP import FP.DerivingPretty data AS a = FooAS Int | BarAS a makePrettySum ''AS data AU a = FooAU Int | BarAU a makePrettyUnion ''AU data BS a b = FooBS Int | BarBS a b makePrettySum ''BS data BU a b = FooBU Int | BarBU a b makePrettyUnion ''BU xas, yas :: AS String xas = FooAS 1 yas = BarAS "hi" xau, yau :: AU String xau = FooAU 1 yau = BarAU "hi" xbs, ybs :: BS String (Int, Int) xbs = FooBS 1 ybs = BarBS "hi" (1, 2) xbu, ybu :: BU String (Int, Int) xbu = FooBU 1 ybu = BarBU "hi" (1, 2) testit :: IO () testit = do pprint xas pprint yas pprint xau pprint xau pprint xbs pprint ybs pprint xbu pprint ybu
davdar/maam
src/FP/Test/DerivingPretty.hs
bsd-3-clause
677
0
7
164
312
162
150
-1
-1
-- Copyright 2016 TensorFlow authors. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- Purposely disabled to confirm doubleFuncNoSig can be written without type. {-# OPTIONS_GHC -fno-warn-missing-signatures #-} import Control.Monad (replicateM) import Control.Monad.IO.Class (liftIO) import Data.Int (Int64) import Test.Framework (defaultMain, Test) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit ((@=?)) import Test.QuickCheck (Arbitrary(..), listOf, suchThat) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.Vector as V import qualified TensorFlow.GenOps.Core as TF (select) import qualified TensorFlow.Ops as TF import qualified TensorFlow.Session as TF import qualified TensorFlow.Tensor as TF import qualified TensorFlow.Types as TF instance Arbitrary B.ByteString where arbitrary = B.pack <$> arbitrary -- Test encoding tensors, feeding them through tensorflow, and decoding the -- results. testFFIRoundTrip :: Test testFFIRoundTrip = testCase "testFFIRoundTrip" $ TF.runSession $ do let floatData = V.fromList [1..6 :: Float] stringData = V.fromList [B8.pack (show x) | x <- [1..6::Integer]] boolData = V.fromList [True, True, False, True, False, False] f <- TF.placeholder [2,3] s <- TF.placeholder [2,3] b <- TF.placeholder [2,3] let feeds = [ TF.feed f (TF.encodeTensorData [2,3] floatData) , TF.feed s (TF.encodeTensorData [2,3] stringData) , TF.feed b (TF.encodeTensorData [2,3] boolData) ] -- Do something idempotent to the tensors to verify that tensorflow can -- handle the encoding. Originally this used `TF.identity`, but that -- wasn't enough to catch a bug in the encoding of Bool. (f', s', b') <- TF.runWithFeeds feeds (f `TF.add` 0, TF.identity s, TF.select b b b) liftIO $ do floatData @=? f' stringData @=? s' boolData @=? b' data TensorDataInputs a = TensorDataInputs [Int64] (V.Vector a) deriving Show instance Arbitrary a => Arbitrary (TensorDataInputs a) where arbitrary = do -- Limit the size of the final vector, and also guard against overflow -- (i.e., p<0) when there are too many dimensions let validProduct p = p > 0 && p < 100 sizes <- listOf (arbitrary `suchThat` (>0)) `suchThat` (validProduct . product) elems <- replicateM (fromIntegral $ product sizes) arbitrary return $ TensorDataInputs sizes (V.fromList elems) -- Test that a vector is unchanged after being encoded and decoded. encodeDecodeProp :: (TF.TensorDataType V.Vector a, Eq a) => TensorDataInputs a -> Bool encodeDecodeProp (TensorDataInputs shape vec) = TF.decodeTensorData (TF.encodeTensorData (TF.Shape shape) vec) == vec testEncodeDecodeQcFloat :: Test testEncodeDecodeQcFloat = testProperty "testEncodeDecodeQcFloat" (encodeDecodeProp :: TensorDataInputs Float -> Bool) testEncodeDecodeQcInt64 :: Test testEncodeDecodeQcInt64 = testProperty "testEncodeDecodeQcInt64" (encodeDecodeProp :: TensorDataInputs Int64 -> Bool) testEncodeDecodeQcString :: Test testEncodeDecodeQcString = testProperty "testEncodeDecodeQcString" (encodeDecodeProp :: TensorDataInputs B.ByteString -> Bool) doubleOrInt64Func :: TF.OneOf '[Double, Int64] a => a -> a doubleOrInt64Func = id doubleOrFloatFunc :: TF.OneOf '[Double, Float] a => a -> a doubleOrFloatFunc = id doubleFunc :: TF.OneOf '[Double] a => a -> a doubleFunc = doubleOrFloatFunc . doubleOrInt64Func -- No explicit type signature; make sure it can be inferred automatically. -- (Note: this would fail if we didn't have NoMonomorphismRestriction, since it -- can't simplify the type all the way to `Double -> Double`. doubleFuncNoSig = doubleOrFloatFunc . doubleOrInt64Func typeConstraintTests :: Test typeConstraintTests = testCase "type constraints" $ do 42 @=? doubleOrInt64Func (42 :: Double) 42 @=? doubleOrInt64Func (42 :: Int64) 42 @=? doubleOrFloatFunc (42 :: Double) 42 @=? doubleOrFloatFunc (42 :: Float) 42 @=? doubleFunc (42 :: Double) 42 @=? doubleFuncNoSig (42 :: Double) main :: IO () main = defaultMain [ testFFIRoundTrip , testEncodeDecodeQcFloat , testEncodeDecodeQcInt64 , testEncodeDecodeQcString , typeConstraintTests ]
tensorflow/haskell
tensorflow-ops/tests/TypesTest.hs
apache-2.0
5,351
0
15
1,109
1,135
636
499
88
1
{- % (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcGenDeriv: Generating derived instance declarations This module is nominally ``subordinate'' to @TcDeriv@, which is the ``official'' interface to deriving-related things. This is where we do all the grimy bindings' generation. -} {-# LANGUAGE CPP, ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} module TcGenDeriv ( BagDerivStuff, DerivStuff(..), canDeriveAnyClass, genDerivedBinds, FFoldType(..), functorLikeTraverse, deepSubtypesContaining, foldDataConArgs, mkCoerceClassMethEqn, gen_Newtype_binds, genAuxBinds, ordOpTbl, boxConTbl, mkRdrFunBind ) where #include "HsVersions.h" import HsSyn import RdrName import BasicTypes import DataCon import Name import DynFlags import PrelInfo import FamInstEnv( FamInst ) import MkCore ( eRROR_ID ) import PrelNames hiding (error_RDR) import MkId ( coerceId ) import PrimOp import SrcLoc import TyCon import TcType import TysPrim import TysWiredIn import Type import Class import TypeRep import VarSet import VarEnv import State import Util import Var #if __GLASGOW_HASKELL__ < 709 import MonadUtils #endif import Outputable import Lexeme import FastString import Pair import Bag import TcEnv (InstInfo) import StaticFlags( opt_PprStyle_Debug ) import ListSetOps ( assocMaybe ) import Data.List ( partition, intersperse ) import Data.Maybe ( isNothing ) type BagDerivStuff = Bag DerivStuff data AuxBindSpec = DerivCon2Tag TyCon -- The con2Tag for given TyCon | DerivTag2Con TyCon -- ...ditto tag2Con | DerivMaxTag TyCon -- ...and maxTag deriving( Eq ) -- All these generate ZERO-BASED tag operations -- I.e first constructor has tag 0 data DerivStuff -- Please add this auxiliary stuff = DerivAuxBind AuxBindSpec -- Generics | DerivTyCon TyCon -- New data types | DerivFamInst FamInst -- New type family instances -- New top-level auxiliary bindings | DerivHsBind (LHsBind RdrName, LSig RdrName) -- Also used for SYB | DerivInst (InstInfo RdrName) -- New, auxiliary instances {- ************************************************************************ * * Top level function * * ************************************************************************ -} genDerivedBinds :: DynFlags -> (Name -> Fixity) -> Class -> SrcSpan -> TyCon -> ( LHsBinds RdrName -- The method bindings of the instance declaration , BagDerivStuff) -- Specifies extra top-level declarations needed -- to support the instance declaration genDerivedBinds dflags fix_env clas loc tycon | Just gen_fn <- assocMaybe gen_list (getUnique clas) = gen_fn loc tycon | otherwise -- Deriving any class simply means giving an empty instance, so no -- bindings have to be generated. = ASSERT2( isNothing (canDeriveAnyClass dflags tycon clas) , ppr "genDerivStuff: bad derived class" <+> ppr clas ) (emptyBag, emptyBag) where gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff))] gen_list = [ (eqClassKey, gen_Eq_binds) , (ordClassKey, gen_Ord_binds) , (enumClassKey, gen_Enum_binds) , (boundedClassKey, gen_Bounded_binds) , (ixClassKey, gen_Ix_binds) , (showClassKey, gen_Show_binds fix_env) , (readClassKey, gen_Read_binds fix_env) , (dataClassKey, gen_Data_binds dflags) , (functorClassKey, gen_Functor_binds) , (foldableClassKey, gen_Foldable_binds) , (traversableClassKey, gen_Traversable_binds) ] -- Nothing: we can (try to) derive it via Generics -- Just s: we can't, reason s canDeriveAnyClass :: DynFlags -> TyCon -> Class -> Maybe SDoc canDeriveAnyClass dflags _tycon clas = let b `orElse` s = if b then Nothing else Just (ptext (sLit s)) Just m <> _ = Just m Nothing <> n = n -- We can derive a given class for a given tycon via Generics iff in -- 1) The class is not a "standard" class (like Show, Functor, etc.) (not (getUnique clas `elem` standardClassKeys) `orElse` "") -- 2) Opt_DeriveAnyClass is on <> (xopt Opt_DeriveAnyClass dflags `orElse` "Try enabling DeriveAnyClass") {- ************************************************************************ * * Eq instances * * ************************************************************************ Here are the heuristics for the code we generate for @Eq@. Let's assume we have a data type with some (possibly zero) nullary data constructors and some ordinary, non-nullary ones (the rest, also possibly zero of them). Here's an example, with both \tr{N}ullary and \tr{O}rdinary data cons. data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ... * For the ordinary constructors (if any), we emit clauses to do The Usual Thing, e.g.,: (==) (O1 a1 b1) (O1 a2 b2) = a1 == a2 && b1 == b2 (==) (O2 a1) (O2 a2) = a1 == a2 (==) (O3 a1 b1 c1) (O3 a2 b2 c2) = a1 == a2 && b1 == b2 && c1 == c2 Note: if we're comparing unlifted things, e.g., if 'a1' and 'a2' are Float#s, then we have to generate case (a1 `eqFloat#` a2) of r -> r for that particular test. * If there are a lot of (more than en) nullary constructors, we emit a catch-all clause of the form: (==) a b = case (con2tag_Foo a) of { a# -> case (con2tag_Foo b) of { b# -> case (a# ==# b#) of { r -> r }}} If con2tag gets inlined this leads to join point stuff, so it's better to use regular pattern matching if there aren't too many nullary constructors. "Ten" is arbitrary, of course * If there aren't any nullary constructors, we emit a simpler catch-all: (==) a b = False * For the @(/=)@ method, we normally just use the default method. If the type is an enumeration type, we could/may/should? generate special code that calls @con2tag_Foo@, much like for @(==)@ shown above. We thought about doing this: If we're also deriving 'Ord' for this tycon, we generate: instance ... Eq (Foo ...) where (==) a b = case (compare a b) of { _LT -> False; _EQ -> True ; _GT -> False} (/=) a b = case (compare a b) of { _LT -> True ; _EQ -> False; _GT -> True } However, that requires that (Ord <whatever>) was put in the context for the instance decl, which it probably wasn't, so the decls produced don't get through the typechecker. -} gen_Eq_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Eq_binds loc tycon = (method_binds, aux_binds) where all_cons = tyConDataCons tycon (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon all_cons -- If there are ten or more (arbitrary number) nullary constructors, -- use the con2tag stuff. For small types it's better to use -- ordinary pattern matching. (tag_match_cons, pat_match_cons) | nullary_cons `lengthExceeds` 10 = (nullary_cons, non_nullary_cons) | otherwise = ([], all_cons) no_tag_match_cons = null tag_match_cons fall_through_eqn | no_tag_match_cons -- All constructors have arguments = case pat_match_cons of [] -> [] -- No constructors; no fall-though case [_] -> [] -- One constructor; no fall-though case _ -> -- Two or more constructors; add fall-through of -- (==) _ _ = False [([nlWildPat, nlWildPat], false_Expr)] | otherwise -- One or more tag_match cons; add fall-through of -- extract tags compare for equality = [([a_Pat, b_Pat], untag_Expr tycon [(a_RDR,ah_RDR), (b_RDR,bh_RDR)] (genPrimOpApp (nlHsVar ah_RDR) eqInt_RDR (nlHsVar bh_RDR)))] aux_binds | no_tag_match_cons = emptyBag | otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon method_binds = listToBag [eq_bind, ne_bind] eq_bind = mk_FunBind loc eq_RDR (map pats_etc pat_match_cons ++ fall_through_eqn) ne_bind = mk_easy_FunBind loc ne_RDR [a_Pat, b_Pat] ( nlHsApp (nlHsVar not_RDR) (nlHsPar (nlHsVarApps eq_RDR [a_RDR, b_RDR]))) ------------------------------------------------------------------ pats_etc data_con = let con1_pat = nlConVarPat data_con_RDR as_needed con2_pat = nlConVarPat data_con_RDR bs_needed data_con_RDR = getRdrName data_con con_arity = length tys_needed as_needed = take con_arity as_RDRs bs_needed = take con_arity bs_RDRs tys_needed = dataConOrigArgTys data_con in ([con1_pat, con2_pat], nested_eq_expr tys_needed as_needed bs_needed) where nested_eq_expr [] [] [] = true_Expr nested_eq_expr tys as bs = foldl1 and_Expr (zipWith3Equal "nested_eq" nested_eq tys as bs) where nested_eq ty a b = nlHsPar (eq_Expr tycon ty (nlHsVar a) (nlHsVar b)) {- ************************************************************************ * * Ord instances * * ************************************************************************ Note [Generating Ord instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose constructors are K1..Kn, and some are nullary. The general form we generate is: * Do case on first argument case a of K1 ... -> rhs_1 K2 ... -> rhs_2 ... Kn ... -> rhs_n _ -> nullary_rhs * To make rhs_i If i = 1, 2, n-1, n, generate a single case. rhs_2 case b of K1 {} -> LT K2 ... -> ...eq_rhs(K2)... _ -> GT Otherwise do a tag compare against the bigger range (because this is the one most likely to succeed) rhs_3 case tag b of tb -> if 3 <# tg then GT else case b of K3 ... -> ...eq_rhs(K3).... _ -> LT * To make eq_rhs(K), which knows that a = K a1 .. av b = K b1 .. bv we just want to compare (a1,b1) then (a2,b2) etc. Take care on the last field to tail-call into comparing av,bv * To make nullary_rhs generate this case con2tag a of a# -> case con2tag b of -> a# `compare` b# Several special cases: * Two or fewer nullary constructors: don't generate nullary_rhs * Be careful about unlifted comparisons. When comparing unboxed values we can't call the overloaded functions. See function unliftedOrdOp Note [Do not rely on compare] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's a bad idea to define only 'compare', and build the other binary comparisons on top of it; see Trac #2130, #4019. Reason: we don't want to laboriously make a three-way comparison, only to extract a binary result, something like this: (>) (I# x) (I# y) = case <# x y of True -> False False -> case ==# x y of True -> False False -> True So for sufficiently small types (few constructors, or all nullary) we generate all methods; for large ones we just use 'compare'. -} data OrdOp = OrdCompare | OrdLT | OrdLE | OrdGE | OrdGT ------------ ordMethRdr :: OrdOp -> RdrName ordMethRdr op = case op of OrdCompare -> compare_RDR OrdLT -> lt_RDR OrdLE -> le_RDR OrdGE -> ge_RDR OrdGT -> gt_RDR ------------ ltResult :: OrdOp -> LHsExpr RdrName -- Knowing a<b, what is the result for a `op` b? ltResult OrdCompare = ltTag_Expr ltResult OrdLT = true_Expr ltResult OrdLE = true_Expr ltResult OrdGE = false_Expr ltResult OrdGT = false_Expr ------------ eqResult :: OrdOp -> LHsExpr RdrName -- Knowing a=b, what is the result for a `op` b? eqResult OrdCompare = eqTag_Expr eqResult OrdLT = false_Expr eqResult OrdLE = true_Expr eqResult OrdGE = true_Expr eqResult OrdGT = false_Expr ------------ gtResult :: OrdOp -> LHsExpr RdrName -- Knowing a>b, what is the result for a `op` b? gtResult OrdCompare = gtTag_Expr gtResult OrdLT = false_Expr gtResult OrdLE = false_Expr gtResult OrdGE = true_Expr gtResult OrdGT = true_Expr ------------ gen_Ord_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Ord_binds loc tycon | null tycon_data_cons -- No data-cons => invoke bale-out case = (unitBag $ mk_FunBind loc compare_RDR [], emptyBag) | otherwise = (unitBag (mkOrdOp OrdCompare) `unionBags` other_ops, aux_binds) where aux_binds | single_con_type = emptyBag | otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon -- Note [Do not rely on compare] other_ops | (last_tag - first_tag) <= 2 -- 1-3 constructors || null non_nullary_cons -- Or it's an enumeration = listToBag (map mkOrdOp [OrdLT,OrdLE,OrdGE,OrdGT]) | otherwise = emptyBag get_tag con = dataConTag con - fIRST_TAG -- We want *zero-based* tags, because that's what -- con2Tag returns (generated by untag_Expr)! tycon_data_cons = tyConDataCons tycon single_con_type = isSingleton tycon_data_cons (first_con : _) = tycon_data_cons (last_con : _) = reverse tycon_data_cons first_tag = get_tag first_con last_tag = get_tag last_con (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon tycon_data_cons mkOrdOp :: OrdOp -> LHsBind RdrName -- Returns a binding op a b = ... compares a and b according to op .... mkOrdOp op = mk_easy_FunBind loc (ordMethRdr op) [a_Pat, b_Pat] (mkOrdOpRhs op) mkOrdOpRhs :: OrdOp -> LHsExpr RdrName mkOrdOpRhs op -- RHS for comparing 'a' and 'b' according to op | length nullary_cons <= 2 -- Two nullary or fewer, so use cases = nlHsCase (nlHsVar a_RDR) $ map (mkOrdOpAlt op) tycon_data_cons -- i.e. case a of { C1 x y -> case b of C1 x y -> ....compare x,y... -- C2 x -> case b of C2 x -> ....comopare x.... } | null non_nullary_cons -- All nullary, so go straight to comparing tags = mkTagCmp op | otherwise -- Mixed nullary and non-nullary = nlHsCase (nlHsVar a_RDR) $ (map (mkOrdOpAlt op) non_nullary_cons ++ [mkSimpleHsAlt nlWildPat (mkTagCmp op)]) mkOrdOpAlt :: OrdOp -> DataCon -> LMatch RdrName (LHsExpr RdrName) -- Make the alternative (Ki a1 a2 .. av -> mkOrdOpAlt op data_con = mkSimpleHsAlt (nlConVarPat data_con_RDR as_needed) (mkInnerRhs op data_con) where as_needed = take (dataConSourceArity data_con) as_RDRs data_con_RDR = getRdrName data_con mkInnerRhs op data_con | single_con_type = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con ] | tag == first_tag = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (ltResult op) ] | tag == last_tag = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (gtResult op) ] | tag == first_tag + 1 = nlHsCase (nlHsVar b_RDR) [ mkSimpleHsAlt (nlConWildPat first_con) (gtResult op) , mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (ltResult op) ] | tag == last_tag - 1 = nlHsCase (nlHsVar b_RDR) [ mkSimpleHsAlt (nlConWildPat last_con) (ltResult op) , mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (gtResult op) ] | tag > last_tag `div` 2 -- lower range is larger = untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsIf (genPrimOpApp (nlHsVar bh_RDR) ltInt_RDR tag_lit) (gtResult op) $ -- Definitely GT nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (ltResult op) ] | otherwise -- upper range is larger = untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsIf (genPrimOpApp (nlHsVar bh_RDR) gtInt_RDR tag_lit) (ltResult op) $ -- Definitely LT nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkSimpleHsAlt nlWildPat (gtResult op) ] where tag = get_tag data_con tag_lit = noLoc (HsLit (HsIntPrim "" (toInteger tag))) mkInnerEqAlt :: OrdOp -> DataCon -> LMatch RdrName (LHsExpr RdrName) -- First argument 'a' known to be built with K -- Returns a case alternative Ki b1 b2 ... bv -> compare (a1,a2,...) with (b1,b2,...) mkInnerEqAlt op data_con = mkSimpleHsAlt (nlConVarPat data_con_RDR bs_needed) $ mkCompareFields tycon op (dataConOrigArgTys data_con) where data_con_RDR = getRdrName data_con bs_needed = take (dataConSourceArity data_con) bs_RDRs mkTagCmp :: OrdOp -> LHsExpr RdrName -- Both constructors known to be nullary -- genreates (case data2Tag a of a# -> case data2Tag b of b# -> a# `op` b# mkTagCmp op = untag_Expr tycon [(a_RDR, ah_RDR),(b_RDR, bh_RDR)] $ unliftedOrdOp tycon intPrimTy op ah_RDR bh_RDR mkCompareFields :: TyCon -> OrdOp -> [Type] -> LHsExpr RdrName -- Generates nested comparisons for (a1,a2...) against (b1,b2,...) -- where the ai,bi have the given types mkCompareFields tycon op tys = go tys as_RDRs bs_RDRs where go [] _ _ = eqResult op go [ty] (a:_) (b:_) | isUnLiftedType ty = unliftedOrdOp tycon ty op a b | otherwise = genOpApp (nlHsVar a) (ordMethRdr op) (nlHsVar b) go (ty:tys) (a:as) (b:bs) = mk_compare ty a b (ltResult op) (go tys as bs) (gtResult op) go _ _ _ = panic "mkCompareFields" -- (mk_compare ty a b) generates -- (case (compare a b) of { LT -> <lt>; EQ -> <eq>; GT -> <bt> }) -- but with suitable special cases for mk_compare ty a b lt eq gt | isUnLiftedType ty = unliftedCompare lt_op eq_op a_expr b_expr lt eq gt | otherwise = nlHsCase (nlHsPar (nlHsApp (nlHsApp (nlHsVar compare_RDR) a_expr) b_expr)) [mkSimpleHsAlt (nlNullaryConPat ltTag_RDR) lt, mkSimpleHsAlt (nlNullaryConPat eqTag_RDR) eq, mkSimpleHsAlt (nlNullaryConPat gtTag_RDR) gt] where a_expr = nlHsVar a b_expr = nlHsVar b (lt_op, _, eq_op, _, _) = primOrdOps "Ord" tycon ty unliftedOrdOp :: TyCon -> Type -> OrdOp -> RdrName -> RdrName -> LHsExpr RdrName unliftedOrdOp tycon ty op a b = case op of OrdCompare -> unliftedCompare lt_op eq_op a_expr b_expr ltTag_Expr eqTag_Expr gtTag_Expr OrdLT -> wrap lt_op OrdLE -> wrap le_op OrdGE -> wrap ge_op OrdGT -> wrap gt_op where (lt_op, le_op, eq_op, ge_op, gt_op) = primOrdOps "Ord" tycon ty wrap prim_op = genPrimOpApp a_expr prim_op b_expr a_expr = nlHsVar a b_expr = nlHsVar b unliftedCompare :: RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName -- What to cmpare -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName -- Three results -> LHsExpr RdrName -- Return (if a < b then lt else if a == b then eq else gt) unliftedCompare lt_op eq_op a_expr b_expr lt eq gt = nlHsIf (genPrimOpApp a_expr lt_op b_expr) lt $ -- Test (<) first, not (==), because the latter -- is true less often, so putting it first would -- mean more tests (dynamically) nlHsIf (genPrimOpApp a_expr eq_op b_expr) eq gt nlConWildPat :: DataCon -> LPat RdrName -- The pattern (K {}) nlConWildPat con = noLoc (ConPatIn (noLoc (getRdrName con)) (RecCon (HsRecFields { rec_flds = [] , rec_dotdot = Nothing }))) {- ************************************************************************ * * Enum instances * * ************************************************************************ @Enum@ can only be derived for enumeration types. For a type \begin{verbatim} data Foo ... = N1 | N2 | ... | Nn \end{verbatim} we use both @con2tag_Foo@ and @tag2con_Foo@ functions, as well as a @maxtag_Foo@ variable (all generated by @gen_tag_n_con_binds@). \begin{verbatim} instance ... Enum (Foo ...) where succ x = toEnum (1 + fromEnum x) pred x = toEnum (fromEnum x - 1) toEnum i = tag2con_Foo i enumFrom a = map tag2con_Foo [con2tag_Foo a .. maxtag_Foo] -- or, really... enumFrom a = case con2tag_Foo a of a# -> map tag2con_Foo (enumFromTo (I# a#) maxtag_Foo) enumFromThen a b = map tag2con_Foo [con2tag_Foo a, con2tag_Foo b .. maxtag_Foo] -- or, really... enumFromThen a b = case con2tag_Foo a of { a# -> case con2tag_Foo b of { b# -> map tag2con_Foo (enumFromThenTo (I# a#) (I# b#) maxtag_Foo) }} \end{verbatim} For @enumFromTo@ and @enumFromThenTo@, we use the default methods. -} gen_Enum_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Enum_binds loc tycon = (method_binds, aux_binds) where method_binds = listToBag [ succ_enum, pred_enum, to_enum, enum_from, enum_from_then, from_enum ] aux_binds = listToBag $ map DerivAuxBind [DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon] occ_nm = getOccString tycon succ_enum = mk_easy_FunBind loc succ_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsIf (nlHsApps eq_RDR [nlHsVar (maxtag_RDR tycon), nlHsVarApps intDataCon_RDR [ah_RDR]]) (illegal_Expr "succ" occ_nm "tried to take `succ' of last tag in enumeration") (nlHsApp (nlHsVar (tag2con_RDR tycon)) (nlHsApps plus_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsIntLit 1])) pred_enum = mk_easy_FunBind loc pred_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsIf (nlHsApps eq_RDR [nlHsIntLit 0, nlHsVarApps intDataCon_RDR [ah_RDR]]) (illegal_Expr "pred" occ_nm "tried to take `pred' of first tag in enumeration") (nlHsApp (nlHsVar (tag2con_RDR tycon)) (nlHsApps plus_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsLit (HsInt "-1" (-1))])) to_enum = mk_easy_FunBind loc toEnum_RDR [a_Pat] $ nlHsIf (nlHsApps and_RDR [nlHsApps ge_RDR [nlHsVar a_RDR, nlHsIntLit 0], nlHsApps le_RDR [nlHsVar a_RDR, nlHsVar (maxtag_RDR tycon)]]) (nlHsVarApps (tag2con_RDR tycon) [a_RDR]) (illegal_toEnum_tag occ_nm (maxtag_RDR tycon)) enum_from = mk_easy_FunBind loc enumFrom_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsApps map_RDR [nlHsVar (tag2con_RDR tycon), nlHsPar (enum_from_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVar (maxtag_RDR tycon)))] enum_from_then = mk_easy_FunBind loc enumFromThen_RDR [a_Pat, b_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)] $ nlHsApp (nlHsVarApps map_RDR [tag2con_RDR tycon]) $ nlHsPar (enum_from_then_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVarApps intDataCon_RDR [bh_RDR]) (nlHsIf (nlHsApps gt_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsVarApps intDataCon_RDR [bh_RDR]]) (nlHsIntLit 0) (nlHsVar (maxtag_RDR tycon)) )) from_enum = mk_easy_FunBind loc fromEnum_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ (nlHsVarApps intDataCon_RDR [ah_RDR]) {- ************************************************************************ * * Bounded instances * * ************************************************************************ -} gen_Bounded_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Bounded_binds loc tycon | isEnumerationTyCon tycon = (listToBag [ min_bound_enum, max_bound_enum ], emptyBag) | otherwise = ASSERT(isSingleton data_cons) (listToBag [ min_bound_1con, max_bound_1con ], emptyBag) where data_cons = tyConDataCons tycon ----- enum-flavored: --------------------------- min_bound_enum = mkHsVarBind loc minBound_RDR (nlHsVar data_con_1_RDR) max_bound_enum = mkHsVarBind loc maxBound_RDR (nlHsVar data_con_N_RDR) data_con_1 = head data_cons data_con_N = last data_cons data_con_1_RDR = getRdrName data_con_1 data_con_N_RDR = getRdrName data_con_N ----- single-constructor-flavored: ------------- arity = dataConSourceArity data_con_1 min_bound_1con = mkHsVarBind loc minBound_RDR $ nlHsVarApps data_con_1_RDR (nOfThem arity minBound_RDR) max_bound_1con = mkHsVarBind loc maxBound_RDR $ nlHsVarApps data_con_1_RDR (nOfThem arity maxBound_RDR) {- ************************************************************************ * * Ix instances * * ************************************************************************ Deriving @Ix@ is only possible for enumeration types and single-constructor types. We deal with them in turn. For an enumeration type, e.g., \begin{verbatim} data Foo ... = N1 | N2 | ... | Nn \end{verbatim} things go not too differently from @Enum@: \begin{verbatim} instance ... Ix (Foo ...) where range (a, b) = map tag2con_Foo [con2tag_Foo a .. con2tag_Foo b] -- or, really... range (a, b) = case (con2tag_Foo a) of { a# -> case (con2tag_Foo b) of { b# -> map tag2con_Foo (enumFromTo (I# a#) (I# b#)) }} -- Generate code for unsafeIndex, because using index leads -- to lots of redundant range tests unsafeIndex c@(a, b) d = case (con2tag_Foo d -# con2tag_Foo a) of r# -> I# r# inRange (a, b) c = let p_tag = con2tag_Foo c in p_tag >= con2tag_Foo a && p_tag <= con2tag_Foo b -- or, really... inRange (a, b) c = case (con2tag_Foo a) of { a_tag -> case (con2tag_Foo b) of { b_tag -> case (con2tag_Foo c) of { c_tag -> if (c_tag >=# a_tag) then c_tag <=# b_tag else False }}} \end{verbatim} (modulo suitable case-ification to handle the unlifted tags) For a single-constructor type (NB: this includes all tuples), e.g., \begin{verbatim} data Foo ... = MkFoo a b Int Double c c \end{verbatim} we follow the scheme given in Figure~19 of the Haskell~1.2 report (p.~147). -} gen_Ix_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Ix_binds loc tycon | isEnumerationTyCon tycon = ( enum_ixes , listToBag $ map DerivAuxBind [DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon]) | otherwise = (single_con_ixes, unitBag (DerivAuxBind (DerivCon2Tag tycon))) where -------------------------------------------------------------- enum_ixes = listToBag [ enum_range, enum_index, enum_inRange ] enum_range = mk_easy_FunBind loc range_RDR [nlTuplePat [a_Pat, b_Pat] Boxed] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsApp (nlHsVarApps map_RDR [tag2con_RDR tycon]) $ nlHsPar (enum_from_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVarApps intDataCon_RDR [bh_RDR])) enum_index = mk_easy_FunBind loc unsafeIndex_RDR [noLoc (AsPat (noLoc c_RDR) (nlTuplePat [a_Pat, nlWildPat] Boxed)), d_Pat] ( untag_Expr tycon [(a_RDR, ah_RDR)] ( untag_Expr tycon [(d_RDR, dh_RDR)] ( let rhs = nlHsVarApps intDataCon_RDR [c_RDR] in nlHsCase (genOpApp (nlHsVar dh_RDR) minusInt_RDR (nlHsVar ah_RDR)) [mkSimpleHsAlt (nlVarPat c_RDR) rhs] )) ) enum_inRange = mk_easy_FunBind loc inRange_RDR [nlTuplePat [a_Pat, b_Pat] Boxed, c_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] ( untag_Expr tycon [(b_RDR, bh_RDR)] ( untag_Expr tycon [(c_RDR, ch_RDR)] ( nlHsIf (genPrimOpApp (nlHsVar ch_RDR) geInt_RDR (nlHsVar ah_RDR)) ( (genPrimOpApp (nlHsVar ch_RDR) leInt_RDR (nlHsVar bh_RDR)) ) {-else-} ( false_Expr )))) -------------------------------------------------------------- single_con_ixes = listToBag [single_con_range, single_con_index, single_con_inRange] data_con = case tyConSingleDataCon_maybe tycon of -- just checking... Nothing -> panic "get_Ix_binds" Just dc -> dc con_arity = dataConSourceArity data_con data_con_RDR = getRdrName data_con as_needed = take con_arity as_RDRs bs_needed = take con_arity bs_RDRs cs_needed = take con_arity cs_RDRs con_pat xs = nlConVarPat data_con_RDR xs con_expr = nlHsVarApps data_con_RDR cs_needed -------------------------------------------------------------- single_con_range = mk_easy_FunBind loc range_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed] $ noLoc (mkHsComp ListComp stmts con_expr) where stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed mk_qual a b c = noLoc $ mkBindStmt (nlVarPat c) (nlHsApp (nlHsVar range_RDR) (mkLHsVarTuple [a,b])) ---------------- single_con_index = mk_easy_FunBind loc unsafeIndex_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed, con_pat cs_needed] -- We need to reverse the order we consider the components in -- so that -- range (l,u) !! index (l,u) i == i -- when i is in range -- (from http://haskell.org/onlinereport/ix.html) holds. (mk_index (reverse $ zip3 as_needed bs_needed cs_needed)) where -- index (l1,u1) i1 + rangeSize (l1,u1) * (index (l2,u2) i2 + ...) mk_index [] = nlHsIntLit 0 mk_index [(l,u,i)] = mk_one l u i mk_index ((l,u,i) : rest) = genOpApp ( mk_one l u i ) plus_RDR ( genOpApp ( (nlHsApp (nlHsVar unsafeRangeSize_RDR) (mkLHsVarTuple [l,u])) ) times_RDR (mk_index rest) ) mk_one l u i = nlHsApps unsafeIndex_RDR [mkLHsVarTuple [l,u], nlHsVar i] ------------------ single_con_inRange = mk_easy_FunBind loc inRange_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed, con_pat cs_needed] $ foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range as_needed bs_needed cs_needed) where in_range a b c = nlHsApps inRange_RDR [mkLHsVarTuple [a,b], nlHsVar c] {- ************************************************************************ * * Read instances * * ************************************************************************ Example infix 4 %% data T = Int %% Int | T1 { f1 :: Int } | T2 T instance Read T where readPrec = parens ( prec 4 ( do x <- ReadP.step Read.readPrec expectP (Symbol "%%") y <- ReadP.step Read.readPrec return (x %% y)) +++ prec (appPrec+1) ( -- Note the "+1" part; "T2 T1 {f1=3}" should parse ok -- Record construction binds even more tightly than application do expectP (Ident "T1") expectP (Punc '{') expectP (Ident "f1") expectP (Punc '=') x <- ReadP.reset Read.readPrec expectP (Punc '}') return (T1 { f1 = x })) +++ prec appPrec ( do expectP (Ident "T2") x <- ReadP.step Read.readPrec return (T2 x)) ) readListPrec = readListPrecDefault readList = readListDefault Note [Use expectP] ~~~~~~~~~~~~~~~~~~ Note that we use expectP (Ident "T1") rather than Ident "T1" <- lexP The latter desugares to inline code for matching the Ident and the string, and this can be very voluminous. The former is much more compact. Cf Trac #7258, although that also concerned non-linearity in the occurrence analyser, a separate issue. Note [Read for empty data types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What should we get for this? (Trac #7931) data Emp deriving( Read ) -- No data constructors Here we want read "[]" :: [Emp] to succeed, returning [] So we do NOT want instance Read Emp where readPrec = error "urk" Rather we want instance Read Emp where readPred = pfail -- Same as choose [] Because 'pfail' allows the parser to backtrack, but 'error' doesn't. These instances are also useful for Read (Either Int Emp), where we want to be able to parse (Left 3) just fine. -} gen_Read_binds :: (Name -> Fixity) -> SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Read_binds get_fixity loc tycon = (listToBag [read_prec, default_readlist, default_readlistprec], emptyBag) where ----------------------------------------------------------------------- default_readlist = mkHsVarBind loc readList_RDR (nlHsVar readListDefault_RDR) default_readlistprec = mkHsVarBind loc readListPrec_RDR (nlHsVar readListPrecDefault_RDR) ----------------------------------------------------------------------- data_cons = tyConDataCons tycon (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon data_cons read_prec = mkHsVarBind loc readPrec_RDR (nlHsApp (nlHsVar parens_RDR) read_cons) read_cons | null data_cons = nlHsVar pfail_RDR -- See Note [Read for empty data types] | otherwise = foldr1 mk_alt (read_nullary_cons ++ read_non_nullary_cons) read_non_nullary_cons = map read_non_nullary_con non_nullary_cons read_nullary_cons = case nullary_cons of [] -> [] [con] -> [nlHsDo DoExpr (match_con con ++ [noLoc $ mkLastStmt (result_expr con [])])] _ -> [nlHsApp (nlHsVar choose_RDR) (nlList (map mk_pair nullary_cons))] -- NB For operators the parens around (:=:) are matched by the -- enclosing "parens" call, so here we must match the naked -- data_con_str con match_con con | isSym con_str = [symbol_pat con_str] | otherwise = ident_h_pat con_str where con_str = data_con_str con -- For nullary constructors we must match Ident s for normal constrs -- and Symbol s for operators mk_pair con = mkLHsTupleExpr [nlHsLit (mkHsString (data_con_str con)), result_expr con []] read_non_nullary_con data_con | is_infix = mk_parser infix_prec infix_stmts body | is_record = mk_parser record_prec record_stmts body -- Using these two lines instead allows the derived -- read for infix and record bindings to read the prefix form -- | is_infix = mk_alt prefix_parser (mk_parser infix_prec infix_stmts body) -- | is_record = mk_alt prefix_parser (mk_parser record_prec record_stmts body) | otherwise = prefix_parser where body = result_expr data_con as_needed con_str = data_con_str data_con prefix_parser = mk_parser prefix_prec prefix_stmts body read_prefix_con | isSym con_str = [read_punc "(", symbol_pat con_str, read_punc ")"] | otherwise = ident_h_pat con_str read_infix_con | isSym con_str = [symbol_pat con_str] | otherwise = [read_punc "`"] ++ ident_h_pat con_str ++ [read_punc "`"] prefix_stmts -- T a b c = read_prefix_con ++ read_args infix_stmts -- a %% b, or a `T` b = [read_a1] ++ read_infix_con ++ [read_a2] record_stmts -- T { f1 = a, f2 = b } = read_prefix_con ++ [read_punc "{"] ++ concat (intersperse [read_punc ","] field_stmts) ++ [read_punc "}"] field_stmts = zipWithEqual "lbl_stmts" read_field labels as_needed con_arity = dataConSourceArity data_con labels = dataConFieldLabels data_con dc_nm = getName data_con is_infix = dataConIsInfix data_con is_record = length labels > 0 as_needed = take con_arity as_RDRs read_args = zipWithEqual "gen_Read_binds" read_arg as_needed (dataConOrigArgTys data_con) (read_a1:read_a2:_) = read_args prefix_prec = appPrecedence infix_prec = getPrecedence get_fixity dc_nm record_prec = appPrecedence + 1 -- Record construction binds even more tightly -- than application; e.g. T2 T1 {x=2} means T2 (T1 {x=2}) ------------------------------------------------------------------------ -- Helpers ------------------------------------------------------------------------ mk_alt e1 e2 = genOpApp e1 alt_RDR e2 -- e1 +++ e2 mk_parser p ss b = nlHsApps prec_RDR [nlHsIntLit p -- prec p (do { ss ; b }) , nlHsDo DoExpr (ss ++ [noLoc $ mkLastStmt b])] con_app con as = nlHsVarApps (getRdrName con) as -- con as result_expr con as = nlHsApp (nlHsVar returnM_RDR) (con_app con as) -- return (con as) -- For constructors and field labels ending in '#', we hackily -- let the lexer generate two tokens, and look for both in sequence -- Thus [Ident "I"; Symbol "#"]. See Trac #5041 ident_h_pat s | Just (ss, '#') <- snocView s = [ ident_pat ss, symbol_pat "#" ] | otherwise = [ ident_pat s ] bindLex pat = noLoc (mkBodyStmt (nlHsApp (nlHsVar expectP_RDR) pat)) -- expectP p -- See Note [Use expectP] ident_pat s = bindLex $ nlHsApps ident_RDR [nlHsLit (mkHsString s)] -- expectP (Ident "foo") symbol_pat s = bindLex $ nlHsApps symbol_RDR [nlHsLit (mkHsString s)] -- expectP (Symbol ">>") read_punc c = bindLex $ nlHsApps punc_RDR [nlHsLit (mkHsString c)] -- expectP (Punc "<") data_con_str con = occNameString (getOccName con) read_arg a ty = ASSERT( not (isUnLiftedType ty) ) noLoc (mkBindStmt (nlVarPat a) (nlHsVarApps step_RDR [readPrec_RDR])) read_field lbl a = read_lbl lbl ++ [read_punc "=", noLoc (mkBindStmt (nlVarPat a) (nlHsVarApps reset_RDR [readPrec_RDR]))] -- When reading field labels we might encounter -- a = 3 -- _a = 3 -- or (#) = 4 -- Note the parens! read_lbl lbl | isSym lbl_str = [read_punc "(", symbol_pat lbl_str, read_punc ")"] | otherwise = ident_h_pat lbl_str where lbl_str = occNameString (getOccName lbl) {- ************************************************************************ * * Show instances * * ************************************************************************ Example infixr 5 :^: data Tree a = Leaf a | Tree a :^: Tree a instance (Show a) => Show (Tree a) where showsPrec d (Leaf m) = showParen (d > app_prec) showStr where showStr = showString "Leaf " . showsPrec (app_prec+1) m showsPrec d (u :^: v) = showParen (d > up_prec) showStr where showStr = showsPrec (up_prec+1) u . showString " :^: " . showsPrec (up_prec+1) v -- Note: right-associativity of :^: ignored up_prec = 5 -- Precedence of :^: app_prec = 10 -- Application has precedence one more than -- the most tightly-binding operator -} gen_Show_binds :: (Name -> Fixity) -> SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Show_binds get_fixity loc tycon = (listToBag [shows_prec, show_list], emptyBag) where ----------------------------------------------------------------------- show_list = mkHsVarBind loc showList_RDR (nlHsApp (nlHsVar showList___RDR) (nlHsPar (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)))) ----------------------------------------------------------------------- data_cons = tyConDataCons tycon shows_prec = mk_FunBind loc showsPrec_RDR (map pats_etc data_cons) pats_etc data_con | nullary_con = -- skip the showParen junk... ASSERT(null bs_needed) ([nlWildPat, con_pat], mk_showString_app op_con_str) | record_syntax = -- skip showParen (#2530) ([a_Pat, con_pat], nlHsPar (nested_compose_Expr show_thingies)) | otherwise = ([a_Pat, con_pat], showParen_Expr (genOpApp a_Expr ge_RDR (nlHsLit (HsInt "" con_prec_plus_one))) (nlHsPar (nested_compose_Expr show_thingies))) where data_con_RDR = getRdrName data_con con_arity = dataConSourceArity data_con bs_needed = take con_arity bs_RDRs arg_tys = dataConOrigArgTys data_con -- Correspond 1-1 with bs_needed con_pat = nlConVarPat data_con_RDR bs_needed nullary_con = con_arity == 0 labels = dataConFieldLabels data_con lab_fields = length labels record_syntax = lab_fields > 0 dc_nm = getName data_con dc_occ_nm = getOccName data_con con_str = occNameString dc_occ_nm op_con_str = wrapOpParens con_str backquote_str = wrapOpBackquotes con_str show_thingies | is_infix = [show_arg1, mk_showString_app (" " ++ backquote_str ++ " "), show_arg2] | record_syntax = mk_showString_app (op_con_str ++ " {") : show_record_args ++ [mk_showString_app "}"] | otherwise = mk_showString_app (op_con_str ++ " ") : show_prefix_args show_label l = mk_showString_app (nm ++ " = ") -- Note the spaces around the "=" sign. If we -- don't have them then we get Foo { x=-1 } and -- the "=-" parses as a single lexeme. Only the -- space after the '=' is necessary, but it -- seems tidier to have them both sides. where occ_nm = getOccName l nm = wrapOpParens (occNameString occ_nm) show_args = zipWith show_arg bs_needed arg_tys (show_arg1:show_arg2:_) = show_args show_prefix_args = intersperse (nlHsVar showSpace_RDR) show_args -- Assumption for record syntax: no of fields == no of -- labelled fields (and in same order) show_record_args = concat $ intersperse [mk_showString_app ", "] $ [ [show_label lbl, arg] | (lbl,arg) <- zipEqual "gen_Show_binds" labels show_args ] show_arg :: RdrName -> Type -> LHsExpr RdrName show_arg b arg_ty | isUnLiftedType arg_ty -- See Note [Deriving and unboxed types] in TcDeriv = nlHsApps compose_RDR [mk_shows_app boxed_arg, mk_showString_app postfixMod] | otherwise = mk_showsPrec_app arg_prec arg where arg = nlHsVar b boxed_arg = box "Show" tycon arg arg_ty postfixMod = assoc_ty_id "Show" tycon postfixModTbl arg_ty -- Fixity stuff is_infix = dataConIsInfix data_con con_prec_plus_one = 1 + getPrec is_infix get_fixity dc_nm arg_prec | record_syntax = 0 -- Record fields don't need parens | otherwise = con_prec_plus_one wrapOpParens :: String -> String wrapOpParens s | isSym s = '(' : s ++ ")" | otherwise = s wrapOpBackquotes :: String -> String wrapOpBackquotes s | isSym s = s | otherwise = '`' : s ++ "`" isSym :: String -> Bool isSym "" = False isSym (c : _) = startsVarSym c || startsConSym c -- | showString :: String -> ShowS mk_showString_app :: String -> LHsExpr RdrName mk_showString_app str = nlHsApp (nlHsVar showString_RDR) (nlHsLit (mkHsString str)) -- | showsPrec :: Show a => Int -> a -> ShowS mk_showsPrec_app :: Integer -> LHsExpr RdrName -> LHsExpr RdrName mk_showsPrec_app p x = nlHsApps showsPrec_RDR [nlHsLit (HsInt "" p), x] -- | shows :: Show a => a -> ShowS mk_shows_app :: LHsExpr RdrName -> LHsExpr RdrName mk_shows_app x = nlHsApp (nlHsVar shows_RDR) x getPrec :: Bool -> (Name -> Fixity) -> Name -> Integer getPrec is_infix get_fixity nm | not is_infix = appPrecedence | otherwise = getPrecedence get_fixity nm appPrecedence :: Integer appPrecedence = fromIntegral maxPrecedence + 1 -- One more than the precedence of the most -- tightly-binding operator getPrecedence :: (Name -> Fixity) -> Name -> Integer getPrecedence get_fixity nm = case get_fixity nm of Fixity x _assoc -> fromIntegral x -- NB: the Report says that associativity is not taken -- into account for either Read or Show; hence we -- ignore associativity here {- ************************************************************************ * * Data instances * * ************************************************************************ From the data type data T a b = T1 a b | T2 we generate $cT1 = mkDataCon $dT "T1" Prefix $cT2 = mkDataCon $dT "T2" Prefix $dT = mkDataType "Module.T" [] [$con_T1, $con_T2] -- the [] is for field labels. instance (Data a, Data b) => Data (T a b) where gfoldl k z (T1 a b) = z T `k` a `k` b gfoldl k z T2 = z T2 -- ToDo: add gmapT,Q,M, gfoldr gunfold k z c = case conIndex c of I# 1# -> k (k (z T1)) I# 2# -> z T2 toConstr (T1 _ _) = $cT1 toConstr T2 = $cT2 dataTypeOf _ = $dT dataCast1 = gcast1 -- If T :: * -> * dataCast2 = gcast2 -- if T :: * -> * -> * -} gen_Data_binds :: DynFlags -> SrcSpan -> TyCon -- For data families, this is the -- *representation* TyCon -> (LHsBinds RdrName, -- The method bindings BagDerivStuff) -- Auxiliary bindings gen_Data_binds dflags loc rep_tc = (listToBag [gfoldl_bind, gunfold_bind, toCon_bind, dataTypeOf_bind] `unionBags` gcast_binds, -- Auxiliary definitions: the data type and constructors listToBag ( DerivHsBind (genDataTyCon) : map (DerivHsBind . genDataDataCon) data_cons)) where data_cons = tyConDataCons rep_tc n_cons = length data_cons one_constr = n_cons == 1 genDataTyCon :: (LHsBind RdrName, LSig RdrName) genDataTyCon -- $dT = (mkHsVarBind loc rdr_name rhs, L loc (TypeSig [L loc rdr_name] sig_ty PlaceHolder)) where rdr_name = mk_data_type_name rep_tc sig_ty = nlHsTyVar dataType_RDR constrs = [nlHsVar (mk_constr_name con) | con <- tyConDataCons rep_tc] rhs = nlHsVar mkDataType_RDR `nlHsApp` nlHsLit (mkHsString (showSDocOneLine dflags (ppr rep_tc))) `nlHsApp` nlList constrs genDataDataCon :: DataCon -> (LHsBind RdrName, LSig RdrName) genDataDataCon dc -- $cT1 etc = (mkHsVarBind loc rdr_name rhs, L loc (TypeSig [L loc rdr_name] sig_ty PlaceHolder)) where rdr_name = mk_constr_name dc sig_ty = nlHsTyVar constr_RDR rhs = nlHsApps mkConstr_RDR constr_args constr_args = [ -- nlHsIntLit (toInteger (dataConTag dc)), -- Tag nlHsVar (mk_data_type_name (dataConTyCon dc)), -- DataType nlHsLit (mkHsString (occNameString dc_occ)), -- String name nlList labels, -- Field labels nlHsVar fixity] -- Fixity labels = map (nlHsLit . mkHsString . getOccString) (dataConFieldLabels dc) dc_occ = getOccName dc is_infix = isDataSymOcc dc_occ fixity | is_infix = infix_RDR | otherwise = prefix_RDR ------------ gfoldl gfoldl_bind = mk_FunBind loc gfoldl_RDR (map gfoldl_eqn data_cons) gfoldl_eqn con = ([nlVarPat k_RDR, nlVarPat z_RDR, nlConVarPat con_name as_needed], foldl mk_k_app (nlHsVar z_RDR `nlHsApp` nlHsVar con_name) as_needed) where con_name :: RdrName con_name = getRdrName con as_needed = take (dataConSourceArity con) as_RDRs mk_k_app e v = nlHsPar (nlHsOpApp e k_RDR (nlHsVar v)) ------------ gunfold gunfold_bind = mk_FunBind loc gunfold_RDR [([k_Pat, z_Pat, if one_constr then nlWildPat else c_Pat], gunfold_rhs)] gunfold_rhs | one_constr = mk_unfold_rhs (head data_cons) -- No need for case | otherwise = nlHsCase (nlHsVar conIndex_RDR `nlHsApp` c_Expr) (map gunfold_alt data_cons) gunfold_alt dc = mkSimpleHsAlt (mk_unfold_pat dc) (mk_unfold_rhs dc) mk_unfold_rhs dc = foldr nlHsApp (nlHsVar z_RDR `nlHsApp` nlHsVar (getRdrName dc)) (replicate (dataConSourceArity dc) (nlHsVar k_RDR)) mk_unfold_pat dc -- Last one is a wild-pat, to avoid -- redundant test, and annoying warning | tag-fIRST_TAG == n_cons-1 = nlWildPat -- Last constructor | otherwise = nlConPat intDataCon_RDR [nlLitPat (HsIntPrim "" (toInteger tag))] where tag = dataConTag dc ------------ toConstr toCon_bind = mk_FunBind loc toConstr_RDR (map to_con_eqn data_cons) to_con_eqn dc = ([nlWildConPat dc], nlHsVar (mk_constr_name dc)) ------------ dataTypeOf dataTypeOf_bind = mk_easy_FunBind loc dataTypeOf_RDR [nlWildPat] (nlHsVar (mk_data_type_name rep_tc)) ------------ gcast1/2 -- Make the binding dataCast1 x = gcast1 x -- if T :: * -> * -- or dataCast2 x = gcast2 s -- if T :: * -> * -> * -- (or nothing if T has neither of these two types) -- But care is needed for data families: -- If we have data family D a -- data instance D (a,b,c) = A | B deriving( Data ) -- and we want instance ... => Data (D [(a,b,c)]) where ... -- then we need dataCast1 x = gcast1 x -- because D :: * -> * -- even though rep_tc has kind * -> * -> * -> * -- Hence looking for the kind of fam_tc not rep_tc -- See Trac #4896 tycon_kind = case tyConFamInst_maybe rep_tc of Just (fam_tc, _) -> tyConKind fam_tc Nothing -> tyConKind rep_tc gcast_binds | tycon_kind `tcEqKind` kind1 = mk_gcast dataCast1_RDR gcast1_RDR | tycon_kind `tcEqKind` kind2 = mk_gcast dataCast2_RDR gcast2_RDR | otherwise = emptyBag mk_gcast dataCast_RDR gcast_RDR = unitBag (mk_easy_FunBind loc dataCast_RDR [nlVarPat f_RDR] (nlHsVar gcast_RDR `nlHsApp` nlHsVar f_RDR)) kind1, kind2 :: Kind kind1 = liftedTypeKind `mkArrowKind` liftedTypeKind kind2 = liftedTypeKind `mkArrowKind` kind1 gfoldl_RDR, gunfold_RDR, toConstr_RDR, dataTypeOf_RDR, mkConstr_RDR, mkDataType_RDR, conIndex_RDR, prefix_RDR, infix_RDR, dataCast1_RDR, dataCast2_RDR, gcast1_RDR, gcast2_RDR, constr_RDR, dataType_RDR, eqChar_RDR , ltChar_RDR , geChar_RDR , gtChar_RDR , leChar_RDR , eqInt_RDR , ltInt_RDR , geInt_RDR , gtInt_RDR , leInt_RDR , eqWord_RDR , ltWord_RDR , geWord_RDR , gtWord_RDR , leWord_RDR , eqAddr_RDR , ltAddr_RDR , geAddr_RDR , gtAddr_RDR , leAddr_RDR , eqFloat_RDR , ltFloat_RDR , geFloat_RDR , gtFloat_RDR , leFloat_RDR , eqDouble_RDR, ltDouble_RDR, geDouble_RDR, gtDouble_RDR, leDouble_RDR :: RdrName gfoldl_RDR = varQual_RDR gENERICS (fsLit "gfoldl") gunfold_RDR = varQual_RDR gENERICS (fsLit "gunfold") toConstr_RDR = varQual_RDR gENERICS (fsLit "toConstr") dataTypeOf_RDR = varQual_RDR gENERICS (fsLit "dataTypeOf") dataCast1_RDR = varQual_RDR gENERICS (fsLit "dataCast1") dataCast2_RDR = varQual_RDR gENERICS (fsLit "dataCast2") gcast1_RDR = varQual_RDR tYPEABLE (fsLit "gcast1") gcast2_RDR = varQual_RDR tYPEABLE (fsLit "gcast2") mkConstr_RDR = varQual_RDR gENERICS (fsLit "mkConstr") constr_RDR = tcQual_RDR gENERICS (fsLit "Constr") mkDataType_RDR = varQual_RDR gENERICS (fsLit "mkDataType") dataType_RDR = tcQual_RDR gENERICS (fsLit "DataType") conIndex_RDR = varQual_RDR gENERICS (fsLit "constrIndex") prefix_RDR = dataQual_RDR gENERICS (fsLit "Prefix") infix_RDR = dataQual_RDR gENERICS (fsLit "Infix") eqChar_RDR = varQual_RDR gHC_PRIM (fsLit "eqChar#") ltChar_RDR = varQual_RDR gHC_PRIM (fsLit "ltChar#") leChar_RDR = varQual_RDR gHC_PRIM (fsLit "leChar#") gtChar_RDR = varQual_RDR gHC_PRIM (fsLit "gtChar#") geChar_RDR = varQual_RDR gHC_PRIM (fsLit "geChar#") eqInt_RDR = varQual_RDR gHC_PRIM (fsLit "==#") ltInt_RDR = varQual_RDR gHC_PRIM (fsLit "<#" ) leInt_RDR = varQual_RDR gHC_PRIM (fsLit "<=#") gtInt_RDR = varQual_RDR gHC_PRIM (fsLit ">#" ) geInt_RDR = varQual_RDR gHC_PRIM (fsLit ">=#") eqWord_RDR = varQual_RDR gHC_PRIM (fsLit "eqWord#") ltWord_RDR = varQual_RDR gHC_PRIM (fsLit "ltWord#") leWord_RDR = varQual_RDR gHC_PRIM (fsLit "leWord#") gtWord_RDR = varQual_RDR gHC_PRIM (fsLit "gtWord#") geWord_RDR = varQual_RDR gHC_PRIM (fsLit "geWord#") eqAddr_RDR = varQual_RDR gHC_PRIM (fsLit "eqAddr#") ltAddr_RDR = varQual_RDR gHC_PRIM (fsLit "ltAddr#") leAddr_RDR = varQual_RDR gHC_PRIM (fsLit "leAddr#") gtAddr_RDR = varQual_RDR gHC_PRIM (fsLit "gtAddr#") geAddr_RDR = varQual_RDR gHC_PRIM (fsLit "geAddr#") eqFloat_RDR = varQual_RDR gHC_PRIM (fsLit "eqFloat#") ltFloat_RDR = varQual_RDR gHC_PRIM (fsLit "ltFloat#") leFloat_RDR = varQual_RDR gHC_PRIM (fsLit "leFloat#") gtFloat_RDR = varQual_RDR gHC_PRIM (fsLit "gtFloat#") geFloat_RDR = varQual_RDR gHC_PRIM (fsLit "geFloat#") eqDouble_RDR = varQual_RDR gHC_PRIM (fsLit "==##") ltDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<##" ) leDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<=##") gtDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">##" ) geDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">=##") {- ************************************************************************ * * Functor instances see http://www.mail-archive.com/[email protected]/msg02116.html * * ************************************************************************ For the data type: data T a = T1 Int a | T2 (T a) We generate the instance: instance Functor T where fmap f (T1 b1 a) = T1 b1 (f a) fmap f (T2 ta) = T2 (fmap f ta) Notice that we don't simply apply 'fmap' to the constructor arguments. Rather - Do nothing to an argument whose type doesn't mention 'a' - Apply 'f' to an argument of type 'a' - Apply 'fmap f' to other arguments That's why we have to recurse deeply into the constructor argument types, rather than just one level, as we typically do. What about types with more than one type parameter? In general, we only derive Functor for the last position: data S a b = S1 [b] | S2 (a, T a b) instance Functor (S a) where fmap f (S1 bs) = S1 (fmap f bs) fmap f (S2 (p,q)) = S2 (a, fmap f q) However, we have special cases for - tuples - functions More formally, we write the derivation of fmap code over type variable 'a for type 'b as ($fmap 'a 'b). In this general notation the derived instance for T is: instance Functor T where fmap f (T1 x1 x2) = T1 ($(fmap 'a 'b1) x1) ($(fmap 'a 'a) x2) fmap f (T2 x1) = T2 ($(fmap 'a '(T a)) x1) $(fmap 'a 'b) = \x -> x -- when b does not contain a $(fmap 'a 'a) = f $(fmap 'a '(b1,b2)) = \x -> case x of (x1,x2) -> ($(fmap 'a 'b1) x1, $(fmap 'a 'b2) x2) $(fmap 'a '(T b1 b2)) = fmap $(fmap 'a 'b2) -- when a only occurs in the last parameter, b2 $(fmap 'a '(b -> c)) = \x b -> $(fmap 'a' 'c) (x ($(cofmap 'a 'b) b)) For functions, the type parameter 'a can occur in a contravariant position, which means we need to derive a function like: cofmap :: (a -> b) -> (f b -> f a) This is pretty much the same as $fmap, only without the $(cofmap 'a 'a) case: $(cofmap 'a 'b) = \x -> x -- when b does not contain a $(cofmap 'a 'a) = error "type variable in contravariant position" $(cofmap 'a '(b1,b2)) = \x -> case x of (x1,x2) -> ($(cofmap 'a 'b1) x1, $(cofmap 'a 'b2) x2) $(cofmap 'a '[b]) = map $(cofmap 'a 'b) $(cofmap 'a '(T b1 b2)) = fmap $(cofmap 'a 'b2) -- when a only occurs in the last parameter, b2 $(cofmap 'a '(b -> c)) = \x b -> $(cofmap 'a' 'c) (x ($(fmap 'a 'c) b)) Note that the code produced by $(fmap _ _) is always a higher order function, with type `(a -> b) -> (g a -> g b)` for some g. When we need to do pattern matching on the type, this means create a lambda function (see the (,) case above). The resulting code for fmap can look a bit weird, for example: data X a = X (a,Int) -- generated instance instance Functor X where fmap f (X x) = (\y -> case y of (x1,x2) -> X (f x1, (\z -> z) x2)) x The optimizer should be able to simplify this code by simple inlining. An older version of the deriving code tried to avoid these applied lambda functions by producing a meta level function. But the function to be mapped, `f`, is a function on the code level, not on the meta level, so it was eta expanded to `\x -> [| f $x |]`. This resulted in too much eta expansion. It is better to produce too many lambdas than to eta expand, see ticket #7436. -} gen_Functor_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Functor_binds loc tycon = (unitBag fmap_bind, emptyBag) where data_cons = tyConDataCons tycon fmap_bind = mkRdrFunBind (L loc fmap_RDR) eqns fmap_eqn con = evalState (match_for_con [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_fmap con eqns | null data_cons = [mkSimpleMatch [nlWildPat, nlWildPat] (error_Expr "Void fmap")] | otherwise = map fmap_eqn data_cons ft_fmap :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_fmap = FT { ft_triv = mkSimpleLam $ \x -> return x -- fmap f = \x -> x , ft_var = return f_Expr -- fmap f = f , ft_fun = \g h -> do -- fmap f = \x b -> h (x (g b)) gg <- g hh <- h mkSimpleLam2 $ \x b -> return $ nlHsApp hh (nlHsApp x (nlHsApp gg b)) , ft_tup = \t gs -> do -- fmap f = \x -> case x of (a1,a2,..) -> (g1 a1,g2 a2,..) gg <- sequence gs mkSimpleLam $ mkSimpleTupleCase match_for_con t gg , ft_ty_app = \_ g -> nlHsApp fmap_Expr <$> g -- fmap f = fmap g , ft_forall = \_ g -> g , ft_bad_app = panic "in other argument" , ft_co_var = panic "contravariant" } -- Con a1 a2 ... -> Con (f1 a1) (f2 a2) ... match_for_con :: [LPat RdrName] -> DataCon -> [LHsExpr RdrName] -> State [RdrName] (LMatch RdrName (LHsExpr RdrName)) match_for_con = mkSimpleConMatch $ \con_name xs -> return $ nlHsApps con_name xs -- Con x1 x2 .. {- Utility functions related to Functor deriving. Since several things use the same pattern of traversal, this is abstracted into functorLikeTraverse. This function works like a fold: it makes a value of type 'a' in a bottom up way. -} -- Generic traversal for Functor deriving data FFoldType a -- Describes how to fold over a Type in a functor like way = FT { ft_triv :: a -- Does not contain variable , ft_var :: a -- The variable itself , ft_co_var :: a -- The variable itself, contravariantly , ft_fun :: a -> a -> a -- Function type , ft_tup :: TyCon -> [a] -> a -- Tuple type , ft_ty_app :: Type -> a -> a -- Type app, variable only in last argument , ft_bad_app :: a -- Type app, variable other than in last argument , ft_forall :: TcTyVar -> a -> a -- Forall type } functorLikeTraverse :: forall a. TyVar -- ^ Variable to look for -> FFoldType a -- ^ How to fold -> Type -- ^ Type to process -> a functorLikeTraverse var (FT { ft_triv = caseTrivial, ft_var = caseVar , ft_co_var = caseCoVar, ft_fun = caseFun , ft_tup = caseTuple, ft_ty_app = caseTyApp , ft_bad_app = caseWrongArg, ft_forall = caseForAll }) ty = fst (go False ty) where go :: Bool -- Covariant or contravariant context -> Type -> (a, Bool) -- (result of type a, does type contain var) go co ty | Just ty' <- coreView ty = go co ty' go co (TyVarTy v) | v == var = (if co then caseCoVar else caseVar,True) go co (FunTy x y) | isPredTy x = go co y | xc || yc = (caseFun xr yr,True) where (xr,xc) = go (not co) x (yr,yc) = go co y go co (AppTy x y) | xc = (caseWrongArg, True) | yc = (caseTyApp x yr, True) where (_, xc) = go co x (yr,yc) = go co y go co ty@(TyConApp con args) | not (or xcs) = (caseTrivial, False) -- Variable does not occur -- At this point we know that xrs, xcs is not empty, -- and at least one xr is True | isTupleTyCon con = (caseTuple con xrs, True) | or (init xcs) = (caseWrongArg, True) -- T (..var..) ty | Just (fun_ty, _) <- splitAppTy_maybe ty -- T (..no var..) ty = (caseTyApp fun_ty (last xrs), True) | otherwise = (caseWrongArg, True) -- Non-decomposable (eg type function) where (xrs,xcs) = unzip (map (go co) args) go co (ForAllTy v x) | v /= var && xc = (caseForAll v xr,True) where (xr,xc) = go co x go _ _ = (caseTrivial,False) -- Return all syntactic subterms of ty that contain var somewhere -- These are the things that should appear in instance constraints deepSubtypesContaining :: TyVar -> Type -> [TcType] deepSubtypesContaining tv = functorLikeTraverse tv (FT { ft_triv = [] , ft_var = [] , ft_fun = (++) , ft_tup = \_ xs -> concat xs , ft_ty_app = (:) , ft_bad_app = panic "in other argument" , ft_co_var = panic "contravariant" , ft_forall = \v xs -> filterOut ((v `elemVarSet`) . tyVarsOfType) xs }) foldDataConArgs :: FFoldType a -> DataCon -> [a] -- Fold over the arguments of the datacon foldDataConArgs ft con = map (functorLikeTraverse tv ft) (dataConOrigArgTys con) where Just tv = getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con))) -- Argument to derive for, 'a in the above description -- The validity and kind checks have ensured that -- the Just will match and a::* -- Make a HsLam using a fresh variable from a State monad mkSimpleLam :: (LHsExpr RdrName -> State [RdrName] (LHsExpr RdrName)) -> State [RdrName] (LHsExpr RdrName) -- (mkSimpleLam fn) returns (\x. fn(x)) mkSimpleLam lam = do (n:names) <- get put names body <- lam (nlHsVar n) return (mkHsLam [nlVarPat n] body) mkSimpleLam2 :: (LHsExpr RdrName -> LHsExpr RdrName -> State [RdrName] (LHsExpr RdrName)) -> State [RdrName] (LHsExpr RdrName) mkSimpleLam2 lam = do (n1:n2:names) <- get put names body <- lam (nlHsVar n1) (nlHsVar n2) return (mkHsLam [nlVarPat n1,nlVarPat n2] body) -- "Con a1 a2 a3 -> fold [x1 a1, x2 a2, x3 a3]" mkSimpleConMatch :: Monad m => (RdrName -> [LHsExpr RdrName] -> m (LHsExpr RdrName)) -> [LPat RdrName] -> DataCon -> [LHsExpr RdrName] -> m (LMatch RdrName (LHsExpr RdrName)) mkSimpleConMatch fold extra_pats con insides = do let con_name = getRdrName con let vars_needed = takeList insides as_RDRs let pat = nlConVarPat con_name vars_needed rhs <- fold con_name (zipWith nlHsApp insides (map nlHsVar vars_needed)) return $ mkMatch (extra_pats ++ [pat]) rhs emptyLocalBinds -- "case x of (a1,a2,a3) -> fold [x1 a1, x2 a2, x3 a3]" mkSimpleTupleCase :: Monad m => ([LPat RdrName] -> DataCon -> [a] -> m (LMatch RdrName (LHsExpr RdrName))) -> TyCon -> [a] -> LHsExpr RdrName -> m (LHsExpr RdrName) mkSimpleTupleCase match_for_con tc insides x = do { let data_con = tyConSingleDataCon tc ; match <- match_for_con [] data_con insides ; return $ nlHsCase x [match] } {- ************************************************************************ * * Foldable instances see http://www.mail-archive.com/[email protected]/msg02116.html * * ************************************************************************ Deriving Foldable instances works the same way as Functor instances, only Foldable instances are not possible for function types at all. Here the derived instance for the type T above is: instance Foldable T where foldr f z (T1 x1 x2 x3) = $(foldr 'a 'b1) x1 ( $(foldr 'a 'a) x2 ( $(foldr 'a 'b2) x3 z ) ) The cases are: $(foldr 'a 'b) = \x z -> z -- when b does not contain a $(foldr 'a 'a) = f $(foldr 'a '(b1,b2)) = \x z -> case x of (x1,x2) -> $(foldr 'a 'b1) x1 ( $(foldr 'a 'b2) x2 z ) $(foldr 'a '(T b1 b2)) = \x z -> foldr $(foldr 'a 'b2) z x -- when a only occurs in the last parameter, b2 Note that the arguments to the real foldr function are the wrong way around, since (f :: a -> b -> b), while (foldr f :: b -> t a -> b). -} gen_Foldable_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Foldable_binds loc tycon = (listToBag [foldr_bind, foldMap_bind], emptyBag) where data_cons = tyConDataCons tycon foldr_bind = mkRdrFunBind (L loc foldable_foldr_RDR) eqns eqns = map foldr_eqn data_cons foldr_eqn con = evalState (match_foldr z_Expr [f_Pat,z_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_foldr con foldMap_bind = mkRdrFunBind (L loc foldMap_RDR) (map foldMap_eqn data_cons) foldMap_eqn con = evalState (match_foldMap [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_foldMap con ft_foldr :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_foldr = FT { ft_triv = mkSimpleLam2 $ \_ z -> return z -- foldr f = \x z -> z , ft_var = return f_Expr -- foldr f = f , ft_tup = \t g -> do gg <- sequence g -- foldr f = (\x z -> case x of ...) mkSimpleLam2 $ \x z -> mkSimpleTupleCase (match_foldr z) t gg x , ft_ty_app = \_ g -> do gg <- g -- foldr f = (\x z -> foldr g z x) mkSimpleLam2 $ \x z -> return $ nlHsApps foldable_foldr_RDR [gg,z,x] , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } match_foldr z = mkSimpleConMatch $ \_con_name xs -> return $ foldr nlHsApp z xs -- g1 v1 (g2 v2 (.. z)) ft_foldMap :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_foldMap = FT { ft_triv = mkSimpleLam $ \_ -> return mempty_Expr -- foldMap f = \x -> mempty , ft_var = return f_Expr -- foldMap f = f , ft_tup = \t g -> do gg <- sequence g -- foldMap f = \x -> case x of (..,) mkSimpleLam $ mkSimpleTupleCase match_foldMap t gg , ft_ty_app = \_ g -> nlHsApp foldMap_Expr <$> g -- foldMap f = foldMap g , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } match_foldMap = mkSimpleConMatch $ \_con_name xs -> return $ case xs of [] -> mempty_Expr xs -> foldr1 (\x y -> nlHsApps mappend_RDR [x,y]) xs {- ************************************************************************ * * Traversable instances see http://www.mail-archive.com/[email protected]/msg02116.html * * ************************************************************************ Again, Traversable is much like Functor and Foldable. The cases are: $(traverse 'a 'b) = pure -- when b does not contain a $(traverse 'a 'a) = f $(traverse 'a '(b1,b2)) = \x -> case x of (x1,x2) -> (,) <$> $(traverse 'a 'b1) x1 <*> $(traverse 'a 'b2) x2 $(traverse 'a '(T b1 b2)) = traverse $(traverse 'a 'b2) -- when a only occurs in the last parameter, b2 Note that the generated code is not as efficient as it could be. For instance: data T a = T Int a deriving Traversable gives the function: traverse f (T x y) = T <$> pure x <*> f y instead of: traverse f (T x y) = T x <$> f y -} gen_Traversable_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Traversable_binds loc tycon = (unitBag traverse_bind, emptyBag) where data_cons = tyConDataCons tycon traverse_bind = mkRdrFunBind (L loc traverse_RDR) eqns eqns = map traverse_eqn data_cons traverse_eqn con = evalState (match_for_con [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_trav con ft_trav :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_trav = FT { ft_triv = return pure_Expr -- traverse f = pure x , ft_var = return f_Expr -- traverse f = f x , ft_tup = \t gs -> do -- traverse f = \x -> case x of (a1,a2,..) -> gg <- sequence gs -- (,,) <$> g1 a1 <*> g2 a2 <*> .. mkSimpleLam $ mkSimpleTupleCase match_for_con t gg , ft_ty_app = \_ g -> nlHsApp traverse_Expr <$> g -- traverse f = travese g , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } -- Con a1 a2 ... -> Con <$> g1 a1 <*> g2 a2 <*> ... match_for_con = mkSimpleConMatch $ \con_name xs -> return $ mkApCon (nlHsVar con_name) xs -- ((Con <$> x1) <*> x2) <*> .. mkApCon con [] = nlHsApps pure_RDR [con] mkApCon con (x:xs) = foldl appAp (nlHsApps fmap_RDR [con,x]) xs where appAp x y = nlHsApps ap_RDR [x,y] {- ************************************************************************ * * Newtype-deriving instances * * ************************************************************************ We take every method in the original instance and `coerce` it to fit into the derived instance. We need a type annotation on the argument to `coerce` to make it obvious what instantiation of the method we're coercing from. See #8503 for more discussion. -} mkCoerceClassMethEqn :: Class -- the class being derived -> [TyVar] -- the tvs in the instance head -> [Type] -- instance head parameters (incl. newtype) -> Type -- the representation type (already eta-reduced) -> Id -- the method to look at -> Pair Type mkCoerceClassMethEqn cls inst_tvs cls_tys rhs_ty id = Pair (substTy rhs_subst user_meth_ty) (substTy lhs_subst user_meth_ty) where cls_tvs = classTyVars cls in_scope = mkInScopeSet $ mkVarSet inst_tvs lhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs cls_tys) rhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs (changeLast cls_tys rhs_ty)) (_class_tvs, _class_constraint, user_meth_ty) = tcSplitSigmaTy (varType id) changeLast :: [a] -> a -> [a] changeLast [] _ = panic "changeLast" changeLast [_] x = [x] changeLast (x:xs) x' = x : changeLast xs x' gen_Newtype_binds :: SrcSpan -> Class -- the class being derived -> [TyVar] -- the tvs in the instance head -> [Type] -- instance head parameters (incl. newtype) -> Type -- the representation type (already eta-reduced) -> LHsBinds RdrName gen_Newtype_binds loc cls inst_tvs cls_tys rhs_ty = listToBag $ zipWith mk_bind (classMethods cls) (map (mkCoerceClassMethEqn cls inst_tvs cls_tys rhs_ty) (classMethods cls)) where coerce_RDR = getRdrName coerceId mk_bind :: Id -> Pair Type -> LHsBind RdrName mk_bind id (Pair tau_ty user_ty) = mkRdrFunBind (L loc meth_RDR) [mkSimpleMatch [] rhs_expr] where meth_RDR = getRdrName id rhs_expr = ( nlHsVar coerce_RDR `nlHsApp` (nlHsVar meth_RDR `nlExprWithTySig` toHsType tau_ty')) `nlExprWithTySig` toHsType user_ty -- Open the representation type here, so that it's forall'ed type -- variables refer to the ones bound in the user_ty (_, _, tau_ty') = tcSplitSigmaTy tau_ty nlExprWithTySig :: LHsExpr RdrName -> LHsType RdrName -> LHsExpr RdrName nlExprWithTySig e s = noLoc (ExprWithTySig e s PlaceHolder) {- ************************************************************************ * * \subsection{Generating extra binds (@con2tag@ and @tag2con@)} * * ************************************************************************ \begin{verbatim} data Foo ... = ... con2tag_Foo :: Foo ... -> Int# tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int# maxtag_Foo :: Int -- ditto (NB: not unlifted) \end{verbatim} The `tags' here start at zero, hence the @fIRST_TAG@ (currently one) fiddling around. -} genAuxBindSpec :: SrcSpan -> AuxBindSpec -> (LHsBind RdrName, LSig RdrName) genAuxBindSpec loc (DerivCon2Tag tycon) = (mk_FunBind loc rdr_name eqns, L loc (TypeSig [L loc rdr_name] (L loc sig_ty) PlaceHolder)) where rdr_name = con2tag_RDR tycon sig_ty = HsCoreTy $ mkSigmaTy (tyConTyVars tycon) (tyConStupidTheta tycon) $ mkParentType tycon `mkFunTy` intPrimTy lots_of_constructors = tyConFamilySize tycon > 8 -- was: mAX_FAMILY_SIZE_FOR_VEC_RETURNS -- but we don't do vectored returns any more. eqns | lots_of_constructors = [get_tag_eqn] | otherwise = map mk_eqn (tyConDataCons tycon) get_tag_eqn = ([nlVarPat a_RDR], nlHsApp (nlHsVar getTag_RDR) a_Expr) mk_eqn :: DataCon -> ([LPat RdrName], LHsExpr RdrName) mk_eqn con = ([nlWildConPat con], nlHsLit (HsIntPrim "" (toInteger ((dataConTag con) - fIRST_TAG)))) genAuxBindSpec loc (DerivTag2Con tycon) = (mk_FunBind loc rdr_name [([nlConVarPat intDataCon_RDR [a_RDR]], nlHsApp (nlHsVar tagToEnum_RDR) a_Expr)], L loc (TypeSig [L loc rdr_name] (L loc sig_ty) PlaceHolder)) where sig_ty = HsCoreTy $ mkForAllTys (tyConTyVars tycon) $ intTy `mkFunTy` mkParentType tycon rdr_name = tag2con_RDR tycon genAuxBindSpec loc (DerivMaxTag tycon) = (mkHsVarBind loc rdr_name rhs, L loc (TypeSig [L loc rdr_name] (L loc sig_ty) PlaceHolder)) where rdr_name = maxtag_RDR tycon sig_ty = HsCoreTy intTy rhs = nlHsApp (nlHsVar intDataCon_RDR) (nlHsLit (HsIntPrim "" max_tag)) max_tag = case (tyConDataCons tycon) of data_cons -> toInteger ((length data_cons) - fIRST_TAG) type SeparateBagsDerivStuff = -- AuxBinds and SYB bindings ( Bag (LHsBind RdrName, LSig RdrName) -- Extra bindings (used by Generic only) , Bag TyCon -- Extra top-level datatypes , Bag (FamInst) -- Extra family instances , Bag (InstInfo RdrName)) -- Extra instances genAuxBinds :: SrcSpan -> BagDerivStuff -> SeparateBagsDerivStuff genAuxBinds loc b = genAuxBinds' b2 where (b1,b2) = partitionBagWith splitDerivAuxBind b splitDerivAuxBind (DerivAuxBind x) = Left x splitDerivAuxBind x = Right x rm_dups = foldrBag dup_check emptyBag dup_check a b = if anyBag (== a) b then b else consBag a b genAuxBinds' :: BagDerivStuff -> SeparateBagsDerivStuff genAuxBinds' = foldrBag f ( mapBag (genAuxBindSpec loc) (rm_dups b1) , emptyBag, emptyBag, emptyBag) f :: DerivStuff -> SeparateBagsDerivStuff -> SeparateBagsDerivStuff f (DerivAuxBind _) = panic "genAuxBinds'" -- We have removed these before f (DerivHsBind b) = add1 b f (DerivTyCon t) = add2 t f (DerivFamInst t) = add3 t f (DerivInst i) = add4 i add1 x (a,b,c,d) = (x `consBag` a,b,c,d) add2 x (a,b,c,d) = (a,x `consBag` b,c,d) add3 x (a,b,c,d) = (a,b,x `consBag` c,d) add4 x (a,b,c,d) = (a,b,c,x `consBag` d) mk_data_type_name :: TyCon -> RdrName -- "$tT" mk_data_type_name tycon = mkAuxBinderName (tyConName tycon) mkDataTOcc mk_constr_name :: DataCon -> RdrName -- "$cC" mk_constr_name con = mkAuxBinderName (dataConName con) mkDataCOcc mkParentType :: TyCon -> Type -- Turn the representation tycon of a family into -- a use of its family constructor mkParentType tc = case tyConFamInst_maybe tc of Nothing -> mkTyConApp tc (mkTyVarTys (tyConTyVars tc)) Just (fam_tc,tys) -> mkTyConApp fam_tc tys {- ************************************************************************ * * \subsection{Utility bits for generating bindings} * * ************************************************************************ -} mk_FunBind :: SrcSpan -> RdrName -> [([LPat RdrName], LHsExpr RdrName)] -> LHsBind RdrName mk_FunBind loc fun pats_and_exprs = mkRdrFunBind (L loc fun) matches where matches = [mkMatch p e emptyLocalBinds | (p,e) <-pats_and_exprs] mkRdrFunBind :: Located RdrName -> [LMatch RdrName (LHsExpr RdrName)] -> LHsBind RdrName mkRdrFunBind fun@(L loc fun_rdr) matches = L loc (mkFunBind fun matches') where -- Catch-all eqn looks like -- fmap = error "Void fmap" -- It's needed if there no data cons at all, -- which can happen with -XEmptyDataDecls -- See Trac #4302 matches' = if null matches then [mkMatch [] (error_Expr str) emptyLocalBinds] else matches str = "Void " ++ occNameString (rdrNameOcc fun_rdr) box :: String -- The class involved -> TyCon -- The tycon involved -> LHsExpr RdrName -- The argument -> Type -- The argument type -> LHsExpr RdrName -- Boxed version of the arg -- See Note [Deriving and unboxed types] in TcDeriv box cls_str tycon arg arg_ty = nlHsApp (nlHsVar box_con) arg where box_con = assoc_ty_id cls_str tycon boxConTbl arg_ty --------------------- primOrdOps :: String -- The class involved -> TyCon -- The tycon involved -> Type -- The type -> (RdrName, RdrName, RdrName, RdrName, RdrName) -- (lt,le,eq,ge,gt) -- See Note [Deriving and unboxed types] in TcDeriv primOrdOps str tycon ty = assoc_ty_id str tycon ordOpTbl ty ordOpTbl :: [(Type, (RdrName, RdrName, RdrName, RdrName, RdrName))] ordOpTbl = [(charPrimTy , (ltChar_RDR , leChar_RDR , eqChar_RDR , geChar_RDR , gtChar_RDR )) ,(intPrimTy , (ltInt_RDR , leInt_RDR , eqInt_RDR , geInt_RDR , gtInt_RDR )) ,(wordPrimTy , (ltWord_RDR , leWord_RDR , eqWord_RDR , geWord_RDR , gtWord_RDR )) ,(addrPrimTy , (ltAddr_RDR , leAddr_RDR , eqAddr_RDR , geAddr_RDR , gtAddr_RDR )) ,(floatPrimTy , (ltFloat_RDR , leFloat_RDR , eqFloat_RDR , geFloat_RDR , gtFloat_RDR )) ,(doublePrimTy, (ltDouble_RDR, leDouble_RDR, eqDouble_RDR, geDouble_RDR, gtDouble_RDR)) ] boxConTbl :: [(Type, RdrName)] boxConTbl = [(charPrimTy , getRdrName charDataCon ) ,(intPrimTy , getRdrName intDataCon ) ,(wordPrimTy , getRdrName wordDataCon ) ,(floatPrimTy , getRdrName floatDataCon ) ,(doublePrimTy, getRdrName doubleDataCon) ] -- | A table of postfix modifiers for unboxed values. postfixModTbl :: [(Type, String)] postfixModTbl = [(charPrimTy , "#" ) ,(intPrimTy , "#" ) ,(wordPrimTy , "##") ,(floatPrimTy , "#" ) ,(doublePrimTy, "##") ] -- | Lookup `Type` in an association list. assoc_ty_id :: String -- The class involved -> TyCon -- The tycon involved -> [(Type,a)] -- The table -> Type -- The type -> a -- The result of the lookup assoc_ty_id cls_str _ tbl ty | null res = pprPanic "Error in deriving:" (text "Can't derive" <+> text cls_str <+> text "for primitive type" <+> ppr ty) | otherwise = head res where res = [id | (ty',id) <- tbl, ty `eqType` ty'] ----------------------------------------------------------------------- and_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName and_Expr a b = genOpApp a and_RDR b ----------------------------------------------------------------------- eq_Expr :: TyCon -> Type -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName eq_Expr tycon ty a b | not (isUnLiftedType ty) = genOpApp a eq_RDR b | otherwise = genPrimOpApp a prim_eq b where (_, _, prim_eq, _, _) = primOrdOps "Eq" tycon ty untag_Expr :: TyCon -> [( RdrName, RdrName)] -> LHsExpr RdrName -> LHsExpr RdrName untag_Expr _ [] expr = expr untag_Expr tycon ((untag_this, put_tag_here) : more) expr = nlHsCase (nlHsPar (nlHsVarApps (con2tag_RDR tycon) [untag_this])) {-of-} [mkSimpleHsAlt (nlVarPat put_tag_here) (untag_Expr tycon more expr)] enum_from_to_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName enum_from_then_to_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName enum_from_to_Expr f t2 = nlHsApp (nlHsApp (nlHsVar enumFromTo_RDR) f) t2 enum_from_then_to_Expr f t t2 = nlHsApp (nlHsApp (nlHsApp (nlHsVar enumFromThenTo_RDR) f) t) t2 showParen_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName showParen_Expr e1 e2 = nlHsApp (nlHsApp (nlHsVar showParen_RDR) e1) e2 nested_compose_Expr :: [LHsExpr RdrName] -> LHsExpr RdrName nested_compose_Expr [] = panic "nested_compose_expr" -- Arg is always non-empty nested_compose_Expr [e] = parenify e nested_compose_Expr (e:es) = nlHsApp (nlHsApp (nlHsVar compose_RDR) (parenify e)) (nested_compose_Expr es) -- impossible_Expr is used in case RHSs that should never happen. -- We generate these to keep the desugarer from complaining that they *might* happen! error_Expr :: String -> LHsExpr RdrName error_Expr string = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString string)) -- illegal_Expr is used when signalling error conditions in the RHS of a derived -- method. It is currently only used by Enum.{succ,pred} illegal_Expr :: String -> String -> String -> LHsExpr RdrName illegal_Expr meth tp msg = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString (meth ++ '{':tp ++ "}: " ++ msg))) -- illegal_toEnum_tag is an extended version of illegal_Expr, which also allows you -- to include the value of a_RDR in the error string. illegal_toEnum_tag :: String -> RdrName -> LHsExpr RdrName illegal_toEnum_tag tp maxtag = nlHsApp (nlHsVar error_RDR) (nlHsApp (nlHsApp (nlHsVar append_RDR) (nlHsLit (mkHsString ("toEnum{" ++ tp ++ "}: tag (")))) (nlHsApp (nlHsApp (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)) (nlHsVar a_RDR)) (nlHsApp (nlHsApp (nlHsVar append_RDR) (nlHsLit (mkHsString ") is outside of enumeration's range (0,"))) (nlHsApp (nlHsApp (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)) (nlHsVar maxtag)) (nlHsLit (mkHsString ")")))))) parenify :: LHsExpr RdrName -> LHsExpr RdrName parenify e@(L _ (HsVar _)) = e parenify e = mkHsPar e -- genOpApp wraps brackets round the operator application, so that the -- renamer won't subsequently try to re-associate it. genOpApp :: LHsExpr RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName genOpApp e1 op e2 = nlHsPar (nlHsOpApp e1 op e2) genPrimOpApp :: LHsExpr RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName genPrimOpApp e1 op e2 = nlHsPar (nlHsApp (nlHsVar tagToEnum_RDR) (nlHsOpApp e1 op e2)) a_RDR, b_RDR, c_RDR, d_RDR, f_RDR, k_RDR, z_RDR, ah_RDR, bh_RDR, ch_RDR, dh_RDR :: RdrName a_RDR = mkVarUnqual (fsLit "a") b_RDR = mkVarUnqual (fsLit "b") c_RDR = mkVarUnqual (fsLit "c") d_RDR = mkVarUnqual (fsLit "d") f_RDR = mkVarUnqual (fsLit "f") k_RDR = mkVarUnqual (fsLit "k") z_RDR = mkVarUnqual (fsLit "z") ah_RDR = mkVarUnqual (fsLit "a#") bh_RDR = mkVarUnqual (fsLit "b#") ch_RDR = mkVarUnqual (fsLit "c#") dh_RDR = mkVarUnqual (fsLit "d#") as_RDRs, bs_RDRs, cs_RDRs :: [RdrName] as_RDRs = [ mkVarUnqual (mkFastString ("a"++show i)) | i <- [(1::Int) .. ] ] bs_RDRs = [ mkVarUnqual (mkFastString ("b"++show i)) | i <- [(1::Int) .. ] ] cs_RDRs = [ mkVarUnqual (mkFastString ("c"++show i)) | i <- [(1::Int) .. ] ] a_Expr, c_Expr, f_Expr, z_Expr, ltTag_Expr, eqTag_Expr, gtTag_Expr, false_Expr, true_Expr, fmap_Expr, pure_Expr, mempty_Expr, foldMap_Expr, traverse_Expr :: LHsExpr RdrName a_Expr = nlHsVar a_RDR -- b_Expr = nlHsVar b_RDR c_Expr = nlHsVar c_RDR f_Expr = nlHsVar f_RDR z_Expr = nlHsVar z_RDR ltTag_Expr = nlHsVar ltTag_RDR eqTag_Expr = nlHsVar eqTag_RDR gtTag_Expr = nlHsVar gtTag_RDR false_Expr = nlHsVar false_RDR true_Expr = nlHsVar true_RDR fmap_Expr = nlHsVar fmap_RDR pure_Expr = nlHsVar pure_RDR mempty_Expr = nlHsVar mempty_RDR foldMap_Expr = nlHsVar foldMap_RDR traverse_Expr = nlHsVar traverse_RDR a_Pat, b_Pat, c_Pat, d_Pat, f_Pat, k_Pat, z_Pat :: LPat RdrName a_Pat = nlVarPat a_RDR b_Pat = nlVarPat b_RDR c_Pat = nlVarPat c_RDR d_Pat = nlVarPat d_RDR f_Pat = nlVarPat f_RDR k_Pat = nlVarPat k_RDR z_Pat = nlVarPat z_RDR minusInt_RDR, tagToEnum_RDR, error_RDR :: RdrName minusInt_RDR = getRdrName (primOpId IntSubOp ) tagToEnum_RDR = getRdrName (primOpId TagToEnumOp) error_RDR = getRdrName eRROR_ID con2tag_RDR, tag2con_RDR, maxtag_RDR :: TyCon -> RdrName -- Generates Orig s RdrName, for the binding positions con2tag_RDR tycon = mk_tc_deriv_name tycon mkCon2TagOcc tag2con_RDR tycon = mk_tc_deriv_name tycon mkTag2ConOcc maxtag_RDR tycon = mk_tc_deriv_name tycon mkMaxTagOcc mk_tc_deriv_name :: TyCon -> (OccName -> OccName) -> RdrName mk_tc_deriv_name tycon occ_fun = mkAuxBinderName (tyConName tycon) occ_fun mkAuxBinderName :: Name -> (OccName -> OccName) -> RdrName -- ^ Make a top-level binder name for an auxiliary binding for a parent name -- See Note [Auxiliary binders] mkAuxBinderName parent occ_fun = mkRdrUnqual (occ_fun uniq_parent_occ) where uniq_parent_occ = mkOccName (occNameSpace parent_occ) uniq_string uniq_string | opt_PprStyle_Debug = showSDocUnsafe (ppr parent_occ <> underscore <> ppr parent_uniq) | otherwise = show parent_uniq -- The debug thing is just to generate longer, but perhaps more perspicuous, names parent_uniq = nameUnique parent parent_occ = nameOccName parent {- Note [Auxiliary binders] ~~~~~~~~~~~~~~~~~~~~~~~~ We often want to make a top-level auxiliary binding. E.g. for comparison we haev instance Ord T where compare a b = $con2tag a `compare` $con2tag b $con2tag :: T -> Int $con2tag = ...code.... Of course these top-level bindings should all have distinct name, and we are generating RdrNames here. We can't just use the TyCon or DataCon to distinguish because with standalone deriving two imported TyCons might both be called T! (See Trac #7947.) So we use the *unique* from the parent name (T in this example) as part of the OccName we generate for the new binding. In the past we used mkDerivedRdrName name occ_fun, which made an original name But: (a) that does not work well for standalone-deriving either (b) an unqualified name is just fine, provided it can't clash with user code -}
urbanslug/ghc
compiler/typecheck/TcGenDeriv.hs
bsd-3-clause
94,714
0
19
29,925
17,473
9,207
8,266
1,219
8
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} -- This program must be called with GHC's libdir as the single command line -- argument. module Main where -- import Data.Generics import Data.Data hiding (Fixity) import Data.List import System.IO import GHC import BasicTypes import DynFlags import FastString import ForeignCall import MonadUtils import Outputable import HsDecls import Bag (filterBag,isEmptyBag) import System.Directory (removeFile) import System.Environment( getArgs ) import qualified Data.Map as Map import Data.Dynamic ( fromDynamic,Dynamic ) main::IO() main = do [libdir,fileName] <- getArgs testOneFile libdir fileName testOneFile libdir fileName = do ((anns,cs),p) <- runGhc (Just libdir) $ do dflags <- getSessionDynFlags setSessionDynFlags dflags let mn =mkModuleName fileName addTarget Target { targetId = TargetModule mn , targetAllowObjCode = True , targetContents = Nothing } load LoadAllTargets modSum <- getModSummary mn p <- parseModule modSum return (pm_annotations p,p) let tupArgs = gq (pm_parsed_source p) putStrLn (intercalate "\n" $ map show tupArgs) -- putStrLn (pp tupArgs) -- putStrLn (intercalate "\n" [showAnns anns]) where gq ast = everything (++) ([] `mkQ` doFixity `extQ` doRuleDecl `extQ` doHsExpr `extQ` doInline ) ast doFixity :: Fixity -> [(String,[String])] doFixity (Fixity (SourceText ss) _ _) = [("f",[ss])] doRuleDecl :: RuleDecl GhcPs -> [(String,[String])] doRuleDecl (HsRule _ (ActiveBefore (SourceText ss) _) _ _ _ _ _) = [("rb",[ss])] doRuleDecl (HsRule _ (ActiveAfter (SourceText ss) _) _ _ _ _ _) = [("ra",[ss])] doRuleDecl (HsRule _ _ _ _ _ _ _) = [] doHsExpr :: HsExpr GhcPs -> [(String,[String])] doHsExpr (HsTickPragma src (_,_,_) ss _) = [("tp",[show ss])] doHsExpr _ = [] doInline (InlinePragma _ _ _ (ActiveBefore (SourceText ss) _) _) = [("ib",[ss])] doInline (InlinePragma _ _ _ (ActiveAfter (SourceText ss) _) _) = [("ia",[ss])] doInline (InlinePragma _ _ _ _ _ ) = [] showAnns anns = "[\n" ++ (intercalate "\n" $ map (\((s,k),v) -> ("(AK " ++ pp s ++ " " ++ show k ++" = " ++ pp v ++ ")\n")) $ Map.toList anns) ++ "]\n" pp a = showPpr unsafeGlobalDynFlags a -- --------------------------------------------------------------------- -- Copied from syb for the test -- | Generic queries of type \"r\", -- i.e., take any \"a\" and return an \"r\" -- type GenericQ r = forall a. Data a => a -> r -- | Make a generic query; -- start from a type-specific case; -- return a constant otherwise -- mkQ :: ( Typeable a , Typeable b ) => r -> (b -> r) -> a -> r (r `mkQ` br) a = case cast a of Just b -> br b Nothing -> r -- | Extend a generic query by a type-specific case extQ :: ( Typeable a , Typeable b ) => (a -> q) -> (b -> q) -> a -> q extQ f g a = maybe (f a) g (cast a) -- | Summarise all nodes in top-down, left-to-right order everything :: (r -> r -> r) -> GenericQ r -> GenericQ r -- Apply f to x to summarise top-level node; -- use gmapQ to recurse into immediate subterms; -- use ordinary foldl to reduce list of intermediate results everything k f x = foldl k (f x) (gmapQ (everything k f) x)
ezyang/ghc
testsuite/tests/ghc-api/annotations/t11430.hs
bsd-3-clause
3,858
1
20
1,261
1,155
625
530
85
6
{-# LANGUAGE CPP #-} module CPP where #define SOMETHING1 foo :: String foo = {- " single quotes are fine in block comments {- nested block comments are fine -} -} "foo" #define SOMETHING2 bar :: String bar = "block comment in a string is not a comment {- " #define SOMETHING3 -- " single quotes are fine in line comments -- {- unclosed block comments are fine in line comments -- Multiline CPP is also fine #define FOO\ 1 baz :: String baz = "line comment in a string is not a comment --"
sdiehl/ghc
testsuite/tests/hiefile/should_compile/CPP.hs
bsd-3-clause
517
0
4
123
43
30
13
9
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module T14131 where import Data.Kind import Data.Proxy data family Nat :: k -> k -> Type newtype instance Nat :: (k -> Type) -> (k -> Type) -> Type where Nat :: (forall xx. f xx -> g xx) -> Nat f g type family F :: Maybe a type instance F = (Nothing :: Maybe a) class C k where data CD :: k -> k -> Type type CT :: k instance C (Maybe a) where data CD :: Maybe a -> Maybe a -> Type where CD :: forall a (m :: Maybe a) (n :: Maybe a). Proxy m -> Proxy n -> CD m n type CT = (Nothing :: Maybe a) class Z k where type ZT :: Maybe k type ZT = (Nothing :: Maybe k)
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/T14131.hs
bsd-3-clause
721
22
9
179
299
160
139
23
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Char -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- The Char type and associated operations. -- ----------------------------------------------------------------------------- module Data.Char ( Char -- * Character classification -- | Unicode characters are divided into letters, numbers, marks, -- punctuation, symbols, separators (including spaces) and others -- (including control characters). , isControl, isSpace , isLower, isUpper, isAlpha, isAlphaNum, isPrint , isDigit, isOctDigit, isHexDigit , isLetter, isMark, isNumber, isPunctuation, isSymbol, isSeparator -- ** Subranges , isAscii, isLatin1 , isAsciiUpper, isAsciiLower -- ** Unicode general categories , GeneralCategory(..), generalCategory -- * Case conversion , toUpper, toLower, toTitle -- * Single digit characters , digitToInt , intToDigit -- * Numeric representations , ord , chr -- * String representations , showLitChar , lexLitChar , readLitChar ) where import GHC.Base import GHC.Arr (Ix) import GHC.Char import GHC.Real (fromIntegral) import GHC.Show import GHC.Read (Read, readLitChar, lexLitChar) import GHC.Unicode import GHC.Num import GHC.Enum -- | Convert a single digit 'Char' to the corresponding 'Int'. -- This function fails unless its argument satisfies 'isHexDigit', -- but recognises both upper and lower-case hexadecimal digits -- (i.e. @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@). digitToInt :: Char -> Int digitToInt c | isDigit c = ord c - ord '0' | c >= 'a' && c <= 'f' = ord c - ord 'a' + 10 | c >= 'A' && c <= 'F' = ord c - ord 'A' + 10 | otherwise = error ("Char.digitToInt: not a digit " ++ show c) -- sigh -- | Unicode General Categories (column 2 of the UnicodeData table) -- in the order they are listed in the Unicode standard. data GeneralCategory = UppercaseLetter -- ^ Lu: Letter, Uppercase | LowercaseLetter -- ^ Ll: Letter, Lowercase | TitlecaseLetter -- ^ Lt: Letter, Titlecase | ModifierLetter -- ^ Lm: Letter, Modifier | OtherLetter -- ^ Lo: Letter, Other | NonSpacingMark -- ^ Mn: Mark, Non-Spacing | SpacingCombiningMark -- ^ Mc: Mark, Spacing Combining | EnclosingMark -- ^ Me: Mark, Enclosing | DecimalNumber -- ^ Nd: Number, Decimal | LetterNumber -- ^ Nl: Number, Letter | OtherNumber -- ^ No: Number, Other | ConnectorPunctuation -- ^ Pc: Punctuation, Connector | DashPunctuation -- ^ Pd: Punctuation, Dash | OpenPunctuation -- ^ Ps: Punctuation, Open | ClosePunctuation -- ^ Pe: Punctuation, Close | InitialQuote -- ^ Pi: Punctuation, Initial quote | FinalQuote -- ^ Pf: Punctuation, Final quote | OtherPunctuation -- ^ Po: Punctuation, Other | MathSymbol -- ^ Sm: Symbol, Math | CurrencySymbol -- ^ Sc: Symbol, Currency | ModifierSymbol -- ^ Sk: Symbol, Modifier | OtherSymbol -- ^ So: Symbol, Other | Space -- ^ Zs: Separator, Space | LineSeparator -- ^ Zl: Separator, Line | ParagraphSeparator -- ^ Zp: Separator, Paragraph | Control -- ^ Cc: Other, Control | Format -- ^ Cf: Other, Format | Surrogate -- ^ Cs: Other, Surrogate | PrivateUse -- ^ Co: Other, Private Use | NotAssigned -- ^ Cn: Other, Not Assigned deriving (Eq, Ord, Enum, Read, Show, Bounded, Ix) -- | The Unicode general category of the character. generalCategory :: Char -> GeneralCategory generalCategory c = toEnum $ fromIntegral $ wgencat $ fromIntegral $ ord c -- derived character classifiers -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and modifiers letters). -- This function is equivalent to 'Data.Char.isAlpha'. isLetter :: Char -> Bool isLetter c = case generalCategory c of UppercaseLetter -> True LowercaseLetter -> True TitlecaseLetter -> True ModifierLetter -> True OtherLetter -> True _ -> False -- | Selects Unicode mark characters, e.g. accents and the like, which -- combine with preceding letters. isMark :: Char -> Bool isMark c = case generalCategory c of NonSpacingMark -> True SpacingCombiningMark -> True EnclosingMark -> True _ -> False -- | Selects Unicode numeric characters, including digits from various -- scripts, Roman numerals, etc. isNumber :: Char -> Bool isNumber c = case generalCategory c of DecimalNumber -> True LetterNumber -> True OtherNumber -> True _ -> False -- | Selects Unicode punctuation characters, including various kinds -- of connectors, brackets and quotes. isPunctuation :: Char -> Bool isPunctuation c = case generalCategory c of ConnectorPunctuation -> True DashPunctuation -> True OpenPunctuation -> True ClosePunctuation -> True InitialQuote -> True FinalQuote -> True OtherPunctuation -> True _ -> False -- | Selects Unicode symbol characters, including mathematical and -- currency symbols. isSymbol :: Char -> Bool isSymbol c = case generalCategory c of MathSymbol -> True CurrencySymbol -> True ModifierSymbol -> True OtherSymbol -> True _ -> False -- | Selects Unicode space and separator characters. isSeparator :: Char -> Bool isSeparator c = case generalCategory c of Space -> True LineSeparator -> True ParagraphSeparator -> True _ -> False
frantisekfarka/ghc-dsi
libraries/base/Data/Char.hs
bsd-3-clause
6,605
0
10
2,110
872
509
363
112
8
module Test where bar :: IO () bar = mdo str <- return "bar" putStrLn str -- Should fail -- bar' :: IO () -- bar' = mdo {str <- return "bar" ; putStrLn str}
ezyang/ghc
testsuite/tests/parser/should_fail/T8501b.hs
bsd-3-clause
167
0
8
45
38
20
18
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} -- | Definition of /Second-Order Array Combinators/ (SOACs), which are -- the main form of parallelism in the early stages of the compiler. module Futhark.IR.SOACS.SOAC ( SOAC (..), StreamOrd (..), StreamForm (..), ScremaForm (..), HistOp (..), Scan (..), scanResults, singleScan, Reduce (..), redResults, singleReduce, -- * Utility scremaType, soacType, typeCheckSOAC, mkIdentityLambda, isIdentityLambda, nilFn, scanomapSOAC, redomapSOAC, scanSOAC, reduceSOAC, mapSOAC, isScanomapSOAC, isRedomapSOAC, isScanSOAC, isReduceSOAC, isMapSOAC, scremaLambda, ppScrema, ppHist, groupScatterResults, groupScatterResults', splitScatterResults, -- * Generic traversal SOACMapper (..), identitySOACMapper, mapSOACM, traverseSOACStms, ) where import Control.Category import Control.Monad.Identity import Control.Monad.State.Strict import Control.Monad.Writer import Data.Function ((&)) import Data.List (intersperse) import qualified Data.Map.Strict as M import Data.Maybe import qualified Futhark.Analysis.Alias as Alias import Futhark.Analysis.Metrics import Futhark.Analysis.PrimExp.Convert import qualified Futhark.Analysis.SymbolTable as ST import Futhark.Construct import Futhark.IR import Futhark.IR.Aliases (Aliases, removeLambdaAliases) import Futhark.IR.Prop.Aliases import qualified Futhark.IR.TypeCheck as TC import Futhark.Optimise.Simplify.Rep import Futhark.Transform.Rename import Futhark.Transform.Substitute import Futhark.Util (chunks, maybeNth) import Futhark.Util.Pretty (Doc, Pretty, comma, commasep, parens, ppr, text, (<+>), (</>)) import qualified Futhark.Util.Pretty as PP import Prelude hiding (id, (.)) -- | A second-order array combinator (SOAC). data SOAC rep = Stream SubExp [VName] (StreamForm rep) [SubExp] (Lambda rep) | -- | @Scatter <length> <lambda> <inputs> <outputs>@ -- -- Scatter maps values from a set of input arrays to indices and values of a -- set of output arrays. It is able to write multiple values to multiple -- outputs each of which may have multiple dimensions. -- -- <inputs> is a list of input arrays, all having size <length>, elements of -- which are applied to the <lambda> function. For instance, if there are -- two arrays, <lambda> will get two values as input, one from each array. -- -- <outputs> specifies the result of the <lambda> and which arrays to write -- to. Each element of the list consists of a <VName> specifying which array -- to scatter to, a <Shape> describing the shape of that array, and an <Int> -- describing how many elements should be written to that array for each -- invocation of the <lambda>. -- -- <lambda> is a function that takes inputs from <inputs> and returns values -- according to the output-specification in <outputs>. It returns values in -- the following manner: -- -- [index_0, index_1, ..., index_n, value_0, value_1, ..., value_m] -- -- For each output in <outputs>, <lambda> returns <i> * <j> index values and -- <j> output values, where <i> is the number of dimensions (rank) of the -- given output, and <j> is the number of output values written to the given -- output. -- -- For example, given the following output specification: -- -- [([x1, y1, z1], 2, arr1), ([x2, y2], 1, arr2)] -- -- <lambda> will produce 6 (3 * 2) index values and 2 output values for -- <arr1>, and 2 (2 * 1) index values and 1 output value for -- arr2. Additionally, the results are grouped, so the first 6 index values -- will correspond to the first two output values, and so on. For this -- example, <lambda> should return a total of 11 values, 8 index values and -- 3 output values. Scatter SubExp [VName] (Lambda rep) [(Shape, Int, VName)] | -- | @Hist <length> <dest-arrays-and-ops> <bucket fun> <input arrays>@ -- -- The first SubExp is the length of the input arrays. The first -- list describes the operations to perform. The t'Lambda' is the -- bucket function. Finally comes the input images. Hist SubExp [VName] [HistOp rep] (Lambda rep) | -- | A combination of scan, reduction, and map. The first -- t'SubExp' is the size of the input arrays. Screma SubExp [VName] (ScremaForm rep) deriving (Eq, Ord, Show) -- | Information about computing a single histogram. data HistOp rep = HistOp { histShape :: Shape, -- | Race factor @RF@ means that only @1/RF@ -- bins are used. histRaceFactor :: SubExp, histDest :: [VName], histNeutral :: [SubExp], histOp :: Lambda rep } deriving (Eq, Ord, Show) -- | Is the stream chunk required to correspond to a contiguous -- subsequence of the original input ('InOrder') or not? 'Disorder' -- streams can be more efficient, but not all algorithms work with -- this. data StreamOrd = InOrder | Disorder deriving (Eq, Ord, Show) -- | What kind of stream is this? data StreamForm rep = Parallel StreamOrd Commutativity (Lambda rep) | Sequential deriving (Eq, Ord, Show) -- | The essential parts of a 'Screma' factored out (everything -- except the input arrays). data ScremaForm rep = ScremaForm [Scan rep] [Reduce rep] (Lambda rep) deriving (Eq, Ord, Show) singleBinOp :: Buildable rep => [Lambda rep] -> Lambda rep singleBinOp lams = Lambda { lambdaParams = concatMap xParams lams ++ concatMap yParams lams, lambdaReturnType = concatMap lambdaReturnType lams, lambdaBody = mkBody (mconcat (map (bodyStms . lambdaBody) lams)) (concatMap (bodyResult . lambdaBody) lams) } where xParams lam = take (length (lambdaReturnType lam)) (lambdaParams lam) yParams lam = drop (length (lambdaReturnType lam)) (lambdaParams lam) -- | How to compute a single scan result. data Scan rep = Scan { scanLambda :: Lambda rep, scanNeutral :: [SubExp] } deriving (Eq, Ord, Show) -- | How many reduction results are produced by these 'Scan's? scanResults :: [Scan rep] -> Int scanResults = sum . map (length . scanNeutral) -- | Combine multiple scan operators to a single operator. singleScan :: Buildable rep => [Scan rep] -> Scan rep singleScan scans = let scan_nes = concatMap scanNeutral scans scan_lam = singleBinOp $ map scanLambda scans in Scan scan_lam scan_nes -- | How to compute a single reduction result. data Reduce rep = Reduce { redComm :: Commutativity, redLambda :: Lambda rep, redNeutral :: [SubExp] } deriving (Eq, Ord, Show) -- | How many reduction results are produced by these 'Reduce's? redResults :: [Reduce rep] -> Int redResults = sum . map (length . redNeutral) -- | Combine multiple reduction operators to a single operator. singleReduce :: Buildable rep => [Reduce rep] -> Reduce rep singleReduce reds = let red_nes = concatMap redNeutral reds red_lam = singleBinOp $ map redLambda reds in Reduce (mconcat (map redComm reds)) red_lam red_nes -- | The types produced by a single 'Screma', given the size of the -- input array. scremaType :: SubExp -> ScremaForm rep -> [Type] scremaType w (ScremaForm scans reds map_lam) = scan_tps ++ red_tps ++ map (`arrayOfRow` w) map_tps where scan_tps = map (`arrayOfRow` w) $ concatMap (lambdaReturnType . scanLambda) scans red_tps = concatMap (lambdaReturnType . redLambda) reds map_tps = drop (length scan_tps + length red_tps) $ lambdaReturnType map_lam -- | Construct a lambda that takes parameters of the given types and -- simply returns them unchanged. mkIdentityLambda :: (Buildable rep, MonadFreshNames m) => [Type] -> m (Lambda rep) mkIdentityLambda ts = do params <- mapM (newParam "x") ts return Lambda { lambdaParams = params, lambdaBody = mkBody mempty $ varsRes $ map paramName params, lambdaReturnType = ts } -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda rep -> Bool isIdentityLambda lam = map resSubExp (bodyResult (lambdaBody lam)) == map (Var . paramName) (lambdaParams lam) -- | A lambda with no parameters that returns no values. nilFn :: Buildable rep => Lambda rep nilFn = Lambda mempty (mkBody mempty mempty) mempty -- | Construct a Screma with possibly multiple scans, and -- the given map function. scanomapSOAC :: [Scan rep] -> Lambda rep -> ScremaForm rep scanomapSOAC scans = ScremaForm scans [] -- | Construct a Screma with possibly multiple reductions, and -- the given map function. redomapSOAC :: [Reduce rep] -> Lambda rep -> ScremaForm rep redomapSOAC = ScremaForm [] -- | Construct a Screma with possibly multiple scans, and identity map -- function. scanSOAC :: (Buildable rep, MonadFreshNames m) => [Scan rep] -> m (ScremaForm rep) scanSOAC scans = scanomapSOAC scans <$> mkIdentityLambda ts where ts = concatMap (lambdaReturnType . scanLambda) scans -- | Construct a Screma with possibly multiple reductions, and -- identity map function. reduceSOAC :: (Buildable rep, MonadFreshNames m) => [Reduce rep] -> m (ScremaForm rep) reduceSOAC reds = redomapSOAC reds <$> mkIdentityLambda ts where ts = concatMap (lambdaReturnType . redLambda) reds -- | Construct a Screma corresponding to a map. mapSOAC :: Lambda rep -> ScremaForm rep mapSOAC = ScremaForm [] [] -- | Does this Screma correspond to a scan-map composition? isScanomapSOAC :: ScremaForm rep -> Maybe ([Scan rep], Lambda rep) isScanomapSOAC (ScremaForm scans reds map_lam) = do guard $ null reds guard $ not $ null scans return (scans, map_lam) -- | Does this Screma correspond to pure scan? isScanSOAC :: ScremaForm rep -> Maybe [Scan rep] isScanSOAC form = do (scans, map_lam) <- isScanomapSOAC form guard $ isIdentityLambda map_lam return scans -- | Does this Screma correspond to a reduce-map composition? isRedomapSOAC :: ScremaForm rep -> Maybe ([Reduce rep], Lambda rep) isRedomapSOAC (ScremaForm scans reds map_lam) = do guard $ null scans guard $ not $ null reds return (reds, map_lam) -- | Does this Screma correspond to a pure reduce? isReduceSOAC :: ScremaForm rep -> Maybe [Reduce rep] isReduceSOAC form = do (reds, map_lam) <- isRedomapSOAC form guard $ isIdentityLambda map_lam return reds -- | Does this Screma correspond to a simple map, without any -- reduction or scan results? isMapSOAC :: ScremaForm rep -> Maybe (Lambda rep) isMapSOAC (ScremaForm scans reds map_lam) = do guard $ null scans guard $ null reds return map_lam -- | Return the "main" lambda of the Screma. For a map, this is -- equivalent to 'isMapSOAC'. Note that the meaning of the return -- value of this lambda depends crucially on exactly which Screma this -- is. The parameters will correspond exactly to elements of the -- input arrays, however. scremaLambda :: ScremaForm rep -> Lambda rep scremaLambda (ScremaForm _ _ map_lam) = map_lam -- | @groupScatterResults <output specification> <results>@ -- -- Groups the index values and result values of <results> according to the -- <output specification>. -- -- This function is used for extracting and grouping the results of a -- scatter. In the SOAC representation, the lambda inside a 'Scatter' returns -- all indices and values as one big list. This function groups each value with -- its corresponding indices (as determined by the t'Shape' of the output array). -- -- The elements of the resulting list correspond to the shape and name of the -- output parameters, in addition to a list of values written to that output -- parameter, along with the array indices marking where to write them to. -- -- See 'Scatter' for more information. groupScatterResults :: [(Shape, Int, array)] -> [a] -> [(Shape, array, [([a], a)])] groupScatterResults output_spec results = let (shapes, ns, arrays) = unzip3 output_spec in groupScatterResults' output_spec results & chunks ns & zip3 shapes arrays -- | @groupScatterResults' <output specification> <results>@ -- -- Groups the index values and result values of <results> according to the -- output specification. This is the simpler version of @groupScatterResults@, -- which doesn't return any information about shapes or output arrays. -- -- See 'groupScatterResults' for more information, groupScatterResults' :: [(Shape, Int, array)] -> [a] -> [([a], a)] groupScatterResults' output_spec results = let (indices, values) = splitScatterResults output_spec results (shapes, ns, _) = unzip3 output_spec chunk_sizes = concat $ zipWith (\shp n -> replicate n $ length shp) shapes ns in zip (chunks chunk_sizes indices) values -- | @splitScatterResults <output specification> <results>@ -- -- Splits the results array into indices and values according to the output -- specification. -- -- See 'groupScatterResults' for more information. splitScatterResults :: [(Shape, Int, array)] -> [a] -> ([a], [a]) splitScatterResults output_spec results = let (shapes, ns, _) = unzip3 output_spec num_indices = sum $ zipWith (*) ns $ map length shapes in splitAt num_indices results -- | Like 'Mapper', but just for 'SOAC's. data SOACMapper frep trep m = SOACMapper { mapOnSOACSubExp :: SubExp -> m SubExp, mapOnSOACLambda :: Lambda frep -> m (Lambda trep), mapOnSOACVName :: VName -> m VName } -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper rep rep m identitySOACMapper = SOACMapper { mapOnSOACSubExp = return, mapOnSOACLambda = return, mapOnSOACVName = return } -- | Map a monadic action across the immediate children of a -- SOAC. The mapping does not descend recursively into subexpressions -- and is done left-to-right. mapSOACM :: (Applicative m, Monad m) => SOACMapper frep trep m -> SOAC frep -> m (SOAC trep) mapSOACM tv (Stream size arrs form accs lam) = Stream <$> mapOnSOACSubExp tv size <*> mapM (mapOnSOACVName tv) arrs <*> mapOnStreamForm form <*> mapM (mapOnSOACSubExp tv) accs <*> mapOnSOACLambda tv lam where mapOnStreamForm (Parallel o comm lam0) = Parallel o comm <$> mapOnSOACLambda tv lam0 mapOnStreamForm Sequential = pure Sequential mapSOACM tv (Scatter w ivs lam as) = Scatter <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) ivs <*> mapOnSOACLambda tv lam <*> mapM ( \(aw, an, a) -> (,,) <$> mapM (mapOnSOACSubExp tv) aw <*> pure an <*> mapOnSOACVName tv a ) as mapSOACM tv (Hist w arrs ops bucket_fun) = Hist <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) arrs <*> mapM ( \(HistOp shape rf op_arrs nes op) -> HistOp <$> mapM (mapOnSOACSubExp tv) shape <*> mapOnSOACSubExp tv rf <*> mapM (mapOnSOACVName tv) op_arrs <*> mapM (mapOnSOACSubExp tv) nes <*> mapOnSOACLambda tv op ) ops <*> mapOnSOACLambda tv bucket_fun mapSOACM tv (Screma w arrs (ScremaForm scans reds map_lam)) = Screma <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) arrs <*> ( ScremaForm <$> forM scans ( \(Scan red_lam red_nes) -> Scan <$> mapOnSOACLambda tv red_lam <*> mapM (mapOnSOACSubExp tv) red_nes ) <*> forM reds ( \(Reduce comm red_lam red_nes) -> Reduce comm <$> mapOnSOACLambda tv red_lam <*> mapM (mapOnSOACSubExp tv) red_nes ) <*> mapOnSOACLambda tv map_lam ) -- | A helper for defining 'TraverseOpStms'. traverseSOACStms :: Monad m => OpStmsTraverser m (SOAC rep) rep traverseSOACStms f = mapSOACM mapper where mapper = identitySOACMapper {mapOnSOACLambda = traverseLambdaStms f} instance ASTRep rep => FreeIn (SOAC rep) where freeIn' = flip execState mempty . mapSOACM free where walk f x = modify (<> f x) >> return x free = SOACMapper { mapOnSOACSubExp = walk freeIn', mapOnSOACLambda = walk freeIn', mapOnSOACVName = walk freeIn' } instance ASTRep rep => Substitute (SOAC rep) where substituteNames subst = runIdentity . mapSOACM substitute where substitute = SOACMapper { mapOnSOACSubExp = return . substituteNames subst, mapOnSOACLambda = return . substituteNames subst, mapOnSOACVName = return . substituteNames subst } instance ASTRep rep => Rename (SOAC rep) where rename = mapSOACM renamer where renamer = SOACMapper rename rename rename -- | The type of a SOAC. soacType :: SOAC rep -> [Type] soacType (Stream outersize _ _ accs lam) = map (substNamesInType substs) rtp where nms = map paramName $ take (1 + length accs) params substs = M.fromList $ zip nms (outersize : accs) Lambda params _ rtp = lam soacType (Scatter _w _ivs lam dests) = zipWith arrayOfShape val_ts ws where indexes = sum $ zipWith (*) ns $ map length ws val_ts = drop indexes $ lambdaReturnType lam (ws, ns, _) = unzip3 dests soacType (Hist _ _ ops _bucket_fun) = do op <- ops map (`arrayOfShape` histShape op) (lambdaReturnType $ histOp op) soacType (Screma w _arrs form) = scremaType w form instance TypedOp (SOAC rep) where opType = pure . staticShapes . soacType instance (ASTRep rep, Aliased rep) => AliasedOp (SOAC rep) where opAliases = map (const mempty) . soacType -- Only map functions can consume anything. The operands to scan -- and reduce functions are always considered "fresh". consumedInOp (Screma _ arrs (ScremaForm _ _ map_lam)) = mapNames consumedArray $ consumedByLambda map_lam where consumedArray v = fromMaybe v $ lookup v params_to_arrs params_to_arrs = zip (map paramName $ lambdaParams map_lam) arrs consumedInOp (Stream _ arrs form accs lam) = namesFromList $ subExpVars $ case form of Sequential -> map consumedArray $ namesToList $ consumedByLambda lam Parallel {} -> map consumedArray $ namesToList $ consumedByLambda lam where consumedArray v = fromMaybe (Var v) $ lookup v paramsToInput -- Drop the chunk parameter, which cannot alias anything. paramsToInput = zip (map paramName $ drop 1 $ lambdaParams lam) (accs ++ map Var arrs) consumedInOp (Scatter _ _ _ as) = namesFromList $ map (\(_, _, a) -> a) as consumedInOp (Hist _ _ ops _) = namesFromList $ concatMap histDest ops mapHistOp :: (Lambda frep -> Lambda trep) -> HistOp frep -> HistOp trep mapHistOp f (HistOp w rf dests nes lam) = HistOp w rf dests nes $ f lam instance ( ASTRep rep, ASTRep (Aliases rep), CanBeAliased (Op rep) ) => CanBeAliased (SOAC rep) where type OpWithAliases (SOAC rep) = SOAC (Aliases rep) addOpAliases aliases (Stream size arr form accs lam) = Stream size arr (analyseStreamForm form) accs $ Alias.analyseLambda aliases lam where analyseStreamForm (Parallel o comm lam0) = Parallel o comm (Alias.analyseLambda aliases lam0) analyseStreamForm Sequential = Sequential addOpAliases aliases (Scatter len arrs lam dests) = Scatter len arrs (Alias.analyseLambda aliases lam) dests addOpAliases aliases (Hist w arrs ops bucket_fun) = Hist w arrs (map (mapHistOp (Alias.analyseLambda aliases)) ops) (Alias.analyseLambda aliases bucket_fun) addOpAliases aliases (Screma w arrs (ScremaForm scans reds map_lam)) = Screma w arrs $ ScremaForm (map onScan scans) (map onRed reds) (Alias.analyseLambda aliases map_lam) where onRed red = red {redLambda = Alias.analyseLambda aliases $ redLambda red} onScan scan = scan {scanLambda = Alias.analyseLambda aliases $ scanLambda scan} removeOpAliases = runIdentity . mapSOACM remove where remove = SOACMapper return (return . removeLambdaAliases) return instance ASTRep rep => IsOp (SOAC rep) where safeOp _ = False cheapOp _ = True substNamesInType :: M.Map VName SubExp -> Type -> Type substNamesInType _ t@Prim {} = t substNamesInType _ t@Acc {} = t substNamesInType _ (Mem space) = Mem space substNamesInType subs (Array btp shp u) = let shp' = Shape $ map (substNamesInSubExp subs) (shapeDims shp) in Array btp shp' u substNamesInSubExp :: M.Map VName SubExp -> SubExp -> SubExp substNamesInSubExp _ e@(Constant _) = e substNamesInSubExp subs (Var idd) = M.findWithDefault (Var idd) idd subs instance (ASTRep rep, CanBeWise (Op rep)) => CanBeWise (SOAC rep) where type OpWithWisdom (SOAC rep) = SOAC (Wise rep) removeOpWisdom = runIdentity . mapSOACM (SOACMapper pure (pure . removeLambdaWisdom) pure) addOpWisdom = runIdentity . mapSOACM (SOACMapper pure (pure . informLambda) pure) instance RepTypes rep => ST.IndexOp (SOAC rep) where indexOp vtable k soac [i] = do (lam, se, arr_params, arrs) <- lambdaAndSubExp soac let arr_indexes = M.fromList $ catMaybes $ zipWith arrIndex arr_params arrs arr_indexes' = foldl expandPrimExpTable arr_indexes $ bodyStms $ lambdaBody lam case se of SubExpRes _ (Var v) -> uncurry (flip ST.Indexed) <$> M.lookup v arr_indexes' _ -> Nothing where lambdaAndSubExp (Screma _ arrs (ScremaForm scans reds map_lam)) = nthMapOut (scanResults scans + redResults reds) map_lam arrs lambdaAndSubExp _ = Nothing nthMapOut num_accs lam arrs = do se <- maybeNth (num_accs + k) $ bodyResult $ lambdaBody lam return (lam, se, drop num_accs $ lambdaParams lam, arrs) arrIndex p arr = do ST.Indexed cs pe <- ST.index' arr [i] vtable return (paramName p, (pe, cs)) expandPrimExpTable table stm | [v] <- patNames $ stmPat stm, Just (pe, cs) <- runWriterT $ primExpFromExp (asPrimExp table) $ stmExp stm, all (`ST.elem` vtable) (unCerts $ stmCerts stm) = M.insert v (pe, stmCerts stm <> cs) table | otherwise = table asPrimExp table v | Just (e, cs) <- M.lookup v table = tell cs >> return e | Just (Prim pt) <- ST.lookupType v vtable = return $ LeafExp v pt | otherwise = lift Nothing indexOp _ _ _ _ = Nothing -- | Type-check a SOAC. typeCheckSOAC :: TC.Checkable rep => SOAC (Aliases rep) -> TC.TypeM rep () typeCheckSOAC (Stream size arrexps form accexps lam) = do TC.require [Prim int64] size accargs <- mapM TC.checkArg accexps arrargs <- mapM lookupType arrexps _ <- TC.checkSOACArrayArgs size arrexps let chunk = head $ lambdaParams lam let asArg t = (t, mempty) inttp = Prim int64 lamarrs' = map (`setOuterSize` Var (paramName chunk)) arrargs let acc_len = length accexps let lamrtp = take acc_len $ lambdaReturnType lam unless (map TC.argType accargs == lamrtp) $ TC.bad $ TC.TypeError "Stream with inconsistent accumulator type in lambda." -- check reduce's lambda, if any _ <- case form of Parallel _ _ lam0 -> do let acct = map TC.argType accargs outerRetType = lambdaReturnType lam0 TC.checkLambda lam0 $ map TC.noArgAliases $ accargs ++ accargs unless (acct == outerRetType) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple acct ++ ", but stream's reduce lambda returns type " ++ prettyTuple outerRetType ++ "." Sequential -> return () -- just get the dflow of lambda on the fakearg, which does not alias -- arr, so we can later check that aliases of arr are not used inside lam. let fake_lamarrs' = map asArg lamarrs' TC.checkLambda lam $ asArg inttp : accargs ++ fake_lamarrs' typeCheckSOAC (Scatter w arrs lam as) = do -- Requirements: -- -- 0. @lambdaReturnType@ of @lam@ must be a list -- [index types..., value types, ...]. -- -- 1. The number of index types and value types must be equal to the number -- of return values from @lam@. -- -- 2. Each index type must have the type i64. -- -- 3. Each array in @as@ and the value types must have the same type -- -- 4. Each array in @as@ is consumed. This is not really a check, but more -- of a requirement, so that e.g. the source is not hoisted out of a -- loop, which will mean it cannot be consumed. -- -- 5. Each of arrs must be an array matching a corresponding lambda -- parameters. -- -- Code: -- First check the input size. TC.require [Prim int64] w -- 0. let (as_ws, as_ns, _as_vs) = unzip3 as indexes = sum $ zipWith (*) as_ns $ map length as_ws rts = lambdaReturnType lam rtsI = take indexes rts rtsV = drop indexes rts -- 1. unless (length rts == sum as_ns + sum (zipWith (*) as_ns $ map length as_ws)) $ TC.bad $ TC.TypeError "Scatter: number of index types, value types and array outputs do not match." -- 2. forM_ rtsI $ \rtI -> unless (Prim int64 == rtI) $ TC.bad $ TC.TypeError "Scatter: Index return type must be i64." forM_ (zip (chunks as_ns rtsV) as) $ \(rtVs, (aw, _, a)) -> do -- All lengths must have type i64. mapM_ (TC.require [Prim int64]) aw -- 3. forM_ rtVs $ \rtV -> TC.requireI [arrayOfShape rtV aw] a -- 4. TC.consume =<< TC.lookupAliases a -- 5. arrargs <- TC.checkSOACArrayArgs w arrs TC.checkLambda lam arrargs typeCheckSOAC (Hist w arrs ops bucket_fun) = do TC.require [Prim int64] w -- Check the operators. forM_ ops $ \(HistOp dest_shape rf dests nes op) -> do nes' <- mapM TC.checkArg nes mapM_ (TC.require [Prim int64]) dest_shape TC.require [Prim int64] rf -- Operator type must match the type of neutral elements. TC.checkLambda op $ map TC.noArgAliases $ nes' ++ nes' let nes_t = map TC.argType nes' unless (nes_t == lambdaReturnType op) $ TC.bad $ TC.TypeError $ "Operator has return type " ++ prettyTuple (lambdaReturnType op) ++ " but neutral element has type " ++ prettyTuple nes_t -- Arrays must have proper type. forM_ (zip nes_t dests) $ \(t, dest) -> do TC.requireI [t `arrayOfShape` dest_shape] dest TC.consume =<< TC.lookupAliases dest -- Types of input arrays must equal parameter types for bucket function. img' <- TC.checkSOACArrayArgs w arrs TC.checkLambda bucket_fun img' -- Return type of bucket function must be an index for each -- operation followed by the values to write. nes_ts <- concat <$> mapM (mapM subExpType . histNeutral) ops let bucket_ret_t = concatMap ((`replicate` Prim int64) . shapeRank . histShape) ops ++ nes_ts unless (bucket_ret_t == lambdaReturnType bucket_fun) $ TC.bad $ TC.TypeError $ "Bucket function has return type " ++ prettyTuple (lambdaReturnType bucket_fun) ++ " but should have type " ++ prettyTuple bucket_ret_t typeCheckSOAC (Screma w arrs (ScremaForm scans reds map_lam)) = do TC.require [Prim int64] w arrs' <- TC.checkSOACArrayArgs w arrs TC.checkLambda map_lam arrs' scan_nes' <- fmap concat $ forM scans $ \(Scan scan_lam scan_nes) -> do scan_nes' <- mapM TC.checkArg scan_nes let scan_t = map TC.argType scan_nes' TC.checkLambda scan_lam $ map TC.noArgAliases $ scan_nes' ++ scan_nes' unless (scan_t == lambdaReturnType scan_lam) $ TC.bad $ TC.TypeError $ "Scan function returns type " ++ prettyTuple (lambdaReturnType scan_lam) ++ " but neutral element has type " ++ prettyTuple scan_t return scan_nes' red_nes' <- fmap concat $ forM reds $ \(Reduce _ red_lam red_nes) -> do red_nes' <- mapM TC.checkArg red_nes let red_t = map TC.argType red_nes' TC.checkLambda red_lam $ map TC.noArgAliases $ red_nes' ++ red_nes' unless (red_t == lambdaReturnType red_lam) $ TC.bad $ TC.TypeError $ "Reduce function returns type " ++ prettyTuple (lambdaReturnType red_lam) ++ " but neutral element has type " ++ prettyTuple red_t return red_nes' let map_lam_ts = lambdaReturnType map_lam unless ( take (length scan_nes' + length red_nes') map_lam_ts == map TC.argType (scan_nes' ++ red_nes') ) $ TC.bad $ TC.TypeError $ "Map function return type " ++ prettyTuple map_lam_ts ++ " wrong for given scan and reduction functions." instance OpMetrics (Op rep) => OpMetrics (SOAC rep) where opMetrics (Stream _ _ _ _ lam) = inside "Stream" $ lambdaMetrics lam opMetrics (Scatter _len _ lam _) = inside "Scatter" $ lambdaMetrics lam opMetrics (Hist _ _ ops bucket_fun) = inside "Hist" $ mapM_ (lambdaMetrics . histOp) ops >> lambdaMetrics bucket_fun opMetrics (Screma _ _ (ScremaForm scans reds map_lam)) = inside "Screma" $ do mapM_ (lambdaMetrics . scanLambda) scans mapM_ (lambdaMetrics . redLambda) reds lambdaMetrics map_lam instance PrettyRep rep => PP.Pretty (SOAC rep) where ppr (Stream size arrs form acc lam) = case form of Parallel o comm lam0 -> let ord_str = if o == Disorder then "Per" else "" comm_str = case comm of Commutative -> "Comm" Noncommutative -> "" in text ("streamPar" ++ ord_str ++ comm_str) <> parens ( ppr size <> comma </> ppTuple' arrs <> comma </> ppr lam0 <> comma </> ppTuple' acc <> comma </> ppr lam ) Sequential -> text "streamSeq" <> parens ( ppr size <> comma </> ppTuple' arrs <> comma </> ppTuple' acc <> comma </> ppr lam ) ppr (Scatter w arrs lam dests) = "scatter" <> parens ( ppr w <> comma </> ppTuple' arrs <> comma </> ppr lam <> comma </> commasep (map ppr dests) ) ppr (Hist w arrs ops bucket_fun) = ppHist w arrs ops bucket_fun ppr (Screma w arrs (ScremaForm scans reds map_lam)) | null scans, null reds = text "map" <> parens ( ppr w <> comma </> ppTuple' arrs <> comma </> ppr map_lam ) | null scans = text "redomap" <> parens ( ppr w <> comma </> ppTuple' arrs <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map ppr reds) <> comma </> ppr map_lam ) | null reds = text "scanomap" <> parens ( ppr w <> comma </> ppTuple' arrs <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map ppr scans) <> comma </> ppr map_lam ) ppr (Screma w arrs form) = ppScrema w arrs form -- | Prettyprint the given Screma. ppScrema :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> ScremaForm rep -> Doc ppScrema w arrs (ScremaForm scans reds map_lam) = text "screma" <> parens ( ppr w <> comma </> ppTuple' arrs <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map ppr scans) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map ppr reds) <> comma </> ppr map_lam ) instance PrettyRep rep => Pretty (Scan rep) where ppr (Scan scan_lam scan_nes) = ppr scan_lam <> comma </> PP.braces (commasep $ map ppr scan_nes) ppComm :: Commutativity -> Doc ppComm Noncommutative = mempty ppComm Commutative = text "commutative " instance PrettyRep rep => Pretty (Reduce rep) where ppr (Reduce comm red_lam red_nes) = ppComm comm <> ppr red_lam <> comma </> PP.braces (commasep $ map ppr red_nes) -- | Prettyprint the given histogram operation. ppHist :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> [HistOp rep] -> Lambda rep -> Doc ppHist w arrs ops bucket_fun = text "hist" <> parens ( ppr w <> comma </> ppTuple' arrs <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map ppOp ops) <> comma </> ppr bucket_fun ) where ppOp (HistOp dest_w rf dests nes op) = ppr dest_w <> comma <+> ppr rf <> comma <+> PP.braces (commasep $ map ppr dests) <> comma </> ppTuple' nes <> comma </> ppr op
diku-dk/futhark
src/Futhark/IR/SOACS/SOAC.hs
isc
32,942
0
22
8,323
8,812
4,480
4,332
646
2
----------------------------------------------------------------------------- -- -- Module : Language.PureScript.CodeGen.JS.Optimizer -- Copyright : (c) Phil Freeman 2013 -- License : MIT -- -- Maintainer : Phil Freeman <[email protected]> -- Stability : experimental -- Portability : -- -- | -- This module optimizes code in the simplified-Javascript intermediate representation. -- -- The following optimizations are supported: -- -- * Collapsing nested blocks -- -- * Tail call elimination -- -- * Inlining of (>>=) and ret for the Eff monad -- -- * Removal of unnecessary thunks -- -- * Eta conversion -- -- * Inlining variables -- -- * Inline Prelude.($), Prelude.(#), Prelude.(++), Prelude.(!!) -- -- * Inlining primitive Javascript operators -- ----------------------------------------------------------------------------- {-# LANGUAGE FlexibleContexts #-} module Language.PureScript.CodeGen.JS.Optimizer ( optimize ) where import Prelude () import Prelude.Compat import Control.Monad.Reader (MonadReader, ask, asks) import Control.Monad.Supply.Class (MonadSupply) import Language.PureScript.CodeGen.JS.AST import Language.PureScript.Options import qualified Language.PureScript.Constants as C import Language.PureScript.CodeGen.JS.Optimizer.Common import Language.PureScript.CodeGen.JS.Optimizer.TCO import Language.PureScript.CodeGen.JS.Optimizer.MagicDo import Language.PureScript.CodeGen.JS.Optimizer.Inliner import Language.PureScript.CodeGen.JS.Optimizer.Unused import Language.PureScript.CodeGen.JS.Optimizer.Blocks -- | -- Apply a series of optimizer passes to simplified Javascript code -- optimize :: (Monad m, MonadReader Options m, Applicative m, MonadSupply m) => JS -> m JS optimize js = do noOpt <- asks optionsNoOptimizations if noOpt then return js else optimize' js optimize' :: (Monad m, MonadReader Options m, Applicative m, MonadSupply m) => JS -> m JS optimize' js = do opts <- ask untilFixedPoint (inlineFnComposition . applyAll [ collapseNestedBlocks , collapseNestedIfs , tco opts , magicDo opts , removeCodeAfterReturnStatements , removeUnusedArg , removeUndefinedApp , unThunk , etaConvert , evaluateIifes , inlineVariables , inlineValues , inlineOperator (C.prelude, (C.$)) $ \f x -> JSApp f [x] , inlineOperator (C.prelude, (C.#)) $ \x f -> JSApp f [x] , inlineOperator (C.dataArrayUnsafe, C.unsafeIndex) $ flip JSIndexer , inlineCommonOperators ]) js untilFixedPoint :: (Monad m, Eq a) => (a -> m a) -> a -> m a untilFixedPoint f = go where go a = do a' <- f a if a' == a then return a' else go a'
michaelficarra/purescript
src/Language/PureScript/CodeGen/JS/Optimizer.hs
mit
2,656
0
15
446
549
330
219
45
2
module P013Spec where import qualified P013 as P import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do let input = [37107287533902102798797998220837590246510135740250::Integer, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250, 23067588207539346171171980310421047513778063246676] describe "solveBasic" $ it "足した結果の先頭10桁" $ P.solveBasic input `shouldBe` 2728190129
yyotti/euler_haskell
test/P013Spec.hs
mit
584
0
10
120
98
55
43
15
1
module Types where type Var = Int data Term = Var Var | App Term [Term] | Lam Var Term
niteria/deterministic-fvs
Types.hs
mit
95
0
7
28
36
22
14
6
0
module Latte.Compile.MainSpec (main, spec) where import Test.Hspec import Latte.Compile.Main main :: IO () main = hspec spec spec :: Spec spec = do describe "Passing" $ do it "No function" $ do 1 == 1
mpsk2/LatteCompiler
testsuite/tests/Latte/Compile/MainSpec.hs
mit
229
0
13
63
81
43
38
10
1
-- | -- Module : Configuration.Dotenv.Types -- Copyright : © 2015–2020 Stack Builders Inc. -- License : MIT -- -- Maintainer : Stack Builders <[email protected]> -- Stability : experimental -- Portability : portable -- -- Provides the types with extra options for loading a dotenv file. module Configuration.Dotenv.Types ( Config(..) , defaultConfig ) where -- | Configuration Data Types with extra options for executing dotenv. data Config = Config { configPath :: [FilePath] -- ^ The paths for the .env files , configExamplePath :: [FilePath] -- ^ The paths for the .env.example files , configOverride :: Bool -- ^ Flag to allow override env variables } deriving (Eq, Show) -- | Default configuration. Use .env file without .env.example strict envs and -- without overriding. defaultConfig :: Config defaultConfig = Config { configExamplePath = [] , configOverride = False , configPath = [ ".env" ] }
stackbuilders/dotenv-hs
src/Configuration/Dotenv/Types.hs
mit
985
0
9
216
114
78
36
14
1
module Vacivity.Proc.BSPDungeon where import Prelude hiding (any, concat, foldl) import Control.Applicative import Control.Monad.Random hiding (split) import Data.List hiding (concat, foldl, any) import Data.Maybe import Data.Foldable import qualified Data.Set as Set import qualified Antiqua.Data.Array2d as A2D import Antiqua.Utils import Antiqua.Data.Coordinate import Antiqua.Common import Vacivity.Data.Tile data NonEmpty type Rect = (Int,Int,Int,Int) data Tree = Node Rect | Tree Orientation [Tree] deriving Show data Orientation = Horizontal | Vertical deriving Show data Line = Line (Int,Int) (Int,Int) deriving Show split :: RandomGen g => Tree -> Rand g Tree split (Tree o ts) = Tree o <$> (sequence $ split <$> ts) split n@(Node (x, y, w, h)) = do b :: Bool <- getRandom p :: Double <- getRandomR (0.33, 0.66) let ratio :: Double = fromIntegral w / fromIntegral h let o = if (ratio > 2) then Vertical else if (ratio < 0.5) then Horizontal else select Vertical Horizontal b let go Vertical = let w1 = floor $ fromIntegral w * p in let w2 = (subtract 1) $ floor $ fromIntegral w * (1 - p) in if w1 < 3 || w2 < 3 then return n else return $ Tree Vertical [ Node ( x, y, w1, h) , Node (x + w1 + 1, y, w2, h) ] go Horizontal = let h1 = floor $ fromIntegral h * p in let h2 = ((subtract 1) . floor) $ fromIntegral h * (1 - p) in if h1 < 3 || h2 < 3 then return n else return $ Tree Horizontal [ Node (x, y, w, h1) , Node (x, y + h1 + 1, w, h2) ] if w < 10 || h < 10 then return n else go o needSplit :: Tree -> Bool needSplit (Tree _ ts) = any id (needSplit <$> ts) needSplit (Node (_, _, w, h)) = let ratio :: Double = fromIntegral w / fromIntegral h in (w > 10 && h > 10) && (ratio > 2 || ratio < 0.5) create :: RandomGen g => Rect -> Int -> Rand g (Set.Set XY, A2D.Array2d TileType) create r@(x, y, w, h) n = do let sr = (x+2, y+2, w-2, h-2) tree <- doSplit n (Node sr) shrunk <- shrink tree let ct = connectAll shrunk return $ toCollisions r shrunk ct where doSplit :: RandomGen g => Int -> Tree -> Rand g Tree doSplit i t = do if i < 0 && (not . needSplit) t then return t else do t' <- split t doSplit (i - 1) t' getRandomTo :: RandomGen g => Int -> Rand g Int getRandomTo i = do if i <= 0 then return 0 else getRandomR (0, i) splitNum :: RandomGen g => Int -> Rand g (Int,Int) splitNum i = do first <- getRandomTo i return (first, i - first) shrinkRect :: RandomGen g => Rect -> Rand g Rect shrinkRect (x, y, w, h) = do sx <- getRandomTo (w - 10) sy <- getRandomTo (h - 10) (sx1, sx2) <- splitNum sx (sy1, sy2) <- splitNum sy let result = (x + sx1 ,y + sy1 ,w - (sx1 + sx2) ,h - (sy1 + sy2)) return $ result shrink :: RandomGen g => Tree -> Rand g Tree shrink (Node n) = Node <$> shrinkRect n shrink (Tree o ts) = Tree o <$> (sequence $ shrink <$> ts) top :: Rect -> Line top (x, y, w, _) = Line (x, y) (x + w, y) bottom :: Rect -> Line bottom (x, y, w, h) = Line (x, y + h) (x + w, y + h) left :: Rect -> Line left (x, y, _, h) = Line (x, y) (x, y + h) right :: Rect -> Line right (x, y, w, h) = Line (x + w, y) (x + w, y + h) nearest :: Orientation -> Rect -> Rect -> (Line, Line) nearest Vertical r1 r2 = (right r1, left r2) nearest Horizontal r1 r2 = (bottom r1, top r2) midPoint :: (Int,Int) -> (Int,Int) -> (Int,Int) midPoint (x1, y1) (x2, y2) = ((x1 + x2) `quot` 2, (y1 + y2) `quot` 2) connect :: Orientation -> Line -> Line -> [Line] connect o (Line p1 p2) (Line q1 q2) = let m1@(m1x, m1y) = midPoint p1 p2 in let m2@(m2x, m2y) = midPoint q1 q2 in let (m3x, m3y) = midPoint m1 m2 in case o of Horizontal -> if abs (m1y - m2y) <= 2 then [ Line (m3x,m1y) (m3x,m2y) ] else [ Line (m1x,m1y) (m1x,m3y) , Line (m1x,m3y) (m2x,m3y) , Line (m2x,m3y) (m2x,m2y) ] Vertical -> if abs (m1x - m2x) <= 2 then [ Line (m1x,m3y) (m2x,m3y) ] else [ Line (m1x,m1y) (m3x,m1y) , Line (m3x,m1y) (m3x,m2y) , Line (m3x,m2y) (m2x,m2y) ] center :: Rect -> (Int,Int) center (x, y, w, h) = (x + (w `quot` 2), y + (h `quot` 2)) dist :: Rect -> Rect -> Int dist r1 r2 = let (m1x, m1y) = center r1 in let (m2x, m2y) = center r2 in let two = 2 :: Int in (m1x - m2x) ^ two + (m1y - m2y) ^ two closest :: [Rect] -> [Rect] -> (Rect, Rect) closest rs1 rs2 = let xs = [ (dist r1 r2, (r1, r2)) | r1 <- rs1, r2 <- rs2 ] in let (best:_) = sortBy (\(x, _) (y, _) -> x `compare` y) xs in snd best connectTree :: Orientation -> Tree -> Tree -> [Line] connectTree o t1 t2 = let n1 = assembleRects t1 in let n2 = assembleRects t2 in let (r1, r2) = closest n1 n2 in let (l1, l2) = nearest o r1 r2 in connect o l1 l2 connectAll :: Tree -> [Line] connectAll t = connectHelper [] t where connectHelper :: [Line] -> Tree -> [Line] connectHelper acc (Tree o ((Node r1):(Node r2):[])) = let (l1, l2) = nearest o r1 r2 in connect o l1 l2 ++ acc connectHelper acc (Tree o ts@(t1:t2:[]) ) = let cs = connectTree o t1 t2 in let rs = connectHelper acc <$> ts in cs ++ concat rs connectHelper acc _ = acc assembleRects :: Tree -> [Rect] assembleRects t = helper [] t where helper acc (Node r) = r:acc helper acc (Tree _ ts) = concat $ helper acc <$> ts rectToPts :: Rect -> [(Int,Int)] rectToPts (x, y, w, h) = [ (i, j) | i <- [x..(x + w - 1)], j <- [y..(y + h - 1)] ] lineToPts :: Line -> [(Int,Int)] lineToPts (Line (x1, y1) (x2, y2)) = let x0 = min x1 x2 in let y0 = min y1 y2 in rectToPts (x0, y0, abs (x1 - x2) + 1, abs (y1 - y2) + 1) contains :: Rect -> XY -> Bool contains (x, y, w, h) (p, q) | p >= x && p < x + w && q >= y && q < y + h = True | otherwise = False toCollisions :: Rect -> Tree -> [Line] -> (Set.Set XY, A2D.Array2d TileType) toCollisions r@(x, y, w, h) t ls = let rects = assembleRects t in let pts = concat $ (lineToPts <$> ls) ++ (rectToPts <$> rects) in let base = A2D.tabulate (w - x) (h - y) (const True) in let result = foldl (A2D.putv False) base pts in let fs = [ (i, j) | i <- [-1..1], j <- [-1..1], i /= 0 || j /= 0 ] in let ns p = catMaybes $ (A2D.get result . (p |+|)) <$> fs in let f p b = let hasSolid = any not (ns p) in if | (not . contains r) p -> Solid | not b -> Free | hasSolid -> Wall | otherwise -> Solid in (Set.fromList pts , f A2D.<$*> result)
olive/vacivity
src/Vacivity/Proc/BSPDungeon.hs
mit
7,364
0
30
2,623
3,556
1,881
1,675
-1
-1
{-# LANGUAGE ConstraintKinds, DataKinds, DeriveFoldable, DeriveFunctor, DeriveTraversable, FlexibleContexts, FlexibleInstances, FunctionalDependencies, GADTs, KindSignatures, MultiParamTypeClasses, PatternSynonyms, RankNTypes, ScopedTypeVariables, StandaloneDeriving, TemplateHaskell, TupleSections, TypeFamilies, TypeOperators, UndecidableInstances, ViewPatterns #-} module Main where import Control.Lens import Control.Monad import Data.Traversable import qualified Test.QuickCheck as Q import qualified Text.Trifecta as P hiding (string) import qualified Text.Trifecta.Delta as P -- | Apply some additional information to a functor. data Ann b f a = Ann b (f a) -- | The datatype for the sum of functors. data Sum (fs :: [* -> *]) x where Void :: Sum '[] x Here :: Traversable f => f x -> Sum (f ': fs) x There :: Sum fs x -> Sum (f ': fs) x instance Eq (Sum '[] x) where _ == _ = True instance (Eq (f x), Eq (Sum fs x)) => Eq (Sum (f ': fs) x) where (Here a) == (Here b) = a == b (Here _ ) == (There _) = False (There _ ) == (Here _) = False (There a) == (There b) = a == b instance Ord (Sum '[] x) where compare Void Void = EQ instance (Ord (f x), Ord (Sum fs x)) => Ord (Sum (f ': fs) x) where compare (Here a) (Here b) = compare a b compare (Here _ ) (There _) = LT compare (There _ ) (Here _) = GT compare (There a) (There b) = compare a b instance Show x => Show (Sum '[] x) where show Void = "∅" instance (Show (f x), Show (Sum fs x)) => Show (Sum (f ': fs) x) where showsPrec n (Here x) = showsPrec n x showsPrec n (There x) = showsPrec n x instance Functor (Sum fs) where fmap _ Void = Void fmap f (Here t) = Here $ fmap f t fmap f (There t) = There $ fmap f t instance Foldable (Sum fs) where foldMap = foldMapDefault instance Traversable (Sum fs) where traverse _ Void = pure Void traverse afb (Here x) = Here <$> traverse afb x traverse afb (There x) = There <$> traverse afb x instance Elem f fs => Matches f (Sum fs x) where type Content f (Sum fs x) = x match = constructor instance Q.Arbitrary (Sum '[] x) where arbitrary = return Void shrink _ = [] instance (Traversable f, Q.Arbitrary (f x)) => Q.Arbitrary (Sum (f ': '[]) x) where arbitrary = Here <$> Q.arbitrary shrink (Here x) = map Here $ Q.shrink x shrink (There x) = map There $ Q.shrink x instance (Traversable f, Q.Arbitrary (f x), Q.Arbitrary (Sum (g ': fs) x)) => Q.Arbitrary (Sum (f ': g ': fs) x) where arbitrary = Q.oneof [Here <$> Q.arbitrary, There <$> Q.arbitrary] shrink (Here x) = map Here $ Q.shrink x shrink (There x) = map There $ Q.shrink x -- | The prisms for accessing the first functor in the Sum _Here :: Traversable f => Prism' (Sum (f ': fs) x) (f x) _Here = let a :: Sum (f ': fs) x -> Maybe (f x) a (Here x) = Just x a _ = Nothing in prism' Here a -- | The prisms for accessing the rest of functors in the Sum _There :: Traversable f => Prism' (Sum (f ': fs) x) (Sum fs x) _There = let a :: Sum (f ': fs) x -> Maybe (Sum fs x) a (There x) = Just x a _ = Nothing in prism' There a -- | The constraint that functor f is an element of 'Sum' fs class Elem f fs where constructor :: Prism' (Sum fs x) (f x) -- | Unicode type synonym for 'Elem' type f ∈ fs = Elem f fs instance {-# OVERLAPPING #-} Traversable f => Elem f (f ': fs) where constructor = _Here instance {-# OVERLAPPABLE #-} (Traversable f, Traversable g, Elem f fs) => Elem f (g ': fs) where constructor = _There . constructor -- | The constraint that set of functors @fs@ is a subset of @gs@ class Subset fs gs where subrep :: Prism' (Sum gs x) (Sum fs x) -- | Unicode type synonym for 'Subset' type fs ⊆ gs = Subset fs gs instance {-# OVERLAPPING #-} Subset '[] '[] where subrep = simple instance {-# OVERLAPPING #-} Subset '[] fs => Subset '[] (f ': fs) where subrep = prism' There (const Nothing) . subrep instance {-# OVERLAPPABLE #-} (Traversable f, Elem f gs, Subset fs gs) => Subset (f ': fs) gs where subrep = let fwd :: Sum (f ': fs) x -> Sum gs x fwd (Here x) = review constructor x fwd (There x) = review subrep x bwd :: Sum gs x -> Maybe (Sum (f ': fs) x) bwd ((^? constructor ) -> Just x) = Just (Here x) bwd ((^? subrep) -> Just x) = Just (There x) bwd _ = Nothing in prism' fwd bwd -- * Tools for matching -- | The constraint that object @x@ can somehow be matched to functor @f@, that is, there is a 'Prism'' from type @x@ -- to type @f (Content f x)@. class Matches f x where type Content f x :: * match :: Prism' x (f (Content f x)) -- | The type of the 'Prism'' that matches any @x@ such that @Matches f x@. type MatchPrism (f :: * -> *) = forall x. Matches f x => Prism' x (f (Content f x)) instance Matches f (f x) where type Content f (f x) = x match = simple -- * Syntax tree -- | The compiler metadata. data Metadata = Metadata {_metadataRendering :: P.Rendering, _metadataBegin :: P.Delta, _metadataEnd :: P.Delta} makeLenses ''Metadata instance Show Metadata where show = const "" instance P.HasRendering Metadata where rendering = metadataRendering -- | The fix point of F-algebra, with compiler metadata information. This is the datatype we use to represent any AST. data Fix f where In :: Functor f => {_out :: f (Fix f)} -> Fix f instance (Eq (f (Fix f))) => Eq (Fix f) where (In a) == (In b) = a == b instance (Ord (f (Fix f))) => Ord (Fix f) where compare (In a) (In b) = compare a b instance (Show (f (Fix f))) => Show (Fix f) where showsPrec n (In x) = showsPrec n x instance (f ∈ fs) => Matches f (Fix (Sum fs)) where type Content f (Fix (Sum fs)) = Fix (Sum fs) match = fix . constructor instance (Functor f, Q.Arbitrary (f (Fix f))) => Q.Arbitrary (Fix f) where arbitrary = In <$> Q.arbitrary shrink (In x) = map In $ Q.shrink x fix :: forall f. Functor f => Iso' (Fix f) (f (Fix f)) fix = iso _out go where go :: f (Fix f) -> Fix f go ffixf = In ffixf -- * A Sample language data ImmF x = ImmF Rational instance Show (ImmF x) where show (ImmF n) = show n main :: IO () main = do putStrLn "hello world"
nushio3/formura
attic/combinator-NT/src/Main.hs
mit
6,362
0
15
1,635
2,667
1,366
1,301
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module Main where import qualified Data.ByteString.Lazy as B import Data.Serialize hiding (get, getBytes) import Data.Serialize.Builder (toLazyByteString) import qualified Data.Map as Map import qualified Control.Monad.State as State import Control.Monad import Data.Word (Word8, Word16, Word32) import Data.List (intercalate, mapAccumL) import System.Environment (getArgs) import System.Directory (getDirectoryContents) import Data.Monoid (Monoid(..)) import Data.Foldable (foldMap) import System.Console.CmdArgs import Prelude hiding (all) data Args = Args { all :: Bool, path :: String } deriving (Show, Data, Typeable) argsDef :: Args argsDef = Args { all = False &= help "Combine all generated samples in one audio file" , path = "./" &= argPos 0 &= typDir } &= versionArg [ignore] &= summary "ags2aiff v0.1, Sjoerd Visscher 2010" sampleRate :: Int sampleRate = 24000 main :: IO () main = do args <- cmdArgs argsDef let p = path args ++ (if last (path args) == '/' then "" else "/") files <- getDirectoryContents p let agsFiles = filter ((== ".ags") . reverse . take 4 . reverse) files sounds <- mapM (generateSound . (p ++)) agsFiles if (all args) then do B.writeFile (p ++ "Sound.aiff") $ generateAIFF (foldMap (`mappend` silence1s) sounds) writeFile (p ++ "Sound.js") $ generateJS sounds agsFiles else do flip mapM_ (zip sounds agsFiles) $ \(sound, fname) -> B.writeFile ((++ ".aiff") . reverse . drop 4 . reverse $ fname) $ generateAIFF sound generateSound :: String -> IO Audio generateSound path = do contents <- liftM B.unpack $ B.readFile path let offsets = State.evalState getOffsets contents let notes = map (State.evalState getNotes . flip drop (contents ++ repeat 0)) offsets return . zipAdd3 . map (foldMap sample) $ notes data Note = Note { duration :: Int, freq :: Int, attenuation :: Int } deriving Show -- First field is length, second field is an infinitly long sample. data Audio = Audio !Int [Word16] instance Monoid Audio where mempty = Audio 0 (repeat 0) Audio l1 d1 `mappend` Audio l2 d2 = Audio (l1 + l2) (take l1 d1 ++ d2) silence1s :: Audio silence1s = Audio sampleRate (repeat 0) sample :: Note -> Audio sample (Note dur f a) = Audio len (dataMap Map.! (f, a `mod` 16)) where len = (dur * sampleRate) `div` 60 dataMap :: Map.Map (Int, Int) [Word16] dataMap = Map.fromList [((f, a), createData (111860 / fromIntegral f) ((15 - fromIntegral a) / 15)) | f <- [0..64*16], a <- [0..15]] createData :: Double -> Double -> [Word16] createData freq vol = [round $ vol * exp (i * decayMul) * max (-10000) (min 10000 (shapeMul * sin (i * freqMul))) | i <- [0..]] where shapeMul :: Double shapeMul = 200000000 / 3 / freq freqMul :: Double freqMul = freq * 2 * pi / fromIntegral sampleRate decayMul :: Double decayMul = (-4) / fromIntegral sampleRate zipAdd3 :: [Audio] -> Audio zipAdd3 [Audio lx xs, Audio ly ys, Audio lz zs] = Audio (maximum [lx, ly, lz]) (zipWith3 (\x y z -> x + y + z) xs ys zs) getOffsets :: State.State [Word8] [Int] getOffsets = replicateM 3 get2 getNote :: State.State [Word8] Note getNote = liftM3 Note get2 getFrequency get1 getNotes :: State.State [Word8] [Note] getNotes = do note <- getNote if (duration note == 0xffff) then return [] else do notes <- getNotes return (note : notes) getFrequency :: State.State [Word8] Int getFrequency = do b1 <- get1 b2 <- get1 return ((b1 `mod` 64) * 16 + (b2 `mod` 16)) get1 :: State.State [Word8] Int get1 = do (b:rest) <- State.get State.put rest return (fromEnum b) get2 :: State.State [Word8] Int get2 = liftM2 (+) get1 (liftM (256 *) get1) generateAIFF :: Audio -> B.ByteString generateAIFF (Audio len samples) = toLazyByteString . execPut $ chunk "FORM" (36 + len * 2) (putAscii "AIFF" >> commonChunk >> soundDataChunk) where commonChunk = chunk "COMM" 18 (short 1 >> long (fromIntegral len) >> short 16 >> ext (fromIntegral sampleRate)) soundDataChunk = chunk "SSND" (8 + len * 2) (long 0 >> long 0 >> (mapM_ short $ take len samples)) chunk :: String -> Int -> Put -> Put chunk ckId len ckData = putAscii ckId >> (long . fromIntegral $ len) >> ckData putAscii :: String -> Put putAscii = mapM_ (putWord8 . fromIntegral . fromEnum) long :: Putter Word32 long = putWord32be short :: Putter Word16 short = putWord16be ext :: Double -> Put ext _ = mapM_ putWord8 [0x40, 0x0D, 0xBB, 0x80, 0, 0, 0, 0, 0, 0] generateJS :: [Audio] -> [String] -> String generateJS audios names = "{" ++ intercalate "," parts ++ "}" where parts = snd $ mapAccumL ( \pos (Audio len _, name) -> let lenInS = fromIntegral len / fromIntegral sampleRate in let num = reverse . drop 4 . reverse . drop 5 $ name in (pos + lenInS + 1, "\"" ++ num ++ "\":[" ++ (take 6 $ show pos) ++ "," ++ (take 6 $ show lenInS) ++ "]") ) (0 :: Double) (zip audios names)
sjoerdvisscher/sarien-sound
ags2aiff.hs
mit
5,149
0
22
1,222
2,077
1,097
980
113
3
-- Copyright (c) 2011 Alexander Poluektov ([email protected]) -- -- Use, modification and distribution are subject to the MIT license -- (See accompanying file MIT-LICENSE) module Domino.Strategy.Counting ( counting ) where import Data.List (minimumBy) import Data.Ord (comparing) import Domino.Game import Domino.GameState import Domino.Strategy type MaxAmount = Int type OpponentHand = [MaxAmount] counting :: Strategy counting = Strategy updateInfo mostInconvenientMove (initialOpponentHand,initialState) mostInconvenientMove :: (OpponentHand, GameState) -> Event mostInconvenientMove (opHand,st) = case events st of [(Me, EBegin _ Me _ firstTile)] -> EMove (Move firstTile L) _ | null moves && stock st > 0 -> EDraw Unknown | null moves -> EPass | otherwise -> EMove (minAmount moves) where moves = correctMoves (hand st) (line st) minAmount = minimumBy (comparing opChoices) opChoices m = sum $ fst $ unzip $ filter f $ zip opHand [0..6] where f (n,i) = (i == a || i == b) (a,b) = ends $ makeMove (line st) m updateInfo :: (OpponentHand, GameState) -> (Player, Event) -> Strategy updateInfo s@(hand, st) e = Strategy updateInfo mostInconvenientMove updState where updState = (updateOpponentHandFromEvent e s, updateGameState e st) restoreOpponentHand :: GameEvents -> OpponentHand restoreOpponentHand = fst . foldr f (initialOpponentHand, initialState) where f e (oh, st) = (updateOpponentHandFromEvent e (oh,st), updateGameState e st) updateOpponentHandFromEvent :: (Player, Event) -> (OpponentHand, GameState) -> OpponentHand updateOpponentHandFromEvent (_, (EBegin h _ _ _)) (oh,gs) = foldr updateOpponentHand oh h -- TODO: take tile that nobody has into account updateOpponentHandFromEvent (Opponent, (EMove (Move p _))) (oh,gs) = updateOpponentHand p oh updateOpponentHandFromEvent (Opponent, (EDraw _)) (oh,gs) = newOh where newOh = map noEnds (zip oh [0..6]) noEnds (n,i) | i == a || i == b = 0 | otherwise = n (a,b) = ends $ line gs updateOpponentHandFromEvent (Me, (EDraw (Known p))) (oh,gs) = updateOpponentHand p oh updateOpponentHandFromEvent _ (oh, _) = oh updateOpponentHand :: Tile -> OpponentHand -> OpponentHand updateOpponentHand (a,b) oh = map u (zip oh [0..6]) where u (n,i) | i == a || i == b = max (n-1) 0 | otherwise = n initialOpponentHand :: OpponentHand initialOpponentHand = (replicate 7 7)
apoluektov/domino
src/Domino/Strategy/Counting.hs
mit
2,659
0
13
667
891
477
414
53
2
{-# LANGUAGE OverloadedStrings #-} module Keter ( keter ) where import Data.Yaml import qualified Data.HashMap.Strict as Map import qualified Data.Text as T import System.Exit import System.Process import Control.Monad import System.Directory import Data.Maybe (mapMaybe) import qualified Filesystem.Path.CurrentOS as F import qualified Filesystem as F import qualified Codec.Archive.Tar as Tar import Control.Exception import qualified Data.ByteString.Lazy as L import Codec.Compression.GZip (compress) import qualified Data.Foldable as Fold import Control.Monad.Trans.Writer (tell, execWriter) run :: String -> [String] -> IO () run a b = do ec <- rawSystem a b unless (ec == ExitSuccess) $ exitWith ec keter :: String -- ^ cabal command -> Bool -- ^ no build? -> IO () keter cabal noBuild = do ketercfg <- keterConfig mvalue <- decodeFile ketercfg value <- case mvalue of Nothing -> error "No config/keter.yaml found" Just (Object value) -> case Map.lookup "host" value of Just (String s) | "<<" `T.isPrefixOf` s -> error $ "Please set your hostname in " ++ ketercfg _ -> case Map.lookup "user-edited" value of Just (Bool False) -> error $ "Please edit your Keter config file at " ++ ketercfg _ -> return value Just _ -> error $ ketercfg ++ " is not an object" files <- getDirectoryContents "." project <- case mapMaybe (T.stripSuffix ".cabal" . T.pack) files of [x] -> return x [] -> error "No cabal file found" _ -> error "Too many cabal files found" let findExecs (Object v) = mapM_ go $ Map.toList v where go ("exec", String s) = tell [F.collapse $ "config" F.</> F.fromText s] go (_, v') = findExecs v' findExecs (Array v) = Fold.mapM_ findExecs v findExecs _ = return () execs = execWriter $ findExecs $ Object value unless noBuild $ do run cabal ["clean"] run cabal ["configure"] run cabal ["build"] _ <- try' $ F.removeTree "static/tmp" archive <- Tar.pack "" $ "config" : "static" : map F.encodeString execs let fp = T.unpack project ++ ".keter" L.writeFile fp $ compress $ Tar.write archive case Map.lookup "copy-to" value of Just (String s) -> case parseMaybe (.: "copy-to-port") value of Just i -> run "scp" ["-P" ++ show (i :: Int), fp, T.unpack s] Nothing -> run "scp" [fp, T.unpack s] _ -> return () where -- Test for alternative config file extension (yaml or yml). keterConfig = do let yml = "config/keter.yml" ymlExists <- doesFileExist yml return $ if ymlExists then yml else "config/keter.yaml" try' :: IO a -> IO (Either SomeException a) try' = try
wujf/yesod
yesod-bin/Keter.hs
mit
3,064
0
19
997
919
465
454
76
13
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | Definitions in this module are Copied verbatim from "System.Process". module System.Process.Copied ( withCreateProcess_ , processFailedException , withForkWait , ignoreSigPipe ) where import System.Process import Prelude hiding (mapM) import System.Process.Internals import Control.Concurrent import Control.DeepSeq (rnf) import Control.Exception (SomeException, mask, try, throwIO) import qualified Control.Exception as C import Control.Monad import Data.Maybe import Foreign import Foreign.C import System.Exit ( ExitCode(..) ) import System.IO import System.IO.Error (mkIOError, ioeSetErrorString) import GHC.IO.Exception ( ioException, IOErrorType(..), IOException(..) ) #if !MIN_VERSION_process(1,2,0) createProcess_ :: String -> CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) createProcess_ _ = createProcess #endif withCreateProcess_ :: String -> CreateProcess -> (Maybe Handle -> Maybe Handle -> Maybe Handle -> ProcessHandle -> IO a) -> IO a withCreateProcess_ fun c action = C.bracketOnError (createProcess_ fun c) cleanupProcess (\(m_in, m_out, m_err, ph) -> action m_in m_out m_err ph) cleanupProcess :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> IO () cleanupProcess (mb_stdin, mb_stdout, mb_stderr, ph) = do terminateProcess ph -- Note, it's important that other threads that might be reading/writing -- these handles also get killed off, since otherwise they might be holding -- the handle lock and prevent us from closing, leading to deadlock. maybe (return ()) (ignoreSigPipe . hClose) mb_stdin maybe (return ()) hClose mb_stdout maybe (return ()) hClose mb_stderr -- terminateProcess does not guarantee that it terminates the process. -- Indeed on Unix it's SIGTERM, which asks nicely but does not guarantee -- that it stops. If it doesn't stop, we don't want to hang, so we wait -- asynchronously using forkIO. _ <- forkIO (waitForProcess ph >> return ()) return () processFailedException :: String -> String -> [String] -> Int -> IO a processFailedException fun cmd args exit_code = ioError (mkIOError OtherError (fun ++ ": " ++ cmd ++ concatMap ((' ':) . show) args ++ " (exit " ++ show exit_code ++ ")") Nothing Nothing) -- | Fork a thread while doing something else, but kill it if there's an -- exception. -- -- This is important in the cases above because we want to kill the thread -- that is holding the Handle lock, because when we clean up the process we -- try to close that handle, which could otherwise deadlock. -- withForkWait :: IO () -> (IO () -> IO a) -> IO a withForkWait async body = do waitVar <- newEmptyMVar :: IO (MVar (Either SomeException ())) mask $ \restore -> do tid <- forkIO $ try (restore async) >>= putMVar waitVar let wait = takeMVar waitVar >>= either throwIO return restore (body wait) `C.onException` killThread tid ignoreSigPipe :: IO () -> IO () #if defined(__GLASGOW_HASKELL__) ignoreSigPipe = C.handle $ \e -> case e of IOError { ioe_type = ResourceVanished , ioe_errno = Just ioe } | Errno ioe == ePIPE -> return () _ -> throwIO e #else ignoreSigPipe = id #endif
sol/better-process
src/System/Process/Copied.hs
mit
3,544
0
16
878
840
447
393
56
1
{-# LANGUAGE RankNTypes, FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Turnip.Eval.Types where import qualified Turnip.AST as AST (Block) import qualified Data.Map as Map import Control.Lens hiding (Context) import Control.Monad.Except import Control.Monad.RWS -- TODO - think about reference counting on those newtype TableRef = TableRef Int deriving (Ord, Eq, Show) newtype FunctionRef = FunctionRef Int deriving (Ord, Eq, Show) newtype LuaMT m a = LuaMT (ExceptT Value (RWST Closure () Context m) a) deriving (Functor, Applicative, Monad, MonadIO, MonadError Value) -- MonadState Context is not provided on purpose -- potentially I could provide those, but the user can also add them himself -- MonadCont, MonadReader Closure, MonadWriter (if ever) instance MonadTrans LuaMT where lift = LuaMT . lift . lift type LuaM a = forall m. Monad m => LuaMT m a data Value where { Nil :: Value; Table :: TableRef -> Value; Function :: FunctionRef -> Value; Str :: String -> Value; Boolean :: Bool -> Value; Number :: Double -> Value; } deriving (Ord, Eq, Show) -- I don't think it's supposed to be an existential type NativeFunction = [Value] -> LuaM [Value] -- This is a stack of tables forming a stack of nested closures data ClosureLevel = ClosureLevel { closureTableRef :: TableRef, closureVarargs :: Maybe [Value] } type Closure = [ClosureLevel] data FunctionData = FunctionData { fdClosure :: Closure, fdBlock :: AST.Block, fdParamNames :: [String], fdHasVarargs :: Bool } | BuiltinFunction { nativeFn :: NativeFunction } type TableMapData = Map.Map Value Value data TableData = TableData { _mapData :: TableMapData, _metatable :: Maybe TableRef -- Can be either nil or some table } data Context = Context { _gRef :: TableRef, _functions :: Map.Map FunctionRef FunctionData, _tables :: Map.Map TableRef TableData, _lastId :: Int } makeLenses ''Context type LuaError = String -- |This type represents something that breaks the block execution -- and moves up the statement chain. data Bubble = BreakBubble | ReturnBubble [Value] | EmptyBubble deriving (Show, Eq) makeLenses ''TableData
bananu7/Turnip
src/Turnip/Eval/Types.hs
mit
2,495
1
11
503
533
320
213
54
0
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module NLP.Senna.Processor where import Control.Applicative ((<$>), (<*>)) import NLP.Senna.Types import NLP.Senna.Tags import NLP.Senna.Util -- | The 'Processor' type class provides the 'process' function which -- can be used to perform NLP tasks on a sentence after -- the 'NLP.Senna.Functions.tokenize' function was called. class Processor a where -- | Perform a NLP task on a previously tokenized sentence. -- -- * Some 'process' functions return 'NLP.Senna.Types.Position' to indicate -- where a tag was found. These positions are always at /token-level/. -- -- * Some 'process' functions return 'NLP.Senna.Types.Phrase'. These phrases -- are a list of tokens which belong to tag. -- -- * Some 'process' functions provide results with and without 'Maybe'. -- The results using 'Maybe' cover all tokens; the results -- without 'Maybe' cover only those tokens which could be tagged. process :: Context -> IO [a] instance Processor Token where process = getTokens instance Processor (Maybe POS) where process ctx = map convert <$> getPosTags ctx instance Processor (Maybe NER, Position) where process ctx = deducePositions <$> getNerTags ctx instance Processor (Maybe CHK, Position) where process ctx = deducePositions <$> getChkTags ctx instance Processor (Maybe NER, Phrase) where process ctx = deducePhrases <$> getTokens ctx <*> process ctx instance Processor (Maybe CHK, Phrase) where process ctx = deducePhrases <$> getTokens ctx <*> process ctx instance Processor (NER, Position) where process ctx = dropNothing <$> process ctx instance Processor (NER, Phrase) where process ctx = dropNothing <$> process ctx instance Processor (CHK, Position) where process ctx = dropNothing <$> process ctx instance Processor (CHK, Phrase) where process ctx = dropNothing <$> process ctx instance Processor [(Maybe SRL, Position)] where process ctx = map deducePositions <$> getSrlTags ctx instance Processor [(Maybe SRL, Phrase)] where process ctx = mapDeduce <$> getTokens ctx <*> process ctx where mapDeduce tokens = map (deducePhrases tokens) instance Processor [(SRL, Position)] where process ctx = map dropNothing <$> process ctx instance Processor [(SRL, Phrase)] where process ctx = map dropNothing <$> process ctx
slyrz/hase
src/NLP/Senna/Processor.hs
mit
2,481
0
10
491
555
295
260
52
0
{-| Module : Data.Telephony.Meid Description : Contains a data structure that represents a Mobile Equipment Identifier and various MEID functions. Copyright : (c) 2015 Nick Saunders License : MIT Maintainer : [email protected] -} module Data.Telephony.Meid (Meid (HexMeid, DecMeid), Data.Telephony.Meid.showHex, showDec) where import Data.Char (toUpper) import Numeric (readHex, showHex) -- | The 'Meid' type represents a Mobile Equipment Identifier (MEID). data Meid = HexMeid [Char] -- ^ Constructs a MEID given a MEID string in hexadecimal format. | DecMeid [Char] -- ^ Constructs a MEID given a MEID string in decimal format. -- | The 'showHex' function shows a MEID in hexadecimal format. showHex :: Meid -- ^ The MEID to show in hexadecimal format -> [Char] -- ^ The MEID in hexadecimal format showHex (HexMeid m) = m showHex (DecMeid m) = uppercase $ (hex (firstPart $ DecMeid m)) ++ (hex (secondPart $ DecMeid m)) -- | The 'showDec' function shows a MEID in decimal format. showDec :: Meid -- ^ The MEID to show in decimal format -> [Char] -- ^ The MEID in decimal format showDec (DecMeid m) = m showDec (HexMeid m) = (++) (unwrap $ readHex (firstPart $ HexMeid m)) (zeropad 8 (unwrap $ readHex (secondPart $ HexMeid m))) uppercase (x:xs) = (toUpper x) : (uppercase xs) uppercase [] = [] hex n = Numeric.showHex (read n) "" unwrap [(a, b)] = show a zeropad n s = if (length s) == n then s else zeropad n ("0" ++ s) firstPart :: Meid -> [Char] firstPart (DecMeid m) = take 10 m firstPart (HexMeid m) = take 8 m secondPart :: Meid -> [Char] secondPart (DecMeid m) = reverse (take 8 $ reverse m) secondPart (HexMeid m) = reverse (take 6 $ reverse m)
therealnicksaunders/meid
library/Data/Telephony/Meid.hs
mit
1,764
0
13
401
500
269
231
29
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ViewPatterns #-} module Main where import Control.Arrow ((***)) import Data.Maybe (fromJust) import Data.Text.Prettyprint.Doc.Render.Text (putDoc) import System.Environment (getArgs) import Language.Egison.AST import Language.Egison.Parser (readUTF8File, removeShebang) import Language.Egison.Parser.SExpr import Language.Egison.Pretty exprInfix :: [(String, Op)] exprInfix = [ ("**", Op "^" 8 InfixL False) , ("**'", Op "^'" 8 InfixL False) , ("*", Op "*" 7 InfixL False) , ("/", Op "/" 7 InfixL False) , ("*'", Op "*'" 7 InfixL False) , ("/'", Op "/'" 7 InfixL False) , (".", Op "." 7 InfixL False) -- tensor multiplication , (".'", Op ".'" 7 InfixL False) -- tensor multiplication , ("remainder", Op "%" 7 InfixL False) -- primitive function , ("+", Op "+" 6 InfixL False) , ("-", Op "-" 6 InfixL False) , ("+'", Op "+'" 6 InfixL False) , ("-'", Op "-'" 6 InfixL False) , ("append", Op "++" 5 InfixR False) , ("cons", Op "::" 5 InfixR False) , ("equal", Op "=" 4 InfixL False) -- primitive function , ("lte", Op "<=" 4 InfixL False) -- primitive function , ("gte", Op ">=" 4 InfixL False) -- primitive function , ("lt", Op "<" 4 InfixL False) -- primitive function , ("gt", Op ">" 4 InfixL False) -- primitive function , ("&&", Op "&&" 3 InfixR False) , ("and", Op "&&" 3 InfixR False) , ("||", Op "||" 2 InfixR False) , ("or", Op "||" 2 InfixR False) , ("apply", Op "$" 0 InfixR False) ] patternInfix :: [(String, Op)] patternInfix = [ ("^", Op "^" 8 InfixL False) -- PowerPat , ("*", Op "*" 7 InfixL False) -- MultPat , ("div", Op "/" 7 InfixL False) -- DivPat , ("+", Op "+" 6 InfixL False) -- PlusPat , ("cons", Op "::" 5 InfixR False) , ("join", Op "++" 5 InfixR False) , ("&", Op "&" 3 InfixR False) , ("|", Op "|" 2 InfixR False) ] lookupVarExprInfix :: String -> Maybe Op lookupVarExprInfix x = lookup x exprInfix class SyntaxElement a where toNonS :: a -> a instance SyntaxElement TopExpr where toNonS (Define x y) = Define (toNonS x) (toNonS y) toNonS (Test x) = Test (toNonS x) toNonS (Execute x) = Execute (toNonS x) toNonS x = x instance SyntaxElement Expr where toNonS (VarExpr (lookupVarExprInfix -> Just op)) = SectionExpr op Nothing Nothing toNonS (VarExpr x) = VarExpr x toNonS (IndexedExpr b x ys) = IndexedExpr b (toNonS x) (map toNonS ys) toNonS (SubrefsExpr b x y) = SubrefsExpr b (toNonS x) (toNonS y) toNonS (SuprefsExpr b x y) = SuprefsExpr b (toNonS x) (toNonS y) toNonS (UserrefsExpr b x y) = UserrefsExpr b (toNonS x) (toNonS y) toNonS (TupleExpr xs) = TupleExpr (map toNonS xs) toNonS (CollectionExpr xs) = CollectionExpr (map toNonS xs) toNonS (ConsExpr x xs) = InfixExpr cons (toNonS x) (toNonS xs) where cons = fromJust $ lookup "cons" exprInfix toNonS (JoinExpr x xs) = InfixExpr append (toNonS x) (toNonS xs) where append = fromJust $ lookup "append" exprInfix toNonS (HashExpr xs) = HashExpr (map (toNonS *** toNonS) xs) toNonS (VectorExpr xs) = VectorExpr (map toNonS xs) toNonS (LambdaExpr xs e) = LambdaExpr xs (toNonS e) toNonS (MemoizedLambdaExpr xs e) = MemoizedLambdaExpr xs (toNonS e) toNonS (CambdaExpr x e) = CambdaExpr x (toNonS e) toNonS (PatternFunctionExpr xs p) = PatternFunctionExpr xs (toNonS p) toNonS (IfExpr x y z) = IfExpr (toNonS x) (toNonS y) (toNonS z) toNonS (LetRecExpr xs y) = LetRecExpr (map toNonS xs) (toNonS y) toNonS (WithSymbolsExpr xs y) = WithSymbolsExpr xs (toNonS y) toNonS (MatchExpr pmmode m p xs) = MatchExpr pmmode (toNonS m) (toNonS p) (map toNonS xs) toNonS (MatchAllExpr pmmode m p xs) = MatchAllExpr pmmode (toNonS m) (toNonS p) (map toNonS xs) toNonS (MatchLambdaExpr p xs) = MatchLambdaExpr (toNonS p) (map toNonS xs) toNonS (MatchAllLambdaExpr p xs) = MatchAllLambdaExpr (toNonS p) (map toNonS xs) toNonS (MatcherExpr xs) = MatcherExpr (map toNonS xs) toNonS (AlgebraicDataMatcherExpr xs) = AlgebraicDataMatcherExpr (map (\(s, es) -> (s, map toNonS es)) xs) toNonS (QuoteExpr x) = QuoteExpr (toNonS x) toNonS (QuoteSymbolExpr x) = QuoteSymbolExpr (toNonS x) toNonS (WedgeApplyExpr (VarExpr (lookupVarExprInfix -> Just op)) (y:ys)) = optimize $ foldl (\acc x -> InfixExpr op' acc (toNonS x)) (toNonS y) ys where op' = op { isWedge = True } optimize (InfixExpr Op{ repr = "*" } (ConstantExpr (IntegerExpr (-1))) e2) = PrefixExpr "-" (optimize e2) optimize (InfixExpr op e1 e2) = InfixExpr op (optimize e1) (optimize e2) optimize e = e toNonS (WedgeApplyExpr x ys) = WedgeApplyExpr (toNonS x) (map toNonS ys) toNonS (DoExpr xs y) = DoExpr (map toNonS xs) (toNonS y) toNonS (SeqExpr e1 e2) = SeqExpr (toNonS e1) (toNonS e2) toNonS (ApplyExpr (VarExpr (lookupVarExprInfix -> Just op)) (y:ys)) = optimize $ foldl (\acc x -> InfixExpr op acc (toNonS x)) (toNonS y) ys where optimize (InfixExpr Op{ repr = "*" } (ConstantExpr (IntegerExpr (-1))) e2) = PrefixExpr "-" (optimize e2) optimize (InfixExpr op e1 e2) = InfixExpr op (optimize e1) (optimize e2) optimize e = e toNonS (ApplyExpr x ys) = ApplyExpr (toNonS x) (map toNonS ys) toNonS (CApplyExpr e1 e2) = CApplyExpr (toNonS e1) (toNonS e2) toNonS (AnonParamFuncExpr n e) = case AnonParamFuncExpr n (toNonS e) of AnonParamFuncExpr 2 (InfixExpr op (AnonParamExpr 1) (AnonParamExpr 2)) -> SectionExpr op Nothing Nothing -- TODO(momohatt): Check if %1 does not appear freely in e -- AnonParamFuncExpr 1 (InfixExpr op e (AnonParamExpr 1)) -> -- SectionExpr op (Just (toNonS e)) Nothing -- AnonParamFuncExpr 1 (InfixExpr op (AnonParamExpr 1) e) -> -- SectionExpr op Nothing (Just (toNonS e)) e' -> e' toNonS (GenerateTensorExpr e1 e2) = GenerateTensorExpr (toNonS e1) (toNonS e2) toNonS (TensorExpr e1 e2) = TensorExpr (toNonS e1) (toNonS e2) toNonS (TensorContractExpr e1) = TensorContractExpr (toNonS e1) toNonS (TensorMapExpr e1 e2) = TensorMapExpr (toNonS e1) (toNonS e2) toNonS (TensorMap2Expr e1 e2 e3) = TensorMap2Expr (toNonS e1) (toNonS e2) (toNonS e3) toNonS (TransposeExpr e1 e2) = TransposeExpr (toNonS e1) (toNonS e2) toNonS (FlipIndicesExpr _) = error "Not supported: FlipIndicesExpr" toNonS x = x instance SyntaxElement Pattern where toNonS (ValuePat e) = ValuePat (toNonS e) toNonS (PredPat e) = PredPat (toNonS e) toNonS (IndexedPat p es) = IndexedPat (toNonS p) (map toNonS es) toNonS (LetPat binds pat) = LetPat (map toNonS binds) (toNonS pat) toNonS (InfixPat op p1 p2) = InfixPat op (toNonS p1) (toNonS p2) toNonS (NotPat p) = NotPat (toNonS p) toNonS (AndPat p1 p2) = InfixPat op (toNonS p1) (toNonS p2) where op = fromJust $ lookup "&" patternInfix toNonS (OrPat p1 p2) = InfixPat op (toNonS p1) (toNonS p2) where op = fromJust $ lookup "|" patternInfix toNonS ForallPat{} = error "Not supported: forall pattern" toNonS (TuplePat ps) = TuplePat (map toNonS ps) toNonS (InductivePat ((`lookup` patternInfix) -> Just op) [p1, p2]) = InfixPat op (toNonS p1) (toNonS p2) toNonS (InductivePat name ps) = InductivePat name (map toNonS ps) toNonS (LoopPat i range p1 p2) = LoopPat i (toNonS range) (toNonS p1) (toNonS p2) toNonS (PApplyPat e p) = PApplyPat (toNonS e) (map toNonS p) toNonS (SeqConsPat p1 p2) = SeqConsPat (toNonS p1) (toNonS p2) toNonS (DApplyPat p ps) = DApplyPat (toNonS p) (map toNonS ps) toNonS p = p instance SyntaxElement PrimitivePatPattern where toNonS (PPInductivePat x pps) = PPInductivePat x (map toNonS pps) toNonS (PPTuplePat pps) = PPTuplePat (map toNonS pps) toNonS pp = pp instance SyntaxElement PrimitiveDataPattern where toNonS (PDInductivePat x pds) = PDInductivePat x (map toNonS pds) toNonS (PDTuplePat pds) = PDTuplePat (map toNonS pds) toNonS (PDConsPat pd1 pd2) = PDConsPat (toNonS pd1) (toNonS pd2) toNonS (PDSnocPat pd1 pd2) = PDSnocPat (toNonS pd1) (toNonS pd2) toNonS pd = pd instance SyntaxElement LoopRange where toNonS (LoopRange e1 e2 p) = LoopRange (toNonS e1) (toNonS e2) (toNonS p) instance SyntaxElement a => SyntaxElement (IndexExpr a) where toNonS script = toNonS <$> script instance SyntaxElement BindingExpr where toNonS (Bind pdp x) = Bind (toNonS pdp) (toNonS x) toNonS (BindWithIndices var x) = BindWithIndices var (toNonS x) instance SyntaxElement MatchClause where toNonS (pat, body) = (toNonS pat, toNonS body) instance SyntaxElement PatternDef where toNonS (x, y, zs) = (toNonS x, toNonS y, map (\(z, w) -> (toNonS z, toNonS w)) zs) instance SyntaxElement VarWithIndices where toNonS = id main :: IO () main = do args <- getArgs input <- readUTF8File $ head args -- 'ast' is not desugared let ast = parseTopExprs (removeShebang True input) case ast of Left err -> print err Right ast -> do putStrLn "--" putStrLn "-- This file has been auto-generated by egison-translator." putStrLn "--" putStrLn "" putDoc $ prettyTopExprs $ map toNonS ast putStrLn ""
egison/egison
hs-src/Tool/translator.hs
mit
9,659
0
16
2,451
3,812
1,935
1,877
181
2
{-# LANGUAGE NoMonomorphismRestriction #-} import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine import Viz.Catalan import Catalan bigarrow = arrowAt (0 ^& 0) (2*unitX) main = let t1 = B (B L (B (B L L) L)) L in let t2 = B L (B (B (B L L) L) L) in let t3 = B L (B (B L L) (B L L)) in let d = hsep 1 [ vsep 1 [diagArcs (tree2arcs t1) # centerX, diagTree t1 # centerX], vsep 1 [mempty,bigarrow], vsep 1 [diagArcs (tree2arcs t2) # centerX, diagTree t2 # centerX], vsep 1 [mempty,bigarrow], vsep 1 [diagArcs (tree2arcs t3) # centerX, diagTree t3 # centerX] ] in mainWith d
noamz/linlam-gos
src/Viz/Test.hs
mit
661
0
22
195
320
162
158
18
1
{-# language DeriveDataTypeable #-} {-# language FlexibleInstances #-} {-# language TupleSections #-} module Algebraic.Set.Multi where import Expression.Op hiding (Identifier) import qualified Autolib.TES.Binu as B import Autolib.ToDoc import Autolib.Reader hiding ((<|>), many) import qualified Data.Map.Strict as M import Control.Applicative import Control.Monad import Data.Typeable import Autolib.Util.Zufall import Autolib.Pick newtype Multiset a = Multiset (M.Map a Int) deriving Typeable instance Ops (Multiset Identifier) where bops = B.Binu { B.nullary = [] , B.unary = [] , B.binary = [ Op { name = "+", arity = 2 , precedence = Just 5, assoc = AssocLeft , inter = lift2 union } , Op { name = "-", arity = 2 , precedence = Just 5, assoc = AssocLeft , inter = lift2 difference } , Op { name = "&", arity = 2 , precedence = Just 7, assoc = AssocLeft , inter = lift2 intersection } ] } roll :: Ord a => [a] -> Int -> IO (Multiset a) roll base max_coeff = multiset <$> ( forM base $ \ b -> do action <- pick [ return 0, randomRIO (1, max_coeff)] (b,) <$> action ) multiset :: Ord a => [(a,Int)] -> Multiset a multiset kvs = Multiset $ M.filter (/= 0) $ M.fromListWith (+) kvs instance ToDoc a => ToDoc (Multiset a) where toDoc (Multiset m) = braces $ hsep $ punctuate comma $ map (\(k,v) -> hcat [ toDoc k, text ":", toDoc v ]) $ M.toList m instance (Ord a, Reader a) => Reader (Multiset a) where reader = multiset <$> ( my_braces $ my_commaSep $ do k <- reader my_symbol ":" v <- mfilter (> 0) reader <|> fail "must be positive" return (k,v) ) null :: Ord a => Multiset a -> Bool null (Multiset a) = M.null a union :: Ord a => Multiset a -> Multiset a -> Multiset a union (Multiset a) (Multiset b) = Multiset $ M.unionWith (+) a b difference :: Ord a => Multiset a -> Multiset a -> Multiset a difference (Multiset a) (Multiset b) = Multiset $ M.filter (> 0) $ M.differenceWith ( \ x y -> Just (x-y) ) a b symmetric_difference :: Ord a => Multiset a -> Multiset a -> Multiset a symmetric_difference (Multiset a) (Multiset b) = Multiset $ M.filter (> 0) $ M.unionWith ( \ x y -> abs (x-y)) a b intersection :: Ord a => Multiset a -> Multiset a -> Multiset a intersection (Multiset a) (Multiset b) = Multiset $ M.filter (> 0) $ M.intersectionWith min a b newtype Identifier = Identifier String deriving (Eq, Ord, Typeable) instance ToDoc Identifier where toDoc (Identifier s) = text s instance Reader Identifier where reader = Identifier <$> ( (:) <$> letter <*> many alphaNum ) <* my_whiteSpace
marcellussiegburg/autotool
collection/src/Algebraic/Set/Multi.hs
gpl-2.0
2,893
0
15
849
1,098
584
514
72
1
--07-07 compute all mnemonics for a phone number import qualified Data.HashMap.Strict as H keypad :: H.HashMap Char String keypad = H.fromList [('2',"abc"),('3',"def"),('4',"ghi"),('5',"jkl"),('6',"mno"),('7',"pqrs"),('8',"tuv"),('9',"wxyz")] encode :: String -> [String] encode [] = [[]] encode (x:xs) = do rest <- encode xs chars <- keypad H.! x return (chars : rest) main :: IO () main = do putStrLn $ show $ encode "29"
cem3394/EPI-Haskell
07-07_computeMnemonics.hs
gpl-3.0
437
0
9
74
212
120
92
12
1
module Lamdu.GUI.Expr.RecordEdit ( make, makeEmpty ) where import qualified Control.Lens as Lens import qualified Data.Char as Char import qualified Data.Text as Text import qualified GUI.Momentu as M import qualified GUI.Momentu.Element as Element import GUI.Momentu.EventMap (EventMap) import qualified GUI.Momentu.EventMap as E import qualified GUI.Momentu.Glue as Glue import qualified GUI.Momentu.I18N as MomentuTexts import GUI.Momentu.Responsive (Responsive) import qualified GUI.Momentu.Responsive as Responsive import GUI.Momentu.Responsive.TaggedList (TaggedItem(..), taggedListIndent, tagPre, tagPost) import qualified GUI.Momentu.State as GuiState import qualified GUI.Momentu.View as View import qualified GUI.Momentu.Widget as Widget import qualified GUI.Momentu.Widgets.Menu as Menu import qualified GUI.Momentu.Widgets.Menu.Search as SearchMenu import qualified GUI.Momentu.Widgets.StdKeys as StdKeys import qualified GUI.Momentu.Widgets.Spacer as Spacer import qualified Lamdu.Config as Config import qualified Lamdu.Config.Theme as Theme import Lamdu.Config.Theme.TextColors (TextColors) import qualified Lamdu.Config.Theme.TextColors as TextColors import qualified Lamdu.GUI.Expr.GetVarEdit as GetVarEdit import qualified Lamdu.GUI.Expr.TagEdit as TagEdit import Lamdu.GUI.Monad (GuiM) import qualified Lamdu.GUI.Monad as GuiM import Lamdu.GUI.Styled (label, grammar) import qualified Lamdu.GUI.Styled as Styled import qualified Lamdu.GUI.TaggedList as TaggedList import qualified Lamdu.GUI.Types as ExprGui import qualified Lamdu.GUI.WidgetIds as WidgetIds import Lamdu.GUI.Wrap (stdWrap, stdWrapParentExpr) import qualified Lamdu.I18N.Code as Texts import qualified Lamdu.I18N.CodeUI as Texts import qualified Lamdu.I18N.Navigation as Texts import Lamdu.Name (Name(..)) import qualified Lamdu.Sugar.Lens as SugarLens import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude import qualified GUI.Momentu.State as M doc :: _ => env -> [Lens.ALens' (Texts.CodeUI Text) Text] -> E.Doc doc env lens = E.toDoc env ([has . MomentuTexts.edit, has . Texts.record] <> (lens <&> (has .))) addFieldWithSearchTermEventMap :: _ => env -> Widget.Id -> EventMap (o GuiState.Update) addFieldWithSearchTermEventMap env myId = E.charEventMap "Letter" (doc env [Texts.field, Texts.add]) f where f c | Char.isAlpha c = TagEdit.addItemId myId & SearchMenu.enterWithSearchTerm (Text.singleton c) & pure & Just | otherwise = Nothing makeUnit :: _ => ExprGui.Payload i o -> GuiM env i o (Responsive o) makeUnit pl = do makeFocusable <- Widget.makeFocusableView ?? myId <&> (M.tValue %~) env <- Lens.view id let addFieldEventMap = E.keysEventMapMovesCursor (env ^. has . Config.recordAddFieldKeys) (doc env [Texts.field, Texts.add]) (pure (TagEdit.addItemId myId)) grammar (label Texts.recordOpener) M./|/ grammar (label Texts.recordCloser) <&> makeFocusable <&> M.tValue %~ Widget.weakerEvents (addFieldEventMap <> addFieldWithSearchTermEventMap env myId) <&> Responsive.fromWithTextPos & stdWrap pl where myId = WidgetIds.fromExprPayload pl makeAddField :: _ => i (Sugar.TagChoice Name o) -> Widget.Id -> GuiM env i o (Maybe (TaggedItem o)) makeAddField addField baseId = GuiState.isSubCursor ?? myId <&> guard >>= (Lens._Just . const) (GuiM.im addField >>= makeAddFieldRow myId) where myId = TagEdit.addItemId baseId makeEmpty :: _ => Annotated (ExprGui.Payload i o) # Const (i (Sugar.TagChoice Name o)) -> GuiM env i o (Responsive o) makeEmpty (Ann (Const pl) (Const addField)) = makeAddField addField (WidgetIds.fromExprPayload pl) >>= maybe (makeUnit pl) (stdWrapParentExpr pl . makeRecord pure . (:[])) make :: _ => ExprGui.Expr Sugar.Composite i o -> GuiM env i o (Responsive o) make (Ann (Const pl) (Sugar.Composite (Sugar.TaggedList addField Nothing) [] Sugar.ClosedCompositeTail{})) = -- Ignore the ClosedComposite actions - it only has the open -- action which is equivalent ot deletion on the unit record makeEmpty (Ann (Const pl) (Const addField)) make (Ann (Const pl) (Sugar.Composite (Sugar.TaggedList addField mTlBody) punned recordTail)) = do tailEventMap <- case recordTail of Sugar.ClosedCompositeTail actions -> closedRecordEventMap actions Sugar.OpenCompositeTail{} -> pure mempty env <- Lens.view id let goToRecordEventMap = WidgetIds.fromExprPayload pl & GuiState.updateCursor & pure & const & E.charGroup Nothing (E.toDoc env [ has . MomentuTexts.navigation , has . Texts.goToParent ]) "}" keys <- traverse Lens.view TaggedList.Keys { TaggedList._kAdd = has . Config.recordAddFieldKeys , TaggedList._kOrderBefore = has . Config.orderDirKeys . StdKeys.keysUp , TaggedList._kOrderAfter = has . Config.orderDirKeys . StdKeys.keysDown } let prependEventMap = addFieldWithSearchTermEventMap env myId mconcat [ makeAddField addField myId <&> (^.. traverse) , foldMap (TaggedList.makeBody (has . Texts.field) keys myId myId) mTlBody >>= traverse makeFieldRow <&> concat <&> Lens.ix 0 . tagPre . Lens._Just . M.tValue %~ M.weakerEvents prependEventMap , case punned of [] -> pure [] _ -> M.weakerEvents <$> TaggedList.addNextEventMap (has . Texts.field) (keys ^. TaggedList.kAdd) punAddId <*> GetVarEdit.makePunnedVars punned <&> (:[]) . (TaggedItem Nothing ?? Nothing) ] >>= makeRecord postProcess <&> Widget.weakerEvents (goToRecordEventMap <> tailEventMap) & stdWrapParentExpr pl & (foldl assignPunned ?? punned) where assignPunned w p = M.assignCursorPrefix (WidgetIds.fromEntityId (p ^. Sugar.pvTagEntityId)) (Widget.joinId punAddId) w myId = WidgetIds.fromExprPayload pl punAddId = mTlBody >>= Lens.lastOf (SugarLens.taggedListBodyItems . Sugar.tiTag) & maybe myId TaggedList.itemId postProcess = case recordTail of Sugar.OpenCompositeTail restExpr -> makeOpenRecord restExpr _ -> pure makeRecord :: _ => (Responsive o -> m (Responsive o)) -> [TaggedItem o] -> m (Responsive o) makeRecord _ [] = error "makeRecord with no fields" makeRecord postProcess fieldGuis = Styled.addValFrame <*> ( grammar (label Texts.recordOpener) M./|/ (taggedListIndent <*> addPostTags fieldGuis >>= postProcess) ) addPostTags :: _ => [TaggedItem o] -> m [TaggedItem o] addPostTags items = do let f idx item = label (if isComma then Texts.recordSep else Texts.recordCloser) & grammar & (if isComma then Element.locallyAugmented idx else id) <&> \lbl -> item & tagPost ?~ (lbl <&> Widget.fromView) where isComma = idx < lastIdx Lens.itraverse f items where lastIdx = length items - 1 makeAddFieldRow :: _ => Widget.Id -> Sugar.TagChoice Name o -> GuiM env i o (TaggedItem o) makeAddFieldRow tagHoleId addField = TagEdit.makeTagHoleEdit mkPickResult tagHoleId addField & Styled.withColor TextColors.recordTagColor & setPickAndAddNextKeys <&> \tagHole -> TaggedItem { _tagPre = Nothing , _taggedItem = Responsive.fromWithTextPos tagHole , _tagPost = Just M.empty } where mkPickResult dst = Menu.PickResult { Menu._pickDest = WidgetIds.ofTagValue dst , Menu._pickMNextEntry = WidgetIds.fromEntityId dst & TagEdit.addItemId & Just } setPickAndAddNextKeys :: _ => GuiM env i o a -> GuiM env i o a setPickAndAddNextKeys = local (\env -> env & has . Menu.configKeysPickOptionAndGotoNext .~ env ^. has . Config.recordAddFieldKeys & has . Menu.configKeysPickOption <>~ env ^. has . Menu.configKeysPickOptionAndGotoNext <> [M.noMods M.Key'Space] ) makeFieldRow :: _ => TaggedList.Item Name i o (ExprGui.Expr Sugar.Term i o) -> GuiM env i o [TaggedItem o] makeFieldRow item = do fieldGui <- GuiM.makeSubexpression (item ^. TaggedList.iValue) & M.assignCursor (WidgetIds.ofTagValue fieldId) (item ^. TaggedList.iValue . annotation & WidgetIds.fromExprPayload) pre <- TagEdit.makeRecordTag (Just . TagEdit.addItemId . WidgetIds.fromEntityId) (item ^. TaggedList.iTag) <&> M.tValue %~ Widget.weakerEvents (item ^. TaggedList.iEventMap) & setPickAndAddNextKeys let row = TaggedItem { _tagPre = Just pre , _taggedItem = M.weakerEvents (item ^. TaggedList.iEventMap) fieldGui , _tagPost = Just M.empty } makeAddField (item ^. TaggedList.iAddAfter) myId <&> (^.. traverse) <&> (row:) where fieldId = item ^. TaggedList.iTag . Sugar.tagRefTag . Sugar.tagInstance myId = WidgetIds.fromEntityId fieldId separationBar :: TextColors -> M.AnimId -> Widget.R -> M.View separationBar theme animId width = View.unitSquare (animId <> ["tailsep"]) & M.tint (theme ^. TextColors.recordTailColor) & M.scale (M.Vector2 width 10) makeOpenRecord :: _ => ExprGui.Expr Sugar.Term i o -> Responsive o -> GuiM env i o (Responsive o) makeOpenRecord rest fieldsGui = do theme <- Lens.view has vspace <- Spacer.stdVSpace restExpr <- Styled.addValPadding <*> GuiM.makeSubexpression rest animId <- Lens.view M.animIdPrefix (|---|) <- Glue.mkGlue ?? Glue.Vertical Responsive.vboxWithSeparator ?? False ?? (separationBar (theme ^. Theme.textColors) animId <&> (|---| vspace)) ?? fieldsGui ?? restExpr closedRecordEventMap :: _ => Sugar.ClosedCompositeActions o -> m (EventMap (o GuiState.Update)) closedRecordEventMap (Sugar.ClosedCompositeActions open) = Lens.view id <&> \env -> open <&> WidgetIds.fromEntityId & E.keysEventMapMovesCursor (env ^. has . Config.recordOpenKeys) (doc env [Texts.open])
lamdu/lamdu
src/Lamdu/GUI/Expr/RecordEdit.hs
gpl-3.0
10,806
0
25
2,890
3,079
1,629
1,450
-1
-1
{-# LANGUAGE GADTs #-} -- | This module houses the persitence backend for node operations. It -- supports appending events and caching reports. module MuPromote.Common.Persist ( EventStore, Report, appendEvent, dirBackedEventStore, memoryBackedEventStore, evalReport, lookupEvent, registerReport ) where import Control.Applicative import Control.Arrow import Control.Concurrent.MVar import Control.Exception import Control.Monad import qualified Data.ByteString as BS import qualified Data.ByteString.Base64 as B64 import qualified Data.Map as M import Data.Maybe import Data.SafeCopy import qualified Data.Serialize as DS import qualified Data.Text as T import qualified Data.Text.Encoding as T import System.Directory import System.IO.Error -- | The type for persistance stores. It supports appending events and -- evaluating reports, which are like cached database queries restricted -- to associative functions on the set of events. Note that an EventStore -- captures only the persisting-interface and does not give any type or -- serialization guarantees. While the backend interface is agnostic of -- serialization infrastructure, the rest of this api uses SafeCopy. data EventStoreBackend = EventStoreBackend { esAppendEvent :: BS.ByteString -> IO (), esNumEvents :: IO Int, esLookupEvent :: Int -> IO (Maybe BS.ByteString), -- | Read a stored report (identified by name), represented as (evNum, state). esReadReport :: String -> IO (Maybe (Int, BS.ByteString)), -- | Store a report evaluation, represented as (evNum, state). esStoreReport :: String -> (Int, BS.ByteString) -> IO () } newtype EventStore a = ES { unES :: EventStoreBackend } -- | The type of report functions, i.e. aggregations on the event log. -- Reports are evaluated in the context of an event store. -- Report functions are always associative. data Report a st = (SafeCopy a, SafeCopy st) => Report { repES :: EventStore a, repName :: String, repInitSt :: st, repFn :: st -> a -> st } -- | Open an EventStore, creating it if it doesn't exist. The given -- filepath should refer to a directory. -- CURRENTLY NOT THREADSAFE. dirBackedEventStore :: SafeCopy a => FilePath -> IO (EventStore a) dirBackedEventStore dir = do let eventDir = dir ++ "/events" let reportDir = dir ++ "/reports" mapM_ (createDirectoryIfMissing True) [eventDir, reportDir] return . ES $ EventStoreBackend { esAppendEvent = \bs -> do fileName <- fmap show (numProperDirChildren eventDir) BS.writeFile (eventDir ++ "/" ++ fileName) bs, esNumEvents = numProperDirChildren eventDir, esLookupEvent = \num -> exn2Maybe isDoesNotExistError $ BS.readFile $ eventDir ++ "/" ++ show num, esReadReport = \reportName -> exn2Maybe isDoesNotExistError $ do let encReportName = encBase64 reportName either error id . DS.decode <$> BS.readFile (reportDir ++ "/" ++ encReportName), esStoreReport = \reportName contents -> do let encReportName = encBase64 reportName BS.writeFile (reportDir ++ "/" ++ encReportName) (DS.encode contents) } where -- | Count the proper children of a directory, i.e. disregarding '.' -- and '..'. numProperDirChildren :: FilePath -> IO Int numProperDirChildren = fmap ((+ negate 2) . length) . getDirectoryContents -- | 'try', specialised to IOException. tryIOEx :: IO a -> IO (Either IOException a) tryIOEx = try -- | Convert certain thrown exceptions to Maybe-actions. exn2Maybe :: (IOException -> Bool) -> IO a -> IO (Maybe a) exn2Maybe exPred act = either (\ex -> if exPred ex then Nothing else throw ex) Just <$> tryIOEx act -- | Base64-encoding for strings. encBase64 :: String -> String encBase64 = T.unpack . T.decodeUtf8 . B64.encode . T.encodeUtf8 . T.pack -- | An 'EventStore a', backed by MVars. memoryBackedEventStore :: SafeCopy a => IO (EventStore a) memoryBackedEventStore = do reportsMV <- newMVar M.empty actionsMV <- newMVar [] return $ ES EventStoreBackend { esAppendEvent = \bs -> modifyMVar_ actionsMV (return . (bs:)), esNumEvents = fmap length (readMVar actionsMV), esLookupEvent = \ix -> do evs <- readMVar actionsMV -- events are reversed relative to list indexing return $ case drop (length evs - succ ix) evs of [] -> Nothing ev:_ -> Just ev, esReadReport = \reportName -> fmap (M.lookup reportName) (readMVar reportsMV), esStoreReport = \reportName val -> modifyMVar_ reportsMV (return . M.insert reportName val) } -- | Append an event to an EventStore. appendEvent :: SafeCopy a => EventStore a -> a -> IO () appendEvent (ES esBackend) = esAppendEvent esBackend . DS.runPut . safePut registerReport :: (SafeCopy a, SafeCopy st) => EventStore a -> String -> st -> (st -> a -> st) -> Report a st registerReport = Report numEvents :: EventStore a -> IO Int numEvents = esNumEvents . unES lookupEvent :: SafeCopy a => EventStore a -> Int -> IO (Maybe a) lookupEvent (ES esBackend) = ((partialDeserialise <$>) <$>) . esLookupEvent esBackend -- | Ignore deserialization errors, throwing exceptions instead of yielding Either. partialDeserialise :: SafeCopy a => BS.ByteString -> a partialDeserialise = either (error "Deserialization error") id . DS.runGet safeGet -- | Evaluate a report. If any events have entered the store since last -- evaluation the stored report is updated. evalReport :: (SafeCopy a, SafeCopy st) => Report a st -> IO st evalReport report = do let es = repES report -- Extract the latest evaluation with index. If esReadReport yields -- Nothing the report has yet to be evaluated, and iteration starts from -- 0 and the inital state. (nextIx, latestEval) <- maybe (0, repInitSt report) (succ *** partialDeserialise) <$> esReadReport (unES es) (repName report) lastIx <- pred <$> numEvents es -- Iterate from the index after latestIx until the last presently -- recorded. res <- foldM (iterateEvalReport es) latestEval [nextIx .. lastIx] esStoreReport (unES es) (repName report) (lastIx, DS.runPut $ safePut res) return res where iterateEvalReport es st ix = do ev <- fromMaybe (error $ "Non-existing event " ++ show ix ++ " in evalReport") <$> lookupEvent es ix return (repFn report st ev)
plcplc/muPromote-code
base/src/MuPromote/Common/Persist.hs
gpl-3.0
6,373
0
19
1,293
1,575
836
739
-1
-1
-- | -- Module : Ligature.JSON -- Copyright : (c) 2013 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Ligature.JSON ( palettes , dashboards ) where import Control.Applicative import Control.Monad import Data.Aeson.Types import Data.Either (partitionEithers) import Data.List (insert, isSuffixOf) import Data.Maybe import Ligature.Types import System.Directory import System.FilePath import qualified Data.Aeson as A import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.HashMap.Strict as H import qualified Data.Text as T palettes :: FilePath -> IO [Palette] palettes dir = map snd <$> loadFiles dir parseJSON dashboards :: FilePath -> [Palette] -> IO (HashMap Dash) dashboards dir ps = H.fromList <$> loadFiles dir (parseDashboard ps) loadFiles :: FilePath -> (Value -> Parser a) -> IO [(Key, a)] loadFiles dir p = do fs <- readFiles dir when (length fs == 0) (error $ "Empty directory: " ++ dir) (es, as) <- partitionEithers . map (parseFile p) <$> readFiles dir mapM putStrLn es return as parseFile :: (Value -> Parser a) -> (FilePath, BL.ByteString) -> Either String (Key, a) parseFile p (path, bstr) = case parseEither p obj of Left e -> Left $ path ++ ": " ++ e Right d -> Right (textKey . T.pack $ takeBaseName path, d) where obj = maybe (error $ "Failed to decode: " ++ BL.unpack bstr) id (A.decode bstr) readFiles :: FilePath -> IO [(FilePath, BL.ByteString)] readFiles dir = jsonFiles dir >>= mapM (g . f) where f x = joinPath [dir, x] g x = (x,) `liftM` BL.readFile x jsonFiles :: FilePath -> IO [FilePath] jsonFiles dir = filter (".json" `isSuffixOf`) <$> getDirectoryContents dir
brendanhay/ligature
src/Ligature/JSON.hs
mpl-2.0
2,148
0
12
508
623
338
285
-1
-1
module Opal.Distance.Stations ( Station(..), stations ) where data Station = Artarmon | Ashfield | Asquith | Auburn | Beecroft | Berowra | Blacktown | BondiJunction | Burwood | Cabramatta | Camellia | CanleyVale | Carlingford | Casula | Central | Chatswood | Cheltenham | CircularQuay | Clarendon | Clyde | ConcordWest | Cowan | Croydon | Denistone | Doonside | Dundas | EastRichmond | Eastwood | Edgecliff | EmuPlains | Epping | Fairfield | Flemington | Gordon | Gosford | Granville | Guildford | HarrisPark | HawkesburyRiver | Homebush | Hornsby | Killara | KingsCross | Kingswood | Koolewong | Lewisham | Lidcombe | Lindfield | Lisarow | Liverpool | Macdonaldtown | MacquariePark | MacquarieUniversity | Marayong | MartinPlace | Meadowbank | Merrylands | MilsonsPoint | MountColah | MountDruitt | MountKuringGai | Mulgrave | Museum | Narara | Newtown | NiagaraPark | Normanhurst | NorthRyde | NorthStrathfield | NorthSydney | OlympicPark | Ourimbah | Parramatta | PendleHill | PennantHills | Penrith | Petersham | PointClare | Pymble | QuakersHill | Redfern | Rhodes | Richmond | Riverstone | RootyHill | Rosehill | Roseville | Rydalmere | Schofields | SevenHills | StJames | StLeonards | StMarys | Stanmore | Strathfield | SummerHill -- TBA at https://www.opal.com.au/en/about-opal/what-services-can-i-use-it-on/Train_stations_with_opal/ | Tascott | Telopea | Thornleigh | Toongabbie | TownHall | Tuggerah | Turramurra | Vineyard | Wahroonga | Waitara | Warrawee | WarwickFarm | Waverton | Wentworthville | Werrington | WestRyde | Westmead | Windsor | Wollstonecraft | Wondobyne | WoyWoy | Wynyard | Wyong | Yennora deriving (Bounded, Eq, Enum, Ord, Read, Show) stations :: [Station] stations = [(minBound :: Station) ..]
mzhou/opaldist
src/Opal/Distance/Stations.hs
agpl-3.0
2,220
0
6
763
434
285
149
127
1
module Main where import Network import qualified Data.ByteString.Char8 as S import Data.Serialize -- Cereal import System.IO import System.Environment import Control.Monad import Control.Applicative import Control.Exception import Data.Word -- Protocol description from the server's Main.hs: -- client a connects -- client b connects -- server sends Response (ready) -- client a sends Request -- client b sends Request -- server sends Response (ready) data Request = Betray | Cooperate deriving Show data Response = Betrayed | Cooperated deriving Show instance Serialize Request where put Betray = put (1 :: Word8) put Cooperate = put (2 :: Word8) get = do byte <- get :: Get Word8 case byte of 1 -> return Betray 2 -> return Cooperate _ -> fail "Invalid Request" instance Serialize Response where put Betrayed = put (4 :: Word8) put Cooperated = put (5 :: Word8) get = do byte <- get :: Get Word8 case byte of 4 -> return Betrayed 5 -> return Cooperated _ -> fail "Invalid Response" port = PortNumber 1234 main :: IO () main = do [hostName, strategy] <- getArgs -- TODO: Parse arguments properly bracket (connectTo hostName port) hClose (runGame (dispatch strategy) Nothing) `catch` disconnected where dispatch strategy = -- TODO: There must be a better way to do this case strategy of "titForTat" -> titForTat "alwaysBetray" -> alwaysBetray "alwaysCooperate" -> alwaysCooperate _ -> fail "Invalid strategy" disconnected :: IOException -> IO () disconnected ex = putStrLn "Done." -- Protocol: just terminate connection. :( runGame :: (Maybe Response -> Request) -> Maybe Response -> Handle -> IO () runGame strategy last h = do request <- S.hPutStrLn h (encode (strategy last)) response <- getResponse runGame strategy (Just response) h where tryDecode bs = case (decode bs) of Left e -> (hClose h) >> error e Right response -> return response getResponse = do bs <- S.hGetLine h tryDecode bs -- Strategies -- TODO: These type signatures are all the same. I feel like I'm missing an abstraction titForTat :: (Maybe Response) -> Request titForTat lastAction = case lastAction of Just Betrayed -> Betray -- Retaliating Just Cooperated -> Cooperate -- Forgiving, Non-Envious Nothing -> Cooperate -- Be Nice alwaysBetray :: (Maybe Response) -> Request alwaysBetray _ = Betray alwaysCooperate :: (Maybe Response) -> Request alwaysCooperate _ = Cooperate
damncabbage/PrisonersDilemmaGameClient
Main.hs
apache-2.0
2,694
0
12
720
691
356
335
68
4
-- Copyright 2017 gRPC authors. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -------------------------------------------------------------------------------- {-# LANGUAGE RecordWildCards #-} module Network.Grpc.CompletionQueue where import Control.Concurrent import Control.Exception import Control.Monad (unless, when) import qualified Data.HashMap.Strict as Map import Foreign.Ptr import Network.Grpc.Lib.Core import Network.Grpc.Lib.TimeSpec data Worker = Worker { cqEventMap :: EventMap, cqNextEventId :: MVar EventId, cqFinished :: MVar () } type EventId = Int type Finalizer = IO () type EventMap = MVar (Map.HashMap EventId (MVar Event, Finalizer)) data EventDesc = EventDesc (MVar Event) EventId startCompletionQueueThread :: CompletionQueue -> IO Worker startCompletionQueueThread cq = do eventMap <- newMVar Map.empty nextEventId <- newMVar 1 finish <- newEmptyMVar let worker = Worker eventMap nextEventId finish _ <- forkIO $ runWorker cq worker return worker waitWorkerTermination :: Worker -> IO () waitWorkerTermination w = readMVar (cqFinished w) eventIdFromTag :: Tag -> EventId eventIdFromTag tag = tag `minusPtr` nullPtr runWorker :: CompletionQueue -> Worker -> IO () runWorker cq Worker{..} = go where go = do e <- grpcCompletionQueueNext cq gprInfFuture case e of QueueTimeOut -> return () QueueShutdown -> do completionQueueDestroy cq b <- tryPutMVar cqFinished () unless b $ putStrLn "** runWorker: error; multiple workers" QueueOpComplete _ tag -> do mDesc <- modifyMVar cqEventMap $ \eventMap -> let mDesc = Map.lookup (eventIdFromTag tag) eventMap eventMap' = Map.delete (eventIdFromTag tag) eventMap in return (eventMap', mDesc) case mDesc of Just (mEvent, finalizer) -> do exc <- try finalizer case exc of Left some -> putStrLn ("** runWorker: finalizer threw exception; " ++ show (some :: SomeException)) Right _ -> return () b <- tryPutMVar mEvent e unless b $ putStrLn "** runWorker: I wasn't first" Nothing -> putStrLn ("** runWorker: could not find tag = " ++ show (eventIdFromTag tag) ++ ", ignoring") go withEvent :: Worker -> Finalizer -> (EventDesc -> IO a) -> IO a withEvent worker finish = bracket (allocateEvent worker finish) (releaseEvent worker) allocateEvent :: Worker -> Finalizer -> IO EventDesc allocateEvent Worker{..} finish = do eventId <- modifyMVar cqNextEventId $ \eventId -> let nextEventId = eventId + 1 in nextEventId `seq` return (nextEventId, eventId) eventMVar <- newEmptyMVar modifyMVar_ cqEventMap $ \eventMap -> return $! Map.insert eventId (eventMVar, finish) eventMap return (EventDesc eventMVar eventId) releaseEvent :: Worker -> EventDesc -> IO () releaseEvent Worker{..} (EventDesc eventMVar eventId) = do b <- tryPutMVar eventMVar (error "releaseEvent: unused event cleanup") when b $ modifyMVar_ cqEventMap $ \eventMap -> return $! Map.delete eventId eventMap interruptibleWaitEvent :: EventDesc -> IO Event interruptibleWaitEvent (EventDesc mvar _) = readMVar mvar eventTag :: EventDesc -> Tag eventTag (EventDesc _ eventId) = mkTag eventId
grpc/grpc-haskell
src/Network/Grpc/CompletionQueue.hs
apache-2.0
3,920
0
26
904
987
495
492
73
5
module Anagram.A279916 (a279916, a279916_list) where import Data.Maybe (fromMaybe) import Data.List (find) import Helpers.AnagramHelper (possibleAnagramBases, nIsBaseBAnagramOf2n) import Anagram.A279688 (a279688) a279916 :: Int -> Integer a279916 n = fromMaybe 0 $ find (nIsBaseBAnagramOf2n a_n) bases where bases = possibleAnagramBases a_n a_n = a279688 n a279916_list :: [Integer] a279916_list = map a279916 [2..]
peterokagey/haskellOEIS
src/Anagram/A279916.hs
apache-2.0
423
0
8
57
131
73
58
11
1
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Application.HXournal.ProgType -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- module Application.HXournal.ProgType where import System.Console.CmdArgs data Hxournal = Test { xojfile :: Maybe FilePath } deriving (Show,Data,Typeable) test :: Hxournal test = Test { xojfile = def &= typ "FILENAME" &= args -- &= argPos 0 &= opt "OPTIONAL" } &= auto mode :: Hxournal mode = modes [test]
wavewave/hxournal
lib/Application/HXournal/ProgType.hs
bsd-2-clause
708
0
10
165
107
66
41
10
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Hakyll.CMS.Types ( PostSummary(..) , Post(..) , NewPost(..) , Title , Author , Tag , getSummary , Id ) where import Control.Category import Data.Aeson import Data.Aeson.TH import qualified Data.Char as Char import Data.Functor import Data.Sequences import Data.Text (Text) import Data.Time import GHC.Generics import Text.Show (Show) type Tag = Text type Author = Text type Title = Text type Id = Text data PostSummary = PostSummary { sumId :: Id , sumTitle :: Title , sumAuthor :: Author , sumTags :: [Tag] , sumDate :: UTCTime , sumTeaser :: Text } deriving (Show) $(deriveJSON defaultOptions{fieldLabelModifier = fmap Char.toLower . drop 3, constructorTagModifier = fmap Char.toLower} ''PostSummary) data Post = Post { title :: Title , author :: Author , tags :: [Tag] , content :: Text , date :: UTCTime } deriving (Generic, Show) instance ToJSON Post instance FromJSON Post data NewPost = NewPost { newTitle :: Title , newAuthor :: Author , newTags :: [Tag] , newContent :: Text } deriving (Show) $(deriveJSON defaultOptions{fieldLabelModifier = fmap Char.toLower . drop 3, constructorTagModifier = fmap Char.toLower} ''NewPost) getSummary :: Id -> Post -> PostSummary getSummary id post = PostSummary { sumId = id , sumTitle = title post , sumAuthor = author post , sumTags = tags post , sumDate = date post , sumTeaser = take 200 (content post) }
Haskell-Praxis/hakyll-cms
api/src/Hakyll/CMS/Types.hs
bsd-2-clause
1,932
0
12
672
476
282
194
64
1
{-# LANGUAGE DeriveDataTypeable #-} -- | Extra functions for working with times. Unlike the other modules in this package, there is no -- corresponding @System.Time@ module. This module enhances the functionality -- from "Data.Time.Clock", but in quite different ways. -- -- Throughout, time is measured in 'Seconds', which is a type alias for 'Double'. module System.Time.Extra( Seconds, sleep, timeout, showDuration, offsetTime, offsetTimeIncrease, duration ) where import Control.Concurrent import System.Clock import Numeric.Extra import Control.Monad.IO.Class import Control.Monad.Extra import Control.Exception.Extra import Data.Typeable import Data.Unique -- | A type alias for seconds, which are stored as 'Double'. type Seconds = Double -- | Sleep for a number of seconds. -- -- > fmap (round . fst) (duration $ sleep 1) == pure 1 sleep :: Seconds -> IO () sleep = loopM $ \s -> -- important to handle both overflow and underflow vs Int if s < 0 then pure $ Right () else if s > 2000 then do threadDelay 2000000000 -- 2000 * 1e6 pure $ Left $ s - 2000 else do threadDelay $ ceiling $ s * 1000000 pure $ Right () -- An internal type that is thrown as a dynamic exception to -- interrupt the running IO computation when the timeout has -- expired. newtype Timeout = Timeout Unique deriving (Eq,Typeable) instance Show Timeout where show _ = "<<timeout>>" instance Exception Timeout -- | A version of 'System.Timeout.timeout' that takes 'Seconds' and never -- overflows the bounds of an 'Int'. In addition, the bug that negative -- timeouts run for ever has been fixed. -- -- > timeout (-3) (print 1) == pure Nothing -- > timeout 0.1 (print 1) == fmap Just (print 1) -- > do (t, _) <- duration $ timeout 0.1 $ sleep 1000; print t; pure $ t < 1 -- > timeout 0.1 (sleep 2 >> print 1) == pure Nothing timeout :: Seconds -> IO a -> IO (Maybe a) -- Copied from GHC with a few tweaks. timeout n f | n <= 0 = pure Nothing | otherwise = do pid <- myThreadId ex <- fmap Timeout newUnique handleBool (== ex) (const $ pure Nothing) (bracket (forkIOWithUnmask $ \unmask -> unmask $ sleep n >> throwTo pid ex) killThread (\_ -> fmap Just f)) -- | Show a number of seconds, typically a duration, in a suitable manner with -- reasonable precision for a human. -- -- > showDuration 3.435 == "3.44s" -- > showDuration 623.8 == "10m24s" -- > showDuration 62003.8 == "17h13m" -- > showDuration 1e8 == "27777h47m" showDuration :: Seconds -> String showDuration x | x >= 3600 = f (x / 60) "h" "m" | x >= 60 = f x "m" "s" | otherwise = showDP 2 x ++ "s" where f x m s = show ms ++ m ++ ['0' | ss < 10] ++ show ss ++ s where (ms,ss) = round x `divMod` 60 -- | Call once to start, then call repeatedly to get the elapsed time since the first call. -- The time is guaranteed to be monotonic. This function is robust to system time changes. -- -- > do f <- offsetTime; xs <- replicateM 10 f; pure $ xs == sort xs offsetTime :: IO (IO Seconds) offsetTime = do start <- time pure $ do end <- time pure $ 1e-9 * fromIntegral (toNanoSecs $ end - start) where time = getTime Monotonic {-# DEPRECATED offsetTimeIncrease "Use 'offsetTime' instead, which is guaranteed to always increase." #-} -- | A synonym for 'offsetTime'. offsetTimeIncrease :: IO (IO Seconds) offsetTimeIncrease = offsetTime -- | Record how long a computation takes in 'Seconds'. -- -- > do (a,_) <- duration $ sleep 1; pure $ a >= 1 && a <= 1.5 duration :: MonadIO m => m a -> m (Seconds, a) duration act = do time <- liftIO offsetTime res <- act time <- liftIO time pure (time, res)
ndmitchell/extra
src/System/Time/Extra.hs
bsd-3-clause
3,852
0
16
977
740
394
346
62
3
module Hatlab.Derivatives where import Hatlab.Expression derivative :: Expression -> Expression derivative (V d) = 0 derivative X = 1 derivative (Add a b) = simplify $ (derivative a) + (derivative b) derivative (Sub a b) = simplify $ (derivative a) - (derivative b) derivative (Negate a)= simplify $ negate (derivative a) derivative (Mul a b) = simplify $ (a * (derivative b)) + ((derivative a) * b) derivative (Div a b) = simplify $ ((b * (derivative a)) - (a * (derivative b))) / (b * b) derivative (Pow f g) = simplify $ (f ** g) * (derivative g) * (log f) + ((f ** (g - 1)) * g * (derivative f)) derivative (Sin e) = simplify $ (cos e) * (derivative e) derivative (Cos e) = simplify $ negate (sin e) * derivative e derivative (Sqrt e) = simplify $ derivative (e ** 0.5) derivative (Exp e) = simplify $ Exp e * derivative e derivative (Ln e) = simplify $ (derivative e) / e derivative (Tan e) = simplify $ (derivative e) * (1 + (tan e)*(tan e)) derivative (ASin e) = simplify $ (derivative e) / (sqrt (1-e*e)) derivative (ACos e) = simplify $ (derivative e) / (-1*(sqrt (1-e*e))) derivative (ATan e) = simplify $ (derivative e) / (e*e+1) derivative (Sinh e) = simplify $ (derivative e) * (cosh e) derivative (Cosh e) = simplify $ (derivative e) * (sinh e) derivative (Tanh e) = simplify $ (derivative e) / (cosh e) derivative (ASinh e) = simplify $ (derivative e) / (sqrt (e*e+1)) derivative (ACosh e) = simplify $ (derivative e) / (sqrt (e*e-1)) derivative (ATanh e) = simplify $ (derivative e) / (1 - e*e)
DSLsofMath/Hatlab
src/Hatlab/Derivatives.hs
bsd-3-clause
1,543
0
12
313
909
463
446
26
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.OVR -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- A convenience module, combining all raw modules containing OVR extensions. -- -------------------------------------------------------------------------------- module Graphics.GL.OVR ( module Graphics.GL.OVR.Multiview ) where import Graphics.GL.OVR.Multiview
haskell-opengl/OpenGLRaw
src/Graphics/GL/OVR.hs
bsd-3-clause
555
0
5
80
37
30
7
3
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} -- | Parsing logic for the Morte language module Nordom.Parser ( -- * Parser exprFromText, -- * Errors ParseError(..), ParseMessage(..) ) where import Nordom.Core import Nordom.Lexer (Position, Token, LocatedToken(..)) import Control.Applicative hiding (Const) import Control.Exception (Exception) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Except (Except, throwE, runExceptT) import Control.Monad.Trans.State.Strict (evalState, get) import Data.Monoid import Data.Text.Buildable (Buildable(..)) import Data.Text.Lazy (Text) import Data.Text.Lazy.Builder (toLazyText) import Data.Typeable (Typeable) import Filesystem.Path.CurrentOS (FilePath) import Prelude hiding (FilePath) import Text.Earley import qualified Nordom.Lexer as Lexer import qualified Pipes.Prelude as Pipes import qualified Data.Text.Lazy as Text import qualified Data.Vector as Vector match :: Token -> Prod r Token LocatedToken Token match t = fmap Lexer.token (satisfy predicate) <?> t where predicate (LocatedToken t' _) = t == t' label :: Prod r e LocatedToken Text label = fmap unsafeFromLabel (satisfy isLabel) where isLabel (LocatedToken (Lexer.Label _) _) = True isLabel _ = False unsafeFromLabel (LocatedToken (Lexer.Label l) _) = l number :: Prod r e LocatedToken Int number = fmap unsafeFromNumber (satisfy isNumber) where isNumber (LocatedToken (Lexer.Number _) _) = True isNumber _ = False unsafeFromNumber (LocatedToken (Lexer.Number n) _) = n text :: Prod r e LocatedToken Text text = fmap unsafeFromTextLit (satisfy isTextLit) where isTextLit (LocatedToken (Lexer.TextLit _) _) = True isTextLit _ = False unsafeFromTextLit (LocatedToken (Lexer.TextLit n) _) = n char :: Prod r e LocatedToken Char char = fmap unsafeFromCharLit (satisfy isCharLit) where isCharLit (LocatedToken (Lexer.CharLit _) _) = True isCharLit _ = False unsafeFromCharLit (LocatedToken (Lexer.CharLit c) _) = c file :: Prod r e LocatedToken FilePath file = fmap unsafeFromFile (satisfy isFile) where isFile (LocatedToken (Lexer.File _) _) = True isFile _ = False unsafeFromFile (LocatedToken (Lexer.File n) _) = n url :: Prod r e LocatedToken Text url = fmap unsafeFromURL (satisfy isURL) where isURL (LocatedToken (Lexer.URL _) _) = True isURL _ = False unsafeFromURL (LocatedToken (Lexer.URL n) _) = n sepBy1 :: Alternative f => f a -> f b -> f [a] sepBy1 x sep = (:) <$> x <*> many (sep *> x) sepBy :: Alternative f => f a -> f b -> f [a] sepBy x sep = sepBy1 x sep <|> pure [] expr :: Grammar r (Prod r Token LocatedToken (Expr Path)) expr = mdo expr <- rule ( bexpr <|> Lam <$> (match Lexer.Lambda *> match Lexer.OpenParen *> label) <*> (match Lexer.Colon *> expr) <*> (match Lexer.CloseParen *> match Lexer.Arrow *> expr) <|> Pi <$> (match Lexer.Pi *> match Lexer.OpenParen *> label) <*> (match Lexer.Colon *> expr) <*> (match Lexer.CloseParen *> match Lexer.Arrow *> expr) <|> Pi "_" <$> bexpr <*> (match Lexer.Arrow *> expr) ) vexpr <- rule ( V <$> label <*> (match Lexer.At *> number) <|> V <$> label <*> pure 0 ) bexpr <- rule ( App <$> bexpr <*> aexpr <|> aexpr ) aexpr <- rule ( Var <$> vexpr <|> match Lexer.Star *> pure (Const Star) <|> match Lexer.Box *> pure (Const Box ) <|> Embed <$> embed <|> (NatLit . fromIntegral) <$> number <|> TextLit <$> text <|> CharLit <$> char <|> ListLit <$> (match Lexer.OpenList *> expr) <*> (fmap Vector.fromList (many (match Lexer.Comma *> expr)) <* match Lexer.CloseBracket) <|> PathLit <$> (match Lexer.OpenPath *> expr) <*> many ((,) <$> object <*> expr) <*> (object <* match Lexer.CloseBracket) <|> Do <$> (match Lexer.Do *> expr) <*> (match Lexer.OpenBrace *> many bind) <*> (bind <* match Lexer.CloseBrace) <|> match Lexer.Char *> pure Char <|> match Lexer.CharEq *> pure CharEq <|> match Lexer.Nat *> pure Nat <|> match Lexer.NatEq *> pure NatEq <|> match Lexer.NatFold *> pure NatFold <|> match Lexer.NatLessEq *> pure NatLessEq <|> match Lexer.NatPlus *> pure NatPlus <|> match Lexer.NatTimes *> pure NatTimes <|> match Lexer.List *> pure List <|> match Lexer.ListAppend *> pure ListAppend <|> match Lexer.ListEq *> pure ListEq <|> match Lexer.ListFold *> pure ListFold <|> match Lexer.ListHead *> pure ListHead <|> match Lexer.ListIndexed *> pure ListIndexed <|> match Lexer.ListJoin *> pure ListJoin <|> match Lexer.ListLast *> pure ListLast <|> match Lexer.ListLength *> pure ListLength <|> match Lexer.ListMap *> pure ListMap <|> match Lexer.ListReplicate *> pure ListReplicate <|> match Lexer.ListReverse *> pure ListReverse <|> match Lexer.ListSpan *> pure ListSpan <|> match Lexer.ListSplitAt *> pure ListSplitAt <|> match Lexer.Text *> pure Text <|> match Lexer.TextAppend *> pure TextAppend <|> match Lexer.TextConcatMap *> pure TextConcatMap <|> match Lexer.TextHead *> pure TextHead <|> match Lexer.TextLast *> pure TextLast <|> match Lexer.TextLength *> pure TextLength <|> match Lexer.TextMap *> pure TextMap <|> match Lexer.TextPack *> pure TextPack <|> match Lexer.TextReverse *> pure TextReverse <|> match Lexer.TextSpan *> pure TextSpan <|> match Lexer.TextSplitAt *> pure TextSplitAt <|> match Lexer.TextUnpack *> pure TextUnpack <|> match Lexer.Cmd *> pure Cmd <|> match Lexer.Path *> pure Path <|> (match Lexer.OpenParen *> expr <* match Lexer.CloseParen) ) arg <- rule ( Arg <$> (match Lexer.OpenParen *> label) <*> (match Lexer.Colon *> expr <* match Lexer.CloseParen) <|> Arg "_" <$> aexpr ) args <- rule (many arg) object <- rule (match Lexer.OpenBrace *> expr <* match Lexer.CloseBrace) bind <- rule ( (\x y z -> Bind (Arg x y) z) <$> label <*> (match Lexer.Colon *> expr) <*> (match Lexer.LArrow *> expr <* match Lexer.Semicolon) ) embed <- rule ( File <$> file <|> URL <$> url ) return expr -- | The specific parsing error data ParseMessage -- | Lexing failed, returning the remainder of the text = Lexing Text -- | Parsing failed, returning the invalid token and the expected tokens | Parsing Token [Token] deriving (Show) -- | Structured type for parsing errors data ParseError = ParseError { position :: Position , parseMessage :: ParseMessage } deriving (Typeable) instance Show ParseError where show = Text.unpack . toLazyText . build instance Exception ParseError instance Buildable ParseError where build (ParseError (Lexer.P l c) e) = "\n" <> "Line: " <> build l <> "\n" <> "Column: " <> build c <> "\n" <> "\n" <> case e of Lexing r -> "Lexing: \"" <> build remainder <> dots <> "\"\n" <> "\n" <> "Error: Lexing failed\n" where remainder = Text.takeWhile (/= '\n') (Text.take 64 r) dots = if Text.length r > 64 then "..." else mempty Parsing t ts -> "Parsing : " <> build (show t ) <> "\n" <> "Expected: " <> build (show ts) <> "\n" <> "\n" <> "Error: Parsing failed\n" runParser :: (forall r . Grammar r (Prod r Token LocatedToken a)) -> Text -> Either ParseError a runParser p text = evalState (runExceptT m) (Lexer.P 1 0) where m = do (locatedTokens, mtxt) <- lift (Pipes.toListM' (Lexer.lexExpr text)) case mtxt of Nothing -> return () Just txt -> do pos <- lift get throwE (ParseError pos (Lexing txt)) let (parses, Report _ needed found) = fullParses (parser p) locatedTokens case parses of parse:_ -> return parse [] -> do let LocatedToken t pos = case found of lt:_ -> lt _ -> LocatedToken Lexer.EOF (Lexer.P 0 0) throwE (ParseError pos (Parsing t needed)) -- | Parse an `Expr` from `Text` or return a `ParseError` if parsing fails exprFromText :: Text -> Either ParseError (Expr Path) exprFromText = runParser expr
Gabriel439/Haskell-Nordom-Library
src/Nordom/Parser.hs
bsd-3-clause
9,470
0
107
3,132
2,970
1,473
1,497
207
4
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP #-} module BuildTyCl ( buildDataCon, buildPatSyn, TcMethInfo, buildClass, distinctAbstractTyConRhs, totallyAbstractTyConRhs, mkNewTyConRhs, mkDataTyConRhs, newImplicitBinder, newTyConRepName ) where #include "HsVersions.h" import IfaceEnv import FamInstEnv( FamInstEnvs, mkNewTypeCoAxiom ) import TysWiredIn( isCTupleTyConName ) import DataCon import PatSyn import Var import VarSet import BasicTypes import Name import MkId import Class import TyCon import Type import Id import TcType import SrcLoc( noSrcSpan ) import DynFlags import TcRnMonad import UniqSupply import Util import Outputable distinctAbstractTyConRhs, totallyAbstractTyConRhs :: AlgTyConRhs distinctAbstractTyConRhs = AbstractTyCon True totallyAbstractTyConRhs = AbstractTyCon False mkDataTyConRhs :: [DataCon] -> AlgTyConRhs mkDataTyConRhs cons = DataTyCon { data_cons = cons, is_enum = not (null cons) && all is_enum_con cons -- See Note [Enumeration types] in TyCon } where is_enum_con con | (_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res) <- dataConFullSig con = null ex_tvs && null eq_spec && null theta && null arg_tys mkNewTyConRhs :: Name -> TyCon -> DataCon -> TcRnIf m n AlgTyConRhs -- ^ Monadic because it makes a Name for the coercion TyCon -- We pass the Name of the parent TyCon, as well as the TyCon itself, -- because the latter is part of a knot, whereas the former is not. mkNewTyConRhs tycon_name tycon con = do { co_tycon_name <- newImplicitBinder tycon_name mkNewTyCoOcc ; let nt_ax = mkNewTypeCoAxiom co_tycon_name tycon etad_tvs etad_roles etad_rhs ; traceIf (text "mkNewTyConRhs" <+> ppr nt_ax) ; return (NewTyCon { data_con = con, nt_rhs = rhs_ty, nt_etad_rhs = (etad_tvs, etad_rhs), nt_co = nt_ax } ) } -- Coreview looks through newtypes with a Nothing -- for nt_co, or uses explicit coercions otherwise where tvs = tyConTyVars tycon roles = tyConRoles tycon inst_con_ty = applyTys (dataConUserType con) (mkTyVarTys tvs) rhs_ty = ASSERT( isFunTy inst_con_ty ) funArgTy inst_con_ty -- Instantiate the data con with the -- type variables from the tycon -- NB: a newtype DataCon has a type that must look like -- forall tvs. <arg-ty> -> T tvs -- Note that we *can't* use dataConInstOrigArgTys here because -- the newtype arising from class Foo a => Bar a where {} -- has a single argument (Foo a) that is a *type class*, so -- dataConInstOrigArgTys returns []. etad_tvs :: [TyVar] -- Matched lazily, so that mkNewTypeCo can etad_roles :: [Role] -- return a TyCon without pulling on rhs_ty etad_rhs :: Type -- See Note [Tricky iface loop] in LoadIface (etad_tvs, etad_roles, etad_rhs) = eta_reduce (reverse tvs) (reverse roles) rhs_ty eta_reduce :: [TyVar] -- Reversed -> [Role] -- also reversed -> Type -- Rhs type -> ([TyVar], [Role], Type) -- Eta-reduced version -- (tyvars in normal order) eta_reduce (a:as) (_:rs) ty | Just (fun, arg) <- splitAppTy_maybe ty, Just tv <- getTyVar_maybe arg, tv == a, not (a `elemVarSet` tyCoVarsOfType fun) = eta_reduce as rs fun eta_reduce tvs rs ty = (reverse tvs, reverse rs, ty) ------------------------------------------------------ buildDataCon :: FamInstEnvs -> Name -> Bool -- Declared infix -> TyConRepName -> [HsSrcBang] -> Maybe [HsImplBang] -- See Note [Bangs on imported data constructors] in MkId -> [FieldLabel] -- Field labels -> [TyVar] -> [TyVar] -- Univ and ext -> [EqSpec] -- Equality spec -> ThetaType -- Does not include the "stupid theta" -- or the GADT equalities -> [Type] -> Type -- Argument and result types -> TyCon -- Rep tycon -> TcRnIf m n DataCon -- A wrapper for DataCon.mkDataCon that -- a) makes the worker Id -- b) makes the wrapper Id if necessary, including -- allocating its unique (hence monadic) buildDataCon fam_envs src_name declared_infix prom_info src_bangs impl_bangs field_lbls univ_tvs ex_tvs eq_spec ctxt arg_tys res_ty rep_tycon = do { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc ; work_name <- newImplicitBinder src_name mkDataConWorkerOcc -- This last one takes the name of the data constructor in the source -- code, which (for Haskell source anyway) will be in the DataName name -- space, and puts it into the VarName name space ; traceIf (text "buildDataCon 1" <+> ppr src_name) ; us <- newUniqueSupply ; dflags <- getDynFlags ; let stupid_ctxt = mkDataConStupidTheta rep_tycon arg_tys univ_tvs data_con = mkDataCon src_name declared_infix prom_info src_bangs field_lbls univ_tvs ex_tvs eq_spec ctxt arg_tys res_ty rep_tycon stupid_ctxt dc_wrk dc_rep dc_wrk = mkDataConWorkId work_name data_con dc_rep = initUs_ us (mkDataConRep dflags fam_envs wrap_name impl_bangs data_con) ; traceIf (text "buildDataCon 2" <+> ppr src_name) ; return data_con } -- The stupid context for a data constructor should be limited to -- the type variables mentioned in the arg_tys -- ToDo: Or functionally dependent on? -- This whole stupid theta thing is, well, stupid. mkDataConStupidTheta :: TyCon -> [Type] -> [TyVar] -> [PredType] mkDataConStupidTheta tycon arg_tys univ_tvs | null stupid_theta = [] -- The common case | otherwise = filter in_arg_tys stupid_theta where tc_subst = zipTopTCvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs) stupid_theta = substTheta tc_subst (tyConStupidTheta tycon) -- Start by instantiating the master copy of the -- stupid theta, taken from the TyCon arg_tyvars = tyCoVarsOfTypes arg_tys in_arg_tys pred = not $ isEmptyVarSet $ tyCoVarsOfType pred `intersectVarSet` arg_tyvars ------------------------------------------------------ buildPatSyn :: Name -> Bool -> (Id,Bool) -> Maybe (Id, Bool) -> ([TyVar], ThetaType) -- ^ Univ and req -> ([TyVar], ThetaType) -- ^ Ex and prov -> [Type] -- ^ Argument types -> Type -- ^ Result type -> [FieldLabel] -- ^ Field labels for -- a record pattern synonym -> PatSyn buildPatSyn src_name declared_infix matcher@(matcher_id,_) builder (univ_tvs, req_theta) (ex_tvs, prov_theta) arg_tys pat_ty field_labels = -- The assertion checks that the matcher is -- compatible with the pattern synonym ASSERT2((and [ univ_tvs `equalLength` univ_tvs1 , ex_tvs `equalLength` ex_tvs1 , pat_ty `eqType` substTyUnchecked subst pat_ty1 , prov_theta `eqTypes` substTys subst prov_theta1 , req_theta `eqTypes` substTys subst req_theta1 , arg_tys `eqTypes` substTys subst arg_tys1 ]) , (vcat [ ppr univ_tvs <+> twiddle <+> ppr univ_tvs1 , ppr ex_tvs <+> twiddle <+> ppr ex_tvs1 , ppr pat_ty <+> twiddle <+> ppr pat_ty1 , ppr prov_theta <+> twiddle <+> ppr prov_theta1 , ppr req_theta <+> twiddle <+> ppr req_theta1 , ppr arg_tys <+> twiddle <+> ppr arg_tys1])) mkPatSyn src_name declared_infix (univ_tvs, req_theta) (ex_tvs, prov_theta) arg_tys pat_ty matcher builder field_labels where ((_:_:univ_tvs1), req_theta1, tau) = tcSplitSigmaTy $ idType matcher_id ([pat_ty1, cont_sigma, _], _) = tcSplitFunTys tau (ex_tvs1, prov_theta1, cont_tau) = tcSplitSigmaTy cont_sigma (arg_tys1, _) = tcSplitFunTys cont_tau twiddle = char '~' subst = zipTopTCvSubst (univ_tvs1 ++ ex_tvs1) (mkTyVarTys (univ_tvs ++ ex_tvs)) ------------------------------------------------------ type TcMethInfo = (Name, Type, Maybe (DefMethSpec Type)) -- A temporary intermediate, to communicate between -- tcClassSigs and buildClass. buildClass :: Name -- Name of the class/tycon (they have the same Name) -> [TyVar] -> [Role] -> ThetaType -> Kind -> [FunDep TyVar] -- Functional dependencies -> [ClassATItem] -- Associated types -> [TcMethInfo] -- Method info -> ClassMinimalDef -- Minimal complete definition -> RecFlag -- Info for type constructor -> TcRnIf m n Class buildClass tycon_name tvs roles sc_theta kind fds at_items sig_stuff mindef tc_isrec = fixM $ \ rec_clas -> -- Only name generation inside loop do { traceIf (text "buildClass") ; datacon_name <- newImplicitBinder tycon_name mkClassDataConOcc ; tc_rep_name <- newTyConRepName tycon_name ; op_items <- mapM (mk_op_item rec_clas) sig_stuff -- Build the selector id and default method id -- Make selectors for the superclasses ; sc_sel_names <- mapM (newImplicitBinder tycon_name . mkSuperDictSelOcc) (takeList sc_theta [fIRST_TAG..]) ; let sc_sel_ids = [ mkDictSelId sc_name rec_clas | sc_name <- sc_sel_names] -- We number off the Dict superclass selectors, 1, 2, 3 etc so that we -- can construct names for the selectors. Thus -- class (C a, C b) => D a b where ... -- gives superclass selectors -- D_sc1, D_sc2 -- (We used to call them D_C, but now we can have two different -- superclasses both called C!) ; let use_newtype = isSingleton arg_tys -- Use a newtype if the data constructor -- (a) has exactly one value field -- i.e. exactly one operation or superclass taken together -- (b) that value is of lifted type (which they always are, because -- we box equality superclasses) -- See note [Class newtypes and equality predicates] -- We treat the dictionary superclasses as ordinary arguments. -- That means that in the case of -- class C a => D a -- we don't get a newtype with no arguments! args = sc_sel_names ++ op_names op_tys = [ty | (_,ty,_) <- sig_stuff] op_names = [op | (op,_,_) <- sig_stuff] arg_tys = sc_theta ++ op_tys rec_tycon = classTyCon rec_clas ; rep_nm <- newTyConRepName datacon_name ; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs") datacon_name False -- Not declared infix rep_nm (map (const no_bang) args) (Just (map (const HsLazy) args)) [{- No fields -}] tvs [{- no existentials -}] [{- No GADT equalities -}] [{- No theta -}] arg_tys (mkTyConApp rec_tycon (mkTyVarTys tvs)) rec_tycon ; rhs <- if use_newtype then mkNewTyConRhs tycon_name rec_tycon dict_con else if isCTupleTyConName tycon_name then return (TupleTyCon { data_con = dict_con , tup_sort = ConstraintTuple }) else return (mkDataTyConRhs [dict_con]) ; let { tycon = mkClassTyCon tycon_name kind tvs roles rhs rec_clas tc_isrec tc_rep_name -- A class can be recursive, and in the case of newtypes -- this matters. For example -- class C a where { op :: C b => a -> b -> Int } -- Because C has only one operation, it is represented by -- a newtype, and it should be a *recursive* newtype. -- [If we don't make it a recursive newtype, we'll expand the -- newtype like a synonym, but that will lead to an infinite -- type] ; result = mkClass tvs fds sc_theta sc_sel_ids at_items op_items mindef tycon } ; traceIf (text "buildClass" <+> ppr tycon) ; return result } where no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict mk_op_item :: Class -> TcMethInfo -> TcRnIf n m ClassOpItem mk_op_item rec_clas (op_name, _, dm_spec) = do { dm_info <- case dm_spec of Nothing -> return Nothing Just spec -> do { dm_name <- newImplicitBinder op_name mkDefaultMethodOcc ; return (Just (dm_name, spec)) } ; return (mkDictSelId op_name rec_clas, dm_info) } {- Note [Class newtypes and equality predicates] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class (a ~ F b) => C a b where op :: a -> b We cannot represent this by a newtype, even though it's not existential, because there are two value fields (the equality predicate and op. See Trac #2238 Moreover, class (a ~ F b) => C a b where {} Here we can't use a newtype either, even though there is only one field, because equality predicates are unboxed, and classes are boxed. -} newImplicitBinder :: Name -- Base name -> (OccName -> OccName) -- Occurrence name modifier -> TcRnIf m n Name -- Implicit name -- Called in BuildTyCl to allocate the implicit binders of type/class decls -- For source type/class decls, this is the first occurrence -- For iface ones, the LoadIface has alrady allocated a suitable name in the cache newImplicitBinder base_name mk_sys_occ | Just mod <- nameModule_maybe base_name = newGlobalBinder mod occ loc | otherwise -- When typechecking a [d| decl bracket |], -- TH generates types, classes etc with Internal names, -- so we follow suit for the implicit binders = do { uniq <- newUnique ; return (mkInternalName uniq occ loc) } where occ = mk_sys_occ (nameOccName base_name) loc = nameSrcSpan base_name -- | Make the 'TyConRepName' for this 'TyCon' newTyConRepName :: Name -> TcRnIf gbl lcl TyConRepName newTyConRepName tc_name | Just mod <- nameModule_maybe tc_name , (mod, occ) <- tyConRepModOcc mod (nameOccName tc_name) = newGlobalBinder mod occ noSrcSpan | otherwise = newImplicitBinder tc_name mkTyConRepOcc
gridaphobe/ghc
compiler/iface/BuildTyCl.hs
bsd-3-clause
16,165
0
19
5,759
2,628
1,429
1,199
223
4
----------------------------------------------------------------------------- -- | -- Module : Language.C.Analysis.TravMonad -- Copyright : (c) 2008 Benedikt Huber -- License : BSD-style -- Maintainer : [email protected] -- Stability : alpha -- Portability : ghc -- -- Monad for Traversals of the C AST. -- -- For the traversal, we maintain a symboltable and need MonadError and unique -- name generation facilities. -- Furthermore, the user may provide callbacks to handle declarations and definitions. ----------------------------------------------------------------------------- module Language.CFamily.C.TravMonad ( -- * Name generation monad MonadName(..), -- * Symbol table monad MonadSymtab(..), -- * Specialized C error-handling monad MonadCError(..), -- * AST traversal monad MonadTrav(..), -- * Handling declarations handleTagDecl, handleTagDef, handleEnumeratorDef, handleTypeDef, handleObjectDef,handleFunDef,handleVarDecl,handleParamDecl, handleAsmBlock, handleCall, -- * Symbol table scope modification enterProtoScope,leaveProtoScope, enterFuncScope,leaveFuncScope, enterBlkScope,leaveBlkScope, -- * Symbol table lookup (delegate) lookupTypeDef, lookupObject, -- * Symbol table modification createSUERef, -- * Additional error handling facilities hadHardErrors,handleTravError,throwOnLeft, astError, warn, -- * Trav - default MonadTrav implementation Trav, runTrav,runTrav_, TravState,initTravState,withExtDeclHandler,modifyUserState,userState, getUserState, TravOptions(..),modifyOptions, travErrors, -- * Language options CLanguage(..), -- * Helpers mapMaybeM,maybeM,mapSndM,concatMapM, ) where import Language.CFamily.Data.Error import Language.CFamily.Data.Ident import Language.CFamily.Data.Name import Language.CFamily.Data.Node import Language.CFamily.Data.RList as RList import Language.CFamily.C.Analysis.Builtins import Language.CFamily.C.Analysis.SemError import Language.CFamily.C.Analysis.SemRep import Language.CFamily.C.DefTable import qualified Language.CFamily.C.DefTable as ST import Language.CFamily.C.Syntax.AST import Data.IntMap (insert) import Data.Maybe import Control.Monad (liftM, ap) import Prelude hiding (lookup) class (Monad m) => MonadName m where -- | unique name generation genName :: m Name class (Monad m) => MonadSymtab m where -- symbol table handling -- | return the definition table getDefTable :: m DefTable -- | perform an action modifying the definition table withDefTable :: (DefTable -> (a, DefTable)) -> m a class (Monad m) => MonadCError m where -- error handling facilities -- | throw an 'Error' throwTravError :: Error e => e -> m a -- | catch an 'Error' (we could implement dynamically-typed catch here) catchTravError :: m a -> (CError -> m a) -> m a -- | remember that an 'Error' occurred (without throwing it) recordError :: Error e => e -> m () -- | return the list of recorded errors getErrors :: m [CError] -- | Traversal monad class (MonadName m, MonadSymtab m, MonadCError m) => MonadTrav m where -- | handling declarations and definitions handleDecl :: DeclEvent -> m () -- * handling declarations -- check wheter a redefinition is ok checkRedef :: (MonadCError m, CNode t, CNode t1) => String -> t -> (DeclarationStatus t1) -> m () checkRedef subject new_decl redecl_status = case redecl_status of NewDecl -> return () Redeclared old_def -> throwTravError $ redefinition LevelError subject DuplicateDef (nodeInfo new_decl) (nodeInfo old_def) KindMismatch old_def -> throwTravError $ redefinition LevelError subject DiffKindRedecl (nodeInfo new_decl) (nodeInfo old_def) Shadowed _old_def -> return () -- warn $ -- redefinition LevelWarn subject ShadowedDef (nodeInfo new_decl) (nodeInfo old_def) KeepDef _old_def -> return () -- | forward declaration of a tag. Only necessary for name analysis, but otherwise no semantic -- consequences. handleTagDecl :: (MonadCError m, MonadSymtab m) => TagFwdDecl -> m () handleTagDecl decl = do redecl <- withDefTable $ declareTag (sueRef decl) decl checkRedef (show $ sueRef decl) decl redecl -- | define the given composite type or enumeration -- If there is a declaration visible, overwrite it with the definition. -- Otherwise, enter a new definition in the current namespace. -- If there is already a definition present, yield an error (redeclaration). handleTagDef :: (MonadTrav m) => TagDef -> m () handleTagDef def = do redecl <- withDefTable $ defineTag (sueRef def) def checkRedef (show $ sueRef def) def redecl handleDecl (TagEvent def) handleEnumeratorDef :: (MonadCError m, MonadSymtab m) => Enumerator -> m () handleEnumeratorDef enumerator = do let ident = declIdent enumerator redecl <- withDefTable $ defineScopedIdent ident (EnumeratorDef enumerator) checkRedef (show ident) ident redecl return () handleTypeDef :: (MonadTrav m) => TypeDef -> m () handleTypeDef typeDef@(TypeDef ident _ _ _) = do redecl <- withDefTable $ defineTypeDef ident typeDef checkRedef (show ident) typeDef redecl handleDecl (TypeDefEvent typeDef) return () handleAsmBlock :: (MonadTrav m) => AsmBlock -> m () handleAsmBlock asm = handleDecl (AsmEvent asm) redefErr :: (MonadCError m, CNode old, CNode new) => Ident -> ErrorLevel -> new -> old -> RedefKind -> m () redefErr name lvl new old kind = throwTravError $ redefinition lvl (show name) kind (nodeInfo new) (nodeInfo old) -- TODO: unused {- checkIdentTyRedef :: (MonadCError m) => IdentEntry -> (DeclarationStatus IdentEntry) -> m () checkIdentTyRedef (Right decl) status = checkVarRedef decl status checkIdentTyRedef (Left tydef) (KindMismatch old_def) = redefErr (identOfTypeDef tydef) LevelError tydef old_def DiffKindRedecl checkIdentTyRedef (Left tydef) (Redeclared old_def) = redefErr (identOfTypeDef tydef) LevelError tydef old_def DuplicateDef checkIdentTyRedef (Left _tydef) _ = return () -} -- Check whether it is ok to declare a variable already in scope checkVarRedef :: (MonadCError m) => IdentDecl -> (DeclarationStatus IdentEntry) -> m () checkVarRedef def redecl = case redecl of -- always an error KindMismatch old_def -> redefVarErr old_def DiffKindRedecl -- Declaration referencing definition: -- * new entry has to be a declaration -- * old entry and new entry have to have linkage and agree on linkage -- * types have to match KeepDef (Right old_def) | not (agreeOnLinkage def old_def) -> linkageErr def old_def | otherwise -> throwOnLeft $ checkCompatibleTypes new_ty (declType old_def) -- redefinition: -- * old entry has to be a declaration or tentative definition -- * old entry and new entry have to have linkage and agree on linkage -- * types have to match Redeclared (Right old_def) | not (agreeOnLinkage def old_def) -> linkageErr def old_def | not(canBeOverwritten old_def) -> redefVarErr old_def DuplicateDef | otherwise -> throwOnLeft $ checkCompatibleTypes new_ty (declType old_def) -- NewDecl/Shadowed is ok _ -> return () where redefVarErr old_def kind = redefErr (declIdent def) LevelError def old_def kind linkageErr def' old_def = case (declLinkage def', declLinkage old_def) of (NoLinkage, _) -> redefErr (declIdent def') LevelError def' old_def NoLinkageOld _ -> redefErr (declIdent def') LevelError def' old_def DisagreeLinkage new_ty = declType def canBeOverwritten (Declaration _) = True canBeOverwritten (ObjectDef od) = isTentative od canBeOverwritten _ = False agreeOnLinkage def' old_def | declStorage old_def == FunLinkage InternalLinkage = True | not (hasLinkage $ declStorage def') || not (hasLinkage $ declStorage old_def) = False | (declLinkage def') /= (declLinkage old_def) = False | otherwise = True -- | handle variable declarations (external object declarations and function prototypes) -- variable declarations are either function prototypes, or external declarations, and not very -- interesting on their own. we only put them in the symbol table and call the handle. -- declarations never override definitions handleVarDecl :: (MonadTrav m) => Bool -> Decl -> m () handleVarDecl is_local decl = do def <- enterDecl decl (const False) handleDecl ((if is_local then LocalEvent else DeclEvent) def) -- | handle parameter declaration. The interesting part is that parameters can be abstract -- (if they are part of a type). If they have a name, we enter the name (usually in function prototype or function scope), -- checking if there are duplicate definitions. -- FIXME: I think it would be more transparent to handle parameter declarations in a special way handleParamDecl :: (MonadTrav m) => ParamDecl -> m () handleParamDecl pd@(AbstractParamDecl _ _) = handleDecl (ParamEvent pd) handleParamDecl pd@(ParamDecl vardecl node) = do let def = ObjectDef (ObjDef vardecl Nothing node) redecl <- withDefTable $ defineScopedIdent (declIdent def) def checkVarRedef def redecl handleDecl (ParamEvent pd) -- shared impl enterDecl :: (MonadCError m, MonadSymtab m) => Decl -> (IdentDecl -> Bool) -> m IdentDecl enterDecl decl cond = do let def = Declaration decl redecl <- withDefTable $ defineScopedIdentWhen cond (declIdent def) def checkVarRedef def redecl return def -- | handle function definitions handleFunDef :: (MonadTrav m) => Ident -> FunDef -> m () handleFunDef ident fun_def = do let def = FunctionDef fun_def redecl <- withDefTable $ defineScopedIdentWhen isDeclaration ident def checkVarRedef def redecl handleDecl (DeclEvent def) handleCall :: (MonadTrav m) => Ident -> Either Ident CExpr -> NodeInfo -> m () handleCall namei e ni = handleDecl (CallEvent namei e ni) isDeclaration :: IdentDecl -> Bool isDeclaration (Declaration _) = True isDeclaration _ = False checkCompatibleTypes :: Type -> Type -> Either TypeMismatch () checkCompatibleTypes _ _ = Right () -- | handle object defintions (maybe tentative) handleObjectDef :: (MonadTrav m) => Bool -> Ident -> ObjDef -> m () handleObjectDef local ident obj_def = do let def = ObjectDef obj_def redecl <- withDefTable $ defineScopedIdentWhen (\old -> shouldOverride def old) ident def checkVarRedef def redecl handleDecl ((if local then LocalEvent else DeclEvent) def) where isTentativeDef (ObjectDef object_def) = isTentative object_def isTentativeDef _ = False shouldOverride def old | isDeclaration old = True | not (isTentativeDef def) = True | isTentativeDef old = True | otherwise = False -- * scope manipulation -- -- * file scope: outside of parameter lists and blocks (outermost) -- -- * function prototype scope -- -- * function scope: labels are visible within the entire function, and declared implicitely -- -- * block scope updDefTable :: (MonadSymtab m) => (DefTable -> DefTable) -> m () updDefTable f = withDefTable (\st -> ((),f st)) enterProtoScope :: (MonadSymtab m) => m () enterProtoScope = updDefTable (ST.enterBlockScope) leaveProtoScope :: (MonadSymtab m) => m () leaveProtoScope = updDefTable (ST.leaveBlockScope) enterFuncScope :: (MonadSymtab m) => m () enterFuncScope = updDefTable (ST.enterFunctionScope) leaveFuncScope :: (MonadSymtab m) => m () leaveFuncScope = updDefTable (ST.leaveFunctionScope) enterBlkScope :: (MonadSymtab m) => m () enterBlkScope = updDefTable (ST.enterBlockScope) leaveBlkScope :: (MonadSymtab m) => m () leaveBlkScope = updDefTable (ST.leaveBlockScope) -- * Lookup -- | lookup a type definition -- the 'wrong kind of object' is an internal error here, -- because the parser should distinguish typeDefs and other -- objects lookupTypeDef :: (MonadCError m, MonadSymtab m) => Ident -> m Type lookupTypeDef ident = getDefTable >>= \symt -> case lookupIdent ident symt of Nothing -> astError (nodeInfo ident) $ "unbound typeDef: " ++ identToString ident Just (Left (TypeDef def_ident ty _ _)) -> addRef ident def_ident >> return ty Just (Right d) -> astError (nodeInfo ident) (wrongKindErrMsg d) where wrongKindErrMsg d = "wrong kind of object: expected typedef but found "++ (objKindDescr d) ++ " (for identifier `" ++ identToString ident ++ "')" -- | lookup an object, function or enumerator lookupObject :: (MonadCError m, MonadSymtab m) => Ident -> m (Maybe IdentDecl) lookupObject ident = do old_decl <- liftM (lookupIdent ident) getDefTable mapMaybeM old_decl $ \obj -> case obj of Right objdef -> addRef ident objdef >> return objdef Left _tydef -> astError (nodeInfo ident) (mismatchErr "lookupObject" "an object" "a typeDef") -- | add link between use and definition (private) addRef :: (MonadCError m, MonadSymtab m, CNode u, CNode d) => u -> d -> m () addRef use def = case (nodeInfo use, nodeInfo def) of (NodeInfo _ _ useName, NodeInfo _ _ defName) -> withDefTable (\dt -> ((), dt { refTable = insert (nameId useName) defName (refTable dt) } ) ) (_, _) -> return () -- Don't have Names for both, so can't record. mismatchErr :: String -> String -> String -> String mismatchErr ctx expect found = ctx ++ ": Expected " ++ expect ++ ", but found: " ++ found -- * inserting declarations -- | create a reference to a struct\/union\/enum -- -- This currently depends on the fact the structs are tagged with unique names. -- We could use the name generation of TravMonad as well, which might be the better -- choice when dealing with autogenerated code. createSUERef :: (MonadCError m, MonadSymtab m) => NodeInfo -> Maybe Ident -> m SUERef createSUERef _node_info (Just ident) = return$ NamedRef ident createSUERef node_info Nothing | (Just name) <- nameOfNode node_info = return $ AnonymousRef name | otherwise = astError node_info "struct/union/enum definition without unique name" -- * error handling facilities handleTravError :: (MonadCError m) => m a -> m (Maybe a) handleTravError a = liftM Just a `catchTravError` (\e -> recordError e >> return Nothing) -- | check wheter non-recoverable errors occurred hadHardErrors :: [CError] -> Bool hadHardErrors = (not . null . filter isHardError) -- | raise an error caused by a malformed AST astError :: (MonadCError m) => NodeInfo -> String -> m a astError node msg = throwTravError $ invalidAST node msg -- | raise an error based on an Either argument throwOnLeft :: (MonadCError m, Error e) => Either e a -> m a throwOnLeft (Left err) = throwTravError err throwOnLeft (Right v) = return v warn :: (Error e, MonadCError m) => e -> m () warn err = recordError (changeErrorLevel err LevelWarn) -- * The Trav datatype -- | simple traversal monad, providing user state and callbacks newtype Trav s a = Trav { unTrav :: TravState s -> Either CError (a, TravState s) } modify :: (TravState s -> TravState s) -> Trav s () modify f = Trav (\s -> Right ((),f s)) gets :: (TravState s -> a) -> Trav s a gets f = Trav (\s -> Right (f s, s)) get :: Trav s (TravState s) get = Trav (\s -> Right (s,s)) put :: TravState s -> Trav s () put s = Trav (\_ -> Right ((),s)) runTrav :: forall s a. s -> Trav s a -> Either [CError] (a, TravState s) runTrav state traversal = case unTrav action (initTravState state) of Left trav_err -> Left [trav_err] Right (v, ts) | hadHardErrors (travErrors ts) -> Left (travErrors ts) | otherwise -> Right (v,ts) where action = do withDefTable (const ((), builtins)) traversal runTrav_ :: Trav () a -> Either [CError] (a,[CError]) runTrav_ t = fmap fst . runTrav () $ do r <- t es <- getErrors return (r,es) withExtDeclHandler :: Trav s a -> (DeclEvent -> Trav s ()) -> Trav s a withExtDeclHandler action handler = do modify $ \st -> st { doHandleExtDecl = handler } action instance Functor (Trav s) where fmap = liftM instance Applicative (Trav s) where pure = return (<*>) = ap instance Monad (Trav s) where return x = Trav (\s -> Right (x,s)) m >>= k = Trav (\s -> case unTrav m s of Right (x,s1) -> unTrav (k x) s1 Left e -> Left e) instance MonadName (Trav s) where -- unique name generation genName = generateName instance MonadSymtab (Trav s) where -- symbol table handling getDefTable = gets symbolTable withDefTable f = do ts <- get let (r,symt') = f (symbolTable ts) put $ ts { symbolTable = symt' } return r instance MonadCError (Trav s) where -- error handling facilities throwTravError e = Trav (\_ -> Left (toError e)) catchTravError a handler = Trav (\s -> case unTrav a s of Left e -> unTrav (handler e) s Right r -> Right r) recordError e = modify $ \st -> st { rerrors = (rerrors st) `snoc` toError e } getErrors = gets (RList.reverse . rerrors) instance MonadTrav (Trav s) where -- handling declarations and definitions handleDecl d = ($ d) =<< gets doHandleExtDecl -- | The variety of the C language to accept. Note: this is not yet enforced. data CLanguage = C89 | C99 | GNU89 | GNU99 data TravOptions = TravOptions { language :: CLanguage } data TravState s = TravState { symbolTable :: DefTable, rerrors :: RList CError, nameGenerator :: [Name], doHandleExtDecl :: (DeclEvent -> Trav s ()), userState :: s, options :: TravOptions } travErrors :: TravState s -> [CError] travErrors = RList.reverse . rerrors initTravState :: s -> TravState s initTravState userst = TravState { symbolTable = emptyDefTable, rerrors = RList.empty, nameGenerator = newNameSupply, doHandleExtDecl = const (return ()), userState = userst, options = TravOptions { language = C99 } } -- * Trav specific operations modifyUserState :: (s -> s) -> Trav s () modifyUserState f = modify $ \ts -> ts { userState = f (userState ts) } getUserState :: Trav s s getUserState = userState `liftM` get modifyOptions :: (TravOptions -> TravOptions) -> Trav s () modifyOptions f = modify $ \ts -> ts { options = f (options ts) } generateName :: Trav s Name generateName = get >>= \ts -> do let (new_name : gen') = nameGenerator ts put $ ts { nameGenerator = gen'} return new_name -- * helpers mapMaybeM :: (Monad m) => (Maybe a) -> (a -> m b) -> m (Maybe b) mapMaybeM m f = maybe (return Nothing) (liftM Just . f) m maybeM :: (Monad m) => (Maybe a) -> (a -> m ()) -> m () maybeM m f = maybe (return ()) f m mapSndM :: (Monad m) => (b -> m c) -> (a,b) -> m (a,c) mapSndM f (a,b) = liftM ((,) a) (f b) concatMapM :: (Monad m) => (a -> m [b]) -> [a] -> m [b] concatMapM f = liftM concat . mapM f
micknelso/language-c
src/Language/CFamily/C/TravMonad.hs
bsd-3-clause
19,676
0
16
4,659
5,336
2,768
2,568
-1
-1
module ArtGallery ( ) where
adarqui/ArtGallery
Haskell/src/ArtGallery.hs
bsd-3-clause
28
0
3
5
7
5
2
1
0
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module TestUnits (tests) where import Control.Applicative (liftA) import Data.Vector.Unboxed as V import Data.Vector.Storable as S import Prelude as P import Test.Framework import Test.Framework.TH import Test.QuickCheck import Test.Framework.Providers.QuickCheck2 import SIGyM.Units as U tests :: Test.Framework.Test tests = $(testGroupGenerator) instance Arbitrary (Length Double) where arbitrary = liftA (*~ meter) arbitrary prop_can_operate_on_quantity_unboxed_vectors :: Length Double -> [Length Double] -> Bool prop_can_operate_on_quantity_unboxed_vectors v vs = (V.toList . V.map fn . V.fromList) vs == P.map fn vs where fn :: Length Double -> Area Double fn = (U.*) v prop_can_operate_on_quantity_storable_vectors :: Length Double -> [Length Double] -> Bool prop_can_operate_on_quantity_storable_vectors v vs = (S.toList . S.map fn . S.fromList) vs == P.map fn vs where fn :: Length Double -> Area Double fn = (U.*) v
meteogrid/sigym-core
tests/TestUnits.hs
bsd-3-clause
1,127
0
11
193
309
171
138
32
1
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators, BangPatterns #-} module Blaze.Show ( BlazeShow(..), showBS, showLBS, ) where import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Char.Utf8 import Blaze.Text.Double import Blaze.Text.Int import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.List import Data.Monoid import GHC.Generics class BlazeShow a where bshow :: a -> Builder default bshow :: (Generic a, GBlazeShow (Rep a)) => a -> Builder bshow = gbshow undefined . from {-# INLINE bshow #-} showBS :: BlazeShow a => a -> S.ByteString showBS = toByteString . bshow {-# INLINE showBS #-} showLBS :: BlazeShow a => a -> L.ByteString showLBS = toLazyByteString . bshow {-# INLINE showLBS #-} class GBlazeShow f where gbshow :: (Builder -> Builder -> Builder) -> f a -> Builder isNull :: f a -> Bool isNull _ = False {-# INLINE isNull #-} instance GBlazeShow U1 where gbshow _ U1 = mempty {-# INLINE gbshow #-} isNull _ = True {-# INLINE isNull #-} instance (BlazeShow a) => GBlazeShow (K1 i a) where gbshow _ (K1 x) = bshow x {-# INLINE gbshow #-} instance (GBlazeShow a, GBlazeShow b) => GBlazeShow (a :+: b) where gbshow f (L1 x) = gbshow f x gbshow f (R1 x) = gbshow f x {-# INLINE gbshow #-} instance (GBlazeShow a, GBlazeShow b) => GBlazeShow (a :*: b) where gbshow f (x :*: y) = f (gbshow f x) (gbshow f y) {-# INLINE gbshow #-} -- for 'C'onstructors instance (GBlazeShow a, Constructor c) => GBlazeShow (M1 C c a) where gbshow _ c@(M1 x) | conIsRecord c = fromString cname <> fromString " {" <> gbshow (\a b -> a <> fromString ", " <> b) x <> fromChar '}' | conIsTuple = fromChar '(' <> gbshow (\a b -> a <> fromChar ',' <> b) x <> fromChar ')' | conFixity c == Prefix = fromString cname <> (if isNull x then mempty else fromChar ' ' <> gbshow (\a b -> a <> fromChar ' ' <> b) x) | otherwise = undefined -- FIXME: implement Infix where cname = conName c conIsTuple = case cname of ('(': ',': _) -> True _ -> False -- for record 'S'electors instance (GBlazeShow a, Selector s) => GBlazeShow (M1 S s a) where gbshow f s@(M1 x) | null sname = gbshow f x | otherwise = fromString (selName s) <> fromString " = " <> gbshow f x where sname = selName s {-# INLINE gbshow #-} -- for 'D'ata types instance (GBlazeShow a) => GBlazeShow (M1 D c a) where -- just ignore it gbshow f (M1 x) = gbshow f x {-# INLINE gbshow #-} -- instances for basic generic types instance BlazeShow Bool instance BlazeShow Char where bshow = fromChar instance BlazeShow Double where bshow = double instance BlazeShow Float where bshow = float instance BlazeShow Int where bshow = integral instance BlazeShow Ordering instance BlazeShow () instance BlazeShow a => BlazeShow [a] where bshow l = fromChar '[' <> mconcat (intersperse (fromChar ',') $ map bshow l) <> fromChar ']' {-# INLINE bshow #-} instance BlazeShow a => BlazeShow (Maybe a) instance (BlazeShow a, BlazeShow b) => BlazeShow (Either a b) instance (BlazeShow a, BlazeShow b) => BlazeShow (a, b) instance (BlazeShow a, BlazeShow b, BlazeShow c) => BlazeShow (a, b, c) instance (BlazeShow a, BlazeShow b, BlazeShow c, BlazeShow d) => BlazeShow (a, b, c, d) instance (BlazeShow a, BlazeShow b, BlazeShow c, BlazeShow d, BlazeShow e) => BlazeShow (a, b, c, d, e) instance (BlazeShow a, BlazeShow b, BlazeShow c, BlazeShow d, BlazeShow e, BlazeShow f) => BlazeShow (a, b, c, d, e, f) instance (BlazeShow a, BlazeShow b, BlazeShow c, BlazeShow d, BlazeShow e, BlazeShow f, BlazeShow g) => BlazeShow (a, b, c, d, e, f, g)
tanakh/blaze-show
Blaze/Show.hs
bsd-3-clause
4,004
0
16
1,004
1,415
742
673
101
1
module Zero.Account.Verification.Model ( insertVerificationCode , enableRecoveryMethod ) where import qualified Data.Vector as V import Zero.Persistence import Zero.Crypto (generateUUID) import Zero.Account.Verification.Internal (VerificationCode) import Zero.Account.Verification.Relations ------------------------------------------------------------------------------ -- Model ------------------------------------------------------------------------------ -- | Creates a new verification code. insertVerificationCode :: SessionId -> Connection -> Text -> VerificationCode -> IO () insertVerificationCode sid conn email code = do let verificationAttributes' = attributesFromList (V.toList verificationAttributes) let verificationTuples = mkTupleSetFromList verificationAttributes' [ [ TextAtom email , BoolAtom False , TextAtom code ] ] case verificationTuples of Right tuples -> do eRes <- executeDatabaseContextExpr sid conn (Insert "verification" $ MakeStaticRelation verificationAttributes' tuples) case eRes of Left err -> error $ show err Right _ -> return () Left err -> error $ show err -- | Updates the status of a recovery method to verified = True. enableRecoveryMethod :: SessionId -> Connection -> Text -> IO () enableRecoveryMethod sid conn email = do putStrLn "Enabling recovery method" let expr = updateVerificationStatus email eRes <- executeDatabaseContextExpr sid conn expr case eRes of Left err -> error $ show err Right _ -> return ()
et4te/zero
server/src/Zero/Account/Verification/Model.hs
bsd-3-clause
1,648
0
16
366
359
179
180
37
3
{-# LANGUAGE OverloadedStrings #-} module Main where import Annah.Core (Data(..), Expr(..), Type(..)) import Control.Applicative ((<|>)) import Control.Exception (Exception, throwIO) import Control.Monad (forM_) import Data.Monoid ((<>),mempty) import Data.Text.Lazy (fromStrict) import Filesystem.Path (FilePath, (</>)) import Morte.Core (Path(..), Var(..)) import Options.Applicative import Prelude hiding (FilePath) import System.IO (stderr) import qualified Annah.Core as Annah import qualified Annah.Parser as Annah import qualified Data.Text.Lazy as Text import qualified Data.Text.Lazy.IO as Text import qualified Filesystem import qualified Filesystem.Path.CurrentOS as Filesystem import qualified Morte.Core as Morte import qualified Morte.Import as Morte throws :: Exception e => Either e a -> IO a throws (Left e) = throwIO e throws (Right r) = return r data Mode = Default | Compile FilePath | Desugar | Types parser :: Parser Mode parser = subparser ( command "compile" (info (helper <*> (Compile <$> parseFilePath)) ( fullDesc <> header "annah compile - Compile Annah code" <> progDesc "Compile an Annah program located at the given \ \file path. Prefer this subcommand over reading \ \from standard input when you want remote \ \references to be resolved relative to that \ \file's path" ) ) <> metavar "compile" ) <|> subparser ( command "desugar" (info (helper <*> pure Desugar) ( fullDesc <> header "annah desugar - Desugar Annah code" <> progDesc "Desugar an Annah program to the equivalent Morte \ \program, reading the Annah program from standard \ \input and writing the Morte program to standard \ \output." ) ) <> metavar "desugar" ) <|> subparser ( command "types" ( info (helper <*> pure Types) ( fullDesc <> header "annah types - Compile an Annah datatype definition" <> progDesc "Translate an Annah datatype definition to the \ \equivalent set of files, reading the datatype \ \definition from standard input. This creates \ \one output directory for each type with one file \ \underneath each directory per data constructor \ \associated with that type." ) ) <> metavar "types" ) <|> pure Default where parseFilePath = fmap Filesystem.decodeString (strArgument (metavar "FILEPATH" <> help "Path to file to compile")) main :: IO () main = do mode <- execParser $ info (helper <*> parser) ( fullDesc <> header "annah - A strongly typed, purely functional language" <> progDesc "Annah is a medium-level language that is a superset of \ \Morte. Use this compiler to desugar Annah code to Morte \ \code." ) case mode of Default -> do txt <- Text.getContents ae <- throws (Annah.exprFromText txt) let me = Annah.desugar ae -- Only statically link the Morte expression for type-checking me' <- Morte.load Nothing me mt <- throws (Morte.typeOf me') -- Return the dynamically linked Morte expression Text.putStrLn (Morte.pretty (Morte.normalize me)) Compile file -> do txt <- Text.readFile (Filesystem.encodeString file) ae <- throws (Annah.exprFromText txt) let me = Annah.desugar ae -- Only statically link the Morte expression for type-checking me' <- Morte.load (Just (File file)) me mt <- throws (Morte.typeOf me') -- Return the dynamically linked Morte expression Text.putStrLn (Morte.pretty (Morte.normalize me)) Desugar -> do txt <- Text.getContents ae <- throws (Annah.exprFromText txt) Text.putStrLn (Morte.pretty (Annah.desugar ae)) Types -> do -- TODO: Handle duplicate type and data constructor names txt <- Text.getContents ts <- throws (Annah.typesFromText txt) let write file txt = Filesystem.writeTextFile file (Text.toStrict txt <> "\n") let named = Filesystem.fromText . Text.toStrict forM_ ts (\t -> do let typeDir = named (typeName t) let typeAnnahFile = named (typeName t <> ".annah") let typeMorteFile = typeDir </> "@" let foldAnnahFile = typeDir </> named (typeFold t <> ".annah") let foldMorteFile = typeDir </> named (typeFold t) Filesystem.createDirectory True typeDir write typeAnnahFile (txt <> "in " <> typeName t) let e0 = Family ts (Var (V (typeName t) 0)) let typeTxt = Morte.pretty (Morte.normalize (Annah.desugar e0)) write typeMorteFile typeTxt if typeFold t /= "_" then do write foldAnnahFile (txt <> "in " <> typeFold t) let e1 = Family ts (Var (V (typeFold t) 0)) let foldTxt = Morte.pretty (Morte.normalize (Annah.desugar e1)) write foldMorteFile foldTxt else return () forM_ (typeDatas t) (\d -> do let dataAnnahName = named (dataName d <> ".annah") let dataMorteName = named (dataName d) let dataAnnahFile = typeDir </> dataAnnahName let dataMorteFile = typeDir </> dataMorteName write dataAnnahFile (txt <> "in " <> dataName d) let e2 = Family ts (Var (V (dataName d) 0)) let dataTxt = Morte.pretty (Morte.normalize (Annah.desugar e2)) write dataMorteFile dataTxt ) )
Gabriel439/Haskell-Annah-Library
exec/Main.hs
bsd-3-clause
6,572
0
31
2,556
1,477
738
739
112
5
{-# LANGUAGE OverloadedStrings #-} module Block.Parse ( Block (Block) , parseBlocks ) where import Data.Attoparsec.ByteString (takeTill, skipWhile) import Data.Attoparsec.ByteString.Char8 hiding (takeTill, skipWhile, parse, eitherResult) import Data.Attoparsec.ByteString.Lazy (parse, eitherResult) import qualified Data.ByteString.Lazy as L (ByteString) import Data.ByteString.Char8 (ByteString, unpack) data Block = Block String String [(String, String)] deriving Show parseBlocks :: L.ByteString -> Either String [Block] parseBlocks = eitherResult . parse ((many' parseBlock) <* endOfInput) parseBlock :: Parser Block parseBlock = do name <- parseAttrWithKey "NAME" type_ <- parseAttrWithKey "TYPE" attrs <- manyTill parseAttr (string "END") _ <- endOfLine return (Block (unpack name) (unpack type_) (map (\ (a, b) -> (unpack a, unpack b)) attrs)) parseAttr :: Parser (ByteString, ByteString) parseAttr = do key <- delim *> takeTill isHorizontalSpace <* delim _ <- char '=' value <- delim *> takeTill isEndOfLine <* endOfLine return (key, value) parseAttrWithKey :: ByteString -> Parser ByteString parseAttrWithKey key = delim *> string key *> delim *> char '=' *> delim *> takeTill isEndOfLine <* endOfLine delim :: Parser () delim = skipWhile isHorizontalSpace
hectorhon/autotrace2
src/Block/Parse.hs
bsd-3-clause
1,392
0
15
294
435
233
202
36
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} -- |Permanently register and retrieve absolute type definitions module Network.Top.Repo ( RepoProtocol(..) , recordType , recordADTs , solveType , solveRefs , knownTypes ) where import Control.Monad import Data.Either.Extra (lefts) import Data.List (nub) import qualified Data.Map as M import Network.Top.Run import Network.Top.Types import Network.Top.Util import Repo.Types import ZM {-| A (simplistic) protocol to permanently store and retrieve ADT definitions. -} data RepoProtocol = Record AbsADT -- ^Permanently record an absolute type | Solve AbsRef -- ^Retrieve the absolute type | Solved AbsRef AbsADT -- ^Return the absolute type identified by an absolute reference | AskDataTypes -- ^Request the list of all known data types | KnownDataTypes [(AbsRef, AbsADT)] -- ^Return the list of all known data types deriving (Eq, Ord, Show, Generic, Flat, Model) --instance Flat [(AbsRef,AbsADT)] type RefSolver = AbsRef -> IO (Either RepoError AbsADT) -- type TypeSolver = AbsType -> IO (Either RepoError AbsTypeModel) type RepoError = String -- SomeException -- |Permanently record all the ADT definitions referred by a type, with all their dependencies recordType :: Model a => Config -> Proxy a -> IO () recordType cfg proxy = recordADTs cfg $ absADTs $ proxy -- |Permanently record a set of ADT definitions with all their dependencies recordADTs :: Foldable t => Config -> t AbsADT -> IO () recordADTs cfg adts = runApp cfg ByType $ \conn -> mapM_ (output conn . Record) adts -- |Retrieve all known data types knownTypes :: Config -> IO (Either String [(AbsRef, AbsADT)]) knownTypes cfg = runApp cfg ByType $ \conn -> do output conn AskDataTypes let loop = do msg <- input conn case msg of KnownDataTypes ts -> return ts _ -> loop withTimeout 30 loop -- |Retrieve the full type model for the given absolute type -- from Top's RepoProtocol channel, using the given Repo as a cache solveType :: Repo -> Config -> AbsType -> IO (Either RepoError AbsTypeModel) solveType repo cfg t = ((TypeModel t) <$>) <$> solveRefs repo cfg (references t) -- |Solve ADT references recursively, returning all dependencies. solveRefs :: Repo -> Config -> [AbsRef] -> IO (Either RepoError (M.Map AbsRef AbsADT)) solveRefs repo cfg refs = runApp cfg ByType $ \conn -> (solveRefsRec repo (resolveRef__ conn)) refs where solveRefsRec :: Repo -> RefSolver -> [AbsRef] -> IO (Either RepoError (M.Map AbsRef AbsADT)) solveRefsRec _ _ [] = return $ Right M.empty solveRefsRec repo solver refs = do er <- allErrs <$> mapM (solveRef repo solver) refs case er of Left err -> return $ Left err Right ros -> (M.union (M.fromList ros) <$>) <$> solveRefsRec repo solver (concatMap (innerReferences . snd) ros) allErrs :: [Either String r] -> Either String [r] allErrs rs = let errs = lefts rs in if null errs then sequence rs else Left (unlines errs) solveRef :: Repo -> RefSolver -> AbsRef -> IO (Either RepoError (AbsRef,AbsADT)) solveRef repo solver ref = ((ref,) <$> )<$> do rr <- get repo ref case rr of Nothing -> solver ref >>= mapM (\o -> put repo o >> return o) Just o -> return $ Right o resolveRef :: Config -> AbsRef -> IO (Either String AbsADT) resolveRef cfg ref = checked $ resolveRef_ cfg ref resolveRef_ :: Config -> AbsRef -> IO (Either String AbsADT) resolveRef_ cfg ref = runApp cfg ByType (flip resolveRef__ ref) resolveRef__ :: Connection RepoProtocol -> AbsRef -> IO (Either String AbsADT) resolveRef__ conn ref = checked $ resolveRef___ conn ref resolveRef___ :: Connection RepoProtocol -> AbsRef -> IO (Either String AbsADT) resolveRef___ conn ref = do output conn (Solve ref) let loop = do msg <- input conn case msg of -- Solved t r | t == typ -> return $ (\e -> AbsoluteType (M.fromList e) typ) <$> r Solved sref sadt | ref == sref && absRef sadt == sref -> return $ Right sadt _ -> loop join <$> withTimeout 25 loop absADTs :: Model a => Proxy a -> [AbsADT] absADTs = typeADTs . absTypeModel checked :: NFData b => IO (Either String b) -> IO (Either String b) checked f = either (Left . show) id <$> strictTry f
tittoassini/top
src/Network/Top/Repo.hs
bsd-3-clause
4,850
0
20
1,300
1,329
677
652
86
5
-- | -- Module: Main -- Copyright: (c) 2013 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <[email protected]> -- -- Benchmark for the pipes-bytestring package. module Main where import Criterion.Main main :: IO () main = defaultMain []
ertes/pipes-bytestring
test/Bench.hs
bsd-3-clause
266
0
6
51
36
23
13
4
1
module FruitShopKata.Day7 (process) where type Bill = (Money, [Product]) type Product = String type Money = Int process :: [Product] -> [Money] process = map fst . tail . scanl addProduct (0, []) where addProduct :: Bill -> Product -> Bill addProduct (total, products) product = (total + findPrice product - discount product, product:products) where findPrice :: Product -> Money findPrice p | p == "Pommes" = 100 | p == "Cerises" = 75 | p == "Bananes" = 150 discount :: Product -> Money discount p = case lookup p specials of Just (discount, m) -> ((applyDiscount discount) . (==0). (`mod` m) . length . filter ((==) p)) (p:products) Nothing -> 0 applyDiscount :: Money -> Bool -> Money applyDiscount discount True = discount applyDiscount _ _ = 0 specials = [("Cerises", (20, 2)), ("Bananes", (150, 2))]
Alex-Diez/haskell-tdd-kata
old-katas/src/FruitShopKata/Day7.hs
bsd-3-clause
1,196
0
19
528
363
200
163
21
3
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} import Hcalc default (Cell') t1 :: Sheet t1 = Sheet [ hcol ":: What?" [ "ab-lippu" , "Wombats kalja" , "Sushi" , "8mm tequila" , "Yesterday" , "Taxi" , "Aamiainen" , "Pumpattava octo" , "Sampe maksaa" ] , hcol ":: Matti-Sampe" $ map cellDouble [ 2.1 , -2.8 , 9 , -2 , 2.8 , -4.5 , 11.5 , -7.5 ] ++ [cellFormula (FDiv (FSum (CR 1 1) (CR 1 8)) (Fnum 2))] ] t2 :: Sheet t2 = Sheet [ colInsAt 9 ":: TOT" (colAt 0 t1) >< "/4" , f 1 $ hcol ":: Matti" [ cellDouble 2 ] , f 2 $ hcol ":: Sampe" [ Cell' CellEmpty, cellDouble 2 ] , f 3 $ hcol ":: Joku" [] , f 4 $ hcol ":: Muu" [] , colInsAt 9 (cellFormula (FSum (CR 1 9) (CR 4 9)) ) ColEmpty >< cellFormula (FDiv (FSum (CR 1 9) (CR 4 9)) (Fnum 4)) ] t4 :: Sheet t4 = eachCol t2 g where g 0 col = col >< "maksettavaa" g 5 col = col g n col = colInsAt 11 (cellFormula (FSub (CR 5 10) (CR n 9))) col -- * ui -- | subst. col 9 with a sum f :: Int -> Col -> Col f n = colInsAt 9 (cellFormula $ FSum (CR n 1) (CR n 8)) main :: IO () main = do printWithTitle t1 "verirahat 1/4" printWithTitle t2 "verirahat 2,3/4" printWithTitle t4 "verirahat 4/4"
SimSaladin/hcalc
examples/verirahat.hs
bsd-3-clause
1,561
0
15
630
540
277
263
47
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} module Control.Eff.Writer where import Control.Eff import Data.Monoid data Writer w x where Tell :: w -> Writer w () tell :: (Writer w :< effs) => w -> Eff effs () tell w = eta (Tell w) runWriter :: Monoid w => Eff (Writer w ': effs) a -> Eff effs (a, w) runWriter = eliminate (\a -> pure (a, mempty)) (\(Tell w) k -> (\(a,w') -> (a, w <> w')) <$> k ()) runWriterWith :: (w -> Eff effs ()) -> Eff (Writer w ': effs) a -> Eff effs a runWriterWith f = eliminate pure (\(Tell w) k -> f w >> k ()) execWriter :: Monoid w => Eff (Writer w ': effs) a -> Eff effs w execWriter = fmap snd . runWriter
mitchellwrosen/effects-a-la-carte
src/Control/Eff/Writer.hs
bsd-3-clause
764
0
12
199
350
184
166
26
1