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
module Miscellaneous.A275673Spec (main, spec) where import Test.Hspec import Miscellaneous.A275673 (a275673) main :: IO () main = hspec spec spec :: Spec spec = describe "A275673" $ it "correctly computes the first 20 elements" $ take 20 (map a275673 [1..]) `shouldBe` expectedValue where expectedValue = [1,2,3,4,5,6,7,9,11,13,15,17,19,22,25,28,31,34,37,41]
peterokagey/haskellOEIS
test/Miscellaneous/A275673Spec.hs
apache-2.0
373
0
10
59
160
95
65
10
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QStyleOptionSpinBox.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QStyleOptionSpinBox ( QStyleOptionSpinBoxStyleOptionType , QStyleOptionSpinBoxStyleOptionVersion ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CQStyleOptionSpinBoxStyleOptionType a = CQStyleOptionSpinBoxStyleOptionType a type QStyleOptionSpinBoxStyleOptionType = QEnum(CQStyleOptionSpinBoxStyleOptionType Int) ieQStyleOptionSpinBoxStyleOptionType :: Int -> QStyleOptionSpinBoxStyleOptionType ieQStyleOptionSpinBoxStyleOptionType x = QEnum (CQStyleOptionSpinBoxStyleOptionType x) instance QEnumC (CQStyleOptionSpinBoxStyleOptionType Int) where qEnum_toInt (QEnum (CQStyleOptionSpinBoxStyleOptionType x)) = x qEnum_fromInt x = QEnum (CQStyleOptionSpinBoxStyleOptionType x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QStyleOptionSpinBoxStyleOptionType -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeType QStyleOptionSpinBoxStyleOptionType where eType = ieQStyleOptionSpinBoxStyleOptionType $ 983042 data CQStyleOptionSpinBoxStyleOptionVersion a = CQStyleOptionSpinBoxStyleOptionVersion a type QStyleOptionSpinBoxStyleOptionVersion = QEnum(CQStyleOptionSpinBoxStyleOptionVersion Int) ieQStyleOptionSpinBoxStyleOptionVersion :: Int -> QStyleOptionSpinBoxStyleOptionVersion ieQStyleOptionSpinBoxStyleOptionVersion x = QEnum (CQStyleOptionSpinBoxStyleOptionVersion x) instance QEnumC (CQStyleOptionSpinBoxStyleOptionVersion Int) where qEnum_toInt (QEnum (CQStyleOptionSpinBoxStyleOptionVersion x)) = x qEnum_fromInt x = QEnum (CQStyleOptionSpinBoxStyleOptionVersion x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QStyleOptionSpinBoxStyleOptionVersion -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeVersion QStyleOptionSpinBoxStyleOptionVersion where eVersion = ieQStyleOptionSpinBoxStyleOptionVersion $ 1
keera-studios/hsQt
Qtc/Enums/Gui/QStyleOptionSpinBox.hs
bsd-2-clause
4,673
0
18
921
1,080
532
548
90
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleInstances #-} module Servant.Common.Req where #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Exception import Control.Monad import Control.Monad.Catch (MonadThrow) import Control.Monad.IO.Class import Control.Monad.Trans.Either import Data.ByteString.Lazy hiding (pack, filter, map, null, elem, unpack) import Data.ByteString.Char8 (unpack, pack) import qualified Data.ByteString as BS import Data.IORef import Data.String import Data.String.Conversions import Data.Proxy import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding import Data.Typeable import Data.Primitive.ByteArray import Data.Primitive.Addr import Data.ByteString.Unsafe (unsafePackAddressLen) import Network.HTTP.Media import Network.HTTP.Types import qualified Network.HTTP.Types.Header as HTTP import Network.URI import Servant.API.ContentTypes import Servant.Common.BaseUrl import Servant.Common.Text import System.IO.Unsafe import GHCJS.Foreign (jsTrue) import GHCJS.Foreign.Callback (Callback (..) , OnBlocked(..) , syncCallback) import Data.JSString (JSString) import qualified Data.JSString as JSString import GHCJS.Marshal import GHCJS.Prim --hiding (fromJSString, toJSString) import Control.Concurrent.MVar import Data.List.Split import Data.Maybe import Data.CaseInsensitive import Data.Char import Unsafe.Coerce data ServantError = FailureResponse { responseStatus :: Status , responseContentType :: MediaType } | DecodeFailure { decodeError :: String , responseContentType :: MediaType , responseBody :: ByteString } | UnsupportedContentType { responseContentType :: MediaType , responseBody :: ByteString } | InvalidContentTypeHeader { responseContentTypeHeader :: ByteString , responseBody :: ByteString } deriving (Show, Typeable) instance Exception ServantError data ForeignRetention = NeverRetain -- ^ do not retain data unless the callback is directly -- referenced by a Haskell thread. | AlwaysRetain -- ^ retain references indefinitely, until `freeCallback` -- is called (the callback will be kept in memory until it's freed) | DomRetain JSVal -- ^ retain data as long as the `JSVal` is a DOM element in -- `window.document` or in a DOM tree referenced by a Haskell -- thread. data Req = Req { reqPath :: String , qs :: QueryText , reqBody :: Maybe (ByteString, MediaType) , reqAccept :: [MediaType] , headers :: [(String, Text)] } defReq :: Req defReq = Req "" [] Nothing [] [] appendToPath :: String -> Req -> Req appendToPath p req = req { reqPath = reqPath req ++ "/" ++ p } appendToMatrixParams :: String -> Maybe String -> Req -> Req appendToMatrixParams pname pvalue req = req { reqPath = reqPath req ++ ";" ++ pname ++ maybe "" ("=" ++) pvalue } appendToQueryString :: Text -- ^ param name -> Maybe Text -- ^ param value -> Req -> Req appendToQueryString pname pvalue req = req { qs = qs req ++ [(pname, pvalue)] } addHeader :: ToText a => String -> a -> Req -> Req addHeader name val req = req { headers = headers req ++ [(name, toText val)] } setRQBody :: ByteString -> MediaType -> Req -> Req setRQBody b t req = req { reqBody = Just (b, t) } displayHttpRequest :: Method -> String displayHttpRequest httpmethod = "HTTP " ++ cs httpmethod ++ " request" performRequest :: Method -> Req -> (Int -> Bool) -> Maybe BaseUrl -> EitherT ServantError IO ( Int, ByteString, MediaType , [HTTP.Header]) performRequest reqMethod req isWantedStatus reqHost = do eResp <- liftIO $ makeRequest reqMethod req isWantedStatus reqHost case eResp of (Left err) -> left err (Right (status_code, hrds, body)) -> do ct <- case lookup "Content-Type" hrds of Nothing -> pure $ "application"//"octet-stream" Just t -> case parseAccept t of Nothing -> left $ InvalidContentTypeHeader (cs t) $ fromStrict body Just t' -> pure t' return (status_code, fromStrict body, ct, hrds) performRequestCT :: MimeUnrender ct result => Proxy ct -> Method -> Req -> [Int] -> Maybe BaseUrl -> EitherT ServantError IO ([HTTP.Header], result) performRequestCT ct reqMethod req wantedStatus reqHost = do let acceptCT = contentType ct (_status, respBody, respCT, hrds) <- performRequest reqMethod (req { reqAccept = [acceptCT] }) (`elem` wantedStatus) reqHost unless (matches respCT (acceptCT)) $ left $ UnsupportedContentType respCT respBody case mimeUnrender ct respBody of Left err -> left $ DecodeFailure err respCT respBody Right val -> return (hrds, val) performRequestNoBody :: Method -> Req -> [Int] -> Maybe BaseUrl -> EitherT ServantError IO () performRequestNoBody reqMethod req wantedStatus reqHost = do _ <- performRequest reqMethod req (`elem` wantedStatus) reqHost return () --data XMLHttpRequest -- foreign import javascript unsafe "new XMLHttpRequest()" -- jsXhrRequest :: IO JSRef -- foreign import javascript unsafe "new XMLHttpRequest()" -- jsXhrRequestString :: IO JSString -- foreign import javascript unsafe "$1.open($2, $3, $4)" -- jsXhrOpen :: JSRef -> JSRef -> JSRef -> JSRef -> IO () -- foreign import javascript unsafe "$1.send()" -- jsXhrSend :: JSRef -> IO () -- foreign import javascript unsafe "$1.send($2)" -- jsXhrSendWith :: JSRef -> JSRef -> IO () -- foreign import javascript unsafe "$1.onreadystatechange = $2" -- jsXhrOnReadyStateChange:: JSRef -> Callback (IO ()) -> IO () -- foreign import javascript unsafe "$1.readyState" -- jsXhrReadyState:: JSRef -> IO JSRef -- foreign import javascript unsafe "$1.responseText" -- jsXhrResponseText:: JSRef -> IO JSString -- foreign import javascript unsafe "$1.response" -- jsXhrResponse:: JSRef -> IO JSRef -- foreign import javascript unsafe "$1.responseType = $2" -- jsXhrResponseType:: JSRef -> JSString -> IO () -- foreign import javascript unsafe "$1.status" -- jsXhrStatus:: JSRef -> IO JSRef -- foreign import javascript unsafe "$1.getAllResponseHeaders()" -- jsXhrResponseHeaders :: JSString -> IO JSRef -- foreign import javascript unsafe "$1.setRequestHeader($2, $3)" -- jsXhrSetRequestHeader :: JSRef -> JSString -> JSString -> IO () -- foreign import javascript unsafe "$1.statusText" -- jsXhrGetStatusText :: JSRef -> IO JSString -- foreign import javascript unsafe "xh = $1" -- jsDebugXhr :: JSRef -> IO () foreign import javascript unsafe "new XMLHttpRequest()" jsXhrRequest :: IO JSVal foreign import javascript unsafe "$1.open($2, $3, $4)" jsXhrOpen :: JSVal -> JSString -> JSString -> JSVal -> IO () foreign import javascript unsafe "$1.send()" jsXhrSend :: JSVal -> IO () foreign import javascript unsafe "$1.send($2)" jsXhrSendWith :: JSVal -> JSVal -> IO () foreign import javascript unsafe "$1.onreadystatechange = $2" jsXhrOnReadyStateChange:: JSVal -> Callback (IO ()) -> IO () foreign import javascript unsafe "$1.readyState" jsXhrReadyState:: JSVal -> IO JSVal foreign import javascript unsafe "$1.responseText" jsXhrResponseText:: JSVal -> IO JSString foreign import javascript unsafe "$1.response" jsXhrResponse:: JSVal -> IO JSVal foreign import javascript unsafe "$1.responseType = $2" jsXhrResponseType:: JSVal -> JSString -> IO () foreign import javascript unsafe "$1.status" jsXhrStatus:: JSVal -> IO JSVal foreign import javascript unsafe "$1.getAllResponseHeaders()" jsXhrResponseHeaders :: JSVal -> IO JSString foreign import javascript unsafe "$1.setRequestHeader($2, $3)" jsXhrSetRequestHeader :: JSVal -> JSString -> JSString -> IO () foreign import javascript unsafe "$1.statusText" jsXhrGetStatusText :: JSVal -> IO JSString foreign import javascript unsafe "xh = $1" jsDebugXhr :: JSVal -> IO () foreign import javascript safe "h$wrapBuffer($3, true, $1, $2)" js_wrapBuffer :: Int -> Int -> JSVal -> IO JSVal foreign import javascript unsafe "h$release($1)" js_release :: Callback (IO ()) -> IO () xhrResponseHeaders :: JSVal -> IO [HTTP.Header] xhrResponseHeaders jReq = do (headers :: JSString) <- jsXhrResponseHeaders jReq let headersStrings = T.lines . T.pack . JSString.unpack $ headers return $ catMaybes $ buildHeader <$> headersStrings buildHeader :: Text -> Maybe HTTP.Header buildHeader xs = parseXs $ splitStr xs where splitStr = T.splitOn (":") parseXs :: [Text] -> Maybe HTTP.Header parseXs (c:cs) = Just (mk $ encodeUtf8 $ T.strip c, encodeUtf8 $ T.strip $ T.concat cs) parseXs _ = Nothing bufferByteString :: Int -- ^ offset from the start in bytes -> Int -- ^ length in bytes (use zero or a negative number to get the whole ArrayBuffer) -> JSVal -> IO BS.ByteString bufferByteString offset length buf = do (ByteArray ba) <- wrapBuffer offset length buf byteArrayByteString ba byteArrayByteString :: ByteArray# -> IO BS.ByteString byteArrayByteString arr = #ifdef ghcjs_HOST_OS let ba = ByteArray arr !(Addr a) = byteArrayContents ba in unsafePackAddressLen (sizeofByteArray ba) a #else error "GHCJS.Foreign.byteArrayToByteString: not JS" #endif wrapBuffer :: Int -- ^ offset from the start in bytes, if this is not a multiple of 8, -- not all types can be read from the ByteArray# -> Int -- ^ length in bytes (use zero or a negative number to use the whole ArrayBuffer) -> JSVal -- ^ JavaScript ArrayBuffer object -> IO ByteArray -- ^ result wrapBuffer offset size buf = unsafeCoerce <$> js_wrapBuffer offset size buf {-# INLINE wrapBuffer #-} makeRequest :: Method -> Req -> (Int -> Bool) -> Maybe BaseUrl -> IO (Either ServantError (Int, [HTTP.Header], BS.ByteString)) makeRequest method req isWantedStatus bUrl = do jRequest <- jsXhrRequest let url = JSString.pack . show $ buildUrl req bUrl methodText = JSString.pack $ unpack method jsXhrOpen jRequest methodText url jsTrue jsXhrResponseType jRequest "arraybuffer" resp <- newEmptyMVar cb <- syncCallback ThrowWouldBlock $ do r <- jsXhrReadyState jRequest :: IO JSVal state <- fromJSVal r when ((state :: Maybe Int) == Just 4) $ do statusCode <- fromMaybe (-1) <$> (fromJSVal =<< jsXhrStatus jRequest) if (statusCode >= 200 && statusCode < 300) then do bsResp <- bufferByteString 0 0 =<< jsXhrResponse jRequest headers <- xhrResponseHeaders jRequest putMVar resp $ Right (statusCode, headers, bsResp) else do bsStatusText <- jsXhrGetStatusText jRequest putMVar resp $ Left $ FailureResponse (mkStatus statusCode . pack . JSString.unpack $ bsStatusText) ("unknown" // "unknown") jsXhrOnReadyStateChange jRequest cb case reqBody req of Nothing -> jsXhrSend jRequest (Just (body, mediaType)) -> do jsXhrSetRequestHeader jRequest "Content-Type" $ JSString.pack $ show mediaType b <- toJSVal (decodeUtf8 $ toStrict body) jsXhrSendWith jRequest b res <- takeMVar resp release cb return res release :: Callback (IO ()) -- ^ the callback -> IO () release = js_release buildUrl :: Req -> Maybe BaseUrl -> URI buildUrl req@(Req path qText mBody rAccept hs) baseurl = (baseURI baseurl){uriPath = path, uriQuery = query} where query = unpack $ renderQuery True $ queryTextToQuery qText baseURI Nothing = nullURI baseURI (Just (BaseUrl scheme host port)) = nullURI { uriScheme = schemeText, uriAuthority = Just $ URIAuth "" host portText } where portText = ":" <> (show port) schemeText = case scheme of Http -> "http:" Https -> "https:"
meiersi/ghcjs-servant-client
src/Servant/Common/Req.hs
bsd-3-clause
12,748
44
23
3,186
2,905
1,544
1,361
-1
-1
-- | TODO: this box is a bit of a hack due to the deadline pressure... module Data.ByteString.IsoBaseFileFormat.Boxes.MovieFragment where import Data.ByteString.IsoBaseFileFormat.Box import Data.ByteString.IsoBaseFileFormat.Util.BoxContent -- | Compose a set of boxes into a 'MovieFragment' movieFragment :: Boxes ts -> Box (ContainerBox MovieFragment ts) movieFragment = containerBox () -- | Movie Fragments data MovieFragment instance IsBox MovieFragment where type BoxContent MovieFragment = () type instance BoxTypeSymbol MovieFragment = "moof" -- | Return the static size of the empty box movieFragmentStaticSize :: Num a => a movieFragmentStaticSize = fromBoxSize 0 (boxSize (movieFragment NoBoxes))
sheyll/isobmff-builder
src/Data/ByteString/IsoBaseFileFormat/Boxes/MovieFragment.hs
bsd-3-clause
714
0
9
98
127
73
54
-1
-1
{-# OPTIONS_GHC -Wall #-} -- |Exports a few routines for dealing with directories. module System.Console.ShSh.Directory ( parentDir, joinDirs ) where import System.FilePath ( splitDirectories, joinPath ) -- |Removes the last directory from the path. We could put this in -- the IO monad and then deal with what happens when we're at the top? parentDir :: FilePath -> FilePath parentDir = joinPath . reverse . drop 1 . reverse . splitDirectories -- |Joins two directories, removing all the '.'s and '..'s. joinDirs :: FilePath -> FilePath -> FilePath joinDirs a' b' = join' (splitDirectories a') (splitDirectories b') where join' a (".":b) = join' a b join' a ("..":b) = join' (take (length a - 1) a) b join' a (x:b) = join' (a++[x]) b join' a [] = joinPath a
shicks/shsh
System/Console/ShSh/Directory.hs
bsd-3-clause
798
0
12
169
218
117
101
11
4
{-# OPTIONS -w #-} {-# LANGUAGE PackageImports #-} module GHC.GHCi (module M) where import "base" GHC.GHCi as M
silkapp/base-noprelude
src/GHC/GHCi.hs
bsd-3-clause
112
0
4
18
22
16
6
4
0
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Distance.IT.Rules ( rules ) where import Data.String import Prelude import Duckling.Dimensions.Types import Duckling.Distance.Helpers import Duckling.Types import qualified Duckling.Distance.Types as TDistance ruleLatentDistKm :: Rule ruleLatentDistKm = Rule { name = "<latent dist> km" , pattern = [ dimension Distance , regex "km|(k|ch)(ilo)?m?(etr)o?i?" ] , prod = \tokens -> case tokens of (Token Distance dd:_) -> Just . Token Distance $ withUnit TDistance.Kilometre dd _ -> Nothing } ruleDistMeters :: Rule ruleDistMeters = Rule { name = "<dist> meters" , pattern = [ dimension Distance , regex "metro?i?|m" ] , prod = \tokens -> case tokens of (Token Distance dd:_) -> Just . Token Distance $ withUnit TDistance.Metre dd _ -> Nothing } ruleDistCentimeters :: Rule ruleDistCentimeters = Rule { name = "<dist> centimeters" , pattern = [ dimension Distance , regex "cm|centimetro?i?" ] , prod = \tokens -> case tokens of (Token Distance dd:_) -> Just . Token Distance $ withUnit TDistance.Centimetre dd _ -> Nothing } ruleDistMiles :: Rule ruleDistMiles = Rule { name = "<dist> miles" , pattern = [ dimension Distance , regex "miglio?a?" ] , prod = \tokens -> case tokens of (Token Distance dd:_) -> Just . Token Distance $ withUnit TDistance.Mile dd _ -> Nothing } rules :: [Rule] rules = [ ruleDistCentimeters , ruleDistMeters , ruleDistMiles , ruleLatentDistKm ]
facebookincubator/duckling
Duckling/Distance/IT/Rules.hs
bsd-3-clause
1,833
0
13
443
451
255
196
56
2
{-| Module : Idris.Elab.Value Description : Code to elaborate values. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Elab.Value( elabVal, elabValBind, elabDocTerms , elabExec, elabREPL ) where import Idris.AbsSyntax import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate hiding (Unchecked) import Idris.Core.TT import Idris.Docstrings import Idris.Elab.Term import Idris.Elab.Utils import Idris.Error import Idris.Output (sendHighlighting) import Prelude hiding (id, (.)) import Control.Category import Data.Char (toLower) import qualified Data.Traversable as Traversable -- | Elaborate a value, returning any new bindings created (this will only -- happen if elaborating as a pattern clause) elabValBind :: ElabInfo -> ElabMode -> Bool -> PTerm -> Idris (Term, Type, [(Name, Type)]) elabValBind info aspat norm tm_in = do ctxt <- getContext i <- getIState let tm = addImpl [] i tm_in logElab 10 (showTmImpls tm) -- try: -- * ordinary elaboration -- * elaboration as a Type -- * elaboration as a function a -> b (ElabResult tm' defer is ctxt' newDecls highlights newGName, _) <- tclift (elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "val") infP initEState (build i info aspat [Reflection] (sMN 0 "val") (infTerm tm))) -- Extend the context with new definitions created setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights updateIState $ \i -> i { idris_name = newGName } let vtm = orderPats (getInferTerm tm') def' <- checkDef info (fileFC "(input)") iderr True defer let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, True, True))) def' addDeferred def'' mapM_ (elabCaseBlock info []) is logElab 3 ("Value: " ++ show vtm) (vtm_in, vty) <- recheckC (constraintNS info) (fileFC "(input)") id [] vtm let vtm = if norm then normalise (tt_ctxt i) [] vtm_in else vtm_in let bargs = getPBtys vtm return (vtm, vty, bargs) elabVal :: ElabInfo -> ElabMode -> PTerm -> Idris (Term, Type) elabVal info aspat tm_in = do (tm, ty, _) <- elabValBind info aspat False tm_in return (tm, ty) elabDocTerms :: ElabInfo -> Docstring (Either Err PTerm) -> Idris (Docstring DocTerm) elabDocTerms info str = do typechecked <- Traversable.mapM decorate str return $ checkDocstring mkDocTerm typechecked where decorate (Left err) = return (Left err) decorate (Right pt) = fmap (fmap fst) (tryElabVal info ERHS pt) tryElabVal :: ElabInfo -> ElabMode -> PTerm -> Idris (Either Err (Term, Type)) tryElabVal info aspat tm_in = idrisCatch (fmap Right $ elabVal info aspat tm_in) (return . Left) mkDocTerm :: String -> [String] -> String -> Either Err Term -> DocTerm mkDocTerm lang attrs src (Left err) | map toLower lang == "idris" = Failing err | otherwise = Unchecked mkDocTerm lang attrs src (Right tm) | map toLower lang == "idris" = if "example" `elem` map (map toLower) attrs then Example tm else Checked tm | otherwise = Unchecked -- | Try running the term directly (as IO ()) or with >>= printLn appended -- (for other IO _), then printing it as an Integer (as a default numeric -- type), then printing it as any Showable thing elabExec :: FC -> PTerm -> PTerm elabExec fc tm = runtm (PAlternative [] FirstSuccess [printtm (PApp fc (PRef fc [] (sUN "the")) [pexp (PConstant NoFC (AType (ATInt ITBig))), pexp tm]), tm, PApp fc (PRef fc [] (sUN ">>=")) [pexp tm, pexp (PRef fc [] (sUN "printLn"))], printtm tm ]) where runtm t = PApp fc (PRef fc [] (sUN "run__IO")) [pimp (sUN "ffi") (PRef fc [] (sUN "FFI_C")) False, pexp t] printtm t = PApp fc (PRef fc [] (sUN "printLn")) [pexp t] elabREPL :: ElabInfo -> ElabMode -> PTerm -> Idris (Term, Type) elabREPL info aspat tm = idrisCatch (elabVal info aspat tm) catchAmbig where catchAmbig (CantResolveAlts _) = elabVal info aspat (PDisamb [[txt "List"]] tm) catchAmbig (NoValidAlts _) = elabVal info aspat (PDisamb [[txt "List"]] tm) catchAmbig e = ierror e
uuhan/Idris-dev
src/Idris/Elab/Value.hs
bsd-3-clause
4,759
0
19
1,419
1,499
771
728
83
4
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.CompressedTexturePixelStorage -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/compressed_texture_pixel_storage.txt ARB_compressed_texture_pixel_storage> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.CompressedTexturePixelStorage ( -- * Enums gl_PACK_COMPRESSED_BLOCK_DEPTH, gl_PACK_COMPRESSED_BLOCK_HEIGHT, gl_PACK_COMPRESSED_BLOCK_SIZE, gl_PACK_COMPRESSED_BLOCK_WIDTH, gl_UNPACK_COMPRESSED_BLOCK_DEPTH, gl_UNPACK_COMPRESSED_BLOCK_HEIGHT, gl_UNPACK_COMPRESSED_BLOCK_SIZE, gl_UNPACK_COMPRESSED_BLOCK_WIDTH ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/CompressedTexturePixelStorage.hs
bsd-3-clause
977
0
4
99
58
45
13
10
0
{-# LANGUAGE OverloadedStrings #-} ------------------------------------------------------------------------------ -- | This module is where all the routes and handlers are defined for your -- site. The 'app' function is the initializer that combines everything -- together and is exported by this module. module Site ( app ) where import Application import Control.Applicative import Snap.Snaplet import Snap.Snaplet.Heist.Compiled import Snap.Util.FileServe import Heist import Control.Lens app :: Example -> SnapletInit App App app ex = makeSnaplet "tutorial" "Heist tutorial" Nothing $ do h <- nestSnaplet "" heist $ heistInit' (examplePath ex) emptyHeistConfig addConfig h $ mempty & scCompiledSplices .~ (exampleSplices ex) wrapSite (<|> heistServe) return $ App h "green"
kaol/heist-tutorial
src/Site.hs
bsd-3-clause
794
0
12
119
154
82
72
16
1
module Connection where import Network.Socket startServer :: String -> IO Socket startServer port = do (serveraddr:_) <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just port) sock <- socket (addrFamily serveraddr) Datagram defaultProtocol bindSocket sock (addrAddress serveraddr) >> return sock getSocket :: String -> IO Socket getSocket port = do (serveraddr:_) <- getAddrInfo Nothing (Just "0.0.0.0") (Just port) s <- socket (addrFamily serveraddr) Datagram defaultProtocol connect s (addrAddress serveraddr) >> return s
semaj/hademlia
src/Connection.hs
bsd-3-clause
596
0
14
118
211
103
108
13
1
import Test.Hspec import Test.QuickCheck import Lib import qualified Data.HashTable.IO as H main :: IO () main = hspec $ do -- describe "incre1" $ do -- it "Incre every existing element" $ do -- do ht <- H.new -- upsert ht (1,1) -- upsert ht (2,2) -- incre1 ht 2 -- xss <- H.toList ht -- -- xss `shouldBe` [((1,1),1)] -- length xss `shouldBe` 4 -- it "Incre every existing element, again" $ do -- do ht <- H.new -- upsert ht (1,1) -- upsert ht (2,1) -- upsert ht (3,1) -- incre1 ht 2 -- xss <- H.toList ht -- -- xss `shouldBe` [((1,1),1)] -- length xss `shouldBe` 6 -- describe "uniqueSums" $ do -- it "gets the empty combos for empty set" $ do -- do ht <- H.new -- uniqueSums [] ht -- xss <- H.toList ht -- length xss `shouldBe` 0 -- it "gets 1 for 1" $ do -- do ht <- H.new -- uniqueSums [1] ht -- xss <- H.toList ht -- length xss `shouldBe` 1 -- it "gets 3 for 2" $ do -- do ht <- H.new -- uniqueSums [1, 2] ht -- xss <- H.toList ht -- length xss `shouldBe` 3 -- it "correct combinations" $ do -- do ht <- H.fromList [((8,3),1),((3,2),1),((5,2),2),((3,1),1),((4,1),1),((10,4),1),((1,1),1),((6,3),1),((4,2),1),((6,2),1),((2,1),1),((7,2),1),((7,3),1),((9,3),1)] -- uniqueSums [5] ht -- xss <- H.toList ht -- countOcc xss `shouldBe` [((1,1),1)] -- countOcc xss 5 `shouldBe` 1 -- countOcc xss 4 `shouldBe` 5 -- -- filterByLen 3 xss `shouldBe` [((1,1), 1)] -- countOcc xss 3 `shouldBe` 10 -- countOcc xss 2 `shouldBe` 10 -- countOcc xss 1 `shouldBe` 5 it "correct combinations with 3 out 6" $ do do ht <- H.new uniqueSums [1,3,6,8,10,11] 3 ht xss <- H.toList ht countOcc xss 3 `shouldBe` 20 it "is correct for the sample" $ do do ht <- H.new uniqueSums [1,3,6,8,10,11] 3 ht xss <- H.toList ht let unik = filterUnique xss 3 in do length unik `shouldBe` 8 sum unik `shouldBe` 156 filterByLen :: Int -> [((Int, Int), Int)] -> [((Int, Int), Int)] filterByLen l = filter (\((sum, len), occ) -> len == l) countOcc :: [((Int, Int), Int)] -> Int -> Int countOcc xs len = sum mapLen where mapLen = map (\((_, l), occ) -> if l == len then occ else 0) xs
hackle/euler
test/Spec.hs
bsd-3-clause
2,895
0
18
1,233
431
253
178
24
2
{-# LANGUAGE OverloadedLists #-} module Test.Examples.FunSpec ( spec ) where import Control.Category (id, (.)) import Control.Lens ((&)) import Data.Foldable (for_) import Prelude hiding (id, (.)) import Test.Hspec (Spec, describe, it) import Test.QuickCheck (NonNegative (..), Property, property) import Universum (one) import Test.Arbitrary () import Test.Execution (describeExecWays, works, (>-*->), (~*~)) import Test.Util (VerySmall (..)) import Toy.Base import Toy.Execution (ExecWay (..), defCompileX86, translateLang) import Toy.Exp import qualified Toy.Lang as L spec :: Spec spec = do let ways = [ Ex id , Ex translateLang , Ex $ defCompileX86 . translateLang ] describe "functions" $ do describeExecWays ways $ \way -> do describe "basic" $ do it "no action" $ noActionTest way it "with body" $ withBodyTest way it "single argument" $ singleArgumentTest way it "arguments order" $ argumentsOrderTest way it "multiple arguments" $ multipleArgumentsTest way it "return" $ returnTest way it "return in the middle" $ returnInTheMiddleTest way describe "recursion" $ do it "simple" $ property $ recSimpleTest way it "fib" $ fibTest way it "gcd" $ gcdTest way describe "standart functions presence" $ do for_ stdFunExamples $ \args@(show -> name, _) -> it name $ stdFunCallTest args way singleFunProg :: [Var] -> [Exp] -> L.Stmt -> L.Program singleFunProg argNames args body = let name = "testfunc" decl = one (name, (FunSign name argNames, body)) in L.Program decl $ L.funCallS name args singleRetFunProg :: [Var] -> [Exp] -> L.Stmt -> L.Program singleRetFunProg argNames args body = let name = "testfunc" decl = one (name, (FunSign name argNames, body)) in L.Program decl $ L.writeS (FunE name args) singleRecFunProg :: [Var] -> [Exp] -> (Var -> L.Stmt) -> L.Program singleRecFunProg argNames args body = let name = "testfunc" decl = one (name, (FunSign name argNames, body name)) in L.Program decl $ L.writeS (FunE name args) noActionTest :: ExecWay L.Program -> Property noActionTest = sample & [] >-*-> [] where sample = singleFunProg [] [] mempty withBodyTest :: ExecWay L.Program -> Property withBodyTest = sample & [] >-*-> [1] where sample = singleFunProg [] [] $ L.writeS 1 singleArgumentTest :: ExecWay L.Program -> Property singleArgumentTest = sample & [] >-*-> [5] where sample = singleFunProg ["a"] [5] $ L.writeS "a" argumentsOrderTest :: ExecWay L.Program -> Property argumentsOrderTest = sample & [] >-*-> [1] where sample = singleFunProg ["a", "b"] (ValueE <$> [1, 0]) $ L.writeS ("a" - "b") multipleArgumentsTest :: ExecWay L.Program -> Property multipleArgumentsTest = sample & [] >-*-> [22020] where input = ValueE . (10 ^) <$> [4 :: Int, 3..0] sample = singleFunProg ["a", "b", "c", "d", "e"] input $ L.writeS ("a" + "b" - "c" + "d" - "e" + 11111) returnTest :: ExecWay L.Program -> Property returnTest = sample & [] >-*-> [7] where sample = singleRetFunProg [] [] $ L.Return 7 returnInTheMiddleTest :: ExecWay L.Program -> Property returnInTheMiddleTest = sample & [] >-*-> [15] where sample = singleRetFunProg [] [] $ mconcat [ "i" L.:= 0 , L.whileS (0 ==: 0) $ mconcat [ L.If ("i" >: 12) (L.Return "i") (L.Skip) , "i" L.:= "i" + 5 ] ] recSimpleTest :: ExecWay L.Program -> Property recSimpleTest way = sample ~*~ fun $ way where sample = singleRecFunProg ["a"] [readE] $ \funName -> L.If ("a" ==: 0) (L.Return 1) $ L.Return (3 * FunE funName ["a" - 1] * 2) fun :: NonNegative (VerySmall Value) -> Value fun (NonNegative (VerySmall x)) = 6 ^ x fibTest :: ExecWay L.Program -> Property fibTest = sample ~*~ fun where sample = singleRecFunProg ["a"] [readE] $ \funName -> L.If ("a" <: 2) (L.Return "a") $ L.Return (FunE funName ["a" - 1] + FunE funName ["a" - 2]) fun :: NonNegative (VerySmall Value) -> Value fun (NonNegative (VerySmall x)) = fibs !! fromIntegral x fibs = 0 : 1 : zipWith (+) fibs (tail fibs) gcdTest :: ExecWay L.Program -> Property gcdTest = sample ~*~ fun where sample = singleRecFunProg ["a", "b"] [readE, readE] $ \funName -> L.If ("b" ==: 0) (L.Return "a") $ L.Return (FunE funName ["b", "a" %: "b"]) fun :: NonNegative Value -> NonNegative Value -> Value fun (NonNegative x) (NonNegative y) = gcd x y stdFunCallTest :: (Var, [Exp]) -> ExecWay L.Program -> Property stdFunCallTest = works . L.Program mempty . uncurry L.funCallS
Martoon-00/toy-compiler
test/Test/Examples/FunSpec.hs
bsd-3-clause
5,336
0
21
1,748
1,847
963
884
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Distance.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import qualified Duckling.Distance.BG.Tests as BG import qualified Duckling.Distance.CA.Tests as CA import qualified Duckling.Distance.CS.Tests as CS import qualified Duckling.Distance.DE.Tests as DE import qualified Duckling.Distance.EN.Tests as EN import qualified Duckling.Distance.ES.Tests as ES import qualified Duckling.Distance.FR.Tests as FR import qualified Duckling.Distance.GA.Tests as GA import qualified Duckling.Distance.HR.Tests as HR import qualified Duckling.Distance.IT.Tests as IT import qualified Duckling.Distance.KM.Tests as KM import qualified Duckling.Distance.KO.Tests as KO import qualified Duckling.Distance.MN.Tests as MN import qualified Duckling.Distance.NL.Tests as NL import qualified Duckling.Distance.PT.Tests as PT import qualified Duckling.Distance.RO.Tests as RO import qualified Duckling.Distance.RU.Tests as RU import qualified Duckling.Distance.TR.Tests as TR import qualified Duckling.Distance.SV.Tests as SV import qualified Duckling.Distance.ZH.Tests as ZH tests :: TestTree tests = testGroup "Distance Tests" [ BG.tests , CA.tests , CS.tests , DE.tests , EN.tests , ES.tests , FR.tests , GA.tests , HR.tests , IT.tests , KM.tests , KO.tests , MN.tests , NL.tests , PT.tests , RO.tests , RU.tests , TR.tests , SV.tests , ZH.tests ]
facebookincubator/duckling
tests/Duckling/Distance/Tests.hs
bsd-3-clause
1,630
0
7
247
345
249
96
47
1
module DataSpec where import Data import Data.Aeson import qualified Data.Map.Strict as M import Test.Hspec import qualified Test.Hspec.Wai.JSON as J spec :: Spec spec = do let fd1 = M.fromList [("1", 1), ("2", 2)] fd2 = M.fromList [("1", 3), ("3", 3)] combined = M.fromList [("1", 1), ("2", 2), ("3", 3)] describe "coalesce" $ do it "should favor earlier filter diffs" $ do coalesce [fd1, fd2] `shouldBe` combined describe "filterDiffJson" $ do it "should encode as json correctly" $ do encode (filterDiffJson [fd1, fd2]) `shouldBe` [J.json| {"filter_diff": {"1": 1, "2": 2,"3": 3 } } |]
semaj/espresso
test/DataSpec.hs
bsd-3-clause
661
0
17
165
231
134
97
-1
-1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, GADTs #-} -- | The @esqueleto@ EDSL (embedded domain specific language). -- This module replaces @Database.Persist@, so instead of -- importing that module you should just import this one: -- -- @ -- -- For a module using just esqueleto. -- import Database.Esqueleto -- @ -- -- If you need to use @persistent@'s default support for queries -- as well, either import it qualified: -- -- @ -- -- For a module that mostly uses esqueleto. -- import Database.Esqueleto -- import qualified Database.Persistent as P -- @ -- -- or import @esqueleto@ itself qualified: -- -- @ -- -- For a module uses esqueleto just on some queries. -- import Database.Persistent -- import qualified Database.Esqueleto as E -- @ -- -- Other than identifier name clashes, @esqueleto@ does not -- conflict with @persistent@ in any way. module Database.Esqueleto ( -- * Setup -- $setup -- * Introduction -- $introduction -- * Getting started -- $gettingstarted -- * @esqueleto@'s Language Esqueleto( where_, on, groupBy, orderBy, rand, asc, desc, limit, offset, having , sub_select, sub_selectDistinct, (^.), (?.) , val, isNothing, just, nothing, joinV, countRows, count, not_ , (==.), (>=.), (>.), (<=.), (<.), (!=.), (&&.), (||.) , (+.), (-.), (/.), (*.) , random_, round_, ceiling_, floor_ , min_, max_, sum_, avg_ , coalesce, coalesceDefault , like, (%), concat_, (++.) , subList_select, subList_selectDistinct, valList , in_, notIn, exists, notExists , set, (=.), (+=.), (-=.), (*=.), (/=.) , case_ ) , when_ , then_ , else_ , from , Value(..) , unValue , ValueList(..) , OrderBy -- ** Joins , InnerJoin(..) , CrossJoin(..) , LeftOuterJoin(..) , RightOuterJoin(..) , FullOuterJoin(..) , OnClauseWithoutMatchingJoinException(..) -- * SQL backend , SqlQuery , SqlExpr , SqlEntity , select , selectDistinct , selectSource , selectDistinctSource , delete , deleteCount , update , updateCount , insertSelect , insertSelectDistinct , (<#) , (<&>) -- * Helpers , valkey , valJ -- * Re-exports -- $reexports , deleteKey , module Database.Esqueleto.Internal.PersistentImport ) where import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Reader (ReaderT) import Data.Int (Int64) import Database.Esqueleto.Internal.Language import Database.Esqueleto.Internal.Sql import Database.Esqueleto.Internal.PersistentImport import qualified Database.Persist -- $setup -- -- If you're already using @persistent@, then you're ready to use -- @esqueleto@, no further setup is needed. If you're just -- starting a new project and would like to use @esqueleto@, take -- a look at @persistent@'s book first -- (<http://www.yesodweb.com/book/persistent>) to learn how to -- define your schema. ---------------------------------------------------------------------- -- $introduction -- -- The main goals of @esqueleto@ are to: -- -- * Be easily translatable to SQL. When you take a look at a -- @esqueleto@ query, you should be able to know exactly how -- the SQL query will end up. (As opposed to being a -- relational algebra EDSL such as HaskellDB, which is -- non-trivial to translate into SQL.) -- -- * Support the mostly used SQL features. We'd like you to be -- able to use @esqueleto@ for all of your queries, no -- exceptions. Send a pull request or open an issue on our -- project page (<https://github.com/meteficha/esqueleto>) if -- there's anything missing that you'd like to see. -- -- * Be as type-safe as possible. We strive to provide as many -- type checks as possible. If you get bitten by some invalid -- code that type-checks, please open an issue on our project -- page so we can take a look. -- -- However, it is /not/ a goal to be able to write portable SQL. -- We do not try to hide the differences between DBMSs from you, -- and @esqueleto@ code that works for one database may not work -- on another. This is a compromise we have to make in order to -- give you as much control over the raw SQL as possible without -- losing too much convenience. This also means that you may -- type-check a query that doesn't work on your DBMS. ---------------------------------------------------------------------- -- $gettingstarted -- -- We like clean, easy-to-read EDSLs. However, in order to -- achieve this goal we've used a lot of type hackery, leading to -- some hard-to-read type signatures. On this section, we'll try -- to build some intuition about the syntax. -- -- For the following examples, we'll use this example schema: -- -- @ -- share [mkPersist sqlSettings, mkMigrate \"migrateAll\"] [persist| -- Person -- name String -- age Int Maybe -- deriving Eq Show -- BlogPost -- title String -- authorId PersonId -- deriving Eq Show -- Follow -- follower PersonId -- followed PersonId -- deriving Eq Show -- |] -- @ -- -- Most of @esqueleto@ was created with @SELECT@ statements in -- mind, not only because they're the most common but also -- because they're the most complex kind of statement. The most -- simple kind of @SELECT@ would be: -- -- @ -- SELECT * -- FROM Person -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- do people <- 'select' $ -- 'from' $ \\person -> do -- return person -- liftIO $ mapM_ (putStrLn . personName . entityVal) people -- @ -- -- The expression above has type @SqlPersist m ()@, while -- @people@ has type @[Entity Person]@. The query above will be -- translated into exactly the same query we wrote manually, but -- instead of @SELECT *@ it will list all entity fields (using -- @*@ is not robust). Note that @esqueleto@ knows that we want -- an @Entity Person@ just because of the @personName@ that we're -- printing later. -- -- However, most of the time we need to filter our queries using -- @WHERE@. For example: -- -- @ -- SELECT * -- FROM Person -- WHERE Person.name = \"John\" -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\p -> do -- 'where_' (p '^.' PersonName '==.' 'val' \"John\") -- return p -- @ -- -- Although @esqueleto@'s code is a bit more noisy, it's has -- almost the same structure (save from the @return@). The -- @('^.')@ operator is used to project a field from an entity. -- The field name is the same one generated by @persistent@'s -- Template Haskell functions. We use 'val' to lift a constant -- Haskell value into the SQL query. -- -- Another example would be: -- -- @ -- SELECT * -- FROM Person -- WHERE Person.age >= 18 -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\p -> do -- where_ (p ^. PersonAge '>=.' 'just' (val 18)) -- return p -- @ -- -- Since @age@ is an optional @Person@ field, we use 'just' lift -- @val 18 :: SqlExpr (Value Int)@ into @just (val 18) :: -- SqlExpr (Value (Maybe Int))@. -- -- Implicit joins are represented by tuples. For example, to get -- the list of all blog posts and their authors, we could write: -- -- @ -- SELECT BlogPost.*, Person.* -- FROM BlogPost, Person -- WHERE BlogPost.authorId = Person.id -- ORDER BY BlogPost.title ASC -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\(b, p) -> do -- where_ (b ^. BlogPostAuthorId ==. p ^. PersonId) -- 'orderBy' ['asc' (b ^. BlogPostTitle)] -- return (b, p) -- @ -- -- However, we may want your results to include people who don't -- have any blog posts as well using a @LEFT OUTER JOIN@: -- -- @ -- SELECT Person.*, BlogPost.* -- FROM Person LEFT OUTER JOIN BlogPost -- ON Person.id = BlogPost.authorId -- ORDER BY Person.name ASC, BlogPost.title ASC -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\(p ``LeftOuterJoin`` mb) -> do -- 'on' (just (p ^. PersonId) ==. mb '?.' BlogPostAuthorId) -- orderBy [asc (p ^. PersonName), asc (mb '?.' BlogPostTitle)] -- return (p, mb) -- @ -- -- On a @LEFT OUTER JOIN@ the entity on the right hand side may -- not exist (i.e. there may be a @Person@ without any -- @BlogPost@s), so while @p :: SqlExpr (Entity Person)@, we have -- @mb :: SqlExpr (Maybe (Entity BlogPost))@. The whole -- expression above has type @SqlPersist m [(Entity Person, Maybe -- (Entity BlogPost))]@. Instead of using @(^.)@, we used -- @('?.')@ to project a field from a @Maybe (Entity a)@. -- -- We are by no means limited to joins of two tables, nor by -- joins of different tables. For example, we may want a list -- the @Follow@ entity: -- -- @ -- SELECT P1.*, Follow.*, P2.* -- FROM Person AS P1 -- INNER JOIN Follow ON P1.id = Follow.follower -- INNER JOIN P2 ON P2.id = Follow.followed -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\(p1 ``InnerJoin`` f ``InnerJoin`` p2) -> do -- on (p2 ^. PersonId ==. f ^. FollowFollowed) -- on (p1 ^. PersonId ==. f ^. FollowFollower) -- return (p1, f, p2) -- @ -- -- /Note carefully that the order of the ON clauses is/ -- /reversed!/ You're required to write your 'on's in reverse -- order because that helps composability (see the documentation -- of 'on' for more details). -- -- We also currently support @UPDATE@ and @DELETE@ statements. -- For example: -- -- @ -- do 'update' $ \\p -> do -- 'set' p [ PersonName '=.' val \"João\" ] -- where_ (p ^. PersonName ==. val \"Joao\") -- 'delete' $ -- from $ \\p -> do -- where_ (p ^. PersonAge <. just (val 14)) -- @ -- -- The results of queries can also be used for insertions. -- In @SQL@, we might write the following, inserting a new blog -- post for every user: -- -- @ -- INSERT INTO BlogPost -- SELECT ('Group Blog Post', id) -- FROM Person -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- insertSelect $ from $ \\p-> -- return $ BlogPost \<# \"Group Blog Post\" \<&\> (p ^. PersonId) -- @ -- -- Individual insertions can be performed through Persistent's -- 'insert' function, reexported for convenience. ---------------------------------------------------------------------- -- $reexports -- -- We re-export many symbols from @persistent@ for convenince: -- -- * \"Store functions\" from "Database.Persist". -- -- * Everything from "Database.Persist.Class" except for -- @PersistQuery@ and @delete@ (use 'deleteKey' instead). -- -- * Everything from "Database.Persist.Types" except for -- @Update@, @SelectOpt@, @BackendSpecificFilter@ and @Filter@. -- -- * Everything from "Database.Persist.Sql" except for -- @deleteWhereCount@ and @updateWhereCount@. ---------------------------------------------------------------------- -- | @valkey i = val (Key (PersistInt64 i))@ -- (<https://github.com/meteficha/esqueleto/issues/9>). valkey :: (Esqueleto query expr backend, ToBackendKey SqlBackend entity, PersistField (Key entity)) => Int64 -> expr (Value (Key entity)) valkey = val . toSqlKey -- | @valJ@ is like @val@ but for something that is already a @Value@. The use -- case it was written for was, given a @Value@ lift the @Key@ for that @Value@ -- into the query expression in a type safe way. However, the implementation is -- more generic than that so we call it @valJ@. -- -- Its important to note that the input entity and the output entity are -- constrained to be the same by the type signature on the function -- (<https://github.com/prowdsponsor/esqueleto/pull/69>). -- -- /Since: 1.4.2/ valJ :: (Esqueleto query expr backend, PersistField (Key entity)) => Value (Key entity) -> expr (Value (Key entity)) valJ = val . unValue ---------------------------------------------------------------------- -- | Synonym for 'Database.Persist.Store.delete' that does not -- clash with @esqueleto@'s 'delete'. deleteKey :: ( PersistStore (PersistEntityBackend val) , MonadIO m , PersistEntity val ) => Key val -> ReaderT (PersistEntityBackend val) m () deleteKey = Database.Persist.delete
frontrowed/esqueleto
src/Database/Esqueleto.hs
bsd-3-clause
12,207
0
11
2,487
889
727
162
70
1
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module MiniC.Print where -- pretty-printer generated by the BNF converter import MiniC.Abs import Data.Char -- the top-level printing method printTree :: Print a => a -> String printTree = render . prt 0 type Doc = [ShowS] -> [ShowS] doc :: ShowS -> Doc doc = (:) render :: Doc -> String render d = rend 0 (map ($ "") $ d []) "" where rend i ss = case ss of "[" :ts -> showChar '[' . rend i ts "(" :ts -> showChar '(' . rend i ts "{" :ts -> showChar '{' . new (i+1) . rend (i+1) ts "}" : ";":ts -> new (i-1) . space "}" . showChar ';' . new (i-1) . rend (i-1) ts "}" :ts -> new (i-1) . showChar '}' . new (i-1) . rend (i-1) ts ";" :ts -> showChar ';' . new i . rend i ts t : "," :ts -> showString t . space "," . rend i ts t : ")" :ts -> showString t . showChar ')' . rend i ts t : "]" :ts -> showString t . showChar ']' . rend i ts t :ts -> space t . rend i ts _ -> id new i = showChar '\n' . replicateS (2*i) (showChar ' ') . dropWhile isSpace space t = showString t . (\s -> if null s then "" else (' ':s)) parenth :: Doc -> Doc parenth ss = doc (showChar '(') . ss . doc (showChar ')') concatS :: [ShowS] -> ShowS concatS = foldr (.) id concatD :: [Doc] -> Doc concatD = foldr (.) id replicateS :: Int -> ShowS -> ShowS replicateS n f = concatS (replicate n f) -- the printer class does the job class Print a where prt :: Int -> a -> Doc prtList :: Int -> [a] -> Doc prtList i = concatD . map (prt i) instance Print a => Print [a] where prt = prtList instance Print Char where prt _ s = doc (showChar '\'' . mkEsc '\'' s . showChar '\'') prtList _ s = doc (showChar '"' . concatS (map (mkEsc '"') s) . showChar '"') mkEsc :: Char -> Char -> ShowS mkEsc q s = case s of _ | s == q -> showChar '\\' . showChar s '\\'-> showString "\\\\" '\n' -> showString "\\n" '\t' -> showString "\\t" _ -> showChar s prPrec :: Int -> Int -> Doc -> Doc prPrec i j = if j<i then parenth else id instance Print Integer where prt _ x = doc (shows x) instance Print Double where prt _ x = doc (shows x) instance Print Ident where prt _ (Ident i) = doc (showString ( i)) instance Print Prg where prt i e = case e of PPrg defs -> prPrec i 0 (concatD [prt 0 defs]) instance Print Dec where prt i e = case e of Dec qtyp id arrs -> prPrec i 0 (concatD [prt 0 qtyp, prt 0 id, prt 0 arrs]) prtList _ [] = (concatD []) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Def where prt i e = case e of DDef dec decs stms -> prPrec i 0 (concatD [prt 0 dec, doc (showString "("), prt 0 decs, doc (showString ")"), doc (showString "{"), prt 0 stms, doc (showString "}")]) DSig dec decs -> prPrec i 0 (concatD [prt 0 dec, doc (showString "("), prt 0 decs, doc (showString ")"), doc (showString ";")]) DDec dec -> prPrec i 0 (concatD [prt 0 dec, doc (showString ";")]) prtList _ [] = (concatD []) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Typ where prt i e = case e of TInt -> prPrec i 0 (concatD [doc (showString "int")]) TDouble -> prPrec i 0 (concatD [doc (showString "double")]) TStr flds -> prPrec i 0 (concatD [doc (showString "struct"), doc (showString "{"), prt 0 flds, doc (showString "}")]) TUni flds -> prPrec i 0 (concatD [doc (showString "union"), doc (showString "{"), prt 0 flds, doc (showString "}")]) TEnum enms -> prPrec i 0 (concatD [doc (showString "enum"), doc (showString "{"), prt 0 enms, doc (showString "}")]) TVoid -> prPrec i 0 (concatD [doc (showString "void")]) TPtr typ -> prPrec i 0 (concatD [prt 0 typ, doc (showString "*")]) prtList _ [] = (concatD []) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Enm where prt i e = case e of EEnm id -> prPrec i 0 (concatD [prt 0 id]) ECst id exp -> prPrec i 0 (concatD [prt 0 id, doc (showString "="), prt 2 exp]) prtList _ [] = (concatD []) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Fld where prt i e = case e of FFld typ id arrs -> prPrec i 0 (concatD [prt 0 typ, prt 0 id, prt 0 arrs]) prtList _ [] = (concatD []) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ";"), prt 0 xs]) instance Print Arr where prt i e = case e of AArr exp -> prPrec i 0 (concatD [doc (showString "["), prt 0 exp, doc (showString "]")]) prtList _ [] = (concatD []) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print QTyp where prt i e = case e of QTyp qual typ -> prPrec i 0 (concatD [prt 0 qual, prt 0 typ]) instance Print Qual where prt i e = case e of NoQual -> prPrec i 0 (concatD []) QConst -> prPrec i 0 (concatD [doc (showString "const")]) instance Print Stm where prt i e = case e of SDec dec init -> prPrec i 0 (concatD [prt 0 dec, prt 0 init]) SPut lval exp -> prPrec i 0 (concatD [prt 0 lval, doc (showString "="), prt 0 exp]) SFor stm1 exp stm2 stms -> prPrec i 0 (concatD [doc (showString "for"), doc (showString "("), prt 0 stm1, doc (showString ";"), prt 0 exp, doc (showString ";"), prt 0 stm2, doc (showString ")"), doc (showString "{"), prt 0 stms, doc (showString "}")]) SSwi exp branchs -> prPrec i 0 (concatD [doc (showString "switch"), doc (showString "("), prt 0 exp, doc (showString ")"), doc (showString "{"), prt 0 branchs, doc (showString "}")]) prtList _ [] = (concatD []) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ";"), prt 0 xs]) instance Print Branch where prt i e = case e of Case exp stms -> prPrec i 0 (concatD [doc (showString "case"), prt 2 exp, doc (showString ":"), prt 0 stms, doc (showString "break"), doc (showString ";")]) prtList _ [] = (concatD []) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Init where prt i e = case e of NoInit -> prPrec i 0 (concatD []) SoInit exp -> prPrec i 0 (concatD [doc (showString "="), prt 0 exp]) instance Print UOp where prt i e = case e of UAmp -> prPrec i 0 (concatD [doc (showString "&")]) UPtr -> prPrec i 0 (concatD [doc (showString "*")]) UPlus -> prPrec i 0 (concatD [doc (showString "+")]) UMinus -> prPrec i 0 (concatD [doc (showString "-")]) UTilde -> prPrec i 0 (concatD [doc (showString "~")]) UBang -> prPrec i 0 (concatD [doc (showString "!")]) instance Print Exp where prt i e = case e of EVar id -> prPrec i 16 (concatD [prt 0 id]) ELit n -> prPrec i 16 (concatD [prt 0 n]) EArw exp id -> prPrec i 15 (concatD [prt 15 exp, doc (showString "->"), prt 0 id]) EFld exp id -> prPrec i 15 (concatD [prt 15 exp, doc (showString "."), prt 0 id]) EArr exp1 exp2 -> prPrec i 15 (concatD [prt 15 exp1, doc (showString "["), prt 0 exp2, doc (showString "]")]) EApp exp exps -> prPrec i 15 (concatD [prt 15 exp, doc (showString "("), prt 0 exps, doc (showString ")")]) UOp uop exp -> prPrec i 14 (concatD [prt 0 uop, prt 13 exp]) Mul exp1 exp2 -> prPrec i 12 (concatD [prt 12 exp1, doc (showString "*"), prt 13 exp2]) Div exp1 exp2 -> prPrec i 12 (concatD [prt 12 exp1, doc (showString "/"), prt 13 exp2]) Mod exp1 exp2 -> prPrec i 12 (concatD [prt 12 exp1, doc (showString "%"), prt 13 exp2]) Add exp1 exp2 -> prPrec i 11 (concatD [prt 11 exp1, doc (showString "+"), prt 12 exp2]) Sub exp1 exp2 -> prPrec i 11 (concatD [prt 11 exp1, doc (showString "-"), prt 12 exp2]) Lsl exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "<<"), prt 11 exp2]) Lsr exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString ">>"), prt 11 exp2]) Lt exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "<"), prt 10 exp2]) Gt exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString ">"), prt 10 exp2]) Le exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "<="), prt 10 exp2]) Ge exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString ">="), prt 10 exp2]) Eq exp1 exp2 -> prPrec i 8 (concatD [prt 8 exp1, doc (showString "=="), prt 9 exp2]) NEq exp1 exp2 -> prPrec i 8 (concatD [prt 8 exp1, doc (showString "!="), prt 9 exp2]) And exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "&"), prt 8 exp2]) Xor exp1 exp2 -> prPrec i 6 (concatD [prt 6 exp1, doc (showString "^"), prt 7 exp2]) Ior exp1 exp2 -> prPrec i 5 (concatD [prt 5 exp1, doc (showString "|"), prt 6 exp2]) Land exp1 exp2 -> prPrec i 4 (concatD [prt 4 exp1, doc (showString "&&"), prt 5 exp2]) Lor exp1 exp2 -> prPrec i 3 (concatD [prt 3 exp1, doc (showString "||"), prt 4 exp2]) Cond exp1 exp2 exp3 -> prPrec i 2 (concatD [prt 3 exp1, doc (showString "?"), prt 0 exp2, doc (showString ":"), prt 2 exp3]) prtList _ [] = (concatD []) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print LVal where prt i e = case e of LVar id -> prPrec i 3 (concatD [prt 0 id]) LArw lval id -> prPrec i 2 (concatD [prt 2 lval, doc (showString "->"), prt 0 id]) LFld lval id -> prPrec i 2 (concatD [prt 2 lval, doc (showString "."), prt 0 id]) LArr lval exp -> prPrec i 2 (concatD [prt 2 lval, doc (showString "["), prt 0 exp, doc (showString "]")]) LPtr lval -> prPrec i 0 (concatD [doc (showString "*"), prt 2 lval])
jyp/ling
MiniC/Print.hs
bsd-3-clause
9,509
0
16
2,311
5,306
2,599
2,707
172
12
{-| Module : Data.Vector.Hashtables.Internal Description : Provides internals of hashtables and set of utilities. Copyright : (c) klapaucius, swamp_agr, 2016-2021 License : BSD3 -} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} module Data.Vector.Hashtables.Internal where import Control.Monad import Control.Monad.Primitive import Data.Bits import Data.Hashable import Data.Maybe import Data.Primitive.MutVar import Data.Vector.Generic (Mutable, Vector) import qualified Data.Vector.Generic as VI import Data.Vector.Generic.Mutable (MVector) import qualified Data.Vector.Generic.Mutable as V import qualified Data.Vector.Mutable as B import qualified Data.Vector.Storable as SI import qualified Data.Vector.Storable.Mutable as S import qualified Data.Vector.Unboxed as UI import qualified Data.Vector.Unboxed.Mutable as U import qualified GHC.Exts as Exts import Prelude hiding (length, lookup) import qualified Data.Primitive.PrimArray as A import qualified Data.Primitive.PrimArray.Utils as A import Data.Vector.Hashtables.Internal.Mask (mask) -- | Alias for 'MutablePrimArray s Int'. type IntArray s = A.MutablePrimArray s Int -- | Single-element mutable array of 'Dictionary_' with primitive state token parameterized with state, keys and values types. -- -- *Example*: -- -- >>> import qualified Data.Vector.Storable.Mutable as VM -- >>> import qualified Data.Vector.Unboxed.Mutable as UM -- >>> import Data.Vector.Hashtables -- >>> type HashTable k v = Dictionary (PrimState IO) VM.MVector k UM.MVector v -- -- Different vectors could be used for keys and values: -- -- - storable, -- - mutable, -- - unboxed. -- -- In most cases unboxed vectors should be used. Nevertheless, it is up to you to decide about final form of hastable. newtype Dictionary s ks k vs v = DRef { getDRef :: MutVar s (Dictionary_ s ks k vs v) } -- | Represents collection of hashtable internal primitive arrays and vectors. -- -- - hash codes, -- -- - references to the next element, -- -- - buckets, -- -- - keys -- -- - and values. -- data Dictionary_ s ks k vs v = Dictionary { hashCode, next, buckets, refs :: IntArray s, key :: ks s k, value :: vs s v } getCount, getFreeList, getFreeCount :: Int getCount = 0 getFreeList = 1 getFreeCount = 2 -- | Represents immutable dictionary as collection of immutable arrays and vectors. -- See 'unsafeFreeze' and 'unsafeThaw' for conversions from/to mutable dictionary. data FrozenDictionary ks k vs v = FrozenDictionary { fhashCode, fnext, fbuckets :: A.PrimArray Int, count, freeList, freeCount :: Int, fkey :: ks k, fvalue :: vs v } deriving (Eq, Ord, Show) -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find dictionary entry by given key in immutable 'FrozenDictionary'. -- If entry not found @-1@ returned. findElem :: (Vector ks k, Vector vs v, Hashable k, Eq k) => FrozenDictionary ks k vs v -> k -> Int findElem FrozenDictionary{..} key' = go $ fbuckets !. (hashCode' `rem` A.sizeofPrimArray fbuckets) where hashCode' = hash key' .&. mask go i | i >= 0 = if fhashCode !. i == hashCode' && fkey !.~ i == key' then i else go $ fnext !. i | otherwise = -1 {-# INLINE findElem #-} -- | Infix version of @unsafeRead@. (!~) :: (MVector v a, PrimMonad m) => v (PrimState m) a -> Int -> m a (!~) = V.unsafeRead -- | Infix version of @unsafeIndex@. (!.~) :: (Vector v a) => v a -> Int -> a (!.~) = VI.unsafeIndex -- | Infix version of @unsafeWrite@. (<~~) :: (MVector v a, PrimMonad m) => v (PrimState m) a -> Int -> a -> m () (<~~) = V.unsafeWrite -- | Infix version of @readPrimArray@. (!) :: PrimMonad m => A.MutablePrimArray (PrimState m) Int -> Int -> m Int (!) = A.readPrimArray -- | Infix version of @indexPrimArray@. (!.) :: A.PrimArray Int -> Int -> Int (!.) = A.indexPrimArray -- | Infix version of @writePrimArray@. (<~) :: PrimMonad m => A.MutablePrimArray (PrimState m) Int -> Int -> Int -> m () (<~) = A.writePrimArray -- | /O(1)/ Dictionary with given capacity. initialize :: (MVector ks k, MVector vs v, PrimMonad m) => Int -> m (Dictionary (PrimState m) ks k vs v) initialize capacity = do let size = getPrime capacity hashCode <- A.replicate size 0 next <- A.replicate size 0 key <- V.new size value <- V.new size buckets <- A.replicate size (-1) refs <- A.replicate 3 0 refs <~ 1 $ -1 dr <- newMutVar Dictionary {..} return . DRef $ dr -- | Create a copy of mutable dictionary. clone :: (MVector ks k, MVector vs v, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) clone DRef {..} = do Dictionary {..} <- readMutVar getDRef hashCode <- A.clone hashCode next <- A.clone next key <- V.clone key value <- V.clone value buckets <- A.clone buckets refs <- A.clone refs dr <- newMutVar Dictionary {..} return . DRef $ dr -- | /O(1)/ Unsafe convert a mutable dictionary to an immutable one without copying. -- The mutable dictionary may not be used after this operation. unsafeFreeze :: (VI.Vector ks k, VI.Vector vs v, PrimMonad m) => Dictionary (PrimState m) (Mutable ks) k (Mutable vs) v -> m (FrozenDictionary ks k vs v) unsafeFreeze DRef {..} = do Dictionary {..} <- readMutVar getDRef fhashCode <- A.unsafeFreeze hashCode fnext <- A.unsafeFreeze next fbuckets <- A.unsafeFreeze buckets count <- refs ! getCount freeList <- refs ! getFreeList freeCount <- refs ! getFreeCount fkey <- VI.unsafeFreeze key fvalue <- VI.unsafeFreeze value return FrozenDictionary {..} -- | /O(1)/ Unsafely convert immutable 'FrozenDictionary' to a mutable 'Dictionary' without copying. -- The immutable dictionary may not be used after this operation. unsafeThaw :: (Vector ks k, Vector vs v, PrimMonad m) => FrozenDictionary ks k vs v -> m (Dictionary (PrimState m) (Mutable ks) k (Mutable vs) v) unsafeThaw FrozenDictionary {..} = do hashCode <- A.unsafeThaw fhashCode next <- A.unsafeThaw fnext buckets <- A.unsafeThaw fbuckets refs <- A.unsafeThaw $ A.primArrayFromListN 3 [count, freeList, freeCount] key <- VI.unsafeThaw fkey value <- VI.unsafeThaw fvalue dr <- newMutVar Dictionary {..} return . DRef $ dr -- | /O(n)/ Retrieve list of keys from 'Dictionary'. keys :: (Vector ks k, PrimMonad m) => Dictionary (PrimState m) (Mutable ks) k vs v -> m (ks k) keys DRef{..} = do Dictionary{..} <- readMutVar getDRef hcs <- A.freeze hashCode ks <- VI.freeze key count <- refs ! getCount return . VI.ifilter (\i _ -> hcs !. i >= 0) . VI.take count $ ks -- | /O(n)/ Retrieve list of values from 'Dictionary'. values :: (Vector vs v, PrimMonad m) => Dictionary (PrimState m) ks k (Mutable vs) v -> m (vs v) values DRef{..} = do Dictionary{..} <- readMutVar getDRef hcs <- A.freeze hashCode vs <- VI.freeze value count <- refs ! getCount return . VI.ifilter (\i _ -> hcs !. i >= 0) . VI.take count $ vs -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Throws an error if value not found. at :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m v at d k = do i <- findEntry d k if i >= 0 then do Dictionary{..} <- readMutVar . getDRef $ d value !~ i else error "KeyNotFoundException!" {-# INLINE at #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Like 'at'' but return 'Nothing' if value not found. at' :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe v) at' d k = do i <- findEntry d k if i >= 0 then do Dictionary{..} <- readMutVar . getDRef $ d Just <$> value !~ i else pure Nothing {-# INLINE at' #-} atWithOrElse :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> (Dictionary (PrimState m) ks k vs v -> Int -> m a) -> (Dictionary (PrimState m) ks k vs v -> m a) -> m a atWithOrElse d k onFound onNothing = do i <- findEntry d k if i >= 0 then onFound d i else onNothing d {-# INLINE atWithOrElse #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find dictionary entry by given key. If entry not found @-1@ returned. findEntry :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m Int findEntry d key' = do Dictionary{..} <- readMutVar . getDRef $ d let hashCode' = hash key' .&. mask go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then return i else go =<< next ! i else go =<< next ! i | otherwise = return $ -1 go =<< buckets ! (hashCode' `rem` A.length buckets) {-# INLINE findEntry #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Insert key and value in dictionary by key's hash. -- If entry with given key found value will be replaced. insert :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> v -> m () insert DRef{..} key' value' = do d@Dictionary{..} <- readMutVar getDRef let hashCode' = hash key' .&. mask targetBucket = hashCode' `rem` A.length buckets go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then value <~~ i $ value' else go =<< next ! i else go =<< next ! i | otherwise = addOrResize addOrResize = do freeCount <- refs ! getFreeCount if freeCount > 0 then do index <- refs ! getFreeList nxt <- next ! index refs <~ getFreeList $ nxt refs <~ getFreeCount $ freeCount - 1 add index targetBucket else do count <- refs ! getCount refs <~ getCount $ count + 1 if count == A.length next then do nd <- resize d count hashCode' key' value' writeMutVar getDRef nd else add (fromIntegral count) (fromIntegral targetBucket) add !index !targetBucket = do hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index go =<< buckets ! targetBucket {-# INLINE insert #-} insertWithIndex :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> k -> v -> MutVar (PrimState m) (Dictionary_ (PrimState m) ks k vs v) -> Dictionary_ (PrimState m) ks k vs v -> Int -> m () insertWithIndex !targetBucket !hashCode' key' value' getDRef d@Dictionary{..} = go where go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then value <~~ i $ value' else go =<< next ! i else go =<< next ! i | otherwise = addOrResize targetBucket hashCode' key' value' getDRef d {-# INLINE insertWithIndex #-} addOrResize :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> k -> v -> MutVar (PrimState m) (Dictionary_ (PrimState m) ks k vs v) -> Dictionary_ (PrimState m) ks k vs v -> m () addOrResize !targetBucket !hashCode' !key' !value' dref d@Dictionary{..} = do freeCount <- refs ! getFreeCount if freeCount > 0 then do index <- refs ! getFreeList nxt <- next ! index refs <~ getFreeList $ nxt refs <~ getFreeCount $ freeCount - 1 add index targetBucket hashCode' key' value' d else do count <- refs ! getCount refs <~ getCount $ count + 1 if count == A.length next then do nd <- resize d count hashCode' key' value' writeMutVar dref nd else add (fromIntegral count) (fromIntegral targetBucket) hashCode' key' value' d {-# INLINE addOrResize #-} add :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> Int -> k -> v -> Dictionary_ (PrimState m) ks k vs v -> m () add !index !targetBucket !hashCode' !key' !value' Dictionary{..} = do hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index {-# INLINE add #-} resize Dictionary{..} index hashCode' key' value' = do let newSize = getPrime (index*2) delta = newSize - index buckets <- A.replicate newSize (-1) hashCode <- A.growNoZ hashCode delta next <- A.growNoZ next delta key <- V.grow key delta value <- V.grow value delta let go i | i < index = do hc <- hashCode ! i when (hc >= 0) $ do let bucket = hc `rem` newSize nx <- buckets ! bucket next <~ i $ nx buckets <~ bucket $ i go (i + 1) | otherwise = return () go 0 let targetBucket = hashCode' `rem` A.length buckets hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index return Dictionary{..} {-# INLINE resize #-} class DeleteEntry xs where deleteEntry :: (MVector xs x, PrimMonad m) => xs (PrimState m) x -> Int -> m () instance DeleteEntry S.MVector where deleteEntry _ _ = return () instance DeleteEntry U.MVector where deleteEntry _ _ = return () instance DeleteEntry B.MVector where deleteEntry v i = v <~~ i $ undefined -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Delete entry from 'Dictionary' by given key. delete :: (Eq k, MVector ks k, MVector vs v, Hashable k, PrimMonad m, DeleteEntry ks, DeleteEntry vs) => Dictionary (PrimState m) ks k vs v -> k -> m () delete DRef{..} key' = do Dictionary{..} <- readMutVar getDRef let hashCode' = hash key' .&. mask bucket = hashCode' `rem` A.length buckets go !last !i | i >= 0 = do hc <- hashCode ! i k <- key !~ i if hc == hashCode' && k == key' then do nxt <- next ! i if last < 0 then buckets <~ bucket $ nxt else next <~ last $ nxt hashCode <~ i $ -1 next <~ i =<< refs ! getFreeList deleteEntry key i deleteEntry value i refs <~ getFreeList $ i fc <- refs ! getFreeCount refs <~ getFreeCount $ fc + 1 else go i =<< next ! i | otherwise = return () go (-1) =<< buckets ! bucket {-# INLINE delete #-} deleteWithIndex :: (Eq k, MVector ks k, MVector vs v, Hashable k, PrimMonad m, DeleteEntry ks, DeleteEntry vs) => Int -> Int -> Dictionary_ (PrimState m) ks k vs v -> k -> Int -> Int -> m () deleteWithIndex !bucket !hashCode' d@Dictionary{..} key' !last !i | i >= 0 = do hc <- hashCode ! i k <- key !~ i if hc == hashCode' && k == key' then do nxt <- next ! i if last < 0 then buckets <~ bucket $ nxt else next <~ last $ nxt hashCode <~ i $ -1 next <~ i =<< refs ! getFreeList deleteEntry key i deleteEntry value i refs <~ getFreeList $ i fc <- refs ! getFreeCount refs <~ getFreeCount $ fc + 1 else deleteWithIndex bucket hashCode' d key' i =<< next ! i | otherwise = return () {-# INLINE deleteWithIndex #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Like 'lookup'' but return 'Nothing' if value not found. lookup :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe v) lookup = at' {-# INLINE lookup #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Throws an error if value not found. lookup' :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m v lookup' = at {-# INLINE lookup' #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Lookup the index of a key, which is its zero-based index in the sequence sorted by keys. -- The index is a number from 0 up to, but not including, the size of the dictionary. lookupIndex :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe Int) lookupIndex ht k = do let safeIndex i | i < 0 = Nothing | otherwise = Just i return . safeIndex =<< findEntry ht k {-# INLINE lookupIndex #-} -- | /O(1)/ Return 'True' if dictionary is empty, 'False' otherwise. null :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Bool null ht = return . (== 0) =<< length ht {-# INLINE null #-} -- | /O(1)/ Return the number of non-empty entries of dictionary. length :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Int length DRef {..} = do Dictionary {..} <- readMutVar getDRef count <- refs ! getCount freeCount <- refs ! getFreeCount return (count - freeCount) {-# INLINE length #-} -- | /O(1)/ Return the number of non-empty entries of dictionary. Synonym of 'length'. size :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Int size = length {-# INLINE size #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Return 'True' if the specified key is present in the dictionary, 'False' otherwise. member :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m Bool member ht k = return . (>= 0) =<< findEntry ht k {-# INLINE member #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- The expression @'findWithDefault' ht def k@ returns -- the value at key @k@ or returns default value @def@ -- when the key is not in the dictionary. findWithDefault :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> v -> k -> m v findWithDefault ht v k = return . fromMaybe v =<< at' ht k {-# INLINE findWithDefault #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- The expression (@'alter' ht f k@) alters the value @x@ at @k@, or absence thereof. -- 'alter' can be used to insert, delete, or update a value in a 'Dictionary'. -- -- > let f _ = Nothing -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 7 -- > toList ht -- > [(3, "b"), (5, "a")] -- -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 5 -- > toList ht -- > [(3 "b")] -- -- > let f _ = Just "c" -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 7 -- > toList ht -- > [(3, "b"), (5, "a"), (7, "c")] -- -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 5 -- > toList ht -- > [(3, "b"), (5, "c")] -- alter :: ( MVector ks k, MVector vs v, DeleteEntry ks, DeleteEntry vs , PrimMonad m, Hashable k, Eq k ) => Dictionary (PrimState m) ks k vs v -> (Maybe v -> Maybe v) -> k -> m () alter ht f k = do d@Dictionary{..} <- readMutVar . getDRef $ ht let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length buckets onFound' value' dict i = insertWithIndex targetBucket hashCode' k value' (getDRef ht) dict i onNothing' dict i = deleteWithIndex targetBucket hashCode' d k (-1) i onFound dict i = do d'@Dictionary{..} <- readMutVar . getDRef $ dict v <- value !~ i case f (Just v) of Nothing -> onNothing' d' i Just v' -> onFound' v' d' i onNothing dict = do d' <- readMutVar . getDRef $ dict case f Nothing of Nothing -> return () Just v' -> onFound' v' d' (-1) void $ atWithOrElse ht k onFound onNothing {-# INLINE alter #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- The expression (@'alterM' ht f k@) alters the value @x@ at @k@, or absence thereof. -- 'alterM' can be used to insert, delete, or update a value in a 'Dictionary' in the same @'PrimMonad' m@. alterM :: ( MVector ks k, MVector vs v, DeleteEntry ks, DeleteEntry vs , PrimMonad m, Hashable k, Eq k ) => Dictionary (PrimState m) ks k vs v -> (Maybe v -> m (Maybe v)) -> k -> m () alterM ht f k = do d@Dictionary{..} <- readMutVar . getDRef $ ht let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length buckets onFound' value' dict i = insertWithIndex targetBucket hashCode' k value' (getDRef ht) dict i onNothing' dict i = deleteWithIndex targetBucket hashCode' d k (-1) i onFound dict i = do d'@Dictionary{..} <- readMutVar . getDRef $ dict v <- value !~ i res <- f (Just v) case res of Nothing -> onNothing' d' i Just v' -> onFound' v' d' i onNothing dict = do d' <- readMutVar . getDRef $ dict res <- f Nothing case res of Nothing -> return () Just v' -> onFound' v' d' (-1) void $ atWithOrElse ht k onFound onNothing {-# INLINE alterM #-} -- * Combine -- | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. -- The union of two maps. -- If a key occurs in both maps, -- the mapping from the first will be the mapping in the result. union :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) union = unionWith const {-# INLINE union #-} -- | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. -- The union of two maps. -- The provided function (first argument) will be used to compute the result. unionWith :: (MVector ks k, MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (v -> v -> v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) unionWith f = unionWithKey (const f) {-# INLINE unionWith #-} -- | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. -- The union of two maps. -- If a key occurs in both maps, -- the provided function (first argument) will be used to compute the result. unionWithKey :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (k -> v -> v -> v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) unionWithKey f t1 t2 = do l1 <- length t1 l2 <- length t2 let smallest = min l1 l2 greatest = max l1 l2 g k v1 v2 = if smallest == l1 then f k v1 v2 else f k v2 v1 (tS, tG) = if smallest == l1 then (t1, t2) else (t2, t1) ht <- clone tG dictG <- readMutVar . getDRef $ tG dictS <- readMutVar . getDRef $ tS hcsS <- A.freeze . hashCode $ dictS let indices = catMaybes . zipWith collect [0 ..] . take smallest . A.primArrayToList $ hcsS collect i _ | hcsS !. i >= 0 = Just i | otherwise = Nothing go !i = do k <- key dictS !~ i v <- value dictS !~ i let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length (buckets dictG) onFound dict i = do d@Dictionary{..} <- readMutVar . getDRef $ dict vG <- value !~ i insertWithIndex targetBucket hashCode' k (g k v vG) (getDRef dict) d i onNothing dict = do d@Dictionary{..} <- readMutVar . getDRef $ dict insertWithIndex targetBucket hashCode' k v (getDRef dict) d =<< buckets ! targetBucket void $ atWithOrElse ht k onFound onNothing mapM_ go indices return ht {-# INLINE unionWithKey #-} -- * Difference and intersection -- | /O(n)/ in the best case, /O(n * m)/ in the worst case. -- Difference of two tables. Return elements of the first table -- not existing in the second. difference :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) difference a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> insert ht k v _ -> return () {-# INLINE difference #-} -- | /O(n)/ in the best case, /O(n * m)/ in the worst case. -- Difference with a combining function. When two equal keys are -- encountered, the combining function is applied to the values of these keys. -- If it returns 'Nothing', the element is discarded (proper set difference). If -- it returns (@'Just' y@), the element is updated with a new value @y@. differenceWith :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => (v -> w -> Maybe v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) differenceWith f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> insert ht k v Just w -> maybe (return ()) (insert ht k) (f v w) {-# INLINE differenceWith #-} -- | /O(n)/ in the best case, /O(n * m)/ in the worst case. -- Intersection of two maps. Return elements of the first -- map for keys existing in the second. intersection :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) intersection a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just _ -> insert ht k v {-# INLINE intersection #-} -- | Intersection of two maps. If a key occurs in both maps -- the provided function is used to combine the values from the two -- maps. intersectionWith :: (MVector ks k, MVector vs v1, MVector vs v2, MVector vs v3, PrimMonad m, Hashable k, Eq k) => (v1 -> v2 -> v3) -> Dictionary (PrimState m) ks k vs v1 -> Dictionary (PrimState m) ks k vs v2 -> m (Dictionary (PrimState m) ks k vs v3) intersectionWith f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just w -> insert ht k (f v w) {-# INLINE intersectionWith #-} -- | Intersection of two maps. If a key occurs in both maps -- the provided function is used to combine the values from the two -- maps. intersectionWithKey :: (MVector ks k, MVector vs v1, MVector vs v2, MVector vs v3, PrimMonad m, Hashable k, Eq k) => (k -> v1 -> v2 -> v3) -> Dictionary (PrimState m) ks k vs v1 -> Dictionary (PrimState m) ks k vs v2 -> m (Dictionary (PrimState m) ks k vs v3) intersectionWithKey f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just w -> insert ht k (f k v w) {-# INLINE intersectionWithKey #-} -- * List conversions -- | /O(n)/ Convert list to a 'Dictionary'. fromList :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => [(k, v)] -> m (Dictionary (PrimState m) ks k vs v) fromList kv = do ht <- initialize 1 mapM_ (uncurry (insert ht)) kv return ht {-# INLINE fromList #-} -- | /O(n)/ Convert 'Dictionary' to a list. toList :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (Dictionary (PrimState m) ks k vs v) -> m [(k, v)] toList DRef {..} = do Dictionary {..} <- readMutVar getDRef hcs <- A.freeze hashCode count <- refs ! getCount let go !i xs | i < 0 = return xs | hcs !. i < 0 = go (i - 1) xs | otherwise = do k <- key !~ i v <- value !~ i go (i - 1) ((k, v) : xs) {-# INLINE go #-} go (count - 1) [] {-# INLINE toList #-} -- * Extras primes :: UI.Vector Int primes = UI.fromList [ 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369, 8639249, 10367101, 12440537, 14928671, 17914409, 21497293, 25796759, 30956117, 37147349, 44576837, 53492207, 64190669, 77028803, 92434613, 110921543, 133105859, 159727031, 191672443, 230006941, 276008387, 331210079, 397452101, 476942527, 572331049, 686797261, 824156741, 988988137, 1186785773, 1424142949, 1708971541, 2050765853 ] getPrime :: Int -> Int getPrime n = fromJust $ UI.find (>= n) primes
klapaucius/vector-hashtables
src/Data/Vector/Hashtables/Internal.hs
bsd-3-clause
30,710
0
21
9,111
9,851
4,961
4,890
629
5
module System.Directory.AsEnv ( module System.Directory.AsEnv ) where -- generated by https://github.com/rvion/ride/tree/master/jetpack-gen import qualified System.Directory as I -- env_canonicalizePath :: FilePath -> IO FilePath env_canonicalizePath = I.canonicalizePath -- env_copyFile :: FilePath -> FilePath -> IO () env_copyFile = I.copyFile -- env_copyPermissions :: FilePath -> FilePath -> IO () env_copyPermissions = I.copyPermissions -- env_createDirectory :: FilePath -> IO () env_createDirectory = I.createDirectory -- env_createDirectoryIfMissing :: Bool -> FilePath -> IO () env_createDirectoryIfMissing = I.createDirectoryIfMissing -- env_doesDirectoryExist :: FilePath -> IO Bool env_doesDirectoryExist = I.doesDirectoryExist -- env_doesFileExist :: FilePath -> IO Bool env_doesFileExist = I.doesFileExist -- env_emptyPermissions :: Permissions env_emptyPermissions = I.emptyPermissions -- env_findExecutable :: String -> IO (Maybe FilePath) env_findExecutable = I.findExecutable -- env_findExecutables :: String -> IO [FilePath] env_findExecutables = I.findExecutables -- env_findFile :: [FilePath] -> String -> IO (Maybe FilePath) env_findFile = I.findFile -- env_findFiles :: [FilePath] -> String -> IO [FilePath] env_findFiles = I.findFiles -- env_findFilesWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO [FilePath] env_findFilesWith = I.findFilesWith -- env_getAppUserDataDirectory :: String -> IO FilePath env_getAppUserDataDirectory = I.getAppUserDataDirectory -- env_getCurrentDirectory :: IO FilePath env_getCurrentDirectory = I.getCurrentDirectory -- env_getDirectoryContents :: FilePath -> IO [FilePath] env_getDirectoryContents = I.getDirectoryContents -- env_getHomeDirectory :: IO FilePath env_getHomeDirectory = I.getHomeDirectory -- env_getModificationTime :: FilePath -> IO UTCTime env_getModificationTime = I.getModificationTime -- env_getPermissions :: FilePath -> IO Permissions env_getPermissions = I.getPermissions -- env_getTemporaryDirectory :: IO FilePath env_getTemporaryDirectory = I.getTemporaryDirectory -- env_getUserDocumentsDirectory :: IO FilePath env_getUserDocumentsDirectory = I.getUserDocumentsDirectory -- env_makeAbsolute :: FilePath -> IO FilePath env_makeAbsolute = I.makeAbsolute -- env_makeRelativeToCurrentDirectory :: FilePath -> IO FilePath env_makeRelativeToCurrentDirectory = I.makeRelativeToCurrentDirectory -- env_removeDirectory :: FilePath -> IO () env_removeDirectory = I.removeDirectory -- env_removeDirectoryRecursive :: FilePath -> IO () env_removeDirectoryRecursive = I.removeDirectoryRecursive -- env_removeFile :: FilePath -> IO () env_removeFile = I.removeFile -- env_renameDirectory :: FilePath -> FilePath -> IO () env_renameDirectory = I.renameDirectory -- env_renameFile :: FilePath -> FilePath -> IO () env_renameFile = I.renameFile -- env_setCurrentDirectory :: FilePath -> IO () env_setCurrentDirectory = I.setCurrentDirectory -- env_setOwnerExecutable :: Bool -> Permissions -> Permissions env_setOwnerExecutable = I.setOwnerExecutable -- env_setOwnerReadable :: Bool -> Permissions -> Permissions env_setOwnerReadable = I.setOwnerReadable -- env_setOwnerSearchable :: Bool -> Permissions -> Permissions env_setOwnerSearchable = I.setOwnerSearchable -- env_setOwnerWritable :: Bool -> Permissions -> Permissions env_setOwnerWritable = I.setOwnerWritable -- env_setPermissions :: FilePath -> Permissions -> IO () env_setPermissions = I.setPermissions type EnvPermissions = I.Permissions get_env_readable o = I.readable o set_env_readable x o = o { I.readable = x} get_env_writable o = I.writable o set_env_writable x o = o { I.writable = x} get_env_executable o = I.executable o set_env_executable x o = o { I.executable = x} get_env_searchable o = I.searchable o set_env_searchable x o = o { I.searchable = x}
rvion/ride
jetpack/src/System/Directory/AsEnv.hs
bsd-3-clause
3,847
0
6
476
437
261
176
46
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Yesod.Squealer ( module Yesod.Squealer , module Yesod.Squealer.Routes ) where import Control.Applicative (pure) import Data.Text (Text) import System.IO (IO) import Yesod.Core (YesodSubDispatch(yesodSubDispatch)) import Yesod.Core.Dispatch (mkYesodSubDispatch) import Yesod.Core.Types (HandlerT) import Yesod.Squealer.Handler.Column (getColumnR) import Yesod.Squealer.Handler.Database (getDatabaseR) import Yesod.Squealer.Handler.Rows (getRowsR, postRowsR) import Yesod.Squealer.Handler.Table (getTableR) import Yesod.Squealer.Handler.Version (getVersionR, putVersionR, deleteVersionR, getPredecessorR, getSuccessorR) import Yesod.Squealer.Routes instance YesodSquealer master ⇒ YesodSubDispatch Squealer (HandlerT master IO) where yesodSubDispatch = $(mkYesodSubDispatch resourcesSquealer) -- TODO: CORS headers, and Allow from the resource stuff. -- TODO: authorization, access restrictions… optionsDatabaseR ∷ SquealerHandler () optionsDatabaseR = pure () optionsTableR ∷ Text → SquealerHandler () optionsTableR _ = pure () optionsRowsR ∷ Text → SquealerHandler () optionsRowsR _ = pure () optionsColumnR ∷ Text → Text → SquealerHandler () optionsColumnR _ _ = pure () optionsVersionR ∷ Text → Text → SquealerHandler () optionsVersionR _ _ = pure () optionsPredecessorR ∷ Text → Text → SquealerHandler () optionsPredecessorR _ _ = pure () optionsSuccessorR ∷ Text → Text → SquealerHandler () optionsSuccessorR _ _ = pure ()
mgomezch/yesod-squealer
source/Yesod/Squealer.hs
bsd-3-clause
1,890
0
8
315
422
238
184
40
1
module Main where import qualified TestConnectFour as Thing -- import qualified UIConnectFour as Thing main = Thing.main
maueroats/teaching
docs/ap-cs/haskell/connect-four/testcases/Main.hs
gpl-3.0
136
0
5
32
18
13
5
3
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Glacier.CompleteMultipartUpload -- 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) -- -- You call this operation to inform Amazon Glacier that all the archive -- parts have been uploaded and that Amazon Glacier can now assemble the -- archive from the uploaded parts. After assembling and saving the archive -- to the vault, Amazon Glacier returns the URI path of the newly created -- archive resource. Using the URI path, you can then access the archive. -- After you upload an archive, you should save the archive ID returned to -- retrieve the archive at a later point. You can also get the vault -- inventory to obtain a list of archive IDs in a vault. For more -- information, see InitiateJob. -- -- In the request, you must include the computed SHA256 tree hash of the -- entire archive you have uploaded. For information about computing a -- SHA256 tree hash, see -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html Computing Checksums>. -- On the server side, Amazon Glacier also constructs the SHA256 tree hash -- of the assembled archive. If the values match, Amazon Glacier saves the -- archive to the vault; otherwise, it returns an error, and the operation -- fails. The ListParts operation returns a list of parts uploaded for a -- specific multipart upload. It includes checksum information for each -- uploaded part that can be used to debug a bad checksum issue. -- -- Additionally, Amazon Glacier also checks for any missing content ranges -- when assembling the archive, if missing content ranges are found, Amazon -- Glacier returns an error and the operation fails. -- -- Complete Multipart Upload is an idempotent operation. After your first -- successful complete multipart upload, if you call the operation again -- within a short period, the operation will succeed and return the same -- archive ID. This is useful in the event you experience a network issue -- that causes an aborted connection or receive a 500 server error, in -- which case you can repeat your Complete Multipart Upload request and get -- the same archive ID without creating duplicate archives. Note, however, -- that after the multipart upload completes, you cannot call the List -- Parts operation and the multipart upload will not appear in List -- Multipart Uploads response, even if idempotent complete is possible. -- -- An AWS account has full permission to perform all operations (actions). -- However, AWS Identity and Access Management (IAM) users don\'t have any -- permissions by default. You must grant them explicit permission to -- perform specific actions. For more information, see -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>. -- -- For conceptual information and underlying REST API, go to -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/uploading-archive-mpu.html Uploading Large Archives in Parts (Multipart Upload)> -- and -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-multipart-complete-upload.html Complete Multipart Upload> -- in the /Amazon Glacier Developer Guide/. -- -- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-CompleteMultipartUpload.html AWS API Reference> for CompleteMultipartUpload. module Network.AWS.Glacier.CompleteMultipartUpload ( -- * Creating a Request completeMultipartUpload , CompleteMultipartUpload -- * Request Lenses , cmuChecksum , cmuArchiveSize , cmuAccountId , cmuVaultName , cmuUploadId -- * Destructuring the Response , archiveCreationOutput , ArchiveCreationOutput -- * Response Lenses , acoArchiveId , acoChecksum , acoLocation ) where import Network.AWS.Glacier.Types import Network.AWS.Glacier.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Provides options to complete a multipart upload operation. This informs -- Amazon Glacier that all the archive parts have been uploaded and Amazon -- Glacier can now assemble the archive from the uploaded parts. After -- assembling and saving the archive to the vault, Amazon Glacier returns -- the URI path of the newly created archive resource. -- -- /See:/ 'completeMultipartUpload' smart constructor. data CompleteMultipartUpload = CompleteMultipartUpload' { _cmuChecksum :: !(Maybe Text) , _cmuArchiveSize :: !(Maybe Text) , _cmuAccountId :: !Text , _cmuVaultName :: !Text , _cmuUploadId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CompleteMultipartUpload' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cmuChecksum' -- -- * 'cmuArchiveSize' -- -- * 'cmuAccountId' -- -- * 'cmuVaultName' -- -- * 'cmuUploadId' completeMultipartUpload :: Text -- ^ 'cmuAccountId' -> Text -- ^ 'cmuVaultName' -> Text -- ^ 'cmuUploadId' -> CompleteMultipartUpload completeMultipartUpload pAccountId_ pVaultName_ pUploadId_ = CompleteMultipartUpload' { _cmuChecksum = Nothing , _cmuArchiveSize = Nothing , _cmuAccountId = pAccountId_ , _cmuVaultName = pVaultName_ , _cmuUploadId = pUploadId_ } -- | The SHA256 tree hash of the entire archive. It is the tree hash of -- SHA256 tree hash of the individual parts. If the value you specify in -- the request does not match the SHA256 tree hash of the final assembled -- archive as computed by Amazon Glacier, Amazon Glacier returns an error -- and the request fails. cmuChecksum :: Lens' CompleteMultipartUpload (Maybe Text) cmuChecksum = lens _cmuChecksum (\ s a -> s{_cmuChecksum = a}); -- | The total size, in bytes, of the entire archive. This value should be -- the sum of all the sizes of the individual parts that you uploaded. cmuArchiveSize :: Lens' CompleteMultipartUpload (Maybe Text) cmuArchiveSize = lens _cmuArchiveSize (\ s a -> s{_cmuArchiveSize = a}); -- | The 'AccountId' value is the AWS account ID of the account that owns the -- vault. You can either specify an AWS account ID or optionally a single -- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account -- ID associated with the credentials used to sign the request. If you use -- an account ID, do not include any hyphens (apos-apos) in the ID. cmuAccountId :: Lens' CompleteMultipartUpload Text cmuAccountId = lens _cmuAccountId (\ s a -> s{_cmuAccountId = a}); -- | The name of the vault. cmuVaultName :: Lens' CompleteMultipartUpload Text cmuVaultName = lens _cmuVaultName (\ s a -> s{_cmuVaultName = a}); -- | The upload ID of the multipart upload. cmuUploadId :: Lens' CompleteMultipartUpload Text cmuUploadId = lens _cmuUploadId (\ s a -> s{_cmuUploadId = a}); instance AWSRequest CompleteMultipartUpload where type Rs CompleteMultipartUpload = ArchiveCreationOutput request = postJSON glacier response = receiveEmpty (\ s h x -> ArchiveCreationOutput' <$> (h .#? "x-amz-archive-id") <*> (h .#? "x-amz-sha256-tree-hash") <*> (h .#? "Location")) instance ToHeaders CompleteMultipartUpload where toHeaders CompleteMultipartUpload'{..} = mconcat ["x-amz-sha256-tree-hash" =# _cmuChecksum, "x-amz-archive-size" =# _cmuArchiveSize] instance ToJSON CompleteMultipartUpload where toJSON = const (Object mempty) instance ToPath CompleteMultipartUpload where toPath CompleteMultipartUpload'{..} = mconcat ["/", toBS _cmuAccountId, "/vaults/", toBS _cmuVaultName, "/multipart-uploads/", toBS _cmuUploadId] instance ToQuery CompleteMultipartUpload where toQuery = const mempty
fmapfmapfmap/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/CompleteMultipartUpload.hs
mpl-2.0
8,530
0
13
1,651
744
466
278
92
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE CPP, OverloadedStrings #-} module IRTS.CodegenLLVM (codegenLLVM) where import IRTS.CodegenCommon import IRTS.Lang import IRTS.Simplified import IRTS.System import qualified Idris.Core.TT as TT import Idris.Core.TT (ArithTy(..), IntTy(..), NativeTy(..), nativeTyWidth, sUN) import Util.System import Paths_idris_llvm import System.FilePath import qualified LLVM import LLVM.Context import qualified LLVM.Target as Target import LLVM.AST import LLVM.AST.AddrSpace import LLVM.AST.DataLayout import qualified LLVM.AST.IntegerPredicate as IPred import qualified LLVM.AST.FloatingPointPredicate as FPred import qualified LLVM.AST.Linkage as L import qualified LLVM.AST.Visibility as V import qualified LLVM.AST.CallingConvention as CC import qualified LLVM.AST.Attribute as A import qualified LLVM.AST.Global as G import qualified LLVM.AST.Constant as C import qualified LLVM.AST.Float as F import qualified Data.ByteString as B import qualified Data.ByteString.Short as BS import Data.Char import Data.List import Data.Maybe import Data.String import qualified Data.Text as T import Data.Text.Encoding import Data.Word import Data.Map (Map) import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Vector.Unboxed as V import Control.Applicative import Control.Monad.RWS import Control.Monad.Writer import Control.Monad.State import Control.Monad.Error import qualified System.Info as SI (arch, os) import System.IO import System.Directory (removeFile) import System.Environment import System.FilePath ((</>)) import System.Process (rawSystem) import System.Exit (ExitCode(..)) import Debug.Trace data Target = Target { triple :: String, dataLayout :: DataLayout } type Machine = String -- These might want to live in a different file -- TODO These should probably be derived from the triple #if defined(FREEBSD) || defined(DRAGONFLY) extraLib = ["-L/usr/local/lib"] #else extraLib = [] #endif getRtsDir = do dir <- getDataDir return $ addTrailingPathSeparator dir #if defined(FREEBSD) || defined(DRAGONFLY) extraInclude = " -I/usr/local/include" #else extraInclude = "" #endif -- This is dumb, but needed. fromSBS :: BS.ShortByteString -> String fromSBS = T.unpack . decodeUtf8 . BS.fromShort getIncFlags = do dir <- getDataDir return $ ["-I" ++ dir </> "rts", extraInclude] -- FIXME: 'optimisation' is no longer a field in CodeGenerator, because -- optimisation levels at the idris command line are meant to -- indicate idris optimisation levels, not levels to pass through to -- back ends. We may need a way to pass back end specific options through. codegenLLVM :: CodeGenerator codegenLLVM ci = codegenLLVM' (simpleDecls ci) (targetTriple ci) (targetCPU ci) 2 (outputFile ci) (outputType ci) codegenLLVM' :: [(TT.Name, SDecl)] -> String -> -- target triple String -> -- target CPU Word -> -- Optimization degree FilePath -> -- output file name OutputType -> IO () codegenLLVM' defs triple cpu optimize file outty = do defTrip <- Target.getDefaultTargetTriple let layout = defaultDataLayout LittleEndian let ast = codegen file (Target (fromSBS defTrip) layout) (map snd defs) outputModule triple file outty ast failInIO :: ErrorT String IO a -> IO a failInIO = either fail return <=< runErrorT getCompiler = fromMaybe "clang" <$> lookupEnv "IDRIS_CLANG" outputModule :: Machine -> FilePath -> OutputType -> Module -> IO () outputModule _ file Raw m = do withContext $ \ctx -> LLVM.withModuleFromAST ctx m $ \mod -> LLVM.writeLLVMAssemblyToFile (LLVM.File file) mod outputModule _ file Object m = error "Not implemented yet" outputModule _ file Executable m = do withContext $ \ctx -> LLVM.withModuleFromAST ctx m $ \mod -> withTmpFile ".ll" $ \tf -> do LLVM.writeLLVMAssemblyToFile (LLVM.File tf) mod cc <- getCompiler rts <- getRtsDir _ <- rawSystem cc ([tf, rts ++ "libidris_rts.a", "-lgc", "-lgmp", "-o" ++ file]) return () withTmpFile :: String -> (FilePath -> IO a) -> IO a withTmpFile suffix f = do (path, handle) <- tempfile suffix hClose handle result <- f path removeFile path return result ierror :: String -> a ierror msg = error $ "INTERNAL ERROR: IRTS.CodegenLLVM: " ++ msg -- Type helpers --------------- glRef n = C.GlobalReference (tyRef n) (mkName n) globalRef n = ConstantOperand $ glRef n i8 = IntegerType 8 i16 = IntegerType 16 i32 = IntegerType 32 i64 = IntegerType 64 f32 = FloatingPointType FloatFP f64 = FloatingPointType DoubleFP -- pointers ptr t = PointerType t (AddrSpace 0) ptrI8 = ptr i8 ppI8 = ptr ptrI8 pmpz = PointerType mpzTy (AddrSpace 0) -- value helpers ---------------- ci32 v = ConstantOperand (C.Int 32 v) mainDef :: Global mainDef = functionDefaults { G.returnType = i32 , G.parameters = ([ Parameter i32 (mkName "argc") [] , Parameter ppI8 (mkName "argv") [] ], False) , G.name = mkName "main" , G.basicBlocks = [ BasicBlock (UnName 0) [ Do $ simpleCall "GC_init" [] -- Initialize Boehm GC , Do $ simpleCall "__gmp_set_memory_functions" [ globalRef "__idris_gmpMalloc" , globalRef "__idris_gmpRealloc" , globalRef "__idris_gmpFree" ] , Do $ Store False (globalRef "__idris_argc") (LocalReference i32 (mkName "argc")) Nothing 0 [] , Do $ Store False (globalRef "__idris_argv") (LocalReference ppI8 (mkName "argv")) Nothing 0 [] , UnName 1 := idrCall "{runMain_0}" [] ] (Do $ Ret (Just (ci32 0)) []) ]} initDefs :: Target -> [Definition] initDefs tgt = [ TypeDefinition (mkName "valTy") (Just $ StructureType False [ i32 , ArrayType 0 (ptr valueType) ]) , TypeDefinition (mkName "mpz") (Just $ StructureType False [i32, i32, ptr intPtr]) , GlobalDefinition $ globalVariableDefaults { G.name = mkName "__idris_intFmtStr" , G.linkage = L.Internal , G.isConstant = True , G.unnamedAddr = Just G.GlobalAddr , G.type' = ArrayType 5 (IntegerType 8) , G.initializer = Just $ C.Array (IntegerType 8) (map (C.Int 8 . fromIntegral . fromEnum) "%lld" ++ [C.Int 8 0]) } , rtsFun "intStr" ptrI8 [IntegerType 64] [ BasicBlock (UnName 0) [ UnName 1 := simpleCall "GC_malloc_atomic" [ConstantOperand (C.Int (tgtWordSize tgt) 21)] , UnName 2 := simpleCall "snprintf" [ LocalReference ptrI8 (UnName 1) , ConstantOperand (C.Int (tgtWordSize tgt) 21) , ConstantOperand $ C.GetElementPtr True (glRef "__idris_intFmtStr") [C.Int 32 0, C.Int 32 0] , LocalReference f64 (UnName 0) ] ] (Do $ Ret (Just (LocalReference ptrI8 (UnName 1))) []) ] , GlobalDefinition $ globalVariableDefaults { G.name = mkName "__idris_floatFmtStr" , G.linkage = L.Internal , G.isConstant = True , G.unnamedAddr = Just G.GlobalAddr , G.type' = ArrayType 3 (IntegerType 8) , G.initializer = Just $ C.Array (IntegerType 8) (map (C.Int 8 . fromIntegral . fromEnum) "%g" ++ [C.Int 8 0]) } , rtsFun "floatStr" ptrI8 [f64] [ BasicBlock (UnName 0) [ UnName 1 := simpleCall "GC_malloc_atomic" [ConstantOperand (C.Int (tgtWordSize tgt) 21)] , UnName 2 := simpleCall "snprintf" [ LocalReference ptrI8 (UnName 1) , ConstantOperand (C.Int (tgtWordSize tgt) 21) , ConstantOperand $ C.GetElementPtr True (glRef "__idris_floatFmtStr") [C.Int 32 0, C.Int 32 0] , LocalReference f64 (UnName 0) ] ] (Do $ Ret (Just (LocalReference ptrI8 (UnName 1))) []) ] , exfun "llvm.sin.f64" (f64) [ f64 ] False , exfun "llvm.cos.f64" (f64) [ f64 ] False , exfun "llvm.pow.f64" (f64) [ f64 ] False , exfun "llvm.ceil.f64" (f64) [ f64 ] False , exfun "llvm.floor.f64" (f64) [ f64 ] False , exfun "llvm.exp.f64" (f64) [ f64 ] False , exfun "llvm.log.f64" (f64) [ f64 ] False , exfun "llvm.sqrt.f64" (f64) [ f64 ] False , exfun "tan" (f64) [ f64 ] False , exfun "asin" (f64) [ f64 ] False , exfun "acos" (f64) [ f64 ] False , exfun "atan" (f64) [ f64 ] False , exfun "llvm.trap" VoidType [] False , exfun "memcpy" ptrI8 [ptrI8, ptrI8, intPtr] False , exfun "llvm.invariant.start" (PointerType (StructureType False []) (AddrSpace 0)) [IntegerType 64, ptrI8] False , exfun "snprintf" (IntegerType 32) [ptrI8, intPtr, ptrI8] True , exfun "strcmp" (IntegerType 32) [ptrI8, ptrI8] False , exfun "strlen" intPtr [ptrI8] False , exfun "GC_init" VoidType [] False , exfun "GC_malloc" ptrI8 [intPtr] False , exfun "GC_malloc_atomic" ptrI8 [intPtr] False , exfun "__gmp_set_memory_functions" VoidType [ PointerType (FunctionType ptrI8 [intPtr] False) (AddrSpace 0) , PointerType (FunctionType ptrI8 [ptrI8, intPtr, intPtr] False) (AddrSpace 0) , PointerType (FunctionType VoidType [ptrI8, intPtr] False) (AddrSpace 0) ] False , exfun "__gmpz_init" VoidType [pmpz] False , exfun "__gmpz_init_set_str" (IntegerType 32) [pmpz, ptrI8, IntegerType 32] False , exfun "__gmpz_get_str" ptrI8 [ptrI8, IntegerType 32, pmpz] False , exfun "__gmpz_get_ui" intPtr [pmpz] False , exfun "__gmpz_cmp" (IntegerType 32) [pmpz, pmpz] False , exfun "__gmpz_fdiv_q_2exp" VoidType [pmpz, pmpz, intPtr] False , exfun "__gmpz_mul_2exp" VoidType [pmpz, pmpz, intPtr] False , exfun "__gmpz_get_d" (f64) [pmpz] False , exfun "__gmpz_set_d" VoidType [pmpz, f64] False , exfun "mpz_get_ull" (IntegerType 64) [pmpz] False , exfun "mpz_init_set_ull" VoidType [pmpz, IntegerType 64] False , exfun "mpz_init_set_sll" VoidType [pmpz, IntegerType 64] False , exfun "__idris_strCons" ptrI8 [IntegerType 8, ptrI8] False , exfun "__idris_readStr" ptrI8 [ptrI8] False -- Actually pointer to FILE, but it's opaque anyway , exfun "__idris_readChars" ptrI8 [i32, ptrI8] False , exfun "__idris_writeStr" i32 [ptrI8, ptrI8] False , exfun "__idris_registerPtr" ptrI8 [ptrI8, i32] False , exfun "__idris_getRegisteredPtr" ptrI8 [ptrI8] False , exfun "__idris_sizeofPtr" i32 [] False , exfun "__idris_stdin" ptrI8 [] False , exfun "__idris_stdout" ptrI8 [] False , exfun "__idris_stderr" ptrI8 [] False , exfun "__idris_gmpMalloc" ptrI8 [intPtr] False , exfun "__idris_gmpRealloc" ptrI8 [ptrI8, intPtr, intPtr] False , exfun "__idris_gmpFree" VoidType [ptrI8, intPtr] False , exfun "__idris_strRev" ptrI8 [ptrI8] False , exfun "strtoll" (IntegerType 64) [ptrI8, PointerType ptrI8 (AddrSpace 0), IntegerType 32] False , exfun "strtod" (f64) [ptrI8, PointerType ptrI8 (AddrSpace 0)] False , exfun "putErr" VoidType [ptrI8] False , exfun "printf" i32 [ptrI8] True , exVar "__idris_argc" (IntegerType 32) , exVar "__idris_argv" (PointerType ptrI8 (AddrSpace 0)) , GlobalDefinition mainDef ] ++ map mpzBinFun ["add", "sub", "mul", "fdiv_q", "fdiv_r", "and", "ior", "xor"] where intPtr = IntegerType (tgtWordSize tgt) mpzBinFun n = exfun ("__gmpz_" ++ n) VoidType [pmpz, pmpz, pmpz] False rtsFun :: String -> Type -> [Type] -> [BasicBlock] -> Definition rtsFun name rty argtys def = GlobalDefinition $ functionDefaults { G.linkage = L.Internal , G.returnType = rty , G.parameters = (flip map argtys $ \ty -> Parameter ty (UnName 0) [], False) , G.name = mkName $ "__idris_" ++ name , G.basicBlocks = def } exfun :: String -> Type -> [Type] -> Bool -> Definition exfun name rty argtys vari = GlobalDefinition $ functionDefaults { G.returnType = rty , G.name = mkName name , G.parameters = (flip map argtys $ \ty -> Parameter ty (UnName 0) [], vari) } exVar :: String -> Type -> Definition exVar name ty = GlobalDefinition $ globalVariableDefaults { G.name = mkName name, G.type' = ty } codegen :: String -> Target -> [SDecl] -> Module codegen file tgt defs = Module { moduleName = "idris", moduleSourceFileName = fromString file, moduleDataLayout = Just . dataLayout $ tgt, moduleTargetTriple = Just (fromString $ triple tgt), moduleDefinitions = initDefs tgt ++ globals ++ gendefs } where (gendefs, _, globals) = runRWS (mapM cgDef defs) tgt initialMGS valueType :: Type valueType = NamedTypeReference (mkName "valTy") nullValue :: C.Constant nullValue = C.Null (PointerType valueType (AddrSpace 0)) primTy :: Type -> Type primTy inner = StructureType False [IntegerType 32, inner] mpzTy :: Type mpzTy = NamedTypeReference (mkName "mpz") tyRef :: String -> Type tyRef = NamedTypeReference . mkName conType :: Word64 -> Type conType nargs = StructureType False [ IntegerType 32 , ArrayType nargs (PointerType valueType (AddrSpace 0)) ] data MGS = MGS { mgsNextGlobalName :: Word , mgsForeignSyms :: Map String (FType, [FType]) } type Modgen = RWS Target [Definition] MGS initialMGS :: MGS initialMGS = MGS { mgsNextGlobalName = 0 , mgsForeignSyms = M.empty } cgDef :: SDecl -> Modgen Definition cgDef (SFun name argNames _ expr) = do nextGlobal <- gets mgsNextGlobalName existingForeignSyms <- gets mgsForeignSyms tgt <- ask let (_, CGS { nextGlobalName = nextGlobal', foreignSyms = foreignSyms' }, (allocas, bbs, globals)) = runRWS (do r <- cgExpr expr case r of Nothing -> terminate $ Unreachable [] Just r' -> terminate $ Ret (Just r') []) (CGR tgt (TT.showCG name)) (CGS 0 nextGlobal (mkName "begin") [] (map ((\n -> Just (LocalReference (NamedTypeReference n) n)) . mkName . TT.showCG) argNames) existingForeignSyms) entryTerm = case bbs of [] -> Do $ Ret Nothing [] BasicBlock n _ _:_ -> Do $ Br n [] tell globals put (MGS { mgsNextGlobalName = nextGlobal', mgsForeignSyms = foreignSyms' }) return . GlobalDefinition $ functionDefaults { G.linkage = L.Internal , G.callingConvention = CC.Fast , G.name = mkName (TT.showCG name) , G.returnType = PointerType valueType (AddrSpace 0) , G.parameters = (flip map argNames $ \argName -> Parameter (PointerType valueType (AddrSpace 0)) (mkName (TT.showCG argName)) [] , False) , G.basicBlocks = BasicBlock (mkName "entry") (map (\(n, t) -> n := Alloca t Nothing 0 []) allocas) entryTerm : bbs } type CGW = ([(Name, Type)], [BasicBlock], [Definition]) type Env = [Maybe Operand] data CGS = CGS { nextName :: Word , nextGlobalName :: Word , currentBlockName :: Name , instAccum :: [Named Instruction] , lexenv :: Env , foreignSyms :: Map String (FType, [FType]) } data CGR = CGR { target :: Target , funcName :: String } type Codegen = RWS CGR CGW CGS getFuncName :: Codegen String getFuncName = asks funcName getGlobalUnName :: Codegen Name getGlobalUnName = do i <- gets nextGlobalName modify $ \s -> s { nextGlobalName = 1 + i } return (UnName i) getUnName :: Codegen Name getUnName = do i <- gets nextName modify $ \s -> s { nextName = 1 + i } return (UnName i) getName :: String -> Codegen Name getName n = do i <- gets nextName modify $ \s -> s { nextName = 1 + i } return (mkName $ n ++ show i) alloca :: Name -> Type -> Codegen () alloca n t = tell ([(n, t)], [], []) terminate :: Terminator -> Codegen () terminate term = do name <- gets currentBlockName insts <- gets instAccum modify $ \s -> s { instAccum = ierror "Not in a block" , currentBlockName = ierror "Not in a block" } tell ([], [BasicBlock name insts (Do term)], []) newBlock :: Name -> Codegen () newBlock name = modify $ \s -> s { instAccum = [] , currentBlockName = name } inst :: Instruction -> Codegen Operand inst i = do n <- getUnName modify $ \s -> s { instAccum = instAccum s ++ [n := i] } return $ LocalReference (NamedTypeReference n) n ninst :: String -> Instruction -> Codegen Operand ninst name i = do n <- getName name modify $ \s -> s { instAccum = instAccum s ++ [n := i] } return $ LocalReference (NamedTypeReference n) n inst' :: Instruction -> Codegen () inst' i = modify $ \s -> s { instAccum = instAccum s ++ [Do i] } insts :: [Named Instruction] -> Codegen () insts is = modify $ \s -> s { instAccum = instAccum s ++ is } var :: LVar -> Codegen (Maybe Operand) var (Loc level) = (!! level) <$> gets lexenv var (Glob n) = return $ Just (globalRef (TT.showCG n)) binds :: Env -> Codegen (Maybe Operand) -> Codegen (Maybe Operand) binds vals cg = do envLen <- length <$> gets lexenv modify $ \s -> s { lexenv = lexenv s ++ vals } value <- cg modify $ \s -> s { lexenv = take envLen $ lexenv s } return value replaceElt :: Int -> a -> [a] -> [a] replaceElt _ val [] = error "replaceElt: Ran out of list" replaceElt 0 val (x:xs) = val:xs replaceElt n val (x:xs) = x : replaceElt (n-1) val xs alloc' :: Operand -> Codegen Operand alloc' size = inst $ simpleCall "GC_malloc" [size] allocAtomic' :: Operand -> Codegen Operand allocAtomic' size = inst $ simpleCall "GC_malloc_atomic" [size] alloc :: Type -> Codegen Operand alloc ty = do size <- sizeOf ty mem <- alloc' size inst $ BitCast mem (PointerType ty (AddrSpace 0)) [] allocAtomic :: Type -> Codegen Operand allocAtomic ty = do size <- sizeOf ty mem <- allocAtomic' size inst $ BitCast mem (PointerType ty (AddrSpace 0)) [] sizeOf :: Type -> Codegen Operand sizeOf ty = ConstantOperand . C.PtrToInt (C.GetElementPtr True (C.Null (PointerType ty (AddrSpace 0))) [C.Int 32 1]) . IntegerType <$> getWordSize loadInv :: Operand -> Instruction loadInv ptr = Load False ptr Nothing 0 [("invariant.load", MetadataNode [])] tgtWordSize :: Target -> Word32 tgtWordSize (Target { dataLayout = DataLayout { pointerLayouts = l } }) = fst . fromJust $ M.lookup (AddrSpace 0) l getWordSize :: Codegen Word32 getWordSize = tgtWordSize <$> asks target cgExpr :: SExp -> Codegen (Maybe Operand) cgExpr (SV v) = var v cgExpr (SApp tailcall fname args) = do argSlots <- mapM var args case sequence argSlots of Nothing -> return Nothing Just argVals -> do fn <- var (Glob fname) Just <$> inst ((idrCall (TT.showCG fname) argVals) { tailCallKind = if tailcall then Just Tail else Nothing }) cgExpr (SLet _ varExpr bodyExpr) = do val <- cgExpr varExpr binds [val] $ cgExpr bodyExpr cgExpr (SUpdate (Loc level) expr) = do val <- cgExpr expr modify $ \s -> s { lexenv = replaceElt level val (lexenv s) } return val cgExpr (SUpdate x expr) = cgExpr expr cgExpr (SCon _ tag name args) = do argSlots <- mapM var args case sequence argSlots of Nothing -> return Nothing Just argVals -> do let ty = conType . fromIntegral . length $ argVals con <- alloc ty tagPtr <- inst $ GetElementPtr True con [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 0)] [] inst' $ Store False tagPtr (ConstantOperand (C.Int 32 (fromIntegral tag))) Nothing 0 [] forM_ (zip argVals [0..]) $ \(arg, i) -> do ptr <- inst $ GetElementPtr True con [ ConstantOperand (C.Int 32 0) , ConstantOperand (C.Int 32 1) , ConstantOperand (C.Int 32 i)] [] inst' $ Store False ptr arg Nothing 0 [] ptrI8 <- inst $ BitCast con (PointerType (IntegerType 8) (AddrSpace 0)) [] inst' $ simpleCall "llvm.invariant.start" [ConstantOperand $ C.Int 64 (-1), ptrI8] Just <$> inst (BitCast con (PointerType valueType (AddrSpace 0)) []) cgExpr (SCase _ inspect alts) = do val <- var inspect case val of Nothing -> return Nothing Just v -> cgCase v alts cgExpr (SChkCase inspect alts) = do mval <- var inspect case mval of Nothing -> return Nothing Just val -> do endBBN <- getName "endChkCase" notNullBBN <- getName "notNull" originBlock <- gets currentBlockName isNull <- inst $ ICmp IPred.EQ val (ConstantOperand nullValue) [] terminate $ CondBr isNull endBBN notNullBBN [] newBlock notNullBBN ptr <- inst $ BitCast val (PointerType (IntegerType 32) (AddrSpace 0)) [] flag <- inst $ Load False ptr Nothing 0 [] isVal <- inst $ ICmp IPred.EQ flag (ConstantOperand (C.Int 32 (-1))) [] conBBN <- getName "constructor" terminate $ CondBr isVal endBBN conBBN [] newBlock conBBN result <- cgCase val alts caseExitBlock <- gets currentBlockName case result of Nothing -> do terminate $ Unreachable [] newBlock endBBN return $ Just val Just caseVal -> do terminate $ Br endBBN [] newBlock endBBN Just <$> inst (Phi (PointerType valueType (AddrSpace 0)) [(val, originBlock), (val, notNullBBN), (caseVal, caseExitBlock)] []) cgExpr (SProj conVar idx) = do val <- var conVar case val of Nothing -> return Nothing Just v -> do ptr <- inst $ GetElementPtr True v [ ConstantOperand (C.Int 32 0) , ConstantOperand (C.Int 32 1) , ConstantOperand (C.Int 32 (fromIntegral idx)) ] [] Just <$> inst (Load False ptr Nothing 0 []) cgExpr (SConst c) = Just <$> cgConst c cgExpr (SForeign rty (FStr fname) args) = do func <- ensureCDecl fname (toFType rty) (map (toFType . fst) args) argVals <- forM args $ \(fty, v) -> do v' <- var v case v' of Just val -> return $ Just (toFType fty, val) Nothing -> return Nothing case sequence argVals of Nothing -> return Nothing Just argVals' -> do argUVals <- mapM (uncurry unbox) argVals' result <- inst Call { tailCallKind = Nothing , callingConvention = CC.C , returnAttributes = [] , function = Right func , arguments = map (\v -> (v, [])) argUVals , functionAttributes = [] , metadata = [] } Just <$> box (toFType rty) result cgExpr (SOp fn args) = do argVals <- mapM var args case sequence argVals of Just ops -> Just <$> cgOp fn ops Nothing -> return Nothing cgExpr SNothing = return . Just . ConstantOperand $ nullValue cgExpr (SError msg) = do str <- addGlobal' (ArrayType (2 + fromIntegral (length msg)) (IntegerType 8)) (cgConst' (TT.Str (msg ++ "\n"))) inst' $ simpleCall "putErr" [ConstantOperand $ C.GetElementPtr True str [ C.Int 32 0 , C.Int 32 0]] inst' Call { tailCallKind = Just Tail , callingConvention = CC.C , returnAttributes = [] , function = Right $ globalRef "llvm.trap" , arguments = [] , functionAttributes = [Right A.NoReturn] , metadata = [] } return Nothing cgCase :: Operand -> [SAlt] -> Codegen (Maybe Operand) cgCase val alts = case find isConstCase alts of Just (SConstCase (TT.BI _) _) -> cgChainCase val defExp constAlts Just (SConstCase (TT.Str _) _) -> cgChainCase val defExp constAlts Just (SConstCase _ _) -> cgPrimCase val defExp constAlts Nothing -> cgConCase val defExp conAlts where defExp = getDefExp =<< find isDefCase alts constAlts = filter isConstCase alts conAlts = filter isConCase alts isConstCase (SConstCase {}) = True isConstCase _ = False isConCase (SConCase {}) = True isConCase _ = False isDefCase (SDefaultCase _) = True isDefCase _ = False getDefExp (SDefaultCase e) = Just e getDefExp _ = Nothing cgPrimCase :: Operand -> Maybe SExp -> [SAlt] -> Codegen (Maybe Operand) cgPrimCase caseValPtr defExp alts = do let caseTy = case head alts of SConstCase (TT.I _) _ -> IntegerType 32 SConstCase (TT.B8 _) _ -> IntegerType 8 SConstCase (TT.B16 _) _ -> IntegerType 16 SConstCase (TT.B32 _) _ -> IntegerType 32 SConstCase (TT.B64 _) _ -> IntegerType 64 SConstCase (TT.Fl _) _ -> f64 SConstCase (TT.Ch _) _ -> IntegerType 32 realPtr <- inst $ BitCast caseValPtr (PointerType (primTy caseTy) (AddrSpace 0)) [] valPtr <- inst $ GetElementPtr True realPtr [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 1)] [] caseVal <- inst $ Load False valPtr Nothing 0 [] defBlockName <- getName "default" exitBlockName <- getName "caseExit" namedAlts <- mapM (\a -> do n <- nameAlt defBlockName a; return (n, a)) alts terminate $ Switch caseVal defBlockName (map (\(n, SConstCase c _) -> (cgConst' c, n)) namedAlts) [] initEnv <- gets lexenv defResult <- cgDefaultAlt exitBlockName defBlockName defExp results <- forM namedAlts $ \(name, SConstCase _ exp) -> cgAlt initEnv exitBlockName name Nothing exp finishCase initEnv exitBlockName (defResult:results) cgConCase :: Operand -> Maybe SExp -> [SAlt] -> Codegen (Maybe Operand) cgConCase con defExp alts = do tagPtr <- inst $ GetElementPtr True con [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 0)] [] tag <- inst $ Load False tagPtr Nothing 0 [] defBlockName <- getName "default" exitBlockName <- getName "caseExit" namedAlts <- mapM (\a -> do n <- nameAlt defBlockName a; return (n, a)) alts terminate $ Switch tag defBlockName (map (\(n, SConCase _ tag _ _ _) -> (C.Int 32 (fromIntegral tag), n)) namedAlts) [] initEnv <- gets lexenv defResult <- cgDefaultAlt exitBlockName defBlockName defExp results <- forM namedAlts $ \(name, SConCase _ _ _ argns exp) -> cgAlt initEnv exitBlockName name (Just (con, map show argns)) exp finishCase initEnv exitBlockName (defResult:results) cgChainCase :: Operand -> Maybe SExp -> [SAlt] -> Codegen (Maybe Operand) cgChainCase caseValPtr defExp alts = do let (caseTy, comparator) = case head alts of SConstCase (TT.BI _) _ -> (FArith (ATInt ITBig), "__gmpz_cmp") SConstCase (TT.Str _) _ -> (FString, "strcmp") caseVal <- unbox caseTy caseValPtr defBlockName <- getName "default" exitBlockName <- getName "caseExit" namedAlts <- mapM (\a -> do n <- nameAlt defBlockName a; return (n, a)) alts initEnv <- gets lexenv results <- forM namedAlts $ \(name, SConstCase c e) -> do const <- unbox caseTy =<< cgConst c cmp <- inst $ simpleCall comparator [const, caseVal] cmpResult <- inst $ ICmp IPred.EQ cmp (ConstantOperand (C.Int 32 0)) [] elseName <- getName "else" terminate $ CondBr cmpResult name elseName [] result <- cgAlt initEnv exitBlockName name Nothing e newBlock elseName return result modify $ \s -> s { lexenv = initEnv } fname <- getFuncName defaultVal <- cgExpr (fromMaybe (SError $ "Inexhaustive case failure in " ++ fname) defExp) defaultBlock <- gets currentBlockName defaultEnv <- gets lexenv defResult <- case defaultVal of Just v -> do terminate $ Br exitBlockName [] return $ Just (v, defaultBlock, defaultEnv) Nothing -> do terminate $ Unreachable [] return Nothing finishCase initEnv exitBlockName (defResult:results) finishCase :: Env -> Name -> [Maybe (Operand, Name, Env)] -> Codegen (Maybe Operand) finishCase initEnv exitBlockName results = do let definedResults = mapMaybe id results case definedResults of [] -> do modify $ \s -> s { lexenv = initEnv } return Nothing xs -> do newBlock exitBlockName mergeEnvs $ map (\(_, altBlock, altEnv) -> (altBlock, altEnv)) xs Just <$> inst (Phi (PointerType valueType (AddrSpace 0)) (map (\(altVal, altBlock, _) -> (altVal, altBlock)) xs) []) cgDefaultAlt :: Name -> Name -> Maybe SExp -> Codegen (Maybe (Operand, Name, Env)) cgDefaultAlt exitName name exp = do newBlock name fname <- getFuncName val <- cgExpr (fromMaybe (SError $ "Inexhaustive case failure in " ++ fname) exp) env <- gets lexenv block <- gets currentBlockName case val of Just v -> do terminate $ Br exitName [] return $ Just (v, block, env) Nothing -> do terminate $ Unreachable [] return Nothing cgAlt :: Env -> Name -> Name -> Maybe (Operand, [String]) -> SExp -> Codegen (Maybe (Operand, Name, Env)) cgAlt initEnv exitBlockName name destr exp = do modify $ \s -> s { lexenv = initEnv } newBlock name locals <- case destr of Nothing -> return [] Just (con, argns) -> forM (zip argns [0..]) $ \(argName, i) -> do ptr <- inst $ GetElementPtr True con [ ConstantOperand (C.Int 32 0) , ConstantOperand (C.Int 32 1) , ConstantOperand (C.Int 32 i)] [] Just <$> ninst argName (Load False ptr Nothing 0 []) altVal <- binds locals $ cgExpr exp altEnv <- gets lexenv altBlock <- gets currentBlockName case altVal of Just v -> do terminate $ Br exitBlockName [] return $ Just (v, altBlock, altEnv) Nothing -> do terminate $ Unreachable [] return Nothing mergeEnvs :: [(Name, Env)] -> Codegen () mergeEnvs es = do let vars = transpose . map (\(block, env) -> map (\x -> (x, block)) env) $ es env <- forM vars $ \var -> case var of [] -> ierror "mergeEnvs: impossible" [(v, _)] -> return v vs@((v, _):_) | all (== v) (map fst vs) -> return v | otherwise -> let valid = map (\(a, b) -> (fromJust a, b)) . filter (isJust . fst) $ vs in Just <$> inst (Phi (PointerType valueType (AddrSpace 0)) valid []) modify $ \s -> s { lexenv = env } nameAlt :: Name -> SAlt -> Codegen Name nameAlt d (SDefaultCase _) = return d nameAlt _ (SConCase _ _ name _ _) = getName (show name) nameAlt _ (SConstCase const _) = getName (show const) isHeapFTy :: FType -> Bool isHeapFTy f = elem f [FString, FPtr, FAny, FArith (ATInt ITBig)] box :: FType -> Operand -> Codegen Operand box FUnit _ = return $ ConstantOperand nullValue box fty fval = do let ty = primTy (ftyToTy fty) val <- if isHeapFTy fty then alloc ty else allocAtomic ty tagptr <- inst $ GetElementPtr True val [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 0)] [] valptr <- inst $ GetElementPtr True val [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 1)] [] inst' $ Store False tagptr (ci32 (-1)) Nothing 0 [] inst' $ Store False valptr fval Nothing 0 [] p <- inst $ BitCast val ptrI8 [] inst' $ simpleCall "llvm.invariant.start" [ConstantOperand $ C.Int 64 (-1), p] inst $ BitCast val (PointerType valueType (AddrSpace 0)) [] unbox :: FType -> Operand -> Codegen Operand unbox FUnit x = return x unbox fty bval = do val <- inst $ BitCast bval (PointerType (primTy (ftyToTy fty)) (AddrSpace 0)) [] fvalptr <- inst $ GetElementPtr True val [ci32 0, ci32 1] [] inst $ Load False fvalptr Nothing 0 [] cgConst' :: TT.Const -> C.Constant cgConst' (TT.I i) = C.Int 32 (fromIntegral i) cgConst' (TT.B8 i) = C.Int 8 (fromIntegral i) cgConst' (TT.B16 i) = C.Int 16 (fromIntegral i) cgConst' (TT.B32 i) = C.Int 32 (fromIntegral i) cgConst' (TT.B64 i) = C.Int 64 (fromIntegral i) cgConst' (TT.BI i) = C.Array i8 (map (C.Int 8 . fromIntegral . fromEnum) (show i) ++ [C.Int 8 0]) cgConst' (TT.Fl f) = C.Float (F.Double f) cgConst' (TT.Ch c) = C.Int 32 . fromIntegral . fromEnum $ c cgConst' (TT.Str s) = C.Array i8 (map (C.Int 8 . fromIntegral . fromEnum) s ++ [C.Int 8 0]) cgConst' x = ierror $ "Unsupported constant: " ++ show x cgConst :: TT.Const -> Codegen Operand cgConst c@(TT.I _) = box (FArith (ATInt ITNative)) (ConstantOperand $ cgConst' c) cgConst c@(TT.B8 _) = box (FArith (ATInt (ITFixed IT8))) (ConstantOperand $ cgConst' c) cgConst c@(TT.B16 _) = box (FArith (ATInt (ITFixed IT16))) (ConstantOperand $ cgConst' c) cgConst c@(TT.B32 _) = box (FArith (ATInt (ITFixed IT32))) (ConstantOperand $ cgConst' c) cgConst c@(TT.B64 _) = box (FArith (ATInt (ITFixed IT64))) (ConstantOperand $ cgConst' c) cgConst c@(TT.Fl _) = box (FArith ATFloat) (ConstantOperand $ cgConst' c) cgConst c@(TT.Ch _) = box (FArith (ATInt ITChar)) (ConstantOperand $ cgConst' c) cgConst c@(TT.Str s) = do str <- addGlobal' (ArrayType (1 + fromIntegral (length s)) (IntegerType 8)) (cgConst' c) box FString (ConstantOperand $ C.GetElementPtr True str [C.Int 32 0, C.Int 32 0]) cgConst c@(TT.BI i) = do let stringRepLen = (if i < 0 then 2 else 1) + fromInteger (numDigits 10 i) str <- addGlobal' (ArrayType stringRepLen (IntegerType 8)) (cgConst' c) mpz <- alloc mpzTy inst $ simpleCall "__gmpz_init_set_str" [mpz , ConstantOperand $ C.GetElementPtr True str [ C.Int 32 0, C.Int 32 0] , ConstantOperand $ C.Int 32 10 ] box (FArith (ATInt ITBig)) mpz cgConst x = return $ ConstantOperand nullValue numDigits :: Integer -> Integer -> Integer numDigits b n = 1 + fst (ilog b (abs n)) where ilog b n | n < b = (0, n) | otherwise = let (e, r) = ilog (b*b) n in if r < b then (2*e, r) else (2*e+1, r `div` b) addGlobal :: Global -> Codegen () addGlobal def = tell ([], [], [GlobalDefinition def]) addGlobal' :: Type -> C.Constant -> Codegen C.Constant addGlobal' ty val = do name <- getGlobalUnName addGlobal $ globalVariableDefaults { G.name = name , G.linkage = L.Internal , G.unnamedAddr = Just G.GlobalAddr , G.isConstant = True , G.type' = ty , G.initializer = Just val } return $ C.GlobalReference ty name ensureCDecl :: String -> FType -> [FType] -> Codegen Operand ensureCDecl name rty argtys = do syms <- gets foreignSyms case M.lookup name syms of Nothing -> do addGlobal (ffunDecl name rty argtys) modify $ \s -> s { foreignSyms = M.insert name (rty, argtys) (foreignSyms s) } Just (rty', argtys') -> unless (rty == rty' && argtys == argtys') . fail $ "Mismatched type declarations for foreign symbol \"" ++ name ++ "\": " ++ show (rty, argtys) ++ " vs " ++ show (rty', argtys') return $ globalRef name ffunDecl :: String -> FType -> [FType] -> Global ffunDecl name rty argtys = functionDefaults { G.returnType = ftyToTy rty , G.name = mkName name , G.parameters = (flip map argtys $ \fty -> Parameter (ftyToTy fty) (UnName 0) [] , False) } ftyToTy :: FType -> Type ftyToTy (FArith (ATInt ITNative)) = i32 ftyToTy (FArith (ATInt ITBig)) = ptr mpzTy ftyToTy (FArith (ATInt (ITFixed ty))) = IntegerType (fromIntegral $ nativeTyWidth ty) ftyToTy (FArith (ATInt ITChar)) = i32 ftyToTy (FArith ATFloat) = f64 ftyToTy FString = ptrI8 ftyToTy FUnit = VoidType ftyToTy FPtr = ptrI8 ftyToTy FManagedPtr = ptrI8 ftyToTy FCData = ptrI8 ftyToTy FFunction = error "hello" ftyToTy FFunctionIO = error "hello" ftyToTy FAny = valueType -- Only use when known not to be ITBig itWidth :: IntTy -> Word32 itWidth ITNative = 32 itWidth ITChar = 32 itWidth (ITFixed x) = fromIntegral $ nativeTyWidth x itWidth x = ierror $ "itWidth: " ++ show x itConst :: IntTy -> Integer -> C.Constant itConst (ITFixed n) x = C.Int (fromIntegral $ nativeTyWidth n) x itConst ITNative x = itConst (ITFixed IT32) x itConst ITChar x = itConst (ITFixed IT32) x cgOp :: PrimFn -> [Operand] -> Codegen Operand cgOp (LTrunc ITBig ity) [x] = do nx <- unbox (FArith (ATInt ITBig)) x val <- inst $ simpleCall "mpz_get_ull" [nx] v <- case ity of (ITFixed IT64) -> return val _ -> inst $ Trunc val (ftyToTy (FArith (ATInt ity))) [] box (FArith (ATInt ity)) v cgOp (LZExt from ITBig) [x] = do nx <- unbox (FArith (ATInt from)) x nx' <- case from of (ITFixed IT64) -> return nx _ -> inst $ ZExt nx (IntegerType 64) [] mpz <- alloc mpzTy inst' $ simpleCall "mpz_init_set_ull" [mpz, nx'] box (FArith (ATInt ITBig)) mpz cgOp (LSExt from ITBig) [x] = do nx <- unbox (FArith (ATInt from)) x nx' <- case from of (ITFixed IT64) -> return nx _ -> inst $ SExt nx (IntegerType 64) [] mpz <- alloc mpzTy inst' $ simpleCall "mpz_init_set_sll" [mpz, nx'] box (FArith (ATInt ITBig)) mpz -- ITChar, ITNative, and IT32 all share representation cgOp (LChInt ITNative) [x] = return x cgOp (LIntCh ITNative) [x] = return x cgOp (LSLt (ATInt ITBig)) [x,y] = mpzCmp IPred.SLT x y cgOp (LSLe (ATInt ITBig)) [x,y] = mpzCmp IPred.SLE x y cgOp (LEq (ATInt ITBig)) [x,y] = mpzCmp IPred.EQ x y cgOp (LSGe (ATInt ITBig)) [x,y] = mpzCmp IPred.SGE x y cgOp (LSGt (ATInt ITBig)) [x,y] = mpzCmp IPred.SGT x y cgOp (LPlus (ATInt ITBig)) [x,y] = mpzBin "add" x y cgOp (LMinus (ATInt ITBig)) [x,y] = mpzBin "sub" x y cgOp (LTimes (ATInt ITBig)) [x,y] = mpzBin "mul" x y cgOp (LSDiv (ATInt ITBig)) [x,y] = mpzBin "fdiv_q" x y cgOp (LSRem (ATInt ITBig)) [x,y] = mpzBin "fdiv_r" x y cgOp (LAnd ITBig) [x,y] = mpzBin "and" x y cgOp (LOr ITBig) [x,y] = mpzBin "ior" x y cgOp (LXOr ITBig) [x,y] = mpzBin "xor" x y cgOp (LCompl ITBig) [x] = mpzUn "com" x cgOp (LSHL ITBig) [x,y] = mpzBit "mul_2exp" x y cgOp (LASHR ITBig) [x,y] = mpzBit "fdiv_q_2exp" x y cgOp (LTrunc ITNative (ITFixed to)) [x] | 32 >= nativeTyWidth to = iCoerce Trunc IT32 to x cgOp (LZExt ITNative (ITFixed to)) [x] | 32 <= nativeTyWidth to = iCoerce ZExt IT32 to x cgOp (LSExt ITNative (ITFixed to)) [x] | 32 <= nativeTyWidth to = iCoerce SExt IT32 to x cgOp (LTrunc (ITFixed from) ITNative) [x] | nativeTyWidth from >= 32 = iCoerce Trunc from IT32 x cgOp (LZExt (ITFixed from) ITNative) [x] | nativeTyWidth from <= 32 = iCoerce ZExt from IT32 x cgOp (LSExt (ITFixed from) ITNative) [x] | nativeTyWidth from <= 32 = iCoerce SExt from IT32 x cgOp (LTrunc (ITFixed from) (ITFixed to)) [x] | nativeTyWidth from > nativeTyWidth to = iCoerce Trunc from to x cgOp (LZExt (ITFixed from) (ITFixed to)) [x] | nativeTyWidth from < nativeTyWidth to = iCoerce ZExt from to x cgOp (LSExt (ITFixed from) (ITFixed to)) [x] | nativeTyWidth from < nativeTyWidth to = iCoerce SExt from to x cgOp (LSLt (ATInt ity)) [x,y] = iCmp ity IPred.SLT x y cgOp (LSLe (ATInt ity)) [x,y] = iCmp ity IPred.SLE x y cgOp (LLt ity) [x,y] = iCmp ity IPred.ULT x y cgOp (LLe ity) [x,y] = iCmp ity IPred.ULE x y cgOp (LEq (ATInt ity)) [x,y] = iCmp ity IPred.EQ x y cgOp (LSGe (ATInt ity)) [x,y] = iCmp ity IPred.SGE x y cgOp (LSGt (ATInt ity)) [x,y] = iCmp ity IPred.SGT x y cgOp (LGe ity) [x,y] = iCmp ity IPred.UGE x y cgOp (LGt ity) [x,y] = iCmp ity IPred.UGT x y cgOp (LPlus ty@(ATInt _)) [x,y] = binary ty x y (Add False False) cgOp (LMinus ty@(ATInt _)) [x,y] = binary ty x y (Sub False False) cgOp (LTimes ty@(ATInt _)) [x,y] = binary ty x y (Mul False False) cgOp (LSDiv ty@(ATInt _)) [x,y] = binary ty x y (SDiv False) cgOp (LSRem ty@(ATInt _)) [x,y] = binary ty x y SRem cgOp (LUDiv ity) [x,y] = binary (ATInt ity) x y (UDiv False) cgOp (LURem ity) [x,y] = binary (ATInt ity) x y URem cgOp (LAnd ity) [x,y] = binary (ATInt ity) x y And cgOp (LOr ity) [x,y] = binary (ATInt ity) x y Or cgOp (LXOr ity) [x,y] = binary (ATInt ity) x y Xor cgOp (LCompl ity) [x] = unary (ATInt ity) x (Xor . ConstantOperand $ itConst ity (-1)) cgOp (LSHL ity) [x,y] = binary (ATInt ity) x y (Shl False False) cgOp (LLSHR ity) [x,y] = binary (ATInt ity) x y (LShr False) cgOp (LASHR ity) [x,y] = binary (ATInt ity) x y (AShr False) cgOp (LSLt ATFloat) [x,y] = fCmp FPred.OLT x y cgOp (LSLe ATFloat) [x,y] = fCmp FPred.OLE x y cgOp (LEq ATFloat) [x,y] = fCmp FPred.OEQ x y cgOp (LSGe ATFloat) [x,y] = fCmp FPred.OGE x y cgOp (LSGt ATFloat) [x,y] = fCmp FPred.OGT x y cgOp (LPlus ATFloat) [x,y] = binary ATFloat x y (FAdd NoFastMathFlags) cgOp (LMinus ATFloat) [x,y] = binary ATFloat x y (FSub NoFastMathFlags) cgOp (LTimes ATFloat) [x,y] = binary ATFloat x y (FMul NoFastMathFlags) cgOp (LSDiv ATFloat) [x,y] = binary ATFloat x y (FDiv NoFastMathFlags) cgOp LFExp [x] = nunary ATFloat "llvm.exp.f64" x cgOp LFLog [x] = nunary ATFloat "llvm.log.f64" x cgOp LFSin [x] = nunary ATFloat "llvm.sin.f64" x cgOp LFCos [x] = nunary ATFloat "llvm.cos.f64" x cgOp LFTan [x] = nunary ATFloat "tan" x cgOp LFASin [x] = nunary ATFloat "asin" x cgOp LFACos [x] = nunary ATFloat "acos" x cgOp LFATan [x] = nunary ATFloat "atan" x cgOp LFSqrt [x] = nunary ATFloat "llvm.sqrt.f64" x cgOp LFFloor [x] = nunary ATFloat "llvm.floor.f64" x cgOp LFCeil [x] = nunary ATFloat "llvm.ceil.f64" x cgOp LFNegate [x] = do z <- box (FArith ATFloat) (ConstantOperand $ C.Float $ F.Double (-0.0)) binary ATFloat z x (FSub NoFastMathFlags) cgOp (LIntFloat ITBig) [x] = do x' <- unbox (FArith (ATInt ITBig)) x uflt <- inst $ simpleCall "__gmpz_get_d" [ x' ] box (FArith ATFloat) uflt cgOp (LIntFloat ity) [x] = do x' <- unbox (FArith (ATInt ity)) x x'' <- inst $ SIToFP x' (f64) [] box (FArith ATFloat) x'' cgOp (LFloatInt ITBig) [x] = do x' <- unbox (FArith ATFloat) x z <- alloc mpzTy inst' $ simpleCall "__gmpz_init" [z] inst' $ simpleCall "__gmpz_set_d" [ z, x' ] box (FArith (ATInt ITBig)) z cgOp (LFloatInt ity) [x] = do x' <- unbox (FArith ATFloat) x x'' <- inst $ FPToSI x' (ftyToTy $ cmpResultTy ity) [] box (FArith (ATInt ity)) x'' cgOp LFloatStr [x] = do x' <- unbox (FArith ATFloat) x ustr <- inst (idrCall "__idris_floatStr" [x']) box FString ustr cgOp LStrFloat [s] = do ns <- unbox FString s nx <- inst $ simpleCall "strtod" [ns , ConstantOperand $ C.Null (PointerType (PointerType (IntegerType 8) (AddrSpace 0)) (AddrSpace 0)) ] box (FArith ATFloat) nx cgOp LNoOp xs = return $ last xs cgOp (LBitCast from to) [x] = do nx <- unbox (FArith from) x nx' <- inst $ BitCast nx (ftyToTy (FArith to)) [] box (FArith to) nx' cgOp LStrEq [x,y] = do x' <- unbox FString x y' <- unbox FString y cmp <- inst $ simpleCall "strcmp" [x', y'] flag <- inst $ ICmp IPred.EQ cmp (ConstantOperand (C.Int 32 0)) [] val <- inst $ ZExt flag (IntegerType 32) [] box (FArith (ATInt (ITFixed IT32))) val cgOp LStrLt [x,y] = do nx <- unbox FString x ny <- unbox FString y cmp <- inst $ simpleCall "strcmp" [nx, ny] flag <- inst $ ICmp IPred.ULT cmp (ConstantOperand (C.Int 32 0)) [] val <- inst $ ZExt flag (IntegerType 32) [] box (FArith (ATInt (ITFixed IT32))) val cgOp (LIntStr ITBig) [x] = do x' <- unbox (FArith (ATInt ITBig)) x ustr <- inst $ simpleCall "__gmpz_get_str" [ ConstantOperand (C.Null (PointerType (IntegerType 8) (AddrSpace 0))) , ConstantOperand (C.Int 32 10) , x' ] box FString ustr cgOp (LIntStr ity) [x] = do x' <- unbox (FArith (ATInt ity)) x x'' <- if itWidth ity < 64 then inst $ SExt x' (IntegerType 64) [] else return x' box FString =<< inst (idrCall "__idris_intStr" [x'']) cgOp (LStrInt ITBig) [s] = do ns <- unbox FString s mpz <- alloc mpzTy inst $ simpleCall "__gmpz_init_set_str" [mpz, ns, ConstantOperand $ C.Int 32 10] box (FArith (ATInt ITBig)) mpz cgOp (LStrInt ity) [s] = do ns <- unbox FString s nx <- inst $ simpleCall "strtoll" [ns , ConstantOperand $ C.Null ppI8 , ConstantOperand $ C.Int 32 10 ] nx' <- case ity of (ITFixed IT64) -> return nx _ -> inst $ Trunc nx (IntegerType (itWidth ity)) [] box (FArith (ATInt ity)) nx' cgOp LStrConcat [x,y] = cgStrCat x y cgOp LStrCons [c,s] = do nc <- unbox (FArith (ATInt ITChar)) c ns <- unbox FString s nc' <- inst $ Trunc nc (IntegerType 8) [] r <- inst $ simpleCall "__idris_strCons" [nc', ns] box FString r cgOp LStrHead [c] = do s <- unbox FString c c <- inst $ Load False s Nothing 0 [] c' <- inst $ ZExt c (IntegerType 32) [] box (FArith (ATInt ITChar)) c' cgOp LStrIndex [s, i] = do ns <- unbox FString s ni <- unbox (FArith (ATInt (ITFixed IT32))) i p <- inst $ GetElementPtr True ns [ni] [] c <- inst $ Load False p Nothing 0 [] c' <- inst $ ZExt c (IntegerType 32) [] box (FArith (ATInt ITChar)) c' cgOp LStrTail [c] = do s <- unbox FString c c <- inst $ GetElementPtr True s [ConstantOperand $ C.Int 32 1] [] box FString c cgOp LStrLen [s] = do ns <- unbox FString s len <- inst $ simpleCall "strlen" [ns] ws <- getWordSize len' <- case ws of 32 -> return len x | x > 32 -> inst $ Trunc len (IntegerType 32) [] | x < 32 -> inst $ ZExt len (IntegerType 32) [] box (FArith (ATInt (ITFixed IT32))) len' cgOp LStrRev [s] = do ns <- unbox FString s box FString =<< inst (simpleCall "__idris_strRev" [ns]) cgOp LStrSubstr [x, y, z] = ignore cgOp LReadStr [_] = do np <- inst $ simpleCall "__idris_stdin" [] s <- inst $ simpleCall "__idris_readStr" [np] box FString s cgOp LWriteStr [_,p] = do np <- unbox FPtr p s <- inst $ simpleCall "printf" [np] box (FArith (ATInt ITNative)) s cgOp LSystemInfo [x] = ignore cgOp LCrash [x] = ignore cgOp LFork [x] = ignore cgOp LPar [x] = ignore -- TODO: ignored primitives, fill in cgOp (LExternal pr) [_, x] | pr == sUN "prim__readFile" = do sp <- unbox FPtr x s <- inst $ simpleCall "__idris_readStr" [sp] box FString s cgOp (LExternal pr) [_,len,x] | pr == sUN "prim__readChars" = do l <- unbox (FArith (ATInt ITNative)) len sp <- unbox FPtr x s <- inst $ simpleCall "__idris_readChars" [l, sp] box FString s cgOp (LExternal pr) [_, x, s] | pr == sUN "prim__writeFile" = do f <- unbox FPtr x sp <- unbox FString s i <- inst $ simpleCall "__idris_writeStr" [f, sp] box (FArith (ATInt ITNative)) i cgOp (LExternal pr) [] | pr == sUN "prim__stdin" = do i <- inst $ simpleCall "__idris_stdin" [] box FPtr i cgOp (LExternal pr) [] | pr == sUN "prim__stdout" = do i <- inst $ simpleCall "__idris_stdout" [] box FPtr i cgOp (LExternal pr) [] | pr == sUN "prim__stderr" = do i <- inst $ simpleCall "__idris_stdout" [] box FPtr i cgOp (LExternal pr) [p] | pr == sUN "prim__asPtr" = do sp <- unbox FManagedPtr p s <- inst $ simpleCall "__idris_getRegisteredPtr" [sp] box FPtr s cgOp (LExternal pr) [] | pr == sUN "prim__null" = box FPtr (ConstantOperand $ C.Null ptrI8) cgOp (LExternal pr) [_] | pr == sUN "prim__vm" = ignore cgOp (LExternal pr) [x, y] | pr == sUN "prim__eqPtr" = ptrEq x y cgOp (LExternal pr) [x, y] | pr == sUN "prim__eqManagedPtr" = do a <- unbox FPtr x b <- unbox FPtr y c <- inst $ Load False a Nothing 0 [] d <- inst $ Load False b Nothing 0 [] e <- inst $ ICmp IPred.EQ c d [] r <- inst $ SExt e i32 [] box (FArith (ATInt ITNative)) r cgOp (LExternal pr) [p, i] | pr == sUN "prim__registerPtr" = do l <- unbox (FArith (ATInt ITNative)) i sp <- unbox FPtr p s <- inst $ simpleCall "__idris_registerPtr" [sp, l] box FManagedPtr s cgOp (LExternal pr) [_, p, o] | pr == sUN "prim__peek8" = peek (FArith (ATInt (ITFixed IT8))) p o cgOp (LExternal pr) [_, p, o, x] | pr == sUN "prim__poke8" = poke (FArith (ATInt (ITFixed IT8))) p o x cgOp (LExternal pr) [_, p, o] | pr == sUN "prim__peek16" = peek (FArith (ATInt (ITFixed IT16))) p o cgOp (LExternal pr) [_, p, o, x] | pr == sUN "prim__poke16" = poke (FArith (ATInt (ITFixed IT16))) p o x cgOp (LExternal pr) [_, p, o] | pr == sUN "prim__peek32" = peek (FArith (ATInt (ITFixed IT32))) p o cgOp (LExternal pr) [_, p, o, x] | pr == sUN "prim__poke32" = poke (FArith (ATInt (ITFixed IT32))) p o x cgOp (LExternal pr) [_, p, o] | pr == sUN "prim__peek64" = peek (FArith (ATInt (ITFixed IT64))) p o cgOp (LExternal pr) [_, p, o, x] | pr == sUN "prim__poke64" = poke (FArith (ATInt (ITFixed IT64))) p o x cgOp (LExternal pr) [_, p, o] | pr == sUN "prim__peekPtr" = peek FPtr p o cgOp (LExternal pr) [_, p, o, x] | pr == sUN "prim__pokePtr" = poke FPtr p o x cgOp (LExternal pr) [_, p, o] | pr == sUN "prim__peekDouble" = peek (FArith ATFloat) p o cgOp (LExternal pr) [_, p, o, x] | pr == sUN "prim__pokeDouble" = poke (FArith ATFloat) p o x cgOp (LExternal pr) [_, p, o] | pr == sUN "prim__peekSingle" = peekSingle p o cgOp (LExternal pr) [_, p, o, x] | pr == sUN "prim__pokeSingle" = pokeSingle p o x cgOp (LExternal pr) [p, n] | pr == sUN "prim__ptrOffset" = do pt <- unbox FPtr p o <- unbox (FArith (ATInt ITNative)) n ws <- getWordSize offz <- inst $ ZExt o (IntegerType ws) [] i <- inst $ PtrToInt pt (IntegerType ws) [] offi <- inst $ Add False True i offz [] offp <- inst $ IntToPtr offi ptrI8 [] box FPtr offp cgOp (LExternal pr) [] | pr == sUN "prim__sizeofPtr" = do i <- inst $ simpleCall "__idris_sizeofPtr" [] box (FArith (ATInt ITNative)) i cgOp prim args = ierror $ "Unimplemented primitive: <" ++ show prim ++ ">(" ++ intersperse ',' (take (length args) ['a'..]) ++ ")" ignore = return $ ConstantOperand nullValue iCoerce :: (Operand -> Type -> InstructionMetadata -> Instruction) -> NativeTy -> NativeTy -> Operand -> Codegen Operand iCoerce _ from to x | from == to = return x iCoerce operator from to x = do x' <- unbox (FArith (ATInt (ITFixed from))) x x'' <- inst $ operator x' (ftyToTy (FArith (ATInt (ITFixed to)))) [] box (FArith (ATInt (ITFixed to))) x'' cgStrCat :: Operand -> Operand -> Codegen Operand cgStrCat x y = do x' <- unbox FString x y' <- unbox FString y xlen <- inst $ simpleCall "strlen" [x'] ylen <- inst $ simpleCall "strlen" [y'] zlen <- inst $ Add False True xlen ylen [] ws <- getWordSize total <- inst $ Add False True zlen (ConstantOperand (C.Int ws 1)) [] mem <- allocAtomic' total inst $ simpleCall "memcpy" [mem, x', xlen] i <- inst $ PtrToInt mem (IntegerType ws) [] offi <- inst $ Add False True i xlen [] offp <- inst $ IntToPtr offi (PointerType (IntegerType 8) (AddrSpace 0)) [] inst $ simpleCall "memcpy" [offp, y', ylen] j <- inst $ PtrToInt offp (IntegerType ws) [] offj <- inst $ Add False True j ylen [] end <- inst $ IntToPtr offj (PointerType (IntegerType 8) (AddrSpace 0)) [] inst' $ Store False end (ConstantOperand (C.Int 8 0)) Nothing 0 [] box FString mem binary :: ArithTy -> Operand -> Operand -> (Operand -> Operand -> InstructionMetadata -> Instruction) -> Codegen Operand binary ty x y instCon = do nx <- unbox (FArith ty) x ny <- unbox (FArith ty) y nr <- inst $ instCon nx ny [] box (FArith ty) nr unary :: ArithTy -> Operand -> (Operand -> InstructionMetadata -> Instruction) -> Codegen Operand unary ty x instCon = do nx <- unbox (FArith ty) x nr <- inst $ instCon nx [] box (FArith ty) nr nunary :: ArithTy -> String -> Operand -> Codegen Operand nunary ty name x = do nx <- unbox (FArith ty) x nr <- inst $ simpleCall name [nx] box (FArith ty) nr iCmp :: IntTy -> IPred.IntegerPredicate -> Operand -> Operand -> Codegen Operand iCmp ity pred x y = do nx <- unbox (FArith (ATInt ity)) x ny <- unbox (FArith (ATInt ity)) y nr <- inst $ ICmp pred nx ny [] nr' <- inst $ SExt nr (ftyToTy $ cmpResultTy ity) [] box (cmpResultTy ity) nr' fCmp :: FPred.FloatingPointPredicate -> Operand -> Operand -> Codegen Operand fCmp pred x y = do nx <- unbox (FArith ATFloat) x ny <- unbox (FArith ATFloat) y nr <- inst $ FCmp pred nx ny [] box (FArith (ATInt (ITFixed IT32))) nr cmpResultTy :: IntTy -> FType -- cmpResultTy v@(ITVec _ _) = FArith (ATInt v) cmpResultTy _ = FArith (ATInt (ITFixed IT32)) mpzBin :: String -> Operand -> Operand -> Codegen Operand mpzBin name x y = do nx <- unbox (FArith (ATInt ITBig)) x ny <- unbox (FArith (ATInt ITBig)) y nz <- alloc mpzTy inst' $ simpleCall "__gmpz_init" [nz] inst' $ simpleCall ("__gmpz_" ++ name) [nz, nx, ny] box (FArith (ATInt ITBig)) nz mpzBit :: String -> Operand -> Operand -> Codegen Operand mpzBit name x y = do nx <- unbox (FArith (ATInt ITBig)) x ny <- unbox (FArith (ATInt ITBig)) y bitcnt <- inst $ simpleCall "__gmpz_get_ui" [ny] nz <- alloc mpzTy inst' $ simpleCall "__gmpz_init" [nz] inst' $ simpleCall ("__gmpz_" ++ name) [nz, nx, bitcnt] box (FArith (ATInt ITBig)) nz mpzUn :: String -> Operand -> Codegen Operand mpzUn name x = do nx <- unbox (FArith (ATInt ITBig)) x nz <- alloc mpzTy inst' $ simpleCall "__gmpz_init" [nz] inst' $ simpleCall ("__gmpz_" ++ name) [nz, nx] box (FArith (ATInt ITBig)) nz mpzCmp :: IPred.IntegerPredicate -> Operand -> Operand -> Codegen Operand mpzCmp pred x y = do nx <- unbox (FArith (ATInt ITBig)) x ny <- unbox (FArith (ATInt ITBig)) y cmp <- inst $ simpleCall "__gmpz_cmp" [nx, ny] result <- inst $ ICmp pred cmp (ConstantOperand (C.Int 32 0)) [] i <- inst $ ZExt result (IntegerType 32) [] box (FArith (ATInt (ITFixed IT32))) i ptrEq x y = do a <- unbox FPtr x b <- unbox FPtr y e <- inst $ ICmp IPred.EQ a b [] r <- inst $ SExt e i32 [] box (FArith (ATInt ITNative)) r peek t p o = do pt <- unbox FPtr p off <- unbox (FArith (ATInt ITNative)) o ws <- getWordSize offz <- inst $ ZExt off (IntegerType ws) [] i <- inst $ PtrToInt pt (IntegerType ws) [] offi <- inst $ Add False True i offz [] offp <- inst $ IntToPtr offi (ptr $ ftyToTy t) [] r <- inst $ Load False offp Nothing 0 [] box t r poke t p o x = do pt <- unbox FPtr p off <- unbox (FArith (ATInt ITNative)) o v <- unbox t x ws <- getWordSize offz <- inst $ ZExt off (IntegerType ws) [] i <- inst $ PtrToInt pt (IntegerType ws) [] offi <- inst $ Add False True i offz [] offp <- inst $ IntToPtr offi (ptr $ ftyToTy t) [] inst' $ Store False offp v Nothing 0 [] box (FArith (ATInt ITNative)) (ci32 0) peekSingle p o = do pt <- unbox FPtr p off <- unbox (FArith (ATInt ITNative)) o ws <- getWordSize offz <- inst $ ZExt off (IntegerType ws) [] i <- inst $ PtrToInt pt (IntegerType ws) [] offi <- inst $ Add False True i offz [] offp <- inst $ IntToPtr offi (ptr f32) [] r <- inst $ Load False offp Nothing 0 [] d <- inst $ FPExt r f64 [] box (FArith ATFloat) d pokeSingle p o x = do pt <- unbox FPtr p off <- unbox (FArith (ATInt ITNative)) o v <- unbox (FArith ATFloat) x s <- inst $ FPTrunc v f32 [] ws <- getWordSize offz <- inst $ ZExt off (IntegerType ws) [] i <- inst $ PtrToInt pt (IntegerType ws) [] offi <- inst $ Add False True i offz [] offp <- inst $ IntToPtr offi (ptr $ f32) [] inst' $ Store False offp s Nothing 0 [] box (FArith (ATInt ITNative)) (ci32 0) -- Deconstruct the Foreign type in the defunctionalised expression and build -- a foreign type description. toAType (FCon i) | i == sUN "C_IntChar" = ATInt ITChar | i == sUN "C_IntNative" = ATInt ITNative | i == sUN "C_IntBits8" = ATInt (ITFixed IT8) | i == sUN "C_IntBits16" = ATInt (ITFixed IT16) | i == sUN "C_IntBits32" = ATInt (ITFixed IT32) | i == sUN "C_IntBits64" = ATInt (ITFixed IT64) toAType t = error (show t ++ " not defined in toAType") toFType (FCon c) | c == sUN "C_Str" = FString | c == sUN "C_Float" = FArith ATFloat | c == sUN "C_Ptr" = FPtr | c == sUN "C_MPtr" = FManagedPtr | c == sUN "C_CData" = FCData | c == sUN "C_Unit" = FUnit toFType (FApp c [_,ity]) | c == sUN "C_IntT" = FArith (toAType ity) | c == sUN "C_FnT" = toFunType ity toFType (FApp c [_]) | c == sUN "C_Any" = FAny toFType t = FAny toFunType (FApp c [_,ity]) | c == sUN "C_FnBase" = FFunction | c == sUN "C_FnIO" = FFunctionIO toFunType (FApp c [_,_,_,ity]) | c == sUN "C_Fn" = toFunType ity toFunType _ = FAny simpleCall :: String -> [Operand] -> Instruction simpleCall name args = Call { tailCallKind = Nothing , callingConvention = CC.C , returnAttributes = [] , function = Right $ globalRef name , arguments = map (\x -> (x, [])) args , functionAttributes = [] , metadata = [] } idrCall :: String -> [Operand] -> Instruction idrCall name args = Call { tailCallKind = Nothing , callingConvention = CC.Fast , returnAttributes = [] , function = Right $ globalRef name , arguments = map (\x -> (x, [])) args , functionAttributes = [] , metadata = [] } assert :: Operand -> String -> Codegen () assert condition message = do passed <- getName "assertPassed" failed <- getName "assertFailed" terminate $ CondBr condition passed failed [] newBlock failed cgExpr (SError message) terminate $ Unreachable [] newBlock passed
idris-hackers/idris-llvm
src/IRTS/CodegenLLVM.hs
bsd-3-clause
59,050
3
24
16,113
24,637
12,201
12,436
1,289
11
{-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------------------- -- | -- Module : Data.Rakhana -- Copyright : (C) 2014 Yorick Laupa -- License : (see the file LICENSE) -- -- Maintainer : Yorick Laupa <[email protected]> -- Stability : provisional -- Portability : non-portable -- -------------------------------------------------------------------------------- module Data.Rakhana ( module Data.Rakhana.Content.Page , Dictionary , Drive , Header , Object , NReq , NResp , Number , NurseryException(..) , Pages , Playground , Reference , Root , Stream , Tape , TReq , TResp , XRefException(..) -- Prisms , _Array , _Boolean , _Bytes , _Dict , _Name , _Natural , _Number , _Real , _Ref , _Stream , dictKey , nth -- Lenses , streamDict , streamPos -- Nursery , nurseryGetInfo , nurseryGetHeader , nurseryGetPages , nurseryLoadStreamData , nurseryGetReferences , nurseryResolve , withNursery -- Tape , driveBackward , driveBottom , driveDiscard , driveForward , driveGet , driveGetLazy , driveGetSeek , driveModifySeek , drivePeek , driveSeek , driveTop , fileTape , runDrive ) where -------------------------------------------------------------------------------- import Data.Rakhana.Content.Page import Data.Rakhana.Internal.Types import Data.Rakhana.Tape import Data.Rakhana.Nursery
erantapaa/rakhana
Data/Rakhana.hs
bsd-3-clause
1,567
0
5
401
220
154
66
58
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Generics -- Copyright : (c) Universiteit Utrecht 2010-2011, University of Oxford 2012-2013 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable -- -- @since 4.6.0.0 -- -- If you're using @GHC.Generics@, you should consider using the -- <http://hackage.haskell.org/package/generic-deriving> package, which -- contains many useful generic functions. module GHC.Generics ( -- * Introduction -- -- | -- -- Datatype-generic functions are are based on the idea of converting values of -- a datatype @T@ into corresponding values of a (nearly) isomorphic type @'Rep' T@. -- The type @'Rep' T@ is -- built from a limited set of type constructors, all provided by this module. A -- datatype-generic function is then an overloaded function with instances -- for most of these type constructors, together with a wrapper that performs -- the mapping between @T@ and @'Rep' T@. By using this technique, we merely need -- a few generic instances in order to implement functionality that works for any -- representable type. -- -- Representable types are collected in the 'Generic' class, which defines the -- associated type 'Rep' as well as conversion functions 'from' and 'to'. -- Typically, you will not define 'Generic' instances by hand, but have the compiler -- derive them for you. -- ** Representing datatypes -- -- | -- -- The key to defining your own datatype-generic functions is to understand how to -- represent datatypes using the given set of type constructors. -- -- Let us look at an example first: -- -- @ -- data Tree a = Leaf a | Node (Tree a) (Tree a) -- deriving 'Generic' -- @ -- -- The above declaration (which requires the language pragma @DeriveGeneric@) -- causes the following representation to be generated: -- -- @ -- instance 'Generic' (Tree a) where -- type 'Rep' (Tree a) = -- 'D1' D1Tree -- ('C1' C1_0Tree -- ('S1' 'NoSelector' ('Par0' a)) -- ':+:' -- 'C1' C1_1Tree -- ('S1' 'NoSelector' ('Rec0' (Tree a)) -- ':*:' -- 'S1' 'NoSelector' ('Rec0' (Tree a)))) -- ... -- @ -- -- /Hint:/ You can obtain information about the code being generated from GHC by passing -- the @-ddump-deriv@ flag. In GHCi, you can expand a type family such as 'Rep' using -- the @:kind!@ command. -- #if 0 -- /TODO:/ Newer GHC versions abandon the distinction between 'Par0' and 'Rec0' and will -- use 'Rec0' everywhere. -- #endif -- This is a lot of information! However, most of it is actually merely meta-information -- that makes names of datatypes and constructors and more available on the type level. -- -- Here is a reduced representation for 'Tree' with nearly all meta-information removed, -- for now keeping only the most essential aspects: -- -- @ -- instance 'Generic' (Tree a) where -- type 'Rep' (Tree a) = -- 'Par0' a -- ':+:' -- ('Rec0' (Tree a) ':*:' 'Rec0' (Tree a)) -- @ -- -- The @Tree@ datatype has two constructors. The representation of individual constructors -- is combined using the binary type constructor ':+:'. -- -- The first constructor consists of a single field, which is the parameter @a@. This is -- represented as @'Par0' a@. -- -- The second constructor consists of two fields. Each is a recursive field of type @Tree a@, -- represented as @'Rec0' (Tree a)@. Representations of individual fields are combined using -- the binary type constructor ':*:'. -- -- Now let us explain the additional tags being used in the complete representation: -- -- * The @'S1' 'NoSelector'@ indicates that there is no record field selector associated with -- this field of the constructor. -- -- * The @'C1' C1_0Tree@ and @'C1' C1_1Tree@ invocations indicate that the enclosed part is -- the representation of the first and second constructor of datatype @Tree@, respectively. -- Here, @C1_0Tree@ and @C1_1Tree@ are datatypes generated by the compiler as part of -- @deriving 'Generic'@. These datatypes are proxy types with no values. They are useful -- because they are instances of the type class 'Constructor'. This type class can be used -- to obtain information about the constructor in question, such as its name -- or infix priority. -- -- * The @'D1' D1Tree@ tag indicates that the enclosed part is the representation of the -- datatype @Tree@. Again, @D1Tree@ is a datatype generated by the compiler. It is a -- proxy type, and is useful by being an instance of class 'Datatype', which -- can be used to obtain the name of a datatype, the module it has been defined in, and -- whether it has been defined using @data@ or @newtype@. -- ** Derived and fundamental representation types -- -- | -- -- There are many datatype-generic functions that do not distinguish between positions that -- are parameters or positions that are recursive calls. There are also many datatype-generic -- functions that do not care about the names of datatypes and constructors at all. To keep -- the number of cases to consider in generic functions in such a situation to a minimum, -- it turns out that many of the type constructors introduced above are actually synonyms, -- defining them to be variants of a smaller set of constructors. -- *** Individual fields of constructors: 'K1' -- -- | -- -- The type constructors 'Par0' and 'Rec0' are variants of 'K1': -- -- @ -- type 'Par0' = 'K1' 'P' -- type 'Rec0' = 'K1' 'R' -- @ -- -- Here, 'P' and 'R' are type-level proxies again that do not have any associated values. -- *** Meta information: 'M1' -- -- | -- -- The type constructors 'S1', 'C1' and 'D1' are all variants of 'M1': -- -- @ -- type 'S1' = 'M1' 'S' -- type 'C1' = 'M1' 'C' -- type 'D1' = 'M1' 'D' -- @ -- -- The types 'S', 'C' and 'D' are once again type-level proxies, just used to create -- several variants of 'M1'. -- *** Additional generic representation type constructors -- -- | -- -- Next to 'K1', 'M1', ':+:' and ':*:' there are a few more type constructors that occur -- in the representations of other datatypes. -- **** Empty datatypes: 'V1' -- -- | -- -- For empty datatypes, 'V1' is used as a representation. For example, -- -- @ -- data Empty deriving 'Generic' -- @ -- -- yields -- -- @ -- instance 'Generic' Empty where -- type 'Rep' Empty = 'D1' D1Empty 'V1' -- @ -- **** Constructors without fields: 'U1' -- -- | -- -- If a constructor has no arguments, then 'U1' is used as its representation. For example -- the representation of 'Bool' is -- -- @ -- instance 'Generic' Bool where -- type 'Rep' Bool = -- 'D1' D1Bool -- ('C1' C1_0Bool 'U1' ':+:' 'C1' C1_1Bool 'U1') -- @ -- *** Representation of types with many constructors or many fields -- -- | -- -- As ':+:' and ':*:' are just binary operators, one might ask what happens if the -- datatype has more than two constructors, or a constructor with more than two -- fields. The answer is simple: the operators are used several times, to combine -- all the constructors and fields as needed. However, users /should not rely on -- a specific nesting strategy/ for ':+:' and ':*:' being used. The compiler is -- free to choose any nesting it prefers. (In practice, the current implementation -- tries to produce a more or less balanced nesting, so that the traversal of the -- structure of the datatype from the root to a particular component can be performed -- in logarithmic rather than linear time.) -- ** Defining datatype-generic functions -- -- | -- -- A datatype-generic function comprises two parts: -- -- 1. /Generic instances/ for the function, implementing it for most of the representation -- type constructors introduced above. -- -- 2. A /wrapper/ that for any datatype that is in `Generic`, performs the conversion -- between the original value and its `Rep`-based representation and then invokes the -- generic instances. -- -- As an example, let us look at a function 'encode' that produces a naive, but lossless -- bit encoding of values of various datatypes. So we are aiming to define a function -- -- @ -- encode :: 'Generic' a => a -> [Bool] -- @ -- -- where we use 'Bool' as our datatype for bits. -- -- For part 1, we define a class @Encode'@. Perhaps surprisingly, this class is parameterized -- over a type constructor @f@ of kind @* -> *@. This is a technicality: all the representation -- type constructors operate with kind @* -> *@ as base kind. But the type argument is never -- being used. This may be changed at some point in the future. The class has a single method, -- and we use the type we want our final function to have, but we replace the occurrences of -- the generic type argument @a@ with @f p@ (where the @p@ is any argument; it will not be used). -- -- > class Encode' f where -- > encode' :: f p -> [Bool] -- -- With the goal in mind to make @encode@ work on @Tree@ and other datatypes, we now define -- instances for the representation type constructors 'V1', 'U1', ':+:', ':*:', 'K1', and 'M1'. -- *** Definition of the generic representation types -- -- | -- -- In order to be able to do this, we need to know the actual definitions of these types: -- -- @ -- data 'V1' p -- lifted version of Empty -- data 'U1' p = 'U1' -- lifted version of () -- data (':+:') f g p = 'L1' (f p) | 'R1' (g p) -- lifted version of 'Either' -- data (':*:') f g p = (f p) ':*:' (g p) -- lifted version of (,) -- newtype 'K1' i c p = 'K1' { 'unK1' :: c } -- a container for a c -- newtype 'M1' i t f p = 'M1' { 'unM1' :: f p } -- a wrapper -- @ -- -- So, 'U1' is just the unit type, ':+:' is just a binary choice like 'Either', -- ':*:' is a binary pair like the pair constructor @(,)@, and 'K1' is a value -- of a specific type @c@, and 'M1' wraps a value of the generic type argument, -- which in the lifted world is an @f p@ (where we do not care about @p@). -- *** Generic instances -- -- | -- -- The instance for 'V1' is slightly awkward (but also rarely used): -- -- @ -- instance Encode' 'V1' where -- encode' x = undefined -- @ -- -- There are no values of type @V1 p@ to pass (except undefined), so this is -- actually impossible. One can ask why it is useful to define an instance for -- 'V1' at all in this case? Well, an empty type can be used as an argument to -- a non-empty type, and you might still want to encode the resulting type. -- As a somewhat contrived example, consider @[Empty]@, which is not an empty -- type, but contains just the empty list. The 'V1' instance ensures that we -- can call the generic function on such types. -- -- There is exactly one value of type 'U1', so encoding it requires no -- knowledge, and we can use zero bits: -- -- @ -- instance Encode' 'U1' where -- encode' 'U1' = [] -- @ -- -- In the case for ':+:', we produce 'False' or 'True' depending on whether -- the constructor of the value provided is located on the left or on the right: -- -- @ -- instance (Encode' f, Encode' g) => Encode' (f ':+:' g) where -- encode' ('L1' x) = False : encode' x -- encode' ('R1' x) = True : encode' x -- @ -- -- In the case for ':*:', we append the encodings of the two subcomponents: -- -- @ -- instance (Encode' f, Encode' g) => Encode' (f ':*:' g) where -- encode' (x ':*:' y) = encode' x ++ encode' y -- @ -- -- The case for 'K1' is rather interesting. Here, we call the final function -- 'encode' that we yet have to define, recursively. We will use another type -- class 'Encode' for that function: -- -- @ -- instance (Encode c) => Encode' ('K1' i c) where -- encode' ('K1' x) = encode x -- @ -- -- Note how 'Par0' and 'Rec0' both being mapped to 'K1' allows us to define -- a uniform instance here. -- -- Similarly, we can define a uniform instance for 'M1', because we completely -- disregard all meta-information: -- -- @ -- instance (Encode' f) => Encode' ('M1' i t f) where -- encode' ('M1' x) = encode' x -- @ -- -- Unlike in 'K1', the instance for 'M1' refers to 'encode'', not 'encode'. -- *** The wrapper and generic default -- -- | -- -- We now define class 'Encode' for the actual 'encode' function: -- -- @ -- class Encode a where -- encode :: a -> [Bool] -- default encode :: ('Generic' a) => a -> [Bool] -- encode x = encode' ('from' x) -- @ -- -- The incoming 'x' is converted using 'from', then we dispatch to the -- generic instances using 'encode''. We use this as a default definition -- for 'encode'. We need the 'default encode' signature because ordinary -- Haskell default methods must not introduce additional class constraints, -- but our generic default does. -- -- Defining a particular instance is now as simple as saying -- -- @ -- instance (Encode a) => Encode (Tree a) -- @ -- #if 0 -- /TODO:/ Add usage example? -- #endif -- The generic default is being used. In the future, it will hopefully be -- possible to use @deriving Encode@ as well, but GHC does not yet support -- that syntax for this situation. -- -- Having 'Encode' as a class has the advantage that we can define -- non-generic special cases, which is particularly useful for abstract -- datatypes that have no structural representation. For example, given -- a suitable integer encoding function 'encodeInt', we can define -- -- @ -- instance Encode Int where -- encode = encodeInt -- @ -- *** Omitting generic instances -- -- | -- -- It is not always required to provide instances for all the generic -- representation types, but omitting instances restricts the set of -- datatypes the functions will work for: -- -- * If no ':+:' instance is given, the function may still work for -- empty datatypes or datatypes that have a single constructor, -- but will fail on datatypes with more than one constructor. -- -- * If no ':*:' instance is given, the function may still work for -- datatypes where each constructor has just zero or one field, -- in particular for enumeration types. -- -- * If no 'K1' instance is given, the function may still work for -- enumeration types, where no constructor has any fields. -- -- * If no 'V1' instance is given, the function may still work for -- any datatype that is not empty. -- -- * If no 'U1' instance is given, the function may still work for -- any datatype where each constructor has at least one field. -- -- An 'M1' instance is always required (but it can just ignore the -- meta-information, as is the case for 'encode' above). #if 0 -- *** Using meta-information -- -- | -- -- TODO #endif -- ** Generic constructor classes -- -- | -- -- Datatype-generic functions as defined above work for a large class -- of datatypes, including parameterized datatypes. (We have used 'Tree' -- as our example above, which is of kind @* -> *@.) However, the -- 'Generic' class ranges over types of kind @*@, and therefore, the -- resulting generic functions (such as 'encode') must be parameterized -- by a generic type argument of kind @*@. -- -- What if we want to define generic classes that range over type -- constructors (such as 'Functor', 'Traversable', or 'Foldable')? -- *** The 'Generic1' class -- -- | -- -- Like 'Generic', there is a class 'Generic1' that defines a -- representation 'Rep1' and conversion functions 'from1' and 'to1', -- only that 'Generic1' ranges over types of kind @* -> *@. -- The 'Generic1' class is also derivable. -- -- The representation 'Rep1' is ever so slightly different from 'Rep'. -- Let us look at 'Tree' as an example again: -- -- @ -- data Tree a = Leaf a | Node (Tree a) (Tree a) -- deriving 'Generic1' -- @ -- -- The above declaration causes the following representation to be generated: -- -- instance 'Generic1' Tree where -- type 'Rep1' Tree = -- 'D1' D1Tree -- ('C1' C1_0Tree -- ('S1' 'NoSelector' 'Par1') -- ':+:' -- 'C1' C1_1Tree -- ('S1' 'NoSelector' ('Rec1' Tree) -- ':*:' -- 'S1' 'NoSelector' ('Rec1' Tree))) -- ... -- -- The representation reuses 'D1', 'C1', 'S1' (and thereby 'M1') as well -- as ':+:' and ':*:' from 'Rep'. (This reusability is the reason that we -- carry around the dummy type argument for kind-@*@-types, but there are -- already enough different names involved without duplicating each of -- these.) -- -- What's different is that we now use 'Par1' to refer to the parameter -- (and that parameter, which used to be @a@), is not mentioned explicitly -- by name anywhere; and we use 'Rec1' to refer to a recursive use of @Tree a@. -- *** Representation of @* -> *@ types -- -- | -- -- Unlike 'Par0' and 'Rec0', the 'Par1' and 'Rec1' type constructors do not -- map to 'K1'. They are defined directly, as follows: -- -- @ -- newtype 'Par1' p = 'Par1' { 'unPar1' :: p } -- gives access to parameter p -- newtype 'Rec1' f p = 'Rec1' { 'unRec1' :: f p } -- a wrapper -- @ -- -- In 'Par1', the parameter @p@ is used for the first time, whereas 'Rec1' simply -- wraps an application of @f@ to @p@. -- -- Note that 'K1' (in the guise of 'Rec0') can still occur in a 'Rep1' representation, -- namely when the datatype has a field that does not mention the parameter. -- -- The declaration -- -- @ -- data WithInt a = WithInt Int a -- deriving 'Generic1' -- @ -- -- yields -- -- @ -- class 'Rep1' WithInt where -- type 'Rep1' WithInt = -- 'D1' D1WithInt -- ('C1' C1_0WithInt -- ('S1' 'NoSelector' ('Rec0' Int) -- ':*:' -- 'S1' 'NoSelector' 'Par1')) -- @ -- -- If the parameter @a@ appears underneath a composition of other type constructors, -- then the representation involves composition, too: -- -- @ -- data Rose a = Fork a [Rose a] -- @ -- -- yields -- -- @ -- class 'Rep1' Rose where -- type 'Rep1' Rose = -- 'D1' D1Rose -- ('C1' C1_0Rose -- ('S1' 'NoSelector' 'Par1' -- ':*:' -- 'S1' 'NoSelector' ([] ':.:' 'Rec1' Rose) -- @ -- -- where -- -- @ -- newtype (':.:') f g p = 'Comp1' { 'unComp1' :: f (g p) } -- @ #if 0 -- *** Limitations -- -- | -- -- /TODO/ -- -- /TODO:/ Also clear up confusion about 'Rec0' and 'Rec1' not really indicating recursion. -- #endif ----------------------------------------------------------------------------- -- * Generic representation types V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..) , (:+:)(..), (:*:)(..), (:.:)(..) -- ** Synonyms for convenience , Rec0, Par0, R, P , D1, C1, S1, D, C, S -- * Meta-information , Datatype(..), Constructor(..), Selector(..), NoSelector , Fixity(..), Associativity(..), Arity(..), prec -- * Generic type classes , Generic(..), Generic1(..) ) where -- We use some base types import GHC.Types import Data.Maybe ( Maybe(..) ) import Data.Either ( Either(..) ) import GHC.Base (NonEmpty(..), Functor(..), Monad(..), Alternative(..), Applicative(..), MonadPlus(..), coerce) import GHC.Err (undefined) -- Needed for instances import GHC.Classes ( Eq, Ord ) import GHC.Read ( Read ) import GHC.Show ( Show ) import Data.Proxy -------------------------------------------------------------------------------- -- Representation types -------------------------------------------------------------------------------- -- | Void: used for datatypes without constructors data V1 p deriving (Functor) -- instance Functor V1 where -- fmap _f _x = undefined -- | Unit: used for constructors without arguments data U1 p = U1 deriving (Eq, Ord, Read, Show, Generic, Functor) -- | @since 4.9.0.0 instance Applicative U1 where pure _ = U1 _ <*> _ = U1 liftA2 _ _ _ = U1 -- | @since 4.9.0.0 instance Alternative U1 where empty = U1 _ <|> _ = U1 -- | @since 4.9.0.0 instance Monad U1 where _ >>= _ = U1 -- | @since 4.9.0.0 instance MonadPlus U1 -- | Used for marking occurrences of the parameter newtype Par1 p = Par1 { unPar1 :: p } deriving (Eq, Ord, Read, Show, Generic, Functor) -- | @since 4.9.0.0 instance Applicative Par1 where pure = Par1 (<*>) = coerce liftA2 = coerce -- | @since 4.9.0.0 instance Monad Par1 where Par1 x >>= f = f x -- | Recursive calls of kind * -> * newtype Rec1 f p = Rec1 { unRec1 :: f p } deriving (Eq, Ord, Read, Show, Generic, Functor) -- | @since 4.9.0.0 deriving instance Applicative f => Applicative (Rec1 f) -- | @since 4.9.0.0 deriving instance Alternative f => Alternative (Rec1 f) -- | @since 4.9.0.0 instance Monad f => Monad (Rec1 f) where Rec1 x >>= f = Rec1 (x >>= \a -> unRec1 (f a)) -- | @since 4.9.0.0 deriving instance MonadPlus f => MonadPlus (Rec1 f) -- | Constants, additional parameters and recursion of kind * newtype K1 i c p = K1 { unK1 :: c } deriving (Eq, Ord, Read, Show, Generic, Functor) -- | @since 4.9.0.0 deriving instance Applicative f => Applicative (M1 i c f) -- | @since 4.9.0.0 deriving instance Alternative f => Alternative (M1 i c f) -- | @since 4.9.0.0 deriving instance Monad f => Monad (M1 i c f) -- | @since 4.9.0.0 deriving instance MonadPlus f => MonadPlus (M1 i c f) -- | Meta-information (constructor names, etc.) newtype M1 i c f p = M1 { unM1 :: f p } deriving (Eq, Ord, Read, Show, Generic, Functor) -- | Sums: encode choice between constructors infixr 5 :+: data (:+:) f g p = L1 (f p) | R1 (g p) deriving (Eq, Ord, Read, Show, Generic, Functor) -- | Products: encode multiple arguments to constructors infixr 6 :*: data (:*:) f g p = f p :*: g p deriving (Eq, Ord, Read, Show, Generic, Functor) -- | @since 4.9.0.0 instance (Applicative f, Applicative g) => Applicative (f :*: g) where pure a = pure a :*: pure a (f :*: g) <*> (x :*: y) = (f <*> x) :*: (g <*> y) liftA2 f (a :*: b) (x :*: y) = liftA2 f a x :*: liftA2 f b y -- | @since 4.9.0.0 instance (Alternative f, Alternative g) => Alternative (f :*: g) where empty = empty :*: empty (x1 :*: y1) <|> (x2 :*: y2) = (x1 <|> x2) :*: (y1 <|> y2) -- | @since 4.9.0.0 instance (Monad f, Monad g) => Monad (f :*: g) where (m :*: n) >>= f = (m >>= \a -> fstP (f a)) :*: (n >>= \a -> sndP (f a)) where fstP (a :*: _) = a sndP (_ :*: b) = b -- | @since 4.9.0.0 instance (MonadPlus f, MonadPlus g) => MonadPlus (f :*: g) -- | Composition of functors infixr 7 :.: newtype (:.:) f g p = Comp1 { unComp1 :: f (g p) } deriving (Eq, Ord, Read, Show, Generic, Functor) -- | @since 4.9.0.0 instance (Applicative f, Applicative g) => Applicative (f :.: g) where pure x = Comp1 (pure (pure x)) Comp1 f <*> Comp1 x = Comp1 (liftA2 (<*>) f x) liftA2 f (Comp1 x) (Comp1 y) = Comp1 (liftA2 (liftA2 f) x y) -- | @since 4.9.0.0 instance (Alternative f, Applicative g) => Alternative (f :.: g) where empty = Comp1 empty (<|>) = coerce ((<|>) :: f (g a) -> f (g a) -> f (g a)) :: forall a . (f :.: g) a -> (f :.: g) a -> (f :.: g) a -- | Tag for K1: recursion (of kind *) data R -- | Tag for K1: parameters (other than the last) data P -- | Type synonym for encoding recursion (of kind *) type Rec0 = K1 R -- | Type synonym for encoding parameters (other than the last) type Par0 = K1 P {-# DEPRECATED Par0 "'Par0' is no longer used; use 'Rec0' instead" #-} -- deprecated in 7.6 {-# DEPRECATED P "'P' is no longer used; use 'R' instead" #-} -- deprecated in 7.6 -- | Tag for M1: datatype data D -- | Tag for M1: constructor data C -- | Tag for M1: record selector data S -- | Type synonym for encoding meta-information for datatypes type D1 = M1 D -- | Type synonym for encoding meta-information for constructors type C1 = M1 C -- | Type synonym for encoding meta-information for record selectors type S1 = M1 S -- | Class for datatypes that represent datatypes class Datatype d where -- | The name of the datatype (unqualified) datatypeName :: t d (f :: * -> *) a -> [Char] -- | The fully-qualified name of the module where the type is declared moduleName :: t d (f :: * -> *) a -> [Char] -- | Marks if the datatype is actually a newtype isNewtype :: t d (f :: * -> *) a -> Bool isNewtype _ = False -- | Class for datatypes that represent records class Selector s where -- | The name of the selector selName :: t s (f :: * -> *) a -> [Char] -- | Used for constructor fields without a name data NoSelector instance Selector NoSelector where selName _ = "" -- | Class for datatypes that represent data constructors class Constructor c where -- | The name of the constructor conName :: t c (f :: * -> *) a -> [Char] -- | The fixity of the constructor conFixity :: t c (f :: * -> *) a -> Fixity conFixity _ = Prefix -- | Marks if this constructor is a record conIsRecord :: t c (f :: * -> *) a -> Bool conIsRecord _ = False -- | Datatype to represent the arity of a tuple. data Arity = NoArity | Arity Int deriving (Eq, Show, Ord, Read, Generic) -- | Datatype to represent the fixity of a constructor. An infix -- | declaration directly corresponds to an application of 'Infix'. data Fixity = Prefix | Infix Associativity Int deriving (Eq, Show, Ord, Read, Generic) -- | Get the precedence of a fixity value. prec :: Fixity -> Int prec Prefix = 10 prec (Infix _ n) = n -- | Datatype to represent the associativity of a constructor data Associativity = LeftAssociative | RightAssociative | NotAssociative deriving (Eq, Show, Ord, Read, Generic) -- | Representable types of kind *. -- This class is derivable in GHC with the DeriveGeneric flag on. class Generic a where -- | Generic representation type type Rep a :: * -> * -- | Convert from the datatype to its representation from :: a -> (Rep a) x -- | Convert from the representation to the datatype to :: (Rep a) x -> a -- | Representable types of kind * -> *. -- This class is derivable in GHC with the DeriveGeneric flag on. class Generic1 f where -- | Generic representation type type Rep1 f :: * -> * -- | Convert from the datatype to its representation from1 :: f a -> (Rep1 f) a -- | Convert from the representation to the datatype to1 :: (Rep1 f) a -> f a -------------------------------------------------------------------------------- -- Derived instances -------------------------------------------------------------------------------- deriving instance Generic [a] deriving instance Generic (NonEmpty a) deriving instance Generic (Maybe a) deriving instance Generic (Either a b) deriving instance Generic Bool deriving instance Generic Ordering deriving instance Generic (Proxy t) deriving instance Generic () deriving instance Generic ((,) a b) deriving instance Generic ((,,) a b c) deriving instance Generic ((,,,) a b c d) deriving instance Generic ((,,,,) a b c d e) deriving instance Generic ((,,,,,) a b c d e f) deriving instance Generic ((,,,,,,) a b c d e f g) deriving instance Generic1 [] deriving instance Generic1 NonEmpty deriving instance Generic1 Maybe deriving instance Generic1 (Either a) deriving instance Generic1 Proxy deriving instance Generic1 ((,) a) deriving instance Generic1 ((,,) a b) deriving instance Generic1 ((,,,) a b c) deriving instance Generic1 ((,,,,) a b c d) deriving instance Generic1 ((,,,,,) a b c d e) deriving instance Generic1 ((,,,,,,) a b c d e f) -------------------------------------------------------------------------------- -- Primitive representations -------------------------------------------------------------------------------- -- Int data D_Int data C_Int instance Datatype D_Int where datatypeName _ = "Int" moduleName _ = "GHC.Int" instance Constructor C_Int where conName _ = "" -- JPM: I'm not sure this is the right implementation... instance Generic Int where type Rep Int = D1 D_Int (C1 C_Int (S1 NoSelector (Rec0 Int))) from x = M1 (M1 (M1 (K1 x))) to (M1 (M1 (M1 (K1 x)))) = x -- Float data D_Float data C_Float instance Datatype D_Float where datatypeName _ = "Float" moduleName _ = "GHC.Float" instance Constructor C_Float where conName _ = "" -- JPM: I'm not sure this is the right implementation... instance Generic Float where type Rep Float = D1 D_Float (C1 C_Float (S1 NoSelector (Rec0 Float))) from x = M1 (M1 (M1 (K1 x))) to (M1 (M1 (M1 (K1 x)))) = x -- Double data D_Double data C_Double instance Datatype D_Double where datatypeName _ = "Double" moduleName _ = "GHC.Float" instance Constructor C_Double where conName _ = "" -- JPM: I'm not sure this is the right implementation... instance Generic Double where type Rep Double = D1 D_Double (C1 C_Double (S1 NoSelector (Rec0 Double))) from x = M1 (M1 (M1 (K1 x))) to (M1 (M1 (M1 (K1 x)))) = x -- Char data D_Char data C_Char instance Datatype D_Char where datatypeName _ = "Char" moduleName _ = "GHC.Base" instance Constructor C_Char where conName _ = "" -- JPM: I'm not sure this is the right implementation... instance Generic Char where type Rep Char = D1 D_Char (C1 C_Char (S1 NoSelector (Rec0 Char))) from x = M1 (M1 (M1 (K1 x))) to (M1 (M1 (M1 (K1 x)))) = x
rahulmutt/ghcvm
libraries/base/GHC/Generics.hs
bsd-3-clause
29,593
0
14
6,282
3,951
2,423
1,528
-1
-1
{-# LANGUAGE Haskell98, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} {-# LINE 1 "Control/Monad/Reader.hs" #-} {- | Module : Control.Monad.Reader Copyright : (c) Andy Gill 2001, (c) Oregon Graduate Institute of Science and Technology 2001, (c) Jeff Newbern 2003-2007, (c) Andriy Palamarchuk 2007 License : BSD-style (see the file LICENSE) Maintainer : [email protected] Stability : experimental Portability : non-portable (multi-param classes, functional dependencies) [Computation type:] Computations which read values from a shared environment. [Binding strategy:] Monad values are functions from the environment to a value. The bound function is applied to the bound value, and both have access to the shared environment. [Useful for:] Maintaining variable bindings, or other shared environment. [Zero and plus:] None. [Example type:] @'Reader' [(String,Value)] a@ The 'Reader' monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, pass values from function to function, and execute sub-computations in a modified environment. Using 'Reader' monad for such computations is often clearer and easier than using the 'Control.Monad.State.State' monad. Inspired by the paper /Functional Programming with Overloading and Higher-Order Polymorphism/, Mark P Jones (<http://web.cecs.pdx.edu/~mpj/>) Advanced School of Functional Programming, 1995. -} module Control.Monad.Reader ( -- * MonadReader class MonadReader(..), asks, -- * The Reader monad Reader, runReader, mapReader, withReader, -- * The ReaderT monad transformer ReaderT(ReaderT), runReaderT, mapReaderT, withReaderT, module Control.Monad, module Control.Monad.Fix, module Control.Monad.Trans, -- * Example 1: Simple Reader Usage -- $simpleReaderExample -- * Example 2: Modifying Reader Content With @local@ -- $localExample -- * Example 3: @ReaderT@ Monad Transformer -- $ReaderTExample ) where import Control.Monad.Reader.Class import Control.Monad.Trans.Reader ( Reader, runReader, mapReader, withReader, ReaderT(ReaderT), runReaderT, mapReaderT, withReaderT) import Control.Monad.Trans import Control.Monad import Control.Monad.Fix {- $simpleReaderExample In this example the @Reader@ monad provides access to variable bindings. Bindings are a @Map@ of integer variables. The variable @count@ contains number of variables in the bindings. You can see how to run a Reader monad and retrieve data from it with 'runReader', how to access the Reader data with 'ask' and 'asks'. > type Bindings = Map String Int; > >-- Returns True if the "count" variable contains correct bindings size. >isCountCorrect :: Bindings -> Bool >isCountCorrect bindings = runReader calc_isCountCorrect bindings > >-- The Reader monad, which implements this complicated check. >calc_isCountCorrect :: Reader Bindings Bool >calc_isCountCorrect = do > count <- asks (lookupVar "count") > bindings <- ask > return (count == (Map.size bindings)) > >-- The selector function to use with 'asks'. >-- Returns value of the variable with specified name. >lookupVar :: String -> Bindings -> Int >lookupVar name bindings = fromJust (Map.lookup name bindings) > >sampleBindings = Map.fromList [("count",3), ("1",1), ("b",2)] > >main = do > putStr $ "Count is correct for bindings " ++ (show sampleBindings) ++ ": "; > putStrLn $ show (isCountCorrect sampleBindings); -} {- $localExample Shows how to modify Reader content with 'local'. >calculateContentLen :: Reader String Int >calculateContentLen = do > content <- ask > return (length content); > >-- Calls calculateContentLen after adding a prefix to the Reader content. >calculateModifiedContentLen :: Reader String Int >calculateModifiedContentLen = local ("Prefix " ++) calculateContentLen > >main = do > let s = "12345"; > let modifiedLen = runReader calculateModifiedContentLen s > let len = runReader calculateContentLen s > putStrLn $ "Modified 's' length: " ++ (show modifiedLen) > putStrLn $ "Original 's' length: " ++ (show len) -} {- $ReaderTExample Now you are thinking: 'Wow, what a great monad! I wish I could use Reader functionality in MyFavoriteComplexMonad!'. Don't worry. This can be easy done with the 'ReaderT' monad transformer. This example shows how to combine @ReaderT@ with the IO monad. >-- The Reader/IO combined monad, where Reader stores a string. >printReaderContent :: ReaderT String IO () >printReaderContent = do > content <- ask > liftIO $ putStrLn ("The Reader Content: " ++ content) > >main = do > runReaderT printReaderContent "Some Content" -}
phischu/fragnix
tests/packages/scotty/Control.Monad.Reader.hs
bsd-3-clause
4,796
0
6
883
144
103
41
25
0
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..)) import Control.Monad (void) import Bob (responseFor) testCase :: String -> Assertion -> Test testCase label assertion = TestLabel label (TestCase assertion) test_respondsToSomething :: Assertion test_respondsToSomething = "Whatever." @=? responseFor "Tom-ay-to, tom-aaaah-to." test_respondsToShouts :: Assertion test_respondsToShouts = "Woah, chill out!" @=? responseFor "WATCH OUT!" test_respondsToQuestions :: Assertion test_respondsToQuestions = "Sure." @=? responseFor "Does this cryogenic chamber make me look fat?" test_respondsToForcefulTalking :: Assertion test_respondsToForcefulTalking = "Whatever." @=? responseFor "Let's go make out behind the gym!" test_respondsToAcronyms :: Assertion test_respondsToAcronyms = "Whatever." @=? responseFor "It's OK if you don't want to go to the DMV." test_respondsToForcefulQuestions :: Assertion test_respondsToForcefulQuestions = "Woah, chill out!" @=? responseFor "WHAT THE HELL WERE YOU THINKING?" test_respondsToShoutingWithSpecialCharacters :: Assertion test_respondsToShoutingWithSpecialCharacters = "Woah, chill out!" @=? responseFor ( "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!") test_respondsToShoutingNumbers :: Assertion test_respondsToShoutingNumbers = "Woah, chill out!" @=? responseFor "1, 2, 3 GO!" test_respondsToShoutingWithNoExclamationMark :: Assertion test_respondsToShoutingWithNoExclamationMark = "Woah, chill out!" @=? responseFor "I HATE YOU" test_respondsToStatementContainingQuestionMark :: Assertion test_respondsToStatementContainingQuestionMark = "Whatever." @=? responseFor "Ending with ? means a question." test_respondsToSilence :: Assertion test_respondsToSilence = "Fine. Be that way!" @=? responseFor "" test_respondsToProlongedSilence :: Assertion test_respondsToProlongedSilence = "Fine. Be that way!" @=? responseFor " " test_respondsToNonLettersWithQuestion :: Assertion test_respondsToNonLettersWithQuestion = "Sure." @=? responseFor ":) ?" test_respondsToMultipleLineQuestions :: Assertion test_respondsToMultipleLineQuestions = "Whatever." @=? responseFor "\nDoes this cryogenic chamber make me look fat? \nno" test_respondsToOtherWhitespace :: Assertion test_respondsToOtherWhitespace = "Fine. Be that way!" @=? responseFor "\n\r \t\v\xA0\x2002" -- \xA0 No-break space, \x2002 En space respondsToTests :: [Test] respondsToTests = [ testCase "something" test_respondsToSomething , testCase "shouts" test_respondsToShouts , testCase "questions" test_respondsToQuestions , testCase "forceful talking" test_respondsToForcefulTalking , testCase "acronyms" test_respondsToAcronyms , testCase "forceful questions" test_respondsToForcefulQuestions , testCase "shouting with special characters" test_respondsToShoutingWithSpecialCharacters , testCase "shouting numbers" test_respondsToShoutingNumbers , testCase "shouting with no exclamation mark" test_respondsToShoutingWithNoExclamationMark , testCase "statement containing question mark" test_respondsToStatementContainingQuestionMark , testCase "silence" test_respondsToSilence , testCase "prolonged silence" test_respondsToProlongedSilence , testCase "questioned nonsence" test_respondsToNonLettersWithQuestion , testCase "multiple-line statement containing question mark" test_respondsToMultipleLineQuestions , testCase "all whitespace is silence" test_respondsToOtherWhitespace ] main :: IO () main = void (runTestTT (TestList respondsToTests))
driis/exercism
haskell/bob/bob_test.hs
mit
3,550
0
9
446
500
266
234
74
1
module Shift.For where -- -- $Id$ import ToDoc import Control.Monad ( guard ) -- this is only used for printing data Prog a = For { var :: String , bound :: Ex , body :: [ Prog a ] } | It { unIt :: a } | FJunk instance ToDoc a => ToDoc ( Prog a ) where toDoc ( x @ It {} ) = toDoc $ unIt x toDoc ( x @ For {} ) = fsep [ hsep [ text "for", text "0", text "<= ", text (var x) , text "<", toDoc (bound x) , text "loop" ] , nest 4 $ fsep $ punctuate ( text ";") $ map toDoc $ body x , hsep [ text "end", text "loop" ] ] toDoc FJunk = text "?" instance ToDoc a => Show ( Prog a ) where show = render . toDoc data Ex = Ex { off :: Int , vars :: [ (Int, String) ] } neu :: Ex -> String neu ex = let l = length ( vars ex ) in "x" ++ show l signed :: ( Num a, Ord a, ToDoc a ) => a -> Doc signed x = ( if x >= 0 then text "+" else empty ) <+> toDoc x factored i = if -1 == i then text "-" else if 1 == i then text "+" else signed i instance ToDoc Ex where toDoc ex = hsep $ do ( i, v ) <- vars ex guard $ i /= 0 return $ factored i <+> text v ++ do guard $ off ex /= 0 return $ signed ( off ex ) instance Show Ex where show = render . toDoc
florianpilz/autotool
src/Shift/For.hs
gpl-2.0
1,290
61
12
449
589
317
272
37
3
--------------------------------------------------------- -- The main program for the hpc-markup tool, part of HPC. -- Andy Gill and Colin Runciman, June 2006 --------------------------------------------------------- module HpcMarkup (markup_plugin) where import Trace.Hpc.Mix import Trace.Hpc.Tix import Trace.Hpc.Util import HpcFlags import HpcUtils import System.Directory import System.IO (localeEncoding) import Data.List import Data.Maybe(fromJust) import Data.Array import Control.Monad import qualified Data.Set as Set ------------------------------------------------------------------------------ markup_options :: FlagOptSeq markup_options = excludeOpt . includeOpt . srcDirOpt . hpcDirOpt . resetHpcDirsOpt . funTotalsOpt . altHighlightOpt . destDirOpt . verbosityOpt markup_plugin :: Plugin markup_plugin = Plugin { name = "markup" , usage = "[OPTION] .. <TIX_FILE> [<MODULE> [<MODULE> ..]]" , options = markup_options , summary = "Markup Haskell source with program coverage" , implementation = markup_main , init_flags = default_flags , final_flags = default_final_flags } ------------------------------------------------------------------------------ markup_main :: Flags -> [String] -> IO () markup_main flags (prog:modNames) = do let hpcflags1 = flags { includeMods = Set.fromList modNames `Set.union` includeMods flags } let Flags { funTotals = theFunTotals , altHighlight = invertOutput , destDir = dest_dir } = hpcflags1 mtix <- readTix (getTixFileName prog) Tix tixs <- case mtix of Nothing -> hpcError markup_plugin $ "unable to find tix file for: " ++ prog Just a -> return a mods <- sequence [ genHtmlFromMod dest_dir hpcflags1 tix theFunTotals invertOutput | tix <- tixs , allowModule hpcflags1 (tixModuleName tix) ] let index_name = "hpc_index" index_fun = "hpc_index_fun" index_alt = "hpc_index_alt" index_exp = "hpc_index_exp" let writeSummary filename cmp = do let mods' = sortBy cmp mods unless (verbosity flags < Normal) $ putStrLn $ "Writing: " ++ (filename ++ ".html") writeFileUsing (dest_dir ++ "/" ++ filename ++ ".html") $ "<html>" ++ "<head>" ++ charEncodingTag ++ "<style type=\"text/css\">" ++ "table.bar { background-color: #f25913; }\n" ++ "td.bar { background-color: #60de51; }\n" ++ "td.invbar { background-color: #f25913; }\n" ++ "table.dashboard { border-collapse: collapse ; border: solid 1px black }\n" ++ ".dashboard td { border: solid 1px black }\n" ++ ".dashboard th { border: solid 1px black }\n" ++ "</style>\n" ++ "</head>" ++ "<body>" ++ "<table class=\"dashboard\" width=\"100%\" border=1>\n" ++ "<tr>" ++ "<th rowspan=2><a href=\"" ++ index_name ++ ".html\">module</a></th>" ++ "<th colspan=3><a href=\"" ++ index_fun ++ ".html\">Top Level Definitions</a></th>" ++ "<th colspan=3><a href=\"" ++ index_alt ++ ".html\">Alternatives</a></th>" ++ "<th colspan=3><a href=\"" ++ index_exp ++ ".html\">Expressions</a></th>" ++ "</tr>" ++ "<tr>" ++ "<th>%</th>" ++ "<th colspan=2>covered / total</th>" ++ "<th>%</th>" ++ "<th colspan=2>covered / total</th>" ++ "<th>%</th>" ++ "<th colspan=2>covered / total</th>" ++ "</tr>" ++ concat [ showModuleSummary (modName,fileName,modSummary) | (modName,fileName,modSummary) <- mods' ] ++ "<tr></tr>" ++ showTotalSummary (mconcat [ modSummary | (_,_,modSummary) <- mods' ]) ++ "</table></body></html>\n" writeSummary index_name $ \ (n1,_,_) (n2,_,_) -> compare n1 n2 writeSummary index_fun $ \ (_,_,s1) (_,_,s2) -> compare (percent (topFunTicked s2) (topFunTotal s2)) (percent (topFunTicked s1) (topFunTotal s1)) writeSummary index_alt $ \ (_,_,s1) (_,_,s2) -> compare (percent (altTicked s2) (altTotal s2)) (percent (altTicked s1) (altTotal s1)) writeSummary index_exp $ \ (_,_,s1) (_,_,s2) -> compare (percent (expTicked s2) (expTotal s2)) (percent (expTicked s1) (expTotal s1)) markup_main _ [] = hpcError markup_plugin $ "no .tix file or executable name specified" charEncodingTag :: String charEncodingTag = "<meta http-equiv=\"Content-Type\" " ++ "content=\"text/html; " ++ "charset=" ++ show localeEncoding ++ "\">" -- Add characters to the left of a string until it is at least as -- large as requested. padLeft :: Int -> Char -> String -> String padLeft n c str = go n str where -- If the string is already long enough, stop traversing it. go 0 _ = str go k [] = replicate k c ++ str go k (_:xs) = go (k-1) xs genHtmlFromMod :: String -> Flags -> TixModule -> Bool -> Bool -> IO (String, [Char], ModuleSummary) genHtmlFromMod dest_dir flags tix theFunTotals invertOutput = do let theHsPath = srcDirs flags let modName0 = tixModuleName tix (Mix origFile _ _ tabStop mix') <- readMixWithFlags flags (Right tix) let arr_tix :: Array Int Integer arr_tix = listArray (0,length (tixModuleTixs tix) - 1) $ tixModuleTixs tix let tickedWith :: Int -> Integer tickedWith n = arr_tix ! n isTicked n = tickedWith n /= 0 let info = [ (pos,theMarkup) | (gid,(pos,boxLabel)) <- zip [0 ..] mix' , let binBox = case (isTicked gid,isTicked (gid+1)) of (False,False) -> [] (True,False) -> [TickedOnlyTrue] (False,True) -> [TickedOnlyFalse] (True,True) -> [] , let tickBox = if isTicked gid then [IsTicked] else [NotTicked] , theMarkup <- case boxLabel of ExpBox {} -> tickBox TopLevelBox {} -> TopLevelDecl theFunTotals (tickedWith gid) : tickBox LocalBox {} -> tickBox BinBox _ True -> binBox _ -> [] ] let modSummary = foldr (.) id [ \ st -> case boxLabel of ExpBox False -> st { expTicked = ticked (expTicked st) , expTotal = succ (expTotal st) } ExpBox True -> st { expTicked = ticked (expTicked st) , expTotal = succ (expTotal st) , altTicked = ticked (altTicked st) , altTotal = succ (altTotal st) } TopLevelBox _ -> st { topFunTicked = ticked (topFunTicked st) , topFunTotal = succ (topFunTotal st) } _ -> st | (gid,(_pos,boxLabel)) <- zip [0 ..] mix' , let ticked = if isTicked gid then succ else id ] $ mempty -- add prefix to modName argument content <- readFileFromPath (hpcError markup_plugin) origFile theHsPath let content' = markup tabStop info content let addLine n xs = "<span class=\"lineno\">" ++ padLeft 5 ' ' (show n) ++ " </span>" ++ xs let addLines = unlines . map (uncurry addLine) . zip [1 :: Int ..] . lines let fileName = modName0 ++ ".hs.html" unless (verbosity flags < Normal) $ putStrLn $ "Writing: " ++ fileName writeFileUsing (dest_dir ++ "/" ++ fileName) $ unlines ["<html>", "<head>", charEncodingTag, "<style type=\"text/css\">", "span.lineno { color: white; background: #aaaaaa; border-right: solid white 12px }", if invertOutput then "span.nottickedoff { color: #404040; background: white; font-style: oblique }" else "span.nottickedoff { background: " ++ yellow ++ "}", if invertOutput then "span.istickedoff { color: black; background: #d0c0ff; font-style: normal; }" else "span.istickedoff { background: white }", "span.tickonlyfalse { margin: -1px; border: 1px solid " ++ red ++ "; background: " ++ red ++ " }", "span.tickonlytrue { margin: -1px; border: 1px solid " ++ green ++ "; background: " ++ green ++ " }", "span.funcount { font-size: small; color: orange; z-index: 2; position: absolute; right: 20 }", if invertOutput then "span.decl { font-weight: bold; background: #d0c0ff }" else "span.decl { font-weight: bold }", "span.spaces { background: white }", "</style>", "</head>", "<body>", "<pre>"] ++ addLines content' ++ "\n</pre>\n</body>\n</html>\n"; modSummary `seq` return (modName0,fileName,modSummary) data Loc = Loc !Int !Int deriving (Eq,Ord,Show) data Markup = NotTicked | TickedOnlyTrue | TickedOnlyFalse | IsTicked | TopLevelDecl Bool -- display entry totals Integer deriving (Eq,Show) markup :: Int -- ^tabStop -> [(HpcPos,Markup)] -- random list of tick location pairs -> String -- text to mark up -> String markup tabStop mix str = addMarkup tabStop str (Loc 1 1) [] sortedTickLocs where tickLocs = [ (Loc ln1 c1,Loc ln2 c2,mark) | (pos,mark) <- mix , let (ln1,c1,ln2,c2) = fromHpcPos pos ] sortedTickLocs = sortBy (\(locA1,locZ1,_) (locA2,locZ2,_) -> (locA1,locZ2) `compare` (locA2,locZ1)) tickLocs addMarkup :: Int -- tabStop -> String -- text to mark up -> Loc -- current location -> [(Loc,Markup)] -- stack of open ticks, with closing location -> [(Loc,Loc,Markup)] -- sorted list of tick location pairs -> String -- check the pre-condition. --addMarkup tabStop cs loc os ticks -- | not (isSorted (map fst os)) = error $ "addMarkup: bad closing ordering: " ++ show os --addMarkup tabStop cs loc os@(_:_) ticks -- | trace (show (loc,os,take 10 ticks)) False = undefined -- close all open ticks, if we have reached the end addMarkup _ [] _loc os [] = concatMap (const closeTick) os addMarkup tabStop cs loc ((o,_):os) ticks | loc > o = closeTick ++ addMarkup tabStop cs loc os ticks --addMarkup tabStop cs loc os ((t1,t2,tik@(TopLevelDecl {})):ticks) | loc == t1 = -- openTick tik ++ closeTick ++ addMarkup tabStop cs loc os ticks addMarkup tabStop cs loc os ((t1,t2,tik0):ticks) | loc == t1 = case os of ((_,tik'):_) | not (allowNesting tik0 tik') -> addMarkup tabStop cs loc os ticks -- already marked or bool within marked bool _ -> openTick tik0 ++ addMarkup tabStop cs loc (addTo (t2,tik0) os) ticks where addTo (t,tik) [] = [(t,tik)] addTo (t,tik) ((t',tik'):xs) | t <= t' = (t,tik):(t',tik'):xs | otherwise = (t',tik):(t',tik'):xs addMarkup tabStop0 cs loc os ((t1,_t2,_tik):ticks) | loc > t1 = -- throw away this tick, because it is from a previous place ?? addMarkup tabStop0 cs loc os ticks addMarkup tabStop0 ('\n':cs) loc@(Loc ln col) os@((Loc ln2 col2,_):_) ticks | ln == ln2 && col < col2 = addMarkup tabStop0 (' ':'\n':cs) loc os ticks addMarkup tabStop0 (c0:cs) loc@(Loc _ p) os ticks = if c0=='\n' && os/=[] then concatMap (const closeTick) (downToTopLevel os) ++ c0 : "<span class=\"spaces\">" ++ expand 1 w ++ "</span>" ++ concatMap (openTick.snd) (reverse (downToTopLevel os)) ++ addMarkup tabStop0 cs' loc' os ticks else if c0=='\t' then expand p "\t" ++ addMarkup tabStop0 cs (incBy c0 loc) os ticks else escape c0 ++ addMarkup tabStop0 cs (incBy c0 loc) os ticks where (w,cs') = span (`elem` " \t") cs loc' = foldl (flip incBy) loc (c0:w) escape '>' = "&gt;" escape '<' = "&lt;" escape '"' = "&quot;" escape '&' = "&amp;" escape c = [c] expand :: Int -> String -> String expand _ "" = "" expand c ('\t':s) = replicate (c' - c) ' ' ++ expand c' s where c' = tabStopAfter 8 c expand c (' ':s) = ' ' : expand (c+1) s expand _ _ = error "bad character in string for expansion" incBy :: Char -> Loc -> Loc incBy '\n' (Loc ln _c) = Loc (succ ln) 1 incBy '\t' (Loc ln c) = Loc ln (tabStopAfter tabStop0 c) incBy _ (Loc ln c) = Loc ln (succ c) tabStopAfter :: Int -> Int -> Int tabStopAfter tabStop c = fromJust (find (>c) [1,(tabStop + 1)..]) addMarkup tabStop cs loc os ticks = "ERROR: " ++ show (take 10 cs,tabStop,loc,take 10 os,take 10 ticks) openTick :: Markup -> String openTick NotTicked = "<span class=\"nottickedoff\">" openTick IsTicked = "<span class=\"istickedoff\">" openTick TickedOnlyTrue = "<span class=\"tickonlytrue\">" openTick TickedOnlyFalse = "<span class=\"tickonlyfalse\">" openTick (TopLevelDecl False _) = openTopDecl openTick (TopLevelDecl True 0) = "<span class=\"funcount\">-- never entered</span>" ++ openTopDecl openTick (TopLevelDecl True 1) = "<span class=\"funcount\">-- entered once</span>" ++ openTopDecl openTick (TopLevelDecl True n0) = "<span class=\"funcount\">-- entered " ++ showBigNum n0 ++ " times</span>" ++ openTopDecl where showBigNum n | n <= 9999 = show n | otherwise = case n `quotRem` 1000 of (q, r) -> showBigNum' q ++ "," ++ showWith r showBigNum' n | n <= 999 = show n | otherwise = case n `quotRem` 1000 of (q, r) -> showBigNum' q ++ "," ++ showWith r showWith n = padLeft 3 '0' $ show n closeTick :: String closeTick = "</span>" openTopDecl :: String openTopDecl = "<span class=\"decl\">" downToTopLevel :: [(Loc,Markup)] -> [(Loc,Markup)] downToTopLevel ((_,TopLevelDecl {}):_) = [] downToTopLevel (o : os) = o : downToTopLevel os downToTopLevel [] = [] -- build in logic for nesting bin boxes allowNesting :: Markup -- innermost -> Markup -- outermost -> Bool allowNesting n m | n == m = False -- no need to double nest allowNesting IsTicked TickedOnlyFalse = False allowNesting IsTicked TickedOnlyTrue = False allowNesting _ _ = True ------------------------------------------------------------------------------ data ModuleSummary = ModuleSummary { expTicked :: !Int , expTotal :: !Int , topFunTicked :: !Int , topFunTotal :: !Int , altTicked :: !Int , altTotal :: !Int } deriving (Show) showModuleSummary :: (String, String, ModuleSummary) -> String showModuleSummary (modName,fileName,modSummary) = "<tr>\n" ++ "<td>&nbsp;&nbsp;<tt>module <a href=\"" ++ fileName ++ "\">" ++ modName ++ "</a></tt></td>\n" ++ showSummary (topFunTicked modSummary) (topFunTotal modSummary) ++ showSummary (altTicked modSummary) (altTotal modSummary) ++ showSummary (expTicked modSummary) (expTotal modSummary) ++ "</tr>\n" showTotalSummary :: ModuleSummary -> String showTotalSummary modSummary = "<tr style=\"background: #e0e0e0\">\n" ++ "<th align=left>&nbsp;&nbsp;Program Coverage Total</tt></th>\n" ++ showSummary (topFunTicked modSummary) (topFunTotal modSummary) ++ showSummary (altTicked modSummary) (altTotal modSummary) ++ showSummary (expTicked modSummary) (expTotal modSummary) ++ "</tr>\n" showSummary :: (Integral t, Show t) => t -> t -> String showSummary ticked total = "<td align=\"right\">" ++ showP (percent ticked total) ++ "</td>" ++ "<td>" ++ show ticked ++ "/" ++ show total ++ "</td>" ++ "<td width=100>" ++ (case percent ticked total of Nothing -> "&nbsp;" Just w -> bar w "bar" ) ++ "</td>" where showP Nothing = "-&nbsp;" showP (Just x) = show x ++ "%" bar 0 _ = bar 100 "invbar" bar w inner = "<table cellpadding=0 cellspacing=0 width=\"100\" class=\"bar\">" ++ "<tr><td><table cellpadding=0 cellspacing=0 width=\"" ++ show w ++ "%\">" ++ "<tr><td height=12 class=" ++ show inner ++ "></td></tr>" ++ "</table></td></tr></table>" percent :: (Integral a) => a -> a -> Maybe a percent ticked total = if total == 0 then Nothing else Just (ticked * 100 `div` total) instance Monoid ModuleSummary where mempty = ModuleSummary { expTicked = 0 , expTotal = 0 , topFunTicked = 0 , topFunTotal = 0 , altTicked = 0 , altTotal = 0 } mappend (ModuleSummary eTik1 eTot1 tTik1 tTot1 aTik1 aTot1) (ModuleSummary eTik2 eTot2 tTik2 tTot2 aTik2 aTot2) = ModuleSummary (eTik1 + eTik2) (eTot1 + eTot2) (tTik1 + tTik2) (tTot1 + tTot2) (aTik1 + aTik2) (aTot1 + aTot2) ------------------------------------------------------------------------------ writeFileUsing :: String -> String -> IO () writeFileUsing filename text = do let dest_dir = dropWhileEndLE (\ x -> x /= '/') $ filename -- We need to check for the dest_dir each time, because we use sub-dirs for -- packages, and a single .tix file might contain information about -- many package. -- create the dest_dir if needed when (not (null dest_dir)) $ createDirectoryIfMissing True dest_dir writeFile filename text ------------------------------------------------------------------------------ -- global color pallete red,green,yellow :: String red = "#f20913" green = "#60de51" yellow = "yellow"
forked-upstream-packages-for-ghcjs/ghc
utils/hpc/HpcMarkup.hs
bsd-3-clause
19,147
0
56
6,364
4,847
2,544
2,303
392
16
{-# LANGUAGE OverloadedStrings #-} module Bead.Daemon.TestAgent where import Control.Exception import Control.Concurrent import qualified Bead.Controller.Logging as L import Bead.Controller.ServiceContext as S import Bead.Controller.UserStories (runUserStory, testAgentFeedbacks) import Bead.View.Translation (trans) -- Starts a thread that polls the persistence layer for new test agent comments in every w seconds -- and places them into the right place. startTestCommentsAgent :: L.Logger -> Int -> Int -> ServiceContext -> IO () startTestCommentsAgent logger initWait wait context = do let agent = do threadDelay (secToMicroSec wait) ((runUserStory context trans TestAgent testAgentFeedbacks) >> return ()) `catch` someException agent forkIO $ do threadDelay (secToMicroSec initWait) agent return () where secToMicroSec = (* 1000000) someException :: SomeException -> IO () someException e = do (L.log logger L.ERROR (show e)) `catch` (loggerException e) return () where loggerException :: SomeException -> SomeException -> IO () loggerException original e = do print original print e
andorp/bead
src/Bead/Daemon/TestAgent.hs
bsd-3-clause
1,259
0
16
312
309
161
148
26
1
{-# LANGUAGE OverloadedStrings #-} module MyInit ( (@/=), (@==), (==@) , asIO , assertNotEqual , assertNotEmpty , assertEmpty , isTravis , BackendMonad , runConn , MonadIO , persistSettings , MkPersistSettings (..) , db , BackendKey(..) , GenerateKey(..) , RunDb -- re-exports , module Database.Persist , module Database.Persist.Sql.Raw.QQ , module Test.Hspec , module Test.HUnit , liftIO , mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase , Int32, Int64 , Text , module Control.Monad.Trans.Reader , module Control.Monad , module Database.Persist.Sql , BS.ByteString , SomeException , MonadFail , TestFn(..) , truncateTimeOfDay , truncateToMicro , truncateUTCTime , arbText , liftA2 ) where import Init ( TestFn(..), truncateTimeOfDay, truncateUTCTime , truncateToMicro, arbText, GenerateKey(..) , (@/=), (@==), (==@) , assertNotEqual, assertNotEmpty, assertEmpty, asIO , isTravis, RunDb, MonadFail ) -- re-exports import Control.Applicative (liftA2) import Control.Exception (SomeException) import Control.Monad (void, replicateM, liftM, when, forM_) import Control.Monad.Trans.Reader import Database.Persist.TH (mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase, MkPersistSettings(..)) import Database.Persist.Sql.Raw.QQ import Test.Hspec import Test.QuickCheck.Instances () -- testing import Test.HUnit ((@?=),(@=?), Assertion, assertFailure, assertBool) import Control.Monad (unless, (>=>)) import Control.Monad.IO.Unlift (MonadUnliftIO) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Trans.Resource (ResourceT, runResourceT) import qualified Data.ByteString as BS import Data.Int (Int32, Int64) import Data.Text (Text) import qualified Database.MySQL.Base as MySQL import System.Log.FastLogger (fromLogStr) import Database.Persist import Database.Persist.MySQL import Database.Persist.Sql import Database.Persist.TH () _debugOn :: Bool _debugOn = False persistSettings :: MkPersistSettings persistSettings = sqlSettings { mpsGeneric = True } type BackendMonad = SqlBackend runConn :: MonadUnliftIO m => SqlPersistT (LoggingT m) t -> m () runConn f = do travis <- liftIO isTravis let debugPrint = not travis && _debugOn let printDebug = if debugPrint then print . fromLogStr else void . return flip runLoggingT (\_ _ _ s -> printDebug s) $ do -- Since version 5.7.5, MySQL adds a mode value `STRICT_TRANS_TABLES` -- which can cause an exception in MaxLenTest, depending on the server -- configuration. Persistent tests do not need any of the modes which are -- set by default, so it is simplest to clear `sql_mode` for the session. let baseConnectInfo = defaultConnectInfo { connectOptions = connectOptions defaultConnectInfo ++ [MySQL.InitCommand "SET SESSION sql_mode = '';\0"] } _ <- if not travis then withMySQLPool baseConnectInfo { connectHost = "localhost" , connectUser = "test" , connectPassword = "test" , connectDatabase = "test" } 1 $ runSqlPool f else withMySQLPool baseConnectInfo { connectHost = "localhost" , connectUser = "travis" , connectPassword = "" , connectDatabase = "persistent" } 1 $ runSqlPool f return () db :: SqlPersistT (LoggingT (ResourceT IO)) () -> Assertion db actions = do runResourceT $ runConn $ actions >> transactionUndo
naushadh/persistent
persistent-mysql/test/MyInit.hs
mit
3,751
0
18
917
862
533
329
99
3
module Network.Wai.Util ( handleAcceptTypes, noStoreFileUploads, mapHeaders, defHeader, defHeader', replaceHeader, replaceHeader', string, text, textBuilder, json, bytestring, redirect, redirect', stringAscii, stringHeader, stringHeaders, stringHeaders', queryLookup, queryLookupAll ) where import Data.Char (isAscii) import Data.Maybe (fromMaybe, mapMaybe) import Data.List (intercalate) import Control.Monad (liftM2,join) import Data.String (IsString, fromString) import Network.URI (URI, uriIsAbsolute) import Network.HTTP.Types (statusIsRedirection, Status, ResponseHeaders, Header, notAcceptable406) import Network.HTTP.Types.QueryLike (QueryLike, QueryKeyLike, toQuery, toQueryKey) import Network.Wai (Request, responseLBS, requestHeaders) import Network.Wai.Internal (Response(ResponseBuilder,ResponseFile,ResponseStream,ResponseRaw)) import Network.Wai.Parse (BackEnd, parseHttpAccept) import Network.HTTP.Accept (selectAcceptType) import Data.ByteString (ByteString) import Data.Text (Text) import Data.Text.Encoding.Error (lenientDecode) import qualified Data.ByteString.Lazy as LZ import qualified Blaze.ByteString.Builder as Builder import qualified Blaze.ByteString.Builder.Char.Utf8 as Builder import qualified Data.Aeson as Aeson import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy.Builder as TL -- | Build an Application that supports multiple Accept types (Content Negotiation) handleAcceptTypes :: (Monad m) => [(String, m Response)] -> Request -> m Response handleAcceptTypes handlers req = fromMaybe notAcceptable handler where handler = lookup acceptType handlers notAcceptable = string notAcceptable406 [] (intercalate "\n" supportedTypes) acceptType = fromMaybe (head supportedTypes) acceptType' acceptType' = (selectAcceptType supportedTypes . parseHttpAccept) =<< lookup (fromString "Accept") (requestHeaders req) supportedTypes = map fst handlers -- | 'BackeEnd' for 'parseRequestBody' that throws out any file uploads noStoreFileUploads :: BackEnd () noStoreFileUploads _ _ _ = return () -- | Run a function over the headers in a 'Response' mapHeaders :: (ResponseHeaders -> ResponseHeaders) -> Response -> Response mapHeaders f (ResponseFile s h b1 b2) = ResponseFile s (f h) b1 b2 mapHeaders f (ResponseBuilder s h b) = ResponseBuilder s (f h) b mapHeaders f (ResponseStream s h b) = ResponseStream s (f h) b mapHeaders f (ResponseRaw io resp) = ResponseRaw io (mapHeaders f resp) -- | Set a default value for a header in a 'Response' defHeader :: Header -> Response -> Response defHeader h = mapHeaders (defHeader' h) -- | Set a default value for a header in 'ResponseHeaders' defHeader' :: Header -> ResponseHeaders -> ResponseHeaders defHeader' (n, v) headers = case lookup n headers of Just _ -> headers Nothing -> (n, v):headers -- | Set the matching header name to this in a 'Response' replaceHeader :: Header -> Response -> Response replaceHeader h = mapHeaders (replaceHeader' h) -- | Set the matching header name to this in 'ResponseHeaders' replaceHeader' :: Header -> ResponseHeaders -> ResponseHeaders replaceHeader' (n, v) = ((n,v):) . filter ((/=n) . fst) -- | Smart constructor to build a 'Response' from a 'String' string :: (Monad m) => Status -> ResponseHeaders -> String -> m Response string status headers = return . defHeader defCT . ResponseBuilder status headers . Builder.fromString where Just defCT = stringHeader ("Content-Type", "text/plain; charset=utf-8") -- | Smart constructor to build a 'Response' from a 'Text' text :: (Monad m) => Status -> ResponseHeaders -> Text -> m Response text status headers = return . defHeader defCT . ResponseBuilder status headers . Builder.fromText where Just defCT = stringHeader ("Content-Type", "text/plain; charset=utf-8") -- | Smart constructor to build a 'Response' from a 'Data.Text.Lazy.Builder.Builder' textBuilder :: (Monad m) => Status -> ResponseHeaders -> TL.Builder -> m Response textBuilder status headers = return . defHeader defCT . ResponseBuilder status headers . Builder.fromLazyText . TL.toLazyText where Just defCT = stringHeader ("Content-Type", "text/plain; charset=utf-8") -- | Smart constructor to build a JSON 'Response' using Aeson json :: (Monad m, Aeson.ToJSON a) => Status -> ResponseHeaders -> a -> m Response json status headers = return . defHeader defCT . responseLBS status headers . Aeson.encode . Aeson.toJSON where Just defCT = stringHeader ("Content-Type", "application/json; charset=utf-8") class IsByteString a where bytestringToBuilder :: a -> Builder.Builder instance IsByteString ByteString where bytestringToBuilder = Builder.fromByteString instance IsByteString LZ.ByteString where bytestringToBuilder = Builder.fromLazyByteString -- | Smart constructor to build a 'Response' from a 'ByteString' bytestring :: (IsByteString bs, Monad m) => Status -> ResponseHeaders -> bs -> m Response bytestring status headers = return . defHeader defCT . ResponseBuilder status headers . bytestringToBuilder where Just defCT = stringHeader ("Content-Type", "application/octet-stream") -- | Smart constructor to build a redirect -- -- Checks if the 'Status' is a redirection and the 'URI' is absolute redirect :: Status -> ResponseHeaders -> URI -> Maybe Response redirect status headers uri | statusIsRedirection status && uriIsAbsolute uri = do uriBS <- stringAscii (show uri) return $ responseLBS status ((location, uriBS):headers) LZ.empty | otherwise = Nothing where Just location = stringAscii "Location" -- | Smart constructor to build a redirect -- -- Asserts redirect conditions with an irrefutable pattern match, only use -- on hard-coded values. redirect' :: (Monad m) => Status -> ResponseHeaders -> URI -> m Response redirect' status headers uri = let Just r = redirect status headers uri in return r -- | Safely convert a 'String' to types that can only encode ASCII stringAscii :: (IsString s) => String -> Maybe s stringAscii s | all isAscii s = Just (fromString s) | otherwise = Nothing -- | Safely convert a pair of 'String' to a pair suitable for use as a -- 'Header', ensuring only ASCII characters are present. stringHeader :: (IsString s1, IsString s2) => (String, String) -> Maybe (s1, s2) stringHeader (n, v) = liftM2 (,) (stringAscii n) (stringAscii v) -- | Safely convert a list of pairs of 'String' to a pair suitable for -- use as a 'Header', ensuring only ASCII characters are present. stringHeaders :: (IsString s1, IsString s2) => [(String, String)] -> Maybe [(s1, s2)] stringHeaders = mapM stringHeader -- | Unsafely convert a list of pairs of 'String' to a pair suitable for -- use as a 'Header', ensuring only ASCII characters are present. -- -- Asserts success with an irrefutable pattern match, only use on -- hard-coded values. stringHeaders' :: (IsString s1, IsString s2) => [(String, String)] -> [(s1, s2)] stringHeaders' hs = let Just headers = stringHeaders hs in headers -- | Lookup a given key in something that acts like a query queryLookup :: (QueryLike q, QueryKeyLike k) => k -> q -> Maybe Text queryLookup k = fmap (T.decodeUtf8With lenientDecode) . join . lookup (toQueryKey k) . toQuery -- | Get all matches for a given key in something that acts like a query queryLookupAll :: (QueryLike q, QueryKeyLike k) => k -> q -> [Text] queryLookupAll k = map (T.decodeUtf8With lenientDecode) . mapMaybe f . toQuery where f (ik, mv) | ik == k' = mv | otherwise = Nothing k' = toQueryKey k
singpolyma/wai-util
Network/Wai/Util.hs
isc
7,473
46
12
1,151
2,013
1,084
929
117
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Safe #-} module Data.Stack ( Stack , pop , top , push , size ) where import Protolude -- | Stack data structure data Stack a = Stack ![a] deriving (Eq,Show) instance Functor Stack where fmap f (Stack xs) = Stack (fmap f xs) instance Applicative Stack where pure x = Stack [x] (Stack xs) <*> (Stack ys) = Stack (xs <*> ys) instance Alternative Stack where empty = Stack [] (<|>) (Stack xs) (Stack ys) = Stack (xs <|> ys) -- | O(1) Push to the stack -- -- >>> push 0 empty -- Stack [0] -- -- >>> empty & push 0 & push 1 -- Stack [1,0] push :: a -> Stack a -> Stack a push x (Stack xs) = Stack (x:xs) -- | pop an element from the stack -- -- >>> pop empty -- Nothing -- -- >>> pop (push 0 empty) -- Just (0,Stack []) -- -- >>> pop (empty & push 0 & push 1) -- Just (1,Stack [0]) -- pop :: Stack a -> Maybe (a, Stack a) pop (Stack (x:xs)) = Just (x, Stack xs) pop _ = Nothing -- | get the element at the top of the stack -- -- >>> top (push 'c' empty) -- Just 'c' -- -- >>> top empty -- Nothing top :: Stack a -> Maybe a top stk = fmap fst (pop stk) -- | return the size of the stack -- -- >>> size empty -- 0 -- -- >>> size (empty & push 0 & push 1) -- 2 size :: Stack a -> Int size (Stack l) = length l
yogsototh/lish
src/Data/Stack.hs
isc
1,319
0
9
347
401
222
179
29
1
{-# LANGUAGE OverloadedStrings #-} module Web.Larceny.Html where import qualified Data.HashSet as HS import Data.Text (Text) -- retrieved from: https://www.w3.org/TR/html-markup/elements-by-function.html html5Nodes :: HS.HashSet Text html5Nodes = HS.fromList [ -- 5.1. The root element "html", -- root element -- 5.2. Document metadata "head", -- document metadata container "title", -- document title "base", -- base URL "link", -- inter-document relationship metadata "meta", -- metadata CHANGED "style", -- style (presentation) information -- 5.3. Scripting "script", -- embedded script "noscript", -- fallback content for script -- 5.4. Sections "body", -- document body "section", -- section NEW "nav", -- group of navigational links NEW "article", -- article NEW "aside", -- tangential content NEW "h1", -- heading "h2", -- heading "h3", -- heading "h4", -- heading "h5", -- heading "h6", -- heading "hgroup", -- heading group NEW "header", -- header NEW "footer", -- footer NEW "main", -- main VERY NEW (wasn't in the spec linked to above) "address", -- contact information -- 5.5. Grouping content "p", -- paragraph "hr", -- thematic break CHANGED "br", -- line break "pre", -- preformatted text "blockquote", -- block quotation "ol", -- ordered list "ul", -- unordered list "li", -- list item "dl", -- description list "dt", -- term or name "dd", -- description or value "figure", -- figure with optional caption NEW "figcaption", -- figure caption NEW "div", -- generic flow container -- 5.6. Text-level semantics "a", -- hyperlink CHANGED "em", -- emphatic stress "strong", -- strong importance "small", -- small print CHANGED "s", -- struck text CHANGED "cite", -- cited title of a work CHANGED "q", -- quoted text "dfn", -- defining instance "abbr", -- abbreviation "time", -- date and/or time NEW "code", -- code fragment "var", -- variable or placeholder text "samp", -- (sample) output "kbd", -- user input "sub", -- subscript "sup", -- superscript "i", -- offset text conventionally styled in italic CHANGED "b", -- offset text conventionally styled in bold CHANGED "u", -- offset text conventionally styled with an underline CHANGED "mark", -- marked (highlighted) text NEW "ruby", -- ruby annotation NEW "rt", -- ruby text NEW "rp", -- ruby parenthesis NEW "bdi", -- BiDi isolate NEW "bdo", -- BiDi override "span", -- generic span -- 5.7. Edits "ins", -- inserted text "del", -- deleted text -- 5.8. Embedded content "img", -- image "iframe", -- nested browsing context (inline frame) "embed", -- integration point for plugins NEW "object", -- generic external content "param", -- initialization parameters for plugins "video", -- video NEW "audio", -- audio stream NEW "source", -- media source NEW "track", -- supplementary media track NEW "canvas", -- canvas for dynamic graphics NEW "map", -- image-map definition "area", -- image-map hyperlink -- 5.9. Tables "table", -- table "caption", -- table title "colgroup", -- table column group "col", -- table column "tbody", -- table row group "thead", -- table heading group "tfoot", -- table footer row group "tr", -- table row "td", -- table cell "th", -- table header cell -- 5.10. Forms "form", -- user-submittable form "fieldset", -- set of related form controls "legend", -- title or explanatory caption "label", -- caption for a form control "input", -- input control CHANGED "button", -- button "select", -- option-selection form control "datalist", -- predefined options for other controls NEW "optgroup", -- group of options "option", -- option "textarea", -- text input area "keygen", -- key-pair generator/input control NEW "output", -- result of a calculation in a form NEW "progress", -- progress indicator NEW "meter", -- scalar gauge NEW -- 5.11. Interactive elements "details", -- control for additional on-demand information NEW "summary", -- summary, caption, or legend for a details control NEW "command", -- command NEW "menu"] -- list of commands CHANGED html5SelfClosingNodes :: HS.HashSet Text html5SelfClosingNodes = HS.fromList [ "area" , "base" , "br" , "col" , "command" , "embed" , "hr" , "img" , "input" , "keygen" , "link" , "meta" , "param" , "source" , "track" , "wbr"]
positiondev/larceny
src/Web/Larceny/Html.hs
isc
4,676
0
6
1,146
558
406
152
132
1
module Main where import Plugin.Pl.Common import Plugin.Pl.Optimize import Plugin.Pl.Parser import Plugin.Pl.PrettyPrinter import Plugin.Pl.Transform import System.Environment (getArgs) import System.Console.GetOpt data Flag = Verbose | StdIn deriving Eq options :: [OptDescr Flag] options = [ Option ['v'] ["verbose"] (NoArg Verbose) "verbose results" , Option [] ["stdin"] (NoArg StdIn) "read from stdin" ] header :: String header = "Usage: pointfree [OPTION...] query" parseArgs :: [String] -> IO ([Flag], [String]) parseArgs args = case getOpt Permute options args of (flags, nonOptions, []) -> return (flags, nonOptions) (_, _, errs) -> ioError (userError (concat errs ++ usageInfo header options)) getQuery :: [Flag] -> [String] -> IO String getQuery flags nonOptions | StdIn `elem` flags = getLine | otherwise = return $ unwords nonOptions main :: IO () main = do args <- getArgs (flags, nonOptions) <- parseArgs args query <- getQuery flags nonOptions if null query then putStrLn $ usageInfo header options else let verbose = Verbose `elem` flags in pf query verbose pf :: String -> Bool -> IO () pf input verbose = case parsePF input of Right d -> if verbose then do putStrLn "Transformed to pointfree style:" let d' = mapTopLevel transform d putStrLn $ prettyTopLevel d' putStrLn "Optimized expression:" mapM_ (putStrLn . prettyTopLevel) $ mapTopLevel' optimize d' else putStrLn . prettyTopLevel . last . mapTopLevel' optimize $ mapTopLevel transform d Left err -> putStrLn err
jystic/pointfree
Main.hs
mit
1,671
0
14
408
548
283
265
45
3
module Y2016.M07.D05.Solution where import Control.Monad.State import Data.List (intercalate) import qualified Data.Set as Set import Control.Scan.CSV import Data.SymbolTable import Data.SymbolTable.Decompiler import Text.HTML.TagSoup -- convert every name and classname to an encoded value and then save out the -- result as the same XML structure. encodeXMLnames :: FilePath -> IO () encodeXMLnames file = readFile file >>= \junits -> let tags = parseTags junits fromsyms = createSyms tags newtags = map (changeNames fromsyms) tags in putStrLn (renderTags newtags) changeNames :: SymbolTable -> Tag String -> Tag String changeNames from t = (if isTagOpen t then substNames from (('S':) . show) else id) t -- first we need to extract all names (name, classname, project) and load them -- into a symbol table: {-- let syms = execState (mapM_ encodeQname . concat . ([fromAttrib] <*> ["name", "classname", "project"] <*>) . filter isTagOpen $ parseTags html) empty in pure syms --} -- do this for test.xml in this directory {-- Okay the structure is testrun name project tests started failures errors ignored testsuite (name) time testcase (name) (classname) time testcase ... testsuite (name) time testcase ... ... where testsuite name is dot.qualified.name and so is classname So, actually, a better way to go about this is to rend all the qnames, put them into a set and then symbol-table-ize those values, instead of querying the symbol table at each qualifying name. --} createSyms :: [Tag String] -> SymbolTable createSyms tags = let opentags = filter isTagOpen tags -- (parseTags html) qnames = [fromAttrib] <*> replacers <*> opentags qualifers = Set.fromList (concatMap (rend '.') qnames) in execState (mapM_ fromEnumS (Set.toList qualifers)) empty {-- lookupNames :: Tag String -> [String] lookupNames = ([fromAttrib] <*> ["name","classname","project"] <*>) . pure Okay, we have the tags, we have the symbols, now we need to one-for-one replace the qnames with some encoding --} replacers :: [String] replacers = ["name","classname","project"] type ReplaceF a = SymbolTable -> (Int -> String) -> a -> a type Attr = Attribute String substNames :: ReplaceF (Tag String) substNames syms f (TagOpen n attrs) = TagOpen n (map (replaceAttrib syms f) attrs) -- for each of the qname-attributes we need to rend the name and replace it -- with the new name replaceAttrib :: ReplaceF Attr replaceAttrib syms f (x,y) = (x, (if x `elem` replacers then intercalate "." . map (f . intVal syms) . rend '.' else id) y) {-- *Y2016.M07.D05.Solution> encodeXMLnames "Y2016/M07/D01/test.xml" <?xml version="1.0" encoding="UTF-8" ?> <testrun name="S9.S6" project="S0" tests="22" started="22" failures="0" errors="0" ignored="0"> <testsuite name="S5.S7.S4.S32.S8.S1" time="0.0"> <testcase name="S24" classname="S5.S7.S4.S32.S8.S1" time="0.0"></testcase> <testcase name="S23.S33" classname="S5.S7.S4.S32.S8.S1" time="0.0"></testcase> ... --}
geophf/1HaskellADay
exercises/HAD/Y2016/M07/D05/Solution.hs
mit
3,037
0
14
534
501
273
228
34
2
module DarkSky.App.Output where import DarkSky.Response import qualified DarkSky.Response.DataBlock as DB import qualified DarkSky.Response.DataPoint as DP import Data.Maybe (fromMaybe) import Data.Text (unpack) data Output = Output { currentTemperature :: String , currentSummary :: String , next48HoursSummary :: String , weekSummary :: String } deriving (Eq, Show) makeOutput :: Response -> Output makeOutput response = Output { currentTemperature = currentTemperatureString , currentSummary = currentSummaryString , next48HoursSummary = next48HoursSummaryString , weekSummary = weekSummaryString } where currentDP = currently response currentTemperatureString = fromMaybe "No temperature available" $ ((++ "°") . show) <$> (currentDP >>= DP.temperature) currentSummaryString = fromMaybe "No summary available" $ unpack <$> (currentDP >>= DP.summary) next48HoursDB = hourly response next48HoursSummaryString = fromMaybe "No summary available" $ unpack <$> (next48HoursDB >>= DB.summary) weekDB = daily response weekSummaryString = fromMaybe "No summary available" $ unpack <$> (weekDB >>= DB.summary)
peterstuart/dark-sky
src/DarkSky/App/Output.hs
mit
1,196
0
11
226
274
159
115
32
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} module Hogldev.Camera ( Camera(..) , cameraOnKeyboard , cameraOnMouse , cameraOnRender , initCamera , initWithLocation ) where import Graphics.Rendering.OpenGL import Graphics.UI.GLUT (SpecialKey(..)) import Hogldev.Utils import Data.Maybe (catMaybes) stepScale = 0.1 rotationScale = 0.05 edgeStep = 0.1 margin = 10 data Edge = UpperEdge | LowerEdge | LeftEdge | RightEdge deriving (Show, Eq, Enum) data Camera = Camera { cameraPos :: !(Vector3 GLfloat) , cameraTarget :: !(Vector3 GLfloat) , cameraUp :: !(Vector3 GLfloat) , cameraWindowWidth :: !GLsizei , cameraWindowHeight :: !GLsizei , cameraAngleH :: !GLfloat , cameraAngleV :: !GLfloat , cameraMousePos :: !(Vector2 GLint) , cameraOnEdges :: ![Edge] } deriving Show initCamera :: Maybe (Vector3 GLfloat, Vector3 GLfloat, Vector3 GLfloat) -> GLsizei -> GLsizei -> Camera initCamera Nothing width height = initWithLocation (Vector3 0 0 0) (Vector3 0 0 1) (Vector3 0 1 0) width height initCamera (Just (pos, target, up)) width height = initWithLocation pos target up width height initWithLocation :: Vector3 GLfloat -> Vector3 GLfloat -> Vector3 GLfloat -> GLsizei -> GLsizei -> Camera initWithLocation pos target up width height = Camera pos target up width height angleH angleV mousePos [] where mousePos = Vector2 (width `div` 2) (height `div` 2) (Vector3 targetX targetY targetZ) = target (Vector3 hTargetX _ hTargetZ) = normalizeVector (Vector3 targetX 0 targetZ) angleV = - toDegree (asin targetY) angleH | hTargetZ >= 0 && hTargetX >= 0 = 360 - toDegree (asin hTargetZ) | hTargetZ >= 0 = 180 + toDegree (asin hTargetZ) | hTargetX >= 0 = toDegree (asin (-hTargetZ)) | otherwise = 90 + toDegree (asin (-hTargetZ)) cameraOnKeyboard :: SpecialKey -> Camera -> Camera cameraOnKeyboard KeyUp c@Camera{..} = c{ cameraPos = cameraPos + fmap (*stepScale) cameraTarget } cameraOnKeyboard KeyDown c@Camera{..} = c{ cameraPos = cameraPos - fmap (*stepScale) cameraTarget } cameraOnKeyboard KeyLeft c@Camera{..} = c{ cameraPos = cameraPos + fmap (*stepScale) left } where left = normalizeVector ( cameraTarget * cameraUp ) cameraOnKeyboard KeyRight c@Camera{..} = c{ cameraPos = cameraPos + fmap (*stepScale) right } where right = normalizeVector ( cameraUp * cameraTarget ) cameraOnKeyboard _ camera = camera cameraOnMouse :: Position -> Camera -> Camera cameraOnMouse (Position x y) c@Camera{..} = cameraUpdate $ c { cameraAngleH = cameraAngleH + fromIntegral deltaX * rotationScale , cameraAngleV = cameraAngleV + fromIntegral deltaY * rotationScale , cameraOnEdges = catMaybes edges , cameraMousePos = Vector2 x y } where Vector2 deltaX deltaY = Vector2 x y - cameraMousePos edges :: [Maybe Edge] edges = map (uncurry wrapMaybe) [ (deltaX == 0 && x <= margin, LeftEdge) , (deltaX == 0 && x >= cameraWindowWidth - margin, RightEdge) , (deltaY == 0 && y <= margin, UpperEdge) , (deltaY == 0 && y >= cameraWindowHeight - margin, LowerEdge) ] cameraOnRender :: Camera -> Camera cameraOnRender c@Camera{..} | null cameraOnEdges = c | otherwise = cameraUpdate $ c { cameraAngleH = angleH , cameraAngleV = angleV } where (angleH, angleV) = foldl moveTarget (cameraAngleH, cameraAngleV) cameraOnEdges moveTarget :: (GLfloat, GLfloat) -> Edge -> (GLfloat, GLfloat) moveTarget (h, v) UpperEdge = if v > -90 then (h, v - edgeStep) else (h, v) moveTarget (h, v) LowerEdge = if v < 90 then (h, v + edgeStep) else (h, v) moveTarget (h, v) LeftEdge = (h - edgeStep, v) moveTarget (h, v) RightEdge = (h + edgeStep, v) cameraUpdate :: Camera -> Camera cameraUpdate c@Camera{..} = c { cameraTarget = target, cameraUp = up } where vaxis = Vector3 0 1 0 view = normalizeVector $ rotateVector cameraAngleH (Vector3 1 0 0) vaxis haxis = normalizeVector $ vaxis * view target = rotateVector cameraAngleV view haxis up = normalizeVector $ target * haxis
triplepointfive/hogldev
common/Hogldev/Camera.hs
mit
4,653
1
13
1,406
1,460
789
671
124
6
{-| Module : Day16 Description : <http://adventofcode.com/2016/day/16 Day 16: Dragon Checksum> -} {-# OPTIONS_HADDOCK ignore-exports #-} module Day16 (main) where import System.IO.Unsafe (unsafePerformIO) input :: String input = filter (`elem` "01") $ unsafePerformIO $ readFile "day16.txt" fill :: String -> String fill a = let a' = a ++ '0' : map invert (reverse a) in a' ++ fill' a' where fill' a' = b ++ fill' a'' where a'' = a' ++ b; b = '0' : map invert (reverse a') invert '0' = '1'; invert _ = '0' cks :: Int -> String -> String cks 0 = error; cks l = case quotRem l 2 of (l', 0) -> cks l' . ck; _ -> take l where ck (a:b:s) = (if a == b then '1' else '0') : ck s; ck _ = [] main :: IO () main = do let dragon = fill input putStrLn $ cks 272 dragon putStrLn $ cks 35651584 dragon
ephemient/aoc2016
src/Day16.hs
mit
820
0
12
193
345
179
166
17
4
module Main where import Test.DocTest main :: IO () main = doctest ["src/Text/LevenshteinDistance.hs"]
ayachigin/LevenshteinDistance
test/doctests.hs
mit
105
0
6
15
30
17
13
4
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} module Clingo.Internal.Utils ( ClingoException (..), pattern Raw.ErrorRuntime, getException, ClingoWarning (..), warningString, checkAndThrow, marshal0, marshal1, marshal1V, marshal1A, marshal1RT, marshal2, marshal3V, reraiseIO ) where import Control.Monad import Control.Monad.IO.Class import Control.Monad.Catch import Data.Typeable import Data.Text (Text, pack) import Foreign import Foreign.C import qualified Clingo.Raw as Raw data ClingoException = ClingoException Raw.ClingoError String deriving (Show, Typeable) instance Exception ClingoException newtype ClingoWarning = ClingoWarning Raw.ClingoWarning deriving (Show, Typeable) instance Exception ClingoWarning getException :: MonadIO m => m ClingoException getException = liftIO $ do code <- Raw.errorCode estr <- peekCString =<< Raw.errorString code return $ ClingoException code estr {-# INLINE getException #-} warningString :: MonadIO m => ClingoWarning -> m Text warningString (ClingoWarning w) = liftIO $ Raw.warningString w >>= fmap pack . peekCString checkAndThrow :: (MonadIO m, MonadThrow m) => Raw.CBool -> m () checkAndThrow b = unless (toBool b) $ getException >>= throwM {-# INLINE checkAndThrow #-} checkAndThrowRT :: (MonadIO m, MonadThrow m) => m a -> Raw.CBool -> m (Maybe a) checkAndThrowRT a b | toBool b = Just <$> a | otherwise = do exc <- getException case exc of ClingoException Raw.ErrorRuntime _ -> return Nothing _ -> throwM exc {-# INLINE checkAndThrowRT #-} marshal0 :: (MonadIO m, MonadThrow m) => IO Raw.CBool -> m () marshal0 action = liftIO action >>= checkAndThrow {-# INLINE marshal0 #-} marshal1 :: (Storable a, MonadIO m, MonadThrow m) => (Ptr a -> IO Raw.CBool) -> m a marshal1 action = do (res, a) <- liftIO $ alloca $ \ptr -> do res <- action ptr a <- peek ptr return (res, a) checkAndThrow res return a {-# INLINE marshal1 #-} marshal1V :: (Storable a, MonadIO m) => (Ptr a -> IO ()) -> m a marshal1V action = liftIO $ alloca $ \ptr -> do _ <- action ptr peek ptr {-# INLINE marshal1V #-} marshal1RT :: (Storable a, MonadIO m) => (Ptr a -> IO Raw.CBool) -> m (Maybe a) marshal1RT action = liftIO $ alloca $ \ptr -> do res <- action ptr checkAndThrowRT (peek ptr) res {-# INLINE marshal1RT #-} marshal2 :: (Storable a, Storable b, MonadIO m, MonadThrow m) => (Ptr a -> Ptr b -> IO Raw.CBool) -> m (a,b) marshal2 action = do (res, (a,b)) <- liftIO $ alloca $ \ptr1 -> alloca $ \ptr2 -> do res <- action ptr1 ptr2 a <- peek ptr1 b <- peek ptr2 return (res, (a,b)) checkAndThrow res return (a,b) {-# INLINE marshal2 #-} marshal1A :: (Storable a, MonadIO m, MonadThrow m) => (Ptr (Ptr a) -> Ptr CSize -> IO Raw.CBool) -> m [a] marshal1A action = do (res, as) <- liftIO $ alloca $ \ptr1 -> alloca $ \ptr2 -> do res <- action ptr1 ptr2 len <- peek ptr2 arrp <- peek ptr1 arr <- peekArray (fromIntegral len) arrp return (res, arr) checkAndThrow res return as {-# INLINE marshal1A #-} marshal3V :: (Storable a, Storable b, Storable c, MonadIO m) => (Ptr a -> Ptr b -> Ptr c -> IO ()) -> m (a,b,c) marshal3V action = do (a,b,c) <- liftIO $ alloca $ \ptr1 -> alloca $ \ptr2 -> alloca $ \ptr3 -> do _ <- action ptr1 ptr2 ptr3 a <- peek ptr1 b <- peek ptr2 c <- peek ptr3 return (a,b,c) return (a,b,c) {-# INLINE marshal3V #-} reraiseIO :: IO a -> IO Raw.CBool reraiseIO action = catch (action >> return (fromBool True)) $ \(ClingoException e s) -> do withCString s $ Raw.setError e return (fromBool False) {-# INLINE reraiseIO #-}
tsahyt/clingo-haskell
src/Clingo/Internal/Utils.hs
mit
4,113
0
17
1,185
1,477
743
734
126
2
{-# LANGUAGE OverloadedStrings #-} module Network.Bitcoin.Api.WalletSpec where import qualified Data.List as L (find) import Data.Maybe (isJust) import qualified Data.Text as T (pack) import qualified Network.Bitcoin.Api.Wallet as Wallet import Network.Bitcoin.Api.TestUtil (testClient) import Test.Hspec spec :: Spec spec = do describe "when testing wallet functions" $ do it "should be able list unspent transactions" $ do r <- testClient Wallet.listUnspent length r `shouldSatisfy` (>= 1) it "should be able list all accounts" $ do r <- testClient Wallet.listAccounts length r `shouldSatisfy` (>= 1) it "should be able to create a new address under the default account" $ do testClient $ \client -> do addr <- Wallet.newAddress client acc <- Wallet.getAddressAccount client addr acc `shouldBe` (T.pack "") it "should be able to create a new address under a specific account" $ do testClient $ \client -> do addr <- Wallet.newAddressWith client (T.pack "emptyTestAccount") acc <- Wallet.getAddressAccount client addr acc `shouldBe` (T.pack "emptyTestAccount") -- Extra validation that the account also appears in the wallet list <- Wallet.listAccounts client L.find (\(needle, _) -> needle == T.pack "emptyTestAccount") list `shouldSatisfy` isJust -- Extra validation that we can look up the balance of the account balance <- Wallet.getAccountBalance client (T.pack "emptyTestAccount") balance `shouldBe` 0 it "should be able to create a change address" $ do testClient $ \client -> do addr <- Wallet.newChangeAddress client acc <- Wallet.getAddressAccount client addr acc `shouldBe` (T.pack "") it "should be able to move from one account to another" $ do testClient $ \client -> do _ <- Wallet.newAddressWith client (T.pack "testAccount") balance <- Wallet.getAccountBalance client ("") _ <- Wallet.move client "" "testAccount" 1 `shouldReturn` True -- Validate that, after the move, our main account's balance has been -- reduced with exactly 1 BTC (which is the amount we're moving). Wallet.getAccountBalance client ("") `shouldReturn` (balance - 1)
solatis/haskell-bitcoin-api
test/Network/Bitcoin/Api/WalletSpec.hs
mit
2,430
0
23
669
570
290
280
42
1
-- -- -- ------------------ -- Exercise 13.25. ------------------ -- -- -- module E'13'25 where
pascal-knodel/haskell-craft
Chapter 13/E'13'25.hs
mit
106
0
2
24
13
12
1
1
0
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Crypto.Hash.SHA256 import Data.Conduit import Data.Hex import Path import System.IO import qualified Data.ByteString as S import Codec.Archive.SAPCAR bufSink :: Sink S.ByteString IO S.ByteString bufSink = S.concat . reverse <$> bufSink' [] where bufSink' :: [S.ByteString] -> Sink S.ByteString IO [S.ByteString] bufSink' acc = do chunk <- await case chunk of Just chunk' -> bufSink' (chunk':acc) Nothing -> return acc main :: IO () main = do path <- parseRelFile "test/test6.sar" res <- withSapCarPath path $ do entries <- getEntries unless (length entries == 1) $ error "test6.sar should contain exactly one entry!" let entry = head entries unless (cfFileName entry == "pg244.txt") $ error "Entry in test6.sar should be called 'pg244.txt'!" unless (cfFileType entry == CarFile) $ error "Entry in test6.sar should be of type 'file'!" sourceEntry entry bufSink let correctDigest = "B9A995A6C7A9E75326CE524CA14D4DC7959F012A9E81BF0A5CD0E709767EDB63" unless (correctDigest == hex (hash res)) $ error "Wrong sha256 hash for pg244.txt"
VirtualForgeGmbH/hascar
test/Spec.hs
gpl-2.0
1,244
2
15
303
334
162
172
29
2
-- OmegaGB Copyright 2007 Bit Connor -- This program is distributed under the terms of the GNU General Public License ----------------------------------------------------------------------------- -- | -- Module : CpuExecution -- Copyright : (c) Bit Connor 2007 <[email protected]> -- License : GPL -- Maintainer : [email protected] -- Stability : in-progress -- -- OmegaGB -- Game Boy Emulator -- -- This module defines an abstract syntax tree CPU execution monad -- ----------------------------------------------------------------------------- {-# OPTIONS -fglasgow-exts #-} module CpuExecution where import Data.Word import Data.Bits data M_Register = M_A | M_B | M_C | M_D | M_E | M_F | M_H | M_L data M_Register2 = M_AF | M_BC | M_DE | M_HL | M_PC | M_SP data ExecutionAST result where Return :: result -> ExecutionAST result Bind :: (ExecutionAST oldres) -> (oldres -> ExecutionAST result) -> ExecutionAST result WriteRegister :: M_Register -> Word8 -> ExecutionAST () ReadRegister :: M_Register -> ExecutionAST Word8 WriteRegister2 :: M_Register2 -> Word16 -> ExecutionAST () ReadRegister2 :: M_Register2 -> ExecutionAST Word16 WriteMemory :: Word16 -> Word8 -> ExecutionAST () ReadMemory :: Word16 -> ExecutionAST Word8 instance Monad ExecutionAST where return = Return (>>=) = Bind writeRegister = WriteRegister readRegister = ReadRegister writeRegister2 = WriteRegister2 readRegister2 = ReadRegister2 writeMemory = WriteMemory readMemory = ReadMemory writeFlags :: Maybe Bool -> Maybe Bool -> Maybe Bool -> Maybe Bool -> ExecutionAST () writeFlags z n h c = do v0 <- readRegister M_F let v1 = case z of Nothing -> v0 Just True -> setBit v0 7 Just False -> clearBit v0 7 let v2 = case n of Nothing -> v1 Just True -> setBit v1 6 Just False -> clearBit v1 6 let v3 = case h of Nothing -> v2 Just True -> setBit v2 5 Just False -> clearBit v2 5 let v4 = case c of Nothing -> v3 Just True -> setBit v3 4 Just False -> clearBit v3 4 writeRegister M_F v4
bitc/omegagb
src/CpuExecution.hs
gpl-2.0
2,272
0
13
627
528
274
254
-1
-1
{-# LANGUAGE TypeFamilies #-} -- | Test precedences module Tests.Precedence where import Control.Monad.Unit (Unit(..)) import qualified Control.Lens as Lens import Control.Lens.Tuple import qualified Lamdu.Calc.Term as V import qualified Lamdu.Sugar.Parens as Parens import qualified Lamdu.Sugar.Types as Sugar import Test.Lamdu.SugarStubs (($$), ($.)) import qualified Test.Lamdu.SugarStubs as Stub import Test.Lamdu.Prelude test :: Test test = testGroup "precedence" [ testMinOpPrecOperator , testPunnedArgOp , testGetFieldOfApply , testInjectInRec , test445 , test513 , test514 ] -- | Test for issue #471 -- https://trello.com/c/fQmgXuRE/471-operators-on-punned-args-dont-work-require-fragmenting-first testPunnedArgOp :: Test testPunnedArgOp = expr ^? hVal . Sugar._BodyLabeledApply . Sugar.aPunnedArgs . traverse . Sugar.pvVar . annotation . _1 . Sugar.piMinOpPrec & assertEqual "punned arg precedence" (Just 0) & testCase "punned-arg-op" where expr = Sugar.BodyLabeledApply Sugar.LabeledApply { Sugar._aFunc = Stub.defRef "a" "a" & Const & Stub.node , Sugar._aMOpArgs = Nothing , Sugar._aAnnotatedArgs = [] , Sugar._aPunnedArgs = [Sugar.PunnedVar (Stub.defRef "b" "b" & Const & Stub.node) "b"] } & Stub.node & Parens.addToTopLevel 0 testGetFieldOfApply :: Test testGetFieldOfApply = expr ^?! hVal . Sugar._BodySimpleApply . V.appArg . annotation . _1 . Sugar.piNeedParens & assertBool "get field should disambiguate compound expression" & testCase "get-field-of-apply" where expr = Stub.identity $$ (Stub.hole $. "a") & Parens.addToTopLevel 0 testInjectInRec :: Test testInjectInRec = expr ^?! hVal . Sugar._BodyRecord . Sugar.cList . Sugar.tlItems . Lens._Just . Sugar.tlHead . Sugar.tiValue . annotation . _1 . Sugar.piNeedParens & assertBool "get field should disambiguate compound expression" & testCase "inject-in-record" where expr = Sugar.BodyRecord Sugar.Composite { Sugar._cList = Sugar.TaggedList { Sugar._tlAddFirst = Identity Stub.tagRefReplace , Sugar._tlItems = Just Sugar.TaggedListBody { Sugar._tlHead = Stub.mkTag Nothing "x" & Sugar.LeafInject & Sugar.BodyLeaf & Stub.node & Sugar.TaggedItem (Stub.mkTag Nothing "x") Unit (Identity Stub.tagRefReplace) , Sugar._tlTail = [] } } , Sugar._cPunnedItems = [] , Sugar._cTail = Sugar.ClosedCompositeTail (Sugar.ClosedCompositeActions Unit) } & Stub.node & Parens.addToTopLevel 0 testMinOpPrecOperator :: Test testMinOpPrecOperator = do assertBool "Plus in mul need no paren?!" needsParens assertEqual "minOpPrec is not 10?!" 10 minOpPrec & testCase "min-op-prec-infix" where (Sugar.ParenInfo minOpPrec needsParens, _) = expr ^?! hVal . Sugar._BodyLabeledApply . Sugar.aMOpArgs . Lens._Just . Sugar.oaRhs . annotation expr = i 1 `Stub.mul` (i 2 `Stub.plus` i 3) & Parens.addToTopLevel 0 i = Stub.litNum -- Test for https://trello.com/c/OuaLvwiJ/445-wrong-parenthesis test445 :: Test test445 = assertBool "Expected paren" (problemPos ^. annotation . _1 . Sugar.piNeedParens) & testCase "445-wrong-parenthesis" where expr = Stub.identity $$ ((i 1 `Stub.plus` i 2) `Stub.mul` i 3) & Parens.addToTopLevel 0 problemPos = expr ^?! hVal . Sugar._BodySimpleApply . Sugar.appArg . hVal . Sugar._BodyLabeledApply . Sugar.aMOpArgs . Lens._Just . Sugar.oaLhs i = Stub.litNum -- Test for https://trello.com/c/xLzHmxpZ/513-disambiguate-applied-get-field-from-operator-function test513 :: Test test513 = assertBool "Expected paren" (problemPos ^. annotation . _1 . Sugar.piNeedParens) & testCase "513-applied-getfield" where expr = h Stub.$. "minimum" $$ h & Parens.addToTopLevel 0 problemPos = expr ^?! hVal . Sugar._BodySimpleApply . Sugar.appFunc h = Stub.hole -- Test for https://trello.com/c/BGSSndJi/514-disambiguate-fragments-on-lambdas-vs-in-lambdas test514 :: Test test514 = assertBool "Expected paren" (problemPos ^. annotation . _1 . Sugar.piNeedParens) & testCase "514-lambda-in-fragment" where expr = Sugar.BodyFragment Sugar.Fragment { Sugar._fExpr = Sugar.BodyLam Sugar.Lambda { Sugar._lamLightweight = False , Sugar._lamApplyLimit = Sugar.UnlimitedFuncApply , Sugar._lamFunc = (Stub.node . Sugar.BodyLeaf . Sugar.LeafGetVar) (Sugar.GetVar (Stub.nameRef (Stub.taggedEntityName "x" "x")) Sugar.GetNormalVar "x" Sugar.CannotInline) $$ Stub.hole & Stub.funcExpr "x" "x" } & Stub.node , Sugar._fHeal = Unit , Sugar._fTypeMismatch = Nothing , Sugar._fOptions = mempty , Sugar._fOptApply = pure (error "shouldn't affect test") , Sugar._fTagSuffixes = mempty } & Stub.node & Parens.addToTopLevel 0 problemPos = expr ^?! hVal . Sugar._BodyFragment . Sugar.fExpr
lamdu/lamdu
test/Tests/Precedence.hs
gpl-3.0
5,590
0
25
1,626
1,301
700
601
-1
-1
{-# LANGUAGE ViewPatterns,PatternGuards #-} module Lang.Deappify where import Lang.FunctionalFO import Lang.Type import Control.Applicative {- if we apply app enough times to a ptr, then we can unpointer it (f_ptr @ x) @ y = f [x,y], when f_ptr :: FOType tvs _ (ArrTy t1 (ArrTy t2 _)) hmm this might not be exactly right. we need the arities of the functions. f x = e zap needs the source level arities of expressions! -} type Zap v a = (v -> Maybe Int) -> a zapFn :: Function v -> Zap v (Function v) zapFn fn k = fn { fn_body = zapBody (fn_body fn) k } zapBody :: Body v -> Zap v (Body v) zapBody b0 = case b0 of Case e alts -> Case <$> zapExpr e <*> sequence [ (,) p <$> zapBody b | (p,b) <- alts ] Body e -> Body <$> zapExpr e zapExpr :: Expr v -> Zap v (Expr v) zapExpr e0 k = zap $ case e0 of Fun x ts es -> Fun x ts (mapM zapExpr es k) App t1 t2 e1 e2 -> App t1 t2 (zapExpr e1 k) (zapExpr e2 k) Ptr{} -> e0 Lit{} -> e0 where zap e = case pointer e of Just ((x,ts),args) | Just arity <- k x , length args == arity -> Fun x ts (mapM zapExpr args k) _ -> e pointer :: Expr v -> Maybe ((v,[Type v]),[Expr v]) pointer e0 = case e0 of App _ _ fn arg | Just (xt,as) <- pointer fn -> Just (xt,as++[arg]) Ptr x ts -> Just ((x,ts),[]) _ -> Nothing
danr/tfp1
Lang/Deappify.hs
gpl-3.0
1,432
0
14
459
560
281
279
29
5
module Add where import System.Console.GetOpt import Common import Ticket addOptions :: [(OptDescr (AddOptions -> AddOptions))] addOptions = [ Option ['m'] ["message"] (ReqArg setMessage "message") "message" ] data AddOptions = AddOptions { addtitle :: String , addmessage :: String } deriving (Show, Read) setTitle :: String -> AddOptions -> AddOptions setTitle s c = c{addtitle = s} setMessage :: String -> AddOptions -> AddOptions setMessage s c = c{addmessage = s} defaultAddOptions = AddOptions "" "" -- TODO: do not overwrite. add :: AddOptions -> IO () add opt = do checkIsInit newTicket (addtitle opt) (addmessage opt) >>= saveTicket handleAdd args = do (opts, nonopts) <- doArgs addOptions defaultAddOptions [] "add" args True if length nonopts /= 1 then putStrLn "You must tell me the title of the ticket." >> cmdUsage "add" addOptions else do putStrLn $ "Adding " ++ (head nonopts) ++ " - " ++ addmessage opts add (setTitle (head nonopts) opts)
anttisalonen/nix
src/Add.hs
gpl-3.0
1,034
0
14
231
336
176
160
26
2
{-# LANGUAGE PackageImports #-} module Main where import Control.Applicative import Control.Monad import "mtl" Control.Monad.Reader import "mtl" Control.Monad.Error import System.FilePath import System.Directory import System.Log.Logger -- import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Model.SM import HEP.Automation.MadGraph.Card import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Run import HEP.Automation.MadGraph.Type import HEP.Storage.WebDAV -- import qualified Paths_madgraph_auto as PMadGraph import qualified Paths_madgraph_auto_model as PModel -- | getScriptSetup :: IO ScriptSetup getScriptSetup = do homedir <- getHomeDirectory mdldir <- (</> "template") <$> PModel.getDataDir rundir <- (</> "template") <$> PMadGraph.getDataDir return $ SS { modeltmpldir = mdldir , runtmpldir = rundir , sandboxdir = homedir </> "repo/workspace/montecarlo/working" , mg5base = homedir </> "repo/ext/MadGraph5_v1_4_8_4/" , mcrundir = homedir </> "repo/workspace/montecarlo/mc/" } -- | processSetup :: ProcessSetup SM processSetup = PS { model = SM , process = MGProc [] [ "p p > a QCD=99 QED=2 @0 " , "p p > a j QCD=99 QED=2 @1 " ] , processBrief = "ajet" , workname = "ajet" } -- | pset :: ModelParam SM pset = SMParam -- | rsetup = RS { numevent = 10000 , machine = LHC7 ATLAS , rgrun = Auto -- Fixed , rgscale = 200.0 , match = MLM -- NoMatch , cut = DefCut , pythia = RunPYTHIA , lhesanitizer = NoLHESanitize , pgs = NoPGS -- RunPGS (Cone 0.4, WithTau) , uploadhep = NoUploadHEP , setnum = 1 } -- | getWSetup :: IO (WorkSetup SM) getWSetup = WS <$> getScriptSetup <*> pure processSetup <*> pure pset <*> pure rsetup <*> pure (WebDAVRemoteDir "") main = do updateGlobalLogger "MadGraphAuto" (setLevel DEBUG) wsetup <- getWSetup print wsetup work wsetup -- | -- work p -- :: IO () work wsetup = do -- wsetup <- getWSetup r <- flip runReaderT wsetup . runErrorT $ do WS ssetup psetup param rsetup _ <- ask liftIO $ print ssetup let wb = mcrundir ssetup wn = workname psetup b <- liftIO $ (doesDirectoryExist (wb </> wn)) when (not b) $ createWorkDir ssetup psetup cardPrepare generateEvents case (lhesanitizer rsetup,pythia rsetup) of (NoLHESanitize, _) -> return () (LHESanitize pid, RunPYTHIA) -> do sanitizeLHE runPYTHIA -- runHEP2LHE runPGS runClean -- updateBanner (LHESanitize pid, NoPYTHIA) -> do sanitizeLHE -- updateBanner cleanHepFiles print r return () {- -- create working directory (only once for each process) mapM_ (createWorkDir my_ssetup) psetuplist sleep 2 mapM_ (runReaderT cmdSequence) totaltasklist -}
wavewave/lhc-analysis-collection
exe/madgraphRun.hs
gpl-3.0
3,484
0
16
1,300
689
382
307
82
3
{-# 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.AppEngine.Apps.Patch -- 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) -- -- Updates the specified Application resource. You can update the following -- fields: auth_domain - Google authentication domain for controlling user -- access to the application. default_cookie_expiration - Cookie expiration -- policy for the application. iap - Identity-Aware Proxy properties for -- the application. -- -- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ App Engine Admin API Reference> for @appengine.apps.patch@. module Network.Google.Resource.AppEngine.Apps.Patch ( -- * REST Resource AppsPatchResource -- * Creating a Request , appsPatch , AppsPatch -- * Request Lenses , apXgafv , apUploadProtocol , apUpdateMask , apAccessToken , apUploadType , apPayload , apAppsId , apCallback ) where import Network.Google.AppEngine.Types import Network.Google.Prelude -- | A resource alias for @appengine.apps.patch@ method which the -- 'AppsPatch' request conforms to. type AppsPatchResource = "v1" :> "apps" :> Capture "appsId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Application :> Patch '[JSON] Operation -- | Updates the specified Application resource. You can update the following -- fields: auth_domain - Google authentication domain for controlling user -- access to the application. default_cookie_expiration - Cookie expiration -- policy for the application. iap - Identity-Aware Proxy properties for -- the application. -- -- /See:/ 'appsPatch' smart constructor. data AppsPatch = AppsPatch' { _apXgafv :: !(Maybe Xgafv) , _apUploadProtocol :: !(Maybe Text) , _apUpdateMask :: !(Maybe GFieldMask) , _apAccessToken :: !(Maybe Text) , _apUploadType :: !(Maybe Text) , _apPayload :: !Application , _apAppsId :: !Text , _apCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AppsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apXgafv' -- -- * 'apUploadProtocol' -- -- * 'apUpdateMask' -- -- * 'apAccessToken' -- -- * 'apUploadType' -- -- * 'apPayload' -- -- * 'apAppsId' -- -- * 'apCallback' appsPatch :: Application -- ^ 'apPayload' -> Text -- ^ 'apAppsId' -> AppsPatch appsPatch pApPayload_ pApAppsId_ = AppsPatch' { _apXgafv = Nothing , _apUploadProtocol = Nothing , _apUpdateMask = Nothing , _apAccessToken = Nothing , _apUploadType = Nothing , _apPayload = pApPayload_ , _apAppsId = pApAppsId_ , _apCallback = Nothing } -- | V1 error format. apXgafv :: Lens' AppsPatch (Maybe Xgafv) apXgafv = lens _apXgafv (\ s a -> s{_apXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). apUploadProtocol :: Lens' AppsPatch (Maybe Text) apUploadProtocol = lens _apUploadProtocol (\ s a -> s{_apUploadProtocol = a}) -- | Required. Standard field mask for the set of fields to be updated. apUpdateMask :: Lens' AppsPatch (Maybe GFieldMask) apUpdateMask = lens _apUpdateMask (\ s a -> s{_apUpdateMask = a}) -- | OAuth access token. apAccessToken :: Lens' AppsPatch (Maybe Text) apAccessToken = lens _apAccessToken (\ s a -> s{_apAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). apUploadType :: Lens' AppsPatch (Maybe Text) apUploadType = lens _apUploadType (\ s a -> s{_apUploadType = a}) -- | Multipart request metadata. apPayload :: Lens' AppsPatch Application apPayload = lens _apPayload (\ s a -> s{_apPayload = a}) -- | Part of \`name\`. Name of the Application resource to update. Example: -- apps\/myapp. apAppsId :: Lens' AppsPatch Text apAppsId = lens _apAppsId (\ s a -> s{_apAppsId = a}) -- | JSONP apCallback :: Lens' AppsPatch (Maybe Text) apCallback = lens _apCallback (\ s a -> s{_apCallback = a}) instance GoogleRequest AppsPatch where type Rs AppsPatch = Operation type Scopes AppsPatch = '["https://www.googleapis.com/auth/cloud-platform"] requestClient AppsPatch'{..} = go _apAppsId _apXgafv _apUploadProtocol _apUpdateMask _apAccessToken _apUploadType _apCallback (Just AltJSON) _apPayload appEngineService where go = buildClient (Proxy :: Proxy AppsPatchResource) mempty
brendanhay/gogol
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Patch.hs
mpl-2.0
5,575
0
18
1,335
867
507
360
121
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.Content.Orders.Setlineitemmetadata -- 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 (or overrides if it already exists) merchant provided annotations -- in the form of key-value pairs. A common use case would be to supply us -- with additional structured information about a line item that cannot be -- provided via other methods. Submitted key-value pairs can be retrieved -- as part of the orders resource. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.orders.setlineitemmetadata@. module Network.Google.Resource.Content.Orders.Setlineitemmetadata ( -- * REST Resource OrdersSetlineitemmetadataResource -- * Creating a Request , ordersSetlineitemmetadata , OrdersSetlineitemmetadata -- * Request Lenses , ossXgafv , ossMerchantId , ossUploadProtocol , ossAccessToken , ossUploadType , ossPayload , ossOrderId , ossCallback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.orders.setlineitemmetadata@ method which the -- 'OrdersSetlineitemmetadata' request conforms to. type OrdersSetlineitemmetadataResource = "content" :> "v2.1" :> Capture "merchantId" (Textual Word64) :> "orders" :> Capture "orderId" Text :> "setLineItemMetadata" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] OrdersSetLineItemMetadataRequest :> Post '[JSON] OrdersSetLineItemMetadataResponse -- | Sets (or overrides if it already exists) merchant provided annotations -- in the form of key-value pairs. A common use case would be to supply us -- with additional structured information about a line item that cannot be -- provided via other methods. Submitted key-value pairs can be retrieved -- as part of the orders resource. -- -- /See:/ 'ordersSetlineitemmetadata' smart constructor. data OrdersSetlineitemmetadata = OrdersSetlineitemmetadata' { _ossXgafv :: !(Maybe Xgafv) , _ossMerchantId :: !(Textual Word64) , _ossUploadProtocol :: !(Maybe Text) , _ossAccessToken :: !(Maybe Text) , _ossUploadType :: !(Maybe Text) , _ossPayload :: !OrdersSetLineItemMetadataRequest , _ossOrderId :: !Text , _ossCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrdersSetlineitemmetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ossXgafv' -- -- * 'ossMerchantId' -- -- * 'ossUploadProtocol' -- -- * 'ossAccessToken' -- -- * 'ossUploadType' -- -- * 'ossPayload' -- -- * 'ossOrderId' -- -- * 'ossCallback' ordersSetlineitemmetadata :: Word64 -- ^ 'ossMerchantId' -> OrdersSetLineItemMetadataRequest -- ^ 'ossPayload' -> Text -- ^ 'ossOrderId' -> OrdersSetlineitemmetadata ordersSetlineitemmetadata pOssMerchantId_ pOssPayload_ pOssOrderId_ = OrdersSetlineitemmetadata' { _ossXgafv = Nothing , _ossMerchantId = _Coerce # pOssMerchantId_ , _ossUploadProtocol = Nothing , _ossAccessToken = Nothing , _ossUploadType = Nothing , _ossPayload = pOssPayload_ , _ossOrderId = pOssOrderId_ , _ossCallback = Nothing } -- | V1 error format. ossXgafv :: Lens' OrdersSetlineitemmetadata (Maybe Xgafv) ossXgafv = lens _ossXgafv (\ s a -> s{_ossXgafv = a}) -- | The ID of the account that manages the order. This cannot be a -- multi-client account. ossMerchantId :: Lens' OrdersSetlineitemmetadata Word64 ossMerchantId = lens _ossMerchantId (\ s a -> s{_ossMerchantId = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ossUploadProtocol :: Lens' OrdersSetlineitemmetadata (Maybe Text) ossUploadProtocol = lens _ossUploadProtocol (\ s a -> s{_ossUploadProtocol = a}) -- | OAuth access token. ossAccessToken :: Lens' OrdersSetlineitemmetadata (Maybe Text) ossAccessToken = lens _ossAccessToken (\ s a -> s{_ossAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ossUploadType :: Lens' OrdersSetlineitemmetadata (Maybe Text) ossUploadType = lens _ossUploadType (\ s a -> s{_ossUploadType = a}) -- | Multipart request metadata. ossPayload :: Lens' OrdersSetlineitemmetadata OrdersSetLineItemMetadataRequest ossPayload = lens _ossPayload (\ s a -> s{_ossPayload = a}) -- | The ID of the order. ossOrderId :: Lens' OrdersSetlineitemmetadata Text ossOrderId = lens _ossOrderId (\ s a -> s{_ossOrderId = a}) -- | JSONP ossCallback :: Lens' OrdersSetlineitemmetadata (Maybe Text) ossCallback = lens _ossCallback (\ s a -> s{_ossCallback = a}) instance GoogleRequest OrdersSetlineitemmetadata where type Rs OrdersSetlineitemmetadata = OrdersSetLineItemMetadataResponse type Scopes OrdersSetlineitemmetadata = '["https://www.googleapis.com/auth/content"] requestClient OrdersSetlineitemmetadata'{..} = go _ossMerchantId _ossOrderId _ossXgafv _ossUploadProtocol _ossAccessToken _ossUploadType _ossCallback (Just AltJSON) _ossPayload shoppingContentService where go = buildClient (Proxy :: Proxy OrdersSetlineitemmetadataResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Orders/Setlineitemmetadata.hs
mpl-2.0
6,493
0
20
1,499
890
519
371
130
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Logging.Organizations.Locations.Buckets.Views.Create -- 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) -- -- Creates a view over logs in a bucket. A bucket may contain a maximum of -- 50 views. -- -- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.organizations.locations.buckets.views.create@. module Network.Google.Resource.Logging.Organizations.Locations.Buckets.Views.Create ( -- * REST Resource OrganizationsLocationsBucketsViewsCreateResource -- * Creating a Request , organizationsLocationsBucketsViewsCreate , OrganizationsLocationsBucketsViewsCreate -- * Request Lenses , olbvcParent , olbvcXgafv , olbvcUploadProtocol , olbvcViewId , olbvcAccessToken , olbvcUploadType , olbvcPayload , olbvcCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.organizations.locations.buckets.views.create@ method which the -- 'OrganizationsLocationsBucketsViewsCreate' request conforms to. type OrganizationsLocationsBucketsViewsCreateResource = "v2" :> Capture "parent" Text :> "views" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "viewId" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] LogView :> Post '[JSON] LogView -- | Creates a view over logs in a bucket. A bucket may contain a maximum of -- 50 views. -- -- /See:/ 'organizationsLocationsBucketsViewsCreate' smart constructor. data OrganizationsLocationsBucketsViewsCreate = OrganizationsLocationsBucketsViewsCreate' { _olbvcParent :: !Text , _olbvcXgafv :: !(Maybe Xgafv) , _olbvcUploadProtocol :: !(Maybe Text) , _olbvcViewId :: !(Maybe Text) , _olbvcAccessToken :: !(Maybe Text) , _olbvcUploadType :: !(Maybe Text) , _olbvcPayload :: !LogView , _olbvcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrganizationsLocationsBucketsViewsCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olbvcParent' -- -- * 'olbvcXgafv' -- -- * 'olbvcUploadProtocol' -- -- * 'olbvcViewId' -- -- * 'olbvcAccessToken' -- -- * 'olbvcUploadType' -- -- * 'olbvcPayload' -- -- * 'olbvcCallback' organizationsLocationsBucketsViewsCreate :: Text -- ^ 'olbvcParent' -> LogView -- ^ 'olbvcPayload' -> OrganizationsLocationsBucketsViewsCreate organizationsLocationsBucketsViewsCreate pOlbvcParent_ pOlbvcPayload_ = OrganizationsLocationsBucketsViewsCreate' { _olbvcParent = pOlbvcParent_ , _olbvcXgafv = Nothing , _olbvcUploadProtocol = Nothing , _olbvcViewId = Nothing , _olbvcAccessToken = Nothing , _olbvcUploadType = Nothing , _olbvcPayload = pOlbvcPayload_ , _olbvcCallback = Nothing } -- | Required. The bucket in which to create the view -- \"projects\/[PROJECT_ID]\/locations\/[LOCATION_ID]\/buckets\/[BUCKET_ID]\" -- Example: -- \"projects\/my-logging-project\/locations\/my-location\/buckets\/my-bucket\" olbvcParent :: Lens' OrganizationsLocationsBucketsViewsCreate Text olbvcParent = lens _olbvcParent (\ s a -> s{_olbvcParent = a}) -- | V1 error format. olbvcXgafv :: Lens' OrganizationsLocationsBucketsViewsCreate (Maybe Xgafv) olbvcXgafv = lens _olbvcXgafv (\ s a -> s{_olbvcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). olbvcUploadProtocol :: Lens' OrganizationsLocationsBucketsViewsCreate (Maybe Text) olbvcUploadProtocol = lens _olbvcUploadProtocol (\ s a -> s{_olbvcUploadProtocol = a}) -- | Required. The id to use for this view. olbvcViewId :: Lens' OrganizationsLocationsBucketsViewsCreate (Maybe Text) olbvcViewId = lens _olbvcViewId (\ s a -> s{_olbvcViewId = a}) -- | OAuth access token. olbvcAccessToken :: Lens' OrganizationsLocationsBucketsViewsCreate (Maybe Text) olbvcAccessToken = lens _olbvcAccessToken (\ s a -> s{_olbvcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). olbvcUploadType :: Lens' OrganizationsLocationsBucketsViewsCreate (Maybe Text) olbvcUploadType = lens _olbvcUploadType (\ s a -> s{_olbvcUploadType = a}) -- | Multipart request metadata. olbvcPayload :: Lens' OrganizationsLocationsBucketsViewsCreate LogView olbvcPayload = lens _olbvcPayload (\ s a -> s{_olbvcPayload = a}) -- | JSONP olbvcCallback :: Lens' OrganizationsLocationsBucketsViewsCreate (Maybe Text) olbvcCallback = lens _olbvcCallback (\ s a -> s{_olbvcCallback = a}) instance GoogleRequest OrganizationsLocationsBucketsViewsCreate where type Rs OrganizationsLocationsBucketsViewsCreate = LogView type Scopes OrganizationsLocationsBucketsViewsCreate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/logging.admin"] requestClient OrganizationsLocationsBucketsViewsCreate'{..} = go _olbvcParent _olbvcXgafv _olbvcUploadProtocol _olbvcViewId _olbvcAccessToken _olbvcUploadType _olbvcCallback (Just AltJSON) _olbvcPayload loggingService where go = buildClient (Proxy :: Proxy OrganizationsLocationsBucketsViewsCreateResource) mempty
brendanhay/gogol
gogol-logging/gen/Network/Google/Resource/Logging/Organizations/Locations/Buckets/Views/Create.hs
mpl-2.0
6,474
0
18
1,422
869
508
361
131
1
{-# LANGUAGE LambdaCase #-} module Reactive ( Value(..) , DynValue (..) , Closure , newDyn , assignDyn , readDyn , readDynIO , writeDynSTM , writeDynIO , destroyDynSTM , destroyDynIO , withDyn , checkStoreAndReturn , storeAndReturn , withDyn2 , withDyn3 , delay , bind , bindWith , clockTime , bindLinear ) where import Control.Concurrent import Control.Concurrent.STM import Control.Monad (void) import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Class (lift,MonadTrans) import Control.Applicative ((<$>)) import System.Clock import GHC.Conc.Sync (unsafeIOToSTM) data Value a = Value a | Destroyed deriving (Show) data DynValue a = DynValue (TVar (Value a)) type Closure s a = StateT (Maybe s) STM (Value a) newDyn :: a -> IO (DynValue a) newDyn a = DynValue <$> newTVarIO (Value a) -- | Assign a closure a to dynamic variable assignDyn :: Closure s a -> DynValue a -> IO () assignDyn f v = assignDynWithDelay 0 f v -- | Assign a closure a to dynamic variable with a specific delay assignDynWithDelay :: Int -> Closure s a -> DynValue a -> IO () assignDynWithDelay d f (DynValue var) = do -- Set initial value synchronously (val,newState) <- exec1 Nothing case val of Destroyed -> return () _ -> void (forkIO (exec newState)) where exec1 initState = atomically $ do -- We do not update a Destroyed variable oldv <- readTVar var case oldv of Destroyed -> return (oldv, initState) _ -> do (v,s) <- runStateT f initState writeTVar var v return (v,s) exec initState = do (val,newState) <- exec1 initState case val of Destroyed -> return () _ -> do -- Make the spinning thread sleep a little bit if necessary if d > 0 then threadDelay d else yield exec newState readDynIO :: DynValue a -> IO (Value a) readDynIO (DynValue a) = readTVarIO a writeDynSTM :: DynValue a -> a -> STM () writeDynSTM (DynValue a) v = do old <- readTVar a case old of Destroyed -> return () _ -> writeTVar a (Value v) writeDynIO :: DynValue a -> a -> IO () writeDynIO a v = atomically $ writeDynSTM a v destroyDynSTM :: DynValue a -> STM () destroyDynSTM (DynValue a) = writeTVar a Destroyed destroyDynIO :: DynValue a -> IO () destroyDynIO = atomically . destroyDynSTM readDyn :: DynValue a -> Closure s a readDyn (DynValue v) = lift $ readTVar v -- | Use a dynamic value. If the value is Destroyed, the closure returns -- Destroyed too withDyn :: DynValue a -> (a -> Closure s b) -> Closure s b withDyn dyn f = do v <- readDyn dyn case v of Destroyed -> return Destroyed Value x -> f x -- | Store state and return a value storeAndReturn :: s -> b -> Closure s b storeAndReturn new ret = do put (Just new) return (Value ret) -- | Retry if old state is equal to the new one. -- Otherwise, call storeAndReturn checkStoreAndReturn :: Eq s => s -> b -> Closure s b checkStoreAndReturn new ret = do -- check that new state is different get >>= \case Just old | old == new ->lift $ retry _ -> storeAndReturn new ret withDyn1 :: (Eq a) => (a -> r) -> DynValue a -> Closure a r withDyn1 f a = withDyn a $ \a' -> checkStoreAndReturn a' (f a') withDyn2 :: (Eq a, Eq b) => (a -> b -> r) -> DynValue a -> DynValue b -> Closure (a,b) r withDyn2 f a b = withDyn a $ \a' -> withDyn b $ \b' -> checkStoreAndReturn (a',b') (f a' b') withDyn3 :: (Eq a, Eq b, Eq c) => (a -> b -> c -> r) -> DynValue a -> DynValue b -> DynValue c -> Closure (a,b,c) r withDyn3 f a b c = withDyn a $ \a' -> withDyn b $ \b' -> withDyn c $ \c' -> checkStoreAndReturn (a',b',c') (f a' b' c') -- | Delay value changes -- -- When the source is destroyed, the target is destroyed too (without any -- delay) -- -- If the source changes too fast, some values may be missed (it depends on the -- thread scheduler). delay :: Eq a => Int -> a -> DynValue a -> Closure (Int,a,[a],[a]) a delay n def v = withDyn v $ \y -> do get >>= \case Nothing -> storeAndReturn (n,y,[y],[]) def Just st -> case st of (_,lst,_,_) | lst == y -> lift $ retry (0,_,ys,x:xs) -> storeAndReturn (0,y,y:ys,xs) x (0,_,ys,[]) -> let (x:xs) = reverse (y:ys) in storeAndReturn (0,y,[],xs) x (m,_,ys,xs) -> storeAndReturn (m-1,y,y:ys,xs) def binderWith :: Eq a => (a -> r) -> DynValue a -> Closure a r binderWith f = withDyn1 f binder :: Eq a => DynValue a -> Closure a a binder = binderWith id -- | Bind a value to another bind :: Eq a => DynValue a -> DynValue a -> IO () bind = assignDyn . binder -- | Bind a value to another with the given modifier function bindWith :: Eq a => (a -> r) -> DynValue a -> DynValue r -> IO () bindWith f = assignDyn . binderWith f -- | Return monotonic clock time (arbitrary origin). This can be used for -- animations clockTime :: MonadTrans t => t STM TimeSpec clockTime = lift $ unsafeIOToSTM (getTime Monotonic) binderLinear :: (Eq a, Num a, Ord a, Integral a) => Float -> DynValue a -> DynValue a -> Closure (TimeSpec,Float) a binderLinear speed src tgt = do let absSpeed = abs speed * (1e-9 :: Float) withDyn src $ \x2 -> withDyn tgt $ \x1 -> if x1 == x2 then lift $ retry else do t2 <- clockTime get >>= \case Nothing -> storeAndReturn (t2,0) x1 Just (t1,dx) -> let tt t = fromIntegral (sec t) * (1e9 :: Float) + (fromIntegral $ nsec t) dt = tt t2 - tt t1 dir = if x2-x1 > 0 then 1 else -1 realx = fromIntegral x1 + dir * absSpeed * dt + dx x' = ceiling realx x = if dir > 0 then min x' x2 else max x' x2 dx' = realx - fromIntegral x' in storeAndReturn (t2,dx') x -- | Linear binding -- -- Speed is in unit/sec bindLinear :: (Eq a, Num a, Ord a, Integral a) => Float -> DynValue a -> DynValue a -> IO () bindLinear speed src tgt = assignDynWithDelay animDelay (binderLinear speed src tgt) tgt -- | Animation delay (milliseconds) animDelay :: Int animDelay = 100
hsyl20/reactive-stm
src/lib/Reactive.hs
lgpl-3.0
6,536
0
26
2,002
2,369
1,218
1,151
156
5
main = do putStrLn "First build!"
thelastnode/jam-jukebox
JamJukebox.hs
unlicense
35
0
7
7
12
5
7
2
1
module Language.Ratscript.Parser.Type ( Parser , ParserState , Operator ) where import Control.Monad.State import Data.Text (Text) import qualified Text.Parsec as P import qualified Text.Parsec.Expr as P import Text.Parsec.Text () ------------------------------------------------------------------------ type Parser a = P.ParsecT Text () ParserState a type ParserState = State P.SourcePos type Operator a = P.Operator Text () ParserState a
jystic/ratscript
src/Language/Ratscript/Parser/Type.hs
apache-2.0
493
0
6
105
113
71
42
12
0
{- Abstract Data Type for Ordered Schemas Toon Nolten Since a schema is nothing more than a set, maybe use RedBlackTree.hs? -} {-# LANGUAGE DataKinds, TypeFamilies #-} module OrderedSchema where import Universe import Data.List (sort, insert) data Bottom type family So (b :: Bool) type instance So True = () type instance So False = Bottom type SchemaDescription = String type Attribute = (String, U) data Schema = Sorted [Attribute] mkSchema :: [Attribute] -> Schema mkSchema xs = Sorted (sort xs) expandSchema :: Attribute -> Schema -> Schema expandSchema x (Sorted xs) = Sorted (insert x xs) schemify :: SchemaDescription -> Schema schemify _sdesc = undefined disjoint :: Schema -> Schema -> Bool disjoint (Sorted schema1) (Sorted schema2) = disjoint' schema1 schema2 where disjoint' :: [Attribute] -> [Attribute] -> Bool disjoint' [] _ = True disjoint' _ [] = True disjoint' (x : xs) (y : ys) | x < y = disjoint' xs (y : ys) | x == y = False | x > y = disjoint' (x : xs) ys sub :: Schema -> Schema -> Bool sub (Sorted littleSchema) (Sorted bigSchema) = sub' littleSchema bigSchema where sub' :: [Attribute] -> [Attribute] -> Bool sub' [] _ = True sub' _ [] = False sub' (x : xs) (y : ys) | x < y = False | x == y = sub' xs ys | x > y = sub' (x : xs) ys same :: Schema -> Schema -> Bool same (Sorted schema1) (Sorted schema2) = same' schema1 schema2 where same' :: [Attribute] -> [Attribute] -> Bool same' [] [] = True same' ((nm1, ty1) : xs) ((nm2, ty2) : ys) = nm1 == nm2 && ty1 == ty2 && same' xs ys same' _ _ = False --occurs :: String -> Schema -> Bool --occurs nm (Sorted s) = nm `elem` map fst s -- --type family Occurs (nm :: String) (s :: Schema) :: Bool -- --class Occurs (nm :: String) (s :: Schema) where --instance Occurs nm ((nm,u) : s') where lookup :: String -> Schema -> So (occurs nm s) -> U lookup nm (Sorted s) _p = lookup' nm s where lookup' :: String -> [Attribute] -> U lookup' _ [] = undefined lookup' nm' ((name, typ) : s') | nm == name = typ | otherwise = lookup' nm' s' append :: Schema -> Schema -> Schema append (Sorted s) (Sorted s') = mkSchema (s ++ s')
toonn/haskell-casestt
OrderedSchema.hs
bsd-2-clause
2,292
0
10
611
828
436
392
-1
-1
{-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE DeriveDataTypeable, DeriveFunctor #-} ----------------------------------------------------------------------------- -- | -- Module : Haddock.Types -- Copyright : (c) Simon Marlow 2003-2006, -- David Waern 2006-2009 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Types that are commonly used through-out Haddock. Some of the most -- important types are defined here, like 'Interface' and 'DocName'. ----------------------------------------------------------------------------- module Haddock.Types ( module Haddock.Types , HsDocString, LHsDocString ) where import Control.Exception import Control.Arrow import Data.Typeable import Data.Map (Map) import qualified Data.Map as Map import GHC hiding (NoLink) import Name ----------------------------------------------------------------------------- -- * Convenient synonyms ----------------------------------------------------------------------------- type IfaceMap = Map Module Interface type InstIfaceMap = Map Module InstalledInterface type DocMap = Map Name (Doc DocName) type SrcMap = Map PackageId FilePath type Decl = LHsDecl Name type GhcDocHdr = Maybe LHsDocString type DocPaths = (FilePath, Maybe FilePath) -- paths to HTML and sources ----------------------------------------------------------------------------- -- * Interface ----------------------------------------------------------------------------- -- | 'Interface' holds all information used to render a single Haddock page. -- It represents the /interface/ of a module. The core business of Haddock -- lies in creating this structure. Note that the record contains some fields -- that are only used to create the final record, and that are not used by the -- backends. data Interface = Interface { -- | The module represented by this interface. ifaceMod :: Module, -- | Original file name of the module. ifaceOrigFilename :: FilePath, -- | Textual information about the module. ifaceInfo :: !(HaddockModInfo Name), -- | Documentation header. ifaceDoc :: !(Maybe (Doc Name)), -- | Documentation header with link information. ifaceRnDoc :: Maybe (Doc DocName), -- | Haddock options for this module (prune, ignore-exports, etc). ifaceOptions :: ![DocOption], -- | Declarations originating from the module. Excludes declarations without -- names (instances and stand-alone documentation comments). Includes -- names of subordinate declarations mapped to their parent declarations. ifaceDeclMap :: Map Name DeclInfo, -- | Documentation of declarations originating from the module (including -- subordinates). ifaceRnDocMap :: Map Name (DocForDecl DocName), ifaceSubMap :: Map Name [Name], ifaceExportItems :: ![ExportItem Name], ifaceRnExportItems :: [ExportItem DocName], -- | All names exported by the module. ifaceExports :: ![Name], -- | All \"visible\" names exported by the module. -- A visible name is a name that will show up in the documentation of the -- module. ifaceVisibleExports :: ![Name], -- | Instances exported by the module. ifaceInstances :: ![Instance], -- | Documentation of instances defined in the module. ifaceInstanceDocMap :: Map Name (Doc Name) } -- | A smaller version of 'Interface' that can be created from Haddock's -- interface files ('InterfaceFile'). data InstalledInterface = InstalledInterface { -- | The module represented by this interface. instMod :: Module, -- | Textual information about the module. instInfo :: HaddockModInfo Name, -- | Documentation of declarations originating from the module (including -- subordinates). instDocMap :: Map Name (DocForDecl Name), -- | All names exported by this module. instExports :: [Name], -- | All \"visible\" names exported by the module. -- A visible name is a name that will show up in the documentation of the -- module. instVisibleExports :: [Name], -- | Haddock options for this module (prune, ignore-exports, etc). instOptions :: [DocOption], instSubMap :: Map Name [Name] } -- | Convert an 'Interface' to an 'InstalledInterface' toInstalledIface :: Interface -> InstalledInterface toInstalledIface interface = InstalledInterface { instMod = ifaceMod interface, instInfo = ifaceInfo interface, instDocMap = fmap unrenameDocForDecl $ ifaceRnDocMap interface, instExports = ifaceExports interface, instVisibleExports = ifaceVisibleExports interface, instOptions = ifaceOptions interface, instSubMap = ifaceSubMap interface } ----------------------------------------------------------------------------- -- * Export items & declarations ----------------------------------------------------------------------------- data ExportItem name = ExportDecl { -- | A declaration expItemDecl :: LHsDecl name, -- | Maybe a doc comment, and possibly docs for arguments (if this -- decl is a function or type-synonym) expItemMbDoc :: DocForDecl name, -- | Subordinate names, possibly with documentation expItemSubDocs :: [(name, DocForDecl name)], -- | Instances relevant to this declaration, possibly with documentation expItemInstances :: [DocInstance name] } -- ^ An exported declaration | ExportNoDecl { expItemName :: name, -- | Subordinate names expItemSubs :: [name] } -- ^ An exported entity for which we have no -- documentation (perhaps because it resides in -- another package) | ExportGroup { -- | Section level (1, 2, 3, ... ) expItemSectionLevel :: Int, -- | Section id (for hyperlinks) expItemSectionId :: String, -- | Section heading text expItemSectionText :: Doc name } -- ^ A section heading | ExportDoc (Doc name) -- ^ Some documentation | ExportModule Module -- ^ A cross-reference to another module -- | A declaration that may have documentation, including its subordinates, -- which may also have documentation type DeclInfo = (Decl, DocForDecl Name, [(Name, DocForDecl Name)]) -- | Arguments and result are indexed by Int, zero-based from the left, -- because that's the easiest to use when recursing over types. type FnArgsDoc name = Map Int (Doc name) type DocForDecl name = (Maybe (Doc name), FnArgsDoc name) noDocForDecl :: DocForDecl name noDocForDecl = (Nothing, Map.empty) unrenameDocForDecl :: DocForDecl DocName -> DocForDecl Name unrenameDocForDecl (mbDoc, fnArgsDoc) = (fmap unrenameDoc mbDoc, fmap unrenameDoc fnArgsDoc) ----------------------------------------------------------------------------- -- * Hyperlinking ----------------------------------------------------------------------------- -- | An environment used to create hyper-linked syntax. type LinkEnv = Map Name Module -- | An extension of 'Name' that may contain the preferred place to link to in -- the documentation. data DocName = Documented Name Module | Undocumented Name deriving Eq -- TODO: simplify to data DocName = DocName Name (Maybe Module) -- | The 'OccName' of this name. docNameOcc :: DocName -> OccName docNameOcc = nameOccName . getName instance NamedThing DocName where getName (Documented name _) = name getName (Undocumented name) = name ----------------------------------------------------------------------------- -- * Instances ----------------------------------------------------------------------------- -- | An instance head that may have documentation. type DocInstance name = (InstHead name, Maybe (Doc name)) -- | The head of an instance. Consists of a context, a class name and a list of -- instance types. type InstHead name = ([HsPred name], name, [HsType name]) ----------------------------------------------------------------------------- -- * Documentation comments ----------------------------------------------------------------------------- type LDoc id = Located (Doc id) data Doc id = DocEmpty | DocAppend (Doc id) (Doc id) | DocString String | DocParagraph (Doc id) | DocIdentifier [id] | DocModule String | DocEmphasis (Doc id) | DocMonospaced (Doc id) | DocUnorderedList [Doc id] | DocOrderedList [Doc id] | DocDefList [(Doc id, Doc id)] | DocCodeBlock (Doc id) | DocURL String | DocPic String | DocAName String | DocExamples [Example] deriving (Eq, Show, Functor) unrenameDoc :: Doc DocName -> Doc Name unrenameDoc = fmap getName data Example = Example { exampleExpression :: String , exampleResult :: [String] } deriving (Eq, Show) exampleToString :: Example -> String exampleToString (Example expression result) = ">>> " ++ expression ++ "\n" ++ unlines result data DocMarkup id a = Markup { markupEmpty :: a, markupString :: String -> a, markupParagraph :: a -> a, markupAppend :: a -> a -> a, markupIdentifier :: [id] -> a, markupModule :: String -> a, markupEmphasis :: a -> a, markupMonospaced :: a -> a, markupUnorderedList :: [a] -> a, markupOrderedList :: [a] -> a, markupDefList :: [(a,a)] -> a, markupCodeBlock :: a -> a, markupURL :: String -> a, markupAName :: String -> a, markupPic :: String -> a, markupExample :: [Example] -> a } data HaddockModInfo name = HaddockModInfo { hmi_description :: Maybe (Doc name), hmi_portability :: Maybe String, hmi_stability :: Maybe String, hmi_maintainer :: Maybe String } emptyHaddockModInfo :: HaddockModInfo a emptyHaddockModInfo = HaddockModInfo { hmi_description = Nothing, hmi_portability = Nothing, hmi_stability = Nothing, hmi_maintainer = Nothing } ----------------------------------------------------------------------------- -- * Options ----------------------------------------------------------------------------- {-! for DocOption derive: Binary !-} -- | Source-level options for controlling the documentation. data DocOption = OptHide -- ^ This module should not appear in the docs | OptPrune | OptIgnoreExports -- ^ Pretend everything is exported | OptNotHome -- ^ Not the best place to get docs for things -- exported by this module. deriving (Eq, Show) ----------------------------------------------------------------------------- -- * Error handling ----------------------------------------------------------------------------- -- A monad which collects error messages, locally defined to avoid a dep on mtl type ErrMsg = String newtype ErrMsgM a = Writer { runWriter :: (a, [ErrMsg]) } instance Functor ErrMsgM where fmap f (Writer (a, msgs)) = Writer (f a, msgs) instance Monad ErrMsgM where return a = Writer (a, []) m >>= k = Writer $ let (a, w) = runWriter m (b, w') = runWriter (k a) in (b, w ++ w') tell :: [ErrMsg] -> ErrMsgM () tell w = Writer ((), w) -- Exceptions -- | Haddock's own exception type data HaddockException = HaddockException String deriving Typeable instance Show HaddockException where show (HaddockException str) = str throwE :: String -> a instance Exception HaddockException throwE str = throw (HaddockException str) -- In "Haddock.Interface.Create", we need to gather -- @Haddock.Types.ErrMsg@s a lot, like @ErrMsgM@ does, -- but we can't just use @GhcT ErrMsgM@ because GhcT requires the -- transformed monad to be MonadIO. newtype ErrMsgGhc a = WriterGhc { runWriterGhc :: (Ghc (a, [ErrMsg])) } --instance MonadIO ErrMsgGhc where -- liftIO = WriterGhc . fmap (\a->(a,[])) liftIO --er, implementing GhcMonad involves annoying ExceptionMonad and --WarnLogMonad classes, so don't bother. liftGhcToErrMsgGhc :: Ghc a -> ErrMsgGhc a liftGhcToErrMsgGhc = WriterGhc . fmap (\a->(a,[])) liftErrMsg :: ErrMsgM a -> ErrMsgGhc a liftErrMsg = WriterGhc . return . runWriter -- for now, use (liftErrMsg . tell) for this --tell :: [ErrMsg] -> ErrMsgGhc () --tell msgs = WriterGhc $ return ( (), msgs ) instance Functor ErrMsgGhc where fmap f (WriterGhc x) = WriterGhc (fmap (first f) x) instance Monad ErrMsgGhc where return a = WriterGhc (return (a, [])) m >>= k = WriterGhc $ runWriterGhc m >>= \ (a, msgs1) -> fmap (second (msgs1 ++)) (runWriterGhc (k a))
nominolo/haddock2
src/Haddock/Types.hs
bsd-2-clause
12,711
0
13
2,726
2,127
1,251
876
189
1
module BlackjackClient where import BlackjackData import Network.NetSpec import Network.NetSpec.Json import Control.Monad (void) import Data.List (intercalate) import System.Environment (getArgs) import Text.Printf (printf) readInt :: String -> Int readInt = read data ClientState = CS { myIndex :: Int } askAction :: Hand -> IO BlackjackClientMessage askAction _ = putStrLn "Hit or Stand?" >> read <$> getLine botAction :: Hand -> IO BlackjackClientMessage botAction h | hiVal h > 17 = putStrLn "Stand" >> return Stand | loVal h > 14 = putStrLn "Stand" >> return Stand | otherwise = putStrLn "Hit" >> return Hit resolution :: String -> ClientState -> BlackjackState -> IO () resolution str (CS i) (BJ hs _) = printEnd hs i >> putStrLn str win :: ClientState -> BlackjackState -> IO () win = resolution "You win!" lose :: ClientState -> BlackjackState -> IO () lose = resolution "You lose!" printEnd :: [Hand] -> Int -> IO () printEnd [h0,h1] i = let (you, opp) = if i == 0 then (h0,h1) else (h1,h0) in do putStrLn $ replicate 40 '-' void $ printf "You: %s (%d)\n" (show you) (bestVal you) void $ printf "Them: %s (%d)\n" (show opp) (bestVal opp) printEnd _ _ = error "Unexpected number of hands" displayTurn :: Hand -> Card -> Int -> IO () displayTurn hand c n = do void $ printf "You: %s" (show hand) putStrLn $ replicate 20 ' ' void $ printf "Opponent: [%s,%s]\n" (show c) oHand where oHand = intercalate "," $ replicate (pred n) "|??|" main :: IO () main = do (host:port:bot) <- getArgs let chooseAction = if null bot then askAction else botAction runSpec ClientSpec { _conns = [(host, PortNumber (fromIntegral $ readInt port))] , _begin = \[h] -> do Just m <- receive h case m of YouAre i -> return $ CS i , _loop = \[h] s -> do Just m <- receive h case m of YourTurn hand c n -> do displayTurn hand c n action <- chooseAction hand h ! action continue s YouWin gs -> win s gs >> stop s YouLose gs -> lose s gs >> stop s , _end = \_ _ -> return () }
DanBurton/netspec
examples/BlackjackClient.hs
bsd-3-clause
2,209
0
19
618
864
426
438
57
4
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module Duckling.Ordinal.Types where import Control.DeepSeq import Data.Aeson import Data.Hashable import Data.Text (Text) import GHC.Generics import Prelude import Duckling.Resolve (Resolve(..)) newtype OrdinalData = OrdinalData { value :: Int } deriving (Eq, Generic, Hashable, Show, Ord, NFData) instance Resolve OrdinalData where type ResolvedValue OrdinalData = OrdinalData resolve _ _ x = Just (x, False) instance ToJSON OrdinalData where toJSON (OrdinalData value) = object [ "type" .= ("value" :: Text) , "value" .= value ] isBetween :: Ord a => a -> a -> a -> Bool isBetween x low high = low <= x && x <= high
facebookincubator/duckling
Duckling/Ordinal/Types.hs
bsd-3-clause
1,016
0
9
180
235
135
100
24
1
module Data.Composition where infixr 9 .* infixr 9 .** infixr 9 .*** (.*) :: (Functor f, Functor f1) => (a -> b) -> f (f1 a) -> f (f1 b) (.*) = fmap . fmap (.**) :: (Functor f, Functor f1, Functor f2) => (a -> b) -> f (f1 (f2 a)) -> f (f1 (f2 b)) (.**) = (.*) . fmap (.***) :: (Functor f, Functor f1, Functor f2, Functor f3) => (a -> b) -> f (f1 (f2 (f3 a))) -> f (f1 (f2 (f3 b))) (.***) = (.**) . fmap
onurzdg/clicklac
src/Data/Composition.hs
bsd-3-clause
462
0
14
152
277
152
125
12
1
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} module Client.KeyConstants where kTab = 9 :: Int kEnter = 13 :: Int kEscape = 27 :: Int kSpace = 32 :: Int kBackspace = 127 :: Int kUpArrow = 128 :: Int kDownArrow = 129 :: Int kLeftArrow = 130 :: Int kRightArrow = 131 :: Int kAlt = 132 :: Int kCtrl = 133 :: Int kShift = 134 :: Int kF1 = 135 :: Int kF2 = 136 :: Int kF3 = 137 :: Int kF4 = 138 :: Int kF5 = 139 :: Int kF6 = 140 :: Int kF7 = 141 :: Int kF8 = 142 :: Int kF9 = 143 :: Int kF10 = 144 :: Int kF11 = 145 :: Int kF12 = 146 :: Int kIns = 147 :: Int kDel = 148 :: Int kPgDn = 149 :: Int kPgUp = 150 :: Int kHome = 151 :: Int kEnd = 152 :: Int kKpHome = 160 :: Int kKpUpArrow = 161 :: Int kKpPgUp = 162 :: Int kKpLeftArrow = 163 :: Int kKp5 = 164 :: Int kKpRightArrow = 165 :: Int kKpEnd = 166 :: Int kKpDownArrow = 167 :: Int kKpPgDn = 168 :: Int kKpEnter = 169 :: Int kKpIns = 170 :: Int kKpDel = 171 :: Int kKpSlash = 172 :: Int kKpMinus = 173 :: Int kKpPlus = 174 :: Int kMouse1 = 200 :: Int kMouse2 = 201 :: Int kMouse3 = 202 :: Int kJoy1 = 203 :: Int kJoy2 = 204 :: Int kJoy3 = 205 :: Int kJoy4 = 206 :: Int kMWheelDown = 239 :: Int kMWheelUp = 240 :: Int kPause = 255 :: Int
ksaveljev/hake-2
src/Client/KeyConstants.hs
bsd-3-clause
1,567
0
4
661
447
280
167
57
1
module Roguelike.Event where import Data.Aeson import Roguelike.ID import Roguelike.Action import Roguelike.Item data CreatureAddress = Other CreatureID | Myself deriving (Show, Eq) type Damage = Int -- Something like a global ID for now newtype Appearance = Appearance ID deriving (Show, Eq, Ord, FromJSON, ToJSON) data KnownEntity = KnownCreature Appearance | KnownItem Item deriving (Show) -- TODO: Maybe send only relative movements; let's conceal the real location! data Event = Appeared ID Point KnownEntity | Updated ID KnownEntity | Disappeared ID | Moved CreatureAddress Point | Striked CreatureAddress CreatureAddress (Maybe Damage) | Slain CreatureAddress deriving (Show)
abbradar/roguelike
src/Roguelike/Event.hs
bsd-3-clause
830
0
8
242
168
97
71
20
0
-- | -- Module : Data.Ini.Types -- Copyright : 2011-2014 Magnus Therning -- License : BSD3 module Data.Ini.Types where import qualified Data.Map as M import Control.Arrow (second) type Config = M.Map SectionName Section type SectionName = String type Section = M.Map OptionName OptionValue type OptionName = String type OptionValue = String -- useful since Map doesn't have any Serial instance cfgFromList :: [(SectionName, [(OptionName, OptionValue)])] -> Config cfgFromList = M.fromList . map (second M.fromList) cfgToList :: Config -> [(SectionName, [(OptionName, OptionValue)])] cfgToList = M.toList . M.map M.toList
magthe/hsini
src/Data/Ini/Types.hs
bsd-3-clause
632
0
9
98
168
102
66
12
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE RecordWildCards #-} module Distribution.Solver.Modular.Dependency ( -- * Variables Var(..) , simplifyVar , varPI , showVar -- * Conflict sets , ConflictSet , ConflictMap , CS.showConflictSet -- * Constrained instances , CI(..) -- * Flagged dependencies , FlaggedDeps , FlaggedDep(..) , Dep(..) , showDep , flattenFlaggedDeps , QualifyOptions(..) , qualifyDeps , unqualifyDeps -- * Reverse dependency map , RevDepMap -- * Goals , Goal(..) , GoalReason(..) , QGoalReason , ResetVar(..) , goalToVar , goalVarToConflictSet , varToConflictSet , goalReasonToVars ) where import Prelude hiding (pi) import Data.Map (Map) import qualified Data.List as L import Language.Haskell.Extension (Extension(..), Language(..)) import Distribution.Text import Distribution.Solver.Modular.ConflictSet (ConflictSet, ConflictMap) import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Package import Distribution.Solver.Modular.Var import Distribution.Solver.Modular.Version import qualified Distribution.Solver.Modular.ConflictSet as CS import Distribution.Solver.Types.ComponentDeps (Component(..)) import Distribution.Solver.Types.PackagePath {------------------------------------------------------------------------------- Constrained instances -------------------------------------------------------------------------------} -- | Constrained instance. If the choice has already been made, this is -- a fixed instance, and we record the package name for which the choice -- is for convenience. Otherwise, it is a list of version ranges paired with -- the goals / variables that introduced them. data CI qpn = Fixed I (Var qpn) | Constrained [VROrigin qpn] deriving (Eq, Show, Functor) showCI :: CI QPN -> String showCI (Fixed i _) = "==" ++ showI i showCI (Constrained vr) = showVR (collapse vr) {------------------------------------------------------------------------------- Flagged dependencies -------------------------------------------------------------------------------} -- | Flagged dependencies -- -- 'FlaggedDeps' is the modular solver's view of a packages dependencies: -- rather than having the dependencies indexed by component, each dependency -- defines what component it is in. -- -- Note that each dependency is associated with a Component. We must know what -- component the dependencies belong to, or else we won't be able to construct -- fine-grained reverse dependencies. type FlaggedDeps qpn = [FlaggedDep qpn] -- | Flagged dependencies can either be plain dependency constraints, -- or flag-dependent dependency trees. data FlaggedDep qpn = -- | Dependencies which are conditional on a flag choice. Flagged (FN qpn) FInfo (TrueFlaggedDeps qpn) (FalseFlaggedDeps qpn) -- | Dependencies which are conditional on whether or not a stanza -- (e.g., a test suite or benchmark) is enabled. | Stanza (SN qpn) (TrueFlaggedDeps qpn) -- | Dependencies for which are always enabled, for the component -- 'comp' (or requested for the user, if comp is @()@). | Simple (Dep qpn) Component deriving (Eq, Show) -- | Conversatively flatten out flagged dependencies -- -- NOTE: We do not filter out duplicates. flattenFlaggedDeps :: FlaggedDeps qpn -> [(Dep qpn, Component)] flattenFlaggedDeps = concatMap aux where aux :: FlaggedDep qpn -> [(Dep qpn, Component)] aux (Flagged _ _ t f) = flattenFlaggedDeps t ++ flattenFlaggedDeps f aux (Stanza _ t) = flattenFlaggedDeps t aux (Simple d c) = [(d, c)] type TrueFlaggedDeps qpn = FlaggedDeps qpn type FalseFlaggedDeps qpn = FlaggedDeps qpn -- | Is this dependency on an executable type IsExe = Bool -- | A dependency (constraint) associates a package name with a -- constrained instance. -- -- 'Dep' intentionally has no 'Functor' instance because the type variable -- is used both to record the dependencies as well as who's doing the -- depending; having a 'Functor' instance makes bugs where we don't distinguish -- these two far too likely. (By rights 'Dep' ought to have two type variables.) data Dep qpn = Dep IsExe qpn (CI qpn) -- ^ dependency on a package (possibly for executable) | Ext Extension -- ^ dependency on a language extension | Lang Language -- ^ dependency on a language version | Pkg PkgconfigName VR -- ^ dependency on a pkg-config package deriving (Eq, Show) showDep :: Dep QPN -> String showDep (Dep is_exe qpn (Fixed i v) ) = (if P qpn /= v then showVar v ++ " => " else "") ++ showQPN qpn ++ (if is_exe then " (exe) " else "") ++ "==" ++ showI i showDep (Dep is_exe qpn (Constrained [(vr, v)])) = showVar v ++ " => " ++ showQPN qpn ++ (if is_exe then " (exe) " else "") ++ showVR vr showDep (Dep is_exe qpn ci ) = showQPN qpn ++ (if is_exe then " (exe) " else "") ++ showCI ci showDep (Ext ext) = "requires " ++ display ext showDep (Lang lang) = "requires " ++ display lang showDep (Pkg pn vr) = "requires pkg-config package " ++ display pn ++ display vr ++ ", not found in the pkg-config database" -- | Options for goal qualification (used in 'qualifyDeps') -- -- See also 'defaultQualifyOptions' data QualifyOptions = QO { -- | Do we have a version of base relying on another version of base? qoBaseShim :: Bool -- Should dependencies of the setup script be treated as independent? , qoSetupIndependent :: Bool } deriving Show -- | Apply built-in rules for package qualifiers -- -- Although the behaviour of 'qualifyDeps' depends on the 'QualifyOptions', -- it is important that these 'QualifyOptions' are _static_. Qualification -- does NOT depend on flag assignment; in other words, it behaves the same no -- matter which choices the solver makes (modulo the global 'QualifyOptions'); -- we rely on this in 'linkDeps' (see comment there). -- -- NOTE: It's the _dependencies_ of a package that may or may not be independent -- from the package itself. Package flag choices must of course be consistent. qualifyDeps :: QualifyOptions -> QPN -> FlaggedDeps PN -> FlaggedDeps QPN qualifyDeps QO{..} (Q pp@(PackagePath ns q) pn) = go where go :: FlaggedDeps PN -> FlaggedDeps QPN go = map go1 go1 :: FlaggedDep PN -> FlaggedDep QPN go1 (Flagged fn nfo t f) = Flagged (fmap (Q pp) fn) nfo (go t) (go f) go1 (Stanza sn t) = Stanza (fmap (Q pp) sn) (go t) go1 (Simple dep comp) = Simple (goD dep comp) comp -- Suppose package B has a setup dependency on package A. -- This will be recorded as something like -- -- > Dep "A" (Constrained [(AnyVersion, Goal (P "B") reason]) -- -- Observe that when we qualify this dependency, we need to turn that -- @"A"@ into @"B-setup.A"@, but we should not apply that same qualifier -- to the goal or the goal reason chain. goD :: Dep PN -> Component -> Dep QPN goD (Ext ext) _ = Ext ext goD (Lang lang) _ = Lang lang goD (Pkg pkn vr) _ = Pkg pkn vr goD (Dep is_exe dep ci) comp | is_exe = Dep is_exe (Q (PackagePath ns (QualExe pn dep)) dep) (fmap (Q pp) ci) | qBase dep = Dep is_exe (Q (PackagePath ns (QualBase pn)) dep) (fmap (Q pp) ci) | qSetup comp = Dep is_exe (Q (PackagePath ns (QualSetup pn)) dep) (fmap (Q pp) ci) | otherwise = Dep is_exe (Q (PackagePath ns inheritedQ) dep) (fmap (Q pp) ci) -- If P has a setup dependency on Q, and Q has a regular dependency on R, then -- we say that the 'Setup' qualifier is inherited: P has an (indirect) setup -- dependency on R. We do not do this for the base qualifier however. -- -- The inherited qualifier is only used for regular dependencies; for setup -- and base deppendencies we override the existing qualifier. See #3160 for -- a detailed discussion. inheritedQ :: Qualifier inheritedQ = case q of QualSetup _ -> q QualExe _ _ -> q QualToplevel -> q QualBase _ -> QualToplevel -- Should we qualify this goal with the 'Base' package path? qBase :: PN -> Bool qBase dep = qoBaseShim && unPackageName dep == "base" -- Should we qualify this goal with the 'Setup' package path? qSetup :: Component -> Bool qSetup comp = qoSetupIndependent && comp == ComponentSetup -- | Remove qualifiers from set of dependencies -- -- This is used during link validation: when we link package @Q.A@ to @Q'.A@, -- then all dependencies @Q.B@ need to be linked to @Q'.B@. In order to compute -- what to link these dependencies to, we need to requalify @Q.B@ to become -- @Q'.B@; we do this by first removing all qualifiers and then calling -- 'qualifyDeps' again. unqualifyDeps :: FlaggedDeps QPN -> FlaggedDeps PN unqualifyDeps = go where go :: FlaggedDeps QPN -> FlaggedDeps PN go = map go1 go1 :: FlaggedDep QPN -> FlaggedDep PN go1 (Flagged fn nfo t f) = Flagged (fmap unq fn) nfo (go t) (go f) go1 (Stanza sn t) = Stanza (fmap unq sn) (go t) go1 (Simple dep comp) = Simple (goD dep) comp goD :: Dep QPN -> Dep PN goD (Dep is_exe qpn ci) = Dep is_exe (unq qpn) (fmap unq ci) goD (Ext ext) = Ext ext goD (Lang lang) = Lang lang goD (Pkg pn vr) = Pkg pn vr unq :: QPN -> PN unq (Q _ pn) = pn {------------------------------------------------------------------------------- Reverse dependency map -------------------------------------------------------------------------------} -- | A map containing reverse dependencies between qualified -- package names. type RevDepMap = Map QPN [(Component, QPN)] {------------------------------------------------------------------------------- Goals -------------------------------------------------------------------------------} -- | A goal is just a solver variable paired with a reason. -- The reason is only used for tracing. data Goal qpn = Goal (Var qpn) (GoalReason qpn) deriving (Eq, Show, Functor) -- | Reason why a goal is being added to a goal set. data GoalReason qpn = UserGoal | PDependency (PI qpn) | FDependency (FN qpn) Bool | SDependency (SN qpn) deriving (Eq, Show, Functor) type QGoalReason = GoalReason QPN class ResetVar f where resetVar :: Var qpn -> f qpn -> f qpn instance ResetVar CI where resetVar v (Fixed i _) = Fixed i v resetVar v (Constrained vrs) = Constrained (L.map (\ (x, y) -> (x, resetVar v y)) vrs) instance ResetVar Dep where resetVar v (Dep is_exe qpn ci) = Dep is_exe qpn (resetVar v ci) resetVar _ (Ext ext) = Ext ext resetVar _ (Lang lang) = Lang lang resetVar _ (Pkg pn vr) = Pkg pn vr instance ResetVar Var where resetVar = const goalToVar :: Goal a -> Var a goalToVar (Goal v _) = v -- | Compute a singleton conflict set from a goal, containing just -- the goal variable. -- -- NOTE: This is just a call to 'varToConflictSet' under the hood; -- the 'GoalReason' is ignored. goalVarToConflictSet :: Goal QPN -> ConflictSet goalVarToConflictSet (Goal g _gr) = varToConflictSet g -- | Compute a singleton conflict set from a 'Var' varToConflictSet :: Var QPN -> ConflictSet varToConflictSet = CS.singleton -- | A goal reason is mostly just a variable paired with the -- decision we made for that variable (except for user goals, -- where we cannot really point to a solver variable). This -- function drops the decision and recovers the list of -- variables (which will be empty or contain one element). -- goalReasonToVars :: GoalReason qpn -> [Var qpn] goalReasonToVars UserGoal = [] goalReasonToVars (PDependency (PI qpn _)) = [P qpn] goalReasonToVars (FDependency qfn _) = [F qfn] goalReasonToVars (SDependency qsn) = [S qsn] {------------------------------------------------------------------------------- Version ranges paired with origins -------------------------------------------------------------------------------} type VROrigin qpn = (VR, Var qpn) -- | Helper function to collapse a list of version ranges with origins into -- a single, simplified, version range. collapse :: [VROrigin qpn] -> VR collapse = simplifyVR . L.foldr ((.&&.) . fst) anyVR
mydaum/cabal
cabal-install/Distribution/Solver/Modular/Dependency.hs
bsd-3-clause
12,349
0
14
2,667
2,592
1,408
1,184
163
9
LevelPreds { lpredPre = NameT { nameTName = "p_galois'a_function_call'P" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ] , nameTCTypes = [] } , lpredLoops = [] , lpredPost = NameT { nameTName = "p_galois'a_function_call'Q" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] ] , nameTCTypes = [] } , lpredCalls = fromList [ ( "a_loop" , CallInfo { lpredCallPre = NameT { nameTName = "p_galois'a_loop'P" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 11 } ] } , lpredCallPost = NameT { nameTName = "p_galois'a_loop'Q" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 11 } ] } , lpredCallSites = [ ( NameT { nameTName = "p_galois'a_function_call'a_loop'C1P" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 11 } ] } , NameT { nameTName = "p_galois'a_function_call'a_loop'C1Q" , nameTParams = [ TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "int" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "addr" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "map" [ TyCon "addr" [] , TyCon "int" [] ] , TyCon "addr" [] , TyCon "int" [] ] , nameTCTypes = [ CType { ctPtrDepth = 1 , ctBaseType = 7 } , CType { ctPtrDepth = 0 , ctBaseType = 11 } ] } ) ] } ) ] }
GaloisInc/verification-game
web-prover/demo-levels/a_function_call/holes.hs
bsd-3-clause
5,095
0
20
2,737
1,421
757
664
-1
-1
module CRDT.Cv.GCounter ( GCounter (..) , initial , query -- * Operation , increment ) where import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Semilattice (Semilattice) -- | Grow-only counter. newtype GCounter a = GCounter (IntMap a) deriving (Eq, Show) instance Ord a => Semigroup (GCounter a) where GCounter x <> GCounter y = GCounter $ IntMap.unionWith max x y -- | See 'CvRDT' instance Ord a => Semilattice (GCounter a) -- | Increment counter increment :: Num a => Word -- ^ replica id -> GCounter a -> GCounter a increment replicaId (GCounter imap) = GCounter (IntMap.insertWith (+) i 1 imap) where i = fromIntegral replicaId -- | Initial state initial :: GCounter a initial = GCounter IntMap.empty -- | Get value from the state query :: Num a => GCounter a -> a query (GCounter v) = sum v
cblp/crdt
crdt/lib/CRDT/Cv/GCounter.hs
bsd-3-clause
919
0
8
223
284
152
132
24
1
-------------------------------------------------------------------------------- -- | -- Module : Language.Verilog.Syntax -- Copyright : (c) Signali Corp. 2010 -- License : All rights reserved -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : ghc -- -- Verilog syntax: the abstract syntax tree (AST) and related modules. -------------------------------------------------------------------------------- module Language.Verilog.Syntax ( -- * Abstract syntax tree module Language.Verilog.Syntax.AST, ) where import Language.Verilog.Syntax.AST --------------------------------------------------------------------------------
githubkleon/ConvenientHDL
src/Language/Verilog/Syntax.hs
bsd-3-clause
697
0
5
99
39
32
7
4
0
{-# LANGUAGE QuasiQuotes #-} {-@ LIQUID "--no-termination "@-} import LiquidHaskell --------------------------------------------------------------------- ----------------------- Datatype Definition ------------------------- --------------------------------------------------------------------- data Bndr data Expr = Lam Bndr Expr | Var Bndr | App Expr Expr [lq| data Expr [elen] = Lam (x::Bndr) (e::Expr) | Var (x::Bndr) | App (e1::Expr) (e2::Expr) |] [lq| measure elen :: Expr -> Int elen(Var x) = 0 elen(Lam x e) = 1 + (elen e) elen(App e1 e2) = 1 + (elen e1) + (elen e2) |] [lq| invariant {v:Expr | (elen v) >= 0} |] [lq| measure isValue :: Expr -> Prop isValue (Lam x e) = true isValue (Var x) = false isValue (App e1 e2) = false |] [lq| type Value = {v: Expr | isValue v } |] [lq| type Store = [(Bndr, Value)] |] --------------------------------------------------------------------- -------------------------- The Evaluator ---------------------------- --------------------------------------------------------------------- [lq| evalVar :: Bndr -> Store -> Value |] evalVar :: Bndr -> [(Bndr, Expr)] -> Expr evalVar = error "HIDEME" [lq| Decrease eval 2 |] [lq| eval :: sto:Store -> e:Expr -> (Store, Value) |] eval sto (Var x) = (sto, evalVar x sto) eval sto (App e1 e2) = let (_, v2 ) = eval sto e2 (sto1, e1') = eval sto e1 in case e1' of (Lam x e) -> eval ((x, v2) : sto1) e _ -> error "non-function application" eval sto (Lam x e) = (sto, Lam x e)
spinda/liquidhaskell
tests/gsoc15/unknown/pos/LambdaEvalTiny.hs
bsd-3-clause
1,610
0
13
383
290
168
122
-1
-1
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.Functions.F11 -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- Raw functions from the -- <http://www.opengl.org/registry/ OpenGL registry>. -- -------------------------------------------------------------------------------- module Graphics.GL.Functions.F11 ( glGetMaterialxOES, glGetMaterialxv, glGetMaterialxvOES, glGetMemoryObjectDetachedResourcesuivNV, glGetMemoryObjectParameterivEXT, glGetMinmax, glGetMinmaxEXT, glGetMinmaxParameterfv, glGetMinmaxParameterfvEXT, glGetMinmaxParameteriv, glGetMinmaxParameterivEXT, glGetMultiTexEnvfvEXT, glGetMultiTexEnvivEXT, glGetMultiTexGendvEXT, glGetMultiTexGenfvEXT, glGetMultiTexGenivEXT, glGetMultiTexImageEXT, glGetMultiTexLevelParameterfvEXT, glGetMultiTexLevelParameterivEXT, glGetMultiTexParameterIivEXT, glGetMultiTexParameterIuivEXT, glGetMultiTexParameterfvEXT, glGetMultiTexParameterivEXT, glGetMultisamplefv, glGetMultisamplefvNV, glGetNamedBufferParameteri64v, glGetNamedBufferParameteriv, glGetNamedBufferParameterivEXT, glGetNamedBufferParameterui64vNV, glGetNamedBufferPointerv, glGetNamedBufferPointervEXT, glGetNamedBufferSubData, glGetNamedBufferSubDataEXT, glGetNamedFramebufferAttachmentParameteriv, glGetNamedFramebufferAttachmentParameterivEXT, glGetNamedFramebufferParameterfvAMD, glGetNamedFramebufferParameteriv, glGetNamedFramebufferParameterivEXT, glGetNamedProgramLocalParameterIivEXT, glGetNamedProgramLocalParameterIuivEXT, glGetNamedProgramLocalParameterdvEXT, glGetNamedProgramLocalParameterfvEXT, glGetNamedProgramStringEXT, glGetNamedProgramivEXT, glGetNamedRenderbufferParameteriv, glGetNamedRenderbufferParameterivEXT, glGetNamedStringARB, glGetNamedStringivARB, glGetNextPerfQueryIdINTEL, glGetObjectBufferfvATI, glGetObjectBufferivATI, glGetObjectLabel, glGetObjectLabelEXT, glGetObjectLabelKHR, glGetObjectParameterfvARB, glGetObjectParameterivAPPLE, glGetObjectParameterivARB, glGetObjectPtrLabel, glGetObjectPtrLabelKHR, glGetOcclusionQueryivNV, glGetOcclusionQueryuivNV, glGetPathColorGenfvNV, glGetPathColorGenivNV, glGetPathCommandsNV, glGetPathCoordsNV, glGetPathDashArrayNV, glGetPathLengthNV, glGetPathMetricRangeNV, glGetPathMetricsNV, glGetPathParameterfvNV, glGetPathParameterivNV, glGetPathSpacingNV, glGetPathTexGenfvNV, glGetPathTexGenivNV, glGetPerfCounterInfoINTEL, glGetPerfMonitorCounterDataAMD, glGetPerfMonitorCounterInfoAMD, glGetPerfMonitorCounterStringAMD, glGetPerfMonitorCountersAMD, glGetPerfMonitorGroupStringAMD, glGetPerfMonitorGroupsAMD, glGetPerfQueryDataINTEL, glGetPerfQueryIdByNameINTEL, glGetPerfQueryInfoINTEL, glGetPixelMapfv, glGetPixelMapuiv, glGetPixelMapusv, glGetPixelMapxv, glGetPixelTexGenParameterfvSGIS, glGetPixelTexGenParameterivSGIS, glGetPixelTransformParameterfvEXT, glGetPixelTransformParameterivEXT, glGetPointerIndexedvEXT, glGetPointeri_vEXT, glGetPointerv, glGetPointervEXT, glGetPointervKHR, glGetPolygonStipple, glGetProgramBinary, glGetProgramBinaryOES ) where import Control.Monad.IO.Class ( MonadIO(..) ) import Foreign.Ptr import Graphics.GL.Foreign import Graphics.GL.Types import System.IO.Unsafe ( unsafePerformIO ) -- glGetMaterialxOES ----------------------------------------------------------- glGetMaterialxOES :: MonadIO m => GLenum -- ^ @face@ of type [MaterialFace](Graphics-GL-Groups.html#MaterialFace). -> GLenum -- ^ @pname@ of type [MaterialParameter](Graphics-GL-Groups.html#MaterialParameter). -> GLfixed -- ^ @param@. -> m () glGetMaterialxOES v1 v2 v3 = liftIO $ dyn169 ptr_glGetMaterialxOES v1 v2 v3 {-# NOINLINE ptr_glGetMaterialxOES #-} ptr_glGetMaterialxOES :: FunPtr (GLenum -> GLenum -> GLfixed -> IO ()) ptr_glGetMaterialxOES = unsafePerformIO $ getCommand "glGetMaterialxOES" -- glGetMaterialxv ------------------------------------------------------------- glGetMaterialxv :: MonadIO m => GLenum -- ^ @face@ of type [MaterialFace](Graphics-GL-Groups.html#MaterialFace). -> GLenum -- ^ @pname@ of type [MaterialParameter](Graphics-GL-Groups.html#MaterialParameter). -> Ptr GLfixed -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfixed@. -> m () glGetMaterialxv v1 v2 v3 = liftIO $ dyn170 ptr_glGetMaterialxv v1 v2 v3 {-# NOINLINE ptr_glGetMaterialxv #-} ptr_glGetMaterialxv :: FunPtr (GLenum -> GLenum -> Ptr GLfixed -> IO ()) ptr_glGetMaterialxv = unsafePerformIO $ getCommand "glGetMaterialxv" -- glGetMaterialxvOES ---------------------------------------------------------- glGetMaterialxvOES :: MonadIO m => GLenum -- ^ @face@ of type [MaterialFace](Graphics-GL-Groups.html#MaterialFace). -> GLenum -- ^ @pname@ of type [MaterialParameter](Graphics-GL-Groups.html#MaterialParameter). -> Ptr GLfixed -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfixed@. -> m () glGetMaterialxvOES v1 v2 v3 = liftIO $ dyn170 ptr_glGetMaterialxvOES v1 v2 v3 {-# NOINLINE ptr_glGetMaterialxvOES #-} ptr_glGetMaterialxvOES :: FunPtr (GLenum -> GLenum -> Ptr GLfixed -> IO ()) ptr_glGetMaterialxvOES = unsafePerformIO $ getCommand "glGetMaterialxvOES" -- glGetMemoryObjectDetachedResourcesuivNV ------------------------------------- glGetMemoryObjectDetachedResourcesuivNV :: MonadIO m => GLuint -- ^ @memory@. -> GLenum -- ^ @pname@. -> GLint -- ^ @first@. -> GLsizei -- ^ @count@. -> Ptr GLuint -- ^ @params@. -> m () glGetMemoryObjectDetachedResourcesuivNV v1 v2 v3 v4 v5 = liftIO $ dyn369 ptr_glGetMemoryObjectDetachedResourcesuivNV v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetMemoryObjectDetachedResourcesuivNV #-} ptr_glGetMemoryObjectDetachedResourcesuivNV :: FunPtr (GLuint -> GLenum -> GLint -> GLsizei -> Ptr GLuint -> IO ()) ptr_glGetMemoryObjectDetachedResourcesuivNV = unsafePerformIO $ getCommand "glGetMemoryObjectDetachedResourcesuivNV" -- glGetMemoryObjectParameterivEXT --------------------------------------------- glGetMemoryObjectParameterivEXT :: MonadIO m => GLuint -- ^ @memoryObject@. -> GLenum -- ^ @pname@ of type [MemoryObjectParameterName](Graphics-GL-Groups.html#MemoryObjectParameterName). -> Ptr GLint -- ^ @params@. -> m () glGetMemoryObjectParameterivEXT v1 v2 v3 = liftIO $ dyn348 ptr_glGetMemoryObjectParameterivEXT v1 v2 v3 {-# NOINLINE ptr_glGetMemoryObjectParameterivEXT #-} ptr_glGetMemoryObjectParameterivEXT :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMemoryObjectParameterivEXT = unsafePerformIO $ getCommand "glGetMemoryObjectParameterivEXT" -- glGetMinmax ----------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetMinmax.xml OpenGL 2.x>. glGetMinmax :: MonadIO m => GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT). -> GLboolean -- ^ @reset@ of type [Boolean](Graphics-GL-Groups.html#Boolean). -> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat). -> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType). -> Ptr a -- ^ @values@ pointing to @COMPSIZE(target,format,type)@ elements of type @a@. -> m () glGetMinmax v1 v2 v3 v4 v5 = liftIO $ dyn351 ptr_glGetMinmax v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetMinmax #-} ptr_glGetMinmax :: FunPtr (GLenum -> GLboolean -> GLenum -> GLenum -> Ptr a -> IO ()) ptr_glGetMinmax = unsafePerformIO $ getCommand "glGetMinmax" -- glGetMinmaxEXT -------------------------------------------------------------- glGetMinmaxEXT :: MonadIO m => GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT). -> GLboolean -- ^ @reset@ of type [Boolean](Graphics-GL-Groups.html#Boolean). -> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat). -> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType). -> Ptr a -- ^ @values@ pointing to @COMPSIZE(target,format,type)@ elements of type @a@. -> m () glGetMinmaxEXT v1 v2 v3 v4 v5 = liftIO $ dyn351 ptr_glGetMinmaxEXT v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetMinmaxEXT #-} ptr_glGetMinmaxEXT :: FunPtr (GLenum -> GLboolean -> GLenum -> GLenum -> Ptr a -> IO ()) ptr_glGetMinmaxEXT = unsafePerformIO $ getCommand "glGetMinmaxEXT" -- glGetMinmaxParameterfv ------------------------------------------------------ -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetMinmaxParameter.xml OpenGL 2.x>. glGetMinmaxParameterfv :: MonadIO m => GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT). -> GLenum -- ^ @pname@ of type [GetMinmaxParameterPNameEXT](Graphics-GL-Groups.html#GetMinmaxParameterPNameEXT). -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetMinmaxParameterfv v1 v2 v3 = liftIO $ dyn139 ptr_glGetMinmaxParameterfv v1 v2 v3 {-# NOINLINE ptr_glGetMinmaxParameterfv #-} ptr_glGetMinmaxParameterfv :: FunPtr (GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetMinmaxParameterfv = unsafePerformIO $ getCommand "glGetMinmaxParameterfv" -- glGetMinmaxParameterfvEXT --------------------------------------------------- glGetMinmaxParameterfvEXT :: MonadIO m => GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT). -> GLenum -- ^ @pname@ of type [GetMinmaxParameterPNameEXT](Graphics-GL-Groups.html#GetMinmaxParameterPNameEXT). -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetMinmaxParameterfvEXT v1 v2 v3 = liftIO $ dyn139 ptr_glGetMinmaxParameterfvEXT v1 v2 v3 {-# NOINLINE ptr_glGetMinmaxParameterfvEXT #-} ptr_glGetMinmaxParameterfvEXT :: FunPtr (GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetMinmaxParameterfvEXT = unsafePerformIO $ getCommand "glGetMinmaxParameterfvEXT" -- glGetMinmaxParameteriv ------------------------------------------------------ -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetMinmaxParameter.xml OpenGL 2.x>. glGetMinmaxParameteriv :: MonadIO m => GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT). -> GLenum -- ^ @pname@ of type [GetMinmaxParameterPNameEXT](Graphics-GL-Groups.html#GetMinmaxParameterPNameEXT). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetMinmaxParameteriv v1 v2 v3 = liftIO $ dyn140 ptr_glGetMinmaxParameteriv v1 v2 v3 {-# NOINLINE ptr_glGetMinmaxParameteriv #-} ptr_glGetMinmaxParameteriv :: FunPtr (GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMinmaxParameteriv = unsafePerformIO $ getCommand "glGetMinmaxParameteriv" -- glGetMinmaxParameterivEXT --------------------------------------------------- glGetMinmaxParameterivEXT :: MonadIO m => GLenum -- ^ @target@ of type [MinmaxTargetEXT](Graphics-GL-Groups.html#MinmaxTargetEXT). -> GLenum -- ^ @pname@ of type [GetMinmaxParameterPNameEXT](Graphics-GL-Groups.html#GetMinmaxParameterPNameEXT). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetMinmaxParameterivEXT v1 v2 v3 = liftIO $ dyn140 ptr_glGetMinmaxParameterivEXT v1 v2 v3 {-# NOINLINE ptr_glGetMinmaxParameterivEXT #-} ptr_glGetMinmaxParameterivEXT :: FunPtr (GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMinmaxParameterivEXT = unsafePerformIO $ getCommand "glGetMinmaxParameterivEXT" -- glGetMultiTexEnvfvEXT ------------------------------------------------------- glGetMultiTexEnvfvEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureEnvTarget](Graphics-GL-Groups.html#TextureEnvTarget). -> GLenum -- ^ @pname@ of type [TextureEnvParameter](Graphics-GL-Groups.html#TextureEnvParameter). -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetMultiTexEnvfvEXT v1 v2 v3 v4 = liftIO $ dyn334 ptr_glGetMultiTexEnvfvEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexEnvfvEXT #-} ptr_glGetMultiTexEnvfvEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetMultiTexEnvfvEXT = unsafePerformIO $ getCommand "glGetMultiTexEnvfvEXT" -- glGetMultiTexEnvivEXT ------------------------------------------------------- glGetMultiTexEnvivEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureEnvTarget](Graphics-GL-Groups.html#TextureEnvTarget). -> GLenum -- ^ @pname@ of type [TextureEnvParameter](Graphics-GL-Groups.html#TextureEnvParameter). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetMultiTexEnvivEXT v1 v2 v3 v4 = liftIO $ dyn335 ptr_glGetMultiTexEnvivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexEnvivEXT #-} ptr_glGetMultiTexEnvivEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMultiTexEnvivEXT = unsafePerformIO $ getCommand "glGetMultiTexEnvivEXT" -- glGetMultiTexGendvEXT ------------------------------------------------------- glGetMultiTexGendvEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @coord@ of type [TextureCoordName](Graphics-GL-Groups.html#TextureCoordName). -> GLenum -- ^ @pname@ of type [TextureGenParameter](Graphics-GL-Groups.html#TextureGenParameter). -> Ptr GLdouble -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLdouble@. -> m () glGetMultiTexGendvEXT v1 v2 v3 v4 = liftIO $ dyn370 ptr_glGetMultiTexGendvEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexGendvEXT #-} ptr_glGetMultiTexGendvEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLdouble -> IO ()) ptr_glGetMultiTexGendvEXT = unsafePerformIO $ getCommand "glGetMultiTexGendvEXT" -- glGetMultiTexGenfvEXT ------------------------------------------------------- glGetMultiTexGenfvEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @coord@ of type [TextureCoordName](Graphics-GL-Groups.html#TextureCoordName). -> GLenum -- ^ @pname@ of type [TextureGenParameter](Graphics-GL-Groups.html#TextureGenParameter). -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetMultiTexGenfvEXT v1 v2 v3 v4 = liftIO $ dyn334 ptr_glGetMultiTexGenfvEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexGenfvEXT #-} ptr_glGetMultiTexGenfvEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetMultiTexGenfvEXT = unsafePerformIO $ getCommand "glGetMultiTexGenfvEXT" -- glGetMultiTexGenivEXT ------------------------------------------------------- glGetMultiTexGenivEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @coord@ of type [TextureCoordName](Graphics-GL-Groups.html#TextureCoordName). -> GLenum -- ^ @pname@ of type [TextureGenParameter](Graphics-GL-Groups.html#TextureGenParameter). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetMultiTexGenivEXT v1 v2 v3 v4 = liftIO $ dyn335 ptr_glGetMultiTexGenivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexGenivEXT #-} ptr_glGetMultiTexGenivEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMultiTexGenivEXT = unsafePerformIO $ getCommand "glGetMultiTexGenivEXT" -- glGetMultiTexImageEXT ------------------------------------------------------- glGetMultiTexImageEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget). -> GLint -- ^ @level@ of type @CheckedInt32@. -> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat). -> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType). -> Ptr a -- ^ @pixels@ pointing to @COMPSIZE(target,level,format,type)@ elements of type @a@. -> m () glGetMultiTexImageEXT v1 v2 v3 v4 v5 v6 = liftIO $ dyn371 ptr_glGetMultiTexImageEXT v1 v2 v3 v4 v5 v6 {-# NOINLINE ptr_glGetMultiTexImageEXT #-} ptr_glGetMultiTexImageEXT :: FunPtr (GLenum -> GLenum -> GLint -> GLenum -> GLenum -> Ptr a -> IO ()) ptr_glGetMultiTexImageEXT = unsafePerformIO $ getCommand "glGetMultiTexImageEXT" -- glGetMultiTexLevelParameterfvEXT -------------------------------------------- glGetMultiTexLevelParameterfvEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget). -> GLint -- ^ @level@ of type @CheckedInt32@. -> GLenum -- ^ @pname@ of type [GetTextureParameter](Graphics-GL-Groups.html#GetTextureParameter). -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetMultiTexLevelParameterfvEXT v1 v2 v3 v4 v5 = liftIO $ dyn372 ptr_glGetMultiTexLevelParameterfvEXT v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetMultiTexLevelParameterfvEXT #-} ptr_glGetMultiTexLevelParameterfvEXT :: FunPtr (GLenum -> GLenum -> GLint -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetMultiTexLevelParameterfvEXT = unsafePerformIO $ getCommand "glGetMultiTexLevelParameterfvEXT" -- glGetMultiTexLevelParameterivEXT -------------------------------------------- glGetMultiTexLevelParameterivEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget). -> GLint -- ^ @level@ of type @CheckedInt32@. -> GLenum -- ^ @pname@ of type [GetTextureParameter](Graphics-GL-Groups.html#GetTextureParameter). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetMultiTexLevelParameterivEXT v1 v2 v3 v4 v5 = liftIO $ dyn373 ptr_glGetMultiTexLevelParameterivEXT v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetMultiTexLevelParameterivEXT #-} ptr_glGetMultiTexLevelParameterivEXT :: FunPtr (GLenum -> GLenum -> GLint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMultiTexLevelParameterivEXT = unsafePerformIO $ getCommand "glGetMultiTexLevelParameterivEXT" -- glGetMultiTexParameterIivEXT ------------------------------------------------ glGetMultiTexParameterIivEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget). -> GLenum -- ^ @pname@ of type [GetTextureParameter](Graphics-GL-Groups.html#GetTextureParameter). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetMultiTexParameterIivEXT v1 v2 v3 v4 = liftIO $ dyn335 ptr_glGetMultiTexParameterIivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexParameterIivEXT #-} ptr_glGetMultiTexParameterIivEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMultiTexParameterIivEXT = unsafePerformIO $ getCommand "glGetMultiTexParameterIivEXT" -- glGetMultiTexParameterIuivEXT ----------------------------------------------- glGetMultiTexParameterIuivEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget). -> GLenum -- ^ @pname@ of type [GetTextureParameter](Graphics-GL-Groups.html#GetTextureParameter). -> Ptr GLuint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLuint@. -> m () glGetMultiTexParameterIuivEXT v1 v2 v3 v4 = liftIO $ dyn374 ptr_glGetMultiTexParameterIuivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexParameterIuivEXT #-} ptr_glGetMultiTexParameterIuivEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLuint -> IO ()) ptr_glGetMultiTexParameterIuivEXT = unsafePerformIO $ getCommand "glGetMultiTexParameterIuivEXT" -- glGetMultiTexParameterfvEXT ------------------------------------------------- glGetMultiTexParameterfvEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget). -> GLenum -- ^ @pname@ of type [GetTextureParameter](Graphics-GL-Groups.html#GetTextureParameter). -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetMultiTexParameterfvEXT v1 v2 v3 v4 = liftIO $ dyn334 ptr_glGetMultiTexParameterfvEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexParameterfvEXT #-} ptr_glGetMultiTexParameterfvEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetMultiTexParameterfvEXT = unsafePerformIO $ getCommand "glGetMultiTexParameterfvEXT" -- glGetMultiTexParameterivEXT ------------------------------------------------- glGetMultiTexParameterivEXT :: MonadIO m => GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget). -> GLenum -- ^ @pname@ of type [GetTextureParameter](Graphics-GL-Groups.html#GetTextureParameter). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetMultiTexParameterivEXT v1 v2 v3 v4 = liftIO $ dyn335 ptr_glGetMultiTexParameterivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetMultiTexParameterivEXT #-} ptr_glGetMultiTexParameterivEXT :: FunPtr (GLenum -> GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetMultiTexParameterivEXT = unsafePerformIO $ getCommand "glGetMultiTexParameterivEXT" -- glGetMultisamplefv ---------------------------------------------------------- -- | Manual pages for <https://www.opengl.org/sdk/docs/man3/xhtml/glGetMultisample.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glGetMultisample.xhtml OpenGL 4.x>. glGetMultisamplefv :: MonadIO m => GLenum -- ^ @pname@ of type [GetMultisamplePNameNV](Graphics-GL-Groups.html#GetMultisamplePNameNV). -> GLuint -- ^ @index@. -> Ptr GLfloat -- ^ @val@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetMultisamplefv v1 v2 v3 = liftIO $ dyn278 ptr_glGetMultisamplefv v1 v2 v3 {-# NOINLINE ptr_glGetMultisamplefv #-} ptr_glGetMultisamplefv :: FunPtr (GLenum -> GLuint -> Ptr GLfloat -> IO ()) ptr_glGetMultisamplefv = unsafePerformIO $ getCommand "glGetMultisamplefv" -- glGetMultisamplefvNV -------------------------------------------------------- -- | This command is an alias for 'glGetMultisamplefv'. glGetMultisamplefvNV :: MonadIO m => GLenum -- ^ @pname@ of type [GetMultisamplePNameNV](Graphics-GL-Groups.html#GetMultisamplePNameNV). -> GLuint -- ^ @index@. -> Ptr GLfloat -- ^ @val@ pointing to @2@ elements of type @GLfloat@. -> m () glGetMultisamplefvNV v1 v2 v3 = liftIO $ dyn278 ptr_glGetMultisamplefvNV v1 v2 v3 {-# NOINLINE ptr_glGetMultisamplefvNV #-} ptr_glGetMultisamplefvNV :: FunPtr (GLenum -> GLuint -> Ptr GLfloat -> IO ()) ptr_glGetMultisamplefvNV = unsafePerformIO $ getCommand "glGetMultisamplefvNV" -- glGetNamedBufferParameteri64v ----------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetBufferParameter.xhtml OpenGL 4.x>. glGetNamedBufferParameteri64v :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [VertexBufferObjectParameter](Graphics-GL-Groups.html#VertexBufferObjectParameter). -> Ptr GLint64 -- ^ @params@. -> m () glGetNamedBufferParameteri64v v1 v2 v3 = liftIO $ dyn375 ptr_glGetNamedBufferParameteri64v v1 v2 v3 {-# NOINLINE ptr_glGetNamedBufferParameteri64v #-} ptr_glGetNamedBufferParameteri64v :: FunPtr (GLuint -> GLenum -> Ptr GLint64 -> IO ()) ptr_glGetNamedBufferParameteri64v = unsafePerformIO $ getCommand "glGetNamedBufferParameteri64v" -- glGetNamedBufferParameteriv ------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetBufferParameter.xhtml OpenGL 4.x>. glGetNamedBufferParameteriv :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [VertexBufferObjectParameter](Graphics-GL-Groups.html#VertexBufferObjectParameter). -> Ptr GLint -- ^ @params@. -> m () glGetNamedBufferParameteriv v1 v2 v3 = liftIO $ dyn348 ptr_glGetNamedBufferParameteriv v1 v2 v3 {-# NOINLINE ptr_glGetNamedBufferParameteriv #-} ptr_glGetNamedBufferParameteriv :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedBufferParameteriv = unsafePerformIO $ getCommand "glGetNamedBufferParameteriv" -- glGetNamedBufferParameterivEXT ---------------------------------------------- glGetNamedBufferParameterivEXT :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [VertexBufferObjectParameter](Graphics-GL-Groups.html#VertexBufferObjectParameter). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetNamedBufferParameterivEXT v1 v2 v3 = liftIO $ dyn348 ptr_glGetNamedBufferParameterivEXT v1 v2 v3 {-# NOINLINE ptr_glGetNamedBufferParameterivEXT #-} ptr_glGetNamedBufferParameterivEXT :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedBufferParameterivEXT = unsafePerformIO $ getCommand "glGetNamedBufferParameterivEXT" -- glGetNamedBufferParameterui64vNV -------------------------------------------- glGetNamedBufferParameterui64vNV :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [VertexBufferObjectParameter](Graphics-GL-Groups.html#VertexBufferObjectParameter). -> Ptr GLuint64EXT -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLuint64EXT@. -> m () glGetNamedBufferParameterui64vNV v1 v2 v3 = liftIO $ dyn376 ptr_glGetNamedBufferParameterui64vNV v1 v2 v3 {-# NOINLINE ptr_glGetNamedBufferParameterui64vNV #-} ptr_glGetNamedBufferParameterui64vNV :: FunPtr (GLuint -> GLenum -> Ptr GLuint64EXT -> IO ()) ptr_glGetNamedBufferParameterui64vNV = unsafePerformIO $ getCommand "glGetNamedBufferParameterui64vNV" -- glGetNamedBufferPointerv ---------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetBufferPointerv.xhtml OpenGL 4.x>. glGetNamedBufferPointerv :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [VertexBufferObjectParameter](Graphics-GL-Groups.html#VertexBufferObjectParameter). -> Ptr (Ptr a) -- ^ @params@. -> m () glGetNamedBufferPointerv v1 v2 v3 = liftIO $ dyn377 ptr_glGetNamedBufferPointerv v1 v2 v3 {-# NOINLINE ptr_glGetNamedBufferPointerv #-} ptr_glGetNamedBufferPointerv :: FunPtr (GLuint -> GLenum -> Ptr (Ptr a) -> IO ()) ptr_glGetNamedBufferPointerv = unsafePerformIO $ getCommand "glGetNamedBufferPointerv" -- glGetNamedBufferPointervEXT ------------------------------------------------- glGetNamedBufferPointervEXT :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [VertexBufferObjectParameter](Graphics-GL-Groups.html#VertexBufferObjectParameter). -> Ptr (Ptr a) -- ^ @params@ pointing to @1@ element of type @Ptr a@. -> m () glGetNamedBufferPointervEXT v1 v2 v3 = liftIO $ dyn377 ptr_glGetNamedBufferPointervEXT v1 v2 v3 {-# NOINLINE ptr_glGetNamedBufferPointervEXT #-} ptr_glGetNamedBufferPointervEXT :: FunPtr (GLuint -> GLenum -> Ptr (Ptr a) -> IO ()) ptr_glGetNamedBufferPointervEXT = unsafePerformIO $ getCommand "glGetNamedBufferPointervEXT" -- glGetNamedBufferSubData ----------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetBufferSubData.xhtml OpenGL 4.x>. glGetNamedBufferSubData :: MonadIO m => GLuint -- ^ @buffer@. -> GLintptr -- ^ @offset@. -> GLsizeiptr -- ^ @size@ of type @BufferSize@. -> Ptr a -- ^ @data@. -> m () glGetNamedBufferSubData v1 v2 v3 v4 = liftIO $ dyn378 ptr_glGetNamedBufferSubData v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedBufferSubData #-} ptr_glGetNamedBufferSubData :: FunPtr (GLuint -> GLintptr -> GLsizeiptr -> Ptr a -> IO ()) ptr_glGetNamedBufferSubData = unsafePerformIO $ getCommand "glGetNamedBufferSubData" -- glGetNamedBufferSubDataEXT -------------------------------------------------- glGetNamedBufferSubDataEXT :: MonadIO m => GLuint -- ^ @buffer@. -> GLintptr -- ^ @offset@. -> GLsizeiptr -- ^ @size@. -> Ptr a -- ^ @data@ pointing to @COMPSIZE(size)@ elements of type @a@. -> m () glGetNamedBufferSubDataEXT v1 v2 v3 v4 = liftIO $ dyn378 ptr_glGetNamedBufferSubDataEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedBufferSubDataEXT #-} ptr_glGetNamedBufferSubDataEXT :: FunPtr (GLuint -> GLintptr -> GLsizeiptr -> Ptr a -> IO ()) ptr_glGetNamedBufferSubDataEXT = unsafePerformIO $ getCommand "glGetNamedBufferSubDataEXT" -- glGetNamedFramebufferAttachmentParameteriv ---------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetFramebufferAttachmentParameter.xhtml OpenGL 4.x>. glGetNamedFramebufferAttachmentParameteriv :: MonadIO m => GLuint -- ^ @framebuffer@. -> GLenum -- ^ @attachment@ of type [FramebufferAttachment](Graphics-GL-Groups.html#FramebufferAttachment). -> GLenum -- ^ @pname@ of type [FramebufferAttachmentParameterName](Graphics-GL-Groups.html#FramebufferAttachmentParameterName). -> Ptr GLint -- ^ @params@. -> m () glGetNamedFramebufferAttachmentParameteriv v1 v2 v3 v4 = liftIO $ dyn379 ptr_glGetNamedFramebufferAttachmentParameteriv v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedFramebufferAttachmentParameteriv #-} ptr_glGetNamedFramebufferAttachmentParameteriv :: FunPtr (GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedFramebufferAttachmentParameteriv = unsafePerformIO $ getCommand "glGetNamedFramebufferAttachmentParameteriv" -- glGetNamedFramebufferAttachmentParameterivEXT ------------------------------- glGetNamedFramebufferAttachmentParameterivEXT :: MonadIO m => GLuint -- ^ @framebuffer@ of type @Framebuffer@. -> GLenum -- ^ @attachment@ of type [FramebufferAttachment](Graphics-GL-Groups.html#FramebufferAttachment). -> GLenum -- ^ @pname@ of type [FramebufferAttachmentParameterName](Graphics-GL-Groups.html#FramebufferAttachmentParameterName). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetNamedFramebufferAttachmentParameterivEXT v1 v2 v3 v4 = liftIO $ dyn379 ptr_glGetNamedFramebufferAttachmentParameterivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedFramebufferAttachmentParameterivEXT #-} ptr_glGetNamedFramebufferAttachmentParameterivEXT :: FunPtr (GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedFramebufferAttachmentParameterivEXT = unsafePerformIO $ getCommand "glGetNamedFramebufferAttachmentParameterivEXT" -- glGetNamedFramebufferParameterfvAMD ----------------------------------------- glGetNamedFramebufferParameterfvAMD :: MonadIO m => GLuint -- ^ @framebuffer@. -> GLenum -- ^ @pname@. -> GLuint -- ^ @numsamples@. -> GLuint -- ^ @pixelindex@. -> GLsizei -- ^ @size@. -> Ptr GLfloat -- ^ @values@. -> m () glGetNamedFramebufferParameterfvAMD v1 v2 v3 v4 v5 v6 = liftIO $ dyn380 ptr_glGetNamedFramebufferParameterfvAMD v1 v2 v3 v4 v5 v6 {-# NOINLINE ptr_glGetNamedFramebufferParameterfvAMD #-} ptr_glGetNamedFramebufferParameterfvAMD :: FunPtr (GLuint -> GLenum -> GLuint -> GLuint -> GLsizei -> Ptr GLfloat -> IO ()) ptr_glGetNamedFramebufferParameterfvAMD = unsafePerformIO $ getCommand "glGetNamedFramebufferParameterfvAMD" -- glGetNamedFramebufferParameteriv -------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetFramebufferParameter.xhtml OpenGL 4.x>. glGetNamedFramebufferParameteriv :: MonadIO m => GLuint -- ^ @framebuffer@. -> GLenum -- ^ @pname@ of type [GetFramebufferParameter](Graphics-GL-Groups.html#GetFramebufferParameter). -> Ptr GLint -- ^ @param@. -> m () glGetNamedFramebufferParameteriv v1 v2 v3 = liftIO $ dyn348 ptr_glGetNamedFramebufferParameteriv v1 v2 v3 {-# NOINLINE ptr_glGetNamedFramebufferParameteriv #-} ptr_glGetNamedFramebufferParameteriv :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedFramebufferParameteriv = unsafePerformIO $ getCommand "glGetNamedFramebufferParameteriv" -- glGetNamedFramebufferParameterivEXT ----------------------------------------- glGetNamedFramebufferParameterivEXT :: MonadIO m => GLuint -- ^ @framebuffer@ of type @Framebuffer@. -> GLenum -- ^ @pname@ of type [GetFramebufferParameter](Graphics-GL-Groups.html#GetFramebufferParameter). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetNamedFramebufferParameterivEXT v1 v2 v3 = liftIO $ dyn348 ptr_glGetNamedFramebufferParameterivEXT v1 v2 v3 {-# NOINLINE ptr_glGetNamedFramebufferParameterivEXT #-} ptr_glGetNamedFramebufferParameterivEXT :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedFramebufferParameterivEXT = unsafePerformIO $ getCommand "glGetNamedFramebufferParameterivEXT" -- glGetNamedProgramLocalParameterIivEXT --------------------------------------- glGetNamedProgramLocalParameterIivEXT :: MonadIO m => GLuint -- ^ @program@. -> GLenum -- ^ @target@ of type [ProgramTarget](Graphics-GL-Groups.html#ProgramTarget). -> GLuint -- ^ @index@. -> Ptr GLint -- ^ @params@ pointing to @4@ elements of type @GLint@. -> m () glGetNamedProgramLocalParameterIivEXT v1 v2 v3 v4 = liftIO $ dyn381 ptr_glGetNamedProgramLocalParameterIivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedProgramLocalParameterIivEXT #-} ptr_glGetNamedProgramLocalParameterIivEXT :: FunPtr (GLuint -> GLenum -> GLuint -> Ptr GLint -> IO ()) ptr_glGetNamedProgramLocalParameterIivEXT = unsafePerformIO $ getCommand "glGetNamedProgramLocalParameterIivEXT" -- glGetNamedProgramLocalParameterIuivEXT -------------------------------------- glGetNamedProgramLocalParameterIuivEXT :: MonadIO m => GLuint -- ^ @program@. -> GLenum -- ^ @target@ of type [ProgramTarget](Graphics-GL-Groups.html#ProgramTarget). -> GLuint -- ^ @index@. -> Ptr GLuint -- ^ @params@ pointing to @4@ elements of type @GLuint@. -> m () glGetNamedProgramLocalParameterIuivEXT v1 v2 v3 v4 = liftIO $ dyn382 ptr_glGetNamedProgramLocalParameterIuivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedProgramLocalParameterIuivEXT #-} ptr_glGetNamedProgramLocalParameterIuivEXT :: FunPtr (GLuint -> GLenum -> GLuint -> Ptr GLuint -> IO ()) ptr_glGetNamedProgramLocalParameterIuivEXT = unsafePerformIO $ getCommand "glGetNamedProgramLocalParameterIuivEXT" -- glGetNamedProgramLocalParameterdvEXT ---------------------------------------- glGetNamedProgramLocalParameterdvEXT :: MonadIO m => GLuint -- ^ @program@. -> GLenum -- ^ @target@ of type [ProgramTarget](Graphics-GL-Groups.html#ProgramTarget). -> GLuint -- ^ @index@. -> Ptr GLdouble -- ^ @params@ pointing to @4@ elements of type @GLdouble@. -> m () glGetNamedProgramLocalParameterdvEXT v1 v2 v3 v4 = liftIO $ dyn383 ptr_glGetNamedProgramLocalParameterdvEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedProgramLocalParameterdvEXT #-} ptr_glGetNamedProgramLocalParameterdvEXT :: FunPtr (GLuint -> GLenum -> GLuint -> Ptr GLdouble -> IO ()) ptr_glGetNamedProgramLocalParameterdvEXT = unsafePerformIO $ getCommand "glGetNamedProgramLocalParameterdvEXT" -- glGetNamedProgramLocalParameterfvEXT ---------------------------------------- glGetNamedProgramLocalParameterfvEXT :: MonadIO m => GLuint -- ^ @program@. -> GLenum -- ^ @target@ of type [ProgramTarget](Graphics-GL-Groups.html#ProgramTarget). -> GLuint -- ^ @index@. -> Ptr GLfloat -- ^ @params@ pointing to @4@ elements of type @GLfloat@. -> m () glGetNamedProgramLocalParameterfvEXT v1 v2 v3 v4 = liftIO $ dyn384 ptr_glGetNamedProgramLocalParameterfvEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedProgramLocalParameterfvEXT #-} ptr_glGetNamedProgramLocalParameterfvEXT :: FunPtr (GLuint -> GLenum -> GLuint -> Ptr GLfloat -> IO ()) ptr_glGetNamedProgramLocalParameterfvEXT = unsafePerformIO $ getCommand "glGetNamedProgramLocalParameterfvEXT" -- glGetNamedProgramStringEXT -------------------------------------------------- glGetNamedProgramStringEXT :: MonadIO m => GLuint -- ^ @program@. -> GLenum -- ^ @target@ of type [ProgramTarget](Graphics-GL-Groups.html#ProgramTarget). -> GLenum -- ^ @pname@ of type [ProgramStringProperty](Graphics-GL-Groups.html#ProgramStringProperty). -> Ptr a -- ^ @string@ pointing to @COMPSIZE(program,pname)@ elements of type @a@. -> m () glGetNamedProgramStringEXT v1 v2 v3 v4 = liftIO $ dyn385 ptr_glGetNamedProgramStringEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedProgramStringEXT #-} ptr_glGetNamedProgramStringEXT :: FunPtr (GLuint -> GLenum -> GLenum -> Ptr a -> IO ()) ptr_glGetNamedProgramStringEXT = unsafePerformIO $ getCommand "glGetNamedProgramStringEXT" -- glGetNamedProgramivEXT ------------------------------------------------------ glGetNamedProgramivEXT :: MonadIO m => GLuint -- ^ @program@. -> GLenum -- ^ @target@ of type [ProgramTarget](Graphics-GL-Groups.html#ProgramTarget). -> GLenum -- ^ @pname@ of type [ProgramPropertyARB](Graphics-GL-Groups.html#ProgramPropertyARB). -> Ptr GLint -- ^ @params@ pointing to @1@ element of type @GLint@. -> m () glGetNamedProgramivEXT v1 v2 v3 v4 = liftIO $ dyn379 ptr_glGetNamedProgramivEXT v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedProgramivEXT #-} ptr_glGetNamedProgramivEXT :: FunPtr (GLuint -> GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedProgramivEXT = unsafePerformIO $ getCommand "glGetNamedProgramivEXT" -- glGetNamedRenderbufferParameteriv ------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetRenderbufferParameter.xhtml OpenGL 4.x>. glGetNamedRenderbufferParameteriv :: MonadIO m => GLuint -- ^ @renderbuffer@. -> GLenum -- ^ @pname@ of type [RenderbufferParameterName](Graphics-GL-Groups.html#RenderbufferParameterName). -> Ptr GLint -- ^ @params@. -> m () glGetNamedRenderbufferParameteriv v1 v2 v3 = liftIO $ dyn348 ptr_glGetNamedRenderbufferParameteriv v1 v2 v3 {-# NOINLINE ptr_glGetNamedRenderbufferParameteriv #-} ptr_glGetNamedRenderbufferParameteriv :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedRenderbufferParameteriv = unsafePerformIO $ getCommand "glGetNamedRenderbufferParameteriv" -- glGetNamedRenderbufferParameterivEXT ---------------------------------------- glGetNamedRenderbufferParameterivEXT :: MonadIO m => GLuint -- ^ @renderbuffer@ of type @Renderbuffer@. -> GLenum -- ^ @pname@ of type [RenderbufferParameterName](Graphics-GL-Groups.html#RenderbufferParameterName). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetNamedRenderbufferParameterivEXT v1 v2 v3 = liftIO $ dyn348 ptr_glGetNamedRenderbufferParameterivEXT v1 v2 v3 {-# NOINLINE ptr_glGetNamedRenderbufferParameterivEXT #-} ptr_glGetNamedRenderbufferParameterivEXT :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedRenderbufferParameterivEXT = unsafePerformIO $ getCommand "glGetNamedRenderbufferParameterivEXT" -- glGetNamedStringARB --------------------------------------------------------- glGetNamedStringARB :: MonadIO m => GLint -- ^ @namelen@. -> Ptr GLchar -- ^ @name@ pointing to @namelen@ elements of type @GLchar@. -> GLsizei -- ^ @bufSize@. -> Ptr GLint -- ^ @stringlen@ pointing to @1@ element of type @GLint@. -> Ptr GLchar -- ^ @string@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetNamedStringARB v1 v2 v3 v4 v5 = liftIO $ dyn386 ptr_glGetNamedStringARB v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetNamedStringARB #-} ptr_glGetNamedStringARB :: FunPtr (GLint -> Ptr GLchar -> GLsizei -> Ptr GLint -> Ptr GLchar -> IO ()) ptr_glGetNamedStringARB = unsafePerformIO $ getCommand "glGetNamedStringARB" -- glGetNamedStringivARB ------------------------------------------------------- glGetNamedStringivARB :: MonadIO m => GLint -- ^ @namelen@. -> Ptr GLchar -- ^ @name@ pointing to @namelen@ elements of type @GLchar@. -> GLenum -- ^ @pname@. -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetNamedStringivARB v1 v2 v3 v4 = liftIO $ dyn387 ptr_glGetNamedStringivARB v1 v2 v3 v4 {-# NOINLINE ptr_glGetNamedStringivARB #-} ptr_glGetNamedStringivARB :: FunPtr (GLint -> Ptr GLchar -> GLenum -> Ptr GLint -> IO ()) ptr_glGetNamedStringivARB = unsafePerformIO $ getCommand "glGetNamedStringivARB" -- glGetNextPerfQueryIdINTEL --------------------------------------------------- glGetNextPerfQueryIdINTEL :: MonadIO m => GLuint -- ^ @queryId@. -> Ptr GLuint -- ^ @nextQueryId@. -> m () glGetNextPerfQueryIdINTEL v1 v2 = liftIO $ dyn201 ptr_glGetNextPerfQueryIdINTEL v1 v2 {-# NOINLINE ptr_glGetNextPerfQueryIdINTEL #-} ptr_glGetNextPerfQueryIdINTEL :: FunPtr (GLuint -> Ptr GLuint -> IO ()) ptr_glGetNextPerfQueryIdINTEL = unsafePerformIO $ getCommand "glGetNextPerfQueryIdINTEL" -- glGetObjectBufferfvATI ------------------------------------------------------ glGetObjectBufferfvATI :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [ArrayObjectPNameATI](Graphics-GL-Groups.html#ArrayObjectPNameATI). -> Ptr GLfloat -- ^ @params@ pointing to @1@ element of type @GLfloat@. -> m () glGetObjectBufferfvATI v1 v2 v3 = liftIO $ dyn364 ptr_glGetObjectBufferfvATI v1 v2 v3 {-# NOINLINE ptr_glGetObjectBufferfvATI #-} ptr_glGetObjectBufferfvATI :: FunPtr (GLuint -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetObjectBufferfvATI = unsafePerformIO $ getCommand "glGetObjectBufferfvATI" -- glGetObjectBufferivATI ------------------------------------------------------ glGetObjectBufferivATI :: MonadIO m => GLuint -- ^ @buffer@. -> GLenum -- ^ @pname@ of type [ArrayObjectPNameATI](Graphics-GL-Groups.html#ArrayObjectPNameATI). -> Ptr GLint -- ^ @params@ pointing to @1@ element of type @GLint@. -> m () glGetObjectBufferivATI v1 v2 v3 = liftIO $ dyn348 ptr_glGetObjectBufferivATI v1 v2 v3 {-# NOINLINE ptr_glGetObjectBufferivATI #-} ptr_glGetObjectBufferivATI :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetObjectBufferivATI = unsafePerformIO $ getCommand "glGetObjectBufferivATI" -- glGetObjectLabel ------------------------------------------------------------ -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetObjectLabel.xhtml OpenGL 4.x>. glGetObjectLabel :: MonadIO m => GLenum -- ^ @identifier@ of type [ObjectIdentifier](Graphics-GL-Groups.html#ObjectIdentifier). -> GLuint -- ^ @name@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLchar -- ^ @label@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetObjectLabel v1 v2 v3 v4 v5 = liftIO $ dyn388 ptr_glGetObjectLabel v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetObjectLabel #-} ptr_glGetObjectLabel :: FunPtr (GLenum -> GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) ptr_glGetObjectLabel = unsafePerformIO $ getCommand "glGetObjectLabel" -- glGetObjectLabelEXT --------------------------------------------------------- glGetObjectLabelEXT :: MonadIO m => GLenum -- ^ @type@. -> GLuint -- ^ @object@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLchar -- ^ @label@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetObjectLabelEXT v1 v2 v3 v4 v5 = liftIO $ dyn388 ptr_glGetObjectLabelEXT v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetObjectLabelEXT #-} ptr_glGetObjectLabelEXT :: FunPtr (GLenum -> GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) ptr_glGetObjectLabelEXT = unsafePerformIO $ getCommand "glGetObjectLabelEXT" -- glGetObjectLabelKHR --------------------------------------------------------- -- | This command is an alias for 'glGetObjectLabel'. glGetObjectLabelKHR :: MonadIO m => GLenum -- ^ @identifier@. -> GLuint -- ^ @name@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@. -> Ptr GLchar -- ^ @label@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetObjectLabelKHR v1 v2 v3 v4 v5 = liftIO $ dyn388 ptr_glGetObjectLabelKHR v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetObjectLabelKHR #-} ptr_glGetObjectLabelKHR :: FunPtr (GLenum -> GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) ptr_glGetObjectLabelKHR = unsafePerformIO $ getCommand "glGetObjectLabelKHR" -- glGetObjectParameterfvARB --------------------------------------------------- glGetObjectParameterfvARB :: MonadIO m => GLhandleARB -- ^ @obj@ of type @handleARB@. -> GLenum -- ^ @pname@. -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetObjectParameterfvARB v1 v2 v3 = liftIO $ dyn389 ptr_glGetObjectParameterfvARB v1 v2 v3 {-# NOINLINE ptr_glGetObjectParameterfvARB #-} ptr_glGetObjectParameterfvARB :: FunPtr (GLhandleARB -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetObjectParameterfvARB = unsafePerformIO $ getCommand "glGetObjectParameterfvARB" -- glGetObjectParameterivAPPLE ------------------------------------------------- glGetObjectParameterivAPPLE :: MonadIO m => GLenum -- ^ @objectType@. -> GLuint -- ^ @name@. -> GLenum -- ^ @pname@. -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetObjectParameterivAPPLE v1 v2 v3 v4 = liftIO $ dyn366 ptr_glGetObjectParameterivAPPLE v1 v2 v3 v4 {-# NOINLINE ptr_glGetObjectParameterivAPPLE #-} ptr_glGetObjectParameterivAPPLE :: FunPtr (GLenum -> GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetObjectParameterivAPPLE = unsafePerformIO $ getCommand "glGetObjectParameterivAPPLE" -- glGetObjectParameterivARB --------------------------------------------------- glGetObjectParameterivARB :: MonadIO m => GLhandleARB -- ^ @obj@ of type @handleARB@. -> GLenum -- ^ @pname@. -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetObjectParameterivARB v1 v2 v3 = liftIO $ dyn390 ptr_glGetObjectParameterivARB v1 v2 v3 {-# NOINLINE ptr_glGetObjectParameterivARB #-} ptr_glGetObjectParameterivARB :: FunPtr (GLhandleARB -> GLenum -> Ptr GLint -> IO ()) ptr_glGetObjectParameterivARB = unsafePerformIO $ getCommand "glGetObjectParameterivARB" -- glGetObjectPtrLabel --------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetObjectPtrLabel.xhtml OpenGL 4.x>. glGetObjectPtrLabel :: MonadIO m => Ptr a -- ^ @ptr@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLchar -- ^ @label@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetObjectPtrLabel v1 v2 v3 v4 = liftIO $ dyn391 ptr_glGetObjectPtrLabel v1 v2 v3 v4 {-# NOINLINE ptr_glGetObjectPtrLabel #-} ptr_glGetObjectPtrLabel :: FunPtr (Ptr a -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) ptr_glGetObjectPtrLabel = unsafePerformIO $ getCommand "glGetObjectPtrLabel" -- glGetObjectPtrLabelKHR ------------------------------------------------------ -- | This command is an alias for 'glGetObjectPtrLabel'. glGetObjectPtrLabelKHR :: MonadIO m => Ptr a -- ^ @ptr@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLchar -- ^ @label@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetObjectPtrLabelKHR v1 v2 v3 v4 = liftIO $ dyn391 ptr_glGetObjectPtrLabelKHR v1 v2 v3 v4 {-# NOINLINE ptr_glGetObjectPtrLabelKHR #-} ptr_glGetObjectPtrLabelKHR :: FunPtr (Ptr a -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) ptr_glGetObjectPtrLabelKHR = unsafePerformIO $ getCommand "glGetObjectPtrLabelKHR" -- glGetOcclusionQueryivNV ----------------------------------------------------- glGetOcclusionQueryivNV :: MonadIO m => GLuint -- ^ @id@. -> GLenum -- ^ @pname@ of type [OcclusionQueryParameterNameNV](Graphics-GL-Groups.html#OcclusionQueryParameterNameNV). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetOcclusionQueryivNV v1 v2 v3 = liftIO $ dyn348 ptr_glGetOcclusionQueryivNV v1 v2 v3 {-# NOINLINE ptr_glGetOcclusionQueryivNV #-} ptr_glGetOcclusionQueryivNV :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetOcclusionQueryivNV = unsafePerformIO $ getCommand "glGetOcclusionQueryivNV" -- glGetOcclusionQueryuivNV ---------------------------------------------------- glGetOcclusionQueryuivNV :: MonadIO m => GLuint -- ^ @id@. -> GLenum -- ^ @pname@ of type [OcclusionQueryParameterNameNV](Graphics-GL-Groups.html#OcclusionQueryParameterNameNV). -> Ptr GLuint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLuint@. -> m () glGetOcclusionQueryuivNV v1 v2 v3 = liftIO $ dyn392 ptr_glGetOcclusionQueryuivNV v1 v2 v3 {-# NOINLINE ptr_glGetOcclusionQueryuivNV #-} ptr_glGetOcclusionQueryuivNV :: FunPtr (GLuint -> GLenum -> Ptr GLuint -> IO ()) ptr_glGetOcclusionQueryuivNV = unsafePerformIO $ getCommand "glGetOcclusionQueryuivNV" -- glGetPathColorGenfvNV ------------------------------------------------------- glGetPathColorGenfvNV :: MonadIO m => GLenum -- ^ @color@ of type [PathColor](Graphics-GL-Groups.html#PathColor). -> GLenum -- ^ @pname@ of type [PathGenMode](Graphics-GL-Groups.html#PathGenMode). -> Ptr GLfloat -- ^ @value@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetPathColorGenfvNV v1 v2 v3 = liftIO $ dyn139 ptr_glGetPathColorGenfvNV v1 v2 v3 {-# NOINLINE ptr_glGetPathColorGenfvNV #-} ptr_glGetPathColorGenfvNV :: FunPtr (GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetPathColorGenfvNV = unsafePerformIO $ getCommand "glGetPathColorGenfvNV" -- glGetPathColorGenivNV ------------------------------------------------------- glGetPathColorGenivNV :: MonadIO m => GLenum -- ^ @color@ of type [PathColor](Graphics-GL-Groups.html#PathColor). -> GLenum -- ^ @pname@ of type [PathGenMode](Graphics-GL-Groups.html#PathGenMode). -> Ptr GLint -- ^ @value@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetPathColorGenivNV v1 v2 v3 = liftIO $ dyn140 ptr_glGetPathColorGenivNV v1 v2 v3 {-# NOINLINE ptr_glGetPathColorGenivNV #-} ptr_glGetPathColorGenivNV :: FunPtr (GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetPathColorGenivNV = unsafePerformIO $ getCommand "glGetPathColorGenivNV" -- glGetPathCommandsNV --------------------------------------------------------- glGetPathCommandsNV :: MonadIO m => GLuint -- ^ @path@ of type @Path@. -> Ptr GLubyte -- ^ @commands@ pointing to @COMPSIZE(path)@ elements of type @PathCommand@. -> m () glGetPathCommandsNV v1 v2 = liftIO $ dyn393 ptr_glGetPathCommandsNV v1 v2 {-# NOINLINE ptr_glGetPathCommandsNV #-} ptr_glGetPathCommandsNV :: FunPtr (GLuint -> Ptr GLubyte -> IO ()) ptr_glGetPathCommandsNV = unsafePerformIO $ getCommand "glGetPathCommandsNV" -- glGetPathCoordsNV ----------------------------------------------------------- glGetPathCoordsNV :: MonadIO m => GLuint -- ^ @path@ of type @Path@. -> Ptr GLfloat -- ^ @coords@ pointing to @COMPSIZE(path)@ elements of type @GLfloat@. -> m () glGetPathCoordsNV v1 v2 = liftIO $ dyn394 ptr_glGetPathCoordsNV v1 v2 {-# NOINLINE ptr_glGetPathCoordsNV #-} ptr_glGetPathCoordsNV :: FunPtr (GLuint -> Ptr GLfloat -> IO ()) ptr_glGetPathCoordsNV = unsafePerformIO $ getCommand "glGetPathCoordsNV" -- glGetPathDashArrayNV -------------------------------------------------------- glGetPathDashArrayNV :: MonadIO m => GLuint -- ^ @path@ of type @Path@. -> Ptr GLfloat -- ^ @dashArray@ pointing to @COMPSIZE(path)@ elements of type @GLfloat@. -> m () glGetPathDashArrayNV v1 v2 = liftIO $ dyn394 ptr_glGetPathDashArrayNV v1 v2 {-# NOINLINE ptr_glGetPathDashArrayNV #-} ptr_glGetPathDashArrayNV :: FunPtr (GLuint -> Ptr GLfloat -> IO ()) ptr_glGetPathDashArrayNV = unsafePerformIO $ getCommand "glGetPathDashArrayNV" -- glGetPathLengthNV ----------------------------------------------------------- glGetPathLengthNV :: MonadIO m => GLuint -- ^ @path@ of type @Path@. -> GLsizei -- ^ @startSegment@. -> GLsizei -- ^ @numSegments@. -> m GLfloat glGetPathLengthNV v1 v2 v3 = liftIO $ dyn395 ptr_glGetPathLengthNV v1 v2 v3 {-# NOINLINE ptr_glGetPathLengthNV #-} ptr_glGetPathLengthNV :: FunPtr (GLuint -> GLsizei -> GLsizei -> IO GLfloat) ptr_glGetPathLengthNV = unsafePerformIO $ getCommand "glGetPathLengthNV" -- glGetPathMetricRangeNV ------------------------------------------------------ glGetPathMetricRangeNV :: MonadIO m => GLbitfield -- ^ @metricQueryMask@ of type [PathMetricMask](Graphics-GL-Groups.html#PathMetricMask). -> GLuint -- ^ @firstPathName@ of type @Path@. -> GLsizei -- ^ @numPaths@. -> GLsizei -- ^ @stride@. -> Ptr GLfloat -- ^ @metrics@ pointing to @COMPSIZE(metricQueryMask,numPaths,stride)@ elements of type @GLfloat@. -> m () glGetPathMetricRangeNV v1 v2 v3 v4 v5 = liftIO $ dyn396 ptr_glGetPathMetricRangeNV v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetPathMetricRangeNV #-} ptr_glGetPathMetricRangeNV :: FunPtr (GLbitfield -> GLuint -> GLsizei -> GLsizei -> Ptr GLfloat -> IO ()) ptr_glGetPathMetricRangeNV = unsafePerformIO $ getCommand "glGetPathMetricRangeNV" -- glGetPathMetricsNV ---------------------------------------------------------- glGetPathMetricsNV :: MonadIO m => GLbitfield -- ^ @metricQueryMask@ of type [PathMetricMask](Graphics-GL-Groups.html#PathMetricMask). -> GLsizei -- ^ @numPaths@. -> GLenum -- ^ @pathNameType@ of type [PathElementType](Graphics-GL-Groups.html#PathElementType). -> Ptr a -- ^ @paths@ pointing to @COMPSIZE(numPaths,pathNameType,paths)@ elements of type @PathElement@. -> GLuint -- ^ @pathBase@ of type @Path@. -> GLsizei -- ^ @stride@. -> Ptr GLfloat -- ^ @metrics@ pointing to @COMPSIZE(metricQueryMask,numPaths,stride)@ elements of type @GLfloat@. -> m () glGetPathMetricsNV v1 v2 v3 v4 v5 v6 v7 = liftIO $ dyn397 ptr_glGetPathMetricsNV v1 v2 v3 v4 v5 v6 v7 {-# NOINLINE ptr_glGetPathMetricsNV #-} ptr_glGetPathMetricsNV :: FunPtr (GLbitfield -> GLsizei -> GLenum -> Ptr a -> GLuint -> GLsizei -> Ptr GLfloat -> IO ()) ptr_glGetPathMetricsNV = unsafePerformIO $ getCommand "glGetPathMetricsNV" -- glGetPathParameterfvNV ------------------------------------------------------ glGetPathParameterfvNV :: MonadIO m => GLuint -- ^ @path@ of type @Path@. -> GLenum -- ^ @pname@ of type [PathParameter](Graphics-GL-Groups.html#PathParameter). -> Ptr GLfloat -- ^ @value@ pointing to @4@ elements of type @GLfloat@. -> m () glGetPathParameterfvNV v1 v2 v3 = liftIO $ dyn364 ptr_glGetPathParameterfvNV v1 v2 v3 {-# NOINLINE ptr_glGetPathParameterfvNV #-} ptr_glGetPathParameterfvNV :: FunPtr (GLuint -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetPathParameterfvNV = unsafePerformIO $ getCommand "glGetPathParameterfvNV" -- glGetPathParameterivNV ------------------------------------------------------ glGetPathParameterivNV :: MonadIO m => GLuint -- ^ @path@ of type @Path@. -> GLenum -- ^ @pname@ of type [PathParameter](Graphics-GL-Groups.html#PathParameter). -> Ptr GLint -- ^ @value@ pointing to @4@ elements of type @GLint@. -> m () glGetPathParameterivNV v1 v2 v3 = liftIO $ dyn348 ptr_glGetPathParameterivNV v1 v2 v3 {-# NOINLINE ptr_glGetPathParameterivNV #-} ptr_glGetPathParameterivNV :: FunPtr (GLuint -> GLenum -> Ptr GLint -> IO ()) ptr_glGetPathParameterivNV = unsafePerformIO $ getCommand "glGetPathParameterivNV" -- glGetPathSpacingNV ---------------------------------------------------------- glGetPathSpacingNV :: MonadIO m => GLenum -- ^ @pathListMode@ of type [PathListMode](Graphics-GL-Groups.html#PathListMode). -> GLsizei -- ^ @numPaths@. -> GLenum -- ^ @pathNameType@ of type [PathElementType](Graphics-GL-Groups.html#PathElementType). -> Ptr a -- ^ @paths@ pointing to @COMPSIZE(numPaths,pathNameType,paths)@ elements of type @PathElement@. -> GLuint -- ^ @pathBase@ of type @Path@. -> GLfloat -- ^ @advanceScale@. -> GLfloat -- ^ @kerningScale@. -> GLenum -- ^ @transformType@ of type [PathTransformType](Graphics-GL-Groups.html#PathTransformType). -> Ptr GLfloat -- ^ @returnedSpacing@ pointing to @COMPSIZE(pathListMode,numPaths)@ elements of type @GLfloat@. -> m () glGetPathSpacingNV v1 v2 v3 v4 v5 v6 v7 v8 v9 = liftIO $ dyn398 ptr_glGetPathSpacingNV v1 v2 v3 v4 v5 v6 v7 v8 v9 {-# NOINLINE ptr_glGetPathSpacingNV #-} ptr_glGetPathSpacingNV :: FunPtr (GLenum -> GLsizei -> GLenum -> Ptr a -> GLuint -> GLfloat -> GLfloat -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetPathSpacingNV = unsafePerformIO $ getCommand "glGetPathSpacingNV" -- glGetPathTexGenfvNV --------------------------------------------------------- glGetPathTexGenfvNV :: MonadIO m => GLenum -- ^ @texCoordSet@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @pname@ of type [PathGenMode](Graphics-GL-Groups.html#PathGenMode). -> Ptr GLfloat -- ^ @value@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetPathTexGenfvNV v1 v2 v3 = liftIO $ dyn139 ptr_glGetPathTexGenfvNV v1 v2 v3 {-# NOINLINE ptr_glGetPathTexGenfvNV #-} ptr_glGetPathTexGenfvNV :: FunPtr (GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetPathTexGenfvNV = unsafePerformIO $ getCommand "glGetPathTexGenfvNV" -- glGetPathTexGenivNV --------------------------------------------------------- glGetPathTexGenivNV :: MonadIO m => GLenum -- ^ @texCoordSet@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit). -> GLenum -- ^ @pname@ of type [PathGenMode](Graphics-GL-Groups.html#PathGenMode). -> Ptr GLint -- ^ @value@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetPathTexGenivNV v1 v2 v3 = liftIO $ dyn140 ptr_glGetPathTexGenivNV v1 v2 v3 {-# NOINLINE ptr_glGetPathTexGenivNV #-} ptr_glGetPathTexGenivNV :: FunPtr (GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetPathTexGenivNV = unsafePerformIO $ getCommand "glGetPathTexGenivNV" -- glGetPerfCounterInfoINTEL --------------------------------------------------- glGetPerfCounterInfoINTEL :: MonadIO m => GLuint -- ^ @queryId@. -> GLuint -- ^ @counterId@. -> GLuint -- ^ @counterNameLength@. -> Ptr GLchar -- ^ @counterName@. -> GLuint -- ^ @counterDescLength@. -> Ptr GLchar -- ^ @counterDesc@. -> Ptr GLuint -- ^ @counterOffset@. -> Ptr GLuint -- ^ @counterDataSize@. -> Ptr GLuint -- ^ @counterTypeEnum@. -> Ptr GLuint -- ^ @counterDataTypeEnum@. -> Ptr GLuint64 -- ^ @rawCounterMaxValue@. -> m () glGetPerfCounterInfoINTEL v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 = liftIO $ dyn399 ptr_glGetPerfCounterInfoINTEL v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 {-# NOINLINE ptr_glGetPerfCounterInfoINTEL #-} ptr_glGetPerfCounterInfoINTEL :: FunPtr (GLuint -> GLuint -> GLuint -> Ptr GLchar -> GLuint -> Ptr GLchar -> Ptr GLuint -> Ptr GLuint -> Ptr GLuint -> Ptr GLuint -> Ptr GLuint64 -> IO ()) ptr_glGetPerfCounterInfoINTEL = unsafePerformIO $ getCommand "glGetPerfCounterInfoINTEL" -- glGetPerfMonitorCounterDataAMD ---------------------------------------------- glGetPerfMonitorCounterDataAMD :: MonadIO m => GLuint -- ^ @monitor@. -> GLenum -- ^ @pname@. -> GLsizei -- ^ @dataSize@. -> Ptr GLuint -- ^ @data@ pointing to @dataSize@ elements of type @GLuint@. -> Ptr GLint -- ^ @bytesWritten@ pointing to @1@ element of type @GLint@. -> m () glGetPerfMonitorCounterDataAMD v1 v2 v3 v4 v5 = liftIO $ dyn400 ptr_glGetPerfMonitorCounterDataAMD v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetPerfMonitorCounterDataAMD #-} ptr_glGetPerfMonitorCounterDataAMD :: FunPtr (GLuint -> GLenum -> GLsizei -> Ptr GLuint -> Ptr GLint -> IO ()) ptr_glGetPerfMonitorCounterDataAMD = unsafePerformIO $ getCommand "glGetPerfMonitorCounterDataAMD" -- glGetPerfMonitorCounterInfoAMD ---------------------------------------------- glGetPerfMonitorCounterInfoAMD :: MonadIO m => GLuint -- ^ @group@. -> GLuint -- ^ @counter@. -> GLenum -- ^ @pname@. -> Ptr a -- ^ @data@ pointing to @COMPSIZE(pname)@ elements of type @a@. -> m () glGetPerfMonitorCounterInfoAMD v1 v2 v3 v4 = liftIO $ dyn401 ptr_glGetPerfMonitorCounterInfoAMD v1 v2 v3 v4 {-# NOINLINE ptr_glGetPerfMonitorCounterInfoAMD #-} ptr_glGetPerfMonitorCounterInfoAMD :: FunPtr (GLuint -> GLuint -> GLenum -> Ptr a -> IO ()) ptr_glGetPerfMonitorCounterInfoAMD = unsafePerformIO $ getCommand "glGetPerfMonitorCounterInfoAMD" -- glGetPerfMonitorCounterStringAMD -------------------------------------------- glGetPerfMonitorCounterStringAMD :: MonadIO m => GLuint -- ^ @group@. -> GLuint -- ^ @counter@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLchar -- ^ @counterString@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetPerfMonitorCounterStringAMD v1 v2 v3 v4 v5 = liftIO $ dyn319 ptr_glGetPerfMonitorCounterStringAMD v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetPerfMonitorCounterStringAMD #-} ptr_glGetPerfMonitorCounterStringAMD :: FunPtr (GLuint -> GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) ptr_glGetPerfMonitorCounterStringAMD = unsafePerformIO $ getCommand "glGetPerfMonitorCounterStringAMD" -- glGetPerfMonitorCountersAMD ------------------------------------------------- glGetPerfMonitorCountersAMD :: MonadIO m => GLuint -- ^ @group@. -> Ptr GLint -- ^ @numCounters@ pointing to @1@ element of type @GLint@. -> Ptr GLint -- ^ @maxActiveCounters@ pointing to @1@ element of type @GLint@. -> GLsizei -- ^ @counterSize@. -> Ptr GLuint -- ^ @counters@ pointing to @counterSize@ elements of type @GLuint@. -> m () glGetPerfMonitorCountersAMD v1 v2 v3 v4 v5 = liftIO $ dyn402 ptr_glGetPerfMonitorCountersAMD v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetPerfMonitorCountersAMD #-} ptr_glGetPerfMonitorCountersAMD :: FunPtr (GLuint -> Ptr GLint -> Ptr GLint -> GLsizei -> Ptr GLuint -> IO ()) ptr_glGetPerfMonitorCountersAMD = unsafePerformIO $ getCommand "glGetPerfMonitorCountersAMD" -- glGetPerfMonitorGroupStringAMD ---------------------------------------------- glGetPerfMonitorGroupStringAMD :: MonadIO m => GLuint -- ^ @group@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLchar -- ^ @groupString@ pointing to @bufSize@ elements of type @GLchar@. -> m () glGetPerfMonitorGroupStringAMD v1 v2 v3 v4 = liftIO $ dyn345 ptr_glGetPerfMonitorGroupStringAMD v1 v2 v3 v4 {-# NOINLINE ptr_glGetPerfMonitorGroupStringAMD #-} ptr_glGetPerfMonitorGroupStringAMD :: FunPtr (GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) ptr_glGetPerfMonitorGroupStringAMD = unsafePerformIO $ getCommand "glGetPerfMonitorGroupStringAMD" -- glGetPerfMonitorGroupsAMD --------------------------------------------------- glGetPerfMonitorGroupsAMD :: MonadIO m => Ptr GLint -- ^ @numGroups@ pointing to @1@ element of type @GLint@. -> GLsizei -- ^ @groupsSize@. -> Ptr GLuint -- ^ @groups@ pointing to @groupsSize@ elements of type @GLuint@. -> m () glGetPerfMonitorGroupsAMD v1 v2 v3 = liftIO $ dyn346 ptr_glGetPerfMonitorGroupsAMD v1 v2 v3 {-# NOINLINE ptr_glGetPerfMonitorGroupsAMD #-} ptr_glGetPerfMonitorGroupsAMD :: FunPtr (Ptr GLint -> GLsizei -> Ptr GLuint -> IO ()) ptr_glGetPerfMonitorGroupsAMD = unsafePerformIO $ getCommand "glGetPerfMonitorGroupsAMD" -- glGetPerfQueryDataINTEL ----------------------------------------------------- glGetPerfQueryDataINTEL :: MonadIO m => GLuint -- ^ @queryHandle@. -> GLuint -- ^ @flags@. -> GLsizei -- ^ @dataSize@. -> Ptr a -- ^ @data@. -> Ptr GLuint -- ^ @bytesWritten@. -> m () glGetPerfQueryDataINTEL v1 v2 v3 v4 v5 = liftIO $ dyn403 ptr_glGetPerfQueryDataINTEL v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetPerfQueryDataINTEL #-} ptr_glGetPerfQueryDataINTEL :: FunPtr (GLuint -> GLuint -> GLsizei -> Ptr a -> Ptr GLuint -> IO ()) ptr_glGetPerfQueryDataINTEL = unsafePerformIO $ getCommand "glGetPerfQueryDataINTEL" -- glGetPerfQueryIdByNameINTEL ------------------------------------------------- glGetPerfQueryIdByNameINTEL :: MonadIO m => Ptr GLchar -- ^ @queryName@. -> Ptr GLuint -- ^ @queryId@. -> m () glGetPerfQueryIdByNameINTEL v1 v2 = liftIO $ dyn404 ptr_glGetPerfQueryIdByNameINTEL v1 v2 {-# NOINLINE ptr_glGetPerfQueryIdByNameINTEL #-} ptr_glGetPerfQueryIdByNameINTEL :: FunPtr (Ptr GLchar -> Ptr GLuint -> IO ()) ptr_glGetPerfQueryIdByNameINTEL = unsafePerformIO $ getCommand "glGetPerfQueryIdByNameINTEL" -- glGetPerfQueryInfoINTEL ----------------------------------------------------- glGetPerfQueryInfoINTEL :: MonadIO m => GLuint -- ^ @queryId@. -> GLuint -- ^ @queryNameLength@. -> Ptr GLchar -- ^ @queryName@. -> Ptr GLuint -- ^ @dataSize@. -> Ptr GLuint -- ^ @noCounters@. -> Ptr GLuint -- ^ @noInstances@. -> Ptr GLuint -- ^ @capsMask@. -> m () glGetPerfQueryInfoINTEL v1 v2 v3 v4 v5 v6 v7 = liftIO $ dyn405 ptr_glGetPerfQueryInfoINTEL v1 v2 v3 v4 v5 v6 v7 {-# NOINLINE ptr_glGetPerfQueryInfoINTEL #-} ptr_glGetPerfQueryInfoINTEL :: FunPtr (GLuint -> GLuint -> Ptr GLchar -> Ptr GLuint -> Ptr GLuint -> Ptr GLuint -> Ptr GLuint -> IO ()) ptr_glGetPerfQueryInfoINTEL = unsafePerformIO $ getCommand "glGetPerfQueryInfoINTEL" -- glGetPixelMapfv ------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetPixelMap.xml OpenGL 2.x>. glGetPixelMapfv :: MonadIO m => GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap). -> Ptr GLfloat -- ^ @values@ pointing to @COMPSIZE(map)@ elements of type @GLfloat@. -> m () glGetPixelMapfv v1 v2 = liftIO $ dyn101 ptr_glGetPixelMapfv v1 v2 {-# NOINLINE ptr_glGetPixelMapfv #-} ptr_glGetPixelMapfv :: FunPtr (GLenum -> Ptr GLfloat -> IO ()) ptr_glGetPixelMapfv = unsafePerformIO $ getCommand "glGetPixelMapfv" -- glGetPixelMapuiv ------------------------------------------------------------ -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetPixelMap.xml OpenGL 2.x>. glGetPixelMapuiv :: MonadIO m => GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap). -> Ptr GLuint -- ^ @values@ pointing to @COMPSIZE(map)@ elements of type @GLuint@. -> m () glGetPixelMapuiv v1 v2 = liftIO $ dyn132 ptr_glGetPixelMapuiv v1 v2 {-# NOINLINE ptr_glGetPixelMapuiv #-} ptr_glGetPixelMapuiv :: FunPtr (GLenum -> Ptr GLuint -> IO ()) ptr_glGetPixelMapuiv = unsafePerformIO $ getCommand "glGetPixelMapuiv" -- glGetPixelMapusv ------------------------------------------------------------ -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetPixelMap.xml OpenGL 2.x>. glGetPixelMapusv :: MonadIO m => GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap). -> Ptr GLushort -- ^ @values@ pointing to @COMPSIZE(map)@ elements of type @GLushort@. -> m () glGetPixelMapusv v1 v2 = liftIO $ dyn406 ptr_glGetPixelMapusv v1 v2 {-# NOINLINE ptr_glGetPixelMapusv #-} ptr_glGetPixelMapusv :: FunPtr (GLenum -> Ptr GLushort -> IO ()) ptr_glGetPixelMapusv = unsafePerformIO $ getCommand "glGetPixelMapusv" -- glGetPixelMapxv ------------------------------------------------------------- glGetPixelMapxv :: MonadIO m => GLenum -- ^ @map@ of type [PixelMap](Graphics-GL-Groups.html#PixelMap). -> GLint -- ^ @size@. -> Ptr GLfixed -- ^ @values@ pointing to @size@ elements of type @GLfixed@. -> m () glGetPixelMapxv v1 v2 v3 = liftIO $ dyn407 ptr_glGetPixelMapxv v1 v2 v3 {-# NOINLINE ptr_glGetPixelMapxv #-} ptr_glGetPixelMapxv :: FunPtr (GLenum -> GLint -> Ptr GLfixed -> IO ()) ptr_glGetPixelMapxv = unsafePerformIO $ getCommand "glGetPixelMapxv" -- glGetPixelTexGenParameterfvSGIS --------------------------------------------- glGetPixelTexGenParameterfvSGIS :: MonadIO m => GLenum -- ^ @pname@ of type [PixelTexGenParameterNameSGIS](Graphics-GL-Groups.html#PixelTexGenParameterNameSGIS). -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @CheckedFloat32@. -> m () glGetPixelTexGenParameterfvSGIS v1 v2 = liftIO $ dyn101 ptr_glGetPixelTexGenParameterfvSGIS v1 v2 {-# NOINLINE ptr_glGetPixelTexGenParameterfvSGIS #-} ptr_glGetPixelTexGenParameterfvSGIS :: FunPtr (GLenum -> Ptr GLfloat -> IO ()) ptr_glGetPixelTexGenParameterfvSGIS = unsafePerformIO $ getCommand "glGetPixelTexGenParameterfvSGIS" -- glGetPixelTexGenParameterivSGIS --------------------------------------------- glGetPixelTexGenParameterivSGIS :: MonadIO m => GLenum -- ^ @pname@ of type [PixelTexGenParameterNameSGIS](Graphics-GL-Groups.html#PixelTexGenParameterNameSGIS). -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @CheckedInt32@. -> m () glGetPixelTexGenParameterivSGIS v1 v2 = liftIO $ dyn143 ptr_glGetPixelTexGenParameterivSGIS v1 v2 {-# NOINLINE ptr_glGetPixelTexGenParameterivSGIS #-} ptr_glGetPixelTexGenParameterivSGIS :: FunPtr (GLenum -> Ptr GLint -> IO ()) ptr_glGetPixelTexGenParameterivSGIS = unsafePerformIO $ getCommand "glGetPixelTexGenParameterivSGIS" -- glGetPixelTransformParameterfvEXT ------------------------------------------- glGetPixelTransformParameterfvEXT :: MonadIO m => GLenum -- ^ @target@. -> GLenum -- ^ @pname@. -> Ptr GLfloat -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLfloat@. -> m () glGetPixelTransformParameterfvEXT v1 v2 v3 = liftIO $ dyn139 ptr_glGetPixelTransformParameterfvEXT v1 v2 v3 {-# NOINLINE ptr_glGetPixelTransformParameterfvEXT #-} ptr_glGetPixelTransformParameterfvEXT :: FunPtr (GLenum -> GLenum -> Ptr GLfloat -> IO ()) ptr_glGetPixelTransformParameterfvEXT = unsafePerformIO $ getCommand "glGetPixelTransformParameterfvEXT" -- glGetPixelTransformParameterivEXT ------------------------------------------- glGetPixelTransformParameterivEXT :: MonadIO m => GLenum -- ^ @target@. -> GLenum -- ^ @pname@. -> Ptr GLint -- ^ @params@ pointing to @COMPSIZE(pname)@ elements of type @GLint@. -> m () glGetPixelTransformParameterivEXT v1 v2 v3 = liftIO $ dyn140 ptr_glGetPixelTransformParameterivEXT v1 v2 v3 {-# NOINLINE ptr_glGetPixelTransformParameterivEXT #-} ptr_glGetPixelTransformParameterivEXT :: FunPtr (GLenum -> GLenum -> Ptr GLint -> IO ()) ptr_glGetPixelTransformParameterivEXT = unsafePerformIO $ getCommand "glGetPixelTransformParameterivEXT" -- glGetPointerIndexedvEXT ----------------------------------------------------- glGetPointerIndexedvEXT :: MonadIO m => GLenum -- ^ @target@. -> GLuint -- ^ @index@. -> Ptr (Ptr a) -- ^ @data@ pointing to @1@ element of type @Ptr a@. -> m () glGetPointerIndexedvEXT v1 v2 v3 = liftIO $ dyn408 ptr_glGetPointerIndexedvEXT v1 v2 v3 {-# NOINLINE ptr_glGetPointerIndexedvEXT #-} ptr_glGetPointerIndexedvEXT :: FunPtr (GLenum -> GLuint -> Ptr (Ptr a) -> IO ()) ptr_glGetPointerIndexedvEXT = unsafePerformIO $ getCommand "glGetPointerIndexedvEXT" -- glGetPointeri_vEXT ---------------------------------------------------------- glGetPointeri_vEXT :: MonadIO m => GLenum -- ^ @pname@. -> GLuint -- ^ @index@. -> Ptr (Ptr a) -- ^ @params@ pointing to @1@ element of type @Ptr a@. -> m () glGetPointeri_vEXT v1 v2 v3 = liftIO $ dyn408 ptr_glGetPointeri_vEXT v1 v2 v3 {-# NOINLINE ptr_glGetPointeri_vEXT #-} ptr_glGetPointeri_vEXT :: FunPtr (GLenum -> GLuint -> Ptr (Ptr a) -> IO ()) ptr_glGetPointeri_vEXT = unsafePerformIO $ getCommand "glGetPointeri_vEXT" -- glGetPointerv --------------------------------------------------------------- -- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetPointerv.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man4/html/glGetPointerv.xhtml OpenGL 4.x>. glGetPointerv :: MonadIO m => GLenum -- ^ @pname@ of type [GetPointervPName](Graphics-GL-Groups.html#GetPointervPName). -> Ptr (Ptr a) -- ^ @params@ pointing to @1@ element of type @Ptr a@. -> m () glGetPointerv v1 v2 = liftIO $ dyn279 ptr_glGetPointerv v1 v2 {-# NOINLINE ptr_glGetPointerv #-} ptr_glGetPointerv :: FunPtr (GLenum -> Ptr (Ptr a) -> IO ()) ptr_glGetPointerv = unsafePerformIO $ getCommand "glGetPointerv" -- glGetPointervEXT ------------------------------------------------------------ -- | This command is an alias for 'glGetPointerv'. glGetPointervEXT :: MonadIO m => GLenum -- ^ @pname@ of type [GetPointervPName](Graphics-GL-Groups.html#GetPointervPName). -> Ptr (Ptr a) -- ^ @params@ pointing to @1@ element of type @Ptr a@. -> m () glGetPointervEXT v1 v2 = liftIO $ dyn279 ptr_glGetPointervEXT v1 v2 {-# NOINLINE ptr_glGetPointervEXT #-} ptr_glGetPointervEXT :: FunPtr (GLenum -> Ptr (Ptr a) -> IO ()) ptr_glGetPointervEXT = unsafePerformIO $ getCommand "glGetPointervEXT" -- glGetPointervKHR ------------------------------------------------------------ -- | This command is an alias for 'glGetPointerv'. glGetPointervKHR :: MonadIO m => GLenum -- ^ @pname@. -> Ptr (Ptr a) -- ^ @params@. -> m () glGetPointervKHR v1 v2 = liftIO $ dyn279 ptr_glGetPointervKHR v1 v2 {-# NOINLINE ptr_glGetPointervKHR #-} ptr_glGetPointervKHR :: FunPtr (GLenum -> Ptr (Ptr a) -> IO ()) ptr_glGetPointervKHR = unsafePerformIO $ getCommand "glGetPointervKHR" -- glGetPolygonStipple --------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glGetPolygonStipple.xml OpenGL 2.x>. glGetPolygonStipple :: MonadIO m => Ptr GLubyte -- ^ @mask@ pointing to @COMPSIZE()@ elements of type @GLubyte@. -> m () glGetPolygonStipple v1 = liftIO $ dyn108 ptr_glGetPolygonStipple v1 {-# NOINLINE ptr_glGetPolygonStipple #-} ptr_glGetPolygonStipple :: FunPtr (Ptr GLubyte -> IO ()) ptr_glGetPolygonStipple = unsafePerformIO $ getCommand "glGetPolygonStipple" -- glGetProgramBinary ---------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glGetProgramBinary.xhtml OpenGL 4.x>. glGetProgramBinary :: MonadIO m => GLuint -- ^ @program@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLenum -- ^ @binaryFormat@ pointing to @1@ element of type @GLenum@. -> Ptr a -- ^ @binary@ pointing to @bufSize@ elements of type @a@. -> m () glGetProgramBinary v1 v2 v3 v4 v5 = liftIO $ dyn409 ptr_glGetProgramBinary v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetProgramBinary #-} ptr_glGetProgramBinary :: FunPtr (GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLenum -> Ptr a -> IO ()) ptr_glGetProgramBinary = unsafePerformIO $ getCommand "glGetProgramBinary" -- glGetProgramBinaryOES ------------------------------------------------------- -- | This command is an alias for 'glGetProgramBinary'. glGetProgramBinaryOES :: MonadIO m => GLuint -- ^ @program@. -> GLsizei -- ^ @bufSize@. -> Ptr GLsizei -- ^ @length@ pointing to @1@ element of type @GLsizei@. -> Ptr GLenum -- ^ @binaryFormat@ pointing to @1@ element of type @GLenum@. -> Ptr a -- ^ @binary@ pointing to @bufSize@ elements of type @a@. -> m () glGetProgramBinaryOES v1 v2 v3 v4 v5 = liftIO $ dyn409 ptr_glGetProgramBinaryOES v1 v2 v3 v4 v5 {-# NOINLINE ptr_glGetProgramBinaryOES #-} ptr_glGetProgramBinaryOES :: FunPtr (GLuint -> GLsizei -> Ptr GLsizei -> Ptr GLenum -> Ptr a -> IO ()) ptr_glGetProgramBinaryOES = unsafePerformIO $ getCommand "glGetProgramBinaryOES"
haskell-opengl/OpenGLRaw
src/Graphics/GL/Functions/F11.hs
bsd-3-clause
75,498
0
19
9,860
12,076
6,170
5,906
1,177
1
{- | Use this module to build your own version of the Yesod scaffolding's DevelMain.hs. Do this by creating a module that wraps a call to update with proper arguments, e.g. the webapp you're developing. Generally you'll re-export shutdown as-is. For an example, see Snowdrift's dev/Runner.hs (FIXME: Add a link once it's merged). Then you can quickly iterate and rerun the computation. Start @stack ghci@, :load your module, and run the computation that is the wrapped version of update. After hacking some, :reload and rerun the computation. -} module Dev.Runner (update, shutdown) where import Control.Exception (finally) import Control.Monad ((>=>)) import Control.Concurrent import Data.IORef import Foreign.Store import GHC.Word -- | (Re)start the computation. update :: IO () -- ^ Computation to run -> IO () -- ^ Shutdown hook (try @return ()@ for simple cases) -> IO () update comp abrt = do mtidStore <- lookupStore tidStoreNum case mtidStore of -- no computation running Nothing -> do lock <- storeAction lockStore newEmptyMVar tid <- start lock _ <- storeAction (Store tidStoreNum) (newIORef tid) return () -- computation is already running Just tidStore -> restartAppInNewThread tidStore where lockStore :: Store (MVar ()) lockStore = Store 0 -- shut the computation down with killThread and wait for the done signal restartAppInNewThread :: Store (IORef ThreadId) -> IO () restartAppInNewThread tidStore = modifyStoredIORef tidStore $ \tid -> do killThread tid withStore lockStore takeMVar readStore lockStore >>= start -- | Start the computation in a separate thread. start :: MVar () -- ^ Written to when the thread is killed. -> IO ThreadId start lock = do forkIO (finally comp -- Note that this implies concurrency -- between shutdownApp and the next app that is starting. -- Normally this should be fine (putMVar lock () >> abrt)) -- | Kill the computation. shutdown :: IO () shutdown = do mtidStore <- lookupStore tidStoreNum case mtidStore of -- no server running Nothing -> putStrLn "no computation running" Just tidStore -> do withStore tidStore $ readIORef >=> killThread putStrLn "computation shut down" tidStoreNum :: Word32 tidStoreNum = 1 modifyStoredIORef :: Store (IORef a) -> (a -> IO a) -> IO () modifyStoredIORef store f = withStore store $ \ref -> do v <- readIORef ref f v >>= writeIORef ref
chreekat/ghci-runner
src/Dev/Runner.hs
bsd-3-clause
2,648
0
15
695
505
248
257
45
2
module Problem14 ( longestCollatz , collatz ) where import Data.List as L longestCollatz :: Int -> Int longestCollatz cap = let seqs = map (\n -> (length.collatz $ n, n)) [1..cap] longest = L.maximum seqs in snd longest collatz :: Int -> [Int] collatz 1 = [1] collatz n = let n' = nextCollatz n in n' : collatz n' where nextCollatz n | even n = n `div` 2 | otherwise = 3*n + 1
candidtim/euler
src/Problem14.hs
bsd-3-clause
427
0
14
126
184
96
88
17
1
{-# LANGUAGE CPP #-} module DBUtil where import Control.Applicative ((<$>)) import Database.Persist import Database.Persist.GenericSql import Model -- #define SQLite #ifdef SQLite import Database.Persist.Sqlite (withSqliteConn) runSql :: SqlPersist IO a -> IO a runSql = withSqliteConn dbfile . runSqlConn where dbfile = "db.sqlite3" #else import Data.Monoid ((<>)) import Data.Text.Encoding (encodeUtf8) import Database.Persist.Postgresql (withPostgresqlConn) import Web.Heroku (dbConnParams) runSql :: SqlPersist IO a -> IO a runSql query = do params <- dbConnParams let connStr = foldr (\(k,v) t -> t <> (encodeUtf8 $ k <> "=" <> v <> " ")) "" params withPostgresqlConn connStr $ runSqlConn query #endif readPosts :: IO [Post] readPosts = map entityVal <$> (runSql $ selectList [] [Desc PostId, LimitTo 50]) addPost :: Post -> IO () addPost post = runSql $ insert post >> return ()
daimatz/scotty-on-heroku
src/DBUtil.hs
bsd-3-clause
1,078
0
10
323
169
93
76
20
1
{-# LANGUAGE PatternGuards #-} {-# LANGUAGE NoMonomorphismRestriction, MonoLocalBinds #-} module XMonad.StackSet (StackSet(..), Workspace(..), Screen(..), Stack(..), RationalRect(..), new, view, greedyView, lookupWorkspace, screens, workspaces, allWindows, currentTag, peek, index, integrate, integrate', differentiate, focusUp, focusDown, focusUp', focusDown', focusMaster, focusWindow, tagMember, renameTag, ensureTags, member, findTag, mapWorkspace, mapLayout, insertUp, delete, delete', filter, swapUp, swapDown, swapMaster, shiftMaster, modify, modify', float, sink, shift, shiftWin, abort) where import Prelude (Ord, Eq, Rational, Show, Read, String, Integral, Bool(True, False), Maybe(Just, Nothing), maybe, reverse, map, elem, return, otherwise, concatMap, not, null, length, zip3, until, any, error, (.), (/=), (==), (<=), ($), (++), (>>=), (&&),enumFrom) import Data.Maybe (listToMaybe, isJust, fromMaybe) import qualified Data.List as L (deleteBy, find, splitAt, filter, nub) import Data.List ((\\)) import qualified Data.Map as M (Map, insert, delete, empty) import Control.Monad (fail,(>>),guard) data StackSet i l a sid sd = StackSet{current :: !(Screen i l a sid sd), visible :: [Screen i l a sid sd], hidden :: [Workspace i l a], floating :: M.Map a RationalRect} deriving (Show, Read, Eq) data Screen i l a sid sd = Screen{workspace :: !(Workspace i l a), screen :: !sid, screenDetail :: !sd} deriving (Show, Read, Eq) data Workspace i l a = Workspace{tag :: !i, layout :: l, stack :: Maybe (Stack a)} deriving (Show, Read, Eq) data RationalRect = RationalRect Rational Rational Rational Rational deriving (Show, Read, Eq) data Stack a = Stack{focus :: !a, up :: [a], down :: [a]} deriving (Show, Read, Eq) abort :: String -> a abort = \ _x7 -> case (_x7) of (x) -> ($) error ((++) "xmonad: StackSet: " x) new :: (Integral s) => l -> [i] -> [sd] -> StackSet i l a s sd new = \ _x8 _x9 _x10 -> case (_x8, _x9, _x10) of (l, wids, m) | (&&) (not (null wids)) ((&&) ((<=) (length m) (length wids)) (not (null m))) -> StackSet cur visi unseen M.empty where (,) seen unseen = ($) (L.splitAt (length m)) (map (\ i -> Workspace i l Nothing) wids) ((:) cur visi) = (>>=) (zip3 seen (enumFrom 0) m) (\ _x0 -> case _x0 of (,,) i s sd -> return (Screen i s sd) _ -> fail "...") (_, _, _) -> abort "non-positive argument to StackSet.new" view :: (Eq s, Eq i) => i -> StackSet i l a s sd -> StackSet i l a s sd view = \ _x11 _x12 -> case (_x11, _x12) of (i, s) | (==) i (currentTag s) -> s | Just x <- L.find ((.) (\ _x2 -> (==) i _x2) ((.) tag workspace)) (visible s) -> s{current = x, visible = (:) (current s) (L.deleteBy (equating screen) x (visible s))} | Just x <- L.find ((.) (\ _x3 -> (==) i _x3) tag) (hidden s) -> s{current = (current s){workspace = x}, hidden = (:) (workspace (current s)) (L.deleteBy (equating tag) x (hidden s))} | otherwise -> s where equating = \ _x13 -> case (_x13) of (f) -> \ x y -> (==) (f x) (f y) greedyView :: (Eq s, Eq i) => i -> StackSet i l a s sd -> StackSet i l a s sd greedyView = \ _x14 _x15 -> case (_x14, _x15) of (w, ws) | any wTag (hidden ws) -> view w ws | (Just s) <- L.find ((.) wTag workspace) (visible ws) -> ws{current = (current ws){workspace = workspace s}, visible = (:) s{workspace = workspace (current ws)} (L.filter ((.) not ((.) wTag workspace)) (visible ws))} | otherwise -> ws where wTag = (.) (\ _x4 -> (==) w _x4) tag lookupWorkspace :: (Eq s) => s -> StackSet i l a s sd -> Maybe i lookupWorkspace = \ _x16 _x17 -> case (_x16, _x17) of (sc, w) -> listToMaybe ((>>=) ((:) (current w) (visible w)) (\ _x1 -> case _x1 of Screen i s _ -> (>>) (guard ((==) s sc)) (return (tag i)) _ -> fail "...")) with :: b -> (Stack a -> b) -> StackSet i l a s sd -> b with = \ _x18 _x19 -> case (_x18, _x19) of (dflt, f) -> (.) (maybe dflt f) ((.) stack ((.) workspace current)) modify :: Maybe (Stack a) -> (Stack a -> Maybe (Stack a)) -> StackSet i l a s sd -> StackSet i l a s sd modify = \ _x20 _x21 _x22 -> case (_x20, _x21, _x22) of (d, f, s) -> s{current = (current s){workspace = (workspace (current s)){stack = with d f s}}} modify' :: (Stack a -> Stack a) -> StackSet i l a s sd -> StackSet i l a s sd modify' = \ _x23 -> case (_x23) of (f) -> modify Nothing ((.) Just f) peek :: StackSet i l a s sd -> Maybe a peek = with Nothing ((.) return focus) integrate :: Stack a -> [a] integrate = \ _x24 -> case (_x24) of ((Stack x l r)) -> (++) (reverse l) ((:) x r) integrate' :: Maybe (Stack a) -> [a] integrate' = maybe [] integrate differentiate :: [a] -> Maybe (Stack a) differentiate = \ _x25 -> case (_x25) of ([]) -> Nothing (((:) x xs)) -> ($) Just (Stack x [] xs) filter :: (a -> Bool) -> Stack a -> Maybe (Stack a) filter = \ _x26 _x27 -> case (_x26, _x27) of (p, (Stack f ls rs)) -> case L.filter p ((:) f rs) of (:) f' rs' -> ($) Just (Stack f' (L.filter p ls) rs') [] -> case L.filter p ls of (:) f' ls' -> ($) Just (Stack f' ls' []) [] -> Nothing index :: StackSet i l a s sd -> [a] index = with [] integrate focusUp, focusDown, swapUp, swapDown :: StackSet i l a s sd -> StackSet i l a s sd focusUp = modify' focusUp' focusDown = modify' focusDown' swapUp = modify' swapUp' swapDown = modify' ((.) reverseStack ((.) swapUp' reverseStack)) focusUp', focusDown' :: Stack a -> Stack a focusUp' = \ _x28 -> case (_x28) of ((Stack t ((:) l ls) rs)) -> Stack l ls ((:) t rs) ((Stack t [] rs)) -> Stack x xs [] where ((:) x xs) = reverse ((:) t rs) focusDown' = (.) reverseStack ((.) focusUp' reverseStack) swapUp' :: Stack a -> Stack a swapUp' = \ _x29 -> case (_x29) of ((Stack t ((:) l ls) rs)) -> Stack t ls ((:) l rs) ((Stack t [] rs)) -> Stack t (reverse rs) [] reverseStack :: Stack a -> Stack a reverseStack = \ _x30 -> case (_x30) of ((Stack t ls rs)) -> Stack t rs ls focusWindow :: (Eq s, Eq a, Eq i) => a -> StackSet i l a s sd -> StackSet i l a s sd focusWindow = \ _x31 _x32 -> case (_x31, _x32) of (w, s) | (==) (Just w) (peek s) -> s | otherwise -> ($) (fromMaybe s) ((>>=) (findTag w s) (\ n -> ($) return (until ((.) (\ _x5 -> (==) (Just w) _x5) peek) focusUp (view n s)))) screens :: StackSet i l a s sd -> [Screen i l a s sd] screens = \ _x33 -> case (_x33) of (s) -> (:) (current s) (visible s) workspaces :: StackSet i l a s sd -> [Workspace i l a] workspaces = \ _x34 -> case (_x34) of (s) -> (:) (workspace (current s)) ((++) (map workspace (visible s)) (hidden s)) allWindows :: (Eq a) => StackSet i l a s sd -> [a] allWindows = (.) L.nub ((.) (concatMap ((.) integrate' stack)) workspaces) currentTag :: StackSet i l a s sd -> i currentTag = (.) tag ((.) workspace current) tagMember :: (Eq i) => i -> StackSet i l a s sd -> Bool tagMember = \ _x35 -> case (_x35) of (t) -> (.) (elem t) ((.) (map tag) workspaces) renameTag :: (Eq i) => i -> i -> StackSet i l a s sd -> StackSet i l a s sd renameTag = \ _x36 _x37 -> case (_x36, _x37) of (o, n) -> mapWorkspace rename where rename = \ _x38 -> case (_x38) of (w) -> case (==) (tag w) o of True -> w{tag = n} False -> w ensureTags :: (Eq i) => l -> [i] -> StackSet i l a s sd -> StackSet i l a s sd ensureTags = \ _x39 _x40 _x41 -> case (_x39, _x40, _x41) of (l, allt, st) -> et allt ((\\) (map tag (workspaces st)) allt) st where et = \ _x42 _x43 _x44 -> case (_x42, _x43, _x44) of ([], _, s) -> s (((:) i is), rn, s) | tagMember i s -> et is rn s (((:) i is), [], s) -> et is [] (s{hidden = (:) (Workspace i l Nothing) (hidden s)}) (((:) i is), ((:) r rs), s) -> ($) (et is rs) (renameTag r i s) mapWorkspace :: (Workspace i l a -> Workspace i l a) -> StackSet i l a s sd -> StackSet i l a s sd mapWorkspace = \ _x45 _x46 -> case (_x45, _x46) of (f, s) -> s{current = updScr (current s), visible = map updScr (visible s), hidden = map f (hidden s)} where updScr = \ _x47 -> case (_x47) of (scr) -> scr{workspace = f (workspace scr)} mapLayout :: (l -> l') -> StackSet i l a s sd -> StackSet i l' a s sd mapLayout = \ _x48 _x49 -> case (_x48, _x49) of (f, (StackSet v vs hs m)) -> StackSet (fScreen v) (map fScreen vs) (map fWorkspace hs) m where fScreen = \ _x50 -> case (_x50) of ((Screen ws s sd)) -> Screen (fWorkspace ws) s sd fWorkspace = \ _x51 -> case (_x51) of ((Workspace t l s)) -> Workspace t (f l) s member :: (Eq a) => a -> StackSet i l a s sd -> Bool member = \ _x52 _x53 -> case (_x52, _x53) of (a, s) -> isJust (findTag a s) findTag :: (Eq a) => a -> StackSet i l a s sd -> Maybe i findTag = \ _x54 _x55 -> case (_x54, _x55) of (a, s) -> listToMaybe ((>>=) (workspaces s) (\ w -> (>>) (guard (has a (stack w))) (return (tag w)))) where has = \ _x56 _x57 -> case (_x56, _x57) of (_, Nothing) -> False (x, (Just (Stack t l r))) -> elem x ((:) t ((++) l r)) insertUp :: (Eq a) => a -> StackSet i l a s sd -> StackSet i l a s sd insertUp = \ _x58 _x59 -> case (_x58, _x59) of (a, s) -> case member a s of True -> s False -> insert where insert = modify (($) Just (Stack a [] [])) (\ (Stack t l r) -> ($) Just (Stack a l ((:) t r))) s delete :: (Ord a, Eq s) => a -> StackSet i l a s sd -> StackSet i l a s sd delete = \ _x60 -> case (_x60) of (w) -> (.) (sink w) (delete' w) delete' :: (Eq a, Eq s) => a -> StackSet i l a s sd -> StackSet i l a s sd delete' = \ _x61 _x62 -> case (_x61, _x62) of (w, s) -> s{current = removeFromScreen (current s), visible = map removeFromScreen (visible s), hidden = map removeFromWorkspace (hidden s)} where removeFromWorkspace = \ _x63 -> case (_x63) of (ws) -> ws{stack = (>>=) (stack ws) (filter (\ _x6 -> (/=) _x6 w))} removeFromScreen = \ _x64 -> case (_x64) of (scr) -> scr{workspace = removeFromWorkspace (workspace scr)} float :: (Ord a) => a -> RationalRect -> StackSet i l a s sd -> StackSet i l a s sd float = \ _x65 _x66 _x67 -> case (_x65, _x66, _x67) of (w, r, s) -> s{floating = M.insert w r (floating s)} sink :: (Ord a) => a -> StackSet i l a s sd -> StackSet i l a s sd sink = \ _x68 _x69 -> case (_x68, _x69) of (w, s) -> s{floating = M.delete w (floating s)} swapMaster :: StackSet i l a s sd -> StackSet i l a s sd swapMaster = ($) modify' (\ c -> case c of Stack _ [] _ -> c Stack t ls rs -> Stack t [] ((++) xs ((:) x rs)) where ((:) x xs) = reverse ls) shiftMaster :: StackSet i l a s sd -> StackSet i l a s sd shiftMaster = ($) modify' (\ c -> case c of Stack _ [] _ -> c Stack t ls rs -> Stack t [] ((++) (reverse ls) rs)) focusMaster :: StackSet i l a s sd -> StackSet i l a s sd focusMaster = ($) modify' (\ c -> case c of Stack _ [] _ -> c Stack t ls rs -> Stack x [] ((++) xs ((:) t rs)) where ((:) x xs) = reverse ls) shift :: (Ord a, Eq s, Eq i) => i -> StackSet i l a s sd -> StackSet i l a s sd shift = \ _x70 _x71 -> case (_x70, _x71) of (n, s) -> maybe s (\ w -> shiftWin n w s) (peek s) shiftWin :: (Ord a, Eq a, Eq s, Eq i) => i -> a -> StackSet i l a s sd -> StackSet i l a s sd shiftWin = \ _x72 _x73 _x74 -> case (_x72, _x73, _x74) of (n, w, s) -> case findTag w s of Just from | (&&) (tagMember n s) ((/=) n from) -> go from s _ -> s where go = \ _x75 -> case (_x75) of (from) -> (.) (onWorkspace n (insertUp w)) (onWorkspace from (delete' w)) onWorkspace :: (Eq i, Eq s) => i -> (StackSet i l a s sd -> StackSet i l a s sd) -> (StackSet i l a s sd -> StackSet i l a s sd) onWorkspace = \ _x76 _x77 _x78 -> case (_x76, _x77, _x78) of (n, f, s) -> ($) ((.) (view (currentTag s)) ((.) f (view n))) s
shayan-najd/Haskell-Desugar-Generic
Examples/XMonad/SS_bitter.hs
bsd-3-clause
15,634
2
24
6,768
6,601
3,606
2,995
394
4
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.HP.ImageTransform -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/HP/image_transform.txt HP_image_transform> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.HP.ImageTransform ( -- * Enums gl_AVERAGE_HP, gl_CUBIC_HP, gl_IMAGE_CUBIC_WEIGHT_HP, gl_IMAGE_MAG_FILTER_HP, gl_IMAGE_MIN_FILTER_HP, gl_IMAGE_ROTATE_ANGLE_HP, gl_IMAGE_ROTATE_ORIGIN_X_HP, gl_IMAGE_ROTATE_ORIGIN_Y_HP, gl_IMAGE_SCALE_X_HP, gl_IMAGE_SCALE_Y_HP, gl_IMAGE_TRANSFORM_2D_HP, gl_IMAGE_TRANSLATE_X_HP, gl_IMAGE_TRANSLATE_Y_HP, gl_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP, gl_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP, -- * Functions glGetImageTransformParameterfvHP, glGetImageTransformParameterivHP, glImageTransformParameterfHP, glImageTransformParameterfvHP, glImageTransformParameteriHP, glImageTransformParameterivHP ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/HP/ImageTransform.hs
bsd-3-clause
1,315
0
4
145
106
78
28
24
0
import Control.Lens import Data.IntMap (fromList) import Hmlk.DataSet ds :: DataSet ds = DataSet {_rows = fromList . zip [1..] $ [[Numeric 0, Numeric 0, Nominal "red", Numeric 0], [Numeric 1, Numeric 1, Nominal "red", Numeric 3], [Numeric 1, Numeric (-2), Nominal "blue", Numeric 4], [Numeric 1, Numeric 0, Nominal "red", Numeric 0], [Numeric 0, Numeric 2, Nominal "red", Numeric 3], [Numeric 16, Numeric 15, Nominal "blue", Numeric 4], [Numeric 15, Numeric 15, Nominal "blue", Numeric 4], [Numeric 0, Numeric 25, Nominal "red", Numeric 0], [Numeric 1, Numeric 23, Nominal "red", Numeric 3] ], _names' = ["x", "y", "color", "value"]} sampleRow = Row {_attributes = [Numeric 10, Nominal "blue", Numeric 4], _names = ["x", "color", "decision"]} ex00 = sampleRow ^. attr "x" -- pokaz wartosc X ex01 = (ds ^. rows) !! 0 -- wez zerowy rzad ex10 = (ds ^. rows) !! 0 ^. numeric "x" -- wez zerowy rzad i pokaz "x" ex11 = sampleRow & numeric "x" .~ 100 -- dodaj 100 do X ex2 = (ds ^. rows) !! 0 & numeric "x" +~ 100 -- wez zerowy rzad i dodaj 100 do wartosci atrybutu "x" ex3 = ds ^.. rows . traversed . attr "x" -- pokaz wszystkie wartosci atrybutu "x" ex4 = ds & rows . traverse . numeric "x" +~ 1 -- dodaj do wszystkich atrybutow "x" wszysktich obiekotw 1 ex5 = ds & rows . traverse . numeric "x" %~ (\x -> if x > 1 then 2 * x else 0) -- tak jak wyzej, ale zamiast dodawania arbitralna funkcja (\x -> ...) ex6 = ds ^.. rows . traverse . filtered (\x -> x ^. nominal "color" == "red") -- wez tylko te wiersze ktore maja "color" = red ex6b = ds & rows .~ fr where fr = ds ^.. rows . traverse . filtered (\x -> x ^. nominal "color" == "red") -- jak wyżej, tylko jako DataSet ex7 = ds & rows . traverse . filtered (\x -> x ^. nominal "color" == "red") . numeric "x" +~ 10 -- dodaj 10 do atrybutu "x" wierszy ktore maja "color" = red
rednum/hmlk
examples/dataset.hs
bsd-3-clause
2,000
0
13
529
705
379
326
-1
-1
{-# LANGUAGE TemplateHaskell #-} module BoolExpr.QuickCheck.OBDD ( runTests , prop_evalTreeEquivalency ) where import Test.QuickCheck (Property, property, quickCheckAll) import qualified BoolExpr.BoolExpr as BE import qualified BoolExpr.OBDD as OBDD import BoolExpr.QuickCheck.BoolExpr (BoolExprWithEnv (..)) -- -- Properties: -- Evaluating OBDD trees generated from boolean expressions must return the -- same result as evaluating that expression directly. prop_evalTreeEquivalency :: BoolExprWithEnv -> Property prop_evalTreeEquivalency (BEwE (expr, env)) = property $ OBDD.eval (OBDD.mkTree expr) env == BE.eval expr env -- Run all quickcheck properties. return [] runTests :: IO Bool runTests = $quickCheckAll
robrene/robdd-with-template-hs
test/BoolExpr/QuickCheck/OBDD.hs
bsd-3-clause
726
0
10
99
149
88
61
14
1
module Main where import qualified Guide.Main import Prelude (IO) main :: IO () main = Guide.Main.main
aelve/hslibs
src/site/Main.hs
bsd-3-clause
120
0
6
33
36
22
14
5
1
{-# LANGUAGE BangPatterns, CPP #-} -- | A CSV parser. The parser defined here is RFC 4180 compliant, with -- the following extensions: -- -- * Empty lines are ignored. -- -- * Non-escaped fields may contain any characters except -- double-quotes, commas, carriage returns, and newlines. -- -- * Escaped fields may contain any characters (but double-quotes -- need to be escaped). -- -- The functions in this module can be used to implement e.g. a -- resumable parser that is fed input incrementally. module Data.Csv.Parser ( DecodeOptions(..) , defaultDecodeOptions , csv , csvWithHeader , header , record , name , field ) where import Blaze.ByteString.Builder (fromByteString, toByteString) import Blaze.ByteString.Builder.Char.Utf8 (fromChar) import Control.Applicative (Alternative, (*>), (<$>), (<*), (<|>), optional, pure) import Data.Attoparsec.Char8 (char, endOfInput, endOfLine) import qualified Data.Attoparsec as A import qualified Data.Attoparsec.Lazy as AL import Data.Attoparsec.Types (Parser) import qualified Data.Attoparsec.Zepto as Z import qualified Data.ByteString as S import qualified Data.ByteString.Unsafe as S import qualified Data.HashMap.Strict as HM import Data.Monoid (mappend, mempty) import qualified Data.Vector as V import Data.Word (Word8) import Data.Csv.Types import Data.Csv.Util ((<$!>)) -- | Options that controls how data is decoded. These options can be -- used to e.g. decode tab-separated data instead of comma-separated -- data. -- -- To avoid having your program stop compiling when new fields are -- added to 'DecodeOptions', create option records by overriding -- values in 'defaultDecodeOptions'. Example: -- -- > myOptions = defaultDecodeOptions { -- > decDelimiter = fromIntegral (ord '\t') -- > } data DecodeOptions = DecodeOptions { -- | Field delimiter. decDelimiter :: {-# UNPACK #-} !Word8 } deriving (Eq, Show) -- | Decoding options for parsing CSV files. defaultDecodeOptions :: DecodeOptions defaultDecodeOptions = DecodeOptions { decDelimiter = 44 -- comma } -- | Parse a CSV file that does not include a header. csv :: DecodeOptions -> AL.Parser Csv csv !opts = do vals <- record (decDelimiter opts) `sepBy1'` endOfLine _ <- optional endOfLine endOfInput let nonEmpty = removeBlankLines vals return $! V.fromList nonEmpty {-# INLINE csv #-} -- | @sepBy1' p sep@ applies /one/ or more occurrences of @p@, -- separated by @sep@. Returns a list of the values returned by @p@. -- The value returned by @p@ is forced to WHNF. -- -- > commaSep p = p `sepBy1'` (symbol ",") sepBy1' :: (Alternative f, Monad f) => f a -> f s -> f [a] sepBy1' p s = go where go = do !a <- p as <- (s *> go) <|> pure [] return (a : as) #if __GLASGOW_HASKELL__ >= 700 {-# SPECIALIZE sepBy1' :: Parser S.ByteString a -> Parser S.ByteString s -> Parser S.ByteString [a] #-} #endif -- | Parse a CSV file that includes a header. csvWithHeader :: DecodeOptions -> AL.Parser (Header, V.Vector NamedRecord) csvWithHeader !opts = do !hdr <- header (decDelimiter opts) vals <- map (toNamedRecord hdr) . removeBlankLines <$> (record (decDelimiter opts)) `sepBy1'` endOfLine _ <- optional endOfLine endOfInput let !v = V.fromList vals return (hdr, v) toNamedRecord :: Header -> Record -> NamedRecord toNamedRecord hdr v = HM.fromList . V.toList $ V.zip hdr v -- | Parse a header, including the terminating line separator. header :: Word8 -- ^ Field delimiter -> AL.Parser Header header !delim = V.fromList <$!> name delim `sepBy1'` (A.word8 delim) <* endOfLine -- | Parse a header name. Header names have the same format as regular -- 'field's. name :: Word8 -> AL.Parser Name name !delim = field delim removeBlankLines :: [Record] -> [Record] removeBlankLines = filter (not . blankLine) where blankLine v = V.length v == 1 && (S.null (V.head v)) -- | Parse a record, not including the terminating line separator. The -- terminating line separate is not included as the last record in a -- CSV file is allowed to not have a terminating line separator. You -- most likely want to use the 'endOfLine' parser in combination with -- this parser. record :: Word8 -- ^ Field delimiter -> AL.Parser Record record !delim = do fs <- field delim `sepBy1'` (A.word8 delim) return $! V.fromList fs {-# INLINE record #-} -- | Parse a field. The field may be in either the escaped or -- non-escaped format. The return value is unescaped. field :: Word8 -> AL.Parser Field field !delim = do mb <- A.peekWord8 -- We purposely don't use <|> as we want to commit to the first -- choice if we see a double quote. case mb of Just b | b == doubleQuote -> escapedField _ -> unescapedField delim {-# INLINE field #-} escapedField :: AL.Parser S.ByteString escapedField = do _ <- dquote -- The scan state is 'True' if the previous character was a double -- quote. We need to drop a trailing double quote left by scan. s <- S.init <$> (A.scan False $ \s c -> if c == doubleQuote then Just (not s) else if s then Nothing else Just False) if doubleQuote `S.elem` s then case Z.parse unescape s of Right r -> return r Left err -> fail err else return s unescapedField :: Word8 -> AL.Parser S.ByteString unescapedField !delim = A.takeWhile (\ c -> c /= doubleQuote && c /= newline && c /= delim && c /= cr) dquote :: AL.Parser Char dquote = char '"' unescape :: Z.Parser S.ByteString unescape = toByteString <$!> go mempty where go acc = do h <- Z.takeWhile (/= doubleQuote) let rest = do start <- Z.take 2 if (S.unsafeHead start == doubleQuote && S.unsafeIndex start 1 == doubleQuote) then go (acc `mappend` fromByteString h `mappend` fromChar '"') else fail "invalid CSV escape sequence" done <- Z.atEnd if done then return (acc `mappend` fromByteString h) else rest doubleQuote, newline, cr :: Word8 doubleQuote = 34 newline = 10 cr = 13
edtsech/cassava
Data/Csv/Parser.hs
bsd-3-clause
6,473
0
20
1,691
1,387
759
628
116
5
{-- | Plugin submodule specialised in operating on the AcidState database. --} module Cardano.Wallet.Server.Plugins.AcidState ( createAndArchiveCheckpoints ) where import Universum import Control.Concurrent (threadDelay) import Data.Acid (AcidState, createArchive, createCheckpoint) import qualified Data.ByteString.Lazy as B import Data.List (isInfixOf) import Data.Time (defaultTimeLocale, formatTime, getCurrentTime, iso8601DateFormat) import Data.Time.Units (Minute, toMicroseconds) import System.Directory (getModificationTime, listDirectory, removeFile) import System.FilePath ((</>)) import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip import Pos.Util.Wlog (logError, logInfo) import Cardano.Wallet.Kernel (DatabaseMode (..), DatabaseOptions (..)) import qualified Cardano.Wallet.Kernel.Mode as Kernel -- | Creates a new acid-state @checkpoint@ every 'Minute' minutes, also -- deleting old ones expect for the most recent one. createAndArchiveCheckpoints :: AcidState db -> Minute -> DatabaseMode -- ^ Path for the acid-state database. -> Kernel.WalletMode () createAndArchiveCheckpoints dbRef delay dbMode = case dbMode of UseInMemory -> pure () UseFilePath dbPaths -> forever (go (dbPathAcidState dbPaths)) where go :: FilePath -> Kernel.WalletMode () go dbPath = do logInfo "createAndArchiveCheckpoints is starting..." res <- try $ do liftIO (createCheckpoint dbRef >> createArchive dbRef) pruneAndCompress 3 dbPath case res of Left (err :: SomeException) -> logError (show err) Right () -> return () -- Wait for the next compaction cycle. liftIO . threadDelay . fromInteger $ toMicroseconds delay -- | Prunes old acid-state archives, keeping only the most @n@ recent of them. -- After the clean-up it tar and gzip compressed them. pruneAndCompress :: Int -- ^ How many to keep. -> FilePath -- ^ The path to the database folder -> Kernel.WalletMode () pruneAndCompress n dbPath = liftIO $ do let archiveDir = dbPath </> "Archive" fullRelPath = (archiveDir </>) archives <- listDirectory archiveDir newestFirst <- map fst . reverse . sortWith snd <$> sequence [(f,) <$> getModificationTime (fullRelPath f) | f <- archives] -- Partition the files into @toPrune@ and @toCompress@ (the @n@ newest). -- Filter from the first subset any previously-created tarball. let (toCompress, toPrune) = first (filter (not . isTarball)) . splitAt n $ newestFirst -- Prune the old archives (including tarballs, if necessary). mapM_ (removeFile . fullRelPath) toPrune logInfo ("pruneAndCompress pruned " <> show (length toPrune) <> " old archives.") now <- getCurrentTime let tarName = "archive_" <> formatTime defaultTimeLocale (iso8601DateFormat (Just "%H_%M_%S")) now <> ".tar.gz" -- Compress and archive (no pun intended) the rest. -- As per documentation, 'Tar.pack' wants @toCompress@ to be relative paths -- to @archiveDir@. B.writeFile (archiveDir </> tarName) . GZip.compress . Tar.write =<< Tar.pack archiveDir toCompress logInfo ("pruneAndCompress compressed " <> show (length toCompress) <> " archives.") -- Remove the archived files. mapM_ (removeFile . fullRelPath) toCompress where isTarball :: FilePath -> Bool isTarball fp = ".tar.gz" `isInfixOf` fp
input-output-hk/pos-haskell-prototype
wallet/src/Cardano/Wallet/Server/Plugins/AcidState.hs
mit
3,844
0
17
1,076
770
411
359
-1
-1
module Parakeet.Linguistics.Romaji ( chList , toKana , otherForms , dakutenize , unDakutenize , isSyllabicN , normSyllabicN , sokuonize , unSokuonize , longVowelize , longVowelizeWithMacron , longVowelize1WithMacron , unLongVowelize , factor ) where import Data.Functor.Compose (Compose (..)) import Data.List (sort, group, isPrefixOf) import Data.List.Extra (concatMapLast) import qualified Data.Map as M import Data.Maybe (maybeToList, fromJust, fromMaybe, isNothing) import Data.Tuple (swap) import Control.Arrow (second) import Control.Monad (mzero, guard) import Control.Monad.Choice (Choice, fromList, toList, foremost) import Parakeet.Types.Lexeme (Lexeme (..), toRLV, toRS, toRB, Hiragana, Katakana, Romaji, RType, Bundle, Single) import Parakeet.Linguistics.Misc (isMacron, toMacron, fromMacron, isVowel) import Parakeet.Linguistics.RawData (hRaw, kRaw) chList :: [Romaji Single] chList = nub' $ concatMap (toList . otherForms . wrap . snd) $ hRaw ++ kRaw where nub' = map head . group . sort buildMap :: [(String, String)] -> M.Map String (Choice String) buildMap raw = M.fromList $ map toChoice (raw ++ raw') where swapped = map swap raw toChoice (k, r) = (r, return k) raw' = concatMap f (tail otherFormList) where f (r, rs) = foldl g [] rs where kana = fromJust $ lookup r swapped g xs cur = case lookup cur swapped of Nothing -> (kana, cur) : xs _ -> xs hMap, kMap :: M.Map String (Choice String) hMap = buildMap hRaw kMap = buildMap kRaw toKana :: Romaji Single -> (Choice Hiragana, Choice Katakana) toKana r = (lookup hMap, lookup kMap) where lookup m = case M.lookup (unwrap r) m of Just ch -> wrap <$> ch Nothing -> mzero otherFormList :: [(String, [String])] otherFormList = [ ("n", ["n", "m", "nn", "n-", "n'"]) -- syllabic n , ("ha", ["ha", "wa"]) -- particles mutation , ("he", ["he", "e"]) , ("wo", ["wo", "o"]) , ("di", ["di", "ji", "dji"]) -- ambiguous ji & zu , ("du", ["du", "zu", "dzu"]) ] otherFormMap :: M.Map String (Choice String) otherFormMap = M.fromList $ map (second fromList) otherFormList otherForms :: Romaji Single -> Choice (Romaji Single) otherForms r = go `lfap` r where go r = fromMaybe (return r) (M.lookup r otherFormMap) buildDakutenPairs :: [(Int, Int)] -> [(String, String)] buildDakutenPairs = extend . concatMap convert where nline = replicate 14 5 ++ [1] ++ replicate 11 3 :: [Int] prefix = zipWith (+) (0 : prefix) nline convert (l1, l2) = map (\x -> (snd (hRaw !! (offset1 + x)), snd (hRaw !! (offset2 + x)))) [0 .. count - 1] where count = nline !! l1 offset1 = prefix !! (l1 - 1) offset2 = prefix !! (l2 - 1) extend pairs = pairs ++ concatMap f pairs where f (s1, s2) = do x <- unwrap <$> toList (otherForms (wrap s1)) guard $ isNothing (lookup x pairs) return (x, s2) dakutenMap, unDakutenMap :: M.Map String String dakutenMap = M.fromList $ buildDakutenPairs (dakutenPair1 ++ map swap dakutenPair3) unDakutenMap = M.fromList $ buildDakutenPairs $ map swap (dakutenPair1 ++ dakutenPair2) dakutenPair1, dakutenPair2, dakutenPair3 :: [(Int, Int)] dakutenPair1 = [(1, 2), (3, 4), (5, 6), (8, 9), (15, 16), (17, 18), (21, 22)] -- (normal, dakuten) dakutenPair2 = [(8, 10), (21, 23)] -- (normal, han-dakuten) dakutenPair3 = [(9, 10), (22, 23)] -- (dakuten, han-dakuten) dakutenize :: Romaji Single -> Romaji Single dakutenize r = lookup `lap` r where lookup x = fromMaybe x (M.lookup x dakutenMap) unDakutenize :: Romaji Single -> Romaji Single unDakutenize r = lookup `lap` r where lookup x = fromMaybe x (M.lookup x unDakutenMap) isSyllabicN :: Romaji Single -> Bool isSyllabicN n = n `elem` toList (otherForms (wrap "n")) -- | normalize syllabic n (take the first alphabet). normSyllabicN :: Romaji Single -> Romaji Single normSyllabicN r | isSyllabicN r = (return . head) `lap` r | otherwise = r -- | sokuonize a factorized romaji, chi -> tchi, ka -> kka, a -> a. sokuonize :: [Romaji Single] -> Choice [Romaji Single] sokuonize [] = return [] sokuonize r = getCompose (lfap (Compose . sokuonizeInternal) (head r)) >>= \h -> return (h ++ tail r) unSokuonize :: Romaji Bundle -> Choice (Maybe (Romaji Single), Romaji Bundle) unSokuonize r | length r' <= 1 = return (Nothing, r) | "tch" `isPrefixOf` r' = return (Just $ wrap [firstOne], tail `lap` r) | sokuonizable firstOne && head exceptFirst == firstOne = return (Just $ wrap [firstOne], tail `lap` r) | otherwise = return (Nothing, r) where r' = unwrap r firstOne = head r' exceptFirst = tail r' sokuonizable :: Char -> Bool -- | https://en.wikipedia.org/wiki/Sokuon sokuonizable c = c `notElem` "aiueonmrwy" -- ++ "gzdbh" sokuonizeInternal :: String -> Choice [String] sokuonizeInternal [] = return [] sokuonizeInternal s@('c':'h':_) = fromList [["t", s], ["c", s]] sokuonizeInternal s@(c:_) | sokuonizable c = return [[c], s] | otherwise = return [s] -- | long vowelize a factorized romaji. longVowelize :: [Romaji Single] -> [Romaji Single] longVowelize [] = [] longVowelize r = concatMapLast (longVowelizeInternal False `lfap`) r longVowelizeWithMacron :: RType a => [Romaji a] -> [Romaji Bundle] longVowelizeWithMacron [] = [] longVowelizeWithMacron r = toRB <$> concatMapLast (longVowelizeInternal True `lfap`) r longVowelize1WithMacron :: RType a => Romaji a -> Romaji Bundle longVowelize1WithMacron r = toRB $ head (longVowelizeInternal True `lfap` r) unLongVowelize :: Romaji Bundle -> Choice (Maybe (Romaji Single), Romaji Bundle) unLongVowelize r | null r' = return (Nothing, r) | isMacron lastOne = lastTo >>= \to -> return (Just (wrap [to]), wrap $ exceptLast ++ [lastDesugar]) | otherwise = return (Nothing, r) where r' = unwrap r lastOne = last r' exceptLast = init r' lastDesugar = fromMacron lastOne lastTo | lastDesugar == 'o' = fromList ['u', 'o'] -- ambiguous 'ō' -> ou | otherwise = return lastDesugar longVowelizeInternal :: Bool -> String -> [String] longVowelizeInternal _ [] = [] longVowelizeInternal m s | not (isVowel ls) = [s] | m = [concatMapLast (return . foremost . toMacron) s] | otherwise = [s, [ls]] where ls = last s -- | factorize a bundle romaji with possible sokuon & macron into different single parts, e.g. tchī -> [t, chi, i]. factor :: Romaji Bundle -> Choice [Romaji Single] factor r = do (sokuonPart, next) <- unSokuonize r (longVowelPart, temp) <- unLongVowelize next let normalized | null longVowelPart = toRS temp | otherwise = toRLV $ toRS temp return $ maybeToList sokuonPart ++ [normalized] ++ maybeToList longVowelPart
foreverbell/parakeet
src/Parakeet/Linguistics/Romaji.hs
mit
7,069
0
17
1,714
2,624
1,417
1,207
142
2
{-# LANGUAGE TemplateHaskell #-} module Lamdu.Data.Meta ( DefinitionState(..) , SpecialArgs(..), _Verbose, _Operator , PresentationMode ) where import qualified Control.Lens as Lens import qualified Lamdu.Calc.Type as T import Lamdu.Prelude data DefinitionState = DeletedDefinition | LiveDefinition deriving stock (Eq, Ord, Show, Generic) deriving anyclass Binary data SpecialArgs a = Verbose | Operator a a deriving stock (Eq, Ord, Show, Generic, Functor, Foldable, Traversable) deriving anyclass Binary type PresentationMode = SpecialArgs T.Tag Lens.makePrisms ''SpecialArgs
lamdu/lamdu
src/Lamdu/Data/Meta.hs
gpl-3.0
633
0
6
127
165
98
67
-1
-1
import Database.HDBC import Database.HDBC.PostgreSQL import System.IO import Control.Exception import Data.ByteString.Base64 import qualified Crypto.Hash.SHA3 as SHA3 main :: IO () main = do putStrLn "Enter database host" dbHost <- getLine putStrLn "Enter database port" dbPort <- getLine putStrLn "Enter database user" dbUser <- getLine putStrLn "Enter database name" dbName <- getLine putStrLn "Enter database password" dbPasswd <- getPasswd let dbString = "host=" ++ dbHost ++ " port=" ++ dbPort ++ " user=" ++ dbUser ++ " dbname=" ++ dbName ++ " password=" ++ dbPasswd conn <- connectPostgreSQL dbString stmt1 <- prepare conn "select * from avatar" _ <- execute stmt1 [] rows <- fetchAllRowsAL stmt1 tups <- return $ map (\entry -> case entry of [("id", theId), ("ident", _), ("data", SqlByteString theData), ("hash", _)] -> [SqlByteString $ encode $ SHA3.hash 32 theData, theId] _ -> error "malformed entry" ) rows stmt2 <- prepare conn "update avatar set hash = ? where id = ?" executeMany stmt2 tups commit conn disconnect conn putStrLn "Migration successfull!!" getPasswd :: IO String getPasswd = do putStr "Password: " hFlush stdout pass <- withEcho False getLine putChar '\n' return pass withEcho :: Bool -> IO a -> IO a withEcho echo action = do old <- hGetEcho stdin bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action
Mic92/yammat
Migration/0.0.0-0.0.1/Migration.hs
agpl-3.0
1,433
0
18
305
463
219
244
46
2
module Instance where data TrafficLight = Red | Yellow | Green class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y) instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False
Atsky/haskell-idea-plugin
data/haskellParserTests/Instance.hs
apache-2.0
314
0
9
103
150
77
73
12
0
----------------------------------------------------------------------------- -- -- | Parsing the top of a Haskell source file to get its module name, -- imports and options. -- -- (c) Simon Marlow 2005 -- (c) Lemmih 2006 -- ----------------------------------------------------------------------------- {-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module HeaderInfo ( getImports , mkPrelImports -- used by the renamer too , getOptionsFromFile, getOptions , optionsErrorMsgs, checkProcessArgsResult ) where #include "HsVersions.h" import RdrName import HscTypes import Parser ( parseHeader ) import Lexer import FastString import HsSyn import Module import PrelNames import StringBuffer import SrcLoc import DynFlags import ErrUtils import Util import Outputable import Pretty () import Maybes import Bag ( emptyBag, listToBag, unitBag ) import MonadUtils import Exception import Control.Monad import System.IO import System.IO.Unsafe import Data.List ------------------------------------------------------------------------------ -- | Parse the imports of a source file. -- -- Throws a 'SourceError' if parsing fails. getImports :: DynFlags -> StringBuffer -- ^ Parse this. -> FilePath -- ^ Filename the buffer came from. Used for -- reporting parse error locations. -> FilePath -- ^ The original source filename (used for locations -- in the function result) -> IO ([Located (ImportDecl RdrName)], [Located (ImportDecl RdrName)], Located ModuleName) -- ^ The source imports, normal imports, and the module name. getImports dflags buf filename source_filename = do let loc = mkRealSrcLoc (mkFastString filename) 1 1 case unP parseHeader (mkPState dflags buf loc) of PFailed span err -> parseError span err POk pst rdr_module -> do let _ms@(_warns, errs) = getMessages pst -- don't log warnings: they'll be reported when we parse the file -- for real. See #2500. ms = (emptyBag, errs) -- logWarnings warns if errorsFound dflags ms then throwIO $ mkSrcErr errs else case rdr_module of L _ (HsModule mb_mod _ imps _ _ _) -> let main_loc = srcLocSpan (mkSrcLoc (mkFastString source_filename) 1 1) mod = mb_mod `orElse` L main_loc mAIN_NAME (src_idecls, ord_idecls) = partition (ideclSource.unLoc) imps -- GHC.Prim doesn't exist physically, so don't go looking for it. ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc . ideclName . unLoc) ord_idecls implicit_prelude = xopt Opt_ImplicitPrelude dflags implicit_imports = mkPrelImports (unLoc mod) main_loc implicit_prelude imps in return (src_idecls, implicit_imports ++ ordinary_imps, mod) mkPrelImports :: ModuleName -> SrcSpan -- Attribute the "import Prelude" to this location -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName] -- Consruct the implicit declaration "import Prelude" (or not) -- -- NB: opt_NoImplicitPrelude is slightly different to import Prelude (); -- because the former doesn't even look at Prelude.hi for instance -- declarations, whereas the latter does. mkPrelImports this_mod loc implicit_prelude import_decls | this_mod == pRELUDE_NAME || explicit_prelude_import || not implicit_prelude = [] | otherwise = [preludeImportDecl] where explicit_prelude_import = notNull [ () | L _ (ImportDecl { ideclName = mod , ideclPkgQual = Nothing }) <- import_decls , unLoc mod == pRELUDE_NAME ] preludeImportDecl :: LImportDecl RdrName preludeImportDecl = L loc $ ImportDecl { ideclName = L loc pRELUDE_NAME, ideclPkgQual = Nothing, ideclSource = False, ideclSafe = False, -- Not a safe import ideclQualified = False, ideclImplicit = True, -- Implicit! ideclAs = Nothing, ideclHiding = Nothing } parseError :: SrcSpan -> Message -> IO a parseError span err = throwOneError $ mkPlainErrMsg span err -------------------------------------------------------------- -- Get options -------------------------------------------------------------- -- | Parse OPTIONS and LANGUAGE pragmas of the source file. -- -- Throws a 'SourceError' if flag parsing fails (including unsupported flags.) getOptionsFromFile :: DynFlags -> FilePath -- ^ Input file -> IO [Located String] -- ^ Parsed options, if any. getOptionsFromFile dflags filename = Exception.bracket (openBinaryFile filename ReadMode) (hClose) (\handle -> do opts <- fmap getOptions' $ lazyGetToks dflags' filename handle seqList opts $ return opts) where -- We don't need to get haddock doc tokens when we're just -- getting the options from pragmas, and lazily lexing them -- correctly is a little tricky: If there is "\n" or "\n-" -- left at the end of a buffer then the haddock doc may -- continue past the end of the buffer, despite the fact that -- we already have an apparently-complete token. -- We therefore just turn Opt_Haddock off when doing the lazy -- lex. dflags' = dopt_unset dflags Opt_Haddock blockSize :: Int -- blockSize = 17 -- for testing :-) blockSize = 1024 lazyGetToks :: DynFlags -> FilePath -> Handle -> IO [Located Token] lazyGetToks dflags filename handle = do buf <- hGetStringBufferBlock handle blockSize unsafeInterleaveIO $ lazyLexBuf handle (pragState dflags buf loc) False where loc = mkRealSrcLoc (mkFastString filename) 1 1 lazyLexBuf :: Handle -> PState -> Bool -> IO [Located Token] lazyLexBuf handle state eof = do case unP (lexer return) state of POk state' t -> do -- pprTrace "lazyLexBuf" (text (show (buffer state'))) (return ()) if atEnd (buffer state') && not eof -- if this token reached the end of the buffer, and we haven't -- necessarily read up to the end of the file, then the token might -- be truncated, so read some more of the file and lex it again. then getMore handle state else case t of L _ ITeof -> return [t] _other -> do rest <- lazyLexBuf handle state' eof return (t : rest) _ | not eof -> getMore handle state | otherwise -> return [L (RealSrcSpan (last_loc state)) ITeof] -- parser assumes an ITeof sentinel at the end getMore :: Handle -> PState -> IO [Located Token] getMore handle state = do -- pprTrace "getMore" (text (show (buffer state))) (return ()) nextbuf <- hGetStringBufferBlock handle blockSize if (len nextbuf == 0) then lazyLexBuf handle state True else do newbuf <- appendStringBuffers (buffer state) nextbuf unsafeInterleaveIO $ lazyLexBuf handle state{buffer=newbuf} False getToks :: DynFlags -> FilePath -> StringBuffer -> [Located Token] getToks dflags filename buf = lexAll (pragState dflags buf loc) where loc = mkRealSrcLoc (mkFastString filename) 1 1 lexAll state = case unP (lexer return) state of POk _ t@(L _ ITeof) -> [t] POk state' t -> t : lexAll state' _ -> [L (RealSrcSpan (last_loc state)) ITeof] -- | Parse OPTIONS and LANGUAGE pragmas of the source file. -- -- Throws a 'SourceError' if flag parsing fails (including unsupported flags.) getOptions :: DynFlags -> StringBuffer -- ^ Input Buffer -> FilePath -- ^ Source filename. Used for location info. -> [Located String] -- ^ Parsed options. getOptions dflags buf filename = getOptions' (getToks dflags filename buf) -- The token parser is written manually because Happy can't -- return a partial result when it encounters a lexer error. -- We want to extract options before the buffer is passed through -- CPP, so we can't use the same trick as 'getImports'. getOptions' :: [Located Token] -- Input buffer -> [Located String] -- Options. getOptions' toks = parseToks toks where getToken (L _loc tok) = tok getLoc (L loc _tok) = loc parseToks (open:close:xs) | IToptions_prag str <- getToken open , ITclose_prag <- getToken close = map (L (getLoc open)) (words str) ++ parseToks xs parseToks (open:close:xs) | ITinclude_prag str <- getToken open , ITclose_prag <- getToken close = map (L (getLoc open)) ["-#include",removeSpaces str] ++ parseToks xs parseToks (open:close:xs) | ITdocOptions str <- getToken open , ITclose_prag <- getToken close = map (L (getLoc open)) ["-haddock-opts", removeSpaces str] ++ parseToks xs parseToks (open:xs) | ITdocOptionsOld str <- getToken open = map (L (getLoc open)) ["-haddock-opts", removeSpaces str] ++ parseToks xs parseToks (open:xs) | ITlanguage_prag <- getToken open = parseLanguage xs parseToks _ = [] parseLanguage (L loc (ITconid fs):rest) = checkExtension (L loc fs) : case rest of (L _loc ITcomma):more -> parseLanguage more (L _loc ITclose_prag):more -> parseToks more (L loc _):_ -> languagePragParseError loc [] -> panic "getOptions'.parseLanguage(1) went past eof token" parseLanguage (tok:_) = languagePragParseError (getLoc tok) parseLanguage [] = panic "getOptions'.parseLanguage(2) went past eof token" ----------------------------------------------------------------------------- -- | Complain about non-dynamic flags in OPTIONS pragmas. -- -- Throws a 'SourceError' if the input list is non-empty claiming that the -- input flags are unknown. checkProcessArgsResult :: MonadIO m => [Located String] -> m () checkProcessArgsResult flags = when (notNull flags) $ liftIO $ throwIO $ mkSrcErr $ listToBag $ map mkMsg flags where mkMsg (L loc flag) = mkPlainErrMsg loc $ (text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+> text flag) ----------------------------------------------------------------------------- checkExtension :: Located FastString -> Located String checkExtension (L l ext) -- Checks if a given extension is valid, and if so returns -- its corresponding flag. Otherwise it throws an exception. = let ext' = unpackFS ext in if ext' `elem` supportedLanguagesAndExtensions then L l ("-X"++ext') else unsupportedExtnError l ext' languagePragParseError :: SrcSpan -> a languagePragParseError loc = throw $ mkSrcErr $ unitBag $ (mkPlainErrMsg loc $ vcat [ text "Cannot parse LANGUAGE pragma" , text "Expecting comma-separated list of language options," , text "each starting with a capital letter" , nest 2 (text "E.g. {-# LANGUAGE RecordPuns, Generics #-}") ]) unsupportedExtnError :: SrcSpan -> String -> a unsupportedExtnError loc unsup = throw $ mkSrcErr $ unitBag $ mkPlainErrMsg loc $ text "Unsupported extension: " <> text unsup $$ if null suggestions then empty else text "Perhaps you meant" <+> quotedListWithOr (map text suggestions) where suggestions = fuzzyMatch unsup supportedLanguagesAndExtensions optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages optionsErrorMsgs unhandled_flags flags_lines _filename = (emptyBag, listToBag (map mkMsg unhandled_flags_lines)) where unhandled_flags_lines = [ L l f | f <- unhandled_flags, L l f' <- flags_lines, f == f' ] mkMsg (L flagSpan flag) = ErrUtils.mkPlainErrMsg flagSpan $ text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+> text flag
mcmaniac/ghc
compiler/main/HeaderInfo.hs
bsd-3-clause
12,803
34
26
3,657
2,652
1,361
1,291
-1
-1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Network/Wai/Handler/Warp/Internal.hs" #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} module Network.Wai.Handler.Warp.Internal ( -- * Settings Settings (..) , ProxyProtocol(..) -- * Low level run functions , runSettingsConnection , runSettingsConnectionMaker , runSettingsConnectionMakerSecure , Transport (..) -- * Connection , Connection (..) , socketConnection -- ** Receive , Recv , RecvBuf , makePlainReceiveN -- ** Buffer , Buffer , BufSize , bufferSize , allocateBuffer , freeBuffer , copy -- ** Sendfile , FileId (..) , SendFile , sendFile , readSendFile -- * Version , warpVersion -- * Data types , InternalInfo (..) , HeaderValue , IndexedHeader , requestMaxIndex -- * Time out manager -- | -- -- In order to provide slowloris protection, Warp provides timeout handlers. We -- follow these rules: -- -- * A timeout is created when a connection is opened. -- -- * When all request headers are read, the timeout is tickled. -- -- * Every time at least the slowloris size settings number of bytes of the request -- body are read, the timeout is tickled. -- -- * The timeout is paused while executing user code. This will apply to both -- the application itself, and a ResponseSource response. The timeout is -- resumed as soon as we return from user code. -- -- * Every time data is successfully sent to the client, the timeout is tickled. , module Network.Wai.Handler.Warp.Timeout -- * File descriptor cache , module Network.Wai.Handler.Warp.FdCache -- * File information cache , module Network.Wai.Handler.Warp.FileInfoCache -- * Date , module Network.Wai.Handler.Warp.Date -- * Request and response , Source , recvRequest , sendResponse ) where import Network.Wai.Handler.Warp.Buffer import Network.Wai.Handler.Warp.Date import Network.Wai.Handler.Warp.FdCache import Network.Wai.Handler.Warp.FileInfoCache import Network.Wai.Handler.Warp.Header import Network.Wai.Handler.Warp.Recv import Network.Wai.Handler.Warp.Request import Network.Wai.Handler.Warp.Response import Network.Wai.Handler.Warp.Run import Network.Wai.Handler.Warp.SendFile import Network.Wai.Handler.Warp.Settings import Network.Wai.Handler.Warp.Timeout import Network.Wai.Handler.Warp.Types
phischu/fragnix
tests/packages/scotty/Network.Wai.Handler.Warp.Internal.hs
bsd-3-clause
2,406
0
5
489
295
223
72
50
0
import qualified System.Random as Rnd import System.Exit (exitFailure) import System.Environment (getArgs) import qualified Data.Array.IArray as Arr -- Casting Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- I'd like to use the below implementation, but as of 2017/01/08, -- the System.Random implementation is _horrible_ with splitting -- their generator. The results are clearly not random, at least -- for the short runs I use here. So, I'll have to do something -- uglier. -- -- casting proc = -- sequence $ take 6 $ repeat (Rnd.newStdGen >>= \g -> return (proc g)) -- -- addChar ch amt = (toEnum $ amt + fromEnum ch) :: Char -- -- coin gen = addChar '6' (sum $ take 3 $ Rnd.randomRs (0,1) gen) -- static gen = addChar '7' $ fst (Rnd.randomR (0,1) gen) -- stalk gen = let roll = (fst (Rnd.randomR (0,15) gen)) :: Int -- in if roll == 0 then '6' else -- if roll <= 5 then '7' else -- if roll <= 12 then '8' else '9' -- import Data.Bits(testBit) casting :: (Int -> Char) -> IO String casting proc = do nums <- sequence $ take 6 $ repeat (Rnd.getStdRandom $ Rnd.randomR (0,255)) return $ map proc nums bit num which | testBit num which = 1 | otherwise = 0 addChar ch amt = (toEnum $ amt + fromEnum ch) :: Char coin num = addChar '6' (sum $ map (bit num) [0,1,2]) static num = addChar '7' (bit num 0) stalk num = let roll = num `mod` 16 in if roll == 0 then '6' else if roll <= 5 then '7' else if roll <= 12 then '8' else '9' -- Hexagram Display Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ decode = foldr dec (0,0,[]) where dec '6' (n1,n2,ls) = (n1*2 , n2*2+1, " -- -- --> -------":ls) dec '7' (n1,n2,ls) = (n1*2+1 , n2*2+1, " ------- -------":ls) dec '8' (n1,n2,ls) = (n1*2 , n2*2 , " -- -- -- --":ls) dec '9' (n1,n2,ls) = (n1*2+1 , n2*2 , " ------- --> -- --":ls) hexStrs casting = lines ++ ("":names) where (hn1,hn2,strs) = decode casting changes = hn1 /= hn2 lines = reverse . (if changes then id else (map (take 9))) $ strs names = (if changes then id else (take 1)) [hexNames Arr.! hn1, " - Changing To ->", hexNames Arr.! hn2] -- Argument Parsing / Main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ getCasting "-coins" = casting coin getCasting "-static" = casting static getCasting "-stalks" = casting stalk getCasting c = if (length c == 6) && (all (\ch -> ch >= '6' && ch <= '9') c) then return c else (mapM_ putStrLn usage) >> exitFailure where usage = [ "Usage: casthex (-coins|-stalks|-static|<casting>)", " -coins 3-coins method", " -stalks yarrow stalks method", " -static a random hexagram", " <casting> 6 digits from the set {6,7,8,9]" ] main = do args <- getArgs c <- getCasting (head $ args ++ ["-coins"]) putStrLn $ "Casting: " ++ c putStrLn "" mapM_ putStrLn (hexStrs c) hexNames :: Arr.Array Int String hexNames = Arr.listArray (0,63) [ "02. K'un -- Earth", "24. Fu -- Return", "07. Shih -- The Army", "19. Lin -- Overseeing", "15. Ch'ien -- Humility", "36. Ming I -- Concealment of Illumination", "46. Sheng -- Rising", "11. T'ai -- Tranquility", "16. Yu -- Enthusiasm", "51. Chen -- Thunder", "40. Hsieh -- Liberation", "54. Kuei Mei -- Making a Young Girl Marry", "62. Hsiao Kuo -- Predominance of the Small", "55. Feng -- Richness", "32. Heng -- Constancy", "34. Ta Chuang -- Great Power", "08. Pi -- Accord", "03. Chun -- Difficulty", "29. K'an -- Mastering Pitfalls", "60. Chieh -- Discipline", "39. Chien -- Halting", "63. Chi Chi -- Settled", "48. Ching -- The Well", "05. Hsu -- Waiting", "45. Ts'ui -- Gathering", "17. Sui -- Following", "47. K'un -- Exhaustion", "58. Tui -- Joy", "31. Hsien -- Sensitivity", "49. Ko -- Revolution", "28. Ta Kuo -- Excess of the Great", "43. Kuai -- Parting", "23. Po -- Stripping Away", "27. I -- Lower Jaw (Nourishment)", "04. Meng -- Darkness", "41. Sun -- Reduction", "52. Ken -- Mountain", "22. Pi -- Adornment", "18. Ku -- Degeneration", "26. Ta Ch'u -- Nurturance of the Great", "35. Chin -- Advance", "21. Shih Ho -- Biting Through", "64. Wei Chi -- Unsettled", "38. K'uei -- Disharmony", "56. Lu -- Travel", "30. Li -- Fire", "50. Ting -- The Cauldron", "14. Ta Yu -- Great Possession", "20. Kuan -- Observation", "42. I -- Increase", "59. Huan -- Dispersal", "61. Chung Fu -- Faithfulness in the Center", "53. Chien -- Gradual Progress", "37. Chia Jen -- People in the Home", "57. Sun -- Wind", "09. Hsiao Ch'u -- Nurturance by the Small", "12. Pi -- Obstruction", "25. Wu Wang -- Fidelity (No Error)", "06. Sung -- Contention", "10. Lu -- Treading", "33. Tun -- Withdrawal", "13. T'ung Je^n -- Sameness with People", "44. Kou -- Meeting", "01. Chi'en -- Heaven" ]
waywardcode/small_programs
casthex/haskell/casthex.hs
gpl-2.0
5,259
0
14
1,542
1,074
610
464
114
4
{-# 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.CloudWatch.DescribeAlarmHistory -- 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. -- | Retrieves history for the specified alarm. Filter alarms by date range or -- item type. If an alarm name is not specified, Amazon CloudWatch returns -- histories for all of the owner's alarms. -- -- <http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarmHistory.html> module Network.AWS.CloudWatch.DescribeAlarmHistory ( -- * Request DescribeAlarmHistory -- ** Request constructor , describeAlarmHistory -- ** Request lenses , dahAlarmName , dahEndDate , dahHistoryItemType , dahMaxRecords , dahNextToken , dahStartDate -- * Response , DescribeAlarmHistoryResponse -- ** Response constructor , describeAlarmHistoryResponse -- ** Response lenses , dahrAlarmHistoryItems , dahrNextToken ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.CloudWatch.Types import qualified GHC.Exts data DescribeAlarmHistory = DescribeAlarmHistory { _dahAlarmName :: Maybe Text , _dahEndDate :: Maybe ISO8601 , _dahHistoryItemType :: Maybe HistoryItemType , _dahMaxRecords :: Maybe Nat , _dahNextToken :: Maybe Text , _dahStartDate :: Maybe ISO8601 } deriving (Eq, Read, Show) -- | 'DescribeAlarmHistory' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dahAlarmName' @::@ 'Maybe' 'Text' -- -- * 'dahEndDate' @::@ 'Maybe' 'UTCTime' -- -- * 'dahHistoryItemType' @::@ 'Maybe' 'HistoryItemType' -- -- * 'dahMaxRecords' @::@ 'Maybe' 'Natural' -- -- * 'dahNextToken' @::@ 'Maybe' 'Text' -- -- * 'dahStartDate' @::@ 'Maybe' 'UTCTime' -- describeAlarmHistory :: DescribeAlarmHistory describeAlarmHistory = DescribeAlarmHistory { _dahAlarmName = Nothing , _dahHistoryItemType = Nothing , _dahStartDate = Nothing , _dahEndDate = Nothing , _dahMaxRecords = Nothing , _dahNextToken = Nothing } -- | The name of the alarm. dahAlarmName :: Lens' DescribeAlarmHistory (Maybe Text) dahAlarmName = lens _dahAlarmName (\s a -> s { _dahAlarmName = a }) -- | The ending date to retrieve alarm history. dahEndDate :: Lens' DescribeAlarmHistory (Maybe UTCTime) dahEndDate = lens _dahEndDate (\s a -> s { _dahEndDate = a }) . mapping _Time -- | The type of alarm histories to retrieve. dahHistoryItemType :: Lens' DescribeAlarmHistory (Maybe HistoryItemType) dahHistoryItemType = lens _dahHistoryItemType (\s a -> s { _dahHistoryItemType = a }) -- | The maximum number of alarm history records to retrieve. dahMaxRecords :: Lens' DescribeAlarmHistory (Maybe Natural) dahMaxRecords = lens _dahMaxRecords (\s a -> s { _dahMaxRecords = a }) . mapping _Nat -- | The token returned by a previous call to indicate that there is more data -- available. dahNextToken :: Lens' DescribeAlarmHistory (Maybe Text) dahNextToken = lens _dahNextToken (\s a -> s { _dahNextToken = a }) -- | The starting date to retrieve alarm history. dahStartDate :: Lens' DescribeAlarmHistory (Maybe UTCTime) dahStartDate = lens _dahStartDate (\s a -> s { _dahStartDate = a }) . mapping _Time data DescribeAlarmHistoryResponse = DescribeAlarmHistoryResponse { _dahrAlarmHistoryItems :: List "member" AlarmHistoryItem , _dahrNextToken :: Maybe Text } deriving (Eq, Read, Show) -- | 'DescribeAlarmHistoryResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dahrAlarmHistoryItems' @::@ ['AlarmHistoryItem'] -- -- * 'dahrNextToken' @::@ 'Maybe' 'Text' -- describeAlarmHistoryResponse :: DescribeAlarmHistoryResponse describeAlarmHistoryResponse = DescribeAlarmHistoryResponse { _dahrAlarmHistoryItems = mempty , _dahrNextToken = Nothing } -- | A list of alarm histories in JSON format. dahrAlarmHistoryItems :: Lens' DescribeAlarmHistoryResponse [AlarmHistoryItem] dahrAlarmHistoryItems = lens _dahrAlarmHistoryItems (\s a -> s { _dahrAlarmHistoryItems = a }) . _List -- | A string that marks the start of the next batch of returned results. dahrNextToken :: Lens' DescribeAlarmHistoryResponse (Maybe Text) dahrNextToken = lens _dahrNextToken (\s a -> s { _dahrNextToken = a }) instance ToPath DescribeAlarmHistory where toPath = const "/" instance ToQuery DescribeAlarmHistory where toQuery DescribeAlarmHistory{..} = mconcat [ "AlarmName" =? _dahAlarmName , "EndDate" =? _dahEndDate , "HistoryItemType" =? _dahHistoryItemType , "MaxRecords" =? _dahMaxRecords , "NextToken" =? _dahNextToken , "StartDate" =? _dahStartDate ] instance ToHeaders DescribeAlarmHistory instance AWSRequest DescribeAlarmHistory where type Sv DescribeAlarmHistory = CloudWatch type Rs DescribeAlarmHistory = DescribeAlarmHistoryResponse request = post "DescribeAlarmHistory" response = xmlResponse instance FromXML DescribeAlarmHistoryResponse where parseXML = withElement "DescribeAlarmHistoryResult" $ \x -> DescribeAlarmHistoryResponse <$> x .@? "AlarmHistoryItems" .!@ mempty <*> x .@? "NextToken" instance AWSPager DescribeAlarmHistory where page rq rs | stop (rs ^. dahrNextToken) = Nothing | otherwise = (\x -> rq & dahNextToken ?~ x) <$> (rs ^. dahrNextToken)
kim/amazonka
amazonka-cloudwatch/gen/Network/AWS/CloudWatch/DescribeAlarmHistory.hs
mpl-2.0
6,398
0
12
1,377
949
555
394
96
1
{- | This is a hets extension to mmt, see http://trac.kwarc.info/MMT/ This extension is/will be used to pattern check the twelf files for hets. hets-mmt-standalone.jar - a standalone package that can be invoked with "java -jar hets-mmt-standalone.jar" command -} module MMT where
nevrenato/HetsAlloy
MMT.hs
gpl-2.0
283
0
2
45
5
4
1
1
0
{-# LANGUAGE RelaxedPolyRec #-} -- needed for inlinesBetween on GHC < 7 {-# LANGUAGE ScopedTypeVariables #-} {- Copyright (C) 2006-2015 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.Markdown Copyright : Copyright (C) 2006-2015 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of markdown-formatted plain text to 'Pandoc' document. -} module Text.Pandoc.Readers.Markdown ( readMarkdown, readMarkdownWithWarnings ) where import Data.List ( transpose, sortBy, findIndex, intersperse, intercalate ) import qualified Data.Map as M import Data.Scientific (coefficient, base10Exponent) import Data.Ord ( comparing ) import Data.Char ( isSpace, isAlphaNum, toLower ) import Data.Maybe import Text.Pandoc.Definition import qualified Data.Text as T import Data.Text (Text) import qualified Data.Yaml as Yaml import Data.Yaml (ParseException(..), YamlException(..), YamlMark(..)) import qualified Data.HashMap.Strict as H import qualified Text.Pandoc.Builder as B import qualified Text.Pandoc.UTF8 as UTF8 import qualified Data.Vector as V import Text.Pandoc.Builder (Inlines, Blocks, trimInlines, (<>)) import Text.Pandoc.Options import Text.Pandoc.Shared import Text.Pandoc.XML (fromEntities) import Text.Pandoc.Parsing hiding (tableWith) import Text.Pandoc.Readers.LaTeX ( rawLaTeXInline, rawLaTeXBlock ) import Text.Pandoc.Readers.HTML ( htmlTag, htmlInBalanced, isInlineTag, isBlockTag, isTextTag, isCommentTag ) import Data.Monoid (mconcat, mempty) import Control.Applicative ((<$>), (<*), (*>), (<$), (<*>)) import Control.Monad import System.FilePath (takeExtension, addExtension) import Text.HTML.TagSoup import Text.HTML.TagSoup.Match (tagOpen) import qualified Data.Set as Set import Text.Printf (printf) import Debug.Trace (trace) import Text.Pandoc.Error type MarkdownParser = Parser [Char] ParserState -- | Read markdown from an input string and return a Pandoc document. readMarkdown :: ReaderOptions -- ^ Reader options -> String -- ^ String to parse (assuming @'\n'@ line endings) -> Either PandocError Pandoc readMarkdown opts s = (readWith parseMarkdown) def{ stateOptions = opts } (s ++ "\n\n") -- | Read markdown from an input string and return a pair of a Pandoc document -- and a list of warnings. readMarkdownWithWarnings :: ReaderOptions -- ^ Reader options -> String -- ^ String to parse (assuming @'\n'@ line endings) -> Either PandocError (Pandoc, [String]) readMarkdownWithWarnings opts s = (readWithWarnings parseMarkdown) def{ stateOptions = opts } (s ++ "\n\n") trimInlinesF :: F Inlines -> F Inlines trimInlinesF = liftM trimInlines -- -- Constants and data structure definitions -- isBulletListMarker :: Char -> Bool isBulletListMarker '*' = True isBulletListMarker '+' = True isBulletListMarker '-' = True isBulletListMarker _ = False isHruleChar :: Char -> Bool isHruleChar '*' = True isHruleChar '-' = True isHruleChar '_' = True isHruleChar _ = False setextHChars :: String setextHChars = "=-" isBlank :: Char -> Bool isBlank ' ' = True isBlank '\t' = True isBlank '\n' = True isBlank _ = False -- -- auxiliary functions -- -- | Succeeds when we're in list context. inList :: MarkdownParser () inList = do ctx <- stateParserContext <$> getState guard (ctx == ListItemState) isNull :: F Inlines -> Bool isNull ils = B.isNull $ runF ils def spnl :: Parser [Char] st () spnl = try $ do skipSpaces optional newline skipSpaces notFollowedBy (char '\n') indentSpaces :: MarkdownParser String indentSpaces = try $ do tabStop <- getOption readerTabStop count tabStop (char ' ') <|> string "\t" <?> "indentation" nonindentSpaces :: MarkdownParser String nonindentSpaces = do tabStop <- getOption readerTabStop sps <- many (char ' ') if length sps < tabStop then return sps else unexpected "indented line" -- returns number of spaces parsed skipNonindentSpaces :: MarkdownParser Int skipNonindentSpaces = do tabStop <- getOption readerTabStop atMostSpaces (tabStop - 1) <* notFollowedBy (char ' ') atMostSpaces :: Int -> MarkdownParser Int atMostSpaces n | n > 0 = (char ' ' >> (+1) <$> atMostSpaces (n-1)) <|> return 0 | otherwise = return 0 litChar :: MarkdownParser Char litChar = escapedChar' <|> characterReference <|> noneOf "\n" <|> try (newline >> notFollowedBy blankline >> return ' ') -- | Parse a sequence of inline elements between square brackets, -- including inlines between balanced pairs of square brackets. inlinesInBalancedBrackets :: MarkdownParser (F Inlines) inlinesInBalancedBrackets = do char '[' (_, raw) <- withRaw $ charsInBalancedBrackets 1 guard $ not $ null raw parseFromString (trimInlinesF . mconcat <$> many inline) (init raw) charsInBalancedBrackets :: Int -> MarkdownParser () charsInBalancedBrackets 0 = return () charsInBalancedBrackets openBrackets = (char '[' >> charsInBalancedBrackets (openBrackets + 1)) <|> (char ']' >> charsInBalancedBrackets (openBrackets - 1)) <|> (( (() <$ code) <|> (() <$ (escapedChar')) <|> (newline >> notFollowedBy blankline) <|> skipMany1 (noneOf "[]`\n\\") <|> (() <$ count 1 (oneOf "`\\")) ) >> charsInBalancedBrackets openBrackets) -- -- document structure -- titleLine :: MarkdownParser (F Inlines) titleLine = try $ do char '%' skipSpaces res <- many $ (notFollowedBy newline >> inline) <|> try (endline >> whitespace) newline return $ trimInlinesF $ mconcat res authorsLine :: MarkdownParser (F [Inlines]) authorsLine = try $ do char '%' skipSpaces authors <- sepEndBy (many (notFollowedBy (satisfy $ \c -> c == ';' || c == '\n') >> inline)) (char ';' <|> try (newline >> notFollowedBy blankline >> spaceChar)) newline return $ sequence $ filter (not . isNull) $ map (trimInlinesF . mconcat) authors dateLine :: MarkdownParser (F Inlines) dateLine = try $ do char '%' skipSpaces trimInlinesF . mconcat <$> manyTill inline newline titleBlock :: MarkdownParser () titleBlock = pandocTitleBlock <|> mmdTitleBlock pandocTitleBlock :: MarkdownParser () pandocTitleBlock = try $ do guardEnabled Ext_pandoc_title_block lookAhead (char '%') title <- option mempty titleLine author <- option (return []) authorsLine date <- option mempty dateLine optional blanklines let meta' = do title' <- title author' <- author date' <- date return $ (if B.isNull title' then id else B.setMeta "title" title') . (if null author' then id else B.setMeta "author" author') . (if B.isNull date' then id else B.setMeta "date" date') $ nullMeta updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' } yamlMetaBlock :: MarkdownParser (F Blocks) yamlMetaBlock = try $ do guardEnabled Ext_yaml_metadata_block pos <- getPosition string "---" blankline notFollowedBy blankline -- if --- is followed by a blank it's an HRULE rawYamlLines <- manyTill anyLine stopLine -- by including --- and ..., we allow yaml blocks with just comments: let rawYaml = unlines ("---" : (rawYamlLines ++ ["..."])) optional blanklines opts <- stateOptions <$> getState meta' <- case Yaml.decodeEither' $ UTF8.fromString rawYaml of Right (Yaml.Object hashmap) -> return $ return $ H.foldrWithKey (\k v m -> if ignorable k then m else case yamlToMeta opts v of Left _ -> m Right v' -> B.setMeta (T.unpack k) v' m) nullMeta hashmap Right Yaml.Null -> return $ return nullMeta Right _ -> do addWarning (Just pos) "YAML header is not an object" return $ return nullMeta Left err' -> do case err' of InvalidYaml (Just YamlParseException{ yamlProblem = problem , yamlContext = _ctxt , yamlProblemMark = Yaml.YamlMark { yamlLine = yline , yamlColumn = ycol }}) -> addWarning (Just $ setSourceLine (setSourceColumn pos (sourceColumn pos + ycol)) (sourceLine pos + 1 + yline)) $ "Could not parse YAML header: " ++ problem _ -> addWarning (Just pos) $ "Could not parse YAML header: " ++ show err' return $ return nullMeta updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' } return mempty -- ignore fields ending with _ ignorable :: Text -> Bool ignorable t = (T.pack "_") `T.isSuffixOf` t toMetaValue :: ReaderOptions -> Text -> Either PandocError MetaValue toMetaValue opts x = toMeta <$> readMarkdown opts' (T.unpack x) where toMeta p = case p of Pandoc _ [Plain xs] -> MetaInlines xs Pandoc _ [Para xs] | endsWithNewline x -> MetaBlocks [Para xs] | otherwise -> MetaInlines xs Pandoc _ bs -> MetaBlocks bs endsWithNewline t = T.pack "\n" `T.isSuffixOf` t opts' = opts{readerExtensions=readerExtensions opts `Set.difference` meta_exts} meta_exts = Set.fromList [ Ext_pandoc_title_block , Ext_mmd_title_block , Ext_yaml_metadata_block ] yamlToMeta :: ReaderOptions -> Yaml.Value -> Either PandocError MetaValue yamlToMeta opts (Yaml.String t) = toMetaValue opts t yamlToMeta _ (Yaml.Number n) -- avoid decimal points for numbers that don't need them: | base10Exponent n >= 0 = return $ MetaString $ show $ coefficient n * (10 ^ base10Exponent n) | otherwise = return $ MetaString $ show n yamlToMeta _ (Yaml.Bool b) = return $ MetaBool b yamlToMeta opts (Yaml.Array xs) = B.toMetaValue <$> mapM (yamlToMeta opts) (V.toList xs) yamlToMeta opts (Yaml.Object o) = MetaMap <$> H.foldrWithKey (\k v m -> if ignorable k then m else (do v' <- yamlToMeta opts v m' <- m return (M.insert (T.unpack k) v' m'))) (return M.empty) o yamlToMeta _ _ = return $ MetaString "" stopLine :: MarkdownParser () stopLine = try $ (string "---" <|> string "...") >> blankline >> return () mmdTitleBlock :: MarkdownParser () mmdTitleBlock = try $ do guardEnabled Ext_mmd_title_block kvPairs <- many1 kvPair blanklines updateState $ \st -> st{ stateMeta' = stateMeta' st <> return (Meta $ M.fromList kvPairs) } kvPair :: MarkdownParser (String, MetaValue) kvPair = try $ do key <- many1Till (alphaNum <|> oneOf "_- ") (char ':') skipMany1 spaceNoNewline val <- manyTill anyChar (try $ newline >> lookAhead (blankline <|> nonspaceChar)) guard $ not . null . trim $ val let key' = concat $ words $ map toLower key let val' = MetaBlocks $ B.toList $ B.plain $ B.text $ trim val return (key',val') where spaceNoNewline = satisfy (\x -> isSpace x && (x/='\n') && (x/='\r')) parseMarkdown :: MarkdownParser Pandoc parseMarkdown = do -- markdown allows raw HTML updateState $ \state -> state { stateOptions = let oldOpts = stateOptions state in oldOpts{ readerParseRaw = True } } optional titleBlock blocks <- parseBlocks st <- getState let meta = runF (stateMeta' st) st let Pandoc _ bs = B.doc $ runF blocks st return $ Pandoc meta bs referenceKey :: MarkdownParser (F Blocks) referenceKey = try $ do pos <- getPosition skipNonindentSpaces (_,raw) <- reference char ':' skipSpaces >> optional newline >> skipSpaces >> notFollowedBy (char '[') let sourceURL = liftM unwords $ many $ try $ do skipMany spaceChar notFollowedBy' referenceTitle notFollowedBy' (() <$ reference) many1 $ notFollowedBy space >> litChar let betweenAngles = try $ char '<' >> manyTill litChar (char '>') src <- try betweenAngles <|> sourceURL tit <- option "" referenceTitle -- currently we just ignore MMD-style link/image attributes _kvs <- option [] $ guardEnabled Ext_link_attributes >> many (try $ spnl >> keyValAttr) blanklines let target = (escapeURI $ trimr src, tit) st <- getState let oldkeys = stateKeys st let key = toKey raw case M.lookup key oldkeys of Just _ -> addWarning (Just pos) $ "Duplicate link reference `" ++ raw ++ "'" Nothing -> return () updateState $ \s -> s { stateKeys = M.insert key target oldkeys } return $ return mempty referenceTitle :: MarkdownParser String referenceTitle = try $ do skipSpaces >> optional newline >> skipSpaces quotedTitle '"' <|> quotedTitle '\'' <|> charsInBalanced '(' ')' litChar -- A link title in quotes quotedTitle :: Char -> MarkdownParser String quotedTitle c = try $ do char c notFollowedBy spaces let pEnder = try $ char c >> notFollowedBy (satisfy isAlphaNum) let regChunk = many1 (noneOf ['\\','\n','&',c]) <|> count 1 litChar let nestedChunk = (\x -> [c] ++ x ++ [c]) <$> quotedTitle c unwords . words . concat <$> manyTill (nestedChunk <|> regChunk) pEnder -- | PHP Markdown Extra style abbreviation key. Currently -- we just skip them, since Pandoc doesn't have an element for -- an abbreviation. abbrevKey :: MarkdownParser (F Blocks) abbrevKey = do guardEnabled Ext_abbreviations try $ do char '*' reference char ':' skipMany (satisfy (/= '\n')) blanklines return $ return mempty noteMarker :: MarkdownParser String noteMarker = string "[^" >> many1Till (satisfy $ not . isBlank) (char ']') rawLine :: MarkdownParser String rawLine = try $ do notFollowedBy blankline notFollowedBy' $ try $ skipNonindentSpaces >> noteMarker optional indentSpaces anyLine rawLines :: MarkdownParser String rawLines = do first <- anyLine rest <- many rawLine return $ unlines (first:rest) noteBlock :: MarkdownParser (F Blocks) noteBlock = try $ do pos <- getPosition skipNonindentSpaces ref <- noteMarker char ':' optional blankline optional indentSpaces first <- rawLines rest <- many $ try $ blanklines >> indentSpaces >> rawLines let raw = unlines (first:rest) ++ "\n" optional blanklines parsed <- parseFromString parseBlocks raw let newnote = (ref, parsed) oldnotes <- stateNotes' <$> getState case lookup ref oldnotes of Just _ -> addWarning (Just pos) $ "Duplicate note reference `" ++ ref ++ "'" Nothing -> return () updateState $ \s -> s { stateNotes' = newnote : oldnotes } return mempty -- -- parsing blocks -- parseBlocks :: MarkdownParser (F Blocks) parseBlocks = mconcat <$> manyTill block eof block :: MarkdownParser (F Blocks) block = do tr <- getOption readerTrace pos <- getPosition res <- choice [ mempty <$ blanklines , codeBlockFenced , yamlMetaBlock , guardEnabled Ext_latex_macros *> (macro >>= return . return) -- note: bulletList needs to be before header because of -- the possibility of empty list items: - , bulletList , header , lhsCodeBlock , divHtml , htmlBlock , table , codeBlockIndented , rawTeXBlock , lineBlock , blockQuote , hrule , orderedList , definitionList , noteBlock , referenceKey , abbrevKey , para , plain ] <?> "block" when tr $ do st <- getState trace (printf "line %d: %s" (sourceLine pos) (take 60 $ show $ B.toList $ runF res st)) (return ()) return res -- -- header blocks -- header :: MarkdownParser (F Blocks) header = setextHeader <|> atxHeader <?> "header" atxHeader :: MarkdownParser (F Blocks) atxHeader = try $ do level <- many1 (char '#') >>= return . length notFollowedBy $ guardEnabled Ext_fancy_lists >> (char '.' <|> char ')') -- this would be a list skipSpaces (text, raw) <- withRaw $ trimInlinesF . mconcat <$> many (notFollowedBy atxClosing >> inline) attr <- atxClosing attr'@(ident,_,_) <- registerHeader attr (runF text defaultParserState) guardDisabled Ext_implicit_header_references <|> registerImplicitHeader raw ident return $ B.headerWith attr' level <$> text atxClosing :: MarkdownParser Attr atxClosing = try $ do attr' <- option nullAttr (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier) skipMany (char '#') skipSpaces attr <- option attr' (guardEnabled Ext_header_attributes >> attributes) blanklines return attr setextHeaderEnd :: MarkdownParser Attr setextHeaderEnd = try $ do attr <- option nullAttr $ (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier) <|> (guardEnabled Ext_header_attributes >> attributes) blanklines return attr mmdHeaderIdentifier :: MarkdownParser Attr mmdHeaderIdentifier = do ident <- stripFirstAndLast . snd <$> reference skipSpaces return (ident,[],[]) setextHeader :: MarkdownParser (F Blocks) setextHeader = try $ do -- This lookahead prevents us from wasting time parsing Inlines -- unless necessary -- it gives a significant performance boost. lookAhead $ anyLine >> many1 (oneOf setextHChars) >> blankline (text, raw) <- withRaw $ trimInlinesF . mconcat <$> many1 (notFollowedBy setextHeaderEnd >> inline) attr <- setextHeaderEnd underlineChar <- oneOf setextHChars many (char underlineChar) blanklines let level = (fromMaybe 0 $ findIndex (== underlineChar) setextHChars) + 1 attr'@(ident,_,_) <- registerHeader attr (runF text defaultParserState) guardDisabled Ext_implicit_header_references <|> registerImplicitHeader raw ident return $ B.headerWith attr' level <$> text registerImplicitHeader :: String -> String -> MarkdownParser () registerImplicitHeader raw ident = do let key = toKey $ "[" ++ raw ++ "]" updateState (\s -> s { stateHeaderKeys = M.insert key ('#':ident,"") (stateHeaderKeys s) }) -- -- hrule block -- hrule :: Parser [Char] st (F Blocks) hrule = try $ do skipSpaces start <- satisfy isHruleChar count 2 (skipSpaces >> char start) skipMany (spaceChar <|> char start) newline optional blanklines return $ return B.horizontalRule -- -- code blocks -- indentedLine :: MarkdownParser String indentedLine = indentSpaces >> anyLine >>= return . (++ "\n") blockDelimiter :: (Char -> Bool) -> Maybe Int -> Parser [Char] st Int blockDelimiter f len = try $ do c <- lookAhead (satisfy f) case len of Just l -> count l (char c) >> many (char c) >> return l Nothing -> count 3 (char c) >> many (char c) >>= return . (+ 3) . length attributes :: MarkdownParser Attr attributes = try $ do char '{' spnl attrs <- many (attribute <* spnl) char '}' return $ foldl (\x f -> f x) nullAttr attrs attribute :: MarkdownParser (Attr -> Attr) attribute = identifierAttr <|> classAttr <|> keyValAttr <|> specialAttr identifier :: MarkdownParser String identifier = do first <- letter rest <- many $ alphaNum <|> oneOf "-_:." return (first:rest) identifierAttr :: MarkdownParser (Attr -> Attr) identifierAttr = try $ do char '#' result <- identifier return $ \(_,cs,kvs) -> (result,cs,kvs) classAttr :: MarkdownParser (Attr -> Attr) classAttr = try $ do char '.' result <- identifier return $ \(id',cs,kvs) -> (id',cs ++ [result],kvs) keyValAttr :: MarkdownParser (Attr -> Attr) keyValAttr = try $ do key <- identifier char '=' val <- enclosed (char '"') (char '"') litChar <|> enclosed (char '\'') (char '\'') litChar <|> many (escapedChar' <|> noneOf " \t\n\r}") return $ \(id',cs,kvs) -> (id',cs,kvs ++ [(key,val)]) specialAttr :: MarkdownParser (Attr -> Attr) specialAttr = do char '-' return $ \(id',cs,kvs) -> (id',cs ++ ["unnumbered"],kvs) codeBlockFenced :: MarkdownParser (F Blocks) codeBlockFenced = try $ do c <- try (guardEnabled Ext_fenced_code_blocks >> lookAhead (char '~')) <|> (guardEnabled Ext_backtick_code_blocks >> lookAhead (char '`')) size <- blockDelimiter (== c) Nothing skipMany spaceChar attr <- option ([],[],[]) $ try (guardEnabled Ext_fenced_code_attributes >> attributes) <|> ((\x -> ("",[toLanguageId x],[])) <$> many1 nonspaceChar) blankline contents <- manyTill anyLine (blockDelimiter (== c) (Just size)) blanklines return $ return $ B.codeBlockWith attr $ intercalate "\n" contents -- correctly handle github language identifiers toLanguageId :: String -> String toLanguageId = map toLower . go where go "c++" = "cpp" go "objective-c" = "objectivec" go x = x codeBlockIndented :: MarkdownParser (F Blocks) codeBlockIndented = do contents <- many1 (indentedLine <|> try (do b <- blanklines l <- indentedLine return $ b ++ l)) optional blanklines classes <- getOption readerIndentedCodeClasses return $ return $ B.codeBlockWith ("", classes, []) $ stripTrailingNewlines $ concat contents lhsCodeBlock :: MarkdownParser (F Blocks) lhsCodeBlock = do guardEnabled Ext_literate_haskell (return . B.codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$> (lhsCodeBlockBird <|> lhsCodeBlockLaTeX)) <|> (return . B.codeBlockWith ("",["sourceCode","haskell"],[]) <$> lhsCodeBlockInverseBird) lhsCodeBlockLaTeX :: MarkdownParser String lhsCodeBlockLaTeX = try $ do string "\\begin{code}" manyTill spaceChar newline contents <- many1Till anyChar (try $ string "\\end{code}") blanklines return $ stripTrailingNewlines contents lhsCodeBlockBird :: MarkdownParser String lhsCodeBlockBird = lhsCodeBlockBirdWith '>' lhsCodeBlockInverseBird :: MarkdownParser String lhsCodeBlockInverseBird = lhsCodeBlockBirdWith '<' lhsCodeBlockBirdWith :: Char -> MarkdownParser String lhsCodeBlockBirdWith c = try $ do pos <- getPosition when (sourceColumn pos /= 1) $ fail "Not in first column" lns <- many1 $ birdTrackLine c -- if (as is normal) there is always a space after >, drop it let lns' = if all (\ln -> null ln || take 1 ln == " ") lns then map (drop 1) lns else lns blanklines return $ intercalate "\n" lns' birdTrackLine :: Char -> Parser [Char] st String birdTrackLine c = try $ do char c -- allow html tags on left margin: when (c == '<') $ notFollowedBy letter anyLine -- -- block quotes -- emailBlockQuoteStart :: MarkdownParser Char emailBlockQuoteStart = try $ skipNonindentSpaces >> char '>' <* optional (char ' ') emailBlockQuote :: MarkdownParser [String] emailBlockQuote = try $ do emailBlockQuoteStart let emailLine = many $ nonEndline <|> try (endline >> notFollowedBy emailBlockQuoteStart >> return '\n') let emailSep = try (newline >> emailBlockQuoteStart) first <- emailLine rest <- many $ try $ emailSep >> emailLine let raw = first:rest newline <|> (eof >> return '\n') optional blanklines return raw blockQuote :: MarkdownParser (F Blocks) blockQuote = do raw <- emailBlockQuote -- parse the extracted block, which may contain various block elements: contents <- parseFromString parseBlocks $ (intercalate "\n" raw) ++ "\n\n" return $ B.blockQuote <$> contents -- -- list blocks -- bulletListStart :: MarkdownParser () bulletListStart = try $ do optional newline -- if preceded by a Plain block in a list context startpos <- sourceColumn <$> getPosition skipNonindentSpaces notFollowedBy' (() <$ hrule) -- because hrules start out just like lists satisfy isBulletListMarker endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) () <$ atMostSpaces (tabStop - (endpos - startpos)) anyOrderedListStart :: MarkdownParser (Int, ListNumberStyle, ListNumberDelim) anyOrderedListStart = try $ do optional newline -- if preceded by a Plain block in a list context startpos <- sourceColumn <$> getPosition skipNonindentSpaces notFollowedBy $ string "p." >> spaceChar >> digit -- page number res <- do guardDisabled Ext_fancy_lists start <- many1 digit >>= safeRead char '.' return (start, DefaultStyle, DefaultDelim) <|> do (num, style, delim) <- anyOrderedListMarker -- if it could be an abbreviated first name, -- insist on more than one space when (delim == Period && (style == UpperAlpha || (style == UpperRoman && num `elem` [1, 5, 10, 50, 100, 500, 1000]))) $ () <$ spaceChar return (num, style, delim) endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) atMostSpaces (tabStop - (endpos - startpos)) return res listStart :: MarkdownParser () listStart = bulletListStart <|> (anyOrderedListStart >> return ()) listLine :: MarkdownParser String listLine = try $ do notFollowedBy' (do indentSpaces many spaceChar listStart) notFollowedByHtmlCloser optional (() <$ indentSpaces) listLineCommon listLineCommon :: MarkdownParser String listLineCommon = concat <$> manyTill ( many1 (satisfy $ \c -> c /= '\n' && c /= '<') <|> liftM snd (htmlTag isCommentTag) <|> count 1 anyChar ) newline -- parse raw text for one list item, excluding start marker and continuations rawListItem :: MarkdownParser a -> MarkdownParser String rawListItem start = try $ do start first <- listLineCommon rest <- many (notFollowedBy listStart >> notFollowedBy blankline >> listLine) blanks <- many blankline return $ unlines (first:rest) ++ blanks -- continuation of a list item - indented and separated by blankline -- or (in compact lists) endline. -- note: nested lists are parsed as continuations listContinuation :: MarkdownParser String listContinuation = try $ do lookAhead indentSpaces result <- many1 listContinuationLine blanks <- many blankline return $ concat result ++ blanks notFollowedByHtmlCloser :: MarkdownParser () notFollowedByHtmlCloser = do inHtmlBlock <- stateInHtmlBlock <$> getState case inHtmlBlock of Just t -> notFollowedBy' $ htmlTag (~== TagClose t) Nothing -> return () listContinuationLine :: MarkdownParser String listContinuationLine = try $ do notFollowedBy blankline notFollowedBy' listStart notFollowedByHtmlCloser optional indentSpaces result <- anyLine return $ result ++ "\n" listItem :: MarkdownParser a -> MarkdownParser (F Blocks) listItem start = try $ do first <- rawListItem start continuations <- many listContinuation -- parsing with ListItemState forces markers at beginning of lines to -- count as list item markers, even if not separated by blank space. -- see definition of "endline" state <- getState let oldContext = stateParserContext state setState $ state {stateParserContext = ListItemState} -- parse the extracted block, which may contain various block elements: let raw = concat (first:continuations) contents <- parseFromString parseBlocks raw updateState (\st -> st {stateParserContext = oldContext}) return contents orderedList :: MarkdownParser (F Blocks) orderedList = try $ do (start, style, delim) <- lookAhead anyOrderedListStart unless (style `elem` [DefaultStyle, Decimal, Example] && delim `elem` [DefaultDelim, Period]) $ guardEnabled Ext_fancy_lists when (style == Example) $ guardEnabled Ext_example_lists items <- fmap sequence $ many1 $ listItem ( try $ do optional newline -- if preceded by Plain block in a list startpos <- sourceColumn <$> getPosition skipNonindentSpaces res <- orderedListMarker style delim endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) atMostSpaces (tabStop - (endpos - startpos)) return res ) start' <- option 1 $ guardEnabled Ext_startnum >> return start return $ B.orderedListWith (start', style, delim) <$> fmap compactify' items bulletList :: MarkdownParser (F Blocks) bulletList = do items <- fmap sequence $ many1 $ listItem bulletListStart return $ B.bulletList <$> fmap compactify' items -- definition lists defListMarker :: MarkdownParser () defListMarker = do sps <- nonindentSpaces char ':' <|> char '~' tabStop <- getOption readerTabStop let remaining = tabStop - (length sps + 1) if remaining > 0 then try (count remaining (char ' ')) <|> string "\t" <|> many1 spaceChar else mzero return () definitionListItem :: Bool -> MarkdownParser (F (Inlines, [Blocks])) definitionListItem compact = try $ do rawLine' <- anyLine raw <- many1 $ defRawBlock compact term <- parseFromString (trimInlinesF . mconcat <$> many inline) rawLine' contents <- mapM (parseFromString parseBlocks . (++"\n")) raw optional blanklines return $ liftM2 (,) term (sequence contents) defRawBlock :: Bool -> MarkdownParser String defRawBlock compact = try $ do hasBlank <- option False $ blankline >> return True defListMarker firstline <- anyLine let dline = try ( do notFollowedBy blankline notFollowedByHtmlCloser if compact -- laziness not compatible with compact then () <$ indentSpaces else (() <$ indentSpaces) <|> notFollowedBy defListMarker anyLine ) rawlines <- many dline cont <- liftM concat $ many $ try $ do trailing <- option "" blanklines ln <- indentSpaces >> notFollowedBy blankline >> anyLine lns <- many dline return $ trailing ++ unlines (ln:lns) return $ trimr (firstline ++ "\n" ++ unlines rawlines ++ cont) ++ if hasBlank || not (null cont) then "\n\n" else "" definitionList :: MarkdownParser (F Blocks) definitionList = try $ do lookAhead (anyLine >> optional (blankline >> notFollowedBy (table >> return ())) >> -- don't capture table caption as def list! defListMarker) compactDefinitionList <|> normalDefinitionList compactDefinitionList :: MarkdownParser (F Blocks) compactDefinitionList = do guardEnabled Ext_compact_definition_lists items <- fmap sequence $ many1 $ definitionListItem True return $ B.definitionList <$> fmap compactify'DL items normalDefinitionList :: MarkdownParser (F Blocks) normalDefinitionList = do guardEnabled Ext_definition_lists items <- fmap sequence $ many1 $ definitionListItem False return $ B.definitionList <$> items -- -- paragraph block -- para :: MarkdownParser (F Blocks) para = try $ do exts <- getOption readerExtensions result <- trimInlinesF . mconcat <$> many1 inline option (B.plain <$> result) $ try $ do newline (blanklines >> return mempty) <|> (guardDisabled Ext_blank_before_blockquote >> () <$ lookAhead blockQuote) <|> (guardEnabled Ext_backtick_code_blocks >> () <$ lookAhead codeBlockFenced) <|> (guardDisabled Ext_blank_before_header >> () <$ lookAhead header) <|> (guardEnabled Ext_lists_without_preceding_blankline >> -- Avoid creating a paragraph in a nested list. notFollowedBy' inList >> () <$ lookAhead listStart) <|> do guardEnabled Ext_native_divs inHtmlBlock <- stateInHtmlBlock <$> getState case inHtmlBlock of Just "div" -> () <$ lookAhead (htmlTag (~== TagClose "div")) _ -> mzero return $ do result' <- result case B.toList result' of [Image alt (src,tit)] | Ext_implicit_figures `Set.member` exts -> -- the fig: at beginning of title indicates a figure return $ B.para $ B.singleton $ Image alt (src,'f':'i':'g':':':tit) _ -> return $ B.para result' plain :: MarkdownParser (F Blocks) plain = fmap B.plain . trimInlinesF . mconcat <$> many1 inline -- -- raw html -- htmlElement :: MarkdownParser String htmlElement = rawVerbatimBlock <|> strictHtmlBlock <|> liftM snd (htmlTag isBlockTag) htmlBlock :: MarkdownParser (F Blocks) htmlBlock = do guardEnabled Ext_raw_html try (do (TagOpen t attrs) <- lookAhead $ fst <$> htmlTag isBlockTag (guard (t `elem` ["pre","style","script"]) >> (return . B.rawBlock "html") <$> rawVerbatimBlock) <|> (do guardEnabled Ext_markdown_attribute oldMarkdownAttribute <- stateMarkdownAttribute <$> getState markdownAttribute <- case lookup "markdown" attrs of Just "0" -> False <$ updateState (\st -> st{ stateMarkdownAttribute = False }) Just _ -> True <$ updateState (\st -> st{ stateMarkdownAttribute = True }) Nothing -> return oldMarkdownAttribute res <- if markdownAttribute then rawHtmlBlocks else htmlBlock' updateState $ \st -> st{ stateMarkdownAttribute = oldMarkdownAttribute } return res) <|> (guardEnabled Ext_markdown_in_html_blocks >> rawHtmlBlocks)) <|> htmlBlock' htmlBlock' :: MarkdownParser (F Blocks) htmlBlock' = try $ do first <- htmlElement skipMany spaceChar optional blanklines return $ return $ B.rawBlock "html" first strictHtmlBlock :: MarkdownParser String strictHtmlBlock = htmlInBalanced (not . isInlineTag) rawVerbatimBlock :: MarkdownParser String rawVerbatimBlock = try $ do (TagOpen tag _, open) <- htmlTag (tagOpen (flip elem ["pre", "style", "script"]) (const True)) contents <- manyTill anyChar (htmlTag (~== TagClose tag)) return $ open ++ contents ++ renderTags' [TagClose tag] rawTeXBlock :: MarkdownParser (F Blocks) rawTeXBlock = do guardEnabled Ext_raw_tex result <- (B.rawBlock "latex" . concat <$> rawLaTeXBlock `sepEndBy1` blankline) <|> (B.rawBlock "context" . concat <$> rawConTeXtEnvironment `sepEndBy1` blankline) spaces return $ return result rawHtmlBlocks :: MarkdownParser (F Blocks) rawHtmlBlocks = do (TagOpen tagtype _, raw) <- htmlTag isBlockTag -- try to find closing tag -- we set stateInHtmlBlock so that closing tags that can be either block or -- inline will not be parsed as inline tags oldInHtmlBlock <- stateInHtmlBlock <$> getState updateState $ \st -> st{ stateInHtmlBlock = Just tagtype } let closer = htmlTag (\x -> x ~== TagClose tagtype) contents <- mconcat <$> many (notFollowedBy' closer >> block) result <- (closer >>= \(_, rawcloser) -> return ( return (B.rawBlock "html" $ stripMarkdownAttribute raw) <> contents <> return (B.rawBlock "html" rawcloser))) <|> return (return (B.rawBlock "html" raw) <> contents) updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock } return result -- remove markdown="1" attribute stripMarkdownAttribute :: String -> String stripMarkdownAttribute s = renderTags' $ map filterAttrib $ parseTags s where filterAttrib (TagOpen t as) = TagOpen t [(k,v) | (k,v) <- as, k /= "markdown"] filterAttrib x = x -- -- line block -- lineBlock :: MarkdownParser (F Blocks) lineBlock = try $ do guardEnabled Ext_line_blocks lines' <- lineBlockLines >>= mapM (parseFromString (trimInlinesF . mconcat <$> many inline)) return $ B.para <$> (mconcat $ intersperse (return B.linebreak) lines') -- -- Tables -- -- Parse a dashed line with optional trailing spaces; return its length -- and the length including trailing space. dashedLine :: Char -> Parser [Char] st (Int, Int) dashedLine ch = do dashes <- many1 (char ch) sp <- many spaceChar let lengthDashes = length dashes lengthSp = length sp return (lengthDashes, lengthDashes + lengthSp) -- Parse a table header with dashed lines of '-' preceded by -- one (or zero) line of text. simpleTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) simpleTableHeader headless = try $ do rawContent <- if headless then return "" else anyLine initSp <- nonindentSpaces dashes <- many1 (dashedLine '-') newline let (lengths, lines') = unzip dashes let indices = scanl (+) (length initSp) lines' -- If no header, calculate alignment on basis of first row of text rawHeads <- liftM (tail . splitStringByIndices (init indices)) $ if headless then lookAhead anyLine else return rawContent let aligns = zipWith alignType (map (\a -> [a]) rawHeads) lengths let rawHeads' = if headless then replicate (length dashes) "" else rawHeads heads <- fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) $ map trim rawHeads' return (heads, aligns, indices) -- Returns an alignment type for a table, based on a list of strings -- (the rows of the column header) and a number (the length of the -- dashed line under the rows. alignType :: [String] -> Int -> Alignment alignType [] _ = AlignDefault alignType strLst len = let nonempties = filter (not . null) $ map trimr strLst (leftSpace, rightSpace) = case sortBy (comparing length) nonempties of (x:_) -> (head x `elem` " \t", length x < len) [] -> (False, False) in case (leftSpace, rightSpace) of (True, False) -> AlignRight (False, True) -> AlignLeft (True, True) -> AlignCenter (False, False) -> AlignDefault -- Parse a table footer - dashed lines followed by blank line. tableFooter :: MarkdownParser String tableFooter = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> blanklines -- Parse a table separator - dashed line. tableSep :: MarkdownParser Char tableSep = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> char '\n' -- Parse a raw line and split it into chunks by indices. rawTableLine :: [Int] -> MarkdownParser [String] rawTableLine indices = do notFollowedBy' (blanklines <|> tableFooter) line <- many1Till anyChar newline return $ map trim $ tail $ splitStringByIndices (init indices) line -- Parse a table line and return a list of lists of blocks (columns). tableLine :: [Int] -> MarkdownParser (F [Blocks]) tableLine indices = rawTableLine indices >>= fmap sequence . mapM (parseFromString (mconcat <$> many plain)) -- Parse a multiline table row and return a list of blocks (columns). multilineRow :: [Int] -> MarkdownParser (F [Blocks]) multilineRow indices = do colLines <- many1 (rawTableLine indices) let cols = map unlines $ transpose colLines fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) cols -- Parses a table caption: inlines beginning with 'Table:' -- and followed by blank lines. tableCaption :: MarkdownParser (F Inlines) tableCaption = try $ do guardEnabled Ext_table_captions skipNonindentSpaces string ":" <|> string "Table:" trimInlinesF . mconcat <$> many1 inline <* blanklines -- Parse a simple table with '---' header and one line per row. simpleTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) simpleTable headless = do (aligns, _widths, heads', lines') <- tableWith (simpleTableHeader headless) tableLine (return ()) (if headless then tableFooter else tableFooter <|> blanklines) -- Simple tables get 0s for relative column widths (i.e., use default) return (aligns, replicate (length aligns) 0, heads', lines') -- Parse a multiline table: starts with row of '-' on top, then header -- (which may be multiline), then the rows, -- which may be multiline, separated by blank lines, and -- ending with a footer (dashed line followed by blank line). multilineTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) multilineTable headless = tableWith (multilineTableHeader headless) multilineRow blanklines tableFooter multilineTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) multilineTableHeader headless = try $ do unless headless $ tableSep >> notFollowedBy blankline rawContent <- if headless then return $ repeat "" else many1 $ notFollowedBy tableSep >> anyLine initSp <- nonindentSpaces dashes <- many1 (dashedLine '-') newline let (lengths, lines') = unzip dashes let indices = scanl (+) (length initSp) lines' rawHeadsList <- if headless then liftM (map (:[]) . tail . splitStringByIndices (init indices)) $ lookAhead anyLine else return $ transpose $ map (tail . splitStringByIndices (init indices)) rawContent let aligns = zipWith alignType rawHeadsList lengths let rawHeads = if headless then replicate (length dashes) "" else map (unlines . map trim) rawHeadsList heads <- fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) $ map trim rawHeads return (heads, aligns, indices) -- Parse a grid table: starts with row of '-' on top, then header -- (which may be grid), then the rows, -- which may be grid, separated by blank lines, and -- ending with a footer (dashed line followed by blank line). gridTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) gridTable headless = tableWith (gridTableHeader headless) gridTableRow (gridTableSep '-') gridTableFooter gridTableSplitLine :: [Int] -> String -> [String] gridTableSplitLine indices line = map removeFinalBar $ tail $ splitStringByIndices (init indices) $ trimr line gridPart :: Char -> Parser [Char] st (Int, Int) gridPart ch = do dashes <- many1 (char ch) char '+' let lengthDashes = length dashes return (lengthDashes, lengthDashes + 1) gridDashedLines :: Char -> Parser [Char] st [(Int,Int)] gridDashedLines ch = try $ char '+' >> many1 (gridPart ch) <* blankline removeFinalBar :: String -> String removeFinalBar = reverse . dropWhile (`elem` " \t") . dropWhile (=='|') . reverse -- | Separator between rows of grid table. gridTableSep :: Char -> MarkdownParser Char gridTableSep ch = try $ gridDashedLines ch >> return '\n' -- | Parse header for a grid table. gridTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) gridTableHeader headless = try $ do optional blanklines dashes <- gridDashedLines '-' rawContent <- if headless then return $ repeat "" else many1 (notFollowedBy (gridTableSep '=') >> char '|' >> many1Till anyChar newline) if headless then return () else gridTableSep '=' >> return () let lines' = map snd dashes let indices = scanl (+) 0 lines' let aligns = replicate (length lines') AlignDefault -- RST does not have a notion of alignments let rawHeads = if headless then replicate (length dashes) "" else map (unlines . map trim) $ transpose $ map (gridTableSplitLine indices) rawContent heads <- fmap sequence $ mapM (parseFromString parseBlocks . trim) rawHeads return (heads, aligns, indices) gridTableRawLine :: [Int] -> MarkdownParser [String] gridTableRawLine indices = do char '|' line <- many1Till anyChar newline return (gridTableSplitLine indices line) -- | Parse row of grid table. gridTableRow :: [Int] -> MarkdownParser (F [Blocks]) gridTableRow indices = do colLines <- many1 (gridTableRawLine indices) let cols = map ((++ "\n") . unlines . removeOneLeadingSpace) $ transpose colLines fmap compactify' <$> fmap sequence (mapM (parseFromString parseBlocks) cols) removeOneLeadingSpace :: [String] -> [String] removeOneLeadingSpace xs = if all startsWithSpace xs then map (drop 1) xs else xs where startsWithSpace "" = True startsWithSpace (y:_) = y == ' ' -- | Parse footer for a grid table. gridTableFooter :: MarkdownParser [Char] gridTableFooter = blanklines pipeBreak :: MarkdownParser [Alignment] pipeBreak = try $ do nonindentSpaces openPipe <- (True <$ char '|') <|> return False first <- pipeTableHeaderPart rest <- many $ sepPipe *> pipeTableHeaderPart -- surrounding pipes needed for a one-column table: guard $ not (null rest && not openPipe) optional (char '|') blankline return (first:rest) pipeTable :: MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) pipeTable = try $ do (heads,aligns) <- (,) <$> pipeTableRow <*> pipeBreak lines' <- sequence <$> many pipeTableRow let widths = replicate (length aligns) 0.0 return $ (aligns, widths, heads, lines') sepPipe :: MarkdownParser () sepPipe = try $ do char '|' <|> char '+' notFollowedBy blankline -- parse a row, also returning probable alignments for org-table cells pipeTableRow :: MarkdownParser (F [Blocks]) pipeTableRow = do nonindentSpaces openPipe <- (True <$ char '|') <|> return False let cell = mconcat <$> many (notFollowedBy (blankline <|> char '|') >> inline) first <- cell rest <- many $ sepPipe *> cell -- surrounding pipes needed for a one-column table: guard $ not (null rest && not openPipe) optional (char '|') blankline let cells = sequence (first:rest) return $ do cells' <- cells return $ map (\ils -> case trimInlines ils of ils' | B.isNull ils' -> mempty | otherwise -> B.plain $ ils') cells' pipeTableHeaderPart :: Parser [Char] st Alignment pipeTableHeaderPart = try $ do skipMany spaceChar left <- optionMaybe (char ':') many1 (char '-') right <- optionMaybe (char ':') skipMany spaceChar return $ case (left,right) of (Nothing,Nothing) -> AlignDefault (Just _,Nothing) -> AlignLeft (Nothing,Just _) -> AlignRight (Just _,Just _) -> AlignCenter -- Succeed only if current line contains a pipe. scanForPipe :: Parser [Char] st () scanForPipe = do inp <- getInput case break (\c -> c == '\n' || c == '|') inp of (_,'|':_) -> return () _ -> mzero -- | Parse a table using 'headerParser', 'rowParser', -- 'lineParser', and 'footerParser'. Variant of the version in -- Text.Pandoc.Parsing. tableWith :: MarkdownParser (F [Blocks], [Alignment], [Int]) -> ([Int] -> MarkdownParser (F [Blocks])) -> MarkdownParser sep -> MarkdownParser end -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) tableWith headerParser rowParser lineParser footerParser = try $ do (heads, aligns, indices) <- headerParser lines' <- fmap sequence $ rowParser indices `sepEndBy1` lineParser footerParser numColumns <- getOption readerColumns let widths = if (indices == []) then replicate (length aligns) 0.0 else widthsFromIndices numColumns indices return $ (aligns, widths, heads, lines') table :: MarkdownParser (F Blocks) table = try $ do frontCaption <- option Nothing (Just <$> tableCaption) (aligns, widths, heads, lns) <- try (guardEnabled Ext_pipe_tables >> scanForPipe >> pipeTable) <|> try (guardEnabled Ext_multiline_tables >> multilineTable False) <|> try (guardEnabled Ext_simple_tables >> (simpleTable True <|> simpleTable False)) <|> try (guardEnabled Ext_multiline_tables >> multilineTable True) <|> try (guardEnabled Ext_grid_tables >> (gridTable False <|> gridTable True)) <?> "table" optional blanklines caption <- case frontCaption of Nothing -> option (return mempty) tableCaption Just c -> return c return $ do caption' <- caption heads' <- heads lns' <- lns return $ B.table caption' (zip aligns widths) heads' lns' -- -- inline -- inline :: MarkdownParser (F Inlines) inline = choice [ whitespace , bareURL , str , endline , code , strongOrEmph , note , cite , link , image , math , strikeout , subscript , superscript , inlineNote -- after superscript because of ^[link](/foo)^ , autoLink , spanHtml , rawHtmlInline , escapedChar , rawLaTeXInline' , exampleRef , smart , return . B.singleton <$> charRef , symbol , ltSign ] <?> "inline" escapedChar' :: MarkdownParser Char escapedChar' = try $ do char '\\' (guardEnabled Ext_all_symbols_escapable >> satisfy (not . isAlphaNum)) <|> oneOf "\\`*_{}[]()>#+-.!~\"" escapedChar :: MarkdownParser (F Inlines) escapedChar = do result <- escapedChar' case result of ' ' -> return $ return $ B.str "\160" -- "\ " is a nonbreaking space '\n' -> guardEnabled Ext_escaped_line_breaks >> return (return B.linebreak) -- "\[newline]" is a linebreak _ -> return $ return $ B.str [result] ltSign :: MarkdownParser (F Inlines) ltSign = do guardDisabled Ext_raw_html <|> (notFollowedByHtmlCloser >> notFollowedBy' (htmlTag isBlockTag)) char '<' return $ return $ B.str "<" exampleRef :: MarkdownParser (F Inlines) exampleRef = try $ do guardEnabled Ext_example_lists char '@' lab <- many1 (alphaNum <|> oneOf "-_") return $ do st <- askF return $ case M.lookup lab (stateExamples st) of Just n -> B.str (show n) Nothing -> B.str ('@':lab) symbol :: MarkdownParser (F Inlines) symbol = do result <- noneOf "<\\\n\t " <|> try (do lookAhead $ char '\\' notFollowedBy' (() <$ rawTeXBlock) char '\\') return $ return $ B.str [result] -- parses inline code, between n `s and n `s code :: MarkdownParser (F Inlines) code = try $ do starts <- many1 (char '`') skipSpaces result <- many1Till (many1 (noneOf "`\n") <|> many1 (char '`') <|> (char '\n' >> notFollowedBy' blankline >> return " ")) (try (skipSpaces >> count (length starts) (char '`') >> notFollowedBy (char '`'))) attr <- option ([],[],[]) (try $ guardEnabled Ext_inline_code_attributes >> optional whitespace >> attributes) return $ return $ B.codeWith attr $ trim $ concat result math :: MarkdownParser (F Inlines) math = (return . B.displayMath <$> (mathDisplay >>= applyMacros')) <|> (return . B.math <$> (mathInline >>= applyMacros')) <+?> ((getOption readerSmart >>= guard) *> (return <$> apostrophe) <* notFollowedBy space) -- Parses material enclosed in *s, **s, _s, or __s. -- Designed to avoid backtracking. enclosure :: Char -> MarkdownParser (F Inlines) enclosure c = do -- we can't start an enclosure with _ if after a string and -- the intraword_underscores extension is enabled: guardDisabled Ext_intraword_underscores <|> guard (c == '*') <|> (guard =<< notAfterString) cs <- many1 (char c) (return (B.str cs) <>) <$> whitespace <|> do case length cs of 3 -> three c 2 -> two c mempty 1 -> one c mempty _ -> return (return $ B.str cs) ender :: Char -> Int -> MarkdownParser () ender c n = try $ do count n (char c) guard (c == '*') <|> guardDisabled Ext_intraword_underscores <|> notFollowedBy alphaNum -- Parse inlines til you hit one c or a sequence of two cs. -- If one c, emit emph and then parse two. -- If two cs, emit strong and then parse one. -- Otherwise, emit ccc then the results. three :: Char -> MarkdownParser (F Inlines) three c = do contents <- mconcat <$> many (notFollowedBy (ender c 1) >> inline) (ender c 3 >> return ((B.strong . B.emph) <$> contents)) <|> (ender c 2 >> one c (B.strong <$> contents)) <|> (ender c 1 >> two c (B.emph <$> contents)) <|> return (return (B.str [c,c,c]) <> contents) -- Parse inlines til you hit two c's, and emit strong. -- If you never do hit two cs, emit ** plus inlines parsed. two :: Char -> F Inlines -> MarkdownParser (F Inlines) two c prefix' = do contents <- mconcat <$> many (try $ notFollowedBy (ender c 2) >> inline) (ender c 2 >> return (B.strong <$> (prefix' <> contents))) <|> return (return (B.str [c,c]) <> (prefix' <> contents)) -- Parse inlines til you hit a c, and emit emph. -- If you never hit a c, emit * plus inlines parsed. one :: Char -> F Inlines -> MarkdownParser (F Inlines) one c prefix' = do contents <- mconcat <$> many ( (notFollowedBy (ender c 1) >> inline) <|> try (string [c,c] >> notFollowedBy (ender c 1) >> two c mempty) ) (ender c 1 >> return (B.emph <$> (prefix' <> contents))) <|> return (return (B.str [c]) <> (prefix' <> contents)) strongOrEmph :: MarkdownParser (F Inlines) strongOrEmph = enclosure '*' <|> enclosure '_' -- | Parses a list of inlines between start and end delimiters. inlinesBetween :: (Show b) => MarkdownParser a -> MarkdownParser b -> MarkdownParser (F Inlines) inlinesBetween start end = (trimInlinesF . mconcat) <$> try (start >> many1Till inner end) where inner = innerSpace <|> (notFollowedBy' (() <$ whitespace) >> inline) innerSpace = try $ whitespace <* notFollowedBy' end strikeout :: MarkdownParser (F Inlines) strikeout = fmap B.strikeout <$> (guardEnabled Ext_strikeout >> inlinesBetween strikeStart strikeEnd) where strikeStart = string "~~" >> lookAhead nonspaceChar >> notFollowedBy (char '~') strikeEnd = try $ string "~~" superscript :: MarkdownParser (F Inlines) superscript = fmap B.superscript <$> try (do guardEnabled Ext_superscript char '^' mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '^')) subscript :: MarkdownParser (F Inlines) subscript = fmap B.subscript <$> try (do guardEnabled Ext_subscript char '~' mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '~')) whitespace :: MarkdownParser (F Inlines) whitespace = spaceChar >> return <$> (lb <|> regsp) <?> "whitespace" where lb = spaceChar >> skipMany spaceChar >> option B.space (endline >> return B.linebreak) regsp = skipMany spaceChar >> return B.space nonEndline :: Parser [Char] st Char nonEndline = satisfy (/='\n') str :: MarkdownParser (F Inlines) str = do result <- many1 alphaNum updateLastStrPos let spacesToNbr = map (\c -> if c == ' ' then '\160' else c) isSmart <- getOption readerSmart if isSmart then case likelyAbbrev result of [] -> return $ return $ B.str result xs -> choice (map (\x -> try (string x >> oneOf " \n" >> lookAhead alphaNum >> return (return $ B.str $ result ++ spacesToNbr x ++ "\160"))) xs) <|> (return $ return $ B.str result) else return $ return $ B.str result -- | if the string matches the beginning of an abbreviation (before -- the first period, return strings that would finish the abbreviation. likelyAbbrev :: String -> [String] likelyAbbrev x = let abbrevs = [ "Mr.", "Mrs.", "Ms.", "Capt.", "Dr.", "Prof.", "Gen.", "Gov.", "e.g.", "i.e.", "Sgt.", "St.", "vol.", "vs.", "Sen.", "Rep.", "Pres.", "Hon.", "Rev.", "Ph.D.", "M.D.", "M.A.", "p.", "pp.", "ch.", "sec.", "cf.", "cp."] abbrPairs = map (break (=='.')) abbrevs in map snd $ filter (\(y,_) -> y == x) abbrPairs -- an endline character that can be treated as a space, not a structural break endline :: MarkdownParser (F Inlines) endline = try $ do newline notFollowedBy blankline -- parse potential list-starts differently if in a list: notFollowedBy (inList >> listStart) guardDisabled Ext_lists_without_preceding_blankline <|> notFollowedBy listStart guardEnabled Ext_blank_before_blockquote <|> notFollowedBy emailBlockQuoteStart guardEnabled Ext_blank_before_header <|> notFollowedBy (char '#') -- atx header guardDisabled Ext_backtick_code_blocks <|> notFollowedBy (() <$ (lookAhead (char '`') >> codeBlockFenced)) notFollowedByHtmlCloser (eof >> return mempty) <|> (guardEnabled Ext_hard_line_breaks >> return (return B.linebreak)) <|> (guardEnabled Ext_ignore_line_breaks >> return mempty) <|> (return $ return B.space) -- -- links -- -- a reference label for a link reference :: MarkdownParser (F Inlines, String) reference = do notFollowedBy' (string "[^") -- footnote reference withRaw $ trimInlinesF <$> inlinesInBalancedBrackets parenthesizedChars :: MarkdownParser [Char] parenthesizedChars = do result <- charsInBalanced '(' ')' litChar return $ '(' : result ++ ")" -- source for a link, with optional title source :: MarkdownParser (String, String) source = do char '(' skipSpaces let urlChunk = try parenthesizedChars <|> (notFollowedBy (oneOf " )") >> (count 1 litChar)) <|> try (many1 spaceChar <* notFollowedBy (oneOf "\"')")) let sourceURL = (unwords . words . concat) <$> many urlChunk let betweenAngles = try $ char '<' >> manyTill litChar (char '>') src <- try betweenAngles <|> sourceURL tit <- option "" $ try $ spnl >> linkTitle skipSpaces char ')' return (escapeURI $ trimr src, tit) linkTitle :: MarkdownParser String linkTitle = quotedTitle '"' <|> quotedTitle '\'' link :: MarkdownParser (F Inlines) link = try $ do st <- getState guard $ stateAllowLinks st setState $ st{ stateAllowLinks = False } (lab,raw) <- reference setState $ st{ stateAllowLinks = True } regLink B.link lab <|> referenceLink B.link (lab,raw) regLink :: (String -> String -> Inlines -> Inlines) -> F Inlines -> MarkdownParser (F Inlines) regLink constructor lab = try $ do (src, tit) <- source return $ constructor src tit <$> lab -- a link like [this][ref] or [this][] or [this] referenceLink :: (String -> String -> Inlines -> Inlines) -> (F Inlines, String) -> MarkdownParser (F Inlines) referenceLink constructor (lab, raw) = do sp <- (True <$ lookAhead (char ' ')) <|> return False (_,raw') <- option (mempty, "") $ lookAhead (try (spnl >> normalCite >> return (mempty, ""))) <|> try (spnl >> reference) when (raw' == "") $ guardEnabled Ext_shortcut_reference_links let labIsRef = raw' == "" || raw' == "[]" let key = toKey $ if labIsRef then raw else raw' parsedRaw <- parseFromString (mconcat <$> many inline) raw' fallback <- parseFromString (mconcat <$> many inline) $ dropBrackets raw implicitHeaderRefs <- option False $ True <$ guardEnabled Ext_implicit_header_references let makeFallback = do parsedRaw' <- parsedRaw fallback' <- fallback return $ B.str "[" <> fallback' <> B.str "]" <> (if sp && not (null raw) then B.space else mempty) <> parsedRaw' return $ do keys <- asksF stateKeys case M.lookup key keys of Nothing -> if implicitHeaderRefs then do headerKeys <- asksF stateHeaderKeys case M.lookup key headerKeys of Just (src, tit) -> constructor src tit <$> lab Nothing -> makeFallback else makeFallback Just (src,tit) -> constructor src tit <$> lab dropBrackets :: String -> String dropBrackets = reverse . dropRB . reverse . dropLB where dropRB (']':xs) = xs dropRB xs = xs dropLB ('[':xs) = xs dropLB xs = xs bareURL :: MarkdownParser (F Inlines) bareURL = try $ do guardEnabled Ext_autolink_bare_uris (orig, src) <- uri <|> emailAddress notFollowedBy $ try $ spaces >> htmlTag (~== TagClose "a") return $ return $ B.link src "" (B.str orig) autoLink :: MarkdownParser (F Inlines) autoLink = try $ do char '<' (orig, src) <- uri <|> emailAddress -- in rare cases, something may remain after the uri parser -- is finished, because the uri parser tries to avoid parsing -- final punctuation. for example: in `<http://hi---there>`, -- the URI parser will stop before the dashes. extra <- fromEntities <$> manyTill nonspaceChar (char '>') return $ return $ B.link (src ++ escapeURI extra) "" (B.str $ orig ++ extra) image :: MarkdownParser (F Inlines) image = try $ do char '!' (lab,raw) <- reference defaultExt <- getOption readerDefaultImageExtension let constructor src = case takeExtension src of "" -> B.image (addExtension src defaultExt) _ -> B.image src regLink constructor lab <|> referenceLink constructor (lab,raw) note :: MarkdownParser (F Inlines) note = try $ do guardEnabled Ext_footnotes ref <- noteMarker return $ do notes <- asksF stateNotes' case lookup ref notes of Nothing -> return $ B.str $ "[^" ++ ref ++ "]" Just contents -> do st <- askF -- process the note in a context that doesn't resolve -- notes, to avoid infinite looping with notes inside -- notes: let contents' = runF contents st{ stateNotes' = [] } return $ B.note contents' inlineNote :: MarkdownParser (F Inlines) inlineNote = try $ do guardEnabled Ext_inline_notes char '^' contents <- inlinesInBalancedBrackets return $ B.note . B.para <$> contents rawLaTeXInline' :: MarkdownParser (F Inlines) rawLaTeXInline' = try $ do guardEnabled Ext_raw_tex lookAhead $ char '\\' >> notFollowedBy' (string "start") -- context env RawInline _ s <- rawLaTeXInline return $ return $ B.rawInline "tex" s -- "tex" because it might be context or latex rawConTeXtEnvironment :: Parser [Char] st String rawConTeXtEnvironment = try $ do string "\\start" completion <- inBrackets (letter <|> digit <|> spaceChar) <|> (many1 letter) contents <- manyTill (rawConTeXtEnvironment <|> (count 1 anyChar)) (try $ string "\\stop" >> string completion) return $ "\\start" ++ completion ++ concat contents ++ "\\stop" ++ completion inBrackets :: (Parser [Char] st Char) -> Parser [Char] st String inBrackets parser = do char '[' contents <- many parser char ']' return $ "[" ++ contents ++ "]" spanHtml :: MarkdownParser (F Inlines) spanHtml = try $ do guardEnabled Ext_native_spans (TagOpen _ attrs, _) <- htmlTag (~== TagOpen "span" []) contents <- mconcat <$> manyTill inline (htmlTag (~== TagClose "span")) let ident = fromMaybe "" $ lookup "id" attrs let classes = maybe [] words $ lookup "class" attrs let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"] case lookup "style" keyvals of Just s | null ident && null classes && map toLower (filter (`notElem` " \t;") s) == "font-variant:small-caps" -> return $ B.smallcaps <$> contents _ -> return $ B.spanWith (ident, classes, keyvals) <$> contents divHtml :: MarkdownParser (F Blocks) divHtml = try $ do guardEnabled Ext_native_divs (TagOpen _ attrs, rawtag) <- htmlTag (~== TagOpen "div" []) -- we set stateInHtmlBlock so that closing tags that can be either block or -- inline will not be parsed as inline tags oldInHtmlBlock <- stateInHtmlBlock <$> getState updateState $ \st -> st{ stateInHtmlBlock = Just "div" } bls <- option "" (blankline >> option "" blanklines) contents <- mconcat <$> many (notFollowedBy' (htmlTag (~== TagClose "div")) >> block) closed <- option False (True <$ htmlTag (~== TagClose "div")) if closed then do updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock } let ident = fromMaybe "" $ lookup "id" attrs let classes = maybe [] words $ lookup "class" attrs let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"] return $ B.divWith (ident, classes, keyvals) <$> contents else -- avoid backtracing return $ return (B.rawBlock "html" (rawtag <> bls)) <> contents rawHtmlInline :: MarkdownParser (F Inlines) rawHtmlInline = do guardEnabled Ext_raw_html inHtmlBlock <- stateInHtmlBlock <$> getState let isCloseBlockTag t = case inHtmlBlock of Just t' -> t ~== TagClose t' Nothing -> False mdInHtml <- option False $ ( guardEnabled Ext_markdown_in_html_blocks <|> guardEnabled Ext_markdown_attribute ) >> return True (_,result) <- htmlTag $ if mdInHtml then (\x -> isInlineTag x && not (isCloseBlockTag x)) else not . isTextTag return $ return $ B.rawInline "html" result -- Citations cite :: MarkdownParser (F Inlines) cite = do guardEnabled Ext_citations citations <- textualCite <|> do (cs, raw) <- withRaw normalCite return $ (flip B.cite (B.text raw)) <$> cs return citations textualCite :: MarkdownParser (F Inlines) textualCite = try $ do (_, key) <- citeKey let first = Citation{ citationId = key , citationPrefix = [] , citationSuffix = [] , citationMode = AuthorInText , citationNoteNum = 0 , citationHash = 0 } mbrest <- option Nothing $ try $ spnl >> Just <$> withRaw normalCite case mbrest of Just (rest, raw) -> return $ (flip B.cite (B.text $ '@':key ++ " " ++ raw) . (first:)) <$> rest Nothing -> (do (cs, raw) <- withRaw $ bareloc first let (spaces',raw') = span isSpace raw spc | null spaces' = mempty | otherwise = B.space lab <- parseFromString (mconcat <$> many inline) $ dropBrackets raw' fallback <- referenceLink B.link (lab,raw') return $ do fallback' <- fallback cs' <- cs return $ case B.toList fallback' of Link{}:_ -> B.cite [first] (B.str $ '@':key) <> spc <> fallback' _ -> B.cite cs' (B.text $ '@':key ++ " " ++ raw)) <|> return (do st <- askF return $ case M.lookup key (stateExamples st) of Just n -> B.str (show n) _ -> B.cite [first] $ B.str $ '@':key) bareloc :: Citation -> MarkdownParser (F [Citation]) bareloc c = try $ do spnl char '[' notFollowedBy $ char '^' suff <- suffix rest <- option (return []) $ try $ char ';' >> citeList spnl char ']' notFollowedBy $ oneOf "[(" return $ do suff' <- suff rest' <- rest return $ c{ citationSuffix = B.toList suff' } : rest' normalCite :: MarkdownParser (F [Citation]) normalCite = try $ do char '[' spnl citations <- citeList spnl char ']' return citations suffix :: MarkdownParser (F Inlines) suffix = try $ do hasSpace <- option False (notFollowedBy nonspaceChar >> return True) spnl rest <- trimInlinesF . mconcat <$> many (notFollowedBy (oneOf ";]") >> inline) return $ if hasSpace then (B.space <>) <$> rest else rest prefix :: MarkdownParser (F Inlines) prefix = trimInlinesF . mconcat <$> manyTill inline (char ']' <|> liftM (const ']') (lookAhead citeKey)) citeList :: MarkdownParser (F [Citation]) citeList = fmap sequence $ sepBy1 citation (try $ char ';' >> spnl) citation :: MarkdownParser (F Citation) citation = try $ do pref <- prefix (suppress_author, key) <- citeKey suff <- suffix return $ do x <- pref y <- suff return $ Citation{ citationId = key , citationPrefix = B.toList x , citationSuffix = B.toList y , citationMode = if suppress_author then SuppressAuthor else NormalCitation , citationNoteNum = 0 , citationHash = 0 } smart :: MarkdownParser (F Inlines) smart = do getOption readerSmart >>= guard doubleQuoted <|> singleQuoted <|> choice (map (return <$>) [apostrophe, dash, ellipses]) singleQuoted :: MarkdownParser (F Inlines) singleQuoted = try $ do singleQuoteStart withQuoteContext InSingleQuote $ fmap B.singleQuoted . trimInlinesF . mconcat <$> many1Till inline singleQuoteEnd -- doubleQuoted will handle regular double-quoted sections, as well -- as dialogues with an open double-quote without a close double-quote -- in the same paragraph. doubleQuoted :: MarkdownParser (F Inlines) doubleQuoted = try $ do doubleQuoteStart contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline) (withQuoteContext InDoubleQuote $ doubleQuoteEnd >> return (fmap B.doubleQuoted . trimInlinesF $ contents)) <|> (return $ return (B.str "\8220") <> contents)
csrhodes/pandoc
src/Text/Pandoc/Readers/Markdown.hs
gpl-2.0
73,232
0
28
20,407
21,562
10,656
10,906
1,611
7
{-# LANGUAGE FlexibleContexts #-} module Language.Haskell.Liquid.Bare.Env ( BareM , Warn , TCEnv , BareEnv(..) , TInline(..), InlnEnv , inModule , withVArgs , setRTAlias , setRPAlias , setREAlias , execBare ) where import HscTypes import TyCon import Var import Control.Monad.Error hiding (Error) import Control.Monad.State import Control.Monad.Writer import qualified Control.Exception as Ex import qualified Data.HashMap.Strict as M import Language.Fixpoint.Types (Expr(..), Symbol, symbol, Pred) import Language.Haskell.Liquid.Errors () import Language.Haskell.Liquid.Types import Language.Haskell.Liquid.Bounds ----------------------------------------------------------------------------------- -- | Error-Reader-IO For Bare Transformation -------------------------------------- ----------------------------------------------------------------------------------- -- FIXME: don't use WriterT [], very slow type BareM = WriterT [Warn] (ErrorT Error (StateT BareEnv IO)) type Warn = String type TCEnv = M.HashMap TyCon RTyCon type InlnEnv = M.HashMap Symbol TInline data TInline = TI { tiargs :: [Symbol] , tibody :: Either Pred Expr } deriving (Show) data BareEnv = BE { modName :: !ModName , tcEnv :: !TCEnv , rtEnv :: !RTEnv , varEnv :: ![(Symbol,Var)] , hscEnv :: HscEnv , logicEnv :: LogicMap , inlines :: InlnEnv , bounds :: RBEnv } setModule m b = b { modName = m } inModule m act = do old <- gets modName modify $ setModule m res <- act modify $ setModule old return res withVArgs l l' vs act = do old <- gets rtEnv mapM_ (mkExprAlias l l' . symbol . showpp) vs res <- act modify $ \be -> be { rtEnv = old } return res mkExprAlias l l' v = setRTAlias v (RTA v [] [] (RExprArg (Loc l l' $ EVar $ symbol v)) l l') setRTAlias s a = modify $ \b -> b { rtEnv = mapRT (M.insert s a) $ rtEnv b } setRPAlias s a = modify $ \b -> b { rtEnv = mapRP (M.insert s a) $ rtEnv b } setREAlias s a = modify $ \b -> b { rtEnv = mapRE (M.insert s a) $ rtEnv b } ------------------------------------------------------------------ execBare :: BareM a -> BareEnv -> IO (Either Error a) ------------------------------------------------------------------ execBare act benv = do z <- evalStateT (runErrorT (runWriterT act)) benv `Ex.catch` (return . Left) case z of Left s -> return $ Left s Right (x, ws) -> do forM_ ws $ putStrLn . ("WARNING: " ++) return $ Right x
mightymoose/liquidhaskell
src/Language/Haskell/Liquid/Bare/Env.hs
bsd-3-clause
2,703
0
14
721
825
452
373
76
2
-- | Extra functions for optparse-applicative. module Options.Applicative.Builder.Extra (boolFlags ,boolFlagsNoDefault ,maybeBoolFlags ,firstBoolFlags ,enableDisableFlags ,enableDisableFlagsNoDefault ,extraHelpOption ,execExtraHelp ,textOption ,textArgument ,optionalFirst ,absFileOption ,relFileOption ,absDirOption ,relDirOption ,eitherReader' ) where import Control.Monad (when) import Data.Either.Combinators import Data.Monoid import Options.Applicative import Options.Applicative.Types (readerAsk) import Path import System.Environment (withArgs) import System.FilePath (takeBaseName) import Data.Text (Text) import qualified Data.Text as T -- | Enable/disable flags for a 'Bool'. boolFlags :: Bool -- ^ Default value -> String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields Bool -> Parser Bool boolFlags defaultValue = enableDisableFlags defaultValue True False -- | Enable/disable flags for a 'Bool', without a default case (to allow chaining with '<|>'). boolFlagsNoDefault :: String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields Bool -> Parser Bool boolFlagsNoDefault = enableDisableFlagsNoDefault True False -- | Enable/disable flags for a @('Maybe' 'Bool')@. maybeBoolFlags :: String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields (Maybe Bool) -> Parser (Maybe Bool) maybeBoolFlags = enableDisableFlags Nothing (Just True) (Just False) -- | Like 'maybeBoolFlags', but parsing a 'First'. firstBoolFlags :: String -> String -> Mod FlagFields (Maybe Bool) -> Parser (First Bool) firstBoolFlags long0 help0 mod0 = First <$> maybeBoolFlags long0 help0 mod0 -- | Enable/disable flags for any type. enableDisableFlags :: a -- ^ Default value -> a -- ^ Enabled value -> a -- ^ Disabled value -> String -- ^ Name -> String -- ^ Help suffix -> Mod FlagFields a -> Parser a enableDisableFlags defaultValue enabledValue disabledValue name helpSuffix mods = enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods <|> pure defaultValue -- | Enable/disable flags for any type, without a default (to allow chaining with '<|>') enableDisableFlagsNoDefault :: a -- ^ Enabled value -> a -- ^ Disabled value -> String -- ^ Name -> String -- ^ Help suffix -> Mod FlagFields a -> Parser a enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods = last <$> some ((flag' enabledValue (hidden <> internal <> long name <> help helpSuffix <> mods) <|> flag' disabledValue (hidden <> internal <> long ("no-" ++ name) <> help helpSuffix <> mods)) <|> flag' disabledValue (long ("[no-]" ++ name) <> help ("Enable/disable " ++ helpSuffix) <> mods)) -- | Show an extra help option (e.g. @--docker-help@ shows help for all @--docker*@ args). -- -- To actually have that help appear, use 'execExtraHelp' before executing the main parser. extraHelpOption :: Bool -- ^ Hide from the brief description? -> String -- ^ Program name, e.g. @"stack"@ -> String -- ^ Option glob expression, e.g. @"docker*"@ -> String -- ^ Help option name, e.g. @"docker-help"@ -> Parser (a -> a) extraHelpOption hide progName fakeName helpName = infoOption (optDesc' ++ ".") (long helpName <> hidden <> internal) <*> infoOption (optDesc' ++ ".") (long fakeName <> help optDesc' <> (if hide then hidden <> internal else idm)) where optDesc' = concat ["Run '", takeBaseName progName, " --", helpName, "' for details"] -- | Display extra help if extra help option passed in arguments. -- -- Since optparse-applicative doesn't allow an arbitrary IO action for an 'abortOption', this -- was the best way I found that doesn't require manually formatting the help. execExtraHelp :: [String] -- ^ Command line arguments -> String -- ^ Extra help option name, e.g. @"docker-help"@ -> Parser a -- ^ Option parser for the relevant command -> String -- ^ Option description -> IO () execExtraHelp args helpOpt parser pd = when (args == ["--" ++ helpOpt]) $ withArgs ["--help"] $ do _ <- execParser (info (hiddenHelper <*> ((,) <$> parser <*> some (strArgument (metavar "OTHER ARGUMENTS")))) (fullDesc <> progDesc pd)) return () where hiddenHelper = abortOption ShowHelpText (long "help" <> hidden <> internal) -- | 'option', specialized to 'Text'. textOption :: Mod OptionFields Text -> Parser Text textOption = option (T.pack <$> readerAsk) -- | 'argument', specialized to 'Text'. textArgument :: Mod ArgumentFields Text -> Parser Text textArgument = argument (T.pack <$> readerAsk) -- | Like 'optional', but returning a 'First'. optionalFirst :: Alternative f => f a -> f (First a) optionalFirst = fmap First . optional absFileOption :: Mod OptionFields (Path Abs File) -> Parser (Path Abs File) absFileOption = option (eitherReader' parseAbsFile) relFileOption :: Mod OptionFields (Path Rel File) -> Parser (Path Rel File) relFileOption = option (eitherReader' parseRelFile) absDirOption :: Mod OptionFields (Path Abs Dir) -> Parser (Path Abs Dir) absDirOption = option (eitherReader' parseAbsDir) relDirOption :: Mod OptionFields (Path Rel Dir) -> Parser (Path Rel Dir) relDirOption = option (eitherReader' parseRelDir) -- | Like 'eitherReader', but accepting any @'Show' e@ on the 'Left'. eitherReader' :: Show e => (String -> Either e a) -> ReadM a eitherReader' f = eitherReader (mapLeft show . f)
AndreasPK/stack
src/Options/Applicative/Builder/Extra.hs
bsd-3-clause
6,524
0
20
2,075
1,294
681
613
124
2
{-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TypeOperators #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Traversable -- Copyright : Conor McBride and Ross Paterson 2005 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Class of data structures that can be traversed from left to right, -- performing an action on each element. -- -- See also -- -- * \"Applicative Programming with Effects\", -- by Conor McBride and Ross Paterson, -- /Journal of Functional Programming/ 18:1 (2008) 1-13, online at -- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>. -- -- * \"The Essence of the Iterator Pattern\", -- by Jeremy Gibbons and Bruno Oliveira, -- in /Mathematically-Structured Functional Programming/, 2006, online at -- <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>. -- -- * \"An Investigation of the Laws of Traversals\", -- by Mauro Jaskelioff and Ondrej Rypacek, -- in /Mathematically-Structured Functional Programming/, 2012, online at -- <http://arxiv.org/pdf/1202.2919>. -- ----------------------------------------------------------------------------- module Data.Traversable ( -- * The 'Traversable' class Traversable(..), -- * Utility functions for, forM, mapAccumL, mapAccumR, -- * General definitions for superclass methods fmapDefault, foldMapDefault, ) where -- It is convenient to use 'Const' here but this means we must -- define a few instances here which really belong in Control.Applicative import Control.Applicative ( Const(..), ZipList(..) ) import Data.Either ( Either(..) ) import Data.Foldable ( Foldable ) import Data.Functor import Data.Functor.Identity ( Identity(..) ) import Data.Functor.Utils ( StateL(..), StateR(..) ) import Data.Monoid ( Dual(..), Sum(..), Product(..), First(..), Last(..) ) import Data.Proxy ( Proxy(..) ) import GHC.Arr import GHC.Base ( Applicative(..), Monad(..), Monoid, Maybe(..), ($), (.), id, flip ) import GHC.Generics import qualified GHC.List as List ( foldr ) -- | Functors representing data structures that can be traversed from -- left to right. -- -- A definition of 'traverse' must satisfy the following laws: -- -- [/naturality/] -- @t . 'traverse' f = 'traverse' (t . f)@ -- for every applicative transformation @t@ -- -- [/identity/] -- @'traverse' Identity = Identity@ -- -- [/composition/] -- @'traverse' (Compose . 'fmap' g . f) = Compose . 'fmap' ('traverse' g) . 'traverse' f@ -- -- A definition of 'sequenceA' must satisfy the following laws: -- -- [/naturality/] -- @t . 'sequenceA' = 'sequenceA' . 'fmap' t@ -- for every applicative transformation @t@ -- -- [/identity/] -- @'sequenceA' . 'fmap' Identity = Identity@ -- -- [/composition/] -- @'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@ -- -- where an /applicative transformation/ is a function -- -- @t :: (Applicative f, Applicative g) => f a -> g a@ -- -- preserving the 'Applicative' operations, i.e. -- -- * @t ('pure' x) = 'pure' x@ -- -- * @t (x '<*>' y) = t x '<*>' t y@ -- -- and the identity functor @Identity@ and composition of functors @Compose@ -- are defined as -- -- > newtype Identity a = Identity a -- > -- > instance Functor Identity where -- > fmap f (Identity x) = Identity (f x) -- > -- > instance Applicative Identity where -- > pure x = Identity x -- > Identity f <*> Identity x = Identity (f x) -- > -- > newtype Compose f g a = Compose (f (g a)) -- > -- > instance (Functor f, Functor g) => Functor (Compose f g) where -- > fmap f (Compose x) = Compose (fmap (fmap f) x) -- > -- > instance (Applicative f, Applicative g) => Applicative (Compose f g) where -- > pure x = Compose (pure (pure x)) -- > Compose f <*> Compose x = Compose ((<*>) <$> f <*> x) -- -- (The naturality law is implied by parametricity.) -- -- Instances are similar to 'Functor', e.g. given a data type -- -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) -- -- a suitable instance would be -- -- > instance Traversable Tree where -- > traverse f Empty = pure Empty -- > traverse f (Leaf x) = Leaf <$> f x -- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r -- -- This is suitable even for abstract types, as the laws for '<*>' -- imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- * In the 'Functor' instance, 'fmap' should be equivalent to traversal -- with the identity applicative functor ('fmapDefault'). -- -- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be -- equivalent to traversal with a constant applicative functor -- ('foldMapDefault'). -- class (Functor t, Foldable t) => Traversable t where {-# MINIMAL traverse | sequenceA #-} -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that ignores -- the results see 'Data.Foldable.traverse_'. traverse :: Applicative f => (a -> f b) -> t a -> f (t b) traverse f = sequenceA . fmap f -- | Evaluate each action in the structure from left to right, and -- and collect the results. For a version that ignores the results -- see 'Data.Foldable.sequenceA_'. sequenceA :: Applicative f => t (f a) -> f (t a) sequenceA = traverse id -- | Map each element of a structure to a monadic action, evaluate -- these actions from left to right, and collect the results. For -- a version that ignores the results see 'Data.Foldable.mapM_'. mapM :: Monad m => (a -> m b) -> t a -> m (t b) mapM = traverse -- | Evaluate each monadic action in the structure from left to -- right, and collect the results. For a version that ignores the -- results see 'Data.Foldable.sequence_'. sequence :: Monad m => t (m a) -> m (t a) sequence = sequenceA -- instances for Prelude types -- | @since 2.01 instance Traversable Maybe where traverse _ Nothing = pure Nothing traverse f (Just x) = Just <$> f x -- | @since 2.01 instance Traversable [] where {-# INLINE traverse #-} -- so that traverse can fuse traverse f = List.foldr cons_f (pure []) where cons_f x ys = (:) <$> f x <*> ys -- | @since 4.7.0.0 instance Traversable (Either a) where traverse _ (Left x) = pure (Left x) traverse f (Right y) = Right <$> f y -- | @since 4.7.0.0 instance Traversable ((,) a) where traverse f (x, y) = (,) x <$> f y -- | @since 2.01 instance Ix i => Traversable (Array i) where traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr) -- | @since 4.7.0.0 instance Traversable Proxy where traverse _ _ = pure Proxy {-# INLINE traverse #-} sequenceA _ = pure Proxy {-# INLINE sequenceA #-} mapM _ _ = pure Proxy {-# INLINE mapM #-} sequence _ = pure Proxy {-# INLINE sequence #-} -- | @since 4.7.0.0 instance Traversable (Const m) where traverse _ (Const m) = pure $ Const m -- | @since 4.8.0.0 instance Traversable Dual where traverse f (Dual x) = Dual <$> f x -- | @since 4.8.0.0 instance Traversable Sum where traverse f (Sum x) = Sum <$> f x -- | @since 4.8.0.0 instance Traversable Product where traverse f (Product x) = Product <$> f x -- | @since 4.8.0.0 instance Traversable First where traverse f (First x) = First <$> traverse f x -- | @since 4.8.0.0 instance Traversable Last where traverse f (Last x) = Last <$> traverse f x -- | @since 4.9.0.0 instance Traversable ZipList where traverse f (ZipList x) = ZipList <$> traverse f x deriving instance Traversable Identity -- Instances for GHC.Generics -- | @since 4.9.0.0 instance Traversable U1 where traverse _ _ = pure U1 {-# INLINE traverse #-} sequenceA _ = pure U1 {-# INLINE sequenceA #-} mapM _ _ = pure U1 {-# INLINE mapM #-} sequence _ = pure U1 {-# INLINE sequence #-} deriving instance Traversable V1 deriving instance Traversable Par1 deriving instance Traversable f => Traversable (Rec1 f) deriving instance Traversable (K1 i c) deriving instance Traversable f => Traversable (M1 i c f) deriving instance (Traversable f, Traversable g) => Traversable (f :+: g) deriving instance (Traversable f, Traversable g) => Traversable (f :*: g) deriving instance (Traversable f, Traversable g) => Traversable (f :.: g) deriving instance Traversable UAddr deriving instance Traversable UChar deriving instance Traversable UDouble deriving instance Traversable UFloat deriving instance Traversable UInt deriving instance Traversable UWord -- general functions -- | 'for' is 'traverse' with its arguments flipped. For a version -- that ignores the results see 'Data.Foldable.for_'. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) {-# INLINE for #-} for = flip traverse -- | 'forM' is 'mapM' with its arguments flipped. For a version that -- ignores the results see 'Data.Foldable.forM_'. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) {-# INLINE forM #-} forM = flip mapM -- |The 'mapAccumL' function behaves like a combination of 'fmap' -- and 'foldl'; it applies a function to each element of a structure, -- passing an accumulating parameter from left to right, and returning -- a final value of this accumulator together with the new structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s -- |The 'mapAccumR' function behaves like a combination of 'fmap' -- and 'foldr'; it applies a function to each element of a structure, -- passing an accumulating parameter from right to left, and returning -- a final value of this accumulator together with the new structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s -- | This function may be used as a value for `fmap` in a `Functor` -- instance, provided that 'traverse' is defined. (Using -- `fmapDefault` with a `Traversable` instance defined only by -- 'sequenceA' will result in infinite recursion.) fmapDefault :: Traversable t => (a -> b) -> t a -> t b {-# INLINE fmapDefault #-} fmapDefault f = runIdentity . traverse (Identity . f) -- | This function may be used as a value for `Data.Foldable.foldMap` -- in a `Foldable` instance. foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m foldMapDefault f = getConst . traverse (Const . f)
snoyberg/ghc
libraries/base/Data/Traversable.hs
bsd-3-clause
10,843
0
12
2,233
1,881
1,068
813
113
1
----------------------------------------------------------------------------- -- | -- Module : Hadrian.Oracles.Cabal -- Copyright : (c) Andrey Mokhov 2014-2018 -- License : MIT (see the file LICENSE) -- Maintainer : [email protected] -- Stability : experimental -- -- This module defines oracles for reading and parsing Cabal files, as well as -- for configuring Haskell packages. ----------------------------------------------------------------------------- module Hadrian.Oracles.Cabal ( readPackageData, readContextData, configurePackageGHC ) where import Development.Shake import Distribution.Simple (Compiler) import Distribution.System (Platform) import Context.Type import Hadrian.Haskell.Cabal.Type import Hadrian.Oracles.Cabal.Type import Hadrian.Package import Stage -- | Read and parse a Cabal file, caching and tracking the result. readPackageData :: Package -> Action PackageData readPackageData = askOracle . PackageDataKey -- | Read and parse a Cabal file recording the obtained 'ContextData', caching -- and tracking the result. Note that unlike 'readPackageData' this function -- resolves all Cabal configuration flags and associated conditionals. readContextData :: Context -> Action ContextData readContextData = askOracle . ContextDataKey -- | Configure a 'Package' using the GHC corresponding to a given 'Stage', -- caching and tracking the result. configurePackageGHC :: Package -> Stage -> Action (Compiler, Platform) configurePackageGHC pkg stage = do PackageConfiguration res <- askOracle $ PackageConfigurationKey (pkg, stage) return res
snowleopard/shaking-up-ghc
src/Hadrian/Oracles/Cabal.hs
bsd-3-clause
1,600
0
10
218
190
114
76
18
1
import qualified Data.Vector as U import Data.Word main = print (U.length (U.replicate 1 (7 :: Word64)))
dolio/vector
old-testsuite/microsuite/length-word64.hs
bsd-3-clause
106
0
10
17
46
26
20
3
1
module Language.Haskell.Format.Utilities ( defaultFormatter , hunitTest , showDiff , wasReformatted ) where import System.IO.Unsafe import Language.Haskell.Format import Language.Haskell.Source.Enumerator import Conduit import Control.Monad import Data.Algorithm.DiffContext import Data.List import Data.Maybe import Test.HUnit import Text.PrettyPrint type ErrorString = String data CheckResult = InvalidCheckResult HaskellSource ErrorString | CheckResult HaskellSource Reformatted checkResultPath :: CheckResult -> FilePath checkResultPath (InvalidCheckResult (HaskellSource filepath _) _) = filepath checkResultPath (CheckResult (HaskellSource filepath _) _) = filepath hunitTest :: FilePath -> Test hunitTest filepath = TestLabel filepath . unsafePerformIO . testPath $ filepath testPath :: FilePath -> IO Test testPath filepath = do formatter <- defaultFormatter TestList <$> runConduit (check formatter filepath .| mapC makeTestCase .| sinkList) makeTestCase :: CheckResult -> Test makeTestCase result = TestLabel (checkResultPath result) . TestCase $ assertCheckResult result assertCheckResult :: CheckResult -> IO () assertCheckResult result = case result of (InvalidCheckResult _ errorString) -> assertFailure ("Error: " ++ errorString) (CheckResult source reformatted) -> when (wasReformatted source reformatted) $ assertFailure (showReformatted source reformatted) where showReformatted :: HaskellSource -> Reformatted -> String showReformatted source reformatted = intercalate "\n" $ catMaybes [ showSourceChanges source reformatted , showSuggestions source reformatted ] showSourceChanges source reformatted = whenMaybe (sourceChanged source reformatted) (showDiff source (reformattedSource reformatted)) showSuggestions _ reformatted = whenMaybe (hasSuggestions reformatted) (concatMap show (suggestions reformatted)) whenMaybe :: Bool -> a -> Maybe a whenMaybe cond val = val <$ guard cond showDiff :: HaskellSource -> HaskellSource -> String showDiff (HaskellSource _ a) (HaskellSource _ b) = render (toDoc diff) where toDoc = prettyContextDiff (text "Original") (text "Reformatted") text diff = getContextDiff linesOfContext (lines a) (lines b) linesOfContext = 1 check :: Formatter -> FilePath -> ConduitT () CheckResult IO () check formatter filepath = enumeratePath filepath .| mapMC readSourceFile .| mapC (checkFormatting formatter) readSourceFile :: FilePath -> IO HaskellSource readSourceFile filepath = HaskellSource filepath <$> readFile filepath checkFormatting :: Formatter -> HaskellSource -> CheckResult checkFormatting (Formatter doFormat) source = case doFormat source of Left err -> InvalidCheckResult source err Right reformatted -> CheckResult source reformatted defaultFormatter :: IO Formatter defaultFormatter = mconcat <$> (autoSettings >>= formatters) wasReformatted :: HaskellSource -> Reformatted -> Bool wasReformatted source reformatted = hasSuggestions reformatted || sourceChanged source reformatted sourceChanged :: HaskellSource -> Reformatted -> Bool sourceChanged source reformatted = source /= reformattedSource reformatted hasSuggestions :: Reformatted -> Bool hasSuggestions reformatted = not (null (suggestions reformatted))
danstiner/hfmt
src/Language/Haskell/Format/Utilities.hs
mit
3,400
0
12
602
904
457
447
81
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.ProcessingInstruction (js_getTarget, getTarget, js_getSheet, getSheet, ProcessingInstruction, castToProcessingInstruction, gTypeProcessingInstruction) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"target\"]" js_getTarget :: JSRef ProcessingInstruction -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/ProcessingInstruction.target Mozilla ProcessingInstruction.target documentation> getTarget :: (MonadIO m, FromJSString result) => ProcessingInstruction -> m (Maybe result) getTarget self = liftIO (fromMaybeJSString <$> (js_getTarget (unProcessingInstruction self))) foreign import javascript unsafe "$1[\"sheet\"]" js_getSheet :: JSRef ProcessingInstruction -> IO (JSRef StyleSheet) -- | <https://developer.mozilla.org/en-US/docs/Web/API/ProcessingInstruction.sheet Mozilla ProcessingInstruction.sheet documentation> getSheet :: (MonadIO m) => ProcessingInstruction -> m (Maybe StyleSheet) getSheet self = liftIO ((js_getSheet (unProcessingInstruction self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/ProcessingInstruction.hs
mit
1,968
12
11
273
483
293
190
35
1
{-# LANGUAGE FlexibleContexts #-} module Main ( hist, main ) where -- | Global imports import Data.List import System.Random import System.Environment ( getArgs ) -- | Local imports import Calculus import Combinatorics import Distribution import Geometry import Random import Statistics import Units import Vec2 import Vec3 -- | Generate histogram -- | xs - Input list -- | n - Number of buckets hist xs n = [floor (min (n - 1)) ((x - l) / i) | x <- xs] where s = sort xs l = head s r = last s range = r - l i = range / n -- | Main entry point main :: IO () main = do [n] <- getArgs g <- getStdGen print n print . take (read n :: Int) $ rand (0 :: Float) (1 :: Float) g
korczis/haskell-world
src/cli/Main.hs
mit
717
0
11
187
243
136
107
29
1
module Proxy.Types.TechTypes where -- | The datatype containing all units special abilites data TechType = Stimpacks | Lockdown | EMPShockwave | SpiderMines | ScannerSweep | TankSiegeMode | DefensiveMatrix | Irradiate | YamatoGun | CloakingField | PersonnelCloaking | Burrowing | Infestation | SpawnBroodlings | DarkSwarm | Plague | Consume | Ensnare | Parasite | PsionicStorm | Hallucination | Recall | StasisField | ArchonWarp | Restoration | DisruptionWeb | UnusedTech26 | MindControl | DarkArchonMeld | Feedback | OpticalFlare | Maelstorm | LurkerAspect | UnusedTech33 | Healing | UnusedTech35 | UnusedTech36 | UnusedTech37 | UnusedTech38 | UnusedTech39 | UnusedTech40 | UnusedTech41 | UnusedTech42 | UnusedTech43 | NoneTechType | UnknownTechType | NuclearStrike deriving (Enum, Show)
mapinguari/SC_HS_Proxy
src/Proxy/Types/TechTypes.hs
mit
1,433
0
6
755
164
108
56
48
0
{-# LANGUAGE CPP #-} -- Just exists due to TH stage restriction... The actual testing TH code -- is in "Data.Store.TH". module Data.StoreSpec.TH where verbose :: Bool verbose = #if VERBOSE_TEST True #else False #endif
fpco/store
test/Data/StoreSpec/TH.hs
mit
228
0
4
45
23
17
6
5
1
----------------------------------------------------------------------------- -- -- Module : Language.PureScript.Kinds -- Copyright : (c) Phil Freeman 2013 -- License : MIT -- -- Maintainer : Phil Freeman <[email protected]> -- Stability : experimental -- Portability : -- -- | -- ----------------------------------------------------------------------------- {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} module Language.PureScript.Kinds where import Prelude () import Prelude.Compat import Data.Data import qualified Data.Aeson.TH as A -- | -- The data type of kinds -- data Kind -- | -- Unification variable of type Kind -- = KUnknown Int -- | -- The kind of types -- | Star -- | -- The kind of effects -- | Bang -- | -- Kinds for labelled, unordered rows without duplicates -- | Row Kind -- | -- Function kinds -- | FunKind Kind Kind deriving (Show, Read, Eq, Ord, Data, Typeable) $(A.deriveJSON A.defaultOptions ''Kind) everywhereOnKinds :: (Kind -> Kind) -> Kind -> Kind everywhereOnKinds f = go where go (Row k1) = f (Row (go k1)) go (FunKind k1 k2) = f (FunKind (go k1) (go k2)) go other = f other everywhereOnKindsM :: (Functor m, Applicative m, Monad m) => (Kind -> m Kind) -> Kind -> m Kind everywhereOnKindsM f = go where go (Row k1) = (Row <$> go k1) >>= f go (FunKind k1 k2) = (FunKind <$> go k1 <*> go k2) >>= f go other = f other everythingOnKinds :: (r -> r -> r) -> (Kind -> r) -> Kind -> r everythingOnKinds (<>) f = go where go k@(Row k1) = f k <> go k1 go k@(FunKind k1 k2) = f k <> go k1 <> go k2 go other = f other
michaelficarra/purescript
src/Language/PureScript/Kinds.hs
mit
1,651
0
11
366
502
275
227
29
3