code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE UndecidableInstances, FlexibleInstances, TypeOperators, MultiParamTypeClasses, FunctionalDependencies, DatatypeContexts #-} -- This one crashed GHC 6.3 due to an error in TcSimplify.add_ors module Foo where data Zero = Zero deriving Show data One = One deriving Show infixl 9 :@ data (Number a, Digit b) => a :@ b = a :@ b deriving Show class Digit a instance Digit Zero instance Digit One class Number a instance Number Zero instance Number One instance (Number a, Digit b) => Number (a :@ b) --- Pretty printing of numbers --- class PrettyNum a where prettyNum :: a -> String instance PrettyNum Zero where prettyNum _ = "0" instance PrettyNum One where prettyNum _ = "1" instance (Number a, Digit b, PrettyNum a, PrettyNum b) => PrettyNum (a :@ b) where prettyNum ~(a:@b) = prettyNum a ++ prettyNum b --- Digit addition --- class (Number a, Digit b, Number c) => AddDigit a b c | a b -> c where addDigit :: a -> b -> c addDigit = undefined instance Number a => AddDigit a Zero a instance AddDigit Zero One One instance AddDigit One One (One:@Zero) instance Number a => AddDigit (a:@Zero) One (a:@One) instance AddDigit a One a' => AddDigit (a:@One) One (a':@Zero) --- Addition --- class (Number a, Number b, Number c) => Add a b c | a b -> c where add :: a -> b -> c add = undefined instance Number n => Add n Zero n instance Add Zero One One instance Add One One (One:@One) instance Number n => Add (n:@Zero) One (n:@One) instance AddDigit n One r' => Add (n:@One) One (r':@Zero) instance (Number n1, Digit d1, Number n2, Digit n2 ,Add n1 n2 nr', AddDigit (d1:@nr') d2 r) => Add (n1:@d1) (n2:@d2) r foo = show $ add (One:@Zero) (One:@One) -- Add (One:@Zero) (One:@One) c, Show c -- ==> Number One, Digit Zero, Number One, Digit One -- Add One One nr', AddDigit (Zero:@nr') One c, Show c -- -- ==> Add One One nr', AddDigit (Zero:@nr') One c, Show c -- -- ==> Add One One (One:@One), AddDigit (Zero:@(One:@One)) One c, Show c -- -- ==> AddDigit (Zero:@(One:@One)) One c, Show c
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail133.hs
bsd-3-clause
2,142
0
9
512
718
374
344
-1
-1
module SimpleJSON where data JValue = JString String | JNumber Double | JBool Bool | JNull | JObject [(String, JValue)] | JArray [JValue] deriving (Eq, Ord, Show) getString :: JValue -> Maybe String getString (JString s) = Just s getString _ = Nothing getInt :: JValue -> Maybe Int getInt (JNumber n) = Just (truncate n) getInt _ = Nothing getDouble :: JValue -> Maybe Double getDouble (JNumber n) = Just n getDouble _ = Nothing getBool :: JValue -> Maybe Bool getBool (JBool b) = Just b getBool _ = Nothing getObject :: JValue -> Maybe [(String, JValue)] getObject (JObject o) = Just o getObject _ = Nothing getArray :: JValue -> Maybe [JValue] getArray (JArray a) = Just a getArray _ = Nothing isNull v = v == JNull
pauldoo/scratch
RealWorldHaskell/ch05/mypretty/SimpleJSON.hs
isc
784
0
8
197
315
163
152
28
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Kata.AdditionCommutes ( plusCommutes ) where import Kata.AdditionCommutes.Definitions ( Z, S , Natural(..), Equal(..) , (:+:)) -- These are some lemmas that may be helpful. -- They will *not* be tested, so rename them -- if you so desire. Good luck! -- | For any n, n = n. reflexive :: Natural n -> Equal n n reflexive NumZ = EqlZ reflexive (NumS n) = EqlS (reflexive n) -- | if a = b, then b = a. symmetric :: Equal a b -> Equal b a symmetric EqlZ = EqlZ symmetric (EqlS a) = EqlS (symmetric a) -- | if a = b and b = c, then a = c. transitive :: Equal a b -> Equal b c -> Equal a c transitive EqlZ EqlZ = EqlZ transitive (EqlS a) (EqlS b) = EqlS (transitive a b) rightS :: Natural a -> Natural b -> Equal (S (a :+: b)) (a :+: S b) rightS NumZ b = EqlS (reflexive b) rightS (NumS a) b = EqlS (rightS a b) -- This is the proof that the kata requires. -- | a + b = b + a plusCommutes :: Natural a -> Natural b -> Equal (a :+: b) (b :+: a) plusCommutes NumZ NumZ = EqlZ plusCommutes NumZ (NumS b) = EqlS (plusCommutes NumZ b) plusCommutes (NumS a) b = transitive (EqlS (plusCommutes a b)) (rightS b a) -- For reference, here are the definitions, if you -- want to copy them into an IDE: {- -- | The natural numbers, encoded in types. data Z data S n -- | Predicate describing natural numbers. -- | This allows us to reason with `Nat`s. data Natural :: * -> * where NumZ :: Natural Z NumS :: Natural n -> Natural (S n) -- | Predicate describing equality of natural numbers. data Equal :: * -> * -> * where EqlZ :: Equal Z Z EqlS :: Equal n m -> Equal (S n) (S m) -- | Peano definition of addition. type family (:+:) (n :: *) (m :: *) :: * type instance Z :+: m = m type instance S n :+: m = S (n :+: m) -}
delta4d/codewars
kata/a-plus-b-equals-b-plus-a-prove-it/AdditionCommutes.hs
mit
1,839
0
11
425
438
228
210
25
1
module Unison.Test.Cache where import EasyTest import Control.Monad import Control.Concurrent.STM import Control.Concurrent.Async import qualified U.Util.Cache as Cache test :: Test () test = scope "util.cache" $ tests [ scope "ex1" $ fits Cache.cache , scope "ex2" $ fits (Cache.semispaceCache n) , scope "ex3" $ doesn'tFit (Cache.semispaceCache n) , scope "ex4" $ do replicateM_ 10 $ concurrent (Cache.semispaceCache n) ok ] where n :: Word n = 1000 -- This checks that items properly expire from the cache doesn'tFit mkCache = do cache <- io $ mkCache misses <- io $ newTVarIO 0 let f x = do atomically $ modifyTVar misses (+1) pure x -- populate the cache, all misses (n*2), but first 1-n will have expired by the end results1 <- io $ traverse (Cache.apply cache f) [1..n*2] -- should be half hits, so an additional `n` misses results2 <- io $ traverse (Cache.apply cache f) (reverse [1..n*2]) misses <- io $ readTVarIO misses expect' (results1 == [1..n*2]) expect' (results2 == reverse [1..n*2]) expect (misses == n * 3) -- This checks the simple case that everything fits in the cache fits mkCache = do cache <- io $ mkCache misses <- io $ newTVarIO 0 let f x = do atomically $ modifyTVar misses (+1) pure x -- populate the cache results1 <- io $ traverse (Cache.apply cache f) [1..n] -- should be all hits results2 <- io $ traverse (Cache.apply cache f) [1..n] misses <- io $ readTVarIO misses expect' (results1 == [1..n]) expect' (results2 == [1..n]) expect (misses == n) -- A simple smoke test of concurrent access. The cache doesn't -- try to linearize all reads / writes so the number of misses -- during concurrent access is unpredictable, but once the cache is -- fully populated, concurrent reads should generate no further misses concurrent mkCache = do cache <- io $ mkCache misses <- io $ newTVarIO 0 let f x = do atomically $ modifyTVar misses (+1) pure x -- we're populating the cache in parallel results1 <- io $ async $ traverse (Cache.apply cache f) [1 .. (n `div` 2)] results2 <- io $ async $ traverse (Cache.apply cache f) [(n `div` 2 + 1) .. n] (results1, results2) <- io $ waitBoth results1 results2 -- now the cache should be fully populated, so no further misses misses1 <- io $ readTVarIO misses -- these should be all hits results3 <- io $ async $ traverse (Cache.apply cache f) [1 .. (n `div` 2)] results4 <- io $ async $ traverse (Cache.apply cache f) [(n `div` 2 + 1) .. n] (results3, results4) <- io $ waitBoth results3 results4 misses2 <- io $ readTVarIO misses expect' (results1 ++ results2 == [1..n]) expect' (results3 ++ results4 == [1..n]) expect' (misses1 == misses2)
unisonweb/platform
parser-typechecker/tests/Unison/Test/Cache.hs
mit
2,988
0
16
838
974
485
489
57
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.Node (getRootNode, getRootNode_, hasChildNodes, hasChildNodes_, normalize, cloneNode, cloneNode_, isEqualNode, isEqualNode_, isSameNode, isSameNode_, compareDocumentPosition, compareDocumentPosition_, contains, contains_, lookupPrefix, lookupPrefix_, lookupPrefixUnsafe, lookupPrefixUnchecked, lookupNamespaceURI, lookupNamespaceURI_, lookupNamespaceURIUnsafe, lookupNamespaceURIUnchecked, isDefaultNamespace, isDefaultNamespace_, insertBefore, insertBefore_, appendChild, appendChild_, replaceChild, replaceChild_, removeChild, removeChild_, pattern ELEMENT_NODE, pattern ATTRIBUTE_NODE, pattern TEXT_NODE, pattern CDATA_SECTION_NODE, pattern ENTITY_REFERENCE_NODE, pattern ENTITY_NODE, pattern PROCESSING_INSTRUCTION_NODE, pattern COMMENT_NODE, pattern DOCUMENT_NODE, pattern DOCUMENT_TYPE_NODE, pattern DOCUMENT_FRAGMENT_NODE, pattern NOTATION_NODE, pattern DOCUMENT_POSITION_DISCONNECTED, pattern DOCUMENT_POSITION_PRECEDING, pattern DOCUMENT_POSITION_FOLLOWING, pattern DOCUMENT_POSITION_CONTAINS, pattern DOCUMENT_POSITION_CONTAINED_BY, pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, getNodeType, getNodeName, getBaseURI, getIsConnected, getOwnerDocument, getOwnerDocumentUnsafe, getOwnerDocumentUnchecked, getParentNode, getParentNodeUnsafe, getParentNodeUnchecked, getParentElement, getParentElementUnsafe, getParentElementUnchecked, getChildNodes, getFirstChild, getFirstChildUnsafe, getFirstChildUnchecked, getLastChild, getLastChildUnsafe, getLastChildUnchecked, getPreviousSibling, getPreviousSiblingUnsafe, getPreviousSiblingUnchecked, getNextSibling, getNextSiblingUnsafe, getNextSiblingUnchecked, setNodeValue, getNodeValue, getNodeValueUnsafe, getNodeValueUnchecked, setTextContent, getTextContent, getTextContentUnsafe, getTextContentUnchecked, Node(..), gTypeNode, IsNode, toNode) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.getRootNode Mozilla Node.getRootNode documentation> getRootNode :: (MonadDOM m, IsNode self) => self -> Maybe GetRootNodeOptions -> m Node getRootNode self options = liftDOM (((toNode self) ^. jsf "getRootNode" [toJSVal options]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.getRootNode Mozilla Node.getRootNode documentation> getRootNode_ :: (MonadDOM m, IsNode self) => self -> Maybe GetRootNodeOptions -> m () getRootNode_ self options = liftDOM (void ((toNode self) ^. jsf "getRootNode" [toJSVal options])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.hasChildNodes Mozilla Node.hasChildNodes documentation> hasChildNodes :: (MonadDOM m, IsNode self) => self -> m Bool hasChildNodes self = liftDOM (((toNode self) ^. jsf "hasChildNodes" ()) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.hasChildNodes Mozilla Node.hasChildNodes documentation> hasChildNodes_ :: (MonadDOM m, IsNode self) => self -> m () hasChildNodes_ self = liftDOM (void ((toNode self) ^. jsf "hasChildNodes" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.normalize Mozilla Node.normalize documentation> normalize :: (MonadDOM m, IsNode self) => self -> m () normalize self = liftDOM (void ((toNode self) ^. jsf "normalize" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode Mozilla Node.cloneNode documentation> cloneNode :: (MonadDOM m, IsNode self) => self -> Bool -> m Node cloneNode self deep = liftDOM (((toNode self) ^. jsf "cloneNode" [toJSVal deep]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode Mozilla Node.cloneNode documentation> cloneNode_ :: (MonadDOM m, IsNode self) => self -> Bool -> m () cloneNode_ self deep = liftDOM (void ((toNode self) ^. jsf "cloneNode" [toJSVal deep])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isEqualNode Mozilla Node.isEqualNode documentation> isEqualNode :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool isEqualNode self other = liftDOM (((toNode self) ^. jsf "isEqualNode" [toJSVal other]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isEqualNode Mozilla Node.isEqualNode documentation> isEqualNode_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () isEqualNode_ self other = liftDOM (void ((toNode self) ^. jsf "isEqualNode" [toJSVal other])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isSameNode Mozilla Node.isSameNode documentation> isSameNode :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool isSameNode self other = liftDOM (((toNode self) ^. jsf "isSameNode" [toJSVal other]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isSameNode Mozilla Node.isSameNode documentation> isSameNode_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () isSameNode_ self other = liftDOM (void ((toNode self) ^. jsf "isSameNode" [toJSVal other])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition Mozilla Node.compareDocumentPosition documentation> compareDocumentPosition :: (MonadDOM m, IsNode self, IsNode other) => self -> other -> m Word compareDocumentPosition self other = liftDOM (round <$> (((toNode self) ^. jsf "compareDocumentPosition" [toJSVal other]) >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition Mozilla Node.compareDocumentPosition documentation> compareDocumentPosition_ :: (MonadDOM m, IsNode self, IsNode other) => self -> other -> m () compareDocumentPosition_ self other = liftDOM (void ((toNode self) ^. jsf "compareDocumentPosition" [toJSVal other])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.contains Mozilla Node.contains documentation> contains :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m Bool contains self other = liftDOM (((toNode self) ^. jsf "contains" [toJSVal other]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.contains Mozilla Node.contains documentation> contains_ :: (MonadDOM m, IsNode self, IsNode other) => self -> Maybe other -> m () contains_ self other = liftDOM (void ((toNode self) ^. jsf "contains" [toJSVal other])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation> lookupPrefix :: (MonadDOM m, IsNode self, ToJSString namespaceURI, FromJSString result) => self -> Maybe namespaceURI -> m (Maybe result) lookupPrefix self namespaceURI = liftDOM (((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation> lookupPrefix_ :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m () lookupPrefix_ self namespaceURI = liftDOM (void ((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation> lookupPrefixUnsafe :: (MonadDOM m, IsNode self, ToJSString namespaceURI, HasCallStack, FromJSString result) => self -> Maybe namespaceURI -> m result lookupPrefixUnsafe self namespaceURI = liftDOM ((((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation> lookupPrefixUnchecked :: (MonadDOM m, IsNode self, ToJSString namespaceURI, FromJSString result) => self -> Maybe namespaceURI -> m result lookupPrefixUnchecked self namespaceURI = liftDOM (((toNode self) ^. jsf "lookupPrefix" [toJSVal namespaceURI]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation> lookupNamespaceURI :: (MonadDOM m, IsNode self, ToJSString prefix, FromJSString result) => self -> Maybe prefix -> m (Maybe result) lookupNamespaceURI self prefix = liftDOM (((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation> lookupNamespaceURI_ :: (MonadDOM m, IsNode self, ToJSString prefix) => self -> Maybe prefix -> m () lookupNamespaceURI_ self prefix = liftDOM (void ((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation> lookupNamespaceURIUnsafe :: (MonadDOM m, IsNode self, ToJSString prefix, HasCallStack, FromJSString result) => self -> Maybe prefix -> m result lookupNamespaceURIUnsafe self prefix = liftDOM ((((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation> lookupNamespaceURIUnchecked :: (MonadDOM m, IsNode self, ToJSString prefix, FromJSString result) => self -> Maybe prefix -> m result lookupNamespaceURIUnchecked self prefix = liftDOM (((toNode self) ^. jsf "lookupNamespaceURI" [toJSVal prefix]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isDefaultNamespace Mozilla Node.isDefaultNamespace documentation> isDefaultNamespace :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m Bool isDefaultNamespace self namespaceURI = liftDOM (((toNode self) ^. jsf "isDefaultNamespace" [toJSVal namespaceURI]) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isDefaultNamespace Mozilla Node.isDefaultNamespace documentation> isDefaultNamespace_ :: (MonadDOM m, IsNode self, ToJSString namespaceURI) => self -> Maybe namespaceURI -> m () isDefaultNamespace_ self namespaceURI = liftDOM (void ((toNode self) ^. jsf "isDefaultNamespace" [toJSVal namespaceURI])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore Mozilla Node.insertBefore documentation> insertBefore :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> Maybe child -> m Node insertBefore self node child = liftDOM (((toNode self) ^. jsf "insertBefore" [toJSVal node, toJSVal child]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore Mozilla Node.insertBefore documentation> insertBefore_ :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> Maybe child -> m () insertBefore_ self node child = liftDOM (void ((toNode self) ^. jsf "insertBefore" [toJSVal node, toJSVal child])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation> appendChild :: (MonadDOM m, IsNode self, IsNode node) => self -> node -> m Node appendChild self node = liftDOM (((toNode self) ^. jsf "appendChild" [toJSVal node]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation> appendChild_ :: (MonadDOM m, IsNode self, IsNode node) => self -> node -> m () appendChild_ self node = liftDOM (void ((toNode self) ^. jsf "appendChild" [toJSVal node])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.replaceChild Mozilla Node.replaceChild documentation> replaceChild :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> child -> m Node replaceChild self node child = liftDOM (((toNode self) ^. jsf "replaceChild" [toJSVal node, toJSVal child]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.replaceChild Mozilla Node.replaceChild documentation> replaceChild_ :: (MonadDOM m, IsNode self, IsNode node, IsNode child) => self -> node -> child -> m () replaceChild_ self node child = liftDOM (void ((toNode self) ^. jsf "replaceChild" [toJSVal node, toJSVal child])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation> removeChild :: (MonadDOM m, IsNode self, IsNode child) => self -> child -> m Node removeChild self child = liftDOM (((toNode self) ^. jsf "removeChild" [toJSVal child]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation> removeChild_ :: (MonadDOM m, IsNode self, IsNode child) => self -> child -> m () removeChild_ self child = liftDOM (void ((toNode self) ^. jsf "removeChild" [toJSVal child])) pattern ELEMENT_NODE = 1 pattern ATTRIBUTE_NODE = 2 pattern TEXT_NODE = 3 pattern CDATA_SECTION_NODE = 4 pattern ENTITY_REFERENCE_NODE = 5 pattern ENTITY_NODE = 6 pattern PROCESSING_INSTRUCTION_NODE = 7 pattern COMMENT_NODE = 8 pattern DOCUMENT_NODE = 9 pattern DOCUMENT_TYPE_NODE = 10 pattern DOCUMENT_FRAGMENT_NODE = 11 pattern NOTATION_NODE = 12 pattern DOCUMENT_POSITION_DISCONNECTED = 1 pattern DOCUMENT_POSITION_PRECEDING = 2 pattern DOCUMENT_POSITION_FOLLOWING = 4 pattern DOCUMENT_POSITION_CONTAINS = 8 pattern DOCUMENT_POSITION_CONTAINED_BY = 16 pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32 -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType Mozilla Node.nodeType documentation> getNodeType :: (MonadDOM m, IsNode self) => self -> m Word getNodeType self = liftDOM (round <$> (((toNode self) ^. js "nodeType") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeName Mozilla Node.nodeName documentation> getNodeName :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getNodeName self = liftDOM (((toNode self) ^. js "nodeName") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.baseURI Mozilla Node.baseURI documentation> getBaseURI :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getBaseURI self = liftDOM (((toNode self) ^. js "baseURI") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isConnected Mozilla Node.isConnected documentation> getIsConnected :: (MonadDOM m, IsNode self) => self -> m Bool getIsConnected self = liftDOM (((toNode self) ^. js "isConnected") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> getOwnerDocument :: (MonadDOM m, IsNode self) => self -> m (Maybe Document) getOwnerDocument self = liftDOM (((toNode self) ^. js "ownerDocument") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> getOwnerDocumentUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Document getOwnerDocumentUnsafe self = liftDOM ((((toNode self) ^. js "ownerDocument") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation> getOwnerDocumentUnchecked :: (MonadDOM m, IsNode self) => self -> m Document getOwnerDocumentUnchecked self = liftDOM (((toNode self) ^. js "ownerDocument") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation> getParentNode :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getParentNode self = liftDOM (((toNode self) ^. js "parentNode") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation> getParentNodeUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getParentNodeUnsafe self = liftDOM ((((toNode self) ^. js "parentNode") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation> getParentNodeUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getParentNodeUnchecked self = liftDOM (((toNode self) ^. js "parentNode") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation> getParentElement :: (MonadDOM m, IsNode self) => self -> m (Maybe Element) getParentElement self = liftDOM (((toNode self) ^. js "parentElement") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation> getParentElementUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Element getParentElementUnsafe self = liftDOM ((((toNode self) ^. js "parentElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation> getParentElementUnchecked :: (MonadDOM m, IsNode self) => self -> m Element getParentElementUnchecked self = liftDOM (((toNode self) ^. js "parentElement") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.childNodes Mozilla Node.childNodes documentation> getChildNodes :: (MonadDOM m, IsNode self) => self -> m NodeList getChildNodes self = liftDOM (((toNode self) ^. js "childNodes") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation> getFirstChild :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getFirstChild self = liftDOM (((toNode self) ^. js "firstChild") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation> getFirstChildUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getFirstChildUnsafe self = liftDOM ((((toNode self) ^. js "firstChild") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation> getFirstChildUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getFirstChildUnchecked self = liftDOM (((toNode self) ^. js "firstChild") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation> getLastChild :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getLastChild self = liftDOM (((toNode self) ^. js "lastChild") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation> getLastChildUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getLastChildUnsafe self = liftDOM ((((toNode self) ^. js "lastChild") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation> getLastChildUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getLastChildUnchecked self = liftDOM (((toNode self) ^. js "lastChild") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation> getPreviousSibling :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getPreviousSibling self = liftDOM (((toNode self) ^. js "previousSibling") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation> getPreviousSiblingUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getPreviousSiblingUnsafe self = liftDOM ((((toNode self) ^. js "previousSibling") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation> getPreviousSiblingUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getPreviousSiblingUnchecked self = liftDOM (((toNode self) ^. js "previousSibling") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> getNextSibling :: (MonadDOM m, IsNode self) => self -> m (Maybe Node) getNextSibling self = liftDOM (((toNode self) ^. js "nextSibling") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> getNextSiblingUnsafe :: (MonadDOM m, IsNode self, HasCallStack) => self -> m Node getNextSiblingUnsafe self = liftDOM ((((toNode self) ^. js "nextSibling") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation> getNextSiblingUnchecked :: (MonadDOM m, IsNode self) => self -> m Node getNextSiblingUnchecked self = liftDOM (((toNode self) ^. js "nextSibling") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation> setNodeValue :: (MonadDOM m, IsNode self, ToJSString val) => self -> Maybe val -> m () setNodeValue self val = liftDOM ((toNode self) ^. jss "nodeValue" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation> getNodeValue :: (MonadDOM m, IsNode self, FromJSString result) => self -> m (Maybe result) getNodeValue self = liftDOM (((toNode self) ^. js "nodeValue") >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation> getNodeValueUnsafe :: (MonadDOM m, IsNode self, HasCallStack, FromJSString result) => self -> m result getNodeValueUnsafe self = liftDOM ((((toNode self) ^. js "nodeValue") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation> getNodeValueUnchecked :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getNodeValueUnchecked self = liftDOM (((toNode self) ^. js "nodeValue") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation> setTextContent :: (MonadDOM m, IsNode self, ToJSString val) => self -> Maybe val -> m () setTextContent self val = liftDOM ((toNode self) ^. jss "textContent" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation> getTextContent :: (MonadDOM m, IsNode self, FromJSString result) => self -> m (Maybe result) getTextContent self = liftDOM (((toNode self) ^. js "textContent") >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation> getTextContentUnsafe :: (MonadDOM m, IsNode self, HasCallStack, FromJSString result) => self -> m result getTextContentUnsafe self = liftDOM ((((toNode self) ^. js "textContent") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation> getTextContentUnchecked :: (MonadDOM m, IsNode self, FromJSString result) => self -> m result getTextContentUnchecked self = liftDOM (((toNode self) ^. js "textContent") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/Node.hs
mit
26,991
0
14
5,352
6,086
3,185
2,901
-1
-1
module Control.Flower.Applicative ( module Control.Flower.Applicative.Lazy, module Control.Flower.Applicative.Strict ) where import Control.Flower.Applicative.Lazy import Control.Flower.Applicative.Strict
expede/flower
src/Control/Flower/Applicative.hs
mit
210
0
5
18
39
28
11
5
0
import Data.List (find) import Data.Maybe (fromMaybe) --euler's formula for Pythagorean triples: a = m^2 - n^2, b = 2mn, c = m^2 + n^2 pythTriples = [(m * m - n * n, 2 * m * n, m * m + n * n) | m <- [1..], n <- [1..m], m /= n ] tuple3product :: (Num a) => (a, a, a) -> a tuple3product (a, b, c) = a * b * c solution = tuple3product $ fromMaybe (0, 0, 0) (find (\(a, b, c) -> a + b + c == 1000) pythTriples)
DylanSp/Project-Euler-in-Haskell
prob9/euler.hs
mit
410
0
13
100
215
121
94
6
1
module WoofToScheme (emitScheme) where import Monad import System.Environment import WoofParse -- Environment emitScheme :: WoofAST -> IO () emitScheme (ASTStatementList (statement:rest)) = do emitScheme statement emitScheme $ ASTStatementList rest emitScheme (ASTStatementList []) = do return () emitScheme (ASTStatement a) = do emitScheme a putStr "\n" emitScheme (ASTIdent s) = do putStr $ "var_" ++ s emitScheme (ASTAssignment (i, e)) = do putStr $ "(define " emitScheme i emitScheme $ e putStr ")" emitScheme (ASTConstant s) = do putStr $ "(constant-by-name \"" ++ s++ "\")" emitScheme (ASTString s) = do putStr $ "(woof-string-instance \"" ++ (content s) ++ "\")" where content t = drop 1 (take ((length t) - 1) t) emitScheme (ASTBlock ((ASTFormalParams params), statements)) = do putStr $ "(woof-block-instance (lambda (" emitList params putStr ")" emitScheme statements putStr "))" where emitList (first:rest) = do emitScheme first putStr " " emitList rest emitList otherwise = do putStr "" emitScheme (ASTList list) = do putStr $ "(woof-list-instance (list " emitList list putStr "))" where emitList (first:rest) = do emitScheme first putStr " " emitList rest emitList otherwise = do putStr "" emitScheme (ASTInlineScheme s) = do putStr $ content s where content t = drop 2 (take ((length t) - 1) t) emitScheme (ASTInteger i) = do putStr $ "(woof-integer-instance " ++ (show i) ++ ")" emitScheme func@(ASTFuncCall funcList) = do putStr $ "(woof-call-function \"" ++ (functionName func) ++ "\" (list " emitArgList funcList putStr "))" where emitArgList ((key,val):rest) = do emitScheme val putStr " " emitArgList rest emitArgList otherwise = do putStr "" emitScheme ast = do putStrLn $ show ast functionName :: WoofAST -> String functionName (ASTFuncCall keyValPairs) = foldl sumKey "" keyValPairs where sumKey sumString (ASTFuncKey key,val) = sumString ++ key
aemoncannon/woof
compiler/woof_to_scheme.hs
mit
2,864
0
13
1,278
754
353
401
48
4
module ImportSort.SortSpec where import qualified ImportSort.Sort as S import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = parallel $ describe "sort" $ do it "sorts values correctly" $ do let string = "import qualified Data.List as L\n\ \import System.IO\n\ \import Data.List ((++))\n\ \import Data.Char (isAlpha)\n\ \import qualified Data.Map.Strict as Map\n" S.sortImport string `shouldBe` "import Data.Char (isAlpha)\n\ \import Data.List ((++))\n\ \import qualified Data.List as L\n\ \import qualified Data.Map.Strict as Map\n\ \import System.IO" it "doesn't introduce a column for 'qualified' if none are present" $ do let string = "import Data.List ((++))\n\ \import Data.Bifunctor (first)\n" S.sortImport string `shouldBe` "import Data.Bifunctor (first)\n\ \import Data.List ((++))" it "retains newlines as separators" $ do let string = "import Data.Maybe (catMaybes)\n\ \import Data.List ((++))\n\n\ \import qualified Data.Bifunctor as BF\n" S.sortImport string `shouldBe` "import Data.List ((++))\n\ \import Data.Maybe (catMaybes)\n\n\ \import qualified Data.Bifunctor as BF" it "allows for full file context" $ do let string = "module Awesome where\n\n\ \import Data.Maybe (catMaybes)\n\ \import Data.List ((++))\n\n\ \import qualified Data.Bifunctor as BF\n\n\ \link :: Int\n\ \link = 1\n\n\ \importPrefixedFunction :: Int\n\ \importPrefixedFunction = 2\n" S.sortImport string `shouldBe` "module Awesome where\n\n\ \import Data.List ((++))\n\ \import Data.Maybe (catMaybes)\n\n\ \import qualified Data.Bifunctor as BF\n\n\ \link :: Int\n\ \link = 1\n\n\ \importPrefixedFunction :: Int\n\ \importPrefixedFunction = 2" it "returns the original string if parsing failed" $ do let string = "import qualified Data.List as L\nfoo" S.sortImport string `shouldBe` string
joshuaclayton/import-sort
test/ImportSort/SortSpec.hs
mit
2,854
0
13
1,294
223
108
115
27
1
{-# LANGUAGE OverloadedStrings #-} module Network.API.Shopify.Types.Metafield ( Metafield(..) , MetafieldId(..) ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad (mzero) import Data.Aeson ( (.:) , (.:?) , (.=) , FromJSON(parseJSON) , object , Value(Object) , ToJSON(toJSON) ) import qualified Data.Aeson as A import Data.Maybe (catMaybes) import Data.Text (Text) import Data.Time (UTCTime) import Network.API.Shopify.Types.MetafieldType (MetafieldType) newtype MetafieldId = MetafieldId Int deriving (Eq, Ord, Show) data Metafield = Metafield { metafieldCreatedAt :: UTCTime , metafieldDescription :: Maybe Text , metafieldId :: MetafieldId , metafieldKey :: Text , metafieldNamespace :: Text , metafieldOwnerId :: Integer , metafieldOwnerResources :: Text , metafieldValue :: Text , metafieldType :: MetafieldType , metafieldUpdatedAt :: UTCTime } deriving (Eq, Ord, Show) instance FromJSON Metafield where parseJSON(Object v) = Metafield <$> v .: "created_at" <*> v .:? "description" <*> (MetafieldId <$> v .: "id") <*> v .: "key" <*> v .: "namespace" <*> v .: "owner_id" <*> v .: "owner_resource" <*> v .: "value" <*> v .: "value_type" <*> v .: "updated_at" parseJSON _ = mzero instance ToJSON Metafield where toJSON (Metafield createdAt description (MetafieldId metaId) key namespace ownerId ownerResource value valueType updatedAt ) = object $ [ "created_at" .= createdAt , "id" .= metaId , "key" .= key , "namespace" .= namespace , "owner_id" .= ownerId , "ownerResource" .= ownerResource , "value" .= value , "value_type" .= valueType , "updated_at" .= updatedAt ] ++ catMaybes [ ("description" .=) . A.String <$> description ]
aaronlevin/haskell-shopify
src/Network/API/Shopify/Types/Metafield.hs
mit
3,139
0
24
1,717
514
303
211
64
0
{-# OPTIONS -fglasgow-exts #-} ------------------------------------------------------------------------------- -- | -- Module : Timeout -- Copyright : (c) The University of Glasgow 2007 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable -- -- Attach a timeout event to arbitrary 'IO' computations. -- ------------------------------------------------------------------------------- module Timeout ( timeout ) where #if __GLASGOW_HASKELL >= 608 import qualified System.Timeout as Timeout (timeout) #else import Prelude (IO, Ord((<)), Eq((==)), Int, (.), otherwise, fmap) import Data.Maybe (Maybe(..)) import Control.Monad (Monad(..), guard) import Control.Concurrent (forkIO, threadDelay, myThreadId, killThread) import Control.Exception (handleJust, throwDynTo, dynExceptions, bracket) import Data.Dynamic (Typeable, fromDynamic) import Data.Unique (Unique, newUnique) -- An internal type that is thrown as a dynamic exception to -- interrupt the running IO computation when the timeout has -- expired. data Timeout = Timeout Unique deriving (Eq, Typeable) -- |Wrap an 'IO' computation to time out and return @Nothing@ in case no result -- is available within @n@ microseconds (@1\/10^6@ seconds). In case a result -- is available before the timeout expires, @Just a@ is returned. A negative -- timeout interval means \"wait indefinitely\". When specifying long timeouts, -- be careful not to exceed @maxBound :: Int@. -- -- The design of this combinator was guided by the objective that @timeout n f@ -- should behave exactly the same as @f@ as long as @f@ doesn't time out. This -- means that @f@ has the same 'myThreadId' it would have without the timeout -- wrapper. Any exceptions @f@ might throw cancel the timeout and propagate -- further up. It also possible for @f@ to receive exceptions thrown to it by -- another thread. -- -- A tricky implementation detail is the question of how to abort an @IO@ -- computation. This combinator relies on asynchronous exceptions internally. -- The technique works very well for computations executing inside of the -- Haskell runtime system, but it doesn't work at all for non-Haskell code. -- Foreign function calls, for example, cannot be timed out with this -- combinator simply because an arbitrary C function cannot receive -- asynchronous exceptions. When @timeout@ is used to wrap an FFI call that -- blocks, no timeout event can be delivered until the FFI call returns, which -- pretty much negates the purpose of the combinator. In practice, however, -- this limitation is less severe than it may sound. Standard I\/O functions -- like 'System.IO.hGetBuf', 'System.IO.hPutBuf', Network.Socket.accept, or -- 'System.IO.hWaitForInput' appear to be blocking, but they really don't -- because the runtime system uses scheduling mechanisms like @select(2)@ to -- perform asynchronous I\/O, so it is possible to interrupt standard socket -- I\/O or file I\/O using this combinator. timeout :: Int -> IO a -> IO (Maybe a) timeout n f | n < 0 = fmap Just f | n == 0 = return Nothing | otherwise = do pid <- myThreadId ex <- fmap Timeout newUnique handleJust (\e -> dynExceptions e >>= fromDynamic >>= guard . (ex ==)) (\_ -> return Nothing) (bracket (forkIO (threadDelay n >> throwDynTo pid ex)) (killThread) (\_ -> fmap Just f)) #endif
msakai/folkung
Haskell/Timeout.hs
mit
3,605
0
5
727
39
32
7
22
1
-------------------------------------------------------------------------------- -- -- GAC Driver program -- -- (c) Tsitsimpis Ilias, 2011-2012 -- -------------------------------------------------------------------------------- module Main(main) where #include "config.h" import Lexer import Parser import SrcLoc import Outputable import TcMonad import SymbolTable import TypeCheck import ErrUtils import UnTypedAst import TypedAst (TAst) import DynFlags import ModeFlags import SysTools import LambdaLift import LlvmCodeGen import System.Exit import System.Environment import System.FilePath import Data.List import Data.Maybe import Control.Monad (when) import qualified Control.Exception as E import qualified Data.ByteString as BS import LLVM.Core -- --------------------------- -- Parse ModeFlags main :: IO () main = do -- 1. extract the -B flag from the args argv0 <- getArgs let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0 mbMinusB | null minusB_args = Nothing | otherwise = Just (drop 2 (last minusB_args)) let argv1' = map (mkGeneralLocated "no the commandline") argv1 -- 2. Parse the "mode" flags (--help, --info etc) case parseModeFlags argv1' of Left errs -> do printLocErrs errs exitFailure Right (mode, argv2, modeFlagWarnings) -> do printLocWarns modeFlagWarnings -- If all we wan to do is something like showing the -- version number then do it now, befor we start a GAC -- session etc. This makes getting basic information much -- more resilient. case mode of Left preStartupMode -> do case preStartupMode of ShowVersion -> showVersion ShowNumVersion -> putStrLn PROJECT_VERSION ShowSupportedExtensions -> showSupportedExtensions ShowGacUsage -> showGacUsage Print str -> putStrLn str Right postStartupMode -> do -- start our GAC session dflags0 <- initDynFlags defaultDynFlags dflags1 <- initSysTools mbMinusB dflags0 case postStartupMode of Left preLoadMode -> do case preLoadMode of ShowInfo -> showInfo dflags1 PrintWithDynFlags f -> putStrLn (f dflags1) Right postLoadMode -> do main' postLoadMode dflags1 argv2 -- --------------------------- -- Parse DynFlags main' :: PostLoadMode -> DynFlags -> [Located String] -> IO () main' postLoadMode dflags0 args = do -- Parse the "dynamic" arguments -- Leftover ones are presumably files case parseDynamicFlags dflags0 args of Left errs -> do printLocErrs errs exitFailure Right (dflags1, fileish_args, dynamicFlagWarnings) -> do printLocWarns dynamicFlagWarnings let normal_fileish_paths = map (normalise . unLoc) fileish_args (srcs, asms, objs) <- partition_args normal_fileish_paths [] [] [] if (sum $ map length [srcs, asms, objs]) == 0 then do printErrs [ progName ++ ": no input files", usageString ] exitFailure else do if length srcs <= 1 || xopt Opt_ExplicitMain dflags1 then main'' postLoadMode dflags1 srcs asms objs else do printErrs [ progName ++ ": cannot handle multiple source files" , "Use -XExplicitMain if you want to enable this" ] exitFailure -- --------------------------- -- Right now handle only one file main'' :: PostLoadMode -> DynFlags -> [String] -> [String] -> [String] -> IO () main'' postLoadMode dflags srcs asms objs = do -- firstly compile our source files into assembly code src_asms <- mapM (driverParse dflags) srcs case postLoadMode of StopBeforeAs -> do cleanAndExit True dflags StopBeforeLn -> do -- ------------------ -- Run the assembler let asms' = (reverse .catMaybes) src_asms ++ asms src_objs <- mapM (driverAssemble dflags) asms' let objs' = src_objs ++ objs if isNoLink (gacLink dflags) || null objs' then cleanAndExit True dflags else do -- ------------------------- -- Link into one executable driverLink dflags objs' cleanAndExit True dflags -- ------------------------------------------------------------------- -- Drive one source file through all the necessary compilation steps -- --------------------------- -- parse a file and call the typechecker driverParse :: DynFlags -> String -> IO (Maybe String) driverParse dflags filename = do let out_file = case outputDir dflags of Just od -> replaceDirectory filename od Nothing -> filename contents <- E.catch (BS.readFile filename) (\e -> do let _err = show (e :: E.IOException) printErrs [ progName ++ ": couldn't open `" ++ filename ++ "'" ] cleanAndExit False dflags ) let p_state = mkPState dflags contents (mkSrcLoc filename 1 1) case unP parser p_state of PFailed msg -> do printMessages dflags msg cleanAndExit False dflags POk p_state' luast -> do when (dopt Opt_D_dump_parsed dflags) $ printDumpedAst (dopt Opt_DumpToFile dflags) (replaceExtension out_file "dump-parsed") (unLoc luast) let p_messages = getPMessages p_state' if errorsFound p_messages || (warnsFound p_messages && dopt Opt_WarnIsError dflags) then do printMessages dflags p_messages cleanAndExit False dflags else do driverTypeCheck dflags p_messages out_file luast -- --------------------------- -- type check an UAst and call the codeGenerator -- the produced object file (if any) driverTypeCheck :: DynFlags -> Messages -> String -> (Located UAst) -> IO (Maybe String) driverTypeCheck dflags p_messages out_file luast = do let tc_state = mkTcState dflags predefinedTable case unTcM (typeCheckAst luast) tc_state of TcFailed msg -> do printMessages dflags msg cleanAndExit False dflags TcOk tc_state' tast -> do let tc_messages = (getTcMessages tc_state') tc_messages' = unionMessages p_messages tc_messages printMessages dflags tc_messages' if errorsFound tc_messages' || (warnsFound tc_messages && dopt Opt_WarnIsError dflags) then do -- errors found cleanAndExit False dflags else do -- check for `-fno-code' if isObjectTarget $ gacTarget dflags then do let protos = getTcProtos tc_state' driverCodeGen dflags out_file protos tast else do return Nothing -- --------------------------- -- generate llvm code and return -- the produced object file (if any) driverCodeGen :: DynFlags -> String -> [Prototype] -> TAst -> IO (Maybe String) driverCodeGen dflags out_file protos tast = do let tast' = lambdaLift protos tast llvm_module <- newModule defineModule llvm_module (compile tast') -- ----------------------- -- output llvm file let bc_file = replaceExtension out_file "bc" writeBitcodeToFile bc_file llvm_module -- ----------------------- -- optimize bytecode llvm -- don't specify anything if user has specified commands. We do this for -- opt but not llc since opt is very specifically for optimisation passes -- only, so if the user is passing us extra options we assume they know -- what they are doing and don't get in the way. let lo_opts = getOpts dflags opt_lo opt_lvl = optLevel dflags opt_Opts = ["", "-O1", "-O2", "-O3"] optFlag = if null lo_opts then [Option (opt_Opts !! opt_lvl)] else [] rlo <- runLlvmOpt dflags ([FileOption "" bc_file, Option "-o", FileOption "" bc_file] ++ optFlag ++ map Option lo_opts) when (not rlo) $ cleanAndExit False dflags when (not $ dopt Opt_KeepLlvmFiles dflags) $ addFilesToClean dflags [bc_file] -- ----------------------- -- generate assembly let asm_file = replaceExtension out_file "s" let lc_opts = getOpts dflags opt_lc llc_Opts = ["-O0", "-O1", "-O2", "-O3"] rll <- runLlvmLlc dflags ([Option (llc_Opts !! opt_lvl), FileOption "" bc_file, Option "-o", FileOption "" asm_file] ++ map Option lc_opts) when (not rll) $ cleanAndExit False dflags when (not $ dopt Opt_KeepSFiles dflags) $ addFilesToClean dflags [asm_file] return (Just asm_file) -- --------------------------- -- generate assembly code -- return the produced asm file driverAssemble :: DynFlags -> String -> IO String driverAssemble dflags input_file = do let output_file = replaceExtension input_file "o" as_opts = getOpts dflags opt_a ra <- runAs dflags (map Option as_opts ++ [ Option "-c" , FileOption "" input_file , Option "-o" , FileOption "" output_file ]) when (not ra) $ cleanAndExit False dflags when (not $ dopt Opt_KeepObjFiles dflags) $ addFilesToClean dflags [output_file] return output_file -- --------------------------- -- generate executable driverLink :: DynFlags -> [String] -> IO () driverLink dflags input_files = do let verb = getVerbFlag dflags out_file = exeFileName dflags lib_paths = (topDir dflags) : (libraryPaths dflags) lib_paths_opts = map ("-L"++) lib_paths extra_ld_opts = getOpts dflags opt_l rl <- runLink dflags ( [ Option verb , Option "-o" , FileOption "" out_file ] ++ map (FileOption "") input_files ++ map Option (lib_paths_opts ++ extra_ld_opts) ++ [Option "-lprelude"]) when (not rl) $ cleanAndExit False dflags return () -- ------------------------------------------------------------------- -- Clean temp files and exit cleanAndExit :: Bool -> DynFlags -> IO a cleanAndExit is_success dflags = do cleanTempFiles dflags if is_success then exitSuccess else exitFailure -- ------------------------------------------------------------------- -- Splitting arguments into source files, assembly files and object files. partition_args :: [FilePath] -> [String] -> [String] -> [String] -> IO ([String], [String], [String]) partition_args [] srcs asms objs = return (reverse srcs, reverse asms, reverse objs) partition_args (arg:args) srcs asms objs | looks_like_an_input arg = partition_args args (arg:srcs) asms objs | looks_like_an_asm arg = partition_args args srcs (arg:asms) objs | looks_like_an_obj arg = partition_args args srcs asms (arg:objs) | otherwise = do printErrs [ progName ++ ": unrecognised flag `" ++ arg ++ "'" , usageString ] exitFailure -- --------------------------- -- We split out the object files (.o, etc) and add them to -- v_Ld_inputs for use by the linker. -- The following things should be considered compilation manager inputs: -- - alan source files (string ending in .alan extension) looks_like_an_input :: String -> Bool looks_like_an_input m = (drop 1 $ takeExtension m) == "alan" looks_like_an_asm :: String -> Bool looks_like_an_asm m = (drop 1 $ takeExtension m) == "s" looks_like_an_obj :: String -> Bool looks_like_an_obj m = (drop 1 $ takeExtension m) == "o" -- --------------------------- exeFileName :: DynFlags -> FilePath exeFileName dflags = case (outputFile dflags, outputDir dflags) of (Just s, Just d) -> d </> s (Just s, Nothing) -> s (Nothing, Just d) -> d </> "a.out" (Nothing, Nothing) -> "a.out"
iliastsi/gac
src/main/Main.hs
mit
12,996
4
27
4,273
2,832
1,398
1,434
235
9
import Control.Applicative import Control.Monad -- ------------------------------------------------------ {- class (Applicative m) => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b -} -- ------------------------------------------------------ data Maybe' a = Just' a | Nothing' deriving Show -- we can base our Functor implementation of Maybe' on it's Monadic properties instance Functor Maybe' where fmap = liftM {- vs... instance Functor Maybe' where fmap _ Nothing' = Nothing' fmap f (Just' x) = Just' (f x) -} -- similarly, for Applicative: instance Applicative Maybe' where pure = return (<*>) = ap -- (see below...) {- vs... instance Applicative Maybe' where pure f = Just' f Nothing' <*> _ = Nothing' _ <*> Nothing' = Nothing' (Just' f) <*> (Just' x) = Just' (f x) -} instance Monad Maybe' where return x = Just' x Nothing' >>= _ = Nothing' (Just' x) >>= f = (f x) main1 = do print $ Just' 10 >>= \x -> Just' (show x) -- Just' "10" print $ Nothing' >>= \x -> Just' (x * 2) -- Nothing' -- ------------------------------------------------------ -- MONAD as FUNCTOR {- liftM is the fmap of Monad... liftM :: Monad m => (a -> b) -> m a -> m b fmap :: Functor m => (a -> b) -> m a -> m b -} main2 = do -- 3 levels of expressing fmap: Functor -> Applicative -> Monad print $ fmap (*2) (Just' 10) -- FUNCTOR print $ pure (*2) <*> (Just' 10) -- APPLICATIVE print $ liftM (*2) (Just' 10) -- MONAD -- Just' 20 -- ------------------------------------------------------ -- MONAD as APPLICATIVE main3 = do print $ (<$>) (*) (Just' 10) <*> (Just' 20) -- APPLICATIVE -- Just' 200 print $ liftM2 (*) (Just' 10) (Just' 20) -- MONAD -- Just' 200 print $ liftM3 f3 (Just' 10) (Just' 20) (Just' 30) -- Just' 6000 where f3 x y z = x * y * z -- ap_ defines <*> for Monads -- (already defined in Control.Monad.ap) ap_ mf mx = do f <- mf -- perform mf action, extract function x <- mx -- perform mf action, extract val return (f x) -- apply f to x main4 = do print $ (Just' (*)) `ap_` (Just' 10) `ap_` (Just' 20) -- Just' 200 {- instance Applicative Maybe' where pure = return (<*>) = ap -} -- ------------------------------------------------------ -- Sequencing actions with Monad and Applicative action s = do putStrLn s; return s main5 = do let actions = map action ["the", "parts", "are", "disconnected"] sequence' actions return () -- where sequence performs the actions one after the other: sequence' [] = return [] sequence' (x:xs) = do x' <- x -- action performed xs' <- sequence' xs return (x':xs') -- But we can also sequence actions with Applicative -- (defined in Prelude.sequenceA) sequenceA' [] = pure [] sequenceA' (x:xs) = (:) <$> x <*> (sequenceA' xs) main6 = do let actions = map action ["the", "parts", "are", "disconnected"] sequenceA' actions return () -- ------------------------------------------------------ -- Monad as Applicative -- cannot do this with Applicative... main7 = do line <- getLine -- ACTION 1 putStrLn $ "You said " ++ line -- ACTION 2 -- uses result of ACTION 1 main8 = mainLoop mainLoop = do line <- getLine -- ACTION 1 if line == "stop" then putStrLn "Bye" -- ACTION 2b else do putStrLn $ "You said " ++ line -- ACTION 2c mainLoop
uroboros/haskell_design_patterns
chapter3/3_monad.hs
mit
3,527
0
11
926
782
415
367
58
2
{-# LANGUAGE RecordWildCards #-} -- they make your code clean and clear. -- Read about this extension here: -- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html module Construction.Internal.Functions ( Context (..) -- make restrictions is good practice. As you can see here, , fresh, free, bound -- we make "public" not all functions, but only Context, fresh, ... , reduce, substitute, alpha, beta, eta )where import Construction.Internal.Types (Name, Term (..)) import Data.Set (Set, delete, empty, insert, member, notMember, singleton, union) import Data.Text (pack) -- Context is just set of names that are in our context. type Context = Set Name -- | @fresh@ generates new variable different from every variables in set. fresh :: Set Name -> Name fresh conflicts = head . dropWhile (`member` conflicts) $ nameGen -- This is ugly name generator. Make it better. where nameGen = [pack $ 'x' : show ind | ind <- [0..] :: [Int]] -- | @free@ finds all free (Amazing!) variables from given term. free :: Term -> Set Name free (Var var) = singleton var free (App algo arg) = free algo `union` free arg free (Lam variable body) = variable `delete` free body -- | @bound@ finds all bounded variables from given term. -- This function uses RecordWildCards. -- If you like it refactor @free@ function. bound :: Term -> Set Name bound Var{} = empty bound App{..} = bound algo `union` bound arg bound Lam{..} = variable `insert` bound body -- a[n := b] - substiturion substitute :: Term -> Name -> Term -> Term substitute v@Var{..} n b | var == n = b | otherwise = v substitute a@App{..} n b = App (substitute algo n b) (substitute arg n b) substitute l@Lam{..} n b | n == variable = l | otherwise = if variable `member` free b then substitute (alpha l (singleton variable)) n b else Lam variable (substitute body n b) -- | alpha reduction alpha :: Term -> Set Name -> Term alpha t s = alphaDeep t s empty alphaDeep :: Term -> Set Name -> Set Name-> Term alphaDeep v@Var{..} s p | var `member` s && var `member` p = Var (fresh s) | otherwise = v alphaDeep App{..} s p = App (alphaDeep algo s p) (alphaDeep arg s p) alphaDeep l@Lam{..} s p | variable `member` s = Lam (fresh s) (alphaDeep body s (variable `insert` p)) | otherwise = Lam variable (alphaDeep body s p) -- | beta reduction beta :: Term -> Term beta v@Var{..} = v beta (App (Lam name body) arg) = substitute body name arg beta App{..} = App (beta algo) (beta arg) beta Lam{..} = Lam variable (beta body) -- | eta reduction eta :: Term -> Term eta v@Var{..} = v eta a@App{..} = a eta l@(Lam var (App x (Var name))) | name == var && not(name `member` free(x)) = x | otherwise = l eta l@(Lam var _) = l -- | reduce term reduce :: Term -> Term reduce term = let term' = beta term in if term' == term then eta term else reduce term'
mortum5/programming
haskell/BM-courses/construct-yourself/src/Construction/Internal/Functions.hs
mit
3,281
0
13
996
1,097
577
520
58
2
{-# LANGUAGE MultiParamTypeClasses , FlexibleInstances -- , UndecidableInstances #-} module Measures( Unit(..) , UnitDecomposition -- Atomic Units , Time(..) , Distance(..) , Mass(..) , Temperature(..) , Luminosity(..) , Angle(..) ------------------ , (:*)(..) , (:/)(..) , (:^)(..) , I1(..) , I2(..) , I3(..) , I4(..) , D' , d' , D'', d'' -- Composite Units , Speed(..) , Acceleration(..) , Force(..) , Impulse(..) , Energy(..) ------------------ , Measure(..) , Measured(..) , MeasuredVal(..) , MeasureSystem (SI, LargeScale) ) where import Measures.IntType import Measures.Unit import Measures.Unit.Internal -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- data MeasureSystem = SI | LargeScale -- | TODO class Measure m where measureName :: m -> String measureSystem :: m -> MeasureSystem class (Measure m) => Measured a d m where measured :: m -> d -> a measuredValue :: a -> d measure :: a -> m --data DimensionlessMeasure = DimensionlessMeasure --instance Measure DimensionlessMeasure data MeasuredVal d m = MeasuredVal d m instance (Measure m) => Measured (MeasuredVal d m) d m where measured measure value = MeasuredVal value measure measuredValue (MeasuredVal val _) = val measure (MeasuredVal _ m) = m --instance (Measured a d m, Measure m) => Num a instance (Num d) => Num (MeasuredVal d m) where (MeasuredVal x m) + (MeasuredVal y _) = MeasuredVal (x + y) m (MeasuredVal x m) * (MeasuredVal y _) = MeasuredVal (x * y) m negate (MeasuredVal x m) = MeasuredVal (negate x) m abs (MeasuredVal x m) = MeasuredVal (abs x) m signum (MeasuredVal x m) = MeasuredVal (signum x) m fromInteger int = MeasuredVal (fromInteger int) (undefined :: m)
fehu/hgt
core-universe/src/Measures.hs
mit
1,920
0
8
516
604
354
250
56
0
prfac2 :: Integral a => a -> a -> [a] prfac2 n m | n == m = [n] | n `mod` m == 0 = m : prfac2 (n `quot` m) m | otherwise = prfac2 n (m+1) prfac :: Integral a => a -> [a] prfac n | n == 1 = [1] | otherwise = prfac2 n 2 -- maximum (prfac 600851475143)
MakerBar/haskell-euler
3/3.hs
mit
271
0
9
86
160
80
80
9
1
import System.Random import qualified Data.Map as Map ns = [7,6..1] chunks n xs | n <= length xs = fst (splitAt n xs) : chunks n (tail xs) | otherwise = [] rootmap str = Map.fromListWith (Map.unionWith (+)) t where t = [(init s, Map.singleton (last s) 1) | s <- chks str] chks str = concat [chunks x str | x <- ns] mapAccumFsum = Map.mapAccum fsum 0 where fsum a b = (a + b, (a+1,a+b)) rands :: IO [Double] rands = do g <- getStdGen let rs = randomRs (0.0,1.0) g return rs floorLogBase = floor . logBase 0.5 truncBetween a b x = a `max` x `min` b filterMe (d,m) c = Map.filter (\(a,b) -> a<=c && c<=b) m randLts rands = map (truncBetween 0 6) r1s where r1s = map floorLogBase rands randAccum rmap (x,out) = findAccum rmap (drop out x) findAccum rmap x = lookAccum rmap (Map.lookup x rmap) x lookAccum rmap (Just x) str = (str,x) lookAccum rmap Nothing str = lookAccum rmap (Map.lookup next rmap) next where next = drop 1 str example = "lacus veris" main = do rs <- rands let rmap = rootmap example examples = chunks 6 example rl = randLts rs l1 = map (findAccum rmap) examples l2 = map (randAccum rmap) (zip examples rl) mapM_ (putStrLn . show) l1 putStrLn "" mapM_ (putStrLn . show) l2
jsavatgy/dit-doo
code/look-accum-01.hs
gpl-2.0
1,280
0
12
323
641
325
316
39
1
-- | This is a parser for HTML documents. Unlike for XML documents, it -- must include a certain amount of error-correction to account for -- HTML features like self-terminating tags, unterminated tags, and -- incorrect nesting. The input is tokenised by the -- XML lexer (a separate lexer is not required for HTML). -- It uses a slightly extended version of the Hutton/Meijer parser -- combinators. module Text.XML.HaXml.Html.Parse ( htmlParse ) where import Prelude hiding (either,maybe,sequence) import qualified Prelude (either) import Maybe hiding (maybe) import Char (toLower, isSpace, isDigit, isHexDigit) import Numeric (readDec,readHex) import Monad import Text.XML.HaXml.Types import Text.XML.HaXml.Lex import Text.ParserCombinators.HuttonMeijerWallace -- #define DEBUG #if defined(DEBUG) # if ( defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ > 502 ) || \ ( defined(__NHC__) && __NHC__ > 114 ) import Debug.Trace(trace) # elif defined(__GLASGOW_HASKELL__) || defined(__HUGS__) import IOExts(trace) # elif defined(__NHC__) || defined(__HBC__) import NonStdTrace # endif debug :: Monad m => String -> m () debug s = trace s (return ()) #else debug :: Monad m => String -> m () debug s = return () #endif -- | The first argument is the name of the file, the second is the string -- contents of the file. The result is the generic representation of -- an XML document. htmlParse :: String -> String -> Document htmlParse name = simplify . sanitycheck . Prelude.either error id . papply' document () . xmlLex name sanitycheck :: Show p => [(a,s,[Either String (p,t)])] -> a sanitycheck [] = error "***Error at line 0: document not HTML?" sanitycheck ((x,_,[]):_) = x sanitycheck ((x,_,s@(Right (n,_):_)):xs) = error ("***Error at "++show n++": data beyond end of parsed document") ---- Document simplification ---- simplify :: Document -> Document simplify (Document p st (Elem n avs cs)) = Document p st (Elem n avs (deepfilter simp cs)) where simp (CElem (Elem "null" [] [])) = False simp (CElem (Elem n _ [])) | n `elem` ["FONT","P","I","B","EM" ,"TT","BIG","SMALL"] = False simp (CString False s) | all isSpace s = False simp _ = True deepfilter p = filter p . map (\c-> case c of (CElem (Elem n avs cs)) -> CElem (Elem n avs (deepfilter p cs)) _ -> c) -- opening any of these, they close again immediately selfclosingtags = ["IMG","HR","BR","META","COL","LINK","BASE" ,"PARAM","AREA","FRAME","INPUT"] --closing this, implicitly closes any of those which are contained in it closeInnerTags = [ ("UL", ["LI"]) , ("OL", ["LI"]) , ("DL", ["DT","DD"]) , ("TR", ["TH","TD"]) , ("DIV", ["P"]) , ("THEAD", ["TH","TR","TD"]) , ("TFOOT", ["TH","TR","TD"]) , ("TBODY", ["TH","TR","TD"]) , ("TABLE", ["TH","TR","TD","THEAD","TFOOT","TBODY"]) , ("CAPTION", ["P"]) , ("TH", ["P"]) , ("TD", ["P"]) , ("LI", ["P"]) , ("DT", ["P"]) , ("DD", ["P"]) , ("OBJECT", ["P"]) , ("MAP", ["P"]) , ("BODY", ["P"]) ] --opening this, implicitly closes that closes :: Name -> Name -> Bool "A" `closes` "A" = True "LI" `closes` "LI" = True "TH" `closes` t | t `elem` ["TH","TD"] = True "TD" `closes` t | t `elem` ["TH","TD"] = True "TR" `closes` t | t `elem` ["TH","TD","TR"] = True "DT" `closes` t | t `elem` ["DT","DD"] = True "DD" `closes` t | t `elem` ["DT","DD"] = True "FORM" `closes` "FORM" = True "LABEL" `closes` "LABEL" = True _ `closes` "OPTION" = True "THEAD" `closes` t | t `elem` ["COLGROUP"] = True "TFOOT" `closes` t | t `elem` ["THEAD","COLGROUP"] = True "TBODY" `closes` t | t `elem` ["TBODY","TFOOT","THEAD","COLGROUP"] = True "COLGROUP" `closes` "COLGROUP" = True t `closes` "P" | t `elem` ["P","H1","H2","H3","H4","H5","H6" ,"HR","DIV","UL","DL","OL","TABLE"] = True _ `closes` _ = False ---- Misc ---- fst3 (a,_,_) = a snd3 (_,a,_) = a thd3 (_,_,a) = a ---- Auxiliary Parsing Functions ---- type HParser a = Parser () (Posn,TokenT) String a name :: HParser Name name = do {(p,TokName s) <- item; return s} string, freetext :: HParser String string = do {(p,TokName s) <- item; return s} freetext = do {(p,TokFreeText s) <- item; return s} maybe :: HParser a -> HParser (Maybe a) maybe p = ( p >>= return . Just) +++ ( return Nothing) either :: HParser a -> HParser b -> HParser (Either a b) either p q = ( p >>= return . Left) +++ ( q >>= return . Right) word :: String -> HParser () word s = P (\st inp-> case inp of { (Left err: _) -> Left err; (Right (p,TokName n):ts) -> if s==n then Right [((),st,ts)] else Right []; (Right (p,TokFreeText n):ts) -> if s==n then Right [((),st,ts)] else Right []; ts -> Right [] } ) posn :: HParser Posn posn = P (\st inp-> case inp of { (Left err: _) -> Left err; (Right (p,_):_) -> Right [(p,st,inp)]; [] -> Right [(Pn "unknown" 0 0 Nothing,st,inp)]; } ) nmtoken :: HParser NmToken nmtoken = (string +++ freetext) ---- XML Parsing Functions ---- document :: HParser Document document = do p <- prolog `elserror` "unrecognisable XML prolog" es <- many1 (element "HTML document") ms <- many misc return (Document p emptyST (case map snd es of [e] -> e es -> Elem "HTML" [] (map CElem es))) comment :: HParser Comment comment = do bracket (tok TokCommentOpen) freetext (tok TokCommentClose) processinginstruction :: HParser ProcessingInstruction processinginstruction = do tok TokPIOpen n <- string `elserror` "processing instruction has no target" f <- freetext (tok TokPIClose +++ tok TokAnyClose) `elserror` "missing ?> or >" return (n, f) cdsect :: HParser CDSect cdsect = do tok TokSectionOpen bracket (tok (TokSection CDATAx)) chardata (tok TokSectionClose) prolog :: HParser Prolog prolog = do x <- maybe xmldecl many misc dtd <- maybe doctypedecl many misc return (Prolog x dtd) xmldecl :: HParser XMLDecl xmldecl = do tok TokPIOpen (word "xml" +++ word "XML") p <- posn s <- freetext tok TokPIClose `elserror` "missing ?> in <?xml ...?>" (raise . papply' aux () . xmlReLex p) s where aux = do v <- versioninfo `elserror` "missing XML version info" e <- maybe encodingdecl s <- maybe sddecl return (XMLDecl v e s) raise (Left err) = mzero `elserror` err raise (Right ok) = (return . fst3 . head) ok versioninfo :: HParser VersionInfo versioninfo = do (word "version" +++ word "VERSION") tok TokEqual bracket (tok TokQuote) freetext (tok TokQuote) misc :: HParser Misc misc = ( comment >>= return . Comment) +++ ( processinginstruction >>= return . PI) -- Question: for HTML, should we disallow in-line DTDs, allowing only externals? -- Answer: I think so. doctypedecl :: HParser DocTypeDecl doctypedecl = do tok TokSpecialOpen tok (TokSpecial DOCTYPEx) n <- name eid <- maybe externalid -- es <- maybe (bracket (tok TokSqOpen) -- (many markupdecl) -- (tok TokSqClose)) tok TokAnyClose `elserror` "missing > in DOCTYPE decl" -- return (DTD n eid (case es of { Nothing -> []; Just e -> e })) return (DTD n eid []) --markupdecl :: HParser MarkupDecl --markupdecl = -- ( elementdecl >>= return . Element) +++ -- ( attlistdecl >>= return . AttList) +++ -- ( entitydecl >>= return . Entity) +++ -- ( notationdecl >>= return . Notation) +++ -- ( misc >>= return . MarkupMisc) +++ -- PEREF(MarkupPE,markupdecl) -- --extsubset :: HParser ExtSubset --extsubset = do -- td <- maybe textdecl -- ds <- many extsubsetdecl -- return (ExtSubset td ds) -- --extsubsetdecl :: HParser ExtSubsetDecl --extsubsetdecl = -- ( markupdecl >>= return . ExtMarkupDecl) +++ -- ( conditionalsect >>= return . ExtConditionalSect) +++ -- PEREF(ExtPEReference,extsubsetdecl) sddecl :: HParser SDDecl sddecl = do (word "standalone" +++ word "STANDALONE") tok TokEqual `elserror` "missing = in 'standalone' decl" bracket (tok TokQuote) ( (word "yes" >> return True) +++ (word "no" >> return False) `elserror` "'standalone' decl requires 'yes' or 'no' value" ) (tok TokQuote) ---- -- VERY IMPORTANT NOTE: The stack returned here contains those tags which -- have been closed implicitly and need to be reopened again at the -- earliest opportunity. type Stack = [(Name,[Attribute])] element :: Name -> HParser (Stack,Element) element ctx = do tok TokAnyOpen (ElemTag e avs) <- elemtag ( if e `closes` ctx then -- insert the missing close-tag, fail forward, and reparse. ( do debug ("/") unparse ([TokEndOpen, TokName ctx, TokAnyClose, TokAnyOpen, TokName e] ++ reformatAttrs avs) return ([], Elem "null" [] [])) else if e `elem` selfclosingtags then -- complete the parse straightaway. ( do tok TokEndClose -- self-closing <tag /> debug (e++"[+]") return ([], Elem e avs [])) +++ -- ( do tok TokAnyClose -- sequence <tag></tag> (**not HTML?**) -- debug (e++"[+") -- n <- bracket (tok TokEndOpen) name (tok TokAnyClose) -- debug "]" -- if e == (map toLower n :: Name) -- then return ([], Elem e avs []) -- else return (error "no nesting in empty tag")) +++ ( do tok TokAnyClose -- <tag> with no close (e.g. <IMG>) debug (e++"[+]") return ([], Elem e avs [])) else (( do tok TokEndClose debug (e++"[]") return ([], Elem e avs [])) +++ ( do tok TokAnyClose `elserror` "missing > or /> in element tag" debug (e++"[") zz <- many (content e) -- (if null zz then return (error ("empty content in context: "++e)) else return ()) let (ss,cs) = unzip zz let s = if null ss then [] else last ss n <- bracket (tok TokEndOpen) name (tok TokAnyClose) debug "]" ( if e == (map toLower n :: Name) then do unparse (reformatTags (closeInner e s)) debug "^" return ([], Elem e avs cs) else do unparse [TokEndOpen, TokName n, TokAnyClose] debug "-" return (((e,avs):s), Elem e avs cs)) ) `elserror` ("failed to repair non-matching tags in context: "++ctx))) closeInner :: Name -> [(Name,[Attribute])] -> [(Name,[Attribute])] closeInner c ts = case lookup c closeInnerTags of (Just these) -> filter ((`notElem` these).fst) ts Nothing -> ts unparse ts = do p <- posn reparse (map Right (zip (repeat p) ts)) reformatAttrs avs = concatMap f0 avs where f0 (a, AttValue [Left s]) = [TokName a, TokEqual, TokQuote, TokFreeText s, TokQuote] reformatTags ts = concatMap f0 ts where f0 (t,avs) = [TokAnyOpen, TokName t]++reformatAttrs avs++[TokAnyClose] content :: Name -> HParser (Stack,Content) content ctx = ( element ctx >>= \(s,e)-> return (s, CElem e)) +++ ( chardata >>= \s-> return ([], CString False s)) +++ ( reference >>= \r-> return ([], CRef r)) +++ ( cdsect >>= \c-> return ([], CString True c)) +++ ( misc >>= \m-> return ([], CMisc m)) ---- elemtag :: HParser ElemTag elemtag = do n <- name `elserror` "malformed element tag" as <- many attribute return (ElemTag (map toLower n) as) attribute :: HParser Attribute attribute = do n <- name v <- (do tok TokEqual attvalue) +++ (return (AttValue [Left "TRUE"])) return (map toLower n,v) --elementdecl :: HParser ElementDecl --elementdecl = do -- tok TokSpecialOpen -- tok (TokSpecial ELEMENTx) -- n <- name `elserror` "missing identifier in ELEMENT decl" -- c <- contentspec `elserror` "missing content spec in ELEMENT decl" -- tok TokAnyClose `elserror` "expected > terminating ELEMENT decl" -- return (ElementDecl n c) -- --contentspec :: HParser ContentSpec --contentspec = -- ( word "EMPTY" >> return EMPTY) +++ -- ( word "ANY" >> return ANY) +++ -- ( mixed >>= return . Mixed) +++ -- ( cp >>= return . ContentSpec) +++ -- PEREF(ContentPE,contentspec) -- --choice :: HParser [CP] --choice = do -- bracket (tok TokBraOpen) -- (cp `sepby1` (tok TokPipe)) -- (tok TokBraClose) -- --sequence :: HParser [CP] --sequence = do -- bracket (tok TokBraOpen) -- (cp `sepby1` (tok TokComma)) -- (tok TokBraClose) -- --cp :: HParser CP --cp = -- ( do n <- name -- m <- modifier -- return (TagName n m)) +++ -- ( do ss <- sequence -- m <- modifier -- return (Seq ss m)) +++ -- ( do cs <- choice -- m <- modifier -- return (Choice cs m)) +++ -- PEREF(CPPE,cp) -- --modifier :: HParser Modifier --modifier = -- ( tok TokStar >> return Star) +++ -- ( tok TokQuery >> return Query) +++ -- ( tok TokPlus >> return Plus) +++ -- ( return None) -- --mixed :: HParser Mixed --mixed = do -- tok TokBraOpen -- tok TokHash -- word "PCDATA" -- cont -- where -- cont = ( tok TokBraClose >> return PCDATA) +++ -- ( do cs <- many ( do tok TokPipe -- n <- name -- return n) -- tok TokBraClose -- tok TokStar -- return (PCDATAplus cs)) -- --attlistdecl :: HParser AttListDecl --attlistdecl = do -- tok TokSpecialOpen -- tok (TokSpecial ATTLISTx) -- n <- name `elserror` "missing identifier in ATTLIST" -- ds <- many attdef -- tok TokAnyClose `elserror` "missing > terminating ATTLIST" -- return (AttListDecl n ds) -- --attdef :: HParser AttDef --attdef = do -- n <- name -- t <- atttype `elserror` "missing attribute type in attlist defn" -- d <- defaultdecl -- return (AttDef n t d) -- --atttype :: HParser AttType --atttype = -- ( word "CDATA" >> return StringType) +++ -- ( tokenizedtype >>= return . TokenizedType) +++ -- ( enumeratedtype >>= return . EnumeratedType) -- --tokenizedtype :: HParser TokenizedType --tokenizedtype = -- ( word "ID" >> return ID) +++ -- ( word "IDREF" >> return IDREF) +++ -- ( word "IDREFS" >> return IDREFS) +++ -- ( word "ENTITY" >> return ENTITY) +++ -- ( word "ENTITIES" >> return ENTITIES) +++ -- ( word "NMTOKEN" >> return NMTOKEN) +++ -- ( word "NMTOKENS" >> return NMTOKENS) -- --enumeratedtype :: HParser EnumeratedType --enumeratedtype = -- ( notationtype >>= return . NotationType) +++ -- ( enumeration >>= return . Enumeration) -- --notationtype :: HParser NotationType --notationtype = do -- word "NOTATION" -- bracket (tok TokBraOpen) -- (name `sepby1` (tok TokPipe)) -- (tok TokBraClose) -- --enumeration :: HParser Enumeration --enumeration = -- bracket (tok TokBraOpen) -- (nmtoken `sepby1` (tok TokPipe)) -- (tok TokBraClose) -- --defaultdecl :: HParser DefaultDecl --defaultdecl = -- ( tok TokHash >> word "REQUIRED" >> return REQUIRED) +++ -- ( tok TokHash >> word "IMPLIED" >> return IMPLIED) +++ -- ( do f <- maybe (tok TokHash >> word "FIXED" >> return FIXED) -- a <- attvalue -- return (DefaultTo a f)) -- --conditionalsect :: HParser ConditionalSect --conditionalsect = -- ( do tok TokSectionOpen -- tok (TokSection INCLUDEx) -- tok TokSqOpen `elserror` "missing [ after INCLUDE" -- i <- extsubsetdecl `elserror` "missing ExtSubsetDecl in INCLUDE" -- tok TokSectionClose `elserror` "missing ] after INCLUDE" -- return (IncludeSect i)) +++ -- ( do tok TokSectionOpen -- tok (TokSection IGNOREx) -- tok TokSqOpen `elserror` "missing [ after IGNORE" -- i <- many ignoresectcontents -- tok TokSectionClose `elserror` "missing ] after IGNORE" -- return (IgnoreSect i)) -- --ignoresectcontents :: HParser IgnoreSectContents --ignoresectcontents = do -- i <- ignore -- is <- many (do tok TokSectionOpen -- ic <- ignoresectcontents -- tok TokSectionClose -- ig <- ignore -- return (ic,ig)) -- return (IgnoreSectContents i is) -- --ignore :: HParser Ignore --ignore = freetext >>= return . Ignore reference :: HParser Reference reference = do bracket (tok TokAmp) (freetext >>= val) (tok TokSemi) where val ('#':'x':i) | all isHexDigit i = return . RefChar . fst . head . readHex $ i val ('#':i) | all isDigit i = return . RefChar . fst . head . readDec $ i val name = return . RefEntity $ name {- reference :: HParser Reference reference = ( charref >>= return . RefChar) +++ ( entityref >>= return . RefEntity) entityref :: HParser EntityRef entityref = do n <- bracket (tok TokAmp) name (tok TokSemi) return n charref :: HParser CharRef charref = do bracket (tok TokAmp) (freetext >>= readCharVal) (tok TokSemi) where readCharVal ('#':'x':i) = return . fst . head . readHex $ i readCharVal ('#':i) = return . fst . head . readDec $ i readCharVal _ = mzero -} --pereference :: HParser PEReference --pereference = do -- bracket (tok TokPercent) nmtoken (tok TokSemi) -- --entitydecl :: HParser EntityDecl --entitydecl = -- ( gedecl >>= return . EntityGEDecl) +++ -- ( pedecl >>= return . EntityPEDecl) -- --gedecl :: HParser GEDecl --gedecl = do -- tok TokSpecialOpen -- tok (TokSpecial ENTITYx) -- n <- name -- e <- entitydef `elserror` "missing entity defn in G ENTITY decl" -- tok TokAnyClose `elserror` "expected > terminating G ENTITY decl" -- return (GEDecl n e) -- --pedecl :: HParser PEDecl --pedecl = do -- tok TokSpecialOpen -- tok (TokSpecial ENTITYx) -- tok TokPercent -- n <- name -- e <- pedef `elserror` "missing entity defn in P ENTITY decl" -- tok TokAnyClose `elserror` "expected > terminating P ENTITY decl" -- return (PEDecl n e) -- --entitydef :: HParser EntityDef --entitydef = -- ( entityvalue >>= return . DefEntityValue) +++ -- ( do eid <- externalid -- ndd <- maybe ndatadecl -- return (DefExternalID eid ndd)) -- --pedef :: HParser PEDef --pedef = -- ( entityvalue >>= return . PEDefEntityValue) +++ -- ( externalid >>= return . PEDefExternalID) externalid :: HParser ExternalID externalid = ( do word "SYSTEM" s <- systemliteral return (SYSTEM s)) +++ ( do word "PUBLIC" p <- pubidliteral s <- (systemliteral +++ return (SystemLiteral "")) return (PUBLIC p s)) --ndatadecl :: HParser NDataDecl --ndatadecl = do -- word "NDATA" -- n <- name -- return (NDATA n) textdecl :: HParser TextDecl textdecl = do tok TokPIOpen (word "xml" +++ word "XML") v <- maybe versioninfo e <- encodingdecl tok TokPIClose `elserror` "expected ?> terminating text decl" return (TextDecl v e) --extparsedent :: HParser ExtParsedEnt --extparsedent = do -- t <- maybe textdecl -- (_,c) <- (content "") -- return (ExtParsedEnt t c) -- --extpe :: HParser ExtPE --extpe = do -- t <- maybe textdecl -- e <- extsubsetdecl -- return (ExtPE t e) encodingdecl :: HParser EncodingDecl encodingdecl = do (word "encoding" +++ word "ENCODING") tok TokEqual `elserror` "expected = in 'encoding' decl" f <- bracket (tok TokQuote) freetext (tok TokQuote) return (EncodingDecl f) --notationdecl :: HParser NotationDecl --notationdecl = do -- tok TokSpecialOpen -- word "NOTATION" -- n <- name -- e <- either externalid publicid -- tok TokAnyClose `elserror` "expected > terminating NOTATION decl" -- return (NOTATION n e) publicid :: HParser PublicID publicid = do word "PUBLICID" p <- pubidliteral return (PUBLICID p) entityvalue :: HParser EntityValue entityvalue = do evs <- bracket (tok TokQuote) (many ev) (tok TokQuote) return (EntityValue evs) ev :: HParser EV ev = ( freetext >>= return . EVString) +++ -- PEREF(EVPERef,ev) +++ ( reference >>= return . EVRef) attvalue :: HParser AttValue attvalue = ( do avs <- bracket (tok TokQuote) (many (either freetext reference)) (tok TokQuote) return (AttValue avs) ) +++ ( do v <- nmtoken return (AttValue [Left v]) ) systemliteral :: HParser SystemLiteral systemliteral = do s <- bracket (tok TokQuote) freetext (tok TokQuote) return (SystemLiteral s) -- note: need to fold &...; escapes pubidliteral :: HParser PubidLiteral pubidliteral = do s <- bracket (tok TokQuote) freetext (tok TokQuote) return (PubidLiteral s) -- note: need to fold &...; escapes chardata :: HParser CharData chardata = freetext -- >>= return . CharData
jgoerzen/dtmconv
HaXml-1.12/src/Text/XML/HaXml/Html/Parse.hs
gpl-2.0
21,622
0
24
5,999
4,964
2,720
2,244
304
6
{- | Module : ./OWL2/CreateOWL.hs Description : translate theories to OWL2 Copyright : (c) C. Maeder, DFKI GmbH 2012 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable (via Logic.Logic) -} module OWL2.CreateOWL where import Common.Result import Common.AS_Annotation import Logic.Coerce import Logic.Comorphism import Static.GTheory import Logic.Prover import Common.ExtSign import OWL2.Sign import OWL2.MS import OWL2.Logic_OWL2 import OWL2.CASL2OWL import OWL2.DMU2OWL2 import OWL2.Propositional2OWL2 import CASL.Logic_CASL import ExtModal.Logic_ExtModal import Comorphisms.ExtModal2OWL import DMU.Logic_DMU import Propositional.Logic_Propositional createOWLTheory :: G_theory -> Result (Sign, [Named Axiom]) createOWLTheory (G_theory lid _ (ExtSign sign0 _) _ sens0 _) = do let th = (sign0, toNamedList sens0) r1 = coerceBasicTheory lid CASL "" th r1' = r1 >>= wrapMapTheory CASL2OWL r2 = coerceBasicTheory lid DMU "" th r2' = r2 >>= wrapMapTheory DMU2OWL2 r3 = coerceBasicTheory lid Propositional "" th r3' = r3 >>= wrapMapTheory Propositional2OWL2 r4 = coerceBasicTheory lid ExtModal "" th r4' = r4 >>= wrapMapTheory ExtModal2OWL r5 = coerceBasicTheory lid OWL2 "" th r6 = case maybeResult r1 of Nothing -> case maybeResult r2 of Nothing -> case maybeResult r3 of Nothing -> case maybeResult r4 of Nothing -> r5 _ -> r4' _ -> r3' _ -> r2' _ -> r1' (sign, sens) <- r6 return (sign, toNamedList $ toThSens sens)
gnn/Hets
OWL2/CreateOWL.hs
gpl-2.0
1,763
0
21
479
402
211
191
42
5
{-# LANGUAGE TemplateHaskell #-} module Dep.Ui.Utils.TableView ( textTable,textTable' ) where import Control.Monad((>=>)) import Data.IORef(readIORef) import Data.List(transpose,map) import Dep.Ui.Utils(EdgeEmit(..),EdgeWidget(..),linC) import Dep.Utils(mapN,Table(..),powerl) import Graphics.Vty.Attributes(Attr(..)) import Graphics.Vty.Prelude(DisplayRegion) import Graphics.Vty.Image(Image,string,char,imageWidth,imageHeight,pad,(<|>),(<->),emptyImage) import Graphics.Vty.Input.Events(Key(..),Modifier) import Graphics.Vty.Widgets.All(Widget(),newWidget,WidgetImpl(..),RenderContext(..),getNormalAttr,getState,updateWidgetState,addToFocusGroup) import Graphics.Vty.Widgets.Core(handleKeyEvent,render,getCursorPosition,getCurrentSize,setCurrentPosition,growHorizontal,growVertical,relayFocusEvents,updateWidgetState,(<~~),(<~)) import Graphics.Vty.Widgets.Box(IndividualPolicy(..),BoxError(..)) import Graphics.Vty.Widgets.Util(plusWidth,plusHeight,withWidth,withHeight) textTable' :: [[String]] -> [Int] -> IO (Widget Table) textTable' dt = textTable . Table dt textTable :: Table -> IO (Widget Table) textTable st = newWidget st $ \w -> w { growHorizontal_ = const $ return False, growVertical_ = const $ return False, render_ = renderTable, keyEventHandler = \_ _ _ -> return False, getCursorPosition_ = const $ return Nothing, setCurrentPosition_ = \_ _ -> return () } renderTable :: Widget Table -> DisplayRegion -> RenderContext -> IO Image renderTable w d r = do Table dt hl <- getState w return $ renderTbl d r ($(mapN 2) (string na) dt) hl where na = normalAttr r renderTbl :: DisplayRegion -> RenderContext -> [[Image]] -> [Int] -> Image renderTbl dr rc ims = rt 0 hhs $ padImages wws hhs ims where rt i hs rs (j:js) | i == j = hl <-> rt i hs rs js rt i (h:hs) (r:rs) js = rti (vl na h) r <-> rt (i+1) hs rs js where rti _ [c] = c rti br (c:cs) = c <|> br <|> rti br cs rti _ [] = emptyImage rt i [] [] _ = emptyImage na = normalAttr rc (wws,hhs) = getImageDimensions ims hl = hline na wws vl :: Attr -> Int -> Image vl a = powerl emptyImage (char a $ linC 17) (<|>) hline :: Attr -> [Int] -> Image hline na = hl where hl [d] = bar d hl (d:ds) = bar d <|> char na (linC 85) <|> hl ds hl [] = emptyImage bar = powerl emptyImage (char na $ linC 68) (<|>) padImages :: [Int] -> [Int] -> [[Image]] -> [[Image]] padImages ww = padi where padi (h:hs) (is:iss) = padij h ww is : padi hs iss padi _ _ = [] padij h (w:ws) (i:is) = pad 0 0 (w-imageWidth i) (h-imageHeight i) i : padij h ws is padij _ _ _ = [] getImageDimensions :: [[Image]] -> ([Int],[Int]) getImageDimensions dis = (map (maximum . map imageWidth) (transpose dis), map (maximum . map imageHeight) dis)
KommuSoft/dep-software
Dep.Ui.Utils.TableView.hs
gpl-3.0
3,063
0
13
774
1,268
701
567
61
5
{-# OPTIONS_GHC -F -pgmF htfpp #-} module Main where -- The main test program. import Test.Framework import Test.Framework.BlackBoxTest import {-@ HTF_TESTS @-} Codec.Archive.CnCMix.LocalMixDatabase import {-@ HTF_TESTS @-} Codec.Archive.CnCMix.TiberianDawn main :: IO () main = htfMain htf_importedTests
cnc-patch/cncmix
Test.hs
gpl-3.0
308
0
6
39
51
33
18
8
1
module Regex where import Control.Monad.Trans import Control.Monad.Writer import Data.Monoid import Fresh import X86 data Regex = Char Char | Regex :^ Regex | Regex :| Regex | Star Regex data Bytecode = CHAR Char | LABEL Label | SPLIT Label Label | JUMP Label compile :: Regex -> WriterT [Bytecode] (Fresh Label) () compile (Char c) = tell [CHAR c] compile (r1 :^ r2) = do compile r1 ; compile r2 compile (r1 :| r2) = do l1 <- lift $ fresh ; l2 <- lift $ fresh ; l3 <- lift $ fresh tell [SPLIT l1 l2] tell [LABEL l1] ; compile r1 ; tell [JUMP l3] tell [LABEL l2] ; compile r2 tell [LABEL l3] compile (Star r) = do l1 <- lift $ fresh ; l2 <- lift $ fresh ; l3 <- lift $ fresh tell [LABEL l1, SPLIT l2 l3] tell [LABEL l2] ; compile r ; tell [JUMP l1] tell [LABEL l3] -- rax is the buffer pointer -- rbx is the end elab :: Bytecode -> [X86] elab (CHAR c) = [ Cmp Nothing (R RAX) (R RBX) , Jge ".fail" , Cmp (Just Byte) (DR RAX) (C c) , Jne ".fail" , Inc (R RAX) ] elab (LABEL l1) = [Label l1] elab (SPLIT l1 l2) = [ Push (R RAX) , Push (V l2) , Jmp l1 ] elab (JUMP l1) = [Jmp l1] runCompile regexp = (snd $ runFresh (runWriterT $ compile regexp) labels) >>= (s . elab) where labels = map ((".l"++).show) [0..]
orchid-hybrid/bee
Bee/Regex.hs
gpl-3.0
1,243
0
11
290
652
328
324
45
1
module Infsabot.Base.Interface ( RDirection(N,E,W,S), oppositeDirection, Team(A,B), BoardSpot(SpotEmpty, SpotMaterial), applyDirection, limitedOffset, InternalState(..), RobotAppearance(RobotAppearance), SeenSpot(SeenSpot), colorOf, baseChecks, get, insert ) where import Infsabot.Base.Logic import Infsabot.Base.Tests
kavigupta/Infsabot
Infsabot/Base/Interface.hs
gpl-3.0
520
0
5
224
94
68
26
24
0
{-# 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.DialogFlow.Projects.Locations.Operations.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists operations that match the specified filter in the request. If the -- server doesn\'t support this method, it returns \`UNIMPLEMENTED\`. NOTE: -- the \`name\` binding allows API services to override the binding to use -- different resource name schemes, such as \`users\/*\/operations\`. To -- override the binding, API services can add a binding such as -- \`\"\/v1\/{name=users\/*}\/operations\"\` to their service -- configuration. For backwards compatibility, the default name includes -- the operations collection id, however overriding users must ensure the -- name binding is the parent resource, without the operations collection -- id. -- -- /See:/ <https://cloud.google.com/dialogflow/ Dialogflow API Reference> for @dialogflow.projects.locations.operations.list@. module Network.Google.Resource.DialogFlow.Projects.Locations.Operations.List ( -- * REST Resource ProjectsLocationsOperationsListResource -- * Creating a Request , projectsLocationsOperationsList , ProjectsLocationsOperationsList -- * Request Lenses , plolXgafv , plolUploadProtocol , plolAccessToken , plolUploadType , plolName , plolFilter , plolPageToken , plolPageSize , plolCallback ) where import Network.Google.DialogFlow.Types import Network.Google.Prelude -- | A resource alias for @dialogflow.projects.locations.operations.list@ method which the -- 'ProjectsLocationsOperationsList' request conforms to. type ProjectsLocationsOperationsListResource = "v3" :> Capture "name" Text :> "operations" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GoogleLongrunningListOperationsResponse -- | Lists operations that match the specified filter in the request. If the -- server doesn\'t support this method, it returns \`UNIMPLEMENTED\`. NOTE: -- the \`name\` binding allows API services to override the binding to use -- different resource name schemes, such as \`users\/*\/operations\`. To -- override the binding, API services can add a binding such as -- \`\"\/v1\/{name=users\/*}\/operations\"\` to their service -- configuration. For backwards compatibility, the default name includes -- the operations collection id, however overriding users must ensure the -- name binding is the parent resource, without the operations collection -- id. -- -- /See:/ 'projectsLocationsOperationsList' smart constructor. data ProjectsLocationsOperationsList = ProjectsLocationsOperationsList' { _plolXgafv :: !(Maybe Xgafv) , _plolUploadProtocol :: !(Maybe Text) , _plolAccessToken :: !(Maybe Text) , _plolUploadType :: !(Maybe Text) , _plolName :: !Text , _plolFilter :: !(Maybe Text) , _plolPageToken :: !(Maybe Text) , _plolPageSize :: !(Maybe (Textual Int32)) , _plolCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsOperationsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plolXgafv' -- -- * 'plolUploadProtocol' -- -- * 'plolAccessToken' -- -- * 'plolUploadType' -- -- * 'plolName' -- -- * 'plolFilter' -- -- * 'plolPageToken' -- -- * 'plolPageSize' -- -- * 'plolCallback' projectsLocationsOperationsList :: Text -- ^ 'plolName' -> ProjectsLocationsOperationsList projectsLocationsOperationsList pPlolName_ = ProjectsLocationsOperationsList' { _plolXgafv = Nothing , _plolUploadProtocol = Nothing , _plolAccessToken = Nothing , _plolUploadType = Nothing , _plolName = pPlolName_ , _plolFilter = Nothing , _plolPageToken = Nothing , _plolPageSize = Nothing , _plolCallback = Nothing } -- | V1 error format. plolXgafv :: Lens' ProjectsLocationsOperationsList (Maybe Xgafv) plolXgafv = lens _plolXgafv (\ s a -> s{_plolXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plolUploadProtocol :: Lens' ProjectsLocationsOperationsList (Maybe Text) plolUploadProtocol = lens _plolUploadProtocol (\ s a -> s{_plolUploadProtocol = a}) -- | OAuth access token. plolAccessToken :: Lens' ProjectsLocationsOperationsList (Maybe Text) plolAccessToken = lens _plolAccessToken (\ s a -> s{_plolAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plolUploadType :: Lens' ProjectsLocationsOperationsList (Maybe Text) plolUploadType = lens _plolUploadType (\ s a -> s{_plolUploadType = a}) -- | The name of the operation\'s parent resource. plolName :: Lens' ProjectsLocationsOperationsList Text plolName = lens _plolName (\ s a -> s{_plolName = a}) -- | The standard list filter. plolFilter :: Lens' ProjectsLocationsOperationsList (Maybe Text) plolFilter = lens _plolFilter (\ s a -> s{_plolFilter = a}) -- | The standard list page token. plolPageToken :: Lens' ProjectsLocationsOperationsList (Maybe Text) plolPageToken = lens _plolPageToken (\ s a -> s{_plolPageToken = a}) -- | The standard list page size. plolPageSize :: Lens' ProjectsLocationsOperationsList (Maybe Int32) plolPageSize = lens _plolPageSize (\ s a -> s{_plolPageSize = a}) . mapping _Coerce -- | JSONP plolCallback :: Lens' ProjectsLocationsOperationsList (Maybe Text) plolCallback = lens _plolCallback (\ s a -> s{_plolCallback = a}) instance GoogleRequest ProjectsLocationsOperationsList where type Rs ProjectsLocationsOperationsList = GoogleLongrunningListOperationsResponse type Scopes ProjectsLocationsOperationsList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/dialogflow"] requestClient ProjectsLocationsOperationsList'{..} = go _plolName _plolXgafv _plolUploadProtocol _plolAccessToken _plolUploadType _plolFilter _plolPageToken _plolPageSize _plolCallback (Just AltJSON) dialogFlowService where go = buildClient (Proxy :: Proxy ProjectsLocationsOperationsListResource) mempty
brendanhay/gogol
gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Locations/Operations/List.hs
mpl-2.0
7,481
0
19
1,638
980
573
407
139
1
-- eidolon -- A simple gallery in Haskell and Yesod -- Copyright (C) 2015 Amedeo Molnár -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Signup where import Import as I import Data.Text as T import Data.Text.Encoding import Data.Maybe getSignupR :: Handler Html getSignupR = do master <- getYesod block <- return $ appSignupBlocked $ appSettings master case block of False -> do formLayout $ do master <- getYesod setTitle "Eidolon :: Signup" $(widgetFile "signup") True -> do setMessage "User signup has been disabled" redirect $ HomeR postSignupR :: Handler Html postSignupR = do master <- getYesod block <- return $ appSignupBlocked $ appSettings master case block of False -> do mUserName <- lookupPostParam "username" newUserName <- case validateLen (fromJust mUserName) of True -> return $ fromJust $ mUserName False -> do setMessage "Invalid username" redirect $ SignupR mEmail <- lookupPostParam "email" mTos1 <- lookupPostParam "tos-1" mTos2 <- lookupPostParam "tos-2" case (mTos1, mTos2) of (Just "tos-1", Just "tos-2") -> return () _ -> do setMessage "You need to agree to our terms." redirect $ SignupR -- create user namesakes <- runDB $ selectList [UserName ==. newUserName] [] case namesakes of [] -> do salt <- liftIO generateSalt newUser <- return $ User newUserName newUserName (fromJust mEmail) salt "" [] False activatorText <- liftIO generateString _ <- runDB $ insert $ Activator activatorText newUser _ <- runDB $ insert $ Token (encodeUtf8 activatorText) "activate" Nothing activateLink <- ($ ActivateR activatorText) <$> getUrlRender sendMail (userEmail newUser) "Please activate your account!" $ [shamlet| <h1>Hello #{userSlug newUser} and Welcome to Eidolon! To complete your signup please activate your account by visiting the following link: <a href="#{activateLink}">#{activateLink} |] setMessage "User pending activation" redirect $ HomeR _ -> do setMessage "This user already exists" redirect $ SignupR True -> do setMessage "User signup is disabled" redirect $ HomeR validateLen :: Text -> Bool validateLen a = (T.length a) > 2
Mic92/eidolon
Handler/Signup.hs
agpl-3.0
3,251
0
21
931
607
293
314
-1
-1
module DNA (toRNA) where toRNA :: String -> String toRNA = let translate 'C' = 'G' translate 'G' = 'C' translate 'A' = 'U' translate 'T' = 'A' in map translate
pierrebeaucamp/Exercism-Haskell
rna-transcription/DNA.hs
unlicense
207
0
9
78
64
33
31
7
4
module HelperSequences.A053645Spec (main, spec) where import Test.Hspec import HelperSequences.A053645 (a053645) main :: IO () main = hspec spec spec :: Spec spec = describe "A053645" $ it "correctly computes the first 20 elements" $ take 20 (map a053645 [1..]) `shouldBe` expectedValue where expectedValue = [0,0,1,0,1,2,3,0,1,2,3,4,5,6,7,0,1,2,3,4]
peterokagey/haskellOEIS
test/HelperSequences/A053645Spec.hs
apache-2.0
365
0
10
59
160
95
65
10
1
splitBy :: Char -> String -> [String] splitBy _ [] = [] splitBy a x = let s = takeWhile (/= a) x x'= dropWhile (/= a) x in if x' == [] then [s] else s:(splitBy a $ drop 1 x') -- 直線QR y = -1*(y2-y1)/(x2-x1) (x-xq) + yq -- 直線P1P2 y = (y2-y1)/(x2-x1) (x-x1) + y1 -- 2つの直線の交点 -- (y2-y1)/(x2-x1) (x-x1) + y1 = -1*(y2-y1)/(x2-x1) (x-xq) + yq -- ans (x1:y1:x2:y2:xq:yq:_) = if x1 == x2 then [xq+2*(x1-xq),yq] else if y1 == y2 then [xq,yq+2*(y1-yq)] else let a = (y2-y1)/(x2-x1) xs = a/(a*a+1) * ( a*x1 - y1 + xq/a + yq) ys = -1/a*(xs-xq)+yq in [xq+2*(xs-xq),yq+2*(ys-yq)] main = do c <- getContents let i = map (map read) $ map (splitBy ',') $ lines c :: [[Float]] o = map ans i mapM_ putStrLn $ map unwords $ map (map show) o
a143753/AOJ
0081.hs
apache-2.0
859
0
17
262
452
239
213
22
3
-- Factorial [tail recursion] in Haskell -- Prashanth Babu V V :: 02nd Dec, 2016. factorial :: Integer -> Integer factorial n = tailrecFact n 1 tailrecFact :: Integer -> Integer -> Integer tailrecFact n acc | n == 1 = acc | otherwise = tailrecFact (n-1) (acc * n) -- ghci factorial -- factorial 12 -- > 479001600 -- factorial 10 -- > 3628800
P7h/FutureLearn__FP_in_Haskell
factorial.hs
apache-2.0
395
0
8
117
89
46
43
5
1
{-# LANGUAGE CPP #-} import Scaffolding.Scaffolder import System.Environment (getArgs) import System.Exit (exitWith) import System.Process (rawSystem) import Yesod.Core(yesodVersion) #ifndef WINDOWS import Build (touch) #endif import Devel (devel) windowsWarning :: String #ifdef WINDOWS windowsWarning = "\n (does not work on Windows)" #else windowsWarning = "" #endif main :: IO () main = do args' <- getArgs let (isDev, args) = case args' of "--dev":rest -> (True, rest) _ -> (False, args') let cmd = if isDev then "cabal-dev" else "cabal" #ifndef WINDOWS let build rest = rawSystem cmd $ "build":rest #endif case args of ["init"] -> scaffold #ifndef WINDOWS "build":rest -> touch >> build rest >>= exitWith ["touch"] -> touch #endif "devel":rest -> devel isDev rest ["version"] -> putStrLn yesodVersion "configure":rest -> rawSystem cmd ("configure":rest) >>= exitWith _ -> do putStrLn "Usage: yesod <command>" putStrLn "Available commands:" putStrLn " init Scaffold a new site" putStrLn " configure Configure a project for building" putStrLn $ " build Build project (performs TH dependency analysis)" ++ windowsWarning putStrLn $ " touch Touch any files with altered TH dependencies but do not build" ++ windowsWarning putStrLn " devel Run project with the devel server" putStrLn " use --dev devel to build with cabal-dev" putStrLn " version Print the version of Yesod"
chreekat/yesod
yesod/main.hs
bsd-2-clause
1,733
0
13
563
361
185
176
38
9
{-# LANGUAGE OverloadedStrings, TupleSections, ScopedTypeVariables, TypeFamilies, FlexibleContexts, PackageImports #-} module Network.XmlPush.HttpPush.Tls ( HttpPushTls, HttpPushTlsArgs(..), HttpPushArgs(..), TlsArgsCl, tlsArgsCl, TlsArgsSv, tlsArgsSv) where import Network.XmlPush.HttpPush.Tls.Body
YoshikuniJujo/xml-push
src/Network/XmlPush/HttpPush/Tls.hs
bsd-3-clause
306
4
5
28
52
36
16
7
0
-- | -- Module: Database.TinkerPop.Types -- Copyright: (c) 2015 The gremlin-haskell Authors -- License : BSD3 -- Maintainer : nakaji.dayo@gmail.com -- Stability : experimental -- Portability : non-portable -- module Database.TinkerPop.Types where import Data.Text hiding (drop, toLower) import Data.Char (toLower) import qualified Data.Map.Strict as M import Data.Aeson (Object, Value) import Data.Aeson.TH import Control.Lens import qualified Network.WebSockets as WS import qualified Control.Concurrent.STM.TChan as S import qualified Control.Concurrent.STM.TVar as S -- | Represent Gremlin code type Gremlin = Text -- | A Map of key/value pairs type Binding = Object -- | parameters to pass to Gremlin Server. (TODO: The requirements for the contents of this Map are dependent on the op selected.) data RequestArgs = RequestArgs { _requestArgsGremlin :: Text -- ^ The Gremlin script to evaluate , _requestArgsBindings :: Maybe Binding -- ^ A map of key/value pairs to apply as variables in the context of the Gremlin script , _requestArgsLanguage :: Text -- ^ The flavor used (e.g. gremlin-groovy) , _requestArgsBatchSize :: Maybe Int -- ^ When the result is an iterator this value defines the number of iterations each ResponseMessage should contain } $(deriveJSON defaultOptions{fieldLabelModifier = (\(x:xs) -> (toLower x):xs).(drop 12)} ''RequestArgs) makeFields ''RequestArgs -- | Format of requests to the Gremlin Server data RequestMessage = RequestMessage { _requestMessageRequestId :: Text -- ^ A UUID representing the unique identification for the request. , _requestMessageOp :: Text -- ^ The name of the "operation" to execute based on the available OpProcessor configured in the Gremlin Server. To evaluate a script, use eval. , _requestMessageProcessor :: Text -- ^ The name of the OpProcessor to utilize. The default OpProcessor for evaluating scripts is unamed and therefore script evaluation purposes, this value can be an empty string. , _requestMessageArgs :: RequestArgs -- ^ Parameters to pass to Gremlin Server } $(deriveJSON defaultOptions{fieldLabelModifier = (\(x:xs) -> (toLower x):xs).(drop 15)} ''RequestMessage) makeFields ''RequestMessage -- | The staus of Gremlin Server Response data ResponseStatus = ResponseStatus { _responseStatusMessage :: Text -- ^ Human-readable String usually associated with errors. , _responseStatusCode :: Int -- ^ HTTP status code , _responseStatusAttributes :: Object -- ^ Protocol-level information } deriving (Show) makeFields ''ResponseStatus $(deriveJSON defaultOptions {fieldLabelModifier = (\(x:xs) -> (toLower x):xs).(drop 15)} ''ResponseStatus) -- | The Result of Gremlin Server response data ResponseResult = ResponseResult { _responseResultData' :: Maybe [Value] -- ^ the actual data returned from the server (the type of data is determined by the operation requested) , _responseResultMeta :: Object -- ^ Map of meta-data related to the response. } deriving (Show) makeFields ''ResponseResult $(deriveJSON defaultOptions {fieldLabelModifier = \f -> if f == "_responseResultData'" then "data" else (\(x:xs) -> (toLower x):xs) (drop 15 f)} ''ResponseResult) -- | Response of Gremlin Server data ResponseMessage = ResponseMessage { _responseMessageRequestId :: Text -- ^ The identifier of the RequestMessage that generated this ResponseMessage. , _responseMessageStatus :: ResponseStatus -- ^ status , _responseMessageResult :: ResponseResult -- ^ result } deriving (Show) $(deriveJSON defaultOptions{fieldLabelModifier = (\(x:xs) -> (toLower x):xs).(drop 16)} ''ResponseMessage) makeFields ''ResponseMessage -- | Connection handle data Connection = Connection { _connectionSocket :: WS.Connection , _connectionChans :: S.TVar (M.Map Text (S.TChan (Either String ResponseMessage))) } makeFields ''Connection
nakaji-dayo/gremlin-haskell
src/Database/TinkerPop/Types.hs
bsd-3-clause
3,953
4
17
692
715
417
298
-1
-1
module Pickle ( module Pickle.Config , module Pickle.Files , module Pickle.Everything , module Pickle.Template ) where import Pickle.Config import Pickle.Files import Pickle.Everything import Pickle.Template
themattchan/pickle
src/Pickle.hs
bsd-3-clause
219
0
5
35
50
32
18
9
0
{-# LANGUAGE ScopedTypeVariables, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, FlexibleInstances #-} module Simple where import Language.XHaskell [xh| g :: Choice Int Bool -> Choice Int Bool g (x :: Int) = x f :: Star Int -> Star (Choice Int Bool) f (x::Star Int, y::Int) = g y h :: Star (Choice Int a) -> Star (Choice Int a) h (x :: a) = x |]
luzhuomi/xhaskell
test/Simple.hs
bsd-3-clause
359
0
4
70
17
12
5
4
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.FramebufferSRGB -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/framebuffer_sRGB.txt ARB_framebuffer_sRGB> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.FramebufferSRGB ( -- * Enums gl_FRAMEBUFFER_SRGB ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/FramebufferSRGB.hs
bsd-3-clause
660
0
4
78
37
31
6
3
0
{-#LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, TypeApplications #-} {-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-} module DirectoryServer where import Network hiding (accept, sClose) import Network.Socket hiding (send, recv, sendTo, recvFrom, Broadcast) import Network.Socket.ByteString import Data.ByteString.Char8 (pack, unpack) import System.Environment import System.IO import Control.Concurrent import Control.Concurrent.STM import Control.Exception import Control.Monad (forever, when, join) import Data.List.Split import Data.Word import Text.Printf (printf) import System.Directory import Data.Map (Map) -- from the `containers` library import Data.Time import System.Random import qualified Data.Map as M import LRUCache as C import Data.Hashable type Uuid = Int type Address = String type Port = String type Filename = String type Timestamp = IO String --Server data type allows me to pass address and port details easily data DirectoryServer = DirectoryServer { address :: String , port :: String , filemappings :: TVar (M.Map Filename Filemapping) , fileservers :: TVar (M.Map Uuid Fileserver) , fileservercount :: TVar Int } --Constructor newDirectoryServer :: String -> String -> IO DirectoryServer newDirectoryServer address port = atomically $ do DirectoryServer <$> return address <*> return port <*> newTVar M.empty <*> newTVar M.empty <*> newTVar 0 addFilemapping :: DirectoryServer -> Filename -> Uuid -> Address -> Port -> Timestamp -> STM () addFilemapping DirectoryServer{..} filename uuid fmaddress fmport timestamp = do fm <- newFilemapping filename uuid fmaddress fmport timestamp modifyTVar filemappings . M.insert filename $ fm addFileserver :: DirectoryServer -> Uuid -> Address -> Port -> STM () addFileserver DirectoryServer{..} uuid fsaddress fsport = do fs <- newFileserver uuid fsaddress fsport modifyTVar fileservers . M.insert uuid $ fs lookupFilemapping :: DirectoryServer -> Filename -> STM (Maybe Filemapping) lookupFilemapping DirectoryServer{..} filename = M.lookup filename <$> readTVar filemappings lookupFileserver :: DirectoryServer -> Uuid -> STM (Maybe Fileserver) lookupFileserver DirectoryServer{..} uuid = M.lookup uuid <$> readTVar fileservers data Filemapping = Filemapping { fmfilename :: Filename , fmuuid :: Uuid , fmaddress :: Address , fmport :: Port , fmtimestamp :: Timestamp } newFilemapping :: Filename -> Uuid -> Address -> Port -> Timestamp -> STM Filemapping newFilemapping fmfilename fmuuid fmaddress fmport fmtimestamp = Filemapping <$> return fmfilename <*> return fmuuid <*> return fmaddress <*> return fmport <*> return fmtimestamp getFilemappinguuid :: Filemapping -> Uuid getFilemappinguuid Filemapping{..} = fmuuid getFilemappingaddress :: Filemapping -> Address getFilemappingaddress Filemapping{..} = fmaddress getFilemappingport :: Filemapping -> Port getFilemappingport Filemapping{..} = fmport getFilemappingtimestamp :: Filemapping -> Timestamp getFilemappingtimestamp Filemapping{..} = fmtimestamp data Fileserver = Fileserver { fsuuid :: Uuid , fsaddress :: HostName , fsport :: Port } newFileserver :: Uuid -> Address -> Port -> STM Fileserver newFileserver fsuuid fsaddress fsport = Fileserver <$> return fsuuid <*> return fsaddress <*> return fsport getFileserveraddress :: Fileserver -> HostName getFileserveraddress Fileserver{..} = fsaddress getFileserverport :: Fileserver -> Port getFileserverport Fileserver{..} = fsport --4 is easy for testing the pooling maxnumThreads = 4 serverport :: String serverport = "7008" serverhost :: String serverhost = "localhost" dirrun:: IO () dirrun = withSocketsDo $ do --Command line arguments for port and address --args <- getArgs server <- newDirectoryServer serverhost serverport --sock <- listenOn (PortNumber (fromIntegral serverport)) addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just serverport) let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol bindSocket sock (addrAddress serveraddr) listen sock 5 _ <- printf "Listening on port %s\n" serverport --Listen on port from command line argument --New Abstract FIFO Channel chan <- newChan --New Cache cache <- C.newHandle 5 --Tvars are variables Stored in memory, this way we can access the numThreads from any method numThreads <- atomically $ newTVar 0 --Spawns a new thread to handle the clientconnectHandler method, passes socket, channel, numThreads and server forkIO $ clientconnectHandler sock chan numThreads server cache --Calls the mainHandler which will monitor the FIFO channel mainHandler sock chan mainHandler :: Socket -> Chan String -> IO () mainHandler sock chan = do --Read current message on the FIFO channel chanMsg <- readChan chan --If KILL_SERVICE, stop mainHandler running, If anything else, call mainHandler again, keeping the service running case (chanMsg) of ("KILL_SERVICE") -> putStrLn "Terminating the Service!" _ -> mainHandler sock chan clientconnectHandler :: Socket -> Chan String -> TVar Int -> DirectoryServer -> (C.Handle k v) -> IO () clientconnectHandler sock chan numThreads server cache = do --Accept the socket which returns a handle, host and port --(handle, host, port) <- accept sock (s,a) <- accept sock --handle <- socketToHandle s ReadWriteMode --Read numThreads from memory and print it on server console count <- atomically $ readTVar numThreads putStrLn $ "numThreads = " ++ show count --If there are still threads remaining create new thread and increment (exception if thread is lost -> decrement), else tell user capacity has been reached if (count < maxnumThreads) then do forkFinally (clientHandler s chan server cache) (\_ -> atomically $ decrementTVar numThreads) atomically $ incrementTVar numThreads else do send s (pack ("Maximum number of threads in use. try again soon"++"\n\n")) sClose s clientconnectHandler sock chan numThreads server cache clientHandler :: Socket -> Chan String -> DirectoryServer -> (C.Handle k v) -> IO () clientHandler sock chan server@DirectoryServer{..} cache = forever $ do message <- recv sock 1024 let msg = unpack message print $ msg ++ "!ENDLINE!" let cmd = head $ words $ head $ splitOn ":" msg print cmd case cmd of ("HELO") -> heloCommand sock server $ (words msg) !! 1 ("KILL_SERVICE") -> killCommand chan sock ("DOWNLOAD") -> downloadCommand sock server msg cache ("UPLOAD") -> uploadCommand sock server msg ("JOIN") -> joinCommand sock server msg ("UPDATE") -> updateCommand sock server msg _ -> do send sock (pack ("Unknown Command - " ++ msg ++ "\n\n")) ; return () --Function called when HELO text command recieved heloCommand :: Socket -> DirectoryServer -> String -> IO () heloCommand sock DirectoryServer{..} msg = do send sock $ pack $ "HELO " ++ msg ++ "\n" ++ "IP:" ++ "192.168.6.129" ++ "\n" ++ "Port:" ++ port ++ "\n" ++ "StudentID:12306421\n\n" return () killCommand :: Chan String -> Socket -> IO () killCommand chan sock = do send sock $ pack $ "Service is now terminating!" writeChan chan "KILL_SERVICE" returnb :: a -> IO a returnb a = return a downloadCommand :: Socket -> DirectoryServer -> String -> (C.Handle String String) -> IO () downloadCommand sock server@DirectoryServer{..} command cache = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 -- let k = filename let k = filename incache <- C.iolookup cache k case incache of (Nothing) -> do fm <- atomically $ lookupFilemapping server filename case fm of (Nothing) -> send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "File not found" ++ "\n\n" (Just fm) -> do forkIO $ downloadmsg filename (getFilemappingaddress fm) (getFilemappingport fm) sock cache send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "SUCCESSFUL" ++ "\n\n" (Just v) -> do print "Cache hit" ioinsert cache filename v send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "DATA: " ++ show v ++ "\n\n" return () downloadmsg :: String -> String -> String -> Socket -> (C.Handle String String) -> IO() downloadmsg filename host port sock cache = do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just "7007") let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "DOWNLOAD:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n\n" resp <- recv clsock 1024 let msg = unpack resp let clines = splitOn "\\n" msg fdata = (splitOn ":" $ clines !! 1) !! 1 sClose clsock send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "DATA: " ++ fdata ++ "\n\n" ioinsert cache filename fdata return () returndata :: String -> Socket -> String -> IO () returndata filename sock fdata = do send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\\n" ++ "DATA: " ++ fdata ++ "\n\n" return () uploadCommand :: Socket -> DirectoryServer ->String -> IO () uploadCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fdata = (splitOn ":" $ clines !! 2) !! 1 fm <- atomically $ lookupFilemapping server filename case fm of (Just fm) -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "File Already Exists" ++ "\n\n" (Nothing) -> do numfs <- atomically $ M.size <$> readTVar fileservers rand <- randomRIO (0, (numfs-1)) fs <- atomically $ lookupFileserver server rand case fs of (Nothing) -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n"++ "FAILED: " ++ "No valid Fileserver found to host" ++ "\n\n" (Just fs) -> do forkIO $ uploadmsg sock filename fdata fs rand server fm <- atomically $ newFilemapping filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) atomically $ addFilemapping server filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) send sock $ pack $ "UPLOAD: " ++ filename ++ "\\n" ++ "STATUS: " ++ "Successfull" ++ "\n\n" return () uploadmsg :: Socket -> String -> String -> Fileserver -> Int -> DirectoryServer -> IO () uploadmsg sock filename fdata fs rand server@DirectoryServer{..} = withSocketsDo $ do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just (getFileserverport fs)) let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "UPLOAD:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n" ++ "DATA:" ++ fdata ++ "\\n" resp <- recv clsock 1024 sClose clsock let msg = unpack resp print $ msg ++ "!ENDLINE!" let clines = splitOn "\\n" msg status = (splitOn ":" $ clines !! 1) !! 1 return () joinCommand :: Socket -> DirectoryServer ->String -> IO () joinCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command newaddress = (splitOn ":" $ clines !! 1) !! 1 newport = (splitOn ":" $ clines !! 2) !! 1 nodeID <- atomically $ readTVar fileservercount fs <- atomically $ newFileserver nodeID newaddress newport atomically $ addFileserver server nodeID newaddress newport atomically $ incrementFileserverCount fileservercount send sock $ pack $ "JOINED DISTRIBUTED FILE SERVICE as fileserver: " ++ (show nodeID) ++ "\n\n" return () updateCommand :: Socket -> DirectoryServer ->String -> IO () updateCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fdata = (splitOn ":" $ clines !! 2) !! 1 fm <- atomically $ lookupFilemapping server filename case fm of (Nothing) -> send sock $ pack $ "UPDATE: " ++ filename ++ "\n" ++ "STATUS: " ++ "File Doesnt Exists" ++ "\n\n" (Just fm) -> do fs <- atomically $ lookupFileserver server (getFilemappinguuid fm) case fs of (Nothing) -> send sock $ pack $ "UPDATE: " ++ filename ++ "\n"++ "FAILED: " ++ "No valid Fileserver found to host" ++ "\n\n" (Just fs) -> do forkIO $ updatemsg sock filename fdata fs (getFilemappinguuid fm) server fm <- atomically $ newFilemapping filename (getFilemappinguuid fm) (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) atomically $ addFilemapping server filename (getFilemappinguuid fm) (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) send sock $ pack $ "UPDATE: " ++ filename ++ "\\n" ++ "STATUS: " ++ "Successfull" ++ "\n\n" return () updatemsg :: Socket -> String -> String -> Fileserver -> Int -> DirectoryServer -> IO () updatemsg sock filename fdata fs rand server@DirectoryServer{..} = withSocketsDo $ do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just (getFileserverport fs)) let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "UPDATE:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n" ++ "DATA:" ++ fdata ++ "\\n" resp <- recv clsock 1024 sClose clsock let msg = unpack resp print $ msg ++ "!ENDLINE!" let clines = splitOn "\\n" msg status = (splitOn ":" $ clines !! 1) !! 1 return () --Increment Tvar stored in memory i.e. numThreads incrementTVar :: TVar Int -> STM () incrementTVar tv = modifyTVar tv ((+) 1) --Decrement Tvar stored in memory i.e. numThreads decrementTVar :: TVar Int -> STM () decrementTVar tv = modifyTVar tv (subtract 1) incrementFileserverCount :: TVar Int -> STM () incrementFileserverCount tv = modifyTVar tv ((+) 1)
Garygunn94/DFS
.stack-work/intero/intero3310OlW.hs
bsd-3-clause
15,432
456
15
4,001
4,189
2,160
2,029
276
7
{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections #-} {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-} ----------------------------------------------------------------------------- -- -- GHC Driver program -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module Main (main) where -- The official GHC API import qualified GHC import GHC ( -- DynFlags(..), HscTarget(..), -- GhcMode(..), GhcLink(..), Ghc, GhcMonad(..), LoadHowMuch(..) ) import CmdLineParser -- Implementations of the various modes (--show-iface, mkdependHS. etc.) import LoadIface ( showIface ) import HscMain ( newHscEnv ) import DriverPipeline ( oneShot, compileFile ) import DriverMkDepend ( doMkDependHS ) #ifdef GHCI import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings ) #endif -- Various other random stuff that we need import Config import Constants import HscTypes import Packages ( pprPackages, pprPackagesSimple, pprModuleMap ) import DriverPhases import BasicTypes ( failed ) import StaticFlags import DynFlags import ErrUtils import FastString import Outputable import SrcLoc import Util import Panic import MonadUtils ( liftIO ) -- Imports for --abi-hash import LoadIface ( loadUserInterface ) import Module ( mkModuleName ) import Finder ( findImportedModule, cannotFindInterface ) import TcRnMonad ( initIfaceCheck ) import Binary ( openBinMem, put_, fingerprintBinMem ) -- Standard Haskell libraries import System.IO import System.Environment import System.Exit import System.FilePath import Control.Monad import Data.Char import Data.List import Data.Maybe ----------------------------------------------------------------------------- -- ToDo: -- time commands when run with -v -- user ways -- Win32 support: proper signal handling -- reading the package configuration file is too slow -- -K<size> ----------------------------------------------------------------------------- -- GHC's command-line interface main :: IO () main = do initGCStatistics -- See Note [-Bsymbolic and hooks] hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do -- 1. extract the -B flag from the args argv0 <- getArgs let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0 mbMinusB | null minusB_args = Nothing | otherwise = Just (drop 2 (last minusB_args)) let argv1' = map (mkGeneralLocated "on the commandline") argv1 (argv2, staticFlagWarnings) <- parseStaticFlags argv1' -- 2. Parse the "mode" flags (--make, --interactive etc.) (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2 let flagWarnings = staticFlagWarnings ++ modeFlagWarnings -- If all we want to do is something like showing the version number -- then do it now, before we start a GHC session etc. This makes -- getting basic information much more resilient. -- In particular, if we wait until later before giving the version -- number then bootstrapping gets confused, as it tries to find out -- what version of GHC it's using before package.conf exists, so -- starting the session fails. case mode of Left preStartupMode -> do case preStartupMode of ShowSupportedExtensions -> showSupportedExtensions ShowVersion -> showVersion ShowNumVersion -> putStrLn cProjectVersion ShowOptions isInteractive -> showOptions isInteractive Right postStartupMode -> -- start our GHC session GHC.runGhc mbMinusB $ do dflags <- GHC.getSessionDynFlags case postStartupMode of Left preLoadMode -> liftIO $ do case preLoadMode of ShowInfo -> showInfo dflags ShowGhcUsage -> showGhcUsage dflags ShowGhciUsage -> showGhciUsage dflags PrintWithDynFlags f -> putStrLn (f dflags) Right postLoadMode -> main' postLoadMode dflags argv3 flagWarnings main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String] -> Ghc () main' postLoadMode dflags0 args flagWarnings = do -- set the default GhcMode, HscTarget and GhcLink. The HscTarget -- can be further adjusted on a module by module basis, using only -- the -fvia-C and -fasm flags. If the default HscTarget is not -- HscC or HscAsm, -fvia-C and -fasm have no effect. let dflt_target = hscTarget dflags0 (mode, lang, link) = case postLoadMode of DoInteractive -> (CompManager, HscInterpreted, LinkInMemory) DoEval _ -> (CompManager, HscInterpreted, LinkInMemory) DoMake -> (CompManager, dflt_target, LinkBinary) DoMkDependHS -> (MkDepend, dflt_target, LinkBinary) DoAbiHash -> (OneShot, dflt_target, LinkBinary) _ -> (OneShot, dflt_target, LinkBinary) let dflags1 = case lang of HscInterpreted -> let platform = targetPlatform dflags0 dflags0a = updateWays $ dflags0 { ways = interpWays } dflags0b = foldl gopt_set dflags0a $ concatMap (wayGeneralFlags platform) interpWays dflags0c = foldl gopt_unset dflags0b $ concatMap (wayUnsetGeneralFlags platform) interpWays in dflags0c _ -> dflags0 dflags2 = dflags1{ ghcMode = mode, hscTarget = lang, ghcLink = link, verbosity = case postLoadMode of DoEval _ -> 0 _other -> 1 } -- turn on -fimplicit-import-qualified for GHCi now, so that it -- can be overriden from the command-line -- XXX: this should really be in the interactive DynFlags, but -- we don't set that until later in interactiveUI dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled | DoEval _ <- postLoadMode = imp_qual_enabled | otherwise = dflags2 where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified -- The rest of the arguments are "dynamic" -- Leftover ones are presumably files (dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args GHC.prettyPrintGhcErrors dflags4 $ do let flagWarnings' = flagWarnings ++ dynamicFlagWarnings handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ handleFlagWarnings dflags4 flagWarnings' -- make sure we clean up after ourselves GHC.defaultCleanupHandler dflags4 $ do liftIO $ showBanner postLoadMode dflags4 let -- To simplify the handling of filepaths, we normalise all filepaths right -- away - e.g., for win32 platforms, backslashes are converted -- into forward slashes. normal_fileish_paths = map (normalise . unLoc) fileish_args (srcs, objs) = partition_args normal_fileish_paths [] [] dflags5 = dflags4 { ldInputs = map (FileOption "") objs ++ ldInputs dflags4 } -- we've finished manipulating the DynFlags, update the session _ <- GHC.setSessionDynFlags dflags5 dflags6 <- GHC.getSessionDynFlags hsc_env <- GHC.getSession ---------------- Display configuration ----------- case verbosity dflags6 of v | v == 4 -> liftIO $ dumpPackagesSimple dflags6 | v >= 5 -> liftIO $ dumpPackages dflags6 | otherwise -> return () when (verbosity dflags6 >= 3) $ do liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags) when (dopt Opt_D_dump_mod_map dflags6) . liftIO $ printInfoForUser (dflags6 { pprCols = 200 }) (pkgQual dflags6) (pprModuleMap dflags6) ---------------- Final sanity checking ----------- liftIO $ checkOptions postLoadMode dflags6 srcs objs ---------------- Do the business ----------- handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do case postLoadMode of ShowInterface f -> liftIO $ doShowIface dflags6 f DoMake -> doMake srcs DoMkDependHS -> doMkDependHS (map fst srcs) StopBefore p -> liftIO (oneShot hsc_env p srcs) DoInteractive -> ghciUI srcs Nothing DoEval exprs -> ghciUI srcs $ Just $ reverse exprs DoAbiHash -> abiHash (map fst srcs) ShowPackages -> liftIO $ showPackages dflags6 liftIO $ dumpFinalStats dflags6 ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc () #ifndef GHCI ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use") #else ghciUI = interactiveUI defaultGhciSettings #endif -- ----------------------------------------------------------------------------- -- Splitting arguments into source files and object files. This is where we -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source -- file indicating the phase specified by the -x option in force, if any. partition_args :: [String] -> [(String, Maybe Phase)] -> [String] -> ([(String, Maybe Phase)], [String]) partition_args [] srcs objs = (reverse srcs, reverse objs) partition_args ("-x":suff:args) srcs objs | "none" <- suff = partition_args args srcs objs | StopLn <- phase = partition_args args srcs (slurp ++ objs) | otherwise = partition_args rest (these_srcs ++ srcs) objs where phase = startPhase suff (slurp,rest) = break (== "-x") args these_srcs = zip slurp (repeat (Just phase)) partition_args (arg:args) srcs objs | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs | otherwise = partition_args args srcs (arg:objs) {- We split out the object files (.o, .dll) and add them to ldInputs for use by the linker. The following things should be considered compilation manager inputs: - haskell source files (strings ending in .hs, .lhs or other haskellish extension), - module names (not forgetting hierarchical module names), - things beginning with '-' are flags that were not recognised by the flag parser, and we want them to generate errors later in checkOptions, so we class them as source files (#5921) - and finally we consider everything not containing a '.' to be a comp manager input, as shorthand for a .hs or .lhs filename. Everything else is considered to be a linker object, and passed straight through to the linker. -} looks_like_an_input :: String -> Bool looks_like_an_input m = isSourceFilename m || looksLikeModuleName m || "-" `isPrefixOf` m || '.' `notElem` m -- ----------------------------------------------------------------------------- -- Option sanity checks -- | Ensure sanity of options. -- -- Throws 'UsageError' or 'CmdLineError' if not. checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO () -- Final sanity checking before kicking off a compilation (pipeline). checkOptions mode dflags srcs objs = do -- Complain about any unknown flags let unknown_opts = [ f | (f@('-':_), _) <- srcs ] when (notNull unknown_opts) (unknownFlagsErr unknown_opts) when (notNull (filter wayRTSOnly (ways dflags)) && isInterpretiveMode mode) $ hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi") -- -prof and --interactive are not a good combination when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays) && isInterpretiveMode mode) $ do throwGhcException (UsageError "--interactive can't be used with -prof.") -- -ohi sanity check if (isJust (outputHi dflags) && (isCompManagerMode mode || srcs `lengthExceeds` 1)) then throwGhcException (UsageError "-ohi can only be used when compiling a single source file") else do -- -o sanity checking if (srcs `lengthExceeds` 1 && isJust (outputFile dflags) && not (isLinkMode mode)) then throwGhcException (UsageError "can't apply -o to multiple source files") else do let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags) when (not_linking && not (null objs)) $ hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs) -- Check that there are some input files -- (except in the interactive case) if null srcs && (null objs || not_linking) && needsInputsMode mode then throwGhcException (UsageError "no input files") else do case mode of StopBefore HCc | hscTarget dflags /= HscC -> throwGhcException $ UsageError $ "the option -C is only available with an unregisterised GHC" _ -> return () -- Verify that output files point somewhere sensible. verifyOutputFiles dflags -- Compiler output options -- Called to verify that the output files point somewhere valid. -- -- The assumption is that the directory portion of these output -- options will have to exist by the time 'verifyOutputFiles' -- is invoked. -- -- We create the directories for -odir, -hidir, -outputdir etc. ourselves if -- they don't exist, so don't check for those here (#2278). verifyOutputFiles :: DynFlags -> IO () verifyOutputFiles dflags = do let ofile = outputFile dflags when (isJust ofile) $ do let fn = fromJust ofile flg <- doesDirNameExist fn when (not flg) (nonExistentDir "-o" fn) let ohi = outputHi dflags when (isJust ohi) $ do let hi = fromJust ohi flg <- doesDirNameExist hi when (not flg) (nonExistentDir "-ohi" hi) where nonExistentDir flg dir = throwGhcException (CmdLineError ("error: directory portion of " ++ show dir ++ " does not exist (used with " ++ show flg ++ " option.)")) ----------------------------------------------------------------------------- -- GHC modes of operation type Mode = Either PreStartupMode PostStartupMode type PostStartupMode = Either PreLoadMode PostLoadMode data PreStartupMode = ShowVersion -- ghc -V/--version | ShowNumVersion -- ghc --numeric-version | ShowSupportedExtensions -- ghc --supported-extensions | ShowOptions Bool {- isInteractive -} -- ghc --show-options showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode showVersionMode = mkPreStartupMode ShowVersion showNumVersionMode = mkPreStartupMode ShowNumVersion showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions showOptionsMode = mkPreStartupMode (ShowOptions False) mkPreStartupMode :: PreStartupMode -> Mode mkPreStartupMode = Left isShowVersionMode :: Mode -> Bool isShowVersionMode (Left ShowVersion) = True isShowVersionMode _ = False isShowNumVersionMode :: Mode -> Bool isShowNumVersionMode (Left ShowNumVersion) = True isShowNumVersionMode _ = False data PreLoadMode = ShowGhcUsage -- ghc -? | ShowGhciUsage -- ghci -? | ShowInfo -- ghc --info | PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode showGhcUsageMode = mkPreLoadMode ShowGhcUsage showGhciUsageMode = mkPreLoadMode ShowGhciUsage showInfoMode = mkPreLoadMode ShowInfo printSetting :: String -> Mode printSetting k = mkPreLoadMode (PrintWithDynFlags f) where f dflags = fromMaybe (panic ("Setting not found: " ++ show k)) $ lookup k (compilerInfo dflags) mkPreLoadMode :: PreLoadMode -> Mode mkPreLoadMode = Right . Left isShowGhcUsageMode :: Mode -> Bool isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True isShowGhcUsageMode _ = False isShowGhciUsageMode :: Mode -> Bool isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True isShowGhciUsageMode _ = False data PostLoadMode = ShowInterface FilePath -- ghc --show-iface | DoMkDependHS -- ghc -M | StopBefore Phase -- ghc -E | -C | -S -- StopBefore StopLn is the default | DoMake -- ghc --make | DoInteractive -- ghc --interactive | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"] | DoAbiHash -- ghc --abi-hash | ShowPackages -- ghc --show-packages doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode, showPackagesMode :: Mode doMkDependHSMode = mkPostLoadMode DoMkDependHS doMakeMode = mkPostLoadMode DoMake doInteractiveMode = mkPostLoadMode DoInteractive doAbiHashMode = mkPostLoadMode DoAbiHash showPackagesMode = mkPostLoadMode ShowPackages showInterfaceMode :: FilePath -> Mode showInterfaceMode fp = mkPostLoadMode (ShowInterface fp) stopBeforeMode :: Phase -> Mode stopBeforeMode phase = mkPostLoadMode (StopBefore phase) doEvalMode :: String -> Mode doEvalMode str = mkPostLoadMode (DoEval [str]) mkPostLoadMode :: PostLoadMode -> Mode mkPostLoadMode = Right . Right isDoInteractiveMode :: Mode -> Bool isDoInteractiveMode (Right (Right DoInteractive)) = True isDoInteractiveMode _ = False isStopLnMode :: Mode -> Bool isStopLnMode (Right (Right (StopBefore StopLn))) = True isStopLnMode _ = False isDoMakeMode :: Mode -> Bool isDoMakeMode (Right (Right DoMake)) = True isDoMakeMode _ = False #ifdef GHCI isInteractiveMode :: PostLoadMode -> Bool isInteractiveMode DoInteractive = True isInteractiveMode _ = False #endif -- isInterpretiveMode: byte-code compiler involved isInterpretiveMode :: PostLoadMode -> Bool isInterpretiveMode DoInteractive = True isInterpretiveMode (DoEval _) = True isInterpretiveMode _ = False needsInputsMode :: PostLoadMode -> Bool needsInputsMode DoMkDependHS = True needsInputsMode (StopBefore _) = True needsInputsMode DoMake = True needsInputsMode _ = False -- True if we are going to attempt to link in this mode. -- (we might not actually link, depending on the GhcLink flag) isLinkMode :: PostLoadMode -> Bool isLinkMode (StopBefore StopLn) = True isLinkMode DoMake = True isLinkMode DoInteractive = True isLinkMode (DoEval _) = True isLinkMode _ = False isCompManagerMode :: PostLoadMode -> Bool isCompManagerMode DoMake = True isCompManagerMode DoInteractive = True isCompManagerMode (DoEval _) = True isCompManagerMode _ = False -- ----------------------------------------------------------------------------- -- Parsing the mode flag parseModeFlags :: [Located String] -> IO (Mode, [Located String], [Located String]) parseModeFlags args = do let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) = runCmdLine (processArgs mode_flags args) (Nothing, [], []) mode = case mModeFlag of Nothing -> doMakeMode Just (m, _) -> m -- See Note [Handling errors when parsing commandline flags] unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $ map (("on the commandline", )) $ map unLoc errs1 ++ errs2 return (mode, flags' ++ leftover, warns) type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String]) -- mode flags sometimes give rise to new DynFlags (eg. -C, see below) -- so we collect the new ones and return them. mode_flags :: [Flag ModeM] mode_flags = [ ------- help / version ---------------------------------------------- defFlag "?" (PassFlag (setMode showGhcUsageMode)) , defFlag "-help" (PassFlag (setMode showGhcUsageMode)) , defFlag "V" (PassFlag (setMode showVersionMode)) , defFlag "-version" (PassFlag (setMode showVersionMode)) , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode)) , defFlag "-info" (PassFlag (setMode showInfoMode)) , defFlag "-show-options" (PassFlag (setMode showOptionsMode)) , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-show-packages" (PassFlag (setMode showPackagesMode)) ] ++ [ defFlag k' (PassFlag (setMode (printSetting k))) | k <- ["Project version", "Project Git commit id", "Booter version", "Stage", "Build platform", "Host platform", "Target platform", "Have interpreter", "Object splitting supported", "Have native code generator", "Support SMP", "Unregisterised", "Tables next to code", "RTS ways", "Leading underscore", "Debug on", "LibDir", "Global Package DB", "C compiler flags", "Gcc Linker flags", "Ld Linker flags"], let k' = "-print-" ++ map (replaceSpace . toLower) k replaceSpace ' ' = '-' replaceSpace c = c ] ++ ------- interfaces ---------------------------------------------------- [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f) "--show-iface")) ------- primary modes ------------------------------------------------ , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f addFlag "-no-link" f)) , defFlag "M" (PassFlag (setMode doMkDependHSMode)) , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc))) , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc))) , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False)))) , defFlag "-make" (PassFlag (setMode doMakeMode)) , defFlag "-interactive" (PassFlag (setMode doInteractiveMode)) , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode)) , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e")) ] setMode :: Mode -> String -> EwM ModeM () setMode newMode newFlag = liftEwM $ do (mModeFlag, errs, flags') <- getCmdLineState let (modeFlag', errs') = case mModeFlag of Nothing -> ((newMode, newFlag), errs) Just (oldMode, oldFlag) -> case (oldMode, newMode) of -- -c/--make are allowed together, and mean --make -no-link _ | isStopLnMode oldMode && isDoMakeMode newMode || isStopLnMode newMode && isDoMakeMode oldMode -> ((doMakeMode, "--make"), []) -- If we have both --help and --interactive then we -- want showGhciUsage _ | isShowGhcUsageMode oldMode && isDoInteractiveMode newMode -> ((showGhciUsageMode, oldFlag), []) | isShowGhcUsageMode newMode && isDoInteractiveMode oldMode -> ((showGhciUsageMode, newFlag), []) -- Otherwise, --help/--version/--numeric-version always win | isDominantFlag oldMode -> ((oldMode, oldFlag), []) | isDominantFlag newMode -> ((newMode, newFlag), []) -- We need to accumulate eval flags like "-e foo -e bar" (Right (Right (DoEval esOld)), Right (Right (DoEval [eNew]))) -> ((Right (Right (DoEval (eNew : esOld))), oldFlag), errs) -- Saying e.g. --interactive --interactive is OK _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs) -- --interactive and --show-options are used together (Right (Right DoInteractive), Left (ShowOptions _)) -> ((Left (ShowOptions True), "--interactive --show-options"), errs) (Left (ShowOptions _), (Right (Right DoInteractive))) -> ((Left (ShowOptions True), "--show-options --interactive"), errs) -- Otherwise, complain _ -> let err = flagMismatchErr oldFlag newFlag in ((oldMode, oldFlag), err : errs) putCmdLineState (Just modeFlag', errs', flags') where isDominantFlag f = isShowGhcUsageMode f || isShowGhciUsageMode f || isShowVersionMode f || isShowNumVersionMode f flagMismatchErr :: String -> String -> String flagMismatchErr oldFlag newFlag = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'" addFlag :: String -> String -> EwM ModeM () addFlag s flag = liftEwM $ do (m, e, flags') <- getCmdLineState putCmdLineState (m, e, mkGeneralLocated loc s : flags') where loc = "addFlag by " ++ flag ++ " on the commandline" -- ---------------------------------------------------------------------------- -- Run --make mode doMake :: [(String,Maybe Phase)] -> Ghc () doMake srcs = do let (hs_srcs, non_hs_srcs) = partition haskellish srcs haskellish (f,Nothing) = looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f haskellish (_,Just phase) = phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm , StopLn] hsc_env <- GHC.getSession -- if we have no haskell sources from which to do a dependency -- analysis, then just do one-shot compilation and/or linking. -- This means that "ghc Foo.o Bar.o -o baz" links the program as -- we expect. if (null hs_srcs) then liftIO (oneShot hsc_env StopLn srcs) else do o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x) non_hs_srcs dflags <- GHC.getSessionDynFlags let dflags' = dflags { ldInputs = map (FileOption "") o_files ++ ldInputs dflags } _ <- GHC.setSessionDynFlags dflags' targets <- mapM (uncurry GHC.guessTarget) hs_srcs GHC.setTargets targets ok_flag <- GHC.load LoadAllTargets when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1)) return () -- --------------------------------------------------------------------------- -- --show-iface mode doShowIface :: DynFlags -> FilePath -> IO () doShowIface dflags file = do hsc_env <- newHscEnv dflags showIface hsc_env file -- --------------------------------------------------------------------------- -- Various banners and verbosity output. showBanner :: PostLoadMode -> DynFlags -> IO () showBanner _postLoadMode dflags = do let verb = verbosity dflags #ifdef GHCI -- Show the GHCi banner when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg #endif -- Display details of the configuration in verbose mode when (verb >= 2) $ do hPutStr stderr "Glasgow Haskell Compiler, Version " hPutStr stderr cProjectVersion hPutStr stderr ", stage " hPutStr stderr cStage hPutStr stderr " booted by GHC version " hPutStrLn stderr cBooterVersion -- We print out a Read-friendly string, but a prettier one than the -- Show instance gives us showInfo :: DynFlags -> IO () showInfo dflags = do let sq x = " [" ++ x ++ "\n ]" putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags showSupportedExtensions :: IO () showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions showVersion :: IO () showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion) showOptions :: Bool -> IO () showOptions isInteractive = putStr (unlines availableOptions) where availableOptions = concat [ flagsForCompletion isInteractive, map ('-':) (concat [ getFlagNames mode_flags , (filterUnwantedStatic . getFlagNames $ flagsStatic) , flagsStaticNames ]) ] getFlagNames opts = map flagName opts -- this is a hack to get rid of two unwanted entries that get listed -- as static flags. Hopefully this hack will disappear one day together -- with static flags filterUnwantedStatic = filter (`notElem`["f", "fno-"]) showGhcUsage :: DynFlags -> IO () showGhcUsage = showUsage False showGhciUsage :: DynFlags -> IO () showGhciUsage = showUsage True showUsage :: Bool -> DynFlags -> IO () showUsage ghci dflags = do let usage_path = if ghci then ghciUsagePath dflags else ghcUsagePath dflags usage <- readFile usage_path dump usage where dump "" = return () dump ('$':'$':s) = putStr progName >> dump s dump (c:s) = putChar c >> dump s dumpFinalStats :: DynFlags -> IO () dumpFinalStats dflags = when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags dumpFastStringStats :: DynFlags -> IO () dumpFastStringStats dflags = do buckets <- getFastStringTable let (entries, longest, has_z) = countFS 0 0 0 buckets msg = text "FastString stats:" $$ nest 4 (vcat [text "size: " <+> int (length buckets), text "entries: " <+> int entries, text "longest chain: " <+> int longest, text "has z-encoding: " <+> (has_z `pcntOf` entries) ]) -- we usually get more "has z-encoding" than "z-encoded", because -- when we z-encode a string it might hash to the exact same string, -- which will is not counted as "z-encoded". Only strings whose -- Z-encoding is different from the original string are counted in -- the "z-encoded" total. putMsg dflags msg where x `pcntOf` y = int ((x * 100) `quot` y) <> char '%' countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int) countFS entries longest has_z [] = (entries, longest, has_z) countFS entries longest has_z (b:bs) = let len = length b longest' = max len longest entries' = entries + len has_zs = length (filter hasZEncoding b) in countFS entries' longest' (has_z + has_zs) bs showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO () showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags)) dumpPackages dflags = putMsg dflags (pprPackages dflags) dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags) -- ----------------------------------------------------------------------------- -- ABI hash support {- ghc --abi-hash Data.Foo System.Bar Generates a combined hash of the ABI for modules Data.Foo and System.Bar. The modules must already be compiled, and appropriate -i options may be necessary in order to find the .hi files. This is used by Cabal for generating the InstalledPackageId for a package. The InstalledPackageId must change when the visible ABI of the package chagnes, so during registration Cabal calls ghc --abi-hash to get a hash of the package's ABI. -} -- | Print ABI hash of input modules. -- -- The resulting hash is the MD5 of the GHC version used (Trac #5328, -- see 'hiVersion') and of the existing ABI hash from each module (see -- 'mi_mod_hash'). abiHash :: [String] -- ^ List of module names -> Ghc () abiHash strs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env liftIO $ do let find_it str = do let modname = mkModuleName str r <- findImportedModule hsc_env modname Nothing case r of Found _ m -> return m _error -> throwGhcException $ CmdLineError $ showSDoc dflags $ cannotFindInterface dflags modname r mods <- mapM find_it strs let get_iface modl = loadUserInterface False (text "abiHash") modl ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods bh <- openBinMem (3*1024) -- just less than a block put_ bh hiVersion -- package hashes change when the compiler version changes (for now) -- see #5328 mapM_ (put_ bh . mi_mod_hash) ifaces f <- fingerprintBinMem bh putStrLn (showPpr dflags f) -- ----------------------------------------------------------------------------- -- Util unknownFlagsErr :: [String] -> a unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs where oneError f = "unrecognised flag: " ++ f ++ "\n" ++ (case fuzzyMatch f (nub allFlags) of [] -> "" suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs)) {- Note [-Bsymbolic and hooks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled (see `man ld`). When dynamically linking, we don't use -Bsymbolic on the RTS package: that is because we want hooks to be overridden by the user, we don't want to constrain them to the RTS package. Unfortunately this seems to have broken somehow on OS X: as a result, defaultHooks (in hschooks.c) is not called, which does not initialize the GC stats. As a result, this breaks things like `:set +s` in GHCi (#8754). As a hacky workaround, we instead call 'defaultHooks' directly to initalize the flags in the RTS. A byproduct of this, I believe, is that hooks are likely broken on OS X when dynamically linking. But this probably doesn't affect most people since we're linking GHC dynamically, but most things themselves link statically. -} foreign import ccall safe "initGCStatistics" initGCStatistics :: IO ()
urbanslug/ghc
ghc/Main.hs
bsd-3-clause
34,965
10
27
9,749
7,130
3,681
3,449
547
15
import Test.FFmpeg as FFmpeg import Test.FFmpeg.H264 as H264 main :: IO () main = do H264.test FFmpeg.test
YLiLarry/compress-video
test/Spec.hs
bsd-3-clause
114
0
7
24
41
23
18
6
1
{-| Module : Data.Network.MRT Description : Multi-Threaded Routing Toolkit Export Information Format types License : BSD3 Stability : Experimental MRT is a library for parsing Multi-Threaded Routing Toolkit (MRT) export files, of the kind you might find on the RouteViews archive. -} {-# LANGUAGE LambdaCase #-} module Data.Network.MRT ( Timestamp , ASNumber , ASPathSegment , BGPAttributeValue ( Origin , ASPath , NextHop , LocalPref , AtomicAggregate , UnknownAttribute) , BGPAttributeFlags (isOptional, isTransitive, isPartial, isExtLength) , BGPAttribute (BGPAttribute) , RIBEntry , getPeerIndex , getOriginationTime , getBGPAttributes , MRTRecord (TableDumpV2, Other) , getSequenceNo , getPrefix , getRIBEntries , getSkippedBytes , MRTMessage , getMessageTimestamp , getRecord , readMessages -- re-export IPs , IPRange ) where import Control.Monad (liftM, replicateM) import Data.Binary import Data.Binary.Get import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.IP import Data.Maybe (listToMaybe) import Data.Network.BGP -- |The `Timestamp` type alias represents a BGP timestamp attribute, -- recorded as seconds since the Unix epoch. type Timestamp = Word32 -- instance Show BGPAttributeFlags where -- show (BGPAttributeFlags o t p e) = map snd $ filter fst $ zip [o, t, p, e] "OTPE" data RIBEntry = RIBEntry { getPeerIndex :: Word16 , getOriginationTime :: Timestamp , getBGPAttributes :: [BGPAttribute] } deriving (Show) data MRTRecord = TableDumpV2 { getSequenceNo :: Word32 , getPrefix :: IPRange , getRIBEntries :: [RIBEntry] } | Other { getTypeCode :: Word16 , getSubType :: Word16 , getSkippedBytes :: Word32 } deriving (Show) data MRTMessage = MRTMessage { getMessageTimestamp :: Timestamp , getRecord :: MRTRecord } deriving (Show) getIPRange :: (Addr a) => (AddrRange a -> IPRange) -> ([Int] -> a) -> Int -> Get IPRange getIPRange toRange toAddr bits = do maskLength <- liftM fromIntegral getWord8 let dataLength = (maskLength - 1) `div` 8 + 1 bytes <- liftM (take bits . (++ replicate bits 0) . BS.unpack) (getByteString dataLength) let address = toAddr (map fromIntegral bytes) let range = makeAddrRange address maskLength return $ toRange range getIPv4Range :: Get IPRange getIPv4Range = getIPRange IPv4Range toIPv4 4 getIPv6Range :: Get IPRange getIPv6Range = getIPRange IPv6Range toIPv6b 16 getBytes16be :: Get BL.ByteString getBytes16be = getWord16be >>= getLazyByteString . fromIntegral getBytes32be :: Get BL.ByteString getBytes32be = getWord32be >>= getLazyByteString . fromIntegral getAttributes :: Get [BGPAttribute] getAttributes = do empty <- isEmpty if empty then return [] else (:) <$> get <*> getAttributes getRIBEntry :: Get RIBEntry getRIBEntry = RIBEntry <$> getWord16be <*> getWord32be <*> liftM (runGet getAttributes) getBytes16be getTimes :: (Integral a) => a -> Get b -> Get [b] getTimes = replicateM . fromIntegral readPayload :: Word16 -> Word16 -> BL.ByteString -> MRTRecord readPayload 13 2 d = flip runGet d $ TableDumpV2 <$> getWord32be <*> getIPv4Range <*> (getWord16be >>= flip getTimes getRIBEntry) readPayload 13 4 d = flip runGet d $ TableDumpV2 <$> getWord32be <*> getIPv6Range <*> (getWord16be >>= flip getTimes getRIBEntry) readPayload t s d = Other t s $ fromIntegral (BL.length d) readMessage :: Get MRTMessage readMessage = do timestamp' <- getWord32be payload' <- readPayload <$> getWord16be <*> getWord16be <*> getBytes32be return $ MRTMessage timestamp' payload' readMessages :: BL.ByteString -> [MRTMessage] readMessages input = more (BL.toChunks input) where more = go (runGetIncremental readMessage) go :: Decoder MRTMessage -> [BS.ByteString] -> [MRTMessage] go (Done r _ m) i = m : case i of { [] -> []; _ -> more $ r : i } go (Partial k) i = go (k . listToMaybe $ i) (drop 1 i) go (Fail _ o s) _ = error (s ++ " at " ++ show o)
codebje/hask-mrt
src/Data/Network/MRT.hs
bsd-3-clause
4,659
0
13
1,405
1,097
604
493
110
4
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveGeneric #-} -- | Lua 5.3 syntax tree, as specified in <http://www.lua.org/manual/5.3/manual.html#9>. -- Annotation implementation is inspired by haskell-src-exts. module Language.Lua.Annotated.Syntax where import Control.DeepSeq (NFData) import Data.Data (Data, Typeable) import GHC.Generics (Generic) import Prelude hiding (EQ, GT, LT) data Name a = Name a String deriving (Show, Eq, Functor, Data, Typeable, Generic) data Stat a = Assign a [Var a] [Exp a] -- ^var1, var2 .. = exp1, exp2 .. | FunCall a (FunCall a) -- ^function call | Label a (Name a) -- ^label for goto | Break a -- ^break | Goto a (Name a) -- ^goto label | Do a (Block a) -- ^do .. end | While a (Exp a) (Block a) -- ^while .. do .. end | Repeat a (Block a) (Exp a) -- ^repeat .. until .. | If a [(Exp a, Block a)] (Maybe (Block a)) -- ^if .. then .. [elseif ..] [else ..] end | ForRange a (Name a) (Exp a) (Exp a) (Maybe (Exp a)) (Block a) -- ^for x=start, end [, step] do .. end | ForIn a [Name a] [Exp a] (Block a) -- ^for x in .. do .. end | FunAssign a (FunName a) (FunBody a) -- ^function \<var\> (..) .. end | LocalFunAssign a (Name a) (FunBody a) -- ^local function \<var\> (..) .. end | LocalAssign a [Name a] (Maybe [Exp a]) -- ^local var1, var2 .. = exp1, exp2 .. | EmptyStat a -- ^/;/ deriving (Show, Eq, Functor, Data, Typeable, Generic) data Exp a = Nil a | Bool a Bool | Number a String | String a String | Vararg a -- ^/.../ | EFunDef a (FunDef a) -- ^/function (..) .. end/ | PrefixExp a (PrefixExp a) | TableConst a (Table a) -- ^table constructor | Binop a (Binop a) (Exp a) (Exp a) -- ^binary operators, /+ - * ^ % .. < <= > >= == ~= and or/ | Unop a (Unop a) (Exp a) -- ^unary operators, /- not #/ deriving (Show, Eq, Functor, Data, Typeable, Generic) data Var a = VarName a (Name a) -- ^variable | Select a (PrefixExp a) (Exp a) -- ^/table[exp]/ | SelectName a (PrefixExp a) (Name a) -- ^/table.variable/ deriving (Show, Eq, Functor, Data, Typeable, Generic) data Binop a = Add a | Sub a | Mul a | Div a | Exp a | Mod a | Concat a | LT a | LTE a | GT a | GTE a | EQ a | NEQ a | And a | Or a | IDiv a | ShiftL a | ShiftR a | BAnd a | BOr a | BXor a deriving (Show, Eq, Functor, Data, Typeable, Generic) data Unop a = Neg a | Not a | Len a | Complement a deriving (Show, Eq, Functor, Data, Typeable, Generic) data PrefixExp a = PEVar a (Var a) | PEFunCall a (FunCall a) | Paren a (Exp a) deriving (Show, Eq, Functor, Data, Typeable, Generic) data Table a = Table a [TableField a] -- ^list of table fields deriving (Show, Eq, Functor, Data, Typeable, Generic) data TableField a = ExpField a (Exp a) (Exp a) -- ^/[exp] = exp/ | NamedField a (Name a) (Exp a) -- ^/name = exp/ | Field a (Exp a) deriving (Show, Eq, Functor, Data, Typeable, Generic) -- | A block is list of statements with optional return statement. data Block a = Block a [Stat a] (Maybe [Exp a]) deriving (Show, Eq, Functor, Data, Typeable, Generic) data FunName a = FunName a (Name a) [Name a] (Maybe (Name a)) deriving (Show, Eq, Functor, Data, Typeable, Generic) data FunDef a = FunDef a (FunBody a) deriving (Show, Eq, Functor, Data, Typeable, Generic) data FunBody a = FunBody a [Name a] (Maybe a) (Block a) -- ^(args, vararg, block) deriving (Show, Eq, Functor, Data, Typeable, Generic) data FunCall a = NormalFunCall a (PrefixExp a) (FunArg a) -- ^/prefixexp ( funarg )/ | MethodCall a (PrefixExp a) (Name a) (FunArg a) -- ^/prefixexp : name ( funarg )/ deriving (Show, Eq, Functor, Data, Typeable, Generic) data FunArg a = Args a [Exp a] -- ^list of args | TableArg a (Table a) -- ^table constructor | StringArg a String -- ^string deriving (Show, Eq, Functor, Data, Typeable, Generic) class Functor ast => Annotated ast where -- | Retrieve the annotation of an AST node. ann :: ast l -> l -- | Change the annotation of an AST node. Note that only the annotation of -- the node itself is affected, and not the annotations of any child nodes. -- if all nodes in the AST tree are to be affected, use 'fmap'. amap :: (l -> l) -> ast l -> ast l instance Annotated Stat where ann (Assign a _ _) = a ann (FunCall a _) = a ann (Label a _) = a ann (Break a) = a ann (Goto a _) = a ann (Do a _) = a ann (While a _ _) = a ann (Repeat a _ _) = a ann (If a _ _) = a ann (ForRange a _ _ _ _ _) = a ann (ForIn a _ _ _) = a ann (FunAssign a _ _) = a ann (LocalFunAssign a _ _) = a ann (LocalAssign a _ _) = a ann (EmptyStat a) = a amap f (Assign a x1 x2) = Assign (f a) x1 x2 amap f (FunCall a x1) = FunCall (f a) x1 amap f (Label a x1) = Label (f a) x1 amap f (Break a) = Break (f a) amap f (Goto a x1) = Goto (f a) x1 amap f (Do a x1) = Do (f a) x1 amap f (While a x1 x2) = While (f a) x1 x2 amap f (Repeat a x1 x2) = Repeat (f a) x1 x2 amap f (If a x1 x2) = If (f a) x1 x2 amap f (ForRange a x1 x2 x3 x4 x5) = ForRange (f a) x1 x2 x3 x4 x5 amap f (ForIn a x1 x2 x3) = ForIn (f a) x1 x2 x3 amap f (FunAssign a x1 x2) = FunAssign (f a) x1 x2 amap f (LocalFunAssign a x1 x2) = LocalFunAssign (f a) x1 x2 amap f (LocalAssign a x1 x2) = LocalAssign (f a) x1 x2 amap f (EmptyStat a) = EmptyStat (f a) instance Annotated Exp where ann (Nil a) = a ann (Bool a _) = a ann (Number a _) = a ann (String a _) = a ann (Vararg a) = a ann (EFunDef a _) = a ann (PrefixExp a _) = a ann (TableConst a _) = a ann (Binop a _ _ _) = a ann (Unop a _ _) = a amap f (Nil a) = Nil (f a) amap f (Bool a x1) = Bool (f a) x1 amap f (Number a x1) = Number (f a) x1 amap f (String a x1) = String (f a) x1 amap f (Vararg a) = Vararg (f a) amap f (EFunDef a x1) = EFunDef (f a) x1 amap f (PrefixExp a x1) = PrefixExp (f a) x1 amap f (TableConst a x1) = TableConst (f a) x1 amap f (Binop a x1 x2 x3) = Binop (f a) x1 x2 x3 amap f (Unop a x1 x2) = Unop (f a) x1 x2 instance Annotated Var where ann (VarName a _) = a ann (Select a _ _) = a ann (SelectName a _ _) = a amap f (VarName a x1) = VarName (f a) x1 amap f (Select a x1 x2) = Select (f a) x1 x2 amap f (SelectName a x1 x2) = SelectName (f a) x1 x2 instance Annotated Binop where ann (Add a) = a ann (Sub a) = a ann (Mul a) = a ann (Div a) = a ann (Exp a) = a ann (Mod a) = a ann (Concat a) = a ann (LT a) = a ann (LTE a) = a ann (GT a) = a ann (GTE a) = a ann (EQ a) = a ann (NEQ a) = a ann (And a) = a ann (Or a) = a ann (BAnd a) = a ann (BOr a) = a ann (BXor a) = a ann (ShiftL a) = a ann (ShiftR a) = a ann (IDiv a) = a amap f (Add a) = Add (f a) amap f (Sub a) = Sub (f a) amap f (Mul a) = Mul (f a) amap f (Div a) = Div (f a) amap f (Exp a) = Exp (f a) amap f (Mod a) = Mod (f a) amap f (Concat a) = Concat (f a) amap f (LT a) = LT (f a) amap f (LTE a) = LTE (f a) amap f (GT a) = GT (f a) amap f (GTE a) = GTE (f a) amap f (EQ a) = EQ (f a) amap f (NEQ a) = NEQ (f a) amap f (And a) = And (f a) amap f (Or a) = Or (f a) amap f (BAnd a) = BAnd (f a) amap f (BOr a) = BOr (f a) amap f (BXor a) = BXor (f a) amap f (ShiftL a) = ShiftL (f a) amap f (ShiftR a) = ShiftR (f a) amap f (IDiv a) = IDiv (f a) instance Annotated Unop where ann (Neg a) = a ann (Not a) = a ann (Len a) = a ann (Complement a) = a amap f (Neg a) = Neg (f a) amap f (Not a) = Not (f a) amap f (Len a) = Len (f a) amap f (Complement a) = Complement (f a) instance Annotated PrefixExp where ann (PEVar a _) = a ann (PEFunCall a _) = a ann (Paren a _) = a amap f (PEVar a x1) = PEVar (f a) x1 amap f (PEFunCall a x1) = PEFunCall (f a) x1 amap f (Paren a x1) = Paren (f a) x1 instance Annotated Table where ann (Table a _) = a amap f (Table a x1) = Table (f a) x1 instance Annotated TableField where ann (ExpField a _ _) = a ann (NamedField a _ _) = a ann (Field a _) = a amap f (ExpField a x1 x2) = ExpField (f a) x1 x2 amap f (NamedField a x1 x2) = NamedField (f a) x1 x2 amap f (Field a x1) = Field (f a) x1 instance Annotated Block where ann (Block a _ _) = a amap f (Block a x1 x2) = Block (f a) x1 x2 instance Annotated FunName where ann (FunName a _ _ _) = a amap f (FunName a x1 x2 x3) = FunName (f a) x1 x2 x3 instance Annotated FunDef where ann (FunDef a _) = a amap f (FunDef a x1) = FunDef (f a) x1 instance Annotated FunBody where ann (FunBody a _ _ _) = a amap f (FunBody a x1 x2 x3) = FunBody (f a) x1 x2 x3 instance Annotated FunCall where ann (NormalFunCall a _ _) = a ann (MethodCall a _ _ _) = a amap f (NormalFunCall a x1 x2) = NormalFunCall (f a) x1 x2 amap f (MethodCall a x1 x2 x3) = MethodCall (f a) x1 x2 x3 instance Annotated FunArg where ann (Args a _) = a ann (TableArg a _) = a ann (StringArg a _) = a amap f (Args a x1) = Args (f a) x1 amap f (TableArg a x1) = TableArg (f a) x1 amap f (StringArg a x1) = StringArg (f a) x1 instance Annotated Name where ann (Name a _) = a amap f (Name a x1) = Name (f a) x1 instance NFData a => NFData (Name a) instance NFData a => NFData (Stat a) instance NFData a => NFData (Exp a) instance NFData a => NFData (Var a) instance NFData a => NFData (Binop a) instance NFData a => NFData (Unop a) instance NFData a => NFData (PrefixExp a) instance NFData a => NFData (Table a) instance NFData a => NFData (TableField a) instance NFData a => NFData (Block a) instance NFData a => NFData (FunName a) instance NFData a => NFData (FunDef a) instance NFData a => NFData (FunBody a) instance NFData a => NFData (FunCall a) instance NFData a => NFData (FunArg a)
osa1/language-lua
src/Language/Lua/Annotated/Syntax.hs
bsd-3-clause
10,126
0
10
2,984
5,105
2,580
2,525
249
0
{- buddhabrot reimplementation based on C source at: http://paulbourke.net/fractals/buddhabrot/ see also: http://www.superliminal.com/fractals/bbrot/bbrot.htm http://erleuchtet.org/2010/07/ridiculously-large-buddhabrot.html http://www.steckles.com/buddha/ http://softologyblog.wordpress.com/2011/06/26/buddhabrot-fractals/ http://kindofdoon.blogspot.fr/2012/09/the-colored-orbit-buddhabrot.html -} {-# OPTIONS_GHC -fno-cse #-} -- required by cmdArgs :-( module Main(main) where import System.Console.CmdArgs import BBrotCompute import BBrotConf import BBrotRender -- Note: CmdArgs annotations are impure, they can be used only once getConf :: IO BBrotConf getConf = cmdArgs $ modes [ Compute { seed = Nothing &= name "s" , samples = 1000 * 300 &= name "n" , minIters = 1000 * 100 &= name "k" , maxIters = 1000 * 200 &= name "K" , ocachepath = Nothing &= name "c" &= typFile , gridStep = 0.001 &= name "g" }, Render { xpixels = 1000 &= name "x" , ypixels = 1000 &= name "y" , icachepath = def &= name "c" &= typFile , isComplex = False &= name "z" , dontRender = False &= name "r" , imagepath = Nothing &= name "o" &= typFile , palette = Flames &= name "p" , curve = Root &= name "C" }, ShowCells { gridStep = 0.001 &= name "g" , maxIters = 1000 &= name "K" , animpath = "cells.gif" &= name "o" &= typFile } ] &= program "buddhabrot" &= verbosity main :: IO () main = do -- Note: CmdArgs annotations are impure, they can be used only once conf <- getConf case conf of Compute{} -> compute conf Render{} -> render conf ShowCells{} -> showCells conf whenNormal $ putStrLn "Done!"
saffroy/buddhabrot
buddhabrot.hs
bsd-3-clause
2,213
0
14
881
402
214
188
34
3
{-# OPTIONS_HADDOCK hide #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.Functions.F07 -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- Raw functions from the -- <http://www.opengl.org/registry/ OpenGL registry>. -- -------------------------------------------------------------------------------- module Graphics.GL.Functions.F07 ( glDrawTexxOES, glDrawTexxvOES, glDrawTransformFeedback, glDrawTransformFeedbackEXT, glDrawTransformFeedbackInstanced, glDrawTransformFeedbackInstancedEXT, glDrawTransformFeedbackNV, glDrawTransformFeedbackStream, glDrawTransformFeedbackStreamInstanced, glDrawVkImageNV, glEGLImageTargetRenderbufferStorageOES, glEGLImageTargetTexStorageEXT, glEGLImageTargetTexture2DOES, glEGLImageTargetTextureStorageEXT, glEdgeFlag, glEdgeFlagFormatNV, glEdgeFlagPointer, glEdgeFlagPointerEXT, glEdgeFlagPointerListIBM, glEdgeFlagv, glElementPointerAPPLE, glElementPointerATI, glEnable, glEnableClientState, glEnableClientStateIndexedEXT, glEnableClientStateiEXT, glEnableDriverControlQCOM, glEnableIndexedEXT, glEnableVariantClientStateEXT, glEnableVertexArrayAttrib, glEnableVertexArrayAttribEXT, glEnableVertexArrayEXT, glEnableVertexAttribAPPLE, glEnableVertexAttribArray, glEnableVertexAttribArrayARB, glEnablei, glEnableiEXT, glEnableiNV, glEnableiOES, glEnd, glEndConditionalRender, glEndConditionalRenderNV, glEndConditionalRenderNVX, glEndFragmentShaderATI, glEndList, glEndOcclusionQueryNV, glEndPerfMonitorAMD, glEndPerfQueryINTEL, glEndQuery, glEndQueryARB, glEndQueryEXT, glEndQueryIndexed, glEndTilingQCOM, glEndTransformFeedback, glEndTransformFeedbackEXT, glEndTransformFeedbackNV, glEndVertexShaderEXT, glEndVideoCaptureNV, glEvalCoord1d, glEvalCoord1dv, glEvalCoord1f, glEvalCoord1fv, glEvalCoord1xOES, glEvalCoord1xvOES, glEvalCoord2d, glEvalCoord2dv, glEvalCoord2f, glEvalCoord2fv, glEvalCoord2xOES, glEvalCoord2xvOES, glEvalMapsNV, glEvalMesh1, glEvalMesh2, glEvalPoint1, glEvalPoint2, glEvaluateDepthValuesARB, glExecuteProgramNV, glExtGetBufferPointervQCOM, glExtGetBuffersQCOM, glExtGetFramebuffersQCOM, glExtGetProgramBinarySourceQCOM, glExtGetProgramsQCOM, glExtGetRenderbuffersQCOM, glExtGetShadersQCOM, glExtGetTexLevelParameterivQCOM, glExtGetTexSubImageQCOM, glExtGetTexturesQCOM, glExtIsProgramBinaryQCOM, glExtTexObjectStateOverrideiQCOM, glExtractComponentEXT, glFeedbackBuffer, glFeedbackBufferxOES, glFenceSync, glFenceSyncAPPLE, glFinalCombinerInputNV, glFinish, glFinishAsyncSGIX, glFinishFenceAPPLE, glFinishFenceNV, glFinishObjectAPPLE ) where import Control.Monad.IO.Class ( MonadIO(..) ) import Foreign.Ptr import Graphics.GL.Foreign import Graphics.GL.Types import System.IO.Unsafe ( unsafePerformIO ) -- glDrawTexxOES --------------------------------------------------------------- -- | The vector equivalent of this command is 'glDrawTexxvOES'. glDrawTexxOES :: MonadIO m => GLfixed -- ^ @x@. -> GLfixed -- ^ @y@. -> GLfixed -- ^ @z@. -> GLfixed -- ^ @width@. -> GLfixed -- ^ @height@. -> m () glDrawTexxOES v1 v2 v3 v4 v5 = liftIO $ dyn264 ptr_glDrawTexxOES v1 v2 v3 v4 v5 {-# NOINLINE ptr_glDrawTexxOES #-} ptr_glDrawTexxOES :: FunPtr (GLfixed -> GLfixed -> GLfixed -> GLfixed -> GLfixed -> IO ()) ptr_glDrawTexxOES = unsafePerformIO $ getCommand "glDrawTexxOES" -- glDrawTexxvOES -------------------------------------------------------------- glDrawTexxvOES :: MonadIO m => Ptr GLfixed -- ^ @coords@ pointing to @5@ elements of type @GLfixed@. -> m () glDrawTexxvOES v1 = liftIO $ dyn114 ptr_glDrawTexxvOES v1 {-# NOINLINE ptr_glDrawTexxvOES #-} ptr_glDrawTexxvOES :: FunPtr (Ptr GLfixed -> IO ()) ptr_glDrawTexxvOES = unsafePerformIO $ getCommand "glDrawTexxvOES" -- glDrawTransformFeedback ----------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glDrawTransformFeedback.xhtml OpenGL 4.x>. glDrawTransformFeedback :: MonadIO m => GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType). -> GLuint -- ^ @id@. -> m () glDrawTransformFeedback v1 v2 = liftIO $ dyn19 ptr_glDrawTransformFeedback v1 v2 {-# NOINLINE ptr_glDrawTransformFeedback #-} ptr_glDrawTransformFeedback :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glDrawTransformFeedback = unsafePerformIO $ getCommand "glDrawTransformFeedback" -- glDrawTransformFeedbackEXT -------------------------------------------------- -- | This command is an alias for 'glDrawTransformFeedback'. glDrawTransformFeedbackEXT :: MonadIO m => GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType). -> GLuint -- ^ @id@. -> m () glDrawTransformFeedbackEXT v1 v2 = liftIO $ dyn19 ptr_glDrawTransformFeedbackEXT v1 v2 {-# NOINLINE ptr_glDrawTransformFeedbackEXT #-} ptr_glDrawTransformFeedbackEXT :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glDrawTransformFeedbackEXT = unsafePerformIO $ getCommand "glDrawTransformFeedbackEXT" -- glDrawTransformFeedbackInstanced -------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glDrawTransformFeedbackInstanced.xhtml OpenGL 4.x>. glDrawTransformFeedbackInstanced :: MonadIO m => GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType). -> GLuint -- ^ @id@. -> GLsizei -- ^ @instancecount@. -> m () glDrawTransformFeedbackInstanced v1 v2 v3 = liftIO $ dyn265 ptr_glDrawTransformFeedbackInstanced v1 v2 v3 {-# NOINLINE ptr_glDrawTransformFeedbackInstanced #-} ptr_glDrawTransformFeedbackInstanced :: FunPtr (GLenum -> GLuint -> GLsizei -> IO ()) ptr_glDrawTransformFeedbackInstanced = unsafePerformIO $ getCommand "glDrawTransformFeedbackInstanced" -- glDrawTransformFeedbackInstancedEXT ----------------------------------------- -- | This command is an alias for 'glDrawTransformFeedbackInstanced'. glDrawTransformFeedbackInstancedEXT :: MonadIO m => GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType). -> GLuint -- ^ @id@. -> GLsizei -- ^ @instancecount@. -> m () glDrawTransformFeedbackInstancedEXT v1 v2 v3 = liftIO $ dyn265 ptr_glDrawTransformFeedbackInstancedEXT v1 v2 v3 {-# NOINLINE ptr_glDrawTransformFeedbackInstancedEXT #-} ptr_glDrawTransformFeedbackInstancedEXT :: FunPtr (GLenum -> GLuint -> GLsizei -> IO ()) ptr_glDrawTransformFeedbackInstancedEXT = unsafePerformIO $ getCommand "glDrawTransformFeedbackInstancedEXT" -- glDrawTransformFeedbackNV --------------------------------------------------- -- | This command is an alias for 'glDrawTransformFeedback'. glDrawTransformFeedbackNV :: MonadIO m => GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType). -> GLuint -- ^ @id@. -> m () glDrawTransformFeedbackNV v1 v2 = liftIO $ dyn19 ptr_glDrawTransformFeedbackNV v1 v2 {-# NOINLINE ptr_glDrawTransformFeedbackNV #-} ptr_glDrawTransformFeedbackNV :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glDrawTransformFeedbackNV = unsafePerformIO $ getCommand "glDrawTransformFeedbackNV" -- glDrawTransformFeedbackStream ----------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glDrawTransformFeedbackStream.xhtml OpenGL 4.x>. glDrawTransformFeedbackStream :: MonadIO m => GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType). -> GLuint -- ^ @id@. -> GLuint -- ^ @stream@. -> m () glDrawTransformFeedbackStream v1 v2 v3 = liftIO $ dyn20 ptr_glDrawTransformFeedbackStream v1 v2 v3 {-# NOINLINE ptr_glDrawTransformFeedbackStream #-} ptr_glDrawTransformFeedbackStream :: FunPtr (GLenum -> GLuint -> GLuint -> IO ()) ptr_glDrawTransformFeedbackStream = unsafePerformIO $ getCommand "glDrawTransformFeedbackStream" -- glDrawTransformFeedbackStreamInstanced -------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glDrawTransformFeedbackStreamInstanced.xhtml OpenGL 4.x>. glDrawTransformFeedbackStreamInstanced :: MonadIO m => GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType). -> GLuint -- ^ @id@. -> GLuint -- ^ @stream@. -> GLsizei -- ^ @instancecount@. -> m () glDrawTransformFeedbackStreamInstanced v1 v2 v3 v4 = liftIO $ dyn257 ptr_glDrawTransformFeedbackStreamInstanced v1 v2 v3 v4 {-# NOINLINE ptr_glDrawTransformFeedbackStreamInstanced #-} ptr_glDrawTransformFeedbackStreamInstanced :: FunPtr (GLenum -> GLuint -> GLuint -> GLsizei -> IO ()) ptr_glDrawTransformFeedbackStreamInstanced = unsafePerformIO $ getCommand "glDrawTransformFeedbackStreamInstanced" -- glDrawVkImageNV ------------------------------------------------------------- glDrawVkImageNV :: MonadIO m => GLuint64 -- ^ @vkImage@. -> GLuint -- ^ @sampler@. -> GLfloat -- ^ @x0@. -> GLfloat -- ^ @y0@. -> GLfloat -- ^ @x1@. -> GLfloat -- ^ @y1@. -> GLfloat -- ^ @z@. -> GLfloat -- ^ @s0@. -> GLfloat -- ^ @t0@. -> GLfloat -- ^ @s1@. -> GLfloat -- ^ @t1@. -> m () glDrawVkImageNV v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 = liftIO $ dyn266 ptr_glDrawVkImageNV v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 {-# NOINLINE ptr_glDrawVkImageNV #-} ptr_glDrawVkImageNV :: FunPtr (GLuint64 -> GLuint -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ()) ptr_glDrawVkImageNV = unsafePerformIO $ getCommand "glDrawVkImageNV" -- glEGLImageTargetRenderbufferStorageOES -------------------------------------- glEGLImageTargetRenderbufferStorageOES :: MonadIO m => GLenum -- ^ @target@. -> GLeglImageOES -- ^ @image@. -> m () glEGLImageTargetRenderbufferStorageOES v1 v2 = liftIO $ dyn267 ptr_glEGLImageTargetRenderbufferStorageOES v1 v2 {-# NOINLINE ptr_glEGLImageTargetRenderbufferStorageOES #-} ptr_glEGLImageTargetRenderbufferStorageOES :: FunPtr (GLenum -> GLeglImageOES -> IO ()) ptr_glEGLImageTargetRenderbufferStorageOES = unsafePerformIO $ getCommand "glEGLImageTargetRenderbufferStorageOES" -- glEGLImageTargetTexStorageEXT ----------------------------------------------- glEGLImageTargetTexStorageEXT :: MonadIO m => GLenum -- ^ @target@. -> GLeglImageOES -- ^ @image@. -> Ptr GLint -- ^ @attrib_list@. -> m () glEGLImageTargetTexStorageEXT v1 v2 v3 = liftIO $ dyn268 ptr_glEGLImageTargetTexStorageEXT v1 v2 v3 {-# NOINLINE ptr_glEGLImageTargetTexStorageEXT #-} ptr_glEGLImageTargetTexStorageEXT :: FunPtr (GLenum -> GLeglImageOES -> Ptr GLint -> IO ()) ptr_glEGLImageTargetTexStorageEXT = unsafePerformIO $ getCommand "glEGLImageTargetTexStorageEXT" -- glEGLImageTargetTexture2DOES ------------------------------------------------ glEGLImageTargetTexture2DOES :: MonadIO m => GLenum -- ^ @target@. -> GLeglImageOES -- ^ @image@. -> m () glEGLImageTargetTexture2DOES v1 v2 = liftIO $ dyn267 ptr_glEGLImageTargetTexture2DOES v1 v2 {-# NOINLINE ptr_glEGLImageTargetTexture2DOES #-} ptr_glEGLImageTargetTexture2DOES :: FunPtr (GLenum -> GLeglImageOES -> IO ()) ptr_glEGLImageTargetTexture2DOES = unsafePerformIO $ getCommand "glEGLImageTargetTexture2DOES" -- glEGLImageTargetTextureStorageEXT ------------------------------------------- glEGLImageTargetTextureStorageEXT :: MonadIO m => GLuint -- ^ @texture@. -> GLeglImageOES -- ^ @image@. -> Ptr GLint -- ^ @attrib_list@. -> m () glEGLImageTargetTextureStorageEXT v1 v2 v3 = liftIO $ dyn269 ptr_glEGLImageTargetTextureStorageEXT v1 v2 v3 {-# NOINLINE ptr_glEGLImageTargetTextureStorageEXT #-} ptr_glEGLImageTargetTextureStorageEXT :: FunPtr (GLuint -> GLeglImageOES -> Ptr GLint -> IO ()) ptr_glEGLImageTargetTextureStorageEXT = unsafePerformIO $ getCommand "glEGLImageTargetTextureStorageEXT" -- glEdgeFlag ------------------------------------------------------------------ -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEdgeFlag.xml OpenGL 2.x>. The vector equivalent of this command is 'glEdgeFlagv'. glEdgeFlag :: MonadIO m => GLboolean -- ^ @flag@ of type [Boolean](Graphics-GL-Groups.html#Boolean). -> m () glEdgeFlag v1 = liftIO $ dyn198 ptr_glEdgeFlag v1 {-# NOINLINE ptr_glEdgeFlag #-} ptr_glEdgeFlag :: FunPtr (GLboolean -> IO ()) ptr_glEdgeFlag = unsafePerformIO $ getCommand "glEdgeFlag" -- glEdgeFlagFormatNV ---------------------------------------------------------- glEdgeFlagFormatNV :: MonadIO m => GLsizei -- ^ @stride@. -> m () glEdgeFlagFormatNV v1 = liftIO $ dyn270 ptr_glEdgeFlagFormatNV v1 {-# NOINLINE ptr_glEdgeFlagFormatNV #-} ptr_glEdgeFlagFormatNV :: FunPtr (GLsizei -> IO ()) ptr_glEdgeFlagFormatNV = unsafePerformIO $ getCommand "glEdgeFlagFormatNV" -- glEdgeFlagPointer ----------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEdgeFlagPointer.xml OpenGL 2.x>. glEdgeFlagPointer :: MonadIO m => GLsizei -- ^ @stride@. -> Ptr a -- ^ @pointer@ pointing to @COMPSIZE(stride)@ elements of type @a@. -> m () glEdgeFlagPointer v1 v2 = liftIO $ dyn271 ptr_glEdgeFlagPointer v1 v2 {-# NOINLINE ptr_glEdgeFlagPointer #-} ptr_glEdgeFlagPointer :: FunPtr (GLsizei -> Ptr a -> IO ()) ptr_glEdgeFlagPointer = unsafePerformIO $ getCommand "glEdgeFlagPointer" -- glEdgeFlagPointerEXT -------------------------------------------------------- glEdgeFlagPointerEXT :: MonadIO m => GLsizei -- ^ @stride@. -> GLsizei -- ^ @count@. -> Ptr GLboolean -- ^ @pointer@ pointing to @COMPSIZE(stride,count)@ elements of type [Boolean](Graphics-GL-Groups.html#Boolean). -> m () glEdgeFlagPointerEXT v1 v2 v3 = liftIO $ dyn272 ptr_glEdgeFlagPointerEXT v1 v2 v3 {-# NOINLINE ptr_glEdgeFlagPointerEXT #-} ptr_glEdgeFlagPointerEXT :: FunPtr (GLsizei -> GLsizei -> Ptr GLboolean -> IO ()) ptr_glEdgeFlagPointerEXT = unsafePerformIO $ getCommand "glEdgeFlagPointerEXT" -- glEdgeFlagPointerListIBM ---------------------------------------------------- glEdgeFlagPointerListIBM :: MonadIO m => GLint -- ^ @stride@. -> Ptr (Ptr GLboolean) -- ^ @pointer@ pointing to @COMPSIZE(stride)@ elements of type @Ptr BooleanPointer@. -> GLint -- ^ @ptrstride@. -> m () glEdgeFlagPointerListIBM v1 v2 v3 = liftIO $ dyn273 ptr_glEdgeFlagPointerListIBM v1 v2 v3 {-# NOINLINE ptr_glEdgeFlagPointerListIBM #-} ptr_glEdgeFlagPointerListIBM :: FunPtr (GLint -> Ptr (Ptr GLboolean) -> GLint -> IO ()) ptr_glEdgeFlagPointerListIBM = unsafePerformIO $ getCommand "glEdgeFlagPointerListIBM" -- glEdgeFlagv ----------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEdgeFlag.xml OpenGL 2.x>. glEdgeFlagv :: MonadIO m => Ptr GLboolean -- ^ @flag@ pointing to @1@ element of type [Boolean](Graphics-GL-Groups.html#Boolean). -> m () glEdgeFlagv v1 = liftIO $ dyn274 ptr_glEdgeFlagv v1 {-# NOINLINE ptr_glEdgeFlagv #-} ptr_glEdgeFlagv :: FunPtr (Ptr GLboolean -> IO ()) ptr_glEdgeFlagv = unsafePerformIO $ getCommand "glEdgeFlagv" -- glElementPointerAPPLE ------------------------------------------------------- glElementPointerAPPLE :: MonadIO m => GLenum -- ^ @type@ of type [ElementPointerTypeATI](Graphics-GL-Groups.html#ElementPointerTypeATI). -> Ptr a -- ^ @pointer@ pointing to @COMPSIZE(type)@ elements of type @a@. -> m () glElementPointerAPPLE v1 v2 = liftIO $ dyn238 ptr_glElementPointerAPPLE v1 v2 {-# NOINLINE ptr_glElementPointerAPPLE #-} ptr_glElementPointerAPPLE :: FunPtr (GLenum -> Ptr a -> IO ()) ptr_glElementPointerAPPLE = unsafePerformIO $ getCommand "glElementPointerAPPLE" -- glElementPointerATI --------------------------------------------------------- glElementPointerATI :: MonadIO m => GLenum -- ^ @type@ of type [ElementPointerTypeATI](Graphics-GL-Groups.html#ElementPointerTypeATI). -> Ptr a -- ^ @pointer@ pointing to @COMPSIZE(type)@ elements of type @a@. -> m () glElementPointerATI v1 v2 = liftIO $ dyn238 ptr_glElementPointerATI v1 v2 {-# NOINLINE ptr_glElementPointerATI #-} ptr_glElementPointerATI :: FunPtr (GLenum -> Ptr a -> IO ()) ptr_glElementPointerATI = unsafePerformIO $ getCommand "glElementPointerATI" -- glEnable -------------------------------------------------------------------- -- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glEnable.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man3/xhtml/glEnable.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glEnable.xhtml OpenGL 4.x>. glEnable :: MonadIO m => GLenum -- ^ @cap@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> m () glEnable v1 = liftIO $ dyn5 ptr_glEnable v1 {-# NOINLINE ptr_glEnable #-} ptr_glEnable :: FunPtr (GLenum -> IO ()) ptr_glEnable = unsafePerformIO $ getCommand "glEnable" -- glEnableClientState --------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEnableClientState.xml OpenGL 2.x>. glEnableClientState :: MonadIO m => GLenum -- ^ @array@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> m () glEnableClientState v1 = liftIO $ dyn5 ptr_glEnableClientState v1 {-# NOINLINE ptr_glEnableClientState #-} ptr_glEnableClientState :: FunPtr (GLenum -> IO ()) ptr_glEnableClientState = unsafePerformIO $ getCommand "glEnableClientState" -- glEnableClientStateIndexedEXT ----------------------------------------------- glEnableClientStateIndexedEXT :: MonadIO m => GLenum -- ^ @array@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> GLuint -- ^ @index@. -> m () glEnableClientStateIndexedEXT v1 v2 = liftIO $ dyn19 ptr_glEnableClientStateIndexedEXT v1 v2 {-# NOINLINE ptr_glEnableClientStateIndexedEXT #-} ptr_glEnableClientStateIndexedEXT :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEnableClientStateIndexedEXT = unsafePerformIO $ getCommand "glEnableClientStateIndexedEXT" -- glEnableClientStateiEXT ----------------------------------------------------- glEnableClientStateiEXT :: MonadIO m => GLenum -- ^ @array@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> GLuint -- ^ @index@. -> m () glEnableClientStateiEXT v1 v2 = liftIO $ dyn19 ptr_glEnableClientStateiEXT v1 v2 {-# NOINLINE ptr_glEnableClientStateiEXT #-} ptr_glEnableClientStateiEXT :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEnableClientStateiEXT = unsafePerformIO $ getCommand "glEnableClientStateiEXT" -- glEnableDriverControlQCOM --------------------------------------------------- glEnableDriverControlQCOM :: MonadIO m => GLuint -- ^ @driverControl@. -> m () glEnableDriverControlQCOM v1 = liftIO $ dyn3 ptr_glEnableDriverControlQCOM v1 {-# NOINLINE ptr_glEnableDriverControlQCOM #-} ptr_glEnableDriverControlQCOM :: FunPtr (GLuint -> IO ()) ptr_glEnableDriverControlQCOM = unsafePerformIO $ getCommand "glEnableDriverControlQCOM" -- glEnableIndexedEXT ---------------------------------------------------------- -- | This command is an alias for 'glEnablei'. glEnableIndexedEXT :: MonadIO m => GLenum -- ^ @target@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> GLuint -- ^ @index@. -> m () glEnableIndexedEXT v1 v2 = liftIO $ dyn19 ptr_glEnableIndexedEXT v1 v2 {-# NOINLINE ptr_glEnableIndexedEXT #-} ptr_glEnableIndexedEXT :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEnableIndexedEXT = unsafePerformIO $ getCommand "glEnableIndexedEXT" -- glEnableVariantClientStateEXT ----------------------------------------------- glEnableVariantClientStateEXT :: MonadIO m => GLuint -- ^ @id@. -> m () glEnableVariantClientStateEXT v1 = liftIO $ dyn3 ptr_glEnableVariantClientStateEXT v1 {-# NOINLINE ptr_glEnableVariantClientStateEXT #-} ptr_glEnableVariantClientStateEXT :: FunPtr (GLuint -> IO ()) ptr_glEnableVariantClientStateEXT = unsafePerformIO $ getCommand "glEnableVariantClientStateEXT" -- glEnableVertexArrayAttrib --------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glEnableVertexAttribArray.xhtml OpenGL 4.x>. glEnableVertexArrayAttrib :: MonadIO m => GLuint -- ^ @vaobj@. -> GLuint -- ^ @index@. -> m () glEnableVertexArrayAttrib v1 v2 = liftIO $ dyn4 ptr_glEnableVertexArrayAttrib v1 v2 {-# NOINLINE ptr_glEnableVertexArrayAttrib #-} ptr_glEnableVertexArrayAttrib :: FunPtr (GLuint -> GLuint -> IO ()) ptr_glEnableVertexArrayAttrib = unsafePerformIO $ getCommand "glEnableVertexArrayAttrib" -- glEnableVertexArrayAttribEXT ------------------------------------------------ glEnableVertexArrayAttribEXT :: MonadIO m => GLuint -- ^ @vaobj@. -> GLuint -- ^ @index@. -> m () glEnableVertexArrayAttribEXT v1 v2 = liftIO $ dyn4 ptr_glEnableVertexArrayAttribEXT v1 v2 {-# NOINLINE ptr_glEnableVertexArrayAttribEXT #-} ptr_glEnableVertexArrayAttribEXT :: FunPtr (GLuint -> GLuint -> IO ()) ptr_glEnableVertexArrayAttribEXT = unsafePerformIO $ getCommand "glEnableVertexArrayAttribEXT" -- glEnableVertexArrayEXT ------------------------------------------------------ glEnableVertexArrayEXT :: MonadIO m => GLuint -- ^ @vaobj@. -> GLenum -- ^ @array@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> m () glEnableVertexArrayEXT v1 v2 = liftIO $ dyn18 ptr_glEnableVertexArrayEXT v1 v2 {-# NOINLINE ptr_glEnableVertexArrayEXT #-} ptr_glEnableVertexArrayEXT :: FunPtr (GLuint -> GLenum -> IO ()) ptr_glEnableVertexArrayEXT = unsafePerformIO $ getCommand "glEnableVertexArrayEXT" -- glEnableVertexAttribAPPLE --------------------------------------------------- glEnableVertexAttribAPPLE :: MonadIO m => GLuint -- ^ @index@. -> GLenum -- ^ @pname@. -> m () glEnableVertexAttribAPPLE v1 v2 = liftIO $ dyn18 ptr_glEnableVertexAttribAPPLE v1 v2 {-# NOINLINE ptr_glEnableVertexAttribAPPLE #-} ptr_glEnableVertexAttribAPPLE :: FunPtr (GLuint -> GLenum -> IO ()) ptr_glEnableVertexAttribAPPLE = unsafePerformIO $ getCommand "glEnableVertexAttribAPPLE" -- glEnableVertexAttribArray --------------------------------------------------- -- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glEnableVertexAttribArray.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man3/xhtml/glEnableVertexAttribArray.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glEnableVertexAttribArray.xhtml OpenGL 4.x>. glEnableVertexAttribArray :: MonadIO m => GLuint -- ^ @index@. -> m () glEnableVertexAttribArray v1 = liftIO $ dyn3 ptr_glEnableVertexAttribArray v1 {-# NOINLINE ptr_glEnableVertexAttribArray #-} ptr_glEnableVertexAttribArray :: FunPtr (GLuint -> IO ()) ptr_glEnableVertexAttribArray = unsafePerformIO $ getCommand "glEnableVertexAttribArray" -- glEnableVertexAttribArrayARB ------------------------------------------------ -- | This command is an alias for 'glEnableVertexAttribArray'. glEnableVertexAttribArrayARB :: MonadIO m => GLuint -- ^ @index@. -> m () glEnableVertexAttribArrayARB v1 = liftIO $ dyn3 ptr_glEnableVertexAttribArrayARB v1 {-# NOINLINE ptr_glEnableVertexAttribArrayARB #-} ptr_glEnableVertexAttribArrayARB :: FunPtr (GLuint -> IO ()) ptr_glEnableVertexAttribArrayARB = unsafePerformIO $ getCommand "glEnableVertexAttribArrayARB" -- glEnablei ------------------------------------------------------------------- -- | Manual pages for <https://www.opengl.org/sdk/docs/man3/xhtml/glEnable.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glEnable.xhtml OpenGL 4.x>. glEnablei :: MonadIO m => GLenum -- ^ @target@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> GLuint -- ^ @index@. -> m () glEnablei v1 v2 = liftIO $ dyn19 ptr_glEnablei v1 v2 {-# NOINLINE ptr_glEnablei #-} ptr_glEnablei :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEnablei = unsafePerformIO $ getCommand "glEnablei" -- glEnableiEXT ---------------------------------------------------------------- -- | This command is an alias for 'glEnablei'. glEnableiEXT :: MonadIO m => GLenum -- ^ @target@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> GLuint -- ^ @index@. -> m () glEnableiEXT v1 v2 = liftIO $ dyn19 ptr_glEnableiEXT v1 v2 {-# NOINLINE ptr_glEnableiEXT #-} ptr_glEnableiEXT :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEnableiEXT = unsafePerformIO $ getCommand "glEnableiEXT" -- glEnableiNV ----------------------------------------------------------------- -- | This command is an alias for 'glEnablei'. glEnableiNV :: MonadIO m => GLenum -- ^ @target@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> GLuint -- ^ @index@. -> m () glEnableiNV v1 v2 = liftIO $ dyn19 ptr_glEnableiNV v1 v2 {-# NOINLINE ptr_glEnableiNV #-} ptr_glEnableiNV :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEnableiNV = unsafePerformIO $ getCommand "glEnableiNV" -- glEnableiOES ---------------------------------------------------------------- -- | This command is an alias for 'glEnablei'. glEnableiOES :: MonadIO m => GLenum -- ^ @target@ of type [EnableCap](Graphics-GL-Groups.html#EnableCap). -> GLuint -- ^ @index@. -> m () glEnableiOES v1 v2 = liftIO $ dyn19 ptr_glEnableiOES v1 v2 {-# NOINLINE ptr_glEnableiOES #-} ptr_glEnableiOES :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEnableiOES = unsafePerformIO $ getCommand "glEnableiOES" -- glEnd ----------------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glBegin.xml OpenGL 2.x>. glEnd :: MonadIO m => m () glEnd = liftIO $ dyn11 ptr_glEnd {-# NOINLINE ptr_glEnd #-} ptr_glEnd :: FunPtr (IO ()) ptr_glEnd = unsafePerformIO $ getCommand "glEnd" -- glEndConditionalRender ------------------------------------------------------ -- | Manual pages for <https://www.opengl.org/sdk/docs/man3/xhtml/glBeginConditionalRender.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glBeginConditionalRender.xhtml OpenGL 4.x>. glEndConditionalRender :: MonadIO m => m () glEndConditionalRender = liftIO $ dyn11 ptr_glEndConditionalRender {-# NOINLINE ptr_glEndConditionalRender #-} ptr_glEndConditionalRender :: FunPtr (IO ()) ptr_glEndConditionalRender = unsafePerformIO $ getCommand "glEndConditionalRender" -- glEndConditionalRenderNV ---------------------------------------------------- -- | This command is an alias for 'glEndConditionalRender'. glEndConditionalRenderNV :: MonadIO m => m () glEndConditionalRenderNV = liftIO $ dyn11 ptr_glEndConditionalRenderNV {-# NOINLINE ptr_glEndConditionalRenderNV #-} ptr_glEndConditionalRenderNV :: FunPtr (IO ()) ptr_glEndConditionalRenderNV = unsafePerformIO $ getCommand "glEndConditionalRenderNV" -- glEndConditionalRenderNVX --------------------------------------------------- -- | This command is an alias for 'glEndConditionalRender'. glEndConditionalRenderNVX :: MonadIO m => m () glEndConditionalRenderNVX = liftIO $ dyn11 ptr_glEndConditionalRenderNVX {-# NOINLINE ptr_glEndConditionalRenderNVX #-} ptr_glEndConditionalRenderNVX :: FunPtr (IO ()) ptr_glEndConditionalRenderNVX = unsafePerformIO $ getCommand "glEndConditionalRenderNVX" -- glEndFragmentShaderATI ------------------------------------------------------ glEndFragmentShaderATI :: MonadIO m => m () glEndFragmentShaderATI = liftIO $ dyn11 ptr_glEndFragmentShaderATI {-# NOINLINE ptr_glEndFragmentShaderATI #-} ptr_glEndFragmentShaderATI :: FunPtr (IO ()) ptr_glEndFragmentShaderATI = unsafePerformIO $ getCommand "glEndFragmentShaderATI" -- glEndList ------------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glNewList.xml OpenGL 2.x>. glEndList :: MonadIO m => m () glEndList = liftIO $ dyn11 ptr_glEndList {-# NOINLINE ptr_glEndList #-} ptr_glEndList :: FunPtr (IO ()) ptr_glEndList = unsafePerformIO $ getCommand "glEndList" -- glEndOcclusionQueryNV ------------------------------------------------------- glEndOcclusionQueryNV :: MonadIO m => m () glEndOcclusionQueryNV = liftIO $ dyn11 ptr_glEndOcclusionQueryNV {-# NOINLINE ptr_glEndOcclusionQueryNV #-} ptr_glEndOcclusionQueryNV :: FunPtr (IO ()) ptr_glEndOcclusionQueryNV = unsafePerformIO $ getCommand "glEndOcclusionQueryNV" -- glEndPerfMonitorAMD --------------------------------------------------------- glEndPerfMonitorAMD :: MonadIO m => GLuint -- ^ @monitor@. -> m () glEndPerfMonitorAMD v1 = liftIO $ dyn3 ptr_glEndPerfMonitorAMD v1 {-# NOINLINE ptr_glEndPerfMonitorAMD #-} ptr_glEndPerfMonitorAMD :: FunPtr (GLuint -> IO ()) ptr_glEndPerfMonitorAMD = unsafePerformIO $ getCommand "glEndPerfMonitorAMD" -- glEndPerfQueryINTEL --------------------------------------------------------- glEndPerfQueryINTEL :: MonadIO m => GLuint -- ^ @queryHandle@. -> m () glEndPerfQueryINTEL v1 = liftIO $ dyn3 ptr_glEndPerfQueryINTEL v1 {-# NOINLINE ptr_glEndPerfQueryINTEL #-} ptr_glEndPerfQueryINTEL :: FunPtr (GLuint -> IO ()) ptr_glEndPerfQueryINTEL = unsafePerformIO $ getCommand "glEndPerfQueryINTEL" -- glEndQuery ------------------------------------------------------------------ -- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glBeginQuery.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man3/xhtml/glBeginQuery.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glBeginQuery.xhtml OpenGL 4.x>. glEndQuery :: MonadIO m => GLenum -- ^ @target@ of type [QueryTarget](Graphics-GL-Groups.html#QueryTarget). -> m () glEndQuery v1 = liftIO $ dyn5 ptr_glEndQuery v1 {-# NOINLINE ptr_glEndQuery #-} ptr_glEndQuery :: FunPtr (GLenum -> IO ()) ptr_glEndQuery = unsafePerformIO $ getCommand "glEndQuery" -- glEndQueryARB --------------------------------------------------------------- -- | This command is an alias for 'glEndQuery'. glEndQueryARB :: MonadIO m => GLenum -- ^ @target@ of type [QueryTarget](Graphics-GL-Groups.html#QueryTarget). -> m () glEndQueryARB v1 = liftIO $ dyn5 ptr_glEndQueryARB v1 {-# NOINLINE ptr_glEndQueryARB #-} ptr_glEndQueryARB :: FunPtr (GLenum -> IO ()) ptr_glEndQueryARB = unsafePerformIO $ getCommand "glEndQueryARB" -- glEndQueryEXT --------------------------------------------------------------- glEndQueryEXT :: MonadIO m => GLenum -- ^ @target@ of type [QueryTarget](Graphics-GL-Groups.html#QueryTarget). -> m () glEndQueryEXT v1 = liftIO $ dyn5 ptr_glEndQueryEXT v1 {-# NOINLINE ptr_glEndQueryEXT #-} ptr_glEndQueryEXT :: FunPtr (GLenum -> IO ()) ptr_glEndQueryEXT = unsafePerformIO $ getCommand "glEndQueryEXT" -- glEndQueryIndexed ----------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glBeginQueryIndexed.xhtml OpenGL 4.x>. glEndQueryIndexed :: MonadIO m => GLenum -- ^ @target@ of type [QueryTarget](Graphics-GL-Groups.html#QueryTarget). -> GLuint -- ^ @index@. -> m () glEndQueryIndexed v1 v2 = liftIO $ dyn19 ptr_glEndQueryIndexed v1 v2 {-# NOINLINE ptr_glEndQueryIndexed #-} ptr_glEndQueryIndexed :: FunPtr (GLenum -> GLuint -> IO ()) ptr_glEndQueryIndexed = unsafePerformIO $ getCommand "glEndQueryIndexed" -- glEndTilingQCOM ------------------------------------------------------------- glEndTilingQCOM :: MonadIO m => GLbitfield -- ^ @preserveMask@ of type [BufferBitQCOM](Graphics-GL-Groups.html#BufferBitQCOM). -> m () glEndTilingQCOM v1 = liftIO $ dyn75 ptr_glEndTilingQCOM v1 {-# NOINLINE ptr_glEndTilingQCOM #-} ptr_glEndTilingQCOM :: FunPtr (GLbitfield -> IO ()) ptr_glEndTilingQCOM = unsafePerformIO $ getCommand "glEndTilingQCOM" -- glEndTransformFeedback ------------------------------------------------------ -- | Manual pages for <https://www.opengl.org/sdk/docs/man3/xhtml/glBeginTransformFeedback.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glBeginTransformFeedback.xhtml OpenGL 4.x>. glEndTransformFeedback :: MonadIO m => m () glEndTransformFeedback = liftIO $ dyn11 ptr_glEndTransformFeedback {-# NOINLINE ptr_glEndTransformFeedback #-} ptr_glEndTransformFeedback :: FunPtr (IO ()) ptr_glEndTransformFeedback = unsafePerformIO $ getCommand "glEndTransformFeedback" -- glEndTransformFeedbackEXT --------------------------------------------------- -- | This command is an alias for 'glEndTransformFeedback'. glEndTransformFeedbackEXT :: MonadIO m => m () glEndTransformFeedbackEXT = liftIO $ dyn11 ptr_glEndTransformFeedbackEXT {-# NOINLINE ptr_glEndTransformFeedbackEXT #-} ptr_glEndTransformFeedbackEXT :: FunPtr (IO ()) ptr_glEndTransformFeedbackEXT = unsafePerformIO $ getCommand "glEndTransformFeedbackEXT" -- glEndTransformFeedbackNV ---------------------------------------------------- -- | This command is an alias for 'glEndTransformFeedback'. glEndTransformFeedbackNV :: MonadIO m => m () glEndTransformFeedbackNV = liftIO $ dyn11 ptr_glEndTransformFeedbackNV {-# NOINLINE ptr_glEndTransformFeedbackNV #-} ptr_glEndTransformFeedbackNV :: FunPtr (IO ()) ptr_glEndTransformFeedbackNV = unsafePerformIO $ getCommand "glEndTransformFeedbackNV" -- glEndVertexShaderEXT -------------------------------------------------------- glEndVertexShaderEXT :: MonadIO m => m () glEndVertexShaderEXT = liftIO $ dyn11 ptr_glEndVertexShaderEXT {-# NOINLINE ptr_glEndVertexShaderEXT #-} ptr_glEndVertexShaderEXT :: FunPtr (IO ()) ptr_glEndVertexShaderEXT = unsafePerformIO $ getCommand "glEndVertexShaderEXT" -- glEndVideoCaptureNV --------------------------------------------------------- glEndVideoCaptureNV :: MonadIO m => GLuint -- ^ @video_capture_slot@. -> m () glEndVideoCaptureNV v1 = liftIO $ dyn3 ptr_glEndVideoCaptureNV v1 {-# NOINLINE ptr_glEndVideoCaptureNV #-} ptr_glEndVideoCaptureNV :: FunPtr (GLuint -> IO ()) ptr_glEndVideoCaptureNV = unsafePerformIO $ getCommand "glEndVideoCaptureNV" -- glEvalCoord1d --------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glEvalCoord1dv'. glEvalCoord1d :: MonadIO m => GLdouble -- ^ @u@ of type @CoordD@. -> m () glEvalCoord1d v1 = liftIO $ dyn84 ptr_glEvalCoord1d v1 {-# NOINLINE ptr_glEvalCoord1d #-} ptr_glEvalCoord1d :: FunPtr (GLdouble -> IO ()) ptr_glEvalCoord1d = unsafePerformIO $ getCommand "glEvalCoord1d" -- glEvalCoord1dv -------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. glEvalCoord1dv :: MonadIO m => Ptr GLdouble -- ^ @u@ pointing to @1@ element of type @CoordD@. -> m () glEvalCoord1dv v1 = liftIO $ dyn42 ptr_glEvalCoord1dv v1 {-# NOINLINE ptr_glEvalCoord1dv #-} ptr_glEvalCoord1dv :: FunPtr (Ptr GLdouble -> IO ()) ptr_glEvalCoord1dv = unsafePerformIO $ getCommand "glEvalCoord1dv" -- glEvalCoord1f --------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glEvalCoord1fv'. glEvalCoord1f :: MonadIO m => GLfloat -- ^ @u@ of type @CoordF@. -> m () glEvalCoord1f v1 = liftIO $ dyn85 ptr_glEvalCoord1f v1 {-# NOINLINE ptr_glEvalCoord1f #-} ptr_glEvalCoord1f :: FunPtr (GLfloat -> IO ()) ptr_glEvalCoord1f = unsafePerformIO $ getCommand "glEvalCoord1f" -- glEvalCoord1fv -------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. glEvalCoord1fv :: MonadIO m => Ptr GLfloat -- ^ @u@ pointing to @1@ element of type @CoordF@. -> m () glEvalCoord1fv v1 = liftIO $ dyn44 ptr_glEvalCoord1fv v1 {-# NOINLINE ptr_glEvalCoord1fv #-} ptr_glEvalCoord1fv :: FunPtr (Ptr GLfloat -> IO ()) ptr_glEvalCoord1fv = unsafePerformIO $ getCommand "glEvalCoord1fv" -- glEvalCoord1xOES ------------------------------------------------------------ glEvalCoord1xOES :: MonadIO m => GLfixed -- ^ @u@. -> m () glEvalCoord1xOES v1 = liftIO $ dyn87 ptr_glEvalCoord1xOES v1 {-# NOINLINE ptr_glEvalCoord1xOES #-} ptr_glEvalCoord1xOES :: FunPtr (GLfixed -> IO ()) ptr_glEvalCoord1xOES = unsafePerformIO $ getCommand "glEvalCoord1xOES" -- glEvalCoord1xvOES ----------------------------------------------------------- glEvalCoord1xvOES :: MonadIO m => Ptr GLfixed -- ^ @coords@ pointing to @1@ element of type @GLfixed@. -> m () glEvalCoord1xvOES v1 = liftIO $ dyn114 ptr_glEvalCoord1xvOES v1 {-# NOINLINE ptr_glEvalCoord1xvOES #-} ptr_glEvalCoord1xvOES :: FunPtr (Ptr GLfixed -> IO ()) ptr_glEvalCoord1xvOES = unsafePerformIO $ getCommand "glEvalCoord1xvOES" -- glEvalCoord2d --------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glEvalCoord2dv'. glEvalCoord2d :: MonadIO m => GLdouble -- ^ @u@ of type @CoordD@. -> GLdouble -- ^ @v@ of type @CoordD@. -> m () glEvalCoord2d v1 v2 = liftIO $ dyn225 ptr_glEvalCoord2d v1 v2 {-# NOINLINE ptr_glEvalCoord2d #-} ptr_glEvalCoord2d :: FunPtr (GLdouble -> GLdouble -> IO ()) ptr_glEvalCoord2d = unsafePerformIO $ getCommand "glEvalCoord2d" -- glEvalCoord2dv -------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. glEvalCoord2dv :: MonadIO m => Ptr GLdouble -- ^ @u@ pointing to @2@ elements of type @CoordD@. -> m () glEvalCoord2dv v1 = liftIO $ dyn42 ptr_glEvalCoord2dv v1 {-# NOINLINE ptr_glEvalCoord2dv #-} ptr_glEvalCoord2dv :: FunPtr (Ptr GLdouble -> IO ()) ptr_glEvalCoord2dv = unsafePerformIO $ getCommand "glEvalCoord2dv" -- glEvalCoord2f --------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glEvalCoord2fv'. glEvalCoord2f :: MonadIO m => GLfloat -- ^ @u@ of type @CoordF@. -> GLfloat -- ^ @v@ of type @CoordF@. -> m () glEvalCoord2f v1 v2 = liftIO $ dyn230 ptr_glEvalCoord2f v1 v2 {-# NOINLINE ptr_glEvalCoord2f #-} ptr_glEvalCoord2f :: FunPtr (GLfloat -> GLfloat -> IO ()) ptr_glEvalCoord2f = unsafePerformIO $ getCommand "glEvalCoord2f" -- glEvalCoord2fv -------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalCoord.xml OpenGL 2.x>. glEvalCoord2fv :: MonadIO m => Ptr GLfloat -- ^ @u@ pointing to @2@ elements of type @CoordF@. -> m () glEvalCoord2fv v1 = liftIO $ dyn44 ptr_glEvalCoord2fv v1 {-# NOINLINE ptr_glEvalCoord2fv #-} ptr_glEvalCoord2fv :: FunPtr (Ptr GLfloat -> IO ()) ptr_glEvalCoord2fv = unsafePerformIO $ getCommand "glEvalCoord2fv" -- glEvalCoord2xOES ------------------------------------------------------------ glEvalCoord2xOES :: MonadIO m => GLfixed -- ^ @u@. -> GLfixed -- ^ @v@. -> m () glEvalCoord2xOES v1 v2 = liftIO $ dyn232 ptr_glEvalCoord2xOES v1 v2 {-# NOINLINE ptr_glEvalCoord2xOES #-} ptr_glEvalCoord2xOES :: FunPtr (GLfixed -> GLfixed -> IO ()) ptr_glEvalCoord2xOES = unsafePerformIO $ getCommand "glEvalCoord2xOES" -- glEvalCoord2xvOES ----------------------------------------------------------- glEvalCoord2xvOES :: MonadIO m => Ptr GLfixed -- ^ @coords@ pointing to @2@ elements of type @GLfixed@. -> m () glEvalCoord2xvOES v1 = liftIO $ dyn114 ptr_glEvalCoord2xvOES v1 {-# NOINLINE ptr_glEvalCoord2xvOES #-} ptr_glEvalCoord2xvOES :: FunPtr (Ptr GLfixed -> IO ()) ptr_glEvalCoord2xvOES = unsafePerformIO $ getCommand "glEvalCoord2xvOES" -- glEvalMapsNV ---------------------------------------------------------------- glEvalMapsNV :: MonadIO m => GLenum -- ^ @target@ of type [EvalTargetNV](Graphics-GL-Groups.html#EvalTargetNV). -> GLenum -- ^ @mode@ of type [EvalMapsModeNV](Graphics-GL-Groups.html#EvalMapsModeNV). -> m () glEvalMapsNV v1 v2 = liftIO $ dyn54 ptr_glEvalMapsNV v1 v2 {-# NOINLINE ptr_glEvalMapsNV #-} ptr_glEvalMapsNV :: FunPtr (GLenum -> GLenum -> IO ()) ptr_glEvalMapsNV = unsafePerformIO $ getCommand "glEvalMapsNV" -- glEvalMesh1 ----------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalMesh.xml OpenGL 2.x>. glEvalMesh1 :: MonadIO m => GLenum -- ^ @mode@ of type [MeshMode1](Graphics-GL-Groups.html#MeshMode1). -> GLint -- ^ @i1@ of type @CheckedInt32@. -> GLint -- ^ @i2@ of type @CheckedInt32@. -> m () glEvalMesh1 v1 v2 v3 = liftIO $ dyn275 ptr_glEvalMesh1 v1 v2 v3 {-# NOINLINE ptr_glEvalMesh1 #-} ptr_glEvalMesh1 :: FunPtr (GLenum -> GLint -> GLint -> IO ()) ptr_glEvalMesh1 = unsafePerformIO $ getCommand "glEvalMesh1" -- glEvalMesh2 ----------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalMesh.xml OpenGL 2.x>. glEvalMesh2 :: MonadIO m => GLenum -- ^ @mode@ of type [MeshMode2](Graphics-GL-Groups.html#MeshMode2). -> GLint -- ^ @i1@ of type @CheckedInt32@. -> GLint -- ^ @i2@ of type @CheckedInt32@. -> GLint -- ^ @j1@ of type @CheckedInt32@. -> GLint -- ^ @j2@ of type @CheckedInt32@. -> m () glEvalMesh2 v1 v2 v3 v4 v5 = liftIO $ dyn276 ptr_glEvalMesh2 v1 v2 v3 v4 v5 {-# NOINLINE ptr_glEvalMesh2 #-} ptr_glEvalMesh2 :: FunPtr (GLenum -> GLint -> GLint -> GLint -> GLint -> IO ()) ptr_glEvalMesh2 = unsafePerformIO $ getCommand "glEvalMesh2" -- glEvalPoint1 ---------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalPoint.xml OpenGL 2.x>. glEvalPoint1 :: MonadIO m => GLint -- ^ @i@. -> m () glEvalPoint1 v1 = liftIO $ dyn13 ptr_glEvalPoint1 v1 {-# NOINLINE ptr_glEvalPoint1 #-} ptr_glEvalPoint1 :: FunPtr (GLint -> IO ()) ptr_glEvalPoint1 = unsafePerformIO $ getCommand "glEvalPoint1" -- glEvalPoint2 ---------------------------------------------------------------- -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glEvalPoint.xml OpenGL 2.x>. glEvalPoint2 :: MonadIO m => GLint -- ^ @i@ of type @CheckedInt32@. -> GLint -- ^ @j@ of type @CheckedInt32@. -> m () glEvalPoint2 v1 v2 = liftIO $ dyn277 ptr_glEvalPoint2 v1 v2 {-# NOINLINE ptr_glEvalPoint2 #-} ptr_glEvalPoint2 :: FunPtr (GLint -> GLint -> IO ()) ptr_glEvalPoint2 = unsafePerformIO $ getCommand "glEvalPoint2" -- glEvaluateDepthValuesARB ---------------------------------------------------- glEvaluateDepthValuesARB :: MonadIO m => m () glEvaluateDepthValuesARB = liftIO $ dyn11 ptr_glEvaluateDepthValuesARB {-# NOINLINE ptr_glEvaluateDepthValuesARB #-} ptr_glEvaluateDepthValuesARB :: FunPtr (IO ()) ptr_glEvaluateDepthValuesARB = unsafePerformIO $ getCommand "glEvaluateDepthValuesARB" -- glExecuteProgramNV ---------------------------------------------------------- glExecuteProgramNV :: MonadIO m => GLenum -- ^ @target@ of type [VertexAttribEnumNV](Graphics-GL-Groups.html#VertexAttribEnumNV). -> GLuint -- ^ @id@. -> Ptr GLfloat -- ^ @params@ pointing to @4@ elements of type @GLfloat@. -> m () glExecuteProgramNV v1 v2 v3 = liftIO $ dyn278 ptr_glExecuteProgramNV v1 v2 v3 {-# NOINLINE ptr_glExecuteProgramNV #-} ptr_glExecuteProgramNV :: FunPtr (GLenum -> GLuint -> Ptr GLfloat -> IO ()) ptr_glExecuteProgramNV = unsafePerformIO $ getCommand "glExecuteProgramNV" -- glExtGetBufferPointervQCOM -------------------------------------------------- glExtGetBufferPointervQCOM :: MonadIO m => GLenum -- ^ @target@. -> Ptr (Ptr a) -- ^ @params@. -> m () glExtGetBufferPointervQCOM v1 v2 = liftIO $ dyn279 ptr_glExtGetBufferPointervQCOM v1 v2 {-# NOINLINE ptr_glExtGetBufferPointervQCOM #-} ptr_glExtGetBufferPointervQCOM :: FunPtr (GLenum -> Ptr (Ptr a) -> IO ()) ptr_glExtGetBufferPointervQCOM = unsafePerformIO $ getCommand "glExtGetBufferPointervQCOM" -- glExtGetBuffersQCOM --------------------------------------------------------- glExtGetBuffersQCOM :: MonadIO m => Ptr GLuint -- ^ @buffers@ pointing to @maxBuffers@ elements of type @GLuint@. -> GLint -- ^ @maxBuffers@. -> Ptr GLint -- ^ @numBuffers@ pointing to @1@ element of type @GLint@. -> m () glExtGetBuffersQCOM v1 v2 v3 = liftIO $ dyn280 ptr_glExtGetBuffersQCOM v1 v2 v3 {-# NOINLINE ptr_glExtGetBuffersQCOM #-} ptr_glExtGetBuffersQCOM :: FunPtr (Ptr GLuint -> GLint -> Ptr GLint -> IO ()) ptr_glExtGetBuffersQCOM = unsafePerformIO $ getCommand "glExtGetBuffersQCOM" -- glExtGetFramebuffersQCOM ---------------------------------------------------- glExtGetFramebuffersQCOM :: MonadIO m => Ptr GLuint -- ^ @framebuffers@ pointing to @maxFramebuffers@ elements of type @GLuint@. -> GLint -- ^ @maxFramebuffers@. -> Ptr GLint -- ^ @numFramebuffers@ pointing to @1@ element of type @GLint@. -> m () glExtGetFramebuffersQCOM v1 v2 v3 = liftIO $ dyn280 ptr_glExtGetFramebuffersQCOM v1 v2 v3 {-# NOINLINE ptr_glExtGetFramebuffersQCOM #-} ptr_glExtGetFramebuffersQCOM :: FunPtr (Ptr GLuint -> GLint -> Ptr GLint -> IO ()) ptr_glExtGetFramebuffersQCOM = unsafePerformIO $ getCommand "glExtGetFramebuffersQCOM" -- glExtGetProgramBinarySourceQCOM --------------------------------------------- glExtGetProgramBinarySourceQCOM :: MonadIO m => GLuint -- ^ @program@. -> GLenum -- ^ @shadertype@ of type [ShaderType](Graphics-GL-Groups.html#ShaderType). -> Ptr GLchar -- ^ @source@. -> Ptr GLint -- ^ @length@. -> m () glExtGetProgramBinarySourceQCOM v1 v2 v3 v4 = liftIO $ dyn281 ptr_glExtGetProgramBinarySourceQCOM v1 v2 v3 v4 {-# NOINLINE ptr_glExtGetProgramBinarySourceQCOM #-} ptr_glExtGetProgramBinarySourceQCOM :: FunPtr (GLuint -> GLenum -> Ptr GLchar -> Ptr GLint -> IO ()) ptr_glExtGetProgramBinarySourceQCOM = unsafePerformIO $ getCommand "glExtGetProgramBinarySourceQCOM" -- glExtGetProgramsQCOM -------------------------------------------------------- glExtGetProgramsQCOM :: MonadIO m => Ptr GLuint -- ^ @programs@ pointing to @maxPrograms@ elements of type @GLuint@. -> GLint -- ^ @maxPrograms@. -> Ptr GLint -- ^ @numPrograms@ pointing to @1@ element of type @GLint@. -> m () glExtGetProgramsQCOM v1 v2 v3 = liftIO $ dyn280 ptr_glExtGetProgramsQCOM v1 v2 v3 {-# NOINLINE ptr_glExtGetProgramsQCOM #-} ptr_glExtGetProgramsQCOM :: FunPtr (Ptr GLuint -> GLint -> Ptr GLint -> IO ()) ptr_glExtGetProgramsQCOM = unsafePerformIO $ getCommand "glExtGetProgramsQCOM" -- glExtGetRenderbuffersQCOM --------------------------------------------------- glExtGetRenderbuffersQCOM :: MonadIO m => Ptr GLuint -- ^ @renderbuffers@ pointing to @maxRenderbuffers@ elements of type @GLuint@. -> GLint -- ^ @maxRenderbuffers@. -> Ptr GLint -- ^ @numRenderbuffers@ pointing to @1@ element of type @GLint@. -> m () glExtGetRenderbuffersQCOM v1 v2 v3 = liftIO $ dyn280 ptr_glExtGetRenderbuffersQCOM v1 v2 v3 {-# NOINLINE ptr_glExtGetRenderbuffersQCOM #-} ptr_glExtGetRenderbuffersQCOM :: FunPtr (Ptr GLuint -> GLint -> Ptr GLint -> IO ()) ptr_glExtGetRenderbuffersQCOM = unsafePerformIO $ getCommand "glExtGetRenderbuffersQCOM" -- glExtGetShadersQCOM --------------------------------------------------------- glExtGetShadersQCOM :: MonadIO m => Ptr GLuint -- ^ @shaders@ pointing to @maxShaders@ elements of type @GLuint@. -> GLint -- ^ @maxShaders@. -> Ptr GLint -- ^ @numShaders@ pointing to @1@ element of type @GLint@. -> m () glExtGetShadersQCOM v1 v2 v3 = liftIO $ dyn280 ptr_glExtGetShadersQCOM v1 v2 v3 {-# NOINLINE ptr_glExtGetShadersQCOM #-} ptr_glExtGetShadersQCOM :: FunPtr (Ptr GLuint -> GLint -> Ptr GLint -> IO ()) ptr_glExtGetShadersQCOM = unsafePerformIO $ getCommand "glExtGetShadersQCOM" -- glExtGetTexLevelParameterivQCOM --------------------------------------------- glExtGetTexLevelParameterivQCOM :: MonadIO m => GLuint -- ^ @texture@. -> GLenum -- ^ @face@. -> GLint -- ^ @level@. -> GLenum -- ^ @pname@. -> Ptr GLint -- ^ @params@. -> m () glExtGetTexLevelParameterivQCOM v1 v2 v3 v4 v5 = liftIO $ dyn282 ptr_glExtGetTexLevelParameterivQCOM v1 v2 v3 v4 v5 {-# NOINLINE ptr_glExtGetTexLevelParameterivQCOM #-} ptr_glExtGetTexLevelParameterivQCOM :: FunPtr (GLuint -> GLenum -> GLint -> GLenum -> Ptr GLint -> IO ()) ptr_glExtGetTexLevelParameterivQCOM = unsafePerformIO $ getCommand "glExtGetTexLevelParameterivQCOM" -- glExtGetTexSubImageQCOM ----------------------------------------------------- glExtGetTexSubImageQCOM :: MonadIO m => GLenum -- ^ @target@. -> GLint -- ^ @level@. -> GLint -- ^ @xoffset@. -> GLint -- ^ @yoffset@. -> GLint -- ^ @zoffset@. -> GLsizei -- ^ @width@. -> GLsizei -- ^ @height@. -> GLsizei -- ^ @depth@. -> GLenum -- ^ @format@ of type [PixelFormat](Graphics-GL-Groups.html#PixelFormat). -> GLenum -- ^ @type@ of type [PixelType](Graphics-GL-Groups.html#PixelType). -> Ptr a -- ^ @texels@. -> m () glExtGetTexSubImageQCOM v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 = liftIO $ dyn283 ptr_glExtGetTexSubImageQCOM v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 {-# NOINLINE ptr_glExtGetTexSubImageQCOM #-} ptr_glExtGetTexSubImageQCOM :: FunPtr (GLenum -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) ptr_glExtGetTexSubImageQCOM = unsafePerformIO $ getCommand "glExtGetTexSubImageQCOM" -- glExtGetTexturesQCOM -------------------------------------------------------- glExtGetTexturesQCOM :: MonadIO m => Ptr GLuint -- ^ @textures@. -> GLint -- ^ @maxTextures@. -> Ptr GLint -- ^ @numTextures@. -> m () glExtGetTexturesQCOM v1 v2 v3 = liftIO $ dyn280 ptr_glExtGetTexturesQCOM v1 v2 v3 {-# NOINLINE ptr_glExtGetTexturesQCOM #-} ptr_glExtGetTexturesQCOM :: FunPtr (Ptr GLuint -> GLint -> Ptr GLint -> IO ()) ptr_glExtGetTexturesQCOM = unsafePerformIO $ getCommand "glExtGetTexturesQCOM" -- glExtIsProgramBinaryQCOM ---------------------------------------------------- glExtIsProgramBinaryQCOM :: MonadIO m => GLuint -- ^ @program@. -> m GLboolean -- ^ of type [Boolean](Graphics-GL-Groups.html#Boolean). glExtIsProgramBinaryQCOM v1 = liftIO $ dyn284 ptr_glExtIsProgramBinaryQCOM v1 {-# NOINLINE ptr_glExtIsProgramBinaryQCOM #-} ptr_glExtIsProgramBinaryQCOM :: FunPtr (GLuint -> IO GLboolean) ptr_glExtIsProgramBinaryQCOM = unsafePerformIO $ getCommand "glExtIsProgramBinaryQCOM" -- glExtTexObjectStateOverrideiQCOM -------------------------------------------- glExtTexObjectStateOverrideiQCOM :: MonadIO m => GLenum -- ^ @target@. -> GLenum -- ^ @pname@. -> GLint -- ^ @param@. -> m () glExtTexObjectStateOverrideiQCOM v1 v2 v3 = liftIO $ dyn66 ptr_glExtTexObjectStateOverrideiQCOM v1 v2 v3 {-# NOINLINE ptr_glExtTexObjectStateOverrideiQCOM #-} ptr_glExtTexObjectStateOverrideiQCOM :: FunPtr (GLenum -> GLenum -> GLint -> IO ()) ptr_glExtTexObjectStateOverrideiQCOM = unsafePerformIO $ getCommand "glExtTexObjectStateOverrideiQCOM" -- glExtractComponentEXT ------------------------------------------------------- glExtractComponentEXT :: MonadIO m => GLuint -- ^ @res@. -> GLuint -- ^ @src@. -> GLuint -- ^ @num@. -> m () glExtractComponentEXT v1 v2 v3 = liftIO $ dyn109 ptr_glExtractComponentEXT v1 v2 v3 {-# NOINLINE ptr_glExtractComponentEXT #-} ptr_glExtractComponentEXT :: FunPtr (GLuint -> GLuint -> GLuint -> IO ()) ptr_glExtractComponentEXT = unsafePerformIO $ getCommand "glExtractComponentEXT" -- glFeedbackBuffer ------------------------------------------------------------ -- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glFeedbackBuffer.xml OpenGL 2.x>. glFeedbackBuffer :: MonadIO m => GLsizei -- ^ @size@. -> GLenum -- ^ @type@ of type [FeedbackType](Graphics-GL-Groups.html#FeedbackType). -> Ptr GLfloat -- ^ @buffer@ pointing to @size@ elements of type @FeedbackElement@. -> m () glFeedbackBuffer v1 v2 v3 = liftIO $ dyn285 ptr_glFeedbackBuffer v1 v2 v3 {-# NOINLINE ptr_glFeedbackBuffer #-} ptr_glFeedbackBuffer :: FunPtr (GLsizei -> GLenum -> Ptr GLfloat -> IO ()) ptr_glFeedbackBuffer = unsafePerformIO $ getCommand "glFeedbackBuffer" -- glFeedbackBufferxOES -------------------------------------------------------- glFeedbackBufferxOES :: MonadIO m => GLsizei -- ^ @n@. -> GLenum -- ^ @type@. -> Ptr GLfixed -- ^ @buffer@ pointing to @n@ elements of type @GLfixed@. -> m () glFeedbackBufferxOES v1 v2 v3 = liftIO $ dyn286 ptr_glFeedbackBufferxOES v1 v2 v3 {-# NOINLINE ptr_glFeedbackBufferxOES #-} ptr_glFeedbackBufferxOES :: FunPtr (GLsizei -> GLenum -> Ptr GLfixed -> IO ()) ptr_glFeedbackBufferxOES = unsafePerformIO $ getCommand "glFeedbackBufferxOES" -- glFenceSync ----------------------------------------------------------------- -- | Manual pages for <https://www.opengl.org/sdk/docs/man3/xhtml/glFenceSync.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glFenceSync.xhtml OpenGL 4.x>. glFenceSync :: MonadIO m => GLenum -- ^ @condition@ of type [SyncCondition](Graphics-GL-Groups.html#SyncCondition). -> GLbitfield -- ^ @flags@. -> m GLsync -- ^ of type @sync@. glFenceSync v1 v2 = liftIO $ dyn287 ptr_glFenceSync v1 v2 {-# NOINLINE ptr_glFenceSync #-} ptr_glFenceSync :: FunPtr (GLenum -> GLbitfield -> IO GLsync) ptr_glFenceSync = unsafePerformIO $ getCommand "glFenceSync" -- glFenceSyncAPPLE ------------------------------------------------------------ -- | This command is an alias for 'glFenceSync'. glFenceSyncAPPLE :: MonadIO m => GLenum -- ^ @condition@ of type [SyncCondition](Graphics-GL-Groups.html#SyncCondition). -> GLbitfield -- ^ @flags@. -> m GLsync glFenceSyncAPPLE v1 v2 = liftIO $ dyn287 ptr_glFenceSyncAPPLE v1 v2 {-# NOINLINE ptr_glFenceSyncAPPLE #-} ptr_glFenceSyncAPPLE :: FunPtr (GLenum -> GLbitfield -> IO GLsync) ptr_glFenceSyncAPPLE = unsafePerformIO $ getCommand "glFenceSyncAPPLE" -- glFinalCombinerInputNV ------------------------------------------------------ glFinalCombinerInputNV :: MonadIO m => GLenum -- ^ @variable@ of type [CombinerVariableNV](Graphics-GL-Groups.html#CombinerVariableNV). -> GLenum -- ^ @input@ of type [CombinerRegisterNV](Graphics-GL-Groups.html#CombinerRegisterNV). -> GLenum -- ^ @mapping@ of type [CombinerMappingNV](Graphics-GL-Groups.html#CombinerMappingNV). -> GLenum -- ^ @componentUsage@ of type [CombinerComponentUsageNV](Graphics-GL-Groups.html#CombinerComponentUsageNV). -> m () glFinalCombinerInputNV v1 v2 v3 v4 = liftIO $ dyn56 ptr_glFinalCombinerInputNV v1 v2 v3 v4 {-# NOINLINE ptr_glFinalCombinerInputNV #-} ptr_glFinalCombinerInputNV :: FunPtr (GLenum -> GLenum -> GLenum -> GLenum -> IO ()) ptr_glFinalCombinerInputNV = unsafePerformIO $ getCommand "glFinalCombinerInputNV" -- glFinish -------------------------------------------------------------------- -- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glFinish.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man3/xhtml/glFinish.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glFinish.xhtml OpenGL 4.x>. glFinish :: MonadIO m => m () glFinish = liftIO $ dyn11 ptr_glFinish {-# NOINLINE ptr_glFinish #-} ptr_glFinish :: FunPtr (IO ()) ptr_glFinish = unsafePerformIO $ getCommand "glFinish" -- glFinishAsyncSGIX ----------------------------------------------------------- glFinishAsyncSGIX :: MonadIO m => Ptr GLuint -- ^ @markerp@ pointing to @1@ element of type @GLuint@. -> m GLint glFinishAsyncSGIX v1 = liftIO $ dyn288 ptr_glFinishAsyncSGIX v1 {-# NOINLINE ptr_glFinishAsyncSGIX #-} ptr_glFinishAsyncSGIX :: FunPtr (Ptr GLuint -> IO GLint) ptr_glFinishAsyncSGIX = unsafePerformIO $ getCommand "glFinishAsyncSGIX" -- glFinishFenceAPPLE ---------------------------------------------------------- glFinishFenceAPPLE :: MonadIO m => GLuint -- ^ @fence@ of type @FenceNV@. -> m () glFinishFenceAPPLE v1 = liftIO $ dyn3 ptr_glFinishFenceAPPLE v1 {-# NOINLINE ptr_glFinishFenceAPPLE #-} ptr_glFinishFenceAPPLE :: FunPtr (GLuint -> IO ()) ptr_glFinishFenceAPPLE = unsafePerformIO $ getCommand "glFinishFenceAPPLE" -- glFinishFenceNV ------------------------------------------------------------- glFinishFenceNV :: MonadIO m => GLuint -- ^ @fence@ of type @FenceNV@. -> m () glFinishFenceNV v1 = liftIO $ dyn3 ptr_glFinishFenceNV v1 {-# NOINLINE ptr_glFinishFenceNV #-} ptr_glFinishFenceNV :: FunPtr (GLuint -> IO ()) ptr_glFinishFenceNV = unsafePerformIO $ getCommand "glFinishFenceNV" -- glFinishObjectAPPLE --------------------------------------------------------- glFinishObjectAPPLE :: MonadIO m => GLenum -- ^ @object@ of type [ObjectTypeAPPLE](Graphics-GL-Groups.html#ObjectTypeAPPLE). -> GLint -- ^ @name@. -> m () glFinishObjectAPPLE v1 v2 = liftIO $ dyn58 ptr_glFinishObjectAPPLE v1 v2 {-# NOINLINE ptr_glFinishObjectAPPLE #-} ptr_glFinishObjectAPPLE :: FunPtr (GLenum -> GLint -> IO ()) ptr_glFinishObjectAPPLE = unsafePerformIO $ getCommand "glFinishObjectAPPLE"
haskell-opengl/OpenGLRaw
src/Graphics/GL/Functions/F07.hs
bsd-3-clause
56,864
0
19
7,273
9,165
4,742
4,423
1,002
1
import Data.List import Control.Monad d3 = [999,998..100] n2dr :: Int -> [Int] n2dr n | n < 10 = [n] | otherwise = d : n2dr (n `div` 10) where d = n `mod` 10 main = do let ans = fmap maximum . sequence . filter (/= Nothing) . fmap (find (\n -> let d = n2dr n in reverse d == d)) $ (\ds -> if ds == [] then []; else map (* head ds) ds) <$> tails d3 print ans
mskmysht/ProjectEuler
src/Problem4.hs
bsd-3-clause
435
0
22
161
223
116
107
16
2
module Newt.Utilities ( copyDirectory , cleanup , trim , isValueArg ) where import Prelude hiding ( catch ) import Control.Exception ( IOException, catch, finally ) import Data.Char (isSpace) import System.Directory ( removeFile, removeDirectory ) import System.Process ( rawSystem ) isValueArg :: String -> Bool isValueArg str = '=' `elem` str -- | Currently using rawSystem -- -- XXX this doesn't do proper exception handling, at all. Sorry about that. copyDirectory :: FilePath -> FilePath -> IO () copyDirectory dir newLocation = do _ <- rawSystem "cp" ["-rf", dir, newLocation] return () cleanup :: [FilePath] -> IO a -> IO a cleanup files operation = do finally operation $ do mapM_ rmIfExists files where rmIfExists :: FilePath -> IO () rmIfExists file = catch (removeFile file) (fileFailedHandler file) fileFailedHandler :: FilePath -> IOException -> IO () fileFailedHandler file _e = catch (removeDirectory file) dirFailedHandler dirFailedHandler :: IOException -> IO () dirFailedHandler _e = return () -- | remove leading / trailing whitespace. trim :: String -> String trim = reverse . dropSpaces . reverse . dropSpaces where dropSpaces = dropWhile isSpace
creswick/Newt
src/Newt/Utilities.hs
bsd-3-clause
1,302
1
10
314
327
176
151
28
1
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- -- | Let expressions. {-# LANGUAGE Trustworthy #-} module Copilot.Language.Operators.Local ( local ) where import Copilot.Core (Typed) import Copilot.Language.Stream (Stream (..)) -------------------------------------------------------------------------------- local :: (Typed a, Typed b) => Stream a -> (Stream a -> Stream b) -> Stream b local = Local --------------------------------------------------------------------------------
leepike/copilot-language
src/Copilot/Language/Operators/Local.hs
bsd-3-clause
675
0
10
68
97
58
39
7
1
module LambdaQuest.SystemFsub.PrettyPrint (prettyPrintTypeP ,prettyPrintType ,prettyPrintTermP ,prettyPrintTerm ) where import LambdaQuest.SystemFsub.Type import LambdaQuest.SystemFsub.Parse (NameBinding(..)) varNames :: [NameBinding] -> [String] varNames = foldr (\x ys -> case x of NVarBind n -> n:ys _ -> ys) [] tyVarNames :: [NameBinding] -> [String] tyVarNames = foldr (\x ys -> case x of NTyVarBind n -> n:ys _ -> ys) [] rename :: [String] -> String -> String rename ctx name | name `notElem` ctx = name | otherwise = loop 1 where loop :: Int -> String loop i = case name ++ show i of m | m `notElem` ctx -> m _ -> loop (i + 1) -- <2>: Int | Real | Bool | <type variable> | <0> -- <1>: <2> -> <1> -- <0>: forall a <: <1>. <0> prettyPrintTypeP :: Int -> [NameBinding] -> Type -> ShowS prettyPrintTypeP p ctx t = case t of TyPrim PTyInt -> showString "Int" TyPrim PTyReal -> showString "Real" TyPrim PTyBool -> showString "Bool" TyPrim PTyUnit -> showString "Unit" TyTop -> showString "Top" TyArr s t -> showParen (p > 1) $ prettyPrintTypeP 2 ctx s . showString " -> " . prettyPrintTypeP 1 (NAnonymousBind : ctx) t TyRef i _ | i < length ctx -> case ctx !! i of NTyVarBind n -> showString n n -> showString "<invalid type variable reference #" . shows i . showString ": " . shows n . showChar '>' | otherwise -> showString "<invalid type variable reference #" . shows i . showString ", index out of range>" TyAll name TyTop t -> let name' = rename (tyVarNames ctx) name in showParen (p > 0) $ showString "forall " . showString name' . showString ". " . prettyPrintTypeP 0 (NTyVarBind name' : ctx) t TyAll name b t -> let name' = rename (tyVarNames ctx) name in showParen (p > 0) $ showString "forall " . showString name' . showString "<:" . prettyPrintTypeP 1 ctx b . showString ". " . prettyPrintTypeP 0 (NTyVarBind name' : ctx) t prettyPrintType :: Type -> String prettyPrintType t = prettyPrintTypeP 0 [] t "" -- <2>: <primitive> | <variable> | (<0>) -- <1>: <1> <2> | <1> [ty] | <1> as <type> -- <0>: \x:t. <0> | ?a. <0> | if <0> then <0> else <0> prettyPrintTermP :: Int -> [NameBinding] -> Term -> ShowS prettyPrintTermP p ctx t = case t of TPrimValue (PVInt x) -> shows x TPrimValue (PVReal x) -> shows x TPrimValue (PVBool x) -> shows x TPrimValue PVUnit -> showString "unit" TPrimValue (PVBuiltinUnary f) -> showString $ case f of BNegateInt -> "negateInt" BNegateReal -> "negateReal" BIntToReal -> "intToReal" TPrimValue (PVBuiltinBinary f) -> showString $ case f of BAddInt -> "addInt" BSubInt -> "subInt" BMulInt -> "mulInt" BLtInt -> "ltInt" BLeInt -> "leInt" BEqualInt -> "equalInt" BAddReal -> "addReal" BSubReal -> "subReal" BMulReal -> "mulReal" BDivReal -> "divReal" BLtReal -> "ltReal" BLeReal -> "leReal" BEqualReal -> "equalReal" TAbs name ty body -> let name' = rename (varNames ctx) name in showParen (p > 0) $ showChar '\\' . showString name' . showChar ':' . prettyPrintTypeP 1 ctx ty . showString ". " . prettyPrintTermP 0 (NVarBind name' : ctx) body TTyAbs name TyTop body -> let name' = rename (tyVarNames ctx) name in showParen (p > 0) $ showString "?" . showString name' . showString ". " . prettyPrintTermP 0 (NTyVarBind name' : ctx) body TTyAbs name b body -> let name' = rename (tyVarNames ctx) name in showParen (p > 0) $ showString "?" . showString name' . showString "<:" . prettyPrintTypeP 1 ctx b . showString ". " . prettyPrintTermP 0 (NTyVarBind name' : ctx) body TRef i _ | i < length ctx -> case ctx !! i of NVarBind n -> showString n n -> showString "<invalid variable reference #" . shows i . showString ": " . shows n . showChar '>' | otherwise -> showString "<invalid variable reference #" . shows i . showString ", index out of range>" TApp u v -> showParen (p > 1) $ prettyPrintTermP 1 ctx u . showChar ' ' . prettyPrintTermP 2 ctx v TTyApp u t -> showParen (p > 1) $ prettyPrintTermP 1 ctx u . showString " [" . prettyPrintTypeP 0 ctx t . showChar ']' TLet name def body -> let name' = rename (varNames ctx) name in showParen (p > 0) $ showString "let " . showString name' . showString " = " . prettyPrintTermP 0 ctx def . showString " in " . prettyPrintTermP 0 (NVarBind name' : ctx) body TIf cond then_ else_ -> showParen (p > 0) $ showString "if " . prettyPrintTermP 0 ctx cond . showString " then " . prettyPrintTermP 0 ctx then_ . showString " else " . prettyPrintTermP 0 ctx else_ TCoerce x t -> showParen (p > 1) $ prettyPrintTermP 1 ctx x . showString " as " . prettyPrintTypeP 1 ctx t prettyPrintTerm :: Term -> String prettyPrintTerm t = prettyPrintTermP 0 [] t ""
minoki/LambdaQuest
src/LambdaQuest/SystemFsub/PrettyPrint.hs
bsd-3-clause
5,123
0
18
1,427
1,774
842
932
82
30
-- | The Language type that is the core of GroteTrap. module Language.GroteTrap.Language ( -- * Language Language(..), language, -- * Operators Operator(..), Fixity1(..), Fixity2(..), isUnary, isBinary, isAssoc, findOperator, -- * Functions Function(..), findFunction, function1, function2 ) where ------------------------------------ -- Language ------------------------------------ -- | Language connects the syntax of identifiers, numbers, operators and functions with their semantics. GroteTrap is able to derive a parser and evaluator from a Language, as well as convert between source text selections and tree selections. data Language a = Language { variable :: Maybe (String -> a) , number :: Maybe (Int -> a) , operators :: [Operator a] , functions :: [Function a] } -- | An empty language. Use this as the starting base of your languages, setting only those fields that are of importance. language :: Language a language = Language { variable = Nothing , number = Nothing , operators = [] , functions = [] } ------------------------------------ -- Operators ------------------------------------ -- | Representation of an operator. data Operator a = -- | An operator expecting one operand. Unary { opSem1 :: a -> a , opFixity1 :: Fixity1 , opPrio :: Int , opToken :: String } | -- | A non-associative operator expecting two operands. Binary { opSem2 :: a -> a -> a , opFixity2 :: Fixity2 , opPrio :: Int , opToken :: String } | -- | An infix associative operator that chains together many operands. Assoc { opSemN :: [a] -> a , opPrio :: Int , opToken :: String } -- | Fixity for unary operators. data Fixity1 = Prefix -- ^ The operator is written before its operand. | Postfix -- ^ The operator is written after its operand. deriving (Show, Enum, Eq) -- | Fixity for infix binary operators. data Fixity2 = InfixL -- ^ The operator associates to the left. | InfixR -- ^ The operator associates to the right. deriving (Show, Enum, Eq) isUnary, isBinary, isAssoc :: Operator a -> Bool isUnary (Unary _ _ _ _) = True isUnary _ = False isBinary (Binary _ _ _ _) = True isBinary _ = False isAssoc (Assoc _ _ _) = True isAssoc _ = False -- | @findOperator name p os@ yields the operator from @os@ that matches the predicate @p@ and has token @name@. Fails if there are no or several matching operators. findOperator :: Monad m => String -> (Operator a -> Bool) -> [Operator a] -> m (Operator a) findOperator name f os = case filter (\o -> f o && opToken o == name) os of [] -> fail ("no such operator: " ++ name) [o] -> return o _ -> fail ("duplicate operator: " ++ name) ------------------------------------ -- Functions ------------------------------------ -- | Representation of a function. data Function a = Function { fnSem :: [a] -> a , fnName :: String } -- | Lifts a unary function to a 'Function'. function1 :: (a -> a) -> String -> Function a function1 f = Function (\[x] -> f x) -- | Lifts a binary function to a 'Function'. function2 :: (a -> a -> a) -> String -> Function a function2 f = Function (\[x, y] -> f x y) -- | Yelds the function with the specified name. Fails if there are no or several matching functions. findFunction :: Monad m => String -> [Function a] -> m (Function a) findFunction name fs = case filter ((== name) . fnName) fs of [] -> fail ("no such function: " ++ name) [f] -> return f _ -> fail ("duplicate function: " ++ name)
MedeaMelana/GroteTrap
Language/GroteTrap/Language.hs
bsd-3-clause
3,739
0
11
974
843
483
360
67
3
module Geometry.Cuboid ( volume, area ) where volume :: Float -> Float -> Float -> Float volume a b c = rectangleArea a b * c area :: Float -> Float -> Float -> Float area a b c = rectangleArea a b * 2 + rectangleArea a c * 2 + rectangleArea c b * 2 rectangleArea :: Float -> Float -> Float rectangleArea a b = a * b
kyk0704/haskell-test
src/Geometry/Cuboid.hs
bsd-3-clause
354
0
10
108
143
73
70
11
1
{-# LANGUAGE DeriveDataTypeable #-} -- | These module exposes internals of the library module Control.IO.Region.Internal where import Prelude (($!), Enum(..)) import Data.Typeable import Data.Bool import Data.Int import Data.Either import Data.Eq import Data.Function import qualified Data.List as List import Data.Tuple import Data.Maybe import Control.Monad import Control.Applicative import Control.Exception import Control.Concurrent.STM import System.IO import Text.Show -- | Region owns resources and frees them on close data Region = Region { resources :: TVar [(Key, IO ())], closed :: TVar Bool } deriving Eq -- | Each resource is identified by unique key data Key = Key { keyRegion :: Region, keyFreed :: TVar Bool } deriving Eq -- | Resource not found in the specified region data NotFound = NotFound deriving (Show, Typeable) instance Exception NotFound where -- | Region already closed data AlreadyClosed = AlreadyClosed deriving (Show, Typeable) instance Exception AlreadyClosed where -- | Resource already freed data AlreadyFreed = AlreadyFreed deriving (Show, Typeable) instance Exception AlreadyFreed where -- | Open new region. Prefer `Control.IO.Region.region` function. open :: IO Region open = Region <$> newTVarIO [] <*> newTVarIO False -- | Close the region. Prefer `Control.IO.Region.region` function. -- -- It is an error to close region twice. -- -- When `close` fails for any reason, the region is guaranteed to be closed -- and all cleanup actions are called. -- -- It will never ignore asynchronous exception in the cleanup action. -- -- When exception occurs in one of the cleanup actions, `close` itself will -- rethrow the exception. If more then one cleanup action throws synchronous -- exception, then one of them is rethrown, others are ignored. If cleanup -- action throws asynchronous exception, then subsequent cleanups are -- executed in masking state `MaskedUninterruptible` to make sure other -- asynchronous exception won't appear. close :: Region -> IO () close r = mask_ $ do ress <- uninterruptibleMask_ $ atomically $ do guardOpen r ress <- readTVar (resources r) writeTVar (resources r) $! [] writeTVar (closed r) True forM_ ress $ \(k, _) -> writeTVar (keyFreed k) True return (List.map snd ress) go ress where go [] = return $! () go (res:ress) = do res `onExceptionEx` go ress go ress -- | Extended version of `onException`, which ignores synchronous -- exceptions from the handler. onExceptionEx :: IO a -> IO b -> IO a onExceptionEx io h = io `catch` \e -> do case fromException e of Just SomeAsyncException{} -> do -- we are handling asynchronous exception, and we don't want another -- one to appear, so mask them hard ignoreExceptions $ uninterruptibleMask_ h throwIO e Nothing -> ignoreExceptions h >> throwIO e -- | Ignore any synchronous exception from the action ignoreExceptions :: IO a -> IO () ignoreExceptions io = mask $ \restore -> do res <- try (restore io) case res of Left e -> case fromException e of Just SomeAsyncException{} -> throwIO e Nothing -> return $! () Right _ -> return $! () -- | Allocate resource inside the region -- -- The cleanup action should guarantee that the resource will be deallocated -- even if it fails for any reason, including the case when it's interrupted -- with asynchronous exception. -- -- Cleanup action might expect to be called with asynchronous exceptions -- masked, but the exact masking state, `MaskedInterruptible` or -- `MaskedUninterruptible`, is not specified. -- -- Cleanup should never throw asynchronous exception under -- `MaskedUninterruptible`. alloc :: Region -> IO a -- ^ action to allocate resource -> (a -> IO ()) -- ^ action to cleanup resource -> IO (a, Key) -- ^ the resource and it's key alloc r acquire cleanup = mask_ $ do res <- acquire uninterruptibleMask_ $ atomically $ do guardOpen r k <- Key <$> pure r <*> newTVar False modifyTVar' (resources r) ((k, cleanup res) :) return (res, k) -- | Free the resource earlier then it's region will be closed. -- It will be removed from the region immediately. -- It is error to free resource twice free :: Key -> IO () free k = mask_ $ join $ atomically $ do let r = keyRegion k guardLive k m_res <- List.lookup k <$> readTVar (resources r) case m_res of Nothing -> throwSTM NotFound Just c -> do modifyTVar' (resources r) $ List.filter ((/= k) . fst) writeTVar (keyFreed k) True return c -- | Move resource to other region. -- The old key becomes invalid and should not be used moveToSTM :: Key -> Region -> STM Key moveToSTM k r = do guardLive k guardOpen (keyRegion k) m_res <- List.lookup k <$> readTVar (resources $ keyRegion k) case m_res of Nothing -> throwSTM NotFound Just c -> do guardOpen r modifyTVar' (resources $ keyRegion k) $ List.filter ((/= k) . fst) writeTVar (keyFreed k) True k' <- Key <$> pure r <*> newTVar False modifyTVar' (resources r) ((k', c) :) return k' guardOpen :: Region -> STM () guardOpen r = do c <- readTVar (closed r) when c $ throwSTM AlreadyClosed guardLive :: Key -> STM () guardLive k = do f <- readTVar (keyFreed k) when f $ throwSTM AlreadyFreed
Yuras/io-region
lib/Control/IO/Region/Internal.hs
bsd-3-clause
5,401
0
17
1,189
1,346
682
664
119
3
import Common.Numbers.Numbers (multiBinomial) import Data.List (group) g d f | d == 0 = [[]] | otherwise = concatMap (\f0 -> map (f0:) (g (d - 1) f0)) [1 .. f] combinations :: Int -> Int -> Int -> Int -> [[Int]] combinations d f top s = concatMap r possibles where possibles = filter (\xs -> sum xs == s) $ g top f :: [[Int]] r xs = map (\ys -> xs ++ ys) $ g (d - top) (last xs) solve d f top s = sum $ map count combs where combs = combinations d f top s count xs = multiBinomial $ map length (group xs) main = print $ solve 20 12 10 70
foreverbell/project-euler-solutions
src/240.hs
bsd-3-clause
568
2
13
150
317
162
155
12
1
module Utils.UnificationTest where {- This module defines -} import Utils.Unification import Utils.Utils import Data.Map (Map, (!), member) import qualified Data.Map as M import Data.Set (Set, insert, findMin, deleteMin) import qualified Data.Set as S import qualified Data.List as L import Data.Maybe import Data.Bifunctor import Control.Arrow ((&&&)) data Tree = Node String [Tree] | Var String deriving (Show, Ord, Eq) instance Node Tree where hasChildren (Node _ ch) = not $ L.null ch hasChildren _ = False getChildren (Node _ ch) = ch getChildren _ = [] newChildren (Node f _) = Node f isVar (Var _) = True isVar _ = False getName (Var s) = s sameSymbol (Node f _) (Node g _) = f == g varX = Var "x" varY = Var "y" tree0 = Node "f" [varX, Node "a"[]] tree1 = Node "f" [Node "b" [], varY] unif0_1 = Right (M.fromList [("x", Node "b" []), ("y", Node "a" [])], []) unifxy = Right (M.fromList [("y", varX)], []) unifx_0 = Right (M.fromList [("x",Node "f" [Var "x",Node "a" []])] , ["x"]) test :: Node a => ((a, a), Either String (Substitution a, [Name])) -> Bool test ((a, b), exp) = let eSubs = unify a b cycles = eSubs |> (id &&& occursCheck) in cycles == exp -- Should return true tests' = [((tree0, tree1), unif0_1), ((varX, varY), unifxy), ((varX, tree0), unifx_0)] tests = tests' |> test & mapi & filter (not . snd) |> fst |> (\i -> Left $ "Unification test "++show i++" failed")
pietervdvn/ALGT
src/Utils/UnificationTest.hs
bsd-3-clause
1,449
58
13
309
663
396
267
38
1
{-# LANGUAGE BangPatterns, MultiWayIf #-} module Geom2D.CubicBezier.Approximate (approximatePath, approximateQuadPath, approximatePathMax, approximateQuadPathMax, approximateCubic) where import Geom2D import Geom2D.CubicBezier.Basic import Geom2D.CubicBezier.Numeric import Data.Maybe import Data.List import qualified Data.Vector.Unboxed as V import qualified Data.Map as M import Data.Function interpolate :: (Num a) => a -> a -> a -> a interpolate a b x = (1-x)*a + x*b -- | Approximate a function with piecewise cubic bezier splines using -- a least-squares fit, within the given tolerance. Each subcurve is -- approximated by using a finite number of samples. It is recommended -- to avoid changes in direction by subdividing the original function -- at points of inflection. approximatePath :: (V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -- ^ The function to approximate and it's derivative -> Int -- ^ The number of discrete samples taken to -- approximate each subcurve. More samples are -- more precise but take more time to calculate. -- For good precision 16 is a good candidate. -> a -- ^ The tolerance -> a -- ^ The lower parameter of the function -> a -- ^ The upper parameter of the function -> Bool -- ^ Calculate the result faster, but with more -- subcurves. Runs typically 10 times faster, but -- generates 50% more subcurves. Useful for interactive use. -> [CubicBezier a] approximatePath f n tol tmin tmax fast | err < tol = [curve] | otherwise = approximatePath' f n tol tmin tmax fast where (curve, err) = approx1cubic n f tmin tmax (if fast then 0 else 5) {-# SPECIALIZE approximatePath :: (Double -> (DPoint, DPoint)) -> Int -> Double -> Double -> Double -> Bool -> [CubicBezier Double] #-} -- | Approximate a function with piecewise quadratic bezier splines -- using a least-squares fit, within the given tolerance. It is -- recommended to avoid changes in direction by subdividing the -- original function at points of inflection. approximateQuadPath :: (Show a, V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -- ^ The function to approximate and it's derivative -> a -- ^ The tolerance -> a -- ^ The lower parameter of the function -> a -- ^ The upper parameter of the function -> Bool -- ^ Calculate the result faster, but with more -- subcurves. -> [QuadBezier a] approximateQuadPath f tol tmin tmax fast | err < tol = [curve] | otherwise = approximateQuad' f tol tmin tmax fast where curve = approx1quad f tmin tmax err = maxDist f curve tmin tmax (if fast then 0 else 5) {-# SPECIALIZE approximateQuadPath :: (Double -> (DPoint, DPoint)) -> Double -> Double -> Double -> Bool -> [QuadBezier Double] #-} -- find the distance between the function at t and the quadratic bezier. -- calculate the value and derivative at t, and improve the closeness of t. quadDist :: (V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -> QuadBezier a -> a -> a -> Int -> a -> a quadDist f qb tmin tmax maxiter t = quadDist' f qb tmin tmax t (fst (f $ interpolate tmin tmax t)) maxiter (evalBezierDeriv qb t) quadDist' :: (V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -> QuadBezier a -> a -> a -> a -> Point a -> Int -> (Point a, Point a) -> a quadDist' f qb tmin tmax t p maxiter (b, b') | maxiter <= 1 || abs (err2-err1) <= err1 * (1/8) = err2 | otherwise = quadDist' f qb tmin tmax (t+ndist) p (maxiter-1) (b2, b2') where dp = p ^-^ b err1 = vectorMag dp -- distance from p to the normal at b(t) / velocity at t ndist = (dp ^.^ b') / (b' ^.^ b') (b2, b2') = evalBezierDeriv qb (t+ndist) err2 = vectorDistance p b2 -- find maximum distance using golden section search maxDist :: (V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -> QuadBezier a -> a -> a -> Int -> a maxDist f qb tmin tmax maxiter = quadDist f qb tmin tmax maxiter $ goldSearch (quadDist f qb tmin tmax maxiter) 4 approxquad :: (Ord a, Floating a) => Point a -> Point a -> Point a -> Point a -> QuadBezier a approxquad p0 p0' p1' p1 | abs (pointY q') < abs (pointX q'*1e-3) = QuadBezier p0 (interpolateVector p0 p1 0.5) p1 | otherwise = QuadBezier p0 (p1^+^p1'^*t) p1 where q = rotateVec (flipVector p0') $* p1^-^p0 q' = rotateVec (flipVector p0') $* p1' t = - pointY q / pointY q' approx1quad :: (Ord a, Floating a) => (a -> (Point a, Point a)) -> a -> a -> QuadBezier a approx1quad f tmin tmax = approxquad p0 p0' p1' p1 where (p0, p0') = f tmin (p1, p1') = f tmax splitQuad :: (Show a, V.Unbox a, Ord a, Floating a) => a -> a -> (a -> (Point a, Point a)) -> a -> a -> Int -> (a, a, QuadBezier a, a, QuadBezier a) splitQuad node offset f tmin tmax maxiter = splitQuad' node offset f tmin tmax maxiter maxiter splitQuad' :: (Show a, V.Unbox a, Ord a, Floating a) => a -> a -> (a -> (Point a, Point a)) -> a -> a -> Int -> Int -> (a, a, QuadBezier a, a, QuadBezier a) splitQuad' node offset f tmin tmax maxiter maxiter2 | maxiter < 1 || (err0 < 2*err1 && err0 > err1/2) = (tmid, err0, curve0, err1, curve1) | otherwise = splitQuad' (if err0 < err1 then node+offset else node-offset) (offset/2) f tmin tmax (maxiter-1) maxiter2 where tmid = interpolate tmin tmax node curve0 = approx1quad f tmin tmid err0 = maxDist f curve0 tmin tmid maxiter2 curve1 = approx1quad f tmid tmax err1 = maxDist f curve1 tmid tmax maxiter2 approximateQuad' :: (Show a, V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -> a -> a -> a -> Bool -> [QuadBezier a] approximateQuad' f tol tmin tmax fast = (if err0 <= tol then [curve0] else approximateQuad' f tol tmin tmid fast) ++ (if err1 <= tol then [curve1] else approximateQuad' f tol tmid tmax fast) where (tmid, err0, curve0, err1, curve1) = splitQuad 0.5 0.25 f tmin tmax (if fast then 0 else 5) approximatePath' :: (V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -> Int -> a -> a -> a -> Bool -> [CubicBezier a] approximatePath' f n tol tmin tmax fast = (if err0 <= tol then [curve0] else approximatePath' f n tol tmin tmid fast) ++ (if err1 <= tol then [curve1] else approximatePath' f n tol tmid tmax fast) where (tmid, err0, curve0, err1, curve1) = splitCubic n 0.5 0.25 f tmin tmax (if fast then 0 else 5) --{-# SPECIALIZE approximatePath' :: (Double -> (Point Double, Point Double)) -> Int -> Double -> Double -> Double -> [CubicBezier Double] #-} -- | Like approximatePath, but limit the number of subcurves. approximatePathMax :: (V.Unbox a, Floating a, Ord a) => Int -- ^ The maximum number of subcurves -> (a -> (Point a, Point a)) -- ^ The function to approximate and it's derivative -> Int -- ^ The number of discrete samples taken to -- approximate each subcurve. More samples are -- more precise but take more time to calculate. -- For good precision 16 is a good candidate. -> a -- ^ The tolerance -> a -- ^ The lower parameter of the function -> a -- ^ The upper parameter of the function -> Bool -- ^ Calculate the result faster, but with more -- subcurves. Runs faster (typically 10 times), -- but generates more subcurves (about 50%). -- Useful for interactive use. -> [CubicBezier a] approximatePathMax m f samples tol tmin tmax fast = approxMax f tol m fast (splitCubic samples) segments where segments = M.singleton err (FunctionSegment tmin tmax outline) (p0, p0') = f tmin (p1, p1') = f tmax ts = V.map (\i -> fromIntegral i/(fromIntegral samples+1) `asTypeOf` tmin) $ V.enumFromN (1::Int) samples points = V.map (fst . f . interpolate tmin tmax) ts curveCb = CubicBezier p0 (p0^+^p0') (p1^-^p1') p1 (outline, err) = approximateCubic curveCb points (Just ts) (if fast then 0 else 5) {-# SPECIALIZE approximatePathMax :: Int -> (Double -> (Point Double, Point Double)) -> Int -> Double -> Double -> Double -> Bool -> [CubicBezier Double] #-} data FunctionSegment b a = FunctionSegment { fsTmin :: !a, -- the least t param of the segment in the original curve _fsTmax :: !a, -- the max t param of the segment in the original curve fsCurve :: b -- the curve segment } -- | Like approximateQuadPath, but limit the number of subcurves. approximateQuadPathMax :: (V.Unbox a, Show a, Floating a, Ord a) => Int -- ^ The maximum number of subcurves -> (a -> (Point a, Point a)) -- ^ The function to approximate and it's derivative -> a -- ^ The tolerance -> a -- ^ The lower parameter of the function -> a -- ^ The upper parameter of the function -> Bool -- ^ Calculate the result faster, but with more -- subcurves. Runs faster, but generates more -- subcurves. Useful for interactive use. -> [QuadBezier a] approximateQuadPathMax m f tol tmin tmax fast = approxMax f tol m fast splitQuad segments where segments = M.singleton err (FunctionSegment tmin tmax curveQd) (p0, p0') = f tmin (p1, p1') = f tmax curveQd = approxquad p0 p0' p1' p1 err = maxDist f curveQd tmin tmax (if fast then 0 else 5) {-# SPECIALIZE approximateQuadPathMax :: Int -> (Double -> (Point Double, Point Double)) -> Double -> Double -> Double -> Bool -> [QuadBezier Double] #-} -- Keep a map from maxError to FunctionSegment for each subsegment to keep -- track of the segment with the maximum error. This ensures a n -- log(n) execution time, rather than n^2 when a list is used. approxMax :: (V.Unbox a, Ord a, Floating a) => (a -> (Point a, Point a)) -> a -> Int -> Bool -> (a -> a -> (a -> (Point a, Point a)) -> a -> a -> Int -> (a, a, b, a, b)) -> M.Map a (FunctionSegment b a) -> [b] approxMax f tol maxCurves fast splitBez segments | (maxCurves <= 1) || (err < tol) = map fsCurve $ sortBy (compare `on` fsTmin) $ map snd $ M.toList segments | otherwise = approxMax f tol (maxCurves-1) fast splitBez $ M.insert err_l (FunctionSegment t_min t_mid curve_l) $ M.insert err_r (FunctionSegment t_mid t_max curve_r) newSegments where ((err, FunctionSegment t_min t_max _), newSegments) = M.deleteFindMax segments (t_mid, err_l, curve_l, err_r, curve_r) = splitBez 0.5 0.25 f t_min t_max (if fast then 0 else 5) splitCubic :: (V.Unbox a, Ord a, Floating a) => Int -> a -> a -> (a -> (Point a, Point a)) -> a -> a -> Int -> (a, a, CubicBezier a, a, CubicBezier a) splitCubic n node offset f tmin tmax maxiter | maxiter < 1 || (err0 < 2*err1 && err0 > err1/2) = (tmid, err0, curve0, err1, curve1) | otherwise = splitCubic n (if err0 < err1 then node+offset else node-offset) (offset/2) f tmin tmax (maxiter-1) where tmid = interpolate tmin tmax node (curve0, err0) = approx1cubic n f tmin tmid maxiter (curve1, err1) = approx1cubic n f tmid tmax maxiter approx1cubic :: (V.Unbox a, Ord a, Floating a) => Int -> (a -> (Point a, Point a)) -> a -> a -> Int -> (CubicBezier a, a) approx1cubic n f t0 t1 maxiter = approximateCubic curveCb points (Just ts) maxiter where (p0, p0') = f t0 (p1, p1') = f t1 ts = V.map (\i -> fromIntegral i/(fromIntegral n+1)) (V.enumFromN 1 n :: V.Vector Int) points = V.map (fst . f . interpolate t0 t1) ts curveCb = CubicBezier p0 (p0^+^p0') (p1^+^p1') p1 {-# SPECIALIZE approx1cubic :: Int -> (Double -> (Point Double, Point Double)) -> Double -> Double -> Int -> (CubicBezier Double, Double) #-} -- | @approximateCubic b pts maxiter@ finds the least squares fit of a bezier -- curve to the points @pts@. The resulting bezier has the same first -- and last control point as the curve @b@, and have tangents colinear with @b@. approximateCubic :: (V.Unbox a, Ord a, Floating a) => CubicBezier a -- ^ Curve -> V.Vector (Point a) -- ^ Points -> Maybe (V.Vector a) -- ^ Params. Approximate if Nothing -> Int -- ^ Maximum iterations -> (CubicBezier a, a) -- ^ result curve and maximum error approximateCubic curve pts mbTs maxiter = let ts = fromMaybe (approximateParams (cubicC0 curve) (cubicC3 curve) pts) mbTs curve2 = fromMaybe curve $ lsqDist curve pts ts (bt, bt') = V.unzip $ V.map (evalBezierDeriv curve2) ts err = V.maximum $ V.zipWith vectorDistance pts bt (c, _, _, err2, _) = fromMaybe (curve2, ts, undefined, err, undefined) $ approximateCubic' curve2 pts ts maxiter err bt bt' in (c, err2) {-# SPECIALIZE approximateCubic :: CubicBezier Double -> V.Vector (Point Double) -> Maybe (V.Vector Double) -> Int -> (CubicBezier Double, Double) #-} -- find (a, b) which minimises ∑ᵢ(a*aᵢ + b*bᵢ + epsᵢ)² leastSquares :: (V.Unbox a, Fractional a, Eq a) => V.Vector a -> V.Vector a -> V.Vector a -> Maybe (a, a) leastSquares as bs epses = solveLinear2x2 a b c d e f where square x = x*x a = V.sum $ V.map square as b = V.sum $ V.zipWith (*) as bs c = V.sum $ V.zipWith (*) as epses d = b e = V.sum $ V.map square bs f = V.sum $ V.zipWith (*) bs epses {-# SPECIALIZE leastSquares ::V.Vector Double -> V.Vector Double -> V.Vector Double -> Maybe (Double, Double) #-} -- find the least squares between the points pᵢ and B(tᵢ) for -- bezier curve B, where pts contains the points pᵢ and ts -- the values of tᵢ . -- The tangent at the beginning and end is maintained. -- Since the start and end point remains the same, -- we need to find the new value of p2' = p1 + α₁ * (p2 - p1) -- and p₃' = p4 + α2 * (p3 - p4) -- minimizing (∑|B(tᵢ) - pᵢ|²) gives a linear equation -- with two unknown values (α₁ and α₂) lsqDist :: (V.Unbox a, Fractional a, Eq a) => CubicBezier a -> V.Vector (Point a) -> V.Vector a -> Maybe (CubicBezier a) lsqDist (CubicBezier (Point !p1x !p1y) (Point !p2x !p2y) (Point !p3x !p3y) (Point !p4x !p4y)) pts ts = let calcParams t (Point px py) = let t2 = t * t; t3 = t2 * t ax = 3 * (p2x - p1x) * (t3 - 2 * t2 + t) ay = 3 * (p2y - p1y) * (t3 - 2 * t2 + t) bx = 3 * (p3x - p4x) * (t2 - t3) by = 3 * (p3y - p4y) * (t2 - t3) cx = (p4x - p1x) * (3 * t2 - 2 * t3) + p1x - px cy = (p4y - p1y) * (3 * t2 - 2 * t3) + p1y - py in (ax * ax + ay * ay, ax * bx + ay * by, ax * cx + ay * cy, bx * ax + by * ay, bx * bx + by * by, bx * cx + by * cy) add6 (!a,!b,!c,!d,!e,!f) (!a',!b',!c',!d',!e',!f') = (a+a',b+b',c+c',d+d',e+e',f+f') ( as, bs, cs, ds, es, fs ) = V.foldl1' add6 $ V.zipWith calcParams ts pts in do (alpha1, alpha2) <- solveLinear2x2 as bs cs ds es fs let cp1 = Point (alpha1 * (p2x - p1x) + p1x) (alpha1 * (p2y - p1y) + p1y) cp2 = Point (alpha2 * (p3x - p4x) + p4x) (alpha2 * (p3y - p4y) + p4y) Just $ CubicBezier (Point p1x p1y) cp1 cp2 (Point p4x p4y) {-# SPECIALIZE lsqDist :: CubicBezier Double -> V.Vector (Point Double) -> V.Vector Double -> Maybe (CubicBezier Double) #-} -- calculate the least Squares bezier curve by choosing approximate values -- of t, and iterating again with an improved estimate of t, by taking the -- the values of t for which the points are closest to the curve approximateCubic' :: (V.Unbox a, Ord a, Floating a) => CubicBezier a -> V.Vector (Point a) -> V.Vector a -> Int -> a -> V.Vector (Point a) -> V.Vector (Point a) -> Maybe (CubicBezier a, V.Vector a, V.Vector a, a, V.Vector (Point a)) approximateCubic' (CubicBezier p1 p2 p3 p4) pts ts maxiter err bt bt' = do let dir1 = V.map (($* (p2^-^p1)) . rotateVec . flipVector) bt' dir2 = V.map (($* (p3^-^p4)) . rotateVec . flipVector) bt' ps = V.zipWith3 (\b b' p -> rotateVec (flipVector b') $* (p^-^b)) bt bt' pts errs = V.map (negate.pointY) ps as = V.zipWith (\d t -> 3*pointY d*(1-t)*(1-t)*t) dir1 ts bs = V.zipWith (\d t -> 3*pointY d*(1-t)*t*t) dir2 ts (a,b) <- leastSquares as bs errs let newTs = V.zipWith5 (\t p d1 d2 b' -> max 0 $ min 1 $ t + (pointX p - 3*(1-t)*t*(a*pointX d1*(1-t) + b*pointX d2*t)) / vectorMag b') ts ps dir1 dir2 bt' newCurve = CubicBezier p1 (p2 ^+^ a*^(p2^-^p1)) (p3 ^+^ b*^(p3^-^p4)) p4 (bt2,bt2') = V.unzip $ V.map (evalBezierDeriv newCurve) newTs err2 = V.zipWith vectorDistance pts bt2 maxErr = V.maximum err2 -- alternative method for finding the t values: -- newTs = V.zipWith (-) ts (V.zipWith (calcDeltaT newCurve) pts ts) if maxiter < 1 || abs(err - maxErr) <= err/8 then return (newCurve, newTs, err2, maxErr, bt2) else approximateCubic' newCurve pts newTs (maxiter-1) maxErr bt2 bt2' {-# SPECIALIZE approximateCubic' :: CubicBezier Double -> V.Vector (Point Double) -> V.Vector Double -> Int -> Double -> V.Vector (Point Double) -> V.Vector (Point Double) -> Maybe (CubicBezier Double, V.Vector Double, V.Vector Double, Double, V.Vector (Point Double)) #-} -- approximate t by calculating the distances between all points -- and dividing by the total sum approximateParams :: (V.Unbox a, Floating a) => Point a -> Point a -> V.Vector (Point a) -> V.Vector a approximateParams start end pts | V.null pts = V.empty | otherwise = let dists = V.generate (V.length pts) (\i -> if i == 0 then vectorDistance start (V.unsafeIndex pts 0) else vectorDistance (V.unsafeIndex pts (i-1)) (V.unsafeIndex pts i)) total = V.sum dists + vectorDistance (V.last pts) end in V.map (/ total) $ V.scanl1 (+) dists {-# SPECIALIZE approximateParams :: Point Double -> Point Double -> V.Vector (Point Double) -> V.Vector Double #-} -- Alternative method for finding the next t values, using -- Newton-Rafphson. There is no noticable difference in speed or -- efficiency. -- calcDeltaT :: CubicBezier -> Point -> Double -> Double -- calcDeltaT curve (Point !ptx !pty) t = let -- (Point bezx bezy, Point dbezx dbezy, Point ddbezx ddbezy, _) = evalBezierDerivs curve t -- in ((bezx - ptx) * dbezx + (bezy - pty) * dbezy) / -- (dbezx * dbezx + dbezy * dbezy + (bezx - ptx) * ddbezx + (bezy - pty) * ddbezy)
kuribas/cubicbezier
Geom2D/CubicBezier/Approximate.hs
bsd-3-clause
20,273
1
23
6,385
5,969
3,142
2,827
318
4
module Main where import Text.Show.Pretty infixr 3 :->: infix 2 ::: infixl 1 :$: data T = TVar String | T :->: T | Int deriving (Show,Read,Eq) data E = String ::: T | E :$: E | Lit Int deriving (Show,Read,Eq) iii :: T iii = Int :->: (Int :->: Int) f :: E f = "f" ::: iii x :: E x = "x" ::: Int e :: E e = f :$: x :$: Lit 5 es :: [E] es = [e,(("*" ::: iii) :$: e) :$: e] main :: IO () main = do let str = ppShow es putStrLn str print (read str == es)
phadej/pretty-show
test/infix/Infix.hs
mit
477
0
10
137
250
139
111
24
1
{- Copyright © 2017-2019 Albert Krewinkel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} {-# LANGUAGE OverloadedStrings #-} {-| Utilities for testing hslua -} module Test.HsLua.Util ( assertLuaBool , pushLuaExpr , shouldBeErrorMessageOf , shouldBeResultOf , shouldHoldForResultOf , (=:) , (?:) ) where import Data.ByteString (ByteString) import Data.Monoid ((<>)) import Foreign.Lua ( Lua, run, runEither, loadstring, call, multret) import Test.Tasty (TestTree) import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=)) import qualified Foreign.Lua as Lua pushLuaExpr :: ByteString -> Lua () pushLuaExpr expr = loadstring ("return " <> expr) *> call 0 multret shouldBeResultOf :: (Eq a, Show a) => a -> Lua a -> Assertion shouldBeResultOf expected luaOp = do errOrRes <- runEither luaOp case errOrRes of Left (Lua.Exception msg) -> assertFailure $ "Lua operation failed with " ++ "message: '" ++ msg ++ "'" Right res -> res @?= expected shouldBeErrorMessageOf :: Show a => String -> Lua a -> Assertion shouldBeErrorMessageOf expectedErrMsg luaOp = do errOrRes <- runEither luaOp case errOrRes of Left (Lua.Exception msg) -> msg @?= expectedErrMsg Right res -> assertFailure ("Lua operation succeeded unexpectedly and returned " ++ show res) shouldHoldForResultOf :: Show a => (a -> Bool) -> Lua a -> Assertion shouldHoldForResultOf predicate luaOp = do errOrRes <- runEither luaOp case errOrRes of Left (Lua.Exception msg) -> assertFailure $ "Lua operation failed with " ++ "message: '" ++ msg ++ "'" Right res -> assertBool ("predicate doesn't hold for " ++ show res) (predicate res) assertLuaBool :: Lua Bool -> Assertion assertLuaBool luaOp = assertBool "" =<< run luaOp infix 3 =: (=:) :: String -> Assertion -> TestTree (=:) = testCase infixr 3 ?: (?:) :: String -> Lua Bool -> TestTree (?:) = luaTestBool luaTestBool :: String -> Lua Bool -> TestTree luaTestBool msg luaOp = testCase msg $ assertBool "Lua operation returned false" =<< run luaOp
tarleb/hslua
test/Test/HsLua/Util.hs
mit
3,140
0
13
647
615
325
290
51
2
module EVT.ParseEVT ( evtBasicSpec , parseEVTGuards , parseEVTActions , parseGuard , parseAction ) where import Common.AnnoState import Common.Id import Text.ParserCombinators.Parsec import Common.GlobalAnnotations (PrefixMap) import Common.Token (sortId) import CASL.AS_Basic_CASL import qualified CASL.Formula as CASL import EVT.AS import EVT.Keywords evtBasicSpec :: PrefixMap -> AParser st MACHINE evtBasicSpec _ = do spaces -- pos1 <- getPos es <- many parseEVTEvents -- pos2 <- getPos return (MACHINE es) parseEVTEvents ::AParser st EVENT parseEVTEvents = do try $ asKey event es <- parseEvent return es parseEvent ::AParser st EVENT parseEvent = do name <- evtSortId spaces gs <- many parseEVTGuards as <- many parseEVTActions return (EVENT name gs as) parseEVTGuards ::AParser st GUARD parseEVTGuards= do try $ asKey grd gs <- parseGuard return gs evtSortId :: AParser st SORT evtSortId = sortId evtKeywords parseGuard :: AParser st GUARD parseGuard= do gid<-evtSortId spaces pr<-CASL.formula evtKeywords return GUARD { gnum = gid , predicate = pr } parseEVTActions :: AParser st ACTION parseEVTActions= do try $ asKey action as <- parseAction return as parseAction :: AParser st ACTION parseAction = do aid<-evtSortId spaces st<- CASL.formula evtKeywords return ACTION { anum = aid , statement = st }
keithodulaigh/Hets
EVT/ParseEVT.hs
gpl-2.0
1,933
0
9
813
438
218
220
64
1
-- C->Haskell Compiler: CHS file abstraction -- -- Author : Manuel M T Chakravarty -- Created: 16 August 99 -- -- Version $Revision: 1.3 $ from $Date: 2005/01/23 15:44:36 $ -- -- Copyright (c) [1999..2004] Manuel M T Chakravarty -- -- This file 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 file 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. -- --- DESCRIPTION --------------------------------------------------------------- -- -- Main file for reading CHS files. -- -- Import hooks & .chi files -- ------------------------- -- -- Reading of `.chi' files is interleaved with parsing. More precisely, -- whenever the parser comes across an import hook, it immediately reads the -- `.chi' file and inserts its contents into the abstract representation of -- the hook. The parser checks the version of the `.chi' file, but does not -- otherwise attempt to interpret its contents. This is only done during -- generation of the binding module. The first line of a .chi file has the -- form -- -- C->Haskell Interface Version <version> -- -- where <version> is the three component version number `Version.version'. -- C->Haskell will only accept files whose version number match its own in -- the first two components (ie, major and minor version). In other words, -- it must be guaranteed that the format of .chi files is not altered between -- versions that differ only in their patchlevel. All remaining lines of the -- file are version dependent and contain a dump of state information that -- the binding file generator needs to rescue across modules. -- --- DOCU ---------------------------------------------------------------------- -- -- language: Haskell 98 -- -- The following binding hooks are recognised: -- -- hook -> `{#' inner `#}' -- inner -> `import' ['qualified'] ident -- | `context' ctxt -- | `type' ident -- | `sizeof' ident -- | `enum' idalias trans [`with' prefix] [deriving] -- | `call' [`pure'] [`unsafe'] [`nolock'] idalias -- | `fun' [`pure'] [`unsafe'] [`nolock'] idalias parms -- | `get' apath -- | `set' apath -- | `pointer' ['*'] idalias ptrkind -- | `class' [ident `=>'] ident ident -- ctxt -> [`lib' `=' string] [prefix] [lock] -- idalias -> ident [`as' (ident | `^')] -- prefix -> `prefix' `=' string -- lock -> `lock' `=' string -- deriving -> `deriving' `(' ident_1 `,' ... `,' ident_n `)' -- parms -> [verbhs `=>'] `{' parm_1 `,' ... `,' parm_n `}' `->' parm -- parm -> [ident_1 [`*' | `-']] verbhs [`&'] [ident_2 [`*' | `-']] -- apath -> ident -- | `*' apath -- | apath `.' ident -- | apath `->' ident -- trans -> `{' alias_1 `,' ... `,' alias_n `}' -- alias -> `underscoreToCase' -- | ident `as' ident -- ptrkind -> [`foreign' | `stable' ] ['newtype' | '->' ident] -- -- If `underscoreToCase' occurs in a translation table, it must be the first -- entry. -- -- Remark: Optional Haskell names are normalised during structure tree -- construction, ie, associations that associated a name with itself -- are removed. (They don't carry semantic content, and make some -- tests more complicated.) -- --- TODO ---------------------------------------------------------------------- -- module CHS (CHSModule(..), CHSFrag(..), CHSHook(..), CHSTrans(..), CHSParm(..), CHSArg(..), CHSAccess(..), CHSAPath(..), CHSPtrType(..), skipToLangPragma, hasCPP, loadCHS, dumpCHS, hssuffix, chssuffix, loadAllCHI, loadCHI, dumpCHI, chisuffix, showCHSParm) where -- standard libraries import Data.Char (isSpace, toUpper, toLower) import Data.List (intersperse) import Control.Monad (when, unless) -- Compiler Toolkit import Position (Position(..), Pos(posOf), nopos, isBuiltinPos) import Errors (interr) import Idents (Ident, identToLexeme, onlyPosIdent) -- C->Haskell import C2HSState (CST, nop, doesFileExistCIO, readFileCIO, writeFileCIO, getId, getSwitch, chiPathSB, catchExc, throwExc, raiseError, fatal, errorsPresent, showErrors, Traces(..), putTraceStr) -- friends import CHSLexer (CHSToken(..), lexCHS) -- CHS abstract syntax -- ------------------- -- representation of a CHS module (EXPORTED) -- data CHSModule = CHSModule [CHSFrag] -- a CHS code fragament (EXPORTED) -- -- * `CHSVerb' fragments are present throughout the compilation and finally -- they are the only type of fragment (describing the generated Haskell -- code) -- -- * `CHSHook' are binding hooks, which are being replaced by Haskell code by -- `GenBind.expandHooks' -- -- * `CHSCPP' and `CHSC' are fragements of C code that are being removed when -- generating the custom C header in `GenHeader.genHeader' -- -- * `CHSCond' are strutured conditionals that are being generated by -- `GenHeader.genHeader' from conditional CPP directives (`CHSCPP') -- data CHSFrag = CHSVerb String -- Haskell code Position | CHSHook CHSHook -- binding hook | CHSCPP String -- pre-processor directive Position | CHSLine Position -- line pragma | CHSC String -- C code Position | CHSCond [(Ident, -- C variable repr. condition [CHSFrag])] -- then/elif branches (Maybe [CHSFrag]) -- else branch | CHSLang [String] -- GHC language pragma Position instance Pos CHSFrag where posOf (CHSVerb _ pos ) = pos posOf (CHSHook hook ) = posOf hook posOf (CHSCPP _ pos ) = pos posOf (CHSLine pos ) = pos posOf (CHSC _ pos ) = pos posOf (CHSCond alts _) = case alts of (_, frag:_):_ -> posOf frag _ -> nopos posOf (CHSLang _ pos) = pos -- a CHS binding hook (EXPORTED) -- data CHSHook = CHSImport Bool -- qualified? Ident -- module name String -- content of .chi file Position | CHSContext (Maybe String) -- library name (Maybe String) -- prefix (Maybe String) -- lock function Position | CHSType Ident -- C type Position | CHSSizeof Ident -- C type Position | CHSEnum Ident -- C enumeration type (Maybe Ident) -- Haskell name CHSTrans -- translation table (Maybe String) -- local prefix [Ident] -- instance requests from user Position | CHSCall Bool -- is a pure function? Bool -- is unsafe? Bool -- is without lock? Ident -- C function (Maybe Ident) -- Haskell name Position | CHSFun Bool -- is a pure function? Bool -- is unsafe? Bool -- is without lock? Ident -- C function (Maybe Ident) -- Haskell name (Maybe String) -- type context [CHSParm] -- argument marshalling CHSParm -- result marshalling Position | CHSField CHSAccess -- access type CHSAPath -- access path Position | CHSPointer Bool -- explicit '*' in hook Ident -- C pointer name (Maybe Ident) -- Haskell name CHSPtrType -- Ptr, ForeignPtr or StablePtr Bool -- create new type? (Maybe Ident) -- Haskell type pointed to Position | CHSClass (Maybe Ident) -- superclass Ident -- class name Ident -- name of pointer type Position instance Pos CHSHook where posOf (CHSImport _ _ _ pos) = pos posOf (CHSContext _ _ _ pos) = pos posOf (CHSType _ pos) = pos posOf (CHSSizeof _ pos) = pos posOf (CHSEnum _ _ _ _ _ pos) = pos posOf (CHSCall _ _ _ _ _ pos) = pos posOf (CHSFun _ _ _ _ _ _ _ _ pos) = pos posOf (CHSField _ _ pos) = pos posOf (CHSPointer _ _ _ _ _ _ pos) = pos posOf (CHSClass _ _ _ pos) = pos -- two hooks are equal if they have the same Haskell name and reference the -- same C object -- instance Eq CHSHook where (CHSImport qual1 ide1 _ _) == (CHSImport qual2 ide2 _ _) = qual1 == qual2 && ide1 == ide2 (CHSContext olib1 opref1 olock1 _ ) == (CHSContext olib2 opref2 olock2 _ ) = olib1 == olib1 && opref1 == opref2 && olock1 == olock2 (CHSType ide1 _) == (CHSType ide2 _) = ide1 == ide2 (CHSSizeof ide1 _) == (CHSSizeof ide2 _) = ide1 == ide2 (CHSEnum ide1 oalias1 _ _ _ _) == (CHSEnum ide2 oalias2 _ _ _ _) = oalias1 == oalias2 && ide1 == ide2 (CHSCall _ _ _ ide1 oalias1 _) == (CHSCall _ _ _ ide2 oalias2 _) = oalias1 == oalias2 && ide1 == ide2 (CHSFun _ _ _ ide1 oalias1 _ _ _ _) == (CHSFun _ _ _ ide2 oalias2 _ _ _ _) = oalias1 == oalias2 && ide1 == ide2 (CHSField acc1 path1 _) == (CHSField acc2 path2 _) = acc1 == acc2 && path1 == path2 (CHSPointer _ ide1 oalias1 _ _ _ _) == (CHSPointer _ ide2 oalias2 _ _ _ _) = ide1 == ide2 && oalias1 == oalias2 (CHSClass _ ide1 _ _) == (CHSClass _ ide2 _ _) = ide1 == ide2 _ == _ = False -- translation table (EXPORTED) -- data CHSTrans = CHSTrans Bool -- underscore to case? [(Ident, Ident)] -- alias list -- marshalling descriptor for function hooks (EXPORTED) -- -- * a marshaller consists of a function name and flag indicating whether it -- has to be executed in the IO monad -- data CHSParm = CHSParm (Maybe (Ident, CHSArg)) -- "in" marshaller String -- Haskell type Bool -- C repr: two values? (Maybe (Ident, CHSArg)) -- "out" marshaller Position -- kinds of arguments in function hooks (EXPORTED) -- data CHSArg = CHSValArg -- plain value argument | CHSIOArg -- reference argument | CHSVoidArg -- no argument deriving (Eq) -- structure member access types (EXPORTED) -- data CHSAccess = CHSSet -- set structure field | CHSGet -- get structure field deriving (Eq) -- structure access path (EXPORTED) -- data CHSAPath = CHSRoot Ident -- root of access path | CHSDeref CHSAPath Position -- dereferencing | CHSRef CHSAPath Ident -- member referencing deriving (Eq) -- pointer options (EXPORTED) -- data CHSPtrType = CHSPtr -- standard Ptr from Haskell | CHSForeignPtr -- a pointer with a finalizer | CHSStablePtr -- a pointer into Haskell land deriving (Eq) instance Show CHSPtrType where show CHSPtr = "Ptr" show CHSForeignPtr = "ForeignPtr" show CHSStablePtr = "StablePtr" instance Read CHSPtrType where readsPrec _ ( 'P':'t':'r':rest) = [(CHSPtr, rest)] readsPrec _ ('F':'o':'r':'e':'i':'g':'n':'P':'t':'r':rest) = [(CHSForeignPtr, rest)] readsPrec _ ('S':'t':'a':'b':'l':'e' :'P':'t':'r':rest) = [(CHSStablePtr, rest)] readsPrec p (c:cs) | isSpace c = readsPrec p cs readsPrec _ _ = [] -- return a modified module description that starts off with a LANGUAGE pragma -- if it contains a LANGUAGE pragma at all skipToLangPragma :: CHSModule -> Maybe CHSModule skipToLangPragma (CHSModule frags) = hLP frags where hLP all@(CHSLang exts _:_) = Just (CHSModule all) hLP (x:xs) = hLP xs hLP [] = Nothing -- test if the language pragma contains the CPP option hasCPP :: CHSModule -> Bool hasCPP (CHSModule (CHSLang exts _:_)) = "CPP" `elem` exts hasCPP _ = False -- load and dump a CHS file -- ------------------------ hssuffix, chssuffix :: String hssuffix = ".hs" chssuffix = ".chs" -- parse a CHS module (EXPORTED) -- -- * in case of a syntactical or lexical error, a fatal error is raised; -- warnings are returned together with the module -- loadCHS :: FilePath -> CST s (CHSModule, String) loadCHS fname = do -- parse -- traceInfoRead fname contents <- readFileCIO fname traceInfoParse mod <- parseCHSModule (Position fname 1 1) contents -- check for errors and finalize -- errs <- errorsPresent if errs then do traceInfoErr errmsgs <- showErrors fatal ("CHS module contains \ \errors:\n\n" ++ errmsgs) -- fatal error else do traceInfoOK warnmsgs <- showErrors return (mod, warnmsgs) where traceInfoRead fname = putTraceStr tracePhasesSW ("Attempting to read file `" ++ fname ++ "'...\n") traceInfoParse = putTraceStr tracePhasesSW ("...parsing `" ++ fname ++ "'...\n") traceInfoErr = putTraceStr tracePhasesSW ("...error(s) detected in `" ++ fname ++ "'.\n") traceInfoOK = putTraceStr tracePhasesSW ("...successfully loaded `" ++ fname ++ "'.\n") -- given a file name (no suffix) and a CHS module, the module is printed -- into that file (EXPORTED) -- -- * the module can be flagged as being pure Haskell -- -- * the correct suffix will automagically be appended -- dumpCHS :: String -> CHSModule -> Bool -> CST s () dumpCHS fname mod pureHaskell = do let (suffix, kind) = if pureHaskell then (hssuffix , "(Haskell)") else (chssuffix, "(C->HS binding)") (version, _, _) <- getId writeFileCIO (fname ++ suffix) (contents version kind) where contents version kind | hasCPP mod = showCHSModule mod pureHaskell | otherwise = "-- GENERATED by " ++ version ++ " " ++ kind ++ "\n\ \-- Edit the ORIGNAL .chs file instead!\n\n" ++ showCHSModule mod pureHaskell -- to keep track of the current state of the line emission automaton -- data LineState = Emit -- emit LINE pragma if next frag is Haskell | Wait -- emit LINE pragma after the next '\n' | NoLine -- no pragma needed deriving (Eq) -- convert a CHS module into a string -- -- * if the second argument is `True', all fragments must contain Haskell code -- showCHSModule :: CHSModule -> Bool -> String showCHSModule (CHSModule frags) pureHaskell = showFrags pureHaskell Emit frags [] where -- the second argument indicates whether the next fragment (if it is -- Haskell code) should be preceded by a LINE pragma; in particular -- generated fragments and those following them need to be prefixed with a -- LINE pragma -- showFrags :: Bool -> LineState -> [CHSFrag] -> ShowS showFrags _ _ [] = id showFrags pureHs state (CHSVerb s pos : frags) = let (Position fname line _) = pos generated = isBuiltinPos pos emitNow = state == Emit || (state == Wait && not (null s) && nlStart) nlStart = head s == '\n' nextState = if generated then Wait else NoLine in (if emitNow then showString ("\n{-# LINE " ++ show (line `max` 0) ++ " " ++ show fname ++ " #-}" ++ (if nlStart then "" else "\n")) else id) . showString s . showFrags pureHs nextState frags showFrags False _ (CHSHook hook : frags) = showString "{#" . showCHSHook hook . showString "#}" . showFrags False Wait frags showFrags False _ (CHSCPP s _ : frags) = showChar '#' . showString s -- . showChar '\n' . showFrags False Emit frags showFrags pureHs _ (CHSLine s : frags) = showFrags pureHs Emit frags showFrags False _ (CHSC s _ : frags) = showString "\n#c" . showString s . showString "\n#endc" . showFrags False Emit frags showFrags False _ (CHSCond _ _ : frags) = interr "showCHSFrag: Cannot print `CHSCond'!" showFrags pureHs _ (CHSLang exts _ : frags) = let extsNoCPP = filter ((/=) "CPP") exts in if null extsNoCPP then showFrags pureHs Emit frags else showString "{-# LANGUAGE " . showString (concat (intersperse "," extsNoCPP)) . showString " #-}\n" . showFrags pureHs Emit frags showFrags True _ _ = interr "showCHSFrag: Illegal hook, cpp directive, or inline C code!" showCHSHook :: CHSHook -> ShowS showCHSHook (CHSImport isQual ide _ _) = showString "import " . (if isQual then showString "qualified " else id) . showCHSIdent ide showCHSHook (CHSContext olib oprefix olock _) = showString "context " . (case olib of Nothing -> showString "" Just lib -> showString "lib = " . showString lib . showString " ") . showPrefix oprefix False . (case olock of Nothing -> showString "" Just lock -> showString "lock = " . showString lock . showString " ") showCHSHook (CHSType ide _) = showString "type " . showCHSIdent ide showCHSHook (CHSSizeof ide _) = showString "sizeof " . showCHSIdent ide showCHSHook (CHSEnum ide oalias trans oprefix derive _) = showString "enum " . showIdAlias ide oalias . showCHSTrans trans . showPrefix oprefix True . if null derive then id else showString $ "deriving (" ++ concat (intersperse ", " (map identToLexeme derive)) ++ ") " showCHSHook (CHSCall isPure isUns isNol ide oalias _) = showString "call " . (if isPure then showString "pure " else id) . (if isUns then showString "unsafe " else id) . (if isNol then showString "nolock " else id) . showIdAlias ide oalias showCHSHook (CHSFun isPure isUns isNol ide oalias octxt parms parm _) = showString "fun " . (if isPure then showString "pure " else id) . (if isUns then showString "unsafe " else id) . (if isNol then showString "nolock " else id) . showIdAlias ide oalias . (case octxt of Nothing -> showChar ' ' Just ctxtStr -> showString ctxtStr . showString " => ") . showString "{" . foldr (.) id (intersperse (showString ", ") (map showCHSParm parms)) . showString "} -> " . showCHSParm parm showCHSHook (CHSField acc path _) = (case acc of CHSGet -> showString "get " CHSSet -> showString "set ") . showCHSAPath path showCHSHook (CHSPointer star ide oalias ptrType isNewtype oRefType _) = showString "pointer " . (if star then showString "*" else showString "") . showIdAlias ide oalias . (case ptrType of CHSForeignPtr -> showString " foreign" CHSStablePtr -> showString " stable" _ -> showString "") . (case (isNewtype, oRefType) of (True , _ ) -> showString " newtype" (False, Just ide) -> showString " -> " . showCHSIdent ide (False, Nothing ) -> showString "") showCHSHook (CHSClass oclassIde classIde typeIde _) = showString "class " . (case oclassIde of Nothing -> showString "" Just classIde -> showCHSIdent classIde . showString " => ") . showCHSIdent classIde . showString " " . showCHSIdent typeIde showPrefix :: Maybe String -> Bool -> ShowS showPrefix Nothing _ = showString "" showPrefix (Just prefix) withWith = maybeWith . showString "prefix = " . showString prefix . showString " " where maybeWith = if withWith then showString "with " else id showIdAlias :: Ident -> Maybe Ident -> ShowS showIdAlias ide oalias = showCHSIdent ide . (case oalias of Nothing -> id Just ide -> showString " as " . showCHSIdent ide) showCHSParm :: CHSParm -> ShowS showCHSParm (CHSParm oimMarsh hsTyStr twoCVals oomMarsh _) = showOMarsh oimMarsh . showChar ' ' . showHsVerb hsTyStr . (if twoCVals then showChar '&' else id) . showChar ' ' . showOMarsh oomMarsh where showOMarsh Nothing = id showOMarsh (Just (ide, argKind)) = showCHSIdent ide . (case argKind of CHSValArg -> id CHSIOArg -> showString "*" CHSVoidArg -> showString "-") -- showHsVerb str = showChar '`' . showString str . showChar '\'' showCHSTrans :: CHSTrans -> ShowS showCHSTrans (CHSTrans _2Case assocs) = showString "{" . (if _2Case then showString ("underscoreToCase" ++ maybeComma) else id) . foldr (.) id (intersperse (showString ", ") (map showAssoc assocs)) . showString "}" where maybeComma = if null assocs then "" else ", " -- showAssoc (ide1, ide2) = showCHSIdent ide1 . showString " as " . showCHSIdent ide2 showCHSAPath :: CHSAPath -> ShowS showCHSAPath (CHSRoot ide) = showCHSIdent ide showCHSAPath (CHSDeref path _) = showString "* " . showCHSAPath path showCHSAPath (CHSRef (CHSDeref path _) ide) = showCHSAPath path . showString "->" . showCHSIdent ide showCHSAPath (CHSRef path ide) = showCHSAPath path . showString "." . showCHSIdent ide showCHSIdent :: Ident -> ShowS showCHSIdent = showString . identToLexeme -- load and dump a CHI file -- ------------------------ chisuffix :: String chisuffix = ".chi" versionPrefix :: String versionPrefix = "C->Haskell Interface Version " -- replace all import names with the content of the CHI file loadAllCHI :: CHSModule -> CST s CHSModule loadAllCHI (CHSModule frags) = do let checkFrag (CHSHook (CHSImport qual name fName pos)) = do chi <- loadCHI fName return (CHSHook (CHSImport qual name chi pos)) checkFrag h = return h frags' <- mapM checkFrag frags return (CHSModule frags') -- load a CHI file (EXPORTED) -- -- * the file suffix is automagically appended -- -- * any error raises a syntax exception (see below) -- -- * the version of the .chi file is checked against the version of the current -- executable; they must match in the major and minor version -- loadCHI :: FilePath -> CST s String loadCHI fname = do -- search for .chi files -- paths <- getSwitch chiPathSB let fullnames = [path ++ '/':fname ++ chisuffix | path <- paths] fullname <- findFirst fullnames (fatal $ fname++chisuffix++" not found in:\n"++ unlines paths) -- read file -- traceInfoRead fullname contents <- readFileCIO fullname -- parse -- traceInfoVersion let ls = lines contents when (null ls) $ errorCHICorrupt fname let versline:chi = ls prefixLen = length versionPrefix when (length versline < prefixLen || take prefixLen versline /= versionPrefix) $ errorCHICorrupt fname let versline' = drop prefixLen versline (major, minor) <- case majorMinor versline' of Nothing -> errorCHICorrupt fname Just majMin -> return majMin (version, _, _) <- getId let Just (myMajor, myMinor) = majorMinor version when (major /= myMajor || minor /= myMinor) $ errorCHIVersion fname (major ++ "." ++ minor) (myMajor ++ "." ++ myMinor) -- finalize -- traceInfoOK return $ concat chi where traceInfoRead fname = putTraceStr tracePhasesSW ("Attempting to read file `" ++ fname ++ "'...\n") traceInfoVersion = putTraceStr tracePhasesSW ("...checking version `" ++ fname ++ "'...\n") traceInfoOK = putTraceStr tracePhasesSW ("...successfully loaded `" ++ fname ++ "'.\n") findFirst [] err = err findFirst (p:aths) err = do e <- doesFileExistCIO p if e then return p else findFirst aths err -- given a file name (no suffix) and a CHI file, the information is printed -- into that file (EXPORTED) -- -- * the correct suffix will automagically be appended -- dumpCHI :: String -> String -> CST s () dumpCHI fname contents = do (version, _, _) <- getId writeFileCIO (fname ++ chisuffix) $ versionPrefix ++ version ++ "\n" ++ contents -- extract major and minor number from a version string -- majorMinor :: String -> Maybe (String, String) majorMinor vers = let (major, rest) = break (== '.') vers (minor, _ ) = break (== '.') . tail $ rest in if null rest then Nothing else Just (major, minor) -- parsing a CHS token stream -- -------------------------- syntaxExc :: String syntaxExc = "syntax" -- alternative action in case of a syntax exception -- ifError :: CST s a -> CST s a -> CST s a ifError action handler = action `catchExc` (syntaxExc, const handler) -- raise syntax error exception -- raiseSyntaxError :: CST s a raiseSyntaxError = throwExc syntaxExc "syntax error" -- parse a complete module -- -- * errors are entered into the compiler state -- parseCHSModule :: Position -> String -> CST s CHSModule parseCHSModule pos cs = do toks <- lexCHS cs pos frags <- parseFrags toks return (CHSModule frags) -- parsing of code fragments -- -- * in case of an error, all tokens that are neither Haskell nor control -- tokens are skipped; afterwards parsing continues -- -- * when encountering inline-C code we scan forward over all inline-C and -- control tokens to avoid turning the control tokens within a sequence of -- inline-C into Haskell fragments -- parseFrags :: [CHSToken] -> CST s [CHSFrag] parseFrags toks = do parseFrags0 toks `ifError` contFrags toks where parseFrags0 :: [CHSToken] -> CST s [CHSFrag] parseFrags0 [] = return [] parseFrags0 (CHSTokHaskell pos s:toks) = do frags <- parseFrags toks return $ CHSVerb s pos : frags parseFrags0 (CHSTokCtrl pos c:toks) = do frags <- parseFrags toks return $ CHSVerb [c] pos : frags parseFrags0 (CHSTokCPP pos s:toks) = do frags <- parseFrags toks return $ CHSCPP s pos : frags parseFrags0 (CHSTokLine pos :toks) = do frags <- parseFrags toks return $ CHSLine pos : frags parseFrags0 (CHSTokC pos s:toks) = parseC pos s toks parseFrags0 (CHSTokImport pos :toks) = parseImport pos toks parseFrags0 (CHSTokContext pos :toks) = parseContext pos toks parseFrags0 (CHSTokType pos :toks) = parseType pos toks parseFrags0 (CHSTokSizeof pos :toks) = parseSizeof pos toks parseFrags0 (CHSTokEnum pos :toks) = parseEnum pos toks parseFrags0 (CHSTokCall pos :toks) = parseCall pos toks parseFrags0 (CHSTokFun pos :toks) = parseFun pos toks parseFrags0 (CHSTokGet pos :toks) = parseField pos CHSGet toks parseFrags0 (CHSTokSet pos :toks) = parseField pos CHSSet toks parseFrags0 (CHSTokClass pos :toks) = parseClass pos toks parseFrags0 (CHSTokPointer pos :toks) = parsePointer pos toks parseFrags0 (CHSTokPragma pos :toks) = parsePragma pos toks parseFrags0 toks = syntaxError toks -- -- skip to next Haskell or control token -- contFrags [] = return [] contFrags toks@(CHSTokHaskell _ _:_ ) = parseFrags toks contFrags toks@(CHSTokCtrl _ _:_ ) = parseFrags toks contFrags (_ :toks) = contFrags toks parseC :: Position -> String -> [CHSToken] -> CST s [CHSFrag] parseC pos s toks = do frags <- collectCtrlAndC toks return $ CHSC s pos : frags where collectCtrlAndC (CHSTokCtrl pos c:toks) = do frags <- collectCtrlAndC toks return $ CHSC [c] pos : frags collectCtrlAndC (CHSTokC pos s:toks) = do frags <- collectCtrlAndC toks return $ CHSC s pos : frags collectCtrlAndC toks = parseFrags toks parseImport :: Position -> [CHSToken] -> CST s [CHSFrag] parseImport pos toks = do (qual, modid, toks') <- case toks of CHSTokIdent _ ide :toks -> let (ide', toks') = rebuildModuleId ide toks in return (False, ide', toks') CHSTokQualif _: CHSTokIdent _ ide:toks -> let (ide', toks') = rebuildModuleId ide toks in return (True , ide', toks') _ -> syntaxError toks let fName = moduleNameToFileName . identToLexeme $ modid toks'' <- parseEndHook toks' frags <- parseFrags toks'' return $ CHSHook (CHSImport qual modid fName pos) : frags -- Qualified module names do not get lexed as a single token so we need to -- reconstruct it from a sequence of identifer and dot tokens. -- rebuildModuleId ide (CHSTokDot _ : CHSTokIdent _ ide' : toks) = let catIdent ide ide' = onlyPosIdent (posOf ide) --FIXME: unpleasent hack (identToLexeme ide ++ '.' : identToLexeme ide') in rebuildModuleId (catIdent ide ide') toks rebuildModuleId ide toks = (ide, toks) moduleNameToFileName :: String -> FilePath moduleNameToFileName = map dotToSlash where dotToSlash '.' = '/' dotToSlash c = c parseContext :: Position -> [CHSToken] -> CST s [CHSFrag] parseContext pos toks = do (olib , toks ) <- parseOptLib toks (opref , toks) <- parseOptPrefix False toks (olock , toks) <- parseOptLock toks toks <- parseEndHook toks frags <- parseFrags toks let frag = CHSContext olib opref olock pos return $ CHSHook frag : frags parseType :: Position -> [CHSToken] -> CST s [CHSFrag] parseType pos (CHSTokIdent _ ide:toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSType ide pos) : frags parseType _ toks = syntaxError toks parseSizeof :: Position -> [CHSToken] -> CST s [CHSFrag] parseSizeof pos (CHSTokIdent _ ide:toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSSizeof ide pos) : frags parseSizeof _ toks = syntaxError toks parseEnum :: Position -> [CHSToken] -> CST s [CHSFrag] parseEnum pos (CHSTokIdent _ ide:toks) = do (oalias, toks' ) <- parseOptAs ide True toks (trans , toks'') <- parseTrans toks' (oprefix, toks''') <- parseOptPrefix True toks'' (derive, toks'''') <- parseDerive toks''' toks''''' <- parseEndHook toks'''' frags <- parseFrags toks''''' return $ CHSHook (CHSEnum ide (norm oalias) trans oprefix derive pos) : frags where norm Nothing = Nothing norm (Just ide') | ide == ide' = Nothing | otherwise = Just ide' parseEnum _ toks = syntaxError toks parseCall :: Position -> [CHSToken] -> CST s [CHSFrag] parseCall pos toks = do (isPure , toks ) <- parseIsPure toks (isUnsafe, toks ) <- parseIsUnsafe toks (isNolock, toks ) <- parseIsNolock toks (ide , toks ) <- parseIdent toks (oalias , toks ) <- parseOptAs ide False toks toks <- parseEndHook toks frags <- parseFrags toks return $ CHSHook (CHSCall isPure isUnsafe isNolock ide (norm ide oalias) pos) : frags parseFun :: Position -> [CHSToken] -> CST s [CHSFrag] parseFun pos toks = do (isPure , toks' ) <- parseIsPure toks (isUnsafe, toks'2) <- parseIsUnsafe toks' (isNolock, toks'3) <- parseIsNolock toks'2 (ide , toks'4) <- parseIdent toks'3 (oalias , toks'5) <- parseOptAs ide False toks'4 (octxt , toks'6) <- parseOptContext toks'5 (parms , toks'7) <- parseParms toks'6 (parm , toks'8) <- parseParm toks'7 toks'9 <- parseEndHook toks'8 frags <- parseFrags toks'9 return $ CHSHook (CHSFun isPure isUnsafe isNolock ide (norm ide oalias) octxt parms parm pos) : frags where parseOptContext (CHSTokHSVerb _ ctxt:CHSTokDArrow _:toks) = return (Just ctxt, toks) parseOptContext toks = return (Nothing , toks) -- parseParms (CHSTokLBrace _:CHSTokRBrace _:CHSTokArrow _:toks) = return ([], toks) parseParms (CHSTokLBrace _ :toks) = parseParms' (CHSTokComma nopos:toks) parseParms toks = syntaxError toks -- parseParms' (CHSTokRBrace _:CHSTokArrow _:toks) = return ([], toks) parseParms' (CHSTokComma _ :toks) = do (parm , toks' ) <- parseParm toks (parms, toks'') <- parseParms' toks' return (parm:parms, toks'') parseParms' (CHSTokRBrace _ :toks) = syntaxError toks -- gives better error messages parseParms' toks = syntaxError toks parseIsPure :: [CHSToken] -> CST s (Bool, [CHSToken]) parseIsPure (CHSTokPure _:toks) = return (True , toks) parseIsPure (CHSTokFun _:toks) = return (True , toks) -- backwards compat. parseIsPure toks = return (False, toks) -- FIXME: eventually, remove `fun'; it's currently deprecated parseIsUnsafe :: [CHSToken] -> CST s (Bool, [CHSToken]) parseIsUnsafe (CHSTokUnsafe _:toks) = return (True , toks) parseIsUnsafe toks = return (False, toks) parseIsNolock :: [CHSToken] -> CST s (Bool, [CHSToken]) parseIsNolock (CHSTokNolock _:toks) = return (True , toks) parseIsNolock toks = return (False, toks) norm :: Ident -> Maybe Ident -> Maybe Ident norm ide Nothing = Nothing norm ide (Just ide') | ide == ide' = Nothing | otherwise = Just ide' parseParm :: [CHSToken] -> CST s (CHSParm, [CHSToken]) parseParm toks = do (oimMarsh, toks' ) <- parseOptMarsh toks (hsTyStr, twoCVals, pos, toks'2) <- case toks' of (CHSTokHSVerb pos hsTyStr:CHSTokAmp _:toks'2) -> return (hsTyStr, True , pos, toks'2) (CHSTokHSVerb pos hsTyStr :toks'2) -> return (hsTyStr, False, pos, toks'2) toks -> syntaxError toks (oomMarsh, toks'3) <- parseOptMarsh toks'2 return (CHSParm oimMarsh hsTyStr twoCVals oomMarsh pos, toks'3) where parseOptMarsh :: [CHSToken] -> CST s (Maybe (Ident, CHSArg), [CHSToken]) parseOptMarsh (CHSTokIdent _ ide:CHSTokStar _ :toks) = return (Just (ide, CHSIOArg) , toks) parseOptMarsh (CHSTokIdent _ ide:CHSTokMinus _:toks) = return (Just (ide, CHSVoidArg), toks) parseOptMarsh (CHSTokIdent _ ide :toks) = return (Just (ide, CHSValArg) , toks) parseOptMarsh toks = return (Nothing, toks) parseField :: Position -> CHSAccess -> [CHSToken] -> CST s [CHSFrag] parseField pos access toks = do (path, toks') <- parsePath toks frags <- parseFrags toks' return $ CHSHook (CHSField access path pos) : frags parsePointer :: Position -> [CHSToken] -> CST s [CHSFrag] parsePointer pos toks = do (isStar, ide, toks') <- case toks of CHSTokStar _:CHSTokIdent _ ide:toks' -> return (True , ide, toks') CHSTokIdent _ ide :toks' -> return (False, ide, toks') _ -> syntaxError toks (oalias , toks'2) <- parseOptAs ide True toks' (ptrType, toks'3) <- parsePtrType toks'2 let (isNewtype, oRefType, toks'4) = case toks'3 of CHSTokNewtype _ :toks' -> (True , Nothing , toks' ) CHSTokArrow _:CHSTokIdent _ ide:toks' -> (False, Just ide, toks' ) _ -> (False, Nothing , toks'3) toks'5 <- parseEndHook toks'4 frags <- parseFrags toks'5 return $ CHSHook (CHSPointer isStar ide (norm ide oalias) ptrType isNewtype oRefType pos) : frags where parsePtrType :: [CHSToken] -> CST s (CHSPtrType, [CHSToken]) parsePtrType (CHSTokForeign _:toks) = return (CHSForeignPtr, toks) parsePtrType (CHSTokStable _ :toks) = return (CHSStablePtr, toks) parsePtrType toks = return (CHSPtr, toks) norm ide Nothing = Nothing norm ide (Just ide') | ide == ide' = Nothing | otherwise = Just ide' parsePragma :: Position -> [CHSToken] -> CST s [CHSFrag] parsePragma pos toks = do let parseExts exts (CHSTokIdent _ ide:CHSTokComma _:toks) = parseExts (identToLexeme ide:exts) toks parseExts exts (CHSTokIdent _ ide:CHSTokPragEnd _:toks) = return (reverse (identToLexeme ide:exts), toks) parseExts exts toks = syntaxError toks (exts, toks) <- parseExts [] toks frags <- parseFrags toks return (CHSLang exts pos : frags) parseClass :: Position -> [CHSToken] -> CST s [CHSFrag] parseClass pos (CHSTokIdent _ sclassIde: CHSTokDArrow _ : CHSTokIdent _ classIde : CHSTokIdent _ typeIde : toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSClass (Just sclassIde) classIde typeIde pos) : frags parseClass pos (CHSTokIdent _ classIde : CHSTokIdent _ typeIde : toks) = do toks' <- parseEndHook toks frags <- parseFrags toks' return $ CHSHook (CHSClass Nothing classIde typeIde pos) : frags parseClass _ toks = syntaxError toks parseOptLib :: [CHSToken] -> CST s (Maybe String, [CHSToken]) parseOptLib (CHSTokLib _ : CHSTokEqual _ : CHSTokString _ str: toks) = return (Just str, toks) parseOptLib (CHSTokLib _:toks ) = syntaxError toks parseOptLib toks = return (Nothing, toks) parseOptLock :: [CHSToken] -> CST s (Maybe String, [CHSToken]) parseOptLock (CHSTokLock _ : CHSTokEqual _ : CHSTokString _ str: toks) = return (Just str, toks) parseOptLock (CHSTokLock _:toks ) = syntaxError toks parseOptLock toks = return (Nothing, toks) parseOptPrefix :: Bool -> [CHSToken] -> CST s (Maybe String, [CHSToken]) parseOptPrefix False (CHSTokPrefix _ : CHSTokEqual _ : CHSTokString _ str: toks) = return (Just str, toks) parseOptPrefix True (CHSTokWith _ : CHSTokPrefix _ : CHSTokEqual _ : CHSTokString _ str: toks) = return (Just str, toks) parseOptPrefix _ (CHSTokWith _:toks) = syntaxError toks parseOptPrefix _ (CHSTokPrefix _:toks) = syntaxError toks parseOptPrefix _ toks = return (Nothing, toks) -- first argument is the identifier that is to be used when `^' is given and -- the second indicates whether the first character has to be upper case -- parseOptAs :: Ident -> Bool -> [CHSToken] -> CST s (Maybe Ident, [CHSToken]) parseOptAs _ _ (CHSTokAs _:CHSTokIdent _ ide:toks) = return (Just ide, toks) parseOptAs ide upper (CHSTokAs _:CHSTokHat pos :toks) = return (Just $ underscoreToCase ide upper pos, toks) parseOptAs _ _ (CHSTokAs _ :toks) = syntaxError toks parseOptAs _ _ toks = return (Nothing, toks) -- convert C style identifier to Haskell style identifier -- underscoreToCase :: Ident -> Bool -> Position -> Ident underscoreToCase ide upper pos = let lexeme = identToLexeme ide ps = filter (not . null) . parts $ lexeme in onlyPosIdent pos . adjustHead . concat . map adjustCase $ ps where parts s = let (l, s') = break (== '_') s in l : case s' of [] -> [] (_:s'') -> parts s'' -- adjustCase (c:cs) = toUpper c : map toLower cs -- adjustHead "" = "" adjustHead (c:cs) = if upper then toUpper c : cs else toLower c:cs -- this is disambiguated and left factored -- parsePath :: [CHSToken] -> CST s (CHSAPath, [CHSToken]) parsePath (CHSTokStar pos:toks) = do (path, toks') <- parsePath toks return (CHSDeref path pos, toks') parsePath (CHSTokIdent _ ide:toks) = do (pathWithHole, toks') <- parsePath' toks return (pathWithHole (CHSRoot ide), toks') parsePath toks = syntaxError toks -- `s->m' is represented by `(*s).m' in the tree -- parsePath' :: [CHSToken] -> CST s (CHSAPath -> CHSAPath, [CHSToken]) parsePath' (CHSTokDot _:CHSTokIdent _ ide:toks) = do (pathWithHole, toks') <- parsePath' toks return (pathWithHole . (\hole -> CHSRef hole ide), toks') parsePath' (CHSTokDot _:toks) = syntaxError toks parsePath' (CHSTokArrow pos:CHSTokIdent _ ide:toks) = do (pathWithHole, toks') <- parsePath' toks return (pathWithHole . (\hole -> CHSRef (CHSDeref hole pos) ide), toks') parsePath' (CHSTokArrow _:toks) = syntaxError toks parsePath' toks = do toks' <- parseEndHook toks return (id, toks') parseTrans :: [CHSToken] -> CST s (CHSTrans, [CHSToken]) parseTrans (CHSTokLBrace _:toks) = do (_2Case, toks' ) <- parse_2Case toks case toks' of (CHSTokRBrace _:toks'') -> return (CHSTrans _2Case [], toks'') _ -> do -- if there was no `underscoreToCase', we add a comma token to meet -- the invariant of `parseTranss' -- (transs, toks'') <- if _2Case then parseTranss toks' else parseTranss (CHSTokComma nopos:toks') return (CHSTrans _2Case transs, toks'') where parse_2Case (CHSTok_2Case _:toks) = return (True, toks) parse_2Case toks = return (False, toks) -- parseTranss (CHSTokRBrace _:toks) = return ([], toks) parseTranss (CHSTokComma _:toks) = do (assoc, toks' ) <- parseAssoc toks (trans, toks'') <- parseTranss toks' return (assoc:trans, toks'') parseTranss toks = syntaxError toks -- parseAssoc (CHSTokIdent _ ide1:CHSTokAs _:CHSTokIdent _ ide2:toks) = return ((ide1, ide2), toks) parseAssoc (CHSTokIdent _ ide1:CHSTokAs _:toks ) = syntaxError toks parseAssoc (CHSTokIdent _ ide1:toks ) = syntaxError toks parseAssoc toks = syntaxError toks parseTrans toks = syntaxError toks parseDerive :: [CHSToken] -> CST s ([Ident], [CHSToken]) parseDerive (CHSTokDerive _ :CHSTokLParen _:CHSTokRParen _:toks) = return ([], toks) parseDerive (CHSTokDerive _ :CHSTokLParen _:toks) = parseCommaIdent (CHSTokComma nopos:toks) where parseCommaIdent :: [CHSToken] -> CST s ([Ident], [CHSToken]) parseCommaIdent (CHSTokComma _:CHSTokIdent _ ide:toks) = do (ids, tok') <- parseCommaIdent toks return (ide:ids, tok') parseCommaIdent (CHSTokRParen _ :toks) = return ([], toks) parseDerive toks = return ([],toks) parseIdent :: [CHSToken] -> CST s (Ident, [CHSToken]) parseIdent (CHSTokIdent _ ide:toks) = return (ide, toks) parseIdent toks = syntaxError toks parseEndHook :: [CHSToken] -> CST s ([CHSToken]) parseEndHook (CHSTokEndHook _:toks) = return toks parseEndHook toks = syntaxError toks syntaxError :: [CHSToken] -> CST s a syntaxError [] = errorEOF syntaxError (tok:_) = errorIllegal tok errorIllegal :: CHSToken -> CST s a errorIllegal tok = do raiseError (posOf tok) ["Syntax error!", "The phrase `" ++ show tok ++ "' is not allowed \ \here."] raiseSyntaxError errorEOF :: CST s a errorEOF = do raiseError nopos ["Premature end of file!", "The .chs file ends in the middle of a binding hook."] raiseSyntaxError errorCHINotFound :: String -> CST s a errorCHINotFound ide = do raiseError nopos ["Unknown .chi file!", "Cannot find the .chi file for `" ++ ide ++ "'."] raiseSyntaxError errorCHICorrupt :: String -> CST s a errorCHICorrupt ide = do raiseError nopos ["Corrupt .chi file!", "The file `" ++ ide ++ ".chi' is corrupt."] raiseSyntaxError errorCHIVersion :: String -> String -> String -> CST s a errorCHIVersion ide chiVersion myVersion = do raiseError nopos ["Wrong version of .chi file!", "The file `" ++ ide ++ ".chi' is version " ++ chiVersion ++ ", but mine is " ++ myVersion ++ "."] raiseSyntaxError
k0001/gtk2hs
tools/c2hs/chs/CHS.hs
gpl-3.0
49,978
0
22
18,238
12,203
6,261
5,942
876
22
{-# LANGUAGE OverloadedStrings #-} -- Module : Test.AWS.Route53 -- Copyright : (c) 2013-2015 Brendan Hay -- 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 <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Test.AWS.Route53 ( tests , fixtures ) where import Network.AWS.Route53 import Test.AWS.Gen.Route53 import Test.Tasty tests :: [TestTree] tests = [] fixtures :: [TestTree] fixtures = []
fmapfmapfmap/amazonka
amazonka-route53/test/Test/AWS/Route53.hs
mpl-2.0
740
0
5
201
73
50
23
11
1
{-# LANGUAGE CPP #-} module Distribution.Client.Dependency.Modular.Builder (buildTree) where -- Building the search tree. -- -- In this phase, we build a search tree that is too large, i.e, it contains -- invalid solutions. We keep track of the open goals at each point. We -- nondeterministically pick an open goal (via a goal choice node), create -- subtrees according to the index and the available solutions, and extend the -- set of open goals by superficially looking at the dependencies recorded in -- the index. -- -- For each goal, we keep track of all the *reasons* why it is being -- introduced. These are for debugging and error messages, mainly. A little bit -- of care has to be taken due to the way we treat flags. If a package has -- flag-guarded dependencies, we cannot introduce them immediately. Instead, we -- store the entire dependency. import Data.List as L import Data.Map as M import Prelude hiding (sequence, mapM) import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.PSQ (PSQ) import qualified Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.ComponentDeps (Component) -- | The state needed during the build phase of the search tree. data BuildState = BS { index :: Index, -- ^ information about packages and their dependencies rdeps :: RevDepMap, -- ^ set of all package goals, completed and open, with reverse dependencies open :: PSQ (OpenGoal ()) (), -- ^ set of still open goals (flag and package goals) next :: BuildType, -- ^ kind of node to generate next qualifyOptions :: QualifyOptions -- ^ qualification options } -- | Extend the set of open goals with the new goals listed. -- -- We also adjust the map of overall goals, and keep track of the -- reverse dependencies of each of the goals. extendOpen :: QPN -> [OpenGoal Component] -> BuildState -> BuildState extendOpen qpn' gs s@(BS { rdeps = gs', open = o' }) = go gs' o' gs where go :: RevDepMap -> PSQ (OpenGoal ()) () -> [OpenGoal Component] -> BuildState go g o [] = s { rdeps = g, open = o } go g o (ng@(OpenGoal (Flagged _ _ _ _) _gr) : ngs) = go g (cons' ng () o) ngs -- Note: for 'Flagged' goals, we always insert, so later additions win. -- This is important, because in general, if a goal is inserted twice, -- the later addition will have better dependency information. go g o (ng@(OpenGoal (Stanza _ _ ) _gr) : ngs) = go g (cons' ng () o) ngs go g o (ng@(OpenGoal (Simple (Dep qpn _) c) _gr) : ngs) | qpn == qpn' = go g o ngs -- we ignore self-dependencies at this point; TODO: more care may be needed | qpn `M.member` g = go (M.adjust ((c, qpn'):) qpn g) o ngs | otherwise = go (M.insert qpn [(c, qpn')] g) (cons' ng () o) ngs -- code above is correct; insert/adjust have different arg order go g o ( (OpenGoal (Simple (Ext _ext ) _) _gr) : ngs) = go g o ngs go g o ( (OpenGoal (Simple (Lang _lang)_) _gr) : ngs) = go g o ngs go g o ( (OpenGoal (Simple (Pkg _pn _vr)_) _gr) : ngs)= go g o ngs cons' = P.cons . forgetCompOpenGoal -- | Given the current scope, qualify all the package names in the given set of -- dependencies and then extend the set of open goals accordingly. scopedExtendOpen :: QPN -> I -> QGoalReasonChain -> FlaggedDeps Component PN -> FlagInfo -> BuildState -> BuildState scopedExtendOpen qpn i gr fdeps fdefs s = extendOpen qpn gs s where -- Qualify all package names qfdeps = qualifyDeps (qualifyOptions s) qpn fdeps -- Introduce all package flags qfdefs = L.map (\ (fn, b) -> Flagged (FN (PI qpn i) fn) b [] []) $ M.toList fdefs -- Combine new package and flag goals gs = L.map (flip OpenGoal gr) (qfdefs ++ qfdeps) -- NOTE: -- -- In the expression @qfdefs ++ qfdeps@ above, flags occur potentially -- multiple times, both via the flag declaration and via dependencies. -- The order is potentially important, because the occurrences via -- dependencies may record flag-dependency information. After a number -- of bugs involving computing this information incorrectly, however, -- we're currently not using carefully computed inter-flag dependencies -- anymore, but instead use 'simplifyVar' when computing conflict sets -- to map all flags of one package to a single flag for conflict set -- purposes, thereby treating them all as interdependent. -- -- If we ever move to a more clever algorithm again, then the line above -- needs to be looked at very carefully, and probably be replaced by -- more systematically computed flag dependency information. -- | Datatype that encodes what to build next data BuildType = Goals -- ^ build a goal choice node | OneGoal (OpenGoal ()) -- ^ build a node for this goal | Instance QPN I PInfo QGoalReasonChain -- ^ build a tree for a concrete instance deriving Show build :: BuildState -> Tree QGoalReasonChain build = ana go where go :: BuildState -> TreeF QGoalReasonChain BuildState -- If we have a choice between many goals, we just record the choice in -- the tree. We select each open goal in turn, and before we descend, remove -- it from the queue of open goals. go bs@(BS { rdeps = rds, open = gs, next = Goals }) | P.null gs = DoneF rds | otherwise = GoalChoiceF (P.mapWithKey (\ g (_sc, gs') -> bs { next = OneGoal g, open = gs' }) (P.splits gs)) -- If we have already picked a goal, then the choice depends on the kind -- of goal. -- -- For a package, we look up the instances available in the global info, -- and then handle each instance in turn. go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Ext _ ) _) _ ) }) = error "Distribution.Client.Dependency.Modular.Builder: build.go called with Ext goal" go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Lang _ ) _) _ ) }) = error "Distribution.Client.Dependency.Modular.Builder: build.go called with Lang goal" go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Pkg _ _ ) _) _ ) }) = error "Distribution.Client.Dependency.Modular.Builder: build.go called with Pkg goal" go bs@(BS { index = idx, next = OneGoal (OpenGoal (Simple (Dep qpn@(Q _ pn) _) _) gr) }) = case M.lookup pn idx of Nothing -> FailF (toConflictSet (Goal (P qpn) gr)) (BuildFailureNotInIndex pn) Just pis -> PChoiceF qpn gr (P.fromList (L.map (\ (i, info) -> (POption i Nothing, bs { next = Instance qpn i info gr })) (M.toList pis))) -- TODO: data structure conversion is rather ugly here -- For a flag, we create only two subtrees, and we create them in the order -- that is indicated by the flag default. -- -- TODO: Should we include the flag default in the tree? go bs@(BS { next = OneGoal (OpenGoal (Flagged qfn@(FN (PI qpn _) _) (FInfo b m w) t f) gr) }) = FChoiceF qfn gr (w || trivial) m (P.fromList (reorder b [(True, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn True : gr)) t) bs) { next = Goals }), (False, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn False : gr)) f) bs) { next = Goals })])) where reorder True = id reorder False = reverse trivial = L.null t && L.null f -- For a stanza, we also create only two subtrees. The order is initially -- False, True. This can be changed later by constraints (force enabling -- the stanza by replacing the False branch with failure) or preferences -- (try enabling the stanza if possible by moving the True branch first). go bs@(BS { next = OneGoal (OpenGoal (Stanza qsn@(SN (PI qpn _) _) t) gr) }) = SChoiceF qsn gr trivial (P.fromList [(False, bs { next = Goals }), (True, (extendOpen qpn (L.map (flip OpenGoal (SDependency qsn : gr)) t) bs) { next = Goals })]) where trivial = L.null t -- For a particular instance, we change the state: we update the scope, -- and furthermore we update the set of goals. -- -- TODO: We could inline this above. go bs@(BS { next = Instance qpn i (PInfo fdeps fdefs _) gr }) = go ((scopedExtendOpen qpn i (PDependency (PI qpn i) : gr) fdeps fdefs bs) { next = Goals }) -- | Interface to the tree builder. Just takes an index and a list of package names, -- and computes the initial state and then the tree from there. buildTree :: Index -> Bool -> [PN] -> Tree QGoalReasonChain buildTree idx ind igs = build BS { index = idx , rdeps = M.fromList (L.map (\ qpn -> (qpn, [])) qpns) , open = P.fromList (L.map (\ qpn -> (topLevelGoal qpn, ())) qpns) , next = Goals , qualifyOptions = defaultQualifyOptions idx } where topLevelGoal qpn = OpenGoal (Simple (Dep qpn (Constrained [])) ()) [UserGoal] qpns | ind = makeIndependent igs | otherwise = L.map (Q None) igs
garetxe/cabal
cabal-install/Distribution/Client/Dependency/Modular/Builder.hs
bsd-3-clause
9,685
0
23
2,643
2,253
1,236
1,017
89
10
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} module SafeCounter ( startCounter, getCount, getCountAsync, incCount, resetCount, wait, waitTimeout, Fetch(..), Increment(..), Reset(..) ) where import Control.Distributed.Process hiding (call, say) import Control.Distributed.Process.Extras import Control.Distributed.Process.Async import Control.Distributed.Process.ManagedProcess ( ProcessDefinition(..) , InitHandler , InitResult(..) , defaultProcess , condition ) import qualified Control.Distributed.Process.ManagedProcess as ManagedProcess (serve) import Control.Distributed.Process.ManagedProcess.Client import Control.Distributed.Process.ManagedProcess.Server.Restricted import Control.Distributed.Process.Extras.Time import Control.Distributed.Process.Serializable import Data.Binary import Data.Typeable (Typeable) import GHC.Generics -------------------------------------------------------------------------------- -- Types -- -------------------------------------------------------------------------------- data Increment = Increment deriving (Show, Typeable, Generic) instance Binary Increment where data Fetch = Fetch deriving (Show, Typeable, Generic) instance Binary Fetch where data Reset = Reset deriving (Show, Typeable, Generic) instance Binary Reset where -------------------------------------------------------------------------------- -- API -- -------------------------------------------------------------------------------- -- | Increment count incCount :: ProcessId -> Process Int incCount sid = call sid Increment -- | Get the current count getCount :: ProcessId -> Process Int getCount sid = call sid Fetch -- | Get the current count asynchronously getCountAsync :: ProcessId -> Process (Async Int) getCountAsync sid = callAsync sid Fetch -- | Reset the current count resetCount :: ProcessId -> Process () resetCount sid = cast sid Reset -- | Start a counter server startCounter :: Int -> Process ProcessId startCounter startCount = let server = serverDefinition in spawnLocal $ ManagedProcess.serve startCount init' server where init' :: InitHandler Int Int init' count = return $ InitOk count Infinity -------------------------------------------------------------------------------- -- Implementation -- -------------------------------------------------------------------------------- serverDefinition :: ProcessDefinition Int serverDefinition = defaultProcess { apiHandlers = [ handleCallIf (condition (\count Increment -> count >= 10)) -- invariant (\Increment -> halt :: RestrictedProcess Int (Result Int)) , handleCall handleIncrement , handleCall (\Fetch -> getState >>= reply) , handleCast (\Reset -> putState (0 :: Int) >> continue) ] } :: ProcessDefinition Int halt :: forall s r . Serializable r => RestrictedProcess s (Result r) halt = haltNoReply (ExitOther "Count > 10") handleIncrement :: Increment -> RestrictedProcess Int (Result Int) handleIncrement _ = modifyState (+1) >> getState >>= reply
qnikst/distributed-process-client-server
tests/SafeCounter.hs
bsd-3-clause
3,425
0
13
701
681
391
290
69
1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.Ex.Commands.BufferDelete -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable module Yi.Keymap.Vim.Ex.Commands.BufferDelete (parse) where import Control.Applicative (Alternative ((<|>))) import Control.Monad (void) import Data.Text () import qualified Data.Attoparsec.Text as P (string, try) import Yi.Editor (closeBufferAndWindowE) import Yi.Keymap (Action (EditorA)) import Yi.Keymap.Vim.Common (EventString) import qualified Yi.Keymap.Vim.Ex.Commands.Common as Common (parse, pureExCommand) import Yi.Keymap.Vim.Ex.Types (ExCommand (cmdAction, cmdShow)) parse :: EventString -> Maybe ExCommand parse = Common.parse $ do void $ P.try ( P.string "bdelete") <|> P.try ( P.string "bdel") <|> P.try (P.string "bd") return $ Common.pureExCommand { cmdShow = "bdelete" , cmdAction = EditorA closeBufferAndWindowE }
siddhanathan/yi
yi-keymap-vim/src/Yi/Keymap/Vim/Ex/Commands/BufferDelete.hs
gpl-2.0
1,233
0
14
366
252
156
96
18
1
module Data.Graph.Inductive.Monad (GraphM(..), ufoldM, nodesM, edgesM, newNodesM, delNodeM, delNodesM, mkUGraphM, contextM, labM) where { import Data.Graph.Inductive.Graph; class (Monad m) => GraphM m gr where { emptyM :: m (gr a b); isEmptyM :: m (gr a b) -> m Bool; matchM :: Node -> m (gr a b) -> m (Decomp gr a b); mkGraphM :: [LNode a] -> [LEdge b] -> m (gr a b); labNodesM :: m (gr a b) -> m [LNode a]; matchAnyM :: m (gr a b) -> m (GDecomp gr a b); noNodesM :: m (gr a b) -> m Int; nodeRangeM :: m (gr a b) -> m (Node, Node); labEdgesM :: m (gr a b) -> m [LEdge b]; matchAnyM g = do { vs <- labNodesM g; case vs of { [] -> error "Match Exception, Empty Graph"; (v, _) : _ -> do { (Just c, g') <- matchM v g; return (c, g')}}}; noNodesM = labNodesM >>. length; nodeRangeM g = do { vs <- labNodesM g; let { vs' = map fst vs}; return (minimum vs', maximum vs')}; labEdgesM = ufoldM (\ (p, v, _, s) -> (((map (i v) p) ++ (map (o v) s)) ++)) [] where { o v = \ (l, w) -> (v, w, l); i v = \ (l, w) -> (w, v, l)}}; (>>.) :: (Monad m) => (m a -> m b) -> (b -> c) -> m a -> m c; f >>. g = (>>= return . g) . f; ufoldM :: (GraphM m gr) => (Context a b -> c -> c) -> c -> m (gr a b) -> m c; ufoldM f u g = do { b <- isEmptyM g; if b then return u else do { (c, g') <- matchAnyM g; x <- ufoldM f u (return g'); return (f c x)}}; nodesM :: (GraphM m gr) => m (gr a b) -> m [Node]; nodesM = labNodesM >>. map fst; edgesM :: (GraphM m gr) => m (gr a b) -> m [Edge]; edgesM = labEdgesM >>. map (\ (v, w, _) -> (v, w)); newNodesM :: (GraphM m gr) => Int -> m (gr a b) -> m [Node]; newNodesM i g = do { (_, n) <- nodeRangeM g; return [n + 1 .. n + i]}; delNodeM :: (GraphM m gr) => Node -> m (gr a b) -> m (gr a b); delNodeM v = delNodesM [v]; delNodesM :: (GraphM m gr) => [Node] -> m (gr a b) -> m (gr a b); delNodesM [] g = g; delNodesM (v : vs) g = do { (_, g') <- matchM v g; delNodesM vs (return g')}; mkUGraphM :: (GraphM m gr) => [Node] -> [Edge] -> m (gr () ()); mkUGraphM vs es = mkGraphM (labUNodes vs) (labUEdges es); labUEdges = map (\ (v, w) -> (v, w, ())); labUNodes = map (\ v -> (v, ())); onMatch :: (GraphM m gr) => (Context a b -> c) -> c -> m (gr a b) -> Node -> m c; onMatch f u g v = do { (x, _) <- matchM v g; return (case x of { Nothing -> u; Just c -> f c})}; contextM :: (GraphM m gr) => m (gr a b) -> Node -> m (Context a b); contextM g v = onMatch id (error ("Match Exception, Node: " ++ show v)) g v; labM :: (GraphM m gr) => m (gr a b) -> Node -> m (Maybe a); labM = onMatch (Just . lab') Nothing}
ckaestne/CIDE
other/CaseStudies/fgl/CIDEfgl/Data/Graph/Inductive/Monad.hs
gpl-3.0
3,391
0
16
1,471
1,669
896
773
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 2000 FunDeps - functional dependencies It's better to read it as: "if we know these, then we're going to know these" -} {-# LANGUAGE CPP #-} module FunDeps ( FunDepEqn(..), pprEquation, improveFromInstEnv, improveFromAnother, checkInstCoverage, checkFunDeps, pprFundeps ) where #include "HsVersions.h" import Name import Var import Class import Type import TcType( transSuperClasses ) import Unify import InstEnv import VarSet import VarEnv import Outputable import ErrUtils( Validity(..), allValid ) import SrcLoc import Util import Pair ( Pair(..) ) import Data.List ( nubBy ) import Data.Maybe import Data.Foldable ( fold ) {- ************************************************************************ * * \subsection{Generate equations from functional dependencies} * * ************************************************************************ Each functional dependency with one variable in the RHS is responsible for generating a single equality. For instance: class C a b | a -> b The constraints ([Wanted] C Int Bool) and [Wanted] C Int alpha will generate the folloing FunDepEqn FDEqn { fd_qtvs = [] , fd_eqs = [Pair Bool alpha] , fd_pred1 = C Int Bool , fd_pred2 = C Int alpha , fd_loc = ... } However notice that a functional dependency may have more than one variable in the RHS which will create more than one pair of types in fd_eqs. Example: class C a b c | a -> b c [Wanted] C Int alpha alpha [Wanted] C Int Bool beta Will generate: FDEqn { fd_qtvs = [] , fd_eqs = [Pair Bool alpha, Pair alpha beta] , fd_pred1 = C Int Bool , fd_pred2 = C Int alpha , fd_loc = ... } INVARIANT: Corresponding types aren't already equal That is, there exists at least one non-identity equality in FDEqs. Assume: class C a b c | a -> b c instance C Int x x And: [Wanted] C Int Bool alpha We will /match/ the LHS of fundep equations, producing a matching substitution and create equations for the RHS sides. In our last example we'd have generated: ({x}, [fd1,fd2]) where fd1 = FDEq 1 Bool x fd2 = FDEq 2 alpha x To ``execute'' the equation, make fresh type variable for each tyvar in the set, instantiate the two types with these fresh variables, and then unify or generate a new constraint. In the above example we would generate a new unification variable 'beta' for x and produce the following constraints: [Wanted] (Bool ~ beta) [Wanted] (alpha ~ beta) Notice the subtle difference between the above class declaration and: class C a b c | a -> b, a -> c where we would generate: ({x},[fd1]),({x},[fd2]) This means that the template variable would be instantiated to different unification variables when producing the FD constraints. Finally, the position parameters will help us rewrite the wanted constraint ``on the spot'' -} data FunDepEqn loc = FDEqn { fd_qtvs :: [TyVar] -- Instantiate these type and kind vars -- to fresh unification vars, -- Non-empty only for FunDepEqns arising from instance decls , fd_eqs :: [Pair Type] -- Make these pairs of types equal , fd_pred1 :: PredType -- The FunDepEqn arose from , fd_pred2 :: PredType -- combining these two constraints , fd_loc :: loc } {- Given a bunch of predicates that must hold, such as C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5 improve figures out what extra equations must hold. For example, if we have class C a b | a->b where ... then improve will return [(t1,t2), (t4,t5)] NOTA BENE: * improve does not iterate. It's possible that when we make t1=t2, for example, that will in turn trigger a new equation. This would happen if we also had C t1 t7, C t2 t8 If t1=t2, we also get t7=t8. improve does *not* do this extra step. It relies on the caller doing so. * The equations unify types that are not already equal. So there is no effect iff the result of improve is empty -} instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type -- (instFD fd tvs tys) returns fd instantiated with (tvs -> tys) instFD (ls,rs) tvs tys = (map lookup ls, map lookup rs) where env = zipVarEnv tvs tys lookup tv = lookupVarEnv_NF env tv zipAndComputeFDEqs :: (Type -> Type -> Bool) -- Discard this FDEq if true -> [Type] -> [Type] -> [Pair Type] -- Create a list of (Type,Type) pairs from two lists of types, -- making sure that the types are not already equal zipAndComputeFDEqs discard (ty1:tys1) (ty2:tys2) | discard ty1 ty2 = zipAndComputeFDEqs discard tys1 tys2 | otherwise = Pair ty1 ty2 : zipAndComputeFDEqs discard tys1 tys2 zipAndComputeFDEqs _ _ _ = [] -- Improve a class constraint from another class constraint -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ improveFromAnother :: loc -> PredType -- Template item (usually given, or inert) -> PredType -- Workitem [that can be improved] -> [FunDepEqn loc] -- Post: FDEqs always oriented from the other to the workitem -- Equations have empty quantified variables improveFromAnother loc pred1 pred2 | Just (cls1, tys1) <- getClassPredTys_maybe pred1 , Just (cls2, tys2) <- getClassPredTys_maybe pred2 , tys1 `lengthAtLeast` 2 && cls1 == cls2 = [ FDEqn { fd_qtvs = [], fd_eqs = eqs, fd_pred1 = pred1, fd_pred2 = pred2, fd_loc = loc } | let (cls_tvs, cls_fds) = classTvsFds cls1 , fd <- cls_fds , let (ltys1, rs1) = instFD fd cls_tvs tys1 (ltys2, rs2) = instFD fd cls_tvs tys2 , eqTypes ltys1 ltys2 -- The LHSs match , let eqs = zipAndComputeFDEqs eqType rs1 rs2 , not (null eqs) ] improveFromAnother _ _ _ = [] -- Improve a class constraint from instance declarations -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pprEquation :: FunDepEqn a -> SDoc pprEquation (FDEqn { fd_qtvs = qtvs, fd_eqs = pairs }) = vcat [text "forall" <+> braces (pprWithCommas ppr qtvs), nest 2 (vcat [ ppr t1 <+> text "~" <+> ppr t2 | Pair t1 t2 <- pairs])] improveFromInstEnv :: InstEnvs -> (PredType -> SrcSpan -> loc) -> PredType -> [FunDepEqn loc] -- Needs to be a FunDepEqn because -- of quantified variables -- Post: Equations oriented from the template (matching instance) to the workitem! improveFromInstEnv _inst_env _ pred | not (isClassPred pred) = panic "improveFromInstEnv: not a class predicate" improveFromInstEnv inst_env mk_loc pred | Just (cls, tys) <- getClassPredTys_maybe pred , tys `lengthAtLeast` 2 , let (cls_tvs, cls_fds) = classTvsFds cls instances = classInstances inst_env cls rough_tcs = roughMatchTcs tys = [ FDEqn { fd_qtvs = meta_tvs, fd_eqs = eqs , fd_pred1 = p_inst, fd_pred2 = pred , fd_loc = mk_loc p_inst (getSrcSpan (is_dfun ispec)) } | fd <- cls_fds -- Iterate through the fundeps first, -- because there often are none! , let trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs -- Trim the rough_tcs based on the head of the fundep. -- Remember that instanceCantMatch treats both argumnents -- symmetrically, so it's ok to trim the rough_tcs, -- rather than trimming each inst_tcs in turn , ispec <- instances , (meta_tvs, eqs) <- improveClsFD cls_tvs fd ispec tys trimmed_tcs -- NB: orientation , let p_inst = mkClassPred cls (is_tys ispec) ] improveFromInstEnv _ _ _ = [] improveClsFD :: [TyVar] -> FunDep TyVar -- One functional dependency from the class -> ClsInst -- An instance template -> [Type] -> [Maybe Name] -- Arguments of this (C tys) predicate -> [([TyCoVar], [Pair Type])] -- Empty or singleton improveClsFD clas_tvs fd (ClsInst { is_tvs = qtvs, is_tys = tys_inst, is_tcs = rough_tcs_inst }) tys_actual rough_tcs_actual -- Compare instance {a,b} C sx sp sy sq -- with wanted [W] C tx tp ty tq -- for fundep (x,y -> p,q) from class (C x p y q) -- If (sx,sy) unifies with (tx,ty), take the subst S -- 'qtvs' are the quantified type variables, the ones which an be instantiated -- to make the types match. For example, given -- class C a b | a->b where ... -- instance C (Maybe x) (Tree x) where .. -- -- and a wanted constraint of form (C (Maybe t1) t2), -- then we will call checkClsFD with -- -- is_qtvs = {x}, is_tys = [Maybe x, Tree x] -- tys_actual = [Maybe t1, t2] -- -- We can instantiate x to t1, and then we want to force -- (Tree x) [t1/x] ~ t2 | instanceCantMatch rough_tcs_inst rough_tcs_actual = [] -- Filter out ones that can't possibly match, | otherwise = ASSERT2( length tys_inst == length tys_actual && length tys_inst == length clas_tvs , ppr tys_inst <+> ppr tys_actual ) case tcMatchTys ltys1 ltys2 of Nothing -> [] Just subst | isJust (tcMatchTysX subst rtys1 rtys2) -- Don't include any equations that already hold. -- Reason: then we know if any actual improvement has happened, -- in which case we need to iterate the solver -- In making this check we must taking account of the fact that any -- qtvs that aren't already instantiated can be instantiated to anything -- at all -- NB: We can't do this 'is-useful-equation' check element-wise -- because of: -- class C a b c | a -> b c -- instance C Int x x -- [Wanted] C Int alpha Int -- We would get that x -> alpha (isJust) and x -> Int (isJust) -- so we would produce no FDs, which is clearly wrong. -> [] | null fdeqs -> [] | otherwise -> [(meta_tvs, fdeqs)] -- We could avoid this substTy stuff by producing the eqn -- (qtvs, ls1++rs1, ls2++rs2) -- which will re-do the ls1/ls2 unification when the equation is -- executed. What we're doing instead is recording the partial -- work of the ls1/ls2 unification leaving a smaller unification problem where rtys1' = map (substTyUnchecked subst) rtys1 fdeqs = zipAndComputeFDEqs (\_ _ -> False) rtys1' rtys2 -- Don't discard anything! -- We could discard equal types but it's an overkill to call -- eqType again, since we know for sure that /at least one/ -- equation in there is useful) meta_tvs = [ setVarType tv (substTyUnchecked subst (varType tv)) | tv <- qtvs, tv `notElemTCvSubst` subst ] -- meta_tvs are the quantified type variables -- that have not been substituted out -- -- Eg. class C a b | a -> b -- instance C Int [y] -- Given constraint C Int z -- we generate the equation -- ({y}, [y], z) -- -- But note (a) we get them from the dfun_id, so they are *in order* -- because the kind variables may be mentioned in the -- type variabes' kinds -- (b) we must apply 'subst' to the kinds, in case we have -- matched out a kind variable, but not a type variable -- whose kind mentions that kind variable! -- Trac #6015, #6068 where (ltys1, rtys1) = instFD fd clas_tvs tys_inst (ltys2, rtys2) = instFD fd clas_tvs tys_actual {- %************************************************************************ %* * The Coverage condition for instance declarations * * ************************************************************************ Note [Coverage condition] ~~~~~~~~~~~~~~~~~~~~~~~~~ Example class C a b | a -> b instance theta => C t1 t2 For the coverage condition, we check (normal) fv(t2) `subset` fv(t1) (liberal) fv(t2) `subset` oclose(fv(t1), theta) The liberal version ensures the self-consistency of the instance, but it does not guarantee termination. Example: class Mul a b c | a b -> c where (.*.) :: a -> b -> c instance Mul Int Int Int where (.*.) = (*) instance Mul Int Float Float where x .*. y = fromIntegral x * y instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]). But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) ) But it is a mistake to accept the instance because then this defn: f = \ b x y -> if b then x .*. [y] else y makes instance inference go into a loop, because it requires the constraint Mul a [b] b -} checkInstCoverage :: Bool -- Be liberal -> Class -> [PredType] -> [Type] -> Validity -- "be_liberal" flag says whether to use "liberal" coverage of -- See Note [Coverage Condition] below -- -- Return values -- Nothing => no problems -- Just msg => coverage problem described by msg checkInstCoverage be_liberal clas theta inst_taus = allValid (map fundep_ok fds) where (tyvars, fds) = classTvsFds clas fundep_ok fd | and (isEmptyVarSet <$> undetermined_tvs) = IsValid | otherwise = NotValid msg where (ls,rs) = instFD fd tyvars inst_taus ls_tvs = tyCoVarsOfTypes ls rs_tvs = splitVisVarsOfTypes rs undetermined_tvs | be_liberal = liberal_undet_tvs | otherwise = conserv_undet_tvs closed_ls_tvs = oclose theta ls_tvs liberal_undet_tvs = (`minusVarSet` closed_ls_tvs) <$> rs_tvs conserv_undet_tvs = (`minusVarSet` ls_tvs) <$> rs_tvs undet_set = fold undetermined_tvs msg = vcat [ -- text "ls_tvs" <+> ppr ls_tvs -- , text "closed ls_tvs" <+> ppr (closeOverKinds ls_tvs) -- , text "theta" <+> ppr theta -- , text "oclose" <+> ppr (oclose theta (closeOverKinds ls_tvs)) -- , text "rs_tvs" <+> ppr rs_tvs sep [ text "The" <+> ppWhen be_liberal (text "liberal") <+> text "coverage condition fails in class" <+> quotes (ppr clas) , nest 2 $ text "for functional dependency:" <+> quotes (pprFunDep fd) ] , sep [ text "Reason: lhs type"<>plural ls <+> pprQuotedList ls , nest 2 $ (if isSingleton ls then text "does not" else text "do not jointly") <+> text "determine rhs type"<>plural rs <+> pprQuotedList rs ] , text "Un-determined variable" <> pluralVarSet undet_set <> colon <+> pprVarSet undet_set (pprWithCommas ppr) , ppWhen (isEmptyVarSet $ pSnd undetermined_tvs) $ ppSuggestExplicitKinds , ppWhen (not be_liberal && and (isEmptyVarSet <$> liberal_undet_tvs)) $ text "Using UndecidableInstances might help" ] {- Note [Closing over kinds in coverage] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have a fundep (a::k) -> b Then if 'a' is instantiated to (x y), where x:k2->*, y:k2, then fixing x really fixes k2 as well, and so k2 should be added to the lhs tyvars in the fundep check. Example (Trac #8391), using liberal coverage data Foo a = ... -- Foo :: forall k. k -> * class Bar a b | a -> b instance Bar a (Foo a) In the instance decl, (a:k) does fix (Foo k a), but only if we notice that (a:k) fixes k. Trac #10109 is another example. Here is a more subtle example, from HList-0.4.0.0 (Trac #10564) class HasFieldM (l :: k) r (v :: Maybe *) | l r -> v where ... class HasFieldM1 (b :: Maybe [*]) (l :: k) r v | b l r -> v where ... class HMemberM (e1 :: k) (l :: [k]) (r :: Maybe [k]) | e1 l -> r data Label :: k -> * type family LabelsOf (a :: [*]) :: * instance (HMemberM (Label {k} (l::k)) (LabelsOf xs) b, HasFieldM1 b l (r xs) v) => HasFieldM l (r xs) v where Is the instance OK? Does {l,r,xs} determine v? Well: * From the instance constraint HMemberM (Label k l) (LabelsOf xs) b, plus the fundep "| el l -> r" in class HMameberM, we get {l,k,xs} -> b * Note the 'k'!! We must call closeOverKinds on the seed set ls_tvs = {l,r,xs}, BEFORE doing oclose, else the {l,k,xs}->b fundep won't fire. This was the reason for #10564. * So starting from seeds {l,r,xs,k} we do oclose to get first {l,r,xs,k,b}, via the HMemberM constraint, and then {l,r,xs,k,b,v}, via the HasFieldM1 constraint. * And that fixes v. However, we must closeOverKinds whenever augmenting the seed set in oclose! Consider Trac #10109: data Succ a -- Succ :: forall k. k -> * class Add (a :: k1) (b :: k2) (ab :: k3) | a b -> ab instance (Add a b ab) => Add (Succ {k1} (a :: k1)) b (Succ {k3} (ab :: k3}) We start with seed set {a:k1,b:k2} and closeOverKinds to {a,k1,b,k2}. Now use the fundep to extend to {a,k1,b,k2,ab}. But we need to closeOverKinds *again* now to {a,k1,b,k2,ab,k3}, so that we fix all the variables free in (Succ {k3} ab). Bottom line: * closeOverKinds on initial seeds (done automatically by tyCoVarsOfTypes in checkInstCoverage) * and closeOverKinds whenever extending those seeds (in oclose) Note [The liberal coverage condition] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (oclose preds tvs) closes the set of type variables tvs, wrt functional dependencies in preds. The result is a superset of the argument set. For example, if we have class C a b | a->b where ... then oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z} because if we know x and y then that fixes z. We also use equality predicates in the predicates; if we have an assumption `t1 ~ t2`, then we use the fact that if we know `t1` we also know `t2` and the other way. eg oclose [C (x,y) z, a ~ x] {a,y} = {a,y,z,x} oclose is used (only) when checking the coverage condition for an instance declaration -} oclose :: [PredType] -> TyCoVarSet -> TyCoVarSet -- See Note [The liberal coverage condition] oclose preds fixed_tvs | null tv_fds = fixed_tvs -- Fast escape hatch for common case. | otherwise = fixVarSet extend fixed_tvs where extend fixed_tvs = foldl add fixed_tvs tv_fds where add fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` closeOverKinds rs | otherwise = fixed_tvs -- closeOverKinds: see Note [Closing over kinds in coverage] tv_fds :: [(TyCoVarSet,TyCoVarSet)] tv_fds = [ (tyCoVarsOfTypes ls, tyCoVarsOfTypes rs) | pred <- preds , pred' <- pred : transSuperClasses pred -- Look for fundeps in superclasses too , (ls, rs) <- determined pred' ] determined :: PredType -> [([Type],[Type])] determined pred = case classifyPredType pred of EqPred NomEq t1 t2 -> [([t1],[t2]), ([t2],[t1])] ClassPred cls tys -> [ instFD fd cls_tvs tys | let (cls_tvs, cls_fds) = classTvsFds cls , fd <- cls_fds ] _ -> [] {- ************************************************************************ * * Check that a new instance decl is OK wrt fundeps * * ************************************************************************ Here is the bad case: class C a b | a->b where ... instance C Int Bool where ... instance C Int Char where ... The point is that a->b, so Int in the first parameter must uniquely determine the second. In general, given the same class decl, and given instance C s1 s2 where ... instance C t1 t2 where ... Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2). Matters are a little more complicated if there are free variables in the s2/t2. class D a b c | a -> b instance D a b => D [(a,a)] [b] Int instance D a b => D [a] [b] Bool The instance decls don't overlap, because the third parameter keeps them separate. But we want to make sure that given any constraint D s1 s2 s3 if s1 matches Note [Bogus consistency check] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In checkFunDeps we check that a new ClsInst is consistent with all the ClsInsts in the environment. The bogus aspect is discussed in Trac #10675. Currenty it if the two types are *contradicatory*, using (isNothing . tcUnifyTys). But all the papers say we should check if the two types are *equal* thus not (substTys subst rtys1 `eqTypes` substTys subst rtys2) For now I'm leaving the bogus form because that's the way it has been for years. -} checkFunDeps :: InstEnvs -> ClsInst -> [ClsInst] -- The Consistency Check. -- Check whether adding DFunId would break functional-dependency constraints -- Used only for instance decls defined in the module being compiled -- Returns a list of the ClsInst in InstEnvs that are inconsistent -- with the proposed new ClsInst checkFunDeps inst_envs (ClsInst { is_tvs = qtvs1, is_cls = cls , is_tys = tys1, is_tcs = rough_tcs1 }) | null fds = [] | otherwise = nubBy eq_inst $ [ ispec | ispec <- cls_insts , fd <- fds , is_inconsistent fd ispec ] where cls_insts = classInstances inst_envs cls (cls_tvs, fds) = classTvsFds cls qtv_set1 = mkVarSet qtvs1 is_inconsistent fd (ClsInst { is_tvs = qtvs2, is_tys = tys2, is_tcs = rough_tcs2 }) | instanceCantMatch trimmed_tcs rough_tcs2 = False | otherwise = case tcUnifyTys bind_fn ltys1 ltys2 of Nothing -> False Just subst -> isNothing $ -- Bogus legacy test (Trac #10675) -- See Note [Bogus consistency check] tcUnifyTys bind_fn (substTysUnchecked subst rtys1) (substTysUnchecked subst rtys2) where trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs1 (ltys1, rtys1) = instFD fd cls_tvs tys1 (ltys2, rtys2) = instFD fd cls_tvs tys2 qtv_set2 = mkVarSet qtvs2 bind_fn tv | tv `elemVarSet` qtv_set1 = BindMe | tv `elemVarSet` qtv_set2 = BindMe | otherwise = Skolem eq_inst i1 i2 = instanceDFunId i1 == instanceDFunId i2 -- An single instance may appear twice in the un-nubbed conflict list -- because it may conflict with more than one fundep. E.g. -- class C a b c | a -> b, a -> c -- instance C Int Bool Bool -- instance C Int Char Char -- The second instance conflicts with the first by *both* fundeps trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name] -- Computing rough_tcs for a particular fundep -- class C a b c | a -> b where ... -- For each instance .... => C ta tb tc -- we want to match only on the type ta; so our -- rough-match thing must similarly be filtered. -- Hence, we Nothing-ise the tb and tc types right here -- -- Result list is same length as input list, just with more Nothings trimRoughMatchTcs clas_tvs (ltvs, _) mb_tcs = zipWith select clas_tvs mb_tcs where select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc | otherwise = Nothing
vikraman/ghc
compiler/typecheck/FunDeps.hs
bsd-3-clause
25,542
0
19
8,459
2,793
1,509
1,284
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Futhark.IR.SeqMem ( SeqMem, -- * Simplification simplifyProg, simpleSeqMem, -- * Module re-exports module Futhark.IR.Mem, ) where import Futhark.Analysis.PrimExp.Convert import Futhark.IR.Mem import Futhark.IR.Mem.Simplify import qualified Futhark.Optimise.Simplify.Engine as Engine import Futhark.Pass import Futhark.Pass.ExplicitAllocations (BuilderOps (..), mkLetNamesB', mkLetNamesB'') import qualified Futhark.TypeCheck as TC data SeqMem instance RepTypes SeqMem where type LetDec SeqMem = LetDecMem type FParamInfo SeqMem = FParamMem type LParamInfo SeqMem = LParamMem type RetType SeqMem = RetTypeMem type BranchType SeqMem = BranchTypeMem type Op SeqMem = MemOp () instance ASTRep SeqMem where expTypesFromPat = return . map snd . bodyReturnsFromPat instance PrettyRep SeqMem instance TC.CheckableOp SeqMem where checkOp (Alloc size _) = TC.require [Prim int64] size checkOp (Inner ()) = pure () instance TC.Checkable SeqMem where checkFParamDec = checkMemInfo checkLParamDec = checkMemInfo checkLetBoundDec = checkMemInfo checkRetType = mapM_ (TC.checkExtType . declExtTypeOf) primFParam name t = return $ Param mempty name (MemPrim t) matchPat = matchPatToExp matchReturnType = matchFunctionReturnType matchBranchType = matchBranchReturnType matchLoopResult = matchLoopResultMem instance BuilderOps SeqMem where mkExpDecB _ _ = return () mkBodyB stms res = return $ Body () stms res mkLetNamesB = mkLetNamesB' () instance TraverseOpStms SeqMem where traverseOpStms _ = pure instance BuilderOps (Engine.Wise SeqMem) where mkExpDecB pat e = return $ Engine.mkWiseExpDec pat () e mkBodyB stms res = return $ Engine.mkWiseBody () stms res mkLetNamesB = mkLetNamesB'' instance TraverseOpStms (Engine.Wise SeqMem) where traverseOpStms _ = pure simplifyProg :: Prog SeqMem -> PassM (Prog SeqMem) simplifyProg = simplifyProgGeneric simpleSeqMem simpleSeqMem :: Engine.SimpleOps SeqMem simpleSeqMem = simpleGeneric (const mempty) $ const $ return ((), mempty)
HIPERFIT/futhark
src/Futhark/IR/SeqMem.hs
isc
2,241
0
9
372
586
318
268
-1
-1
-- -- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. -- What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? -- import List factors :: (Integral a) => a -> [a] factors x = filter (\ y -> x `mod` y == 0) [1..x] isPrime x = (length $ factors x) == 2 primeFactors x = filter isPrime $ factors x isDivisible :: (Integral a) => a -> a -> Bool isDivisible x y = x `mod` y == 0 isDivisibleAll :: (Integral a) => a -> [a] -> Bool isDivisibleAll x = all (\ y -> isDivisible x y) range = [1..20] primes = foldl union [] $ map primeFactors range rangeMax = product primes rangeReduced = filter (\ x -> not $ isAnyDivisible x $ rangeBigger x ) range where rangeBigger x = filter (> x) range isAnyDivisible x ys = any (\ y -> isDivisible y x) ys main = putStrLn $ show $ head $ filter (\ x -> isDivisibleAll x rangeReduced) [rangeMax, rangeMax + rangeMax ..]
stu-smith/project-euler-haskell
Euler-005.hs
mit
1,005
0
10
248
360
191
169
16
1
module Main where import Lib printInt :: Int -> IO () printInt x = print x main :: IO () main = str <- getLine printInt (read str)
gitrookie/functionalcode
code/Haskell/stmonads/app/Main.hs
mit
138
1
7
35
62
32
30
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE CPP #-} module Yesod.Core.Dispatch ( -- * Quasi-quoted routing parseRoutes , parseRoutesNoCheck , parseRoutesFile , parseRoutesFileNoCheck , mkYesod -- ** More fine-grained , mkYesodData , mkYesodSubData , mkYesodDispatch , mkYesodSubDispatch -- ** Path pieces , PathPiece (..) , PathMultiPiece (..) , Texts -- * Convert to WAI , toWaiApp , toWaiAppPlain , warp , warpDebug , warpEnv , mkDefaultMiddlewares , defaultMiddlewaresNoLogging -- * WAI subsites , WaiSubsite (..) ) where import Prelude hiding (exp) import Yesod.Core.Internal.TH import Language.Haskell.TH.Syntax (qLocation) import Web.PathPieces import qualified Network.Wai as W import Data.ByteString.Lazy.Char8 () import Data.Text (Text) import Data.Monoid (mappend) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Blaze.ByteString.Builder import Network.HTTP.Types (status301, status307) import Yesod.Routes.Parse import Yesod.Core.Types import Yesod.Core.Class.Yesod import Yesod.Core.Class.Dispatch import Yesod.Core.Internal.Run import Safe (readMay) import System.Environment (getEnvironment) import Network.Wai.Middleware.Autohead import Network.Wai.Middleware.AcceptOverride import Network.Wai.Middleware.RequestLogger import Network.Wai.Middleware.Gzip import Network.Wai.Middleware.MethodOverride import qualified Network.Wai.Handler.Warp import System.Log.FastLogger import Control.Monad.Logger import Control.Monad (when) import qualified Paths_yesod_core import Data.Version (showVersion) import qualified System.Random.MWC as MWC -- | Convert the given argument into a WAI application, executable with any WAI -- handler. This function will provide no middlewares; if you want commonly -- used middlewares, please use 'toWaiApp'. toWaiAppPlain :: YesodDispatch site => site -> IO W.Application toWaiAppPlain site = do logger <- makeLogger site sb <- makeSessionBackend site gen <- MWC.createSystemRandom return $ toWaiAppYre $ YesodRunnerEnv { yreLogger = logger , yreSite = site , yreSessionBackend = sb , yreGen = gen } toWaiAppYre :: YesodDispatch site => YesodRunnerEnv site -> W.Application toWaiAppYre yre req = case cleanPath site $ W.pathInfo req of Left pieces -> sendRedirect site pieces req Right pieces -> yesodDispatch yre req { W.pathInfo = pieces } where site = yreSite yre sendRedirect :: Yesod master => master -> [Text] -> W.Application sendRedirect y segments' env sendResponse = sendResponse $ W.responseLBS status [ ("Content-Type", "text/plain") , ("Location", Blaze.ByteString.Builder.toByteString dest') ] "Redirecting" where -- Ensure that non-GET requests get redirected correctly. See: -- https://github.com/yesodweb/yesod/issues/951 status | W.requestMethod env == "GET" = status301 | otherwise = status307 dest = joinPath y (resolveApproot y env) segments' [] dest' = if S.null (W.rawQueryString env) then dest else (dest `mappend` Blaze.ByteString.Builder.fromByteString (W.rawQueryString env)) -- | Same as 'toWaiAppPlain', but provides a default set of middlewares. This -- set may change with future releases, but currently covers: -- -- * Logging -- -- * GZIP compression -- -- * Automatic HEAD method handling -- -- * Request method override with the _method query string parameter -- -- * Accept header override with the _accept query string parameter toWaiApp :: YesodDispatch site => site -> IO W.Application toWaiApp site = do logger <- makeLogger site toWaiAppLogger logger site toWaiAppLogger :: YesodDispatch site => Logger -> site -> IO W.Application toWaiAppLogger logger site = do sb <- makeSessionBackend site gen <- MWC.createSystemRandom let yre = YesodRunnerEnv { yreLogger = logger , yreSite = site , yreSessionBackend = sb , yreGen = gen } messageLoggerSource site logger $(qLocation >>= liftLoc) "yesod-core" LevelInfo (toLogStr ("Application launched" :: S.ByteString)) middleware <- mkDefaultMiddlewares logger return $ middleware $ toWaiAppYre yre -- | A convenience method to run an application using the Warp webserver on the -- specified port. Automatically calls 'toWaiApp'. Provides a default set of -- middlewares. This set may change at any point without a breaking version -- number. Currently, it includes: -- -- If you need more fine-grained control of middlewares, please use 'toWaiApp' -- directly. -- -- Since 1.2.0 warp :: YesodDispatch site => Int -> site -> IO () warp port site = do logger <- makeLogger site toWaiAppLogger logger site >>= Network.Wai.Handler.Warp.runSettings ( Network.Wai.Handler.Warp.setPort port $ Network.Wai.Handler.Warp.setServerName serverValue $ Network.Wai.Handler.Warp.setOnException (\_ e -> when (shouldLog' e) $ messageLoggerSource site logger $(qLocation >>= liftLoc) "yesod-core" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) $ Network.Wai.Handler.Warp.defaultSettings) where shouldLog' = Network.Wai.Handler.Warp.defaultShouldDisplayException serverValue :: S8.ByteString serverValue = S8.pack $ concat [ "Warp/" , Network.Wai.Handler.Warp.warpVersion , " + Yesod/" , showVersion Paths_yesod_core.version , " (core)" ] -- | A default set of middlewares. -- -- Since 1.2.0 mkDefaultMiddlewares :: Logger -> IO W.Middleware mkDefaultMiddlewares logger = do logWare <- mkRequestLogger def { destination = Network.Wai.Middleware.RequestLogger.Logger $ loggerSet logger , outputFormat = Apache FromSocket } return $ logWare . defaultMiddlewaresNoLogging -- | All of the default middlewares, excluding logging. -- -- Since 1.2.12 defaultMiddlewaresNoLogging :: W.Middleware defaultMiddlewaresNoLogging = acceptOverride . autohead . gzip def . methodOverride -- | Deprecated synonym for 'warp'. warpDebug :: YesodDispatch site => Int -> site -> IO () warpDebug = warp {-# DEPRECATED warpDebug "Please use warp instead" #-} -- | Runs your application using default middlewares (i.e., via 'toWaiApp'). It -- reads port information from the PORT environment variable, as used by tools -- such as Keter and the FP Complete School of Haskell. -- -- Note that the exact behavior of this function may be modified slightly over -- time to work correctly with external tools, without a change to the type -- signature. warpEnv :: YesodDispatch site => site -> IO () warpEnv site = do env <- getEnvironment case lookup "PORT" env of Nothing -> error $ "warpEnv: no PORT environment variable found" Just portS -> case readMay portS of Nothing -> error $ "warpEnv: invalid PORT environment variable: " ++ show portS Just port -> warp port site
ygale/yesod
yesod-core/Yesod/Core/Dispatch.hs
mit
7,617
0
19
1,857
1,412
798
614
157
3
{-# LANGUAGE OverloadedStrings #-} module FeatureSpec where import qualified Data.Text as T import qualified Data.Map as Map import SpaceWeather.Feature import SpaceWeather.Format import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck.Arbitrary newtype SmallPositive = SmallPositive Int deriving (Eq,Show) instance Arbitrary SmallPositive where arbitrary = do n <- arbitrary return $ SmallPositive $ 1 + mod n 10 shrink (SmallPositive n) = map SmallPositive $ filter (>0) $ shrink n testFeature :: Feature testFeature = Map.fromList [(0,1.2),(3,4.5)] testFeature2 :: Feature testFeature2 = Map.fromList $ zip [1..11] [3..33] testFeature3 :: Feature testFeature3 = Map.fromList $ zip [2..22] [44..444] testFeatures23 :: Features testFeatures23 = Map.fromList $ [(t, [fromIntegral t+2, fromIntegral t+42])|t<-[2..11]] testEncode1 :: T.Text testEncode1 = "0 1.2\n3 4.5\n" testEncode2 :: T.Text testEncode2 = "#comment\n0 1.2\n # another comment \n 3 \t 4.5 \n" spec :: Spec spec = do describe "Feature" $ do it "is encoded as expected." $ encode testFeature `shouldBe` testEncode1 it "is robust against comment and spaces." $ decode testEncode2 `shouldBe` Right testFeature prop "is encoded/decoded back properly." $ \feature -> (decode $ encode (feature :: Feature)) == Right feature describe "Features" $ do it "cats as expected." $ catFeatures [testFeature2, testFeature3] `shouldBe` testFeatures23 prop "cat is idempotent." $ \(SmallPositive n, feature)-> catFeatures (replicate n feature) == Map.map (replicate n) feature prop "every row of cat of N features contain N elements." $ \fs -> all ((== length fs) . length) $ Map.elems $ catFeatures fs describe "FeatureIOPair" $ do prop "is encoded/decoded back properly." $ \fio -> (decode $ encode (fio :: FeatureIOPair)) == Right fio
nushio3/UFCORIN
test/FeatureSpec.hs
mit
1,910
0
18
364
598
315
283
46
1
{-# LANGUAGE OverloadedStrings #-} module Tests.Bed (tests) where import Bio.Data.Bed import Bio.Data.Bed.Types import Bio.Data.Bed.Utils import Bio.Utils.BitVector hiding (size) import Lens.Micro import Conduit import Data.Function (on) import Data.List (sortBy, sort) import qualified Data.Vector as V import Test.Tasty import Test.Tasty.HUnit import qualified Data.HashMap.Strict as M import Data.Ord import Data.Maybe import Bio.RealWorld.GENCODE import Data.Conduit.Zlib tests :: TestTree tests = testGroup "Test: Bio.Data.Bed" [ testCase "sortBed" sortBedTest , testCase "split" splitBedTest , testCase "splitOverlapped" splitOverlappedTest , testCase "mergeBed" mergeBedTest , testCase "intersectBed" intersectBedTest , testCase "baseMap" baseMapTest , testCase "domain assignment" geneDomainTest ] sortBedTest :: Assertion sortBedTest = do beds <- runResourceT $ runConduit $ streamBedGzip "tests/data/peaks.bed.gz" .| sinkList :: IO [BED3] let (Sorted actual) = sortBed beds expect <- runResourceT $ runConduit $ streamBedGzip "tests/data/peaks.sorted.bed.gz" .| sinkVector expect @=? actual splitBedTest :: Assertion splitBedTest = (s1', s2', s3') @=? (s1, s2, s3) where bed = asBed "chr1" 0 99 s1 = splitBedBySize 20 bed s1' = map f [(0, 20), (20, 40), (40, 60), (60, 80)] s2 = splitBedBySizeLeft 20 bed s2' = map f [(0, 20), (20, 40), (40, 60), (60, 80), (80, 100)] s3 = splitBedBySizeOverlap 20 10 bed s3' = map f [ ( 0, 20), (10, 30), (20, 40), (30, 50), (40, 60) , (50, 70), (60, 80), (70, 90), (80, 100) ] f (a,b) = asBed "chr1" a b :: BED3 splitOverlappedTest :: Assertion splitOverlappedTest = expect @=? result where input :: [BED3] input = map (\(a,b) -> asBed "chr1" a b) [ (0, 100) , (10, 20) , (50, 150) , (120, 160) , (155, 200) , (155, 220) , (0, 10) , (0, 10) ] expect = map (\((a,b), x) -> (asBed "chr1" a b, x)) [ ((0, 10), 3) , ((10, 20), 2) , ((20, 50), 1) , ((50, 100), 2) , ((100, 120), 1) , ((120, 150), 2) , ((150, 155), 1) , ((155, 160), 3) , ((160, 200), 2) , ((200, 220), 1) ] --result = sortBy (compareBed `on` fst) $ splitOverlapped length input result = sortBy (compareBed `on` fst) $ countOverlapped input mergeBedTest :: Assertion mergeBedTest = expect @=? result where input :: [BED3] input = map (\(a,b) -> asBed "chr1" a b) [ (0, 100) , (10, 20) , (50, 150) , (120, 160) , (155, 200) , (155, 220) , (500, 1000) ] expect = map (\(a,b) -> asBed "chr1" a b) [ (0, 220) , (500, 1000) ] result = runIdentity $ runConduit $ mergeBed input .| sinkList intersectBedTest :: Assertion intersectBedTest = do expect <- runResourceT $ runConduit $ streamBedGzip "tests/data/example_intersect_peaks.bed.gz" .| sinkList :: IO [BED3] peaks <- runResourceT $ runConduit $ streamBedGzip "tests/data/peaks.bed.gz" .| sinkList :: IO [BED3] result <- runResourceT $ runConduit $ streamBedGzip "tests/data/example.bed.gz" .| intersectBed peaks .| sinkList expect @=? result baseMapTest :: Assertion baseMapTest = do BaseMap bv <- runResourceT $ runConduit $ streamBedGzip "tests/data/example.bed.gz" .| baseMap [("chr1", 300000000)] let res = M.lookupDefault undefined "chr1" $ fmap (map fst . filter snd . zip [0..] . toList) bv expect <- runResourceT $ runConduit $ streamBedGzip "tests/data/example.bed.gz" .| concatMapC f .| sinkList sort expect @=? sort res where f :: BED -> Maybe Int f bed = if bed^.chrom == "chr1" then Just $ if fromJust (bed^.strand) then bed^.chromStart else bed^.chromEnd - 1 else Nothing geneDomainTest :: Assertion geneDomainTest = do genes <- runResourceT $ runConduit $ sourceFile "tests/data/genes.gtf.gz" .| multiple ungzip .| readGenesC let promoters = bedToTree const $ zip (concatMap (getPromoters 5000 1000) genes) $ repeat () domain = getDomains 1000000 $ concatMap (getPromoters 5000 1000) genes f x = not (isIntersected promoters x) && (c1 || c2) where c1 = isIntersected promoters (chromStart %~ (`subtract` 1) $ x) && isIntersected promoters (chromEnd %~ (+1) $ x) && size x < 1000000 c2 = isIntersected promoters (chromStart %~ (`subtract` 1) $ chromEnd %~ (+1) $ x) && size x == 1000000 all f domain @=? True
kaizhang/bioinformatics-toolkit
bioinformatics-toolkit/tests/Tests/Bed.hs
mit
4,837
0
20
1,403
1,696
960
736
122
3
{-# LANGUAGE ExistentialQuantification #-} module Contract.Type ( Contract(..) -- constructors exported , MContract -- managed contract, including a start date , Party -- smart constructors and convenience functions , zero, transfOne, transl, iff, checkWithin, both, allCs, scale, flow, foreach -- pretty-printer , ppContr ) where import Contract.Expr import Contract.ExprIO import Contract.Date import Contract.Hash -- | party of a contract. A simple string type Party = String -- | a managed contract is a contract with a start date type MContract = (Date, Contract) -- | the contract representation type data Contract = Zero | TransfOne Currency Party Party -- ^ Atom: Transfer money | Scale RealE Contract -- ^ Scaling a contract by a RealE | Transl Int Contract -- ^ Translating a contract into the future | Both Contract Contract -- ^ Combining two contracts | If BoolE Contract Contract -- ^ Conditional contract | CheckWithin BoolE Int Contract Contract -- ^ Repeatedly checks every day, until given end, whether condition is true. When it is true, the first contract argument comes into effect. Otherwise (never true until end) the second contract comes into effect. -- | forall a . Let (Expr a) (Expr a -> Contract) deriving (Show) -- | computes hash of a contract, considering symmetry of 'Both' constructor hashContr :: [Var] -> Contract -> Hash -> Hash hashContr vs c a = let ps = hashPrimes in case c of Zero -> hash (ps!!0) a -- symmetric Both c1 c2 -> hashContr vs c1 0 + hashContr vs c2 0 + a TransfOne cur p1 p2 -> hashStr (show cur) (hashStr p1 (hashStr p2 (hash (ps!!1) a))) If e c1 c2 -> hashContr vs c1 (hashContr vs c2 (hashExp vs e (hash (ps!!2) a))) Scale e c -> hashExp vs e (hashContr vs c (hash (ps!!3) a)) Transl i c -> hash i (hashContr vs c (hash (ps!!4) a)) CheckWithin e1 i c1 c2 -> hashContr vs c1 (hashContr vs c2 (hashExp vs e1 (hash i (hash (ps!!5) a)))) -- Let e f -> hashContr(v::vs,c,hashExp(vs,e,H(17,a))) -- | hash-based equality, levelling out some symmetries instance Eq Contract where c1 == c2 = hashContr [] c1 0 == hashContr [] c2 0 -- | pretty-prints a contract. ppContr :: Contract -> String ppContr c = case c of TransfOne c p1 p2 -> "TransfOne" ++ par (show c ++ "," ++ p1 ++ "," ++ p2) Scale e c -> "Scale" ++ par (ppExp e ++ "," ++ ppContr c) Transl i c -> "Transl" ++ par (ppDays i ++ "," ++ ppContr c) Zero -> "zero" Both c1 c2 -> "Both" ++ par (ppContrs[c1,c2]) If e c1 c2 -> "If" ++ par (ppExp e ++ ", " ++ ppContr c1 ++ ", " ++ ppContr c2) CheckWithin e i c1 c2 -> "CheckWithin" ++ par (ppExp e ++ ", " ++ ppDays i ++ ", " ++ ppContr c1 ++ ", " ++ ppContr c2) -- | Let(v,e,c) -> "Let" ++ par (v ++ "," ++ ppExp e ++ "," ++ ppContr c) where par s = "(" ++ s ++ ")" ppContrs [] = "" ppContrs [c] = ppContr c ppContrs (c:cs) = ppContr c ++ ", " ++ ppContrs cs -- smart constructors (for reexport) TODO make them smarter! -- | the empty contract zero = Zero -- | Transfer one unit. Rarely used... transfOne = TransfOne -- | translate a contract into the future by a number of days transl :: Int -> Contract -> Contract transl d c | d < 0 = error "transl: negative time" transl 0 c = c transl _ Zero = Zero transl d (Transl d' c) = Transl (d+d') c transl d c = Transl d c -- | conditional contract (two branches) iff = If -- | repeatedly checking condition for the given number of days, branching into first contract when true, or else into second contract at the end checkWithin = CheckWithin -- | two contracts both c1 Zero = c1 both Zero c2 = c2 both c1 c2 | c1 == c2 = scale (r 2) c1 | otherwise = Both c1 c2 -- | many contracts (a 'book') allCs :: [Contract] -> Contract allCs [] = Zero allCs [c] = c allCs (Zero:cs) = allCs cs allCs (c:cs) = both c (allCs cs) -- | scaling a contract by a 'RealE' expression scale _ Zero = Zero scale r (Scale r' c) = Scale (r*r') c scale r c | r == 0 = Zero | r == 1 = c | otherwise = Scale r c -- | straightforward money transfer (translate, scale, transfOne): after given number of days, transfer from one party to another the given amount in the given currency flow :: Int -> RealE -> Currency -> Party -> Party -> Contract flow d amount cur from to = transl d (scale amount (transfOne cur from to)) foreach :: [Int] -> Contract -> Contract foreach ds c = allCs (map (\ d -> transl d c) ds)
annenkov/contracts
Haskell/Contract/Type.hs
mit
4,758
0
20
1,309
1,398
717
681
81
7
module Sync.MerkleTree.Server where import Codec.Compression.GZip import Control.Monad.State import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.Map (Map) import qualified Data.Map as M import Data.String.Interpolate.IsString import qualified Data.Text.IO as T import Data.Time.Clock import Sync.MerkleTree.CommTypes import Sync.MerkleTree.Trie import Sync.MerkleTree.Types import System.IO data ServerState = ServerState { -- | Map of open file handles with their ids st_handles :: Map Int Handle, -- | Next available id st_nextHandle :: Int, -- | Merkle Hash Tree of server file hierarchy st_trie :: Trie Entry, -- | path of the root of the file hierarchy st_path :: FilePath } type ServerMonad = StateT ServerState IO startServerState :: FilePath -> Trie Entry -> IO ServerState startServerState fp trie = do T.hPutStr stderr $ [i|Hash of source directory: #{t_hash trie}.\n|] return $ ServerState { st_handles = M.empty, st_nextHandle = 0, st_trie = trie, st_path = fp } instance Protocol ServerMonad where querySetReq l = get >>= (\s -> querySet (st_trie s) l) queryHashReq l = get >>= (\s -> queryHash (st_trie s) l) logReq msg = liftIO (T.hPutStr stderr msg) >> return True queryFileContReq (ContHandle n) = do s <- get let Just h = M.lookup n (st_handles s) withHandle h n queryFileReq f = do s <- get h <- liftIO $ openFile (toFilePath (st_path s) f) ReadMode let n = st_nextHandle s put $ s {st_handles = M.insert n h (st_handles s), st_nextHandle = n + 1} withHandle h n queryTime = liftIO getCurrentTime terminateReq _ = return True -- | Respond to a queryFile or queryFileCont request for a given file handle and id withHandle :: Handle -> Int -> ServerMonad QueryFileResponse withHandle h n = do bs <- liftIO $ BS.hGet h (2 ^ (17 :: Int)) if BS.null bs then do liftIO $ hClose h modify (\s -> s {st_handles = M.delete n (st_handles s)}) return $ Final else return $ ToBeContinued (BL.toStrict $ compress $ BL.fromStrict bs) $ ContHandle n
ekarayel/sync-mht
src/Sync/MerkleTree/Server.hs
mit
2,212
0
17
538
670
357
313
-1
-1
module StringCalculator.Coercion (integer, string) where integer n = read n :: Integer string n = show n
jtrim/string-calculator-hs
src/StringCalculator/Coercion.hs
mit
110
0
5
22
39
21
18
3
1
module LensUtil where import Prelude import Control.Lens import Language.Haskell.TH makeLensesCustom :: Name -> DecsQ makeLensesCustom = makeLensesWith $ lensRules & lensField .~ \_ _ name -> [TopName (mkName $ nameBase name ++ "L")]
jonschoning/pinboard
gen/LensUtil.hs
mit
238
0
12
37
73
41
32
7
1
{-# LANGUAGE BangPatterns #-} -- Sutherland-Hodgman polygon clipping module Graphics.Perfract.PolyClip ( clipTo , ConvPoly , polyArea , polyLines , (.|) , (.@) ) where import Control.Applicative import qualified Data.Vector as Vec import Graphics.Perfract.Pt import Graphics.Perfract.Tupelo -- | Note: Do not repeat the initial vertex at the end. -- | Points in counterclockwise order. -- Should this be strict? type ConvPoly a = Vec.Vector (Pt a) polyArea :: (Eq a, Fractional a) => ConvPoly a -> a polyArea poly = Vec.sum (Vec.map ptDet $ polyLines poly) / 2 where ptDet (AB (XY x1 y1) (XY x2 y2)) = x1 * y2 - x2 * y1 type PtV a = Vec.Vector (Pt a) type LnV a = Vec.Vector (Ln a) polyLines :: Eq a => ConvPoly a -> LnV a polyLines !x = linesFrom $ selfComplete x -- Return a self-completed polygon from a list of points. selfComplete :: Eq a => ConvPoly a -> PtV a -- selfComplete ps = ps `deepseq` (last ps : ps) selfComplete ps = if pLast == Vec.head ps then ps else Vec.cons pLast ps where pLast = Vec.last ps -- Return all polygon lines from the self-complete point list. linesFrom :: PtV a -> LnV a linesFrom ps = Vec.zipWith AB ps (Vec.tail ps) -- Return true if the point is on or to the left of the oriented line. (.|) :: (Num a, Ord a) => Pt a -> Ln a -> Bool (.|) !(XY x y) !(AB (XY px py) (XY qx qy)) = (qx-px)*(y-py) >= (qy-py)*(x-px) {-# INLINE (.|) #-} -- Return true if the point is in (or on the border of) the polygon. (.@) :: Pt Rational -> ConvPoly Rational -> Bool (.@) pt = Vec.all (pt .|) . polyLines -- Return the intersection of two lines. -- Parallel lines will give a fatal exception. -- (We always know that lines aren't parallel the one time we call this and -- don't want to waste time checking anyway.) (><) :: (Fractional a, Num a) => Ln a -> Ln a -> Pt a (><) !(AB (XY x1 y1) (XY x2 y2)) !(AB (XY x3 y3) (XY x4 y4)) = XY ((d12 * x34 - d34 * x12) / d) ((d12 * y34 - d34 * y12) / d) where x12 = x1 - x2 y34 = y3 - y4 y12 = y1 - y2 x34 = x3 - x4 d12 = x1 * y2 - y1 * x2 d34 = x3 * y4 - y3 * x4 d = x12 * y34 - y12 * x34 {-# INLINE (><) #-} -- Intersect the line segment (p0,p1) with the clipping line's left halfspace, -- returning the point closest to p1. In the special case where p0 lies outside -- the halfspace and p1 lies inside we return both the intersection point and -- p1. This ensures we will have the necessary segment along the clipping line. (-|) :: (Eq a, Fractional a, Num a, Ord a) => Ln a -> Ln a -> PtV a (-|) !ln@(AB p0 p1) !clipLn = if in0 then Vec.singleton $ if in1 then p1 else isect else if in1 then if isect == p1 then Vec.singleton p1 else Vec.fromList [isect, p1] else Vec.empty where isect = ln >< clipLn in0 = p0 .| clipLn in1 = p1 .| clipLn -- Intersect the polygon with the clipping line's left halfspace. (<|) :: (Eq a, Fractional a, Num a, Ord a) => PtV a -> Ln a -> Maybe (PtV a) (<|) !poly !clipLn = let res = Vec.concatMap (-| clipLn) (linesFrom poly) in if Vec.null res then Nothing else Just $ selfComplete res -- Intersect a polygon with a clipping polygon. clipTo :: (Eq a, Fractional a, Num a, Ord a) => ConvPoly a -> ConvPoly a -> Maybe (ConvPoly a) clipTo !poly !clip = Vec.tail <$> (Vec.foldM (<|) (selfComplete poly) (polyLines clip))
dancor/perfract
src/Graphics/Perfract/PolyClip.hs
mit
3,342
0
11
776
1,169
622
547
59
5
--Replicate the elemtns of a list a given number of times module Problem15 where repli:: (Eq b, Num b, Ord b) => [a] -> b -> [a] repli _ t | t < 0 = error "times < 0" repli [] _ = [] repli (x:xs) times = let rep _ 0 = [] rep y times' = y : rep y (times'-1) in (rep x times) ++ repli xs times
Matt-Renfro/haskell
H-99/Problem15.hs
mit
354
0
12
133
160
81
79
8
2
module GHCJS.DOM.IDBOpenDBRequest ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/IDBOpenDBRequest.hs
mit
46
0
3
7
10
7
3
1
0
{-# LANGUAGE OverloadedStrings #-} module Site.Action where import BasePrelude import Prelude () import Heist import Snap (ifTop) import Snap.Snaplet.Heist.Compiled import Site.Internal actionRoutes :: PhbRoutes actionRoutes = [("/actions",ifTop $ render "actions/all")] allActionSplices :: Splices PhbSplice allActionSplices = mempty
benkolera/phb
hs/Site/Action.hs
mit
369
0
8
71
78
48
30
13
1
module Demiurge.Utils where import Demiurge.Common updateAt :: Same a => a -> [a] -> [a] updateAt xx yys = let helper x acc (y:ys) = if same x y then (x:ys ++ acc) else helper x (y:acc) ys helper x acc [] = x:acc in helper xx [] yys fstsnd :: (a, b, c) -> (a, b) fstsnd (x, y, _) = (x, y)
olive/demiurge
src/Demiurge/Utils.hs
mit
374
0
12
149
184
100
84
11
3
module Cis194.Spring13.HW04Spec (spec) where import Cis194.Spring13.HW04 import Test.Hspec spec :: Spec spec = describe "HW04" $ do describe "fun1'" $ do it "treats empty lists like fun1" $ fun1' [] `shouldBe` fun1 [] it "treats single-value odd lists like fun1" $ fun1' [1] `shouldBe` fun1 [1] it "treats single-value even lists like fun1" $ fun1' [2] `shouldBe` fun1 [2] it "treats two-value odd lists like fun1" $ fun1' [1,3] `shouldBe` fun1 [1,3] it "treats two-value even lists like fun1" $ fun1' [0,2] `shouldBe` fun1 [0,2] it "treats large mixed lists like fun1" $ fun1' [1,6,3,0,1,3] `shouldBe` fun1 [1,6,3,0,1,3] describe "fun2'" $ do it "treats one values like fun2" $ fun2' 1 `shouldBe` fun2 1 it "treats small even values like fun2" $ fun2' 2 `shouldBe` fun2 2 it "treats large even values like fun2" $ fun2' 100 `shouldBe` fun2 100 it "treats small odd values like fun2" $ fun2' 3 `shouldBe` fun2 3 it "treats large odd values like fun2" $ fun2' 101 `shouldBe` fun2 101 -- describe "foldTree" $ do -- it "should fold strings" $ -- foldTree "ABCDEFGHIJ" `shouldBe` -- Node 3 -- (Node 2 -- (Node 0 Leaf 'F' Leaf) -- 'I' -- (Node 1 (Node 0 Leaf 'B' Leaf) 'C' Leaf)) -- 'J' -- (Node 2 -- (Node 1 (Node 0 Leaf 'A' Leaf) 'G' Leaf) -- 'H' -- (Node 1 (Node 0 Leaf 'D' Leaf) 'E' Leaf))
tylerjl/cis194
test-suite/Cis194/Spring13/HW04Spec.hs
mit
1,928
0
14
870
391
205
186
30
1
{-# htermination plusFM :: FiniteMap Ordering b -> FiniteMap Ordering b -> FiniteMap Ordering b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_plusFM_11.hs
mit
117
0
3
18
5
3
2
1
0
module P07RoomArea where import Library main :: IO () main = do l <- promptNonNegFloat "length in feet: " w <- promptNonNegFloat "width in feet: " let f2 = f2ed w l putStrLn $ "Dimensions: " ++ show l ++ " feet by " ++ show w ++ " feet" putStrLn $ "Area: " ++ show f2 ++ " square feet" putStrLn $ " " ++ show (f2tom2 f2) ++ " square meters" f2ed :: Float -> Float -> Float f2ed w l = w * l f2tom2 :: Float -> Float f2tom2 = (*) conversionFactor where conversionFactor = 0.09290304 -- TODO: allow data in meters too, GUI
ciderpunx/57-exercises-for-programmers
src/P07RoomArea.hs
gpl-3.0
568
0
11
156
181
89
92
16
1
import Data.Text import Control.Exception.Base import Control.Monad.Trans.Either import Control.Monad.IO.Class import Control.Monad.State import Control.Monad.RWS import Control.Monad.Reader data MyException = MyException String deriving (Show) instance Exception MyException foo x | x < 0 = "foo" foo x = "fee" doMonadOnList :: Monad m => [a] -> (a -> m b) -> (m [b]) doMonadOnList [] _ = return [] doMonadOnList (a : as) f = do b <- (f a) bs <- doMonadOnList as f return (b : bs) -- doMonadOnMaybe :: Monad m => Maybe a -> (a -> m b) -> (m (Maybe b)) -- doMonadOnMaybe Nothing _ = return Nothing -- doMonadOnMaybe (Just a) f = ???? -- co: Doesn't seem possible, but strangely seems like it would work on most -- monads... dunno.. actually it doesn't seem to work for Maybe -- magic :: (Monad m1, Monad m2) => (m1 a) -> (a -> m2 b) -> m2 (m1 b) -- magic m1a f = -- (m1a >>= (\a -> return (f a))) eithertest :: EitherT (IO ()) IO () eithertest = do --left $ putStrLn "Hello Left?" left $ putStrLn "Hello Left?" two <- liftIO $ ((return $ 1 + 1) :: IO Int) liftIO $ putStrLn ("Hello Right? " ++ (show two)) return () doeithertest :: IO () doeithertest = runEitherT eithertest >>= (\x -> case x of (Left c) -> c;(Right c) -> return c) eitherstatetest :: StateT Int (EitherT (IO ()) IO) () eitherstatetest = do --lift $ left $ putStrLn "Hello Left?" state <- get liftIO $ putStrLn ("State is " ++ (show state)) two <- liftIO $ ((return $ 1 + 1) :: IO Int) liftIO $ putStrLn ("Hello Right? " ++ (show two)) put two state <- get liftIO $ putStrLn ("State is " ++ (show state)) return () doeitherstatetest :: IO () doeitherstatetest = do val <- runEitherT (runStateT eitherstatetest 1) case val of (Left c) -> c; (Right c)-> putStrLn $ "result: "++(show c) return () data X m = X { xfoo :: m ()} xmonadTest :: X m -> m () xmonadTest x = xfoo x data X2 m = Maybe m type X2p m = Maybe m rwsTest :: IO () rwsTest = do (res, state, writer) <- runRWST myMonadBro 5 6.0 putStrLn $ "state is "++(show state) putStrLn $ "writer is "++(show writer) where myMonadBro :: RWST Int [String] Double IO () myMonadBro = do v <- ask put 7.0 tell ["my man!"] tell ["yo brah!"] let x = 1 tell [show x] return () --data Xz = Xz { mytype :: * }
redfish64/MpvLangLearn
Learn.hs
gpl-3.0
2,504
0
12
714
858
433
425
65
2
module Analysis.Graph.Plot where import Data.Packed.Vector (Vector, toList) import Graphics.Rendering.Plot import qualified Graphics.Rendering.Cairo as C import Graphics.Rendering.Pango.Enums import Graphics.UI.Gtk hiding (Circle, Cross) import Data.Colour.Names (red, lightgray) import Control.Monad.Trans -- Create a Figure containing a Plot of two Vector vx, vy -- For documentation see: -- http://hackage.haskell.org/package/plot-0.2.3/docs/Graphics-Rendering-Plot-Figure.html create :: Vector Double -> Vector Double -> [String] -> String -> String -> String -> Figure () create vx vy labels title xLabel yLabel = do withTitle $ setText title withPointDefaults $ setPointSize 1.0 setPlots 1 1 withPlot (1, 1) $ do --setLegend True SouthWest Inside addAxis XAxis (Side Lower) $ withAxisLabel $ setText xLabel addAxis YAxis (Side Lower) $ do withAxisLabel $ setText yLabel withGridLine Major $ do setDashStyle [Dash] setLineColour lightgray --setRange XAxis Lower Linear (min vx) (max vx) --setRange YAxis Lower Linear (min vy) (max vy) setDataset (vx, [point vy (Bullet, red)]) -- Circle, Box, Diamond, Asterisk, Triangle, Bullet, Top, Bot let annotation (x, y, label) = text (x, y) (do setText label setFontSize 8) in withAnnotations $ do mapM_ annotation $ zip3 (toList vx) (toList vy) labels setRangeFromData XAxis Lower Linear setRangeFromData YAxis Lower Linear -- Show a Plot instance in a window view graph = display $ render graph -- Write a plot to a file as PDF write filepath graph = writeFigure PDF filepath graph writeSVG filepath graph = writeFigure SVG filepath graph -- Create a window and show in it a renderable element like a Plot -- Mostly copied from https://github.com/amcphail/plot/blob/master/examples/Test4.hs display :: ((Int, Int) -> C.Render ()) -> IO () display r = do initGUI window <- windowNew set window [ windowTitle := "Plot" , windowDefaultWidth := 600 , windowDefaultHeight := 400 , containerBorderWidth := 1 ] frame <- frameNew containerAdd window frame canvas <- drawingAreaNew containerAdd frame canvas widgetModifyBg canvas StateNormal (Color 65535 65535 65535) widgetShowAll window on canvas exposeEvent $ tryEvent $ do s <- liftIO $ widgetGetSize canvas drw <- liftIO $ widgetGetDrawWindow canvas liftIO $ renderWithDrawable drw (r s) onDestroy window mainQuit mainGUI
acardona/haskell-lib
CATMAID/Analysis/Graph/Plot.hs
gpl-3.0
2,823
0
18
838
669
330
339
52
1
module PrimeFactors where primeFactors :: Integer -> [Integer] primeFactors = factors 2 factors :: Integer -> Integer -> [Integer] factors d n | n == 1 = [] | d * d > n = [n] | n `mod` d == 0 = d : factors d (n `div` d) | otherwise = factors (d + 1) n
ciderpunx/exercismo
src/PrimeFactors.hs
gpl-3.0
292
0
9
98
140
73
67
9
1
module LanguageDef.Interpreter (resolveAndRun, constructParseTree, VariableStore', VariableStore, patternMatchAll, evalExpression) where {- Interprets functions -} import Utils.All import LanguageDef.Data.LanguageDef import LanguageDef.Data.SyntacticForm hiding (assert') import LanguageDef.Data.ParseTree import LanguageDef.Data.SyntFormIndex import LanguageDef.Data.Function import LanguageDef.Data.Expression import LanguageDef.Utils.LocationInfo import LanguageDef.Utils.ExceptionInfo import LanguageDef.Utils.Grouper import LanguageDef.LangDefs import qualified LanguageDef.Builtins as Builtins import qualified Data.Map as M import Data.Map (Map) import Debug.Trace {- | The type representing a variable store >>> import LanguageDef.API >>> import LanguageDef.LangDefs >>> let testType x = (["TestLanguage"], x) >>> let createPT tp p = createParseTree testLanguage (testType tp) "?" p & crash' & removeHidden >>> let createExp tp e = createTypedExpression testLanguage "?" e (testType tp) & crash' >>> let t te e tpt pt = patternMatch testLanguage M.empty (createExp te e) (createPT tpt pt) >>> t "bool" "\"True\"" "bool" "True" Success (fromList []) >>> t "bool" "\"True\"" "bool" "False" Failed (ExceptionInfo {_errMsg = "Argument does not match expected token\nExpected: True\nGot: False\n", _errSeverity = Error, _errSuggestion = Nothing}) >>> t "bool" "x" "bool" "True" Success (fromList [("x",RuleEnter {_pt = Literal {_ptToken = "True", _ptLocation = ..., _ptUsedRule = (["TestLanguage"],"bool"), _ptUsedIndex = 0, _ptLocation = ...})]) >>> t "bool" "_" "bool" "True" Success (fromList []) >>> t "bool" "(x:bool)" "bool" "True" Success (fromList [("x",RuleEnter {_pt = Literal {_ptToken = "True", _ptLocation = ...}, _ptUsedRule = (["TestLanguage"],"bool"), _ptUsedIndex = 0, ...})]) >>> t "bool" "(x:bool)" "int" "5" Failed (ExceptionInfo {_errMsg = "Ascription failed\nExpected something of type TestLanguage.bool\nbut got a parsetree of the form TestLanguage.int\n", _errSeverity = Error, _errSuggestion = Nothing}) >>> t "bool" "(x:bool)" "expr" "True" Success (fromList [("x",RuleEnter {_pt = RuleEnter {_pt = Literal {_ptToken = "True", ..., _ptHidden = False}, _ptUsedRule = (["TestLanguage"],"bool"), _ptUsedIndex = 0, ...}, _ptUsedRule = (["TestLanguage"],"expr"), _ptUsedIndex = 0, ...})]) >>> t "bool" "(x:bool)" "expr" "5" Failed (ExceptionInfo {_errMsg = "Ascription failed\nExpected something of type TestLanguage.bool\nbut got a parsetree of the form TestLanguage.int\n", _errSeverity = Error, _errSuggestion = Nothing}) >>> t "bool" "x&(y:bool)" "bool" "True" Success (fromList [("x",RuleEnter {_pt = Literal {_ptToken = "True", ..., _ptHidden = False}, _ptUsedRule = (["TestLanguage"],"bool"), _ptUsedIndex = 0, ...}),("y",RuleEnter {_pt = Literal {_ptToken = "True", ..., _ptHidden = False}, _ptUsedRule = (["TestLanguage"],"bool"), _ptUsedIndex = 0, ...})]) >>> t "exprSum" "x \"+\" y" "exprSum" "5 + 6 + 7" Success (fromList [("x",RuleEnter {_pt = RuleEnter {_pt = Int {_ptInt = 5, ...}, _ptUsedRule = (["TestLanguage"],"int"), _ptUsedIndex = 0, ...}, _ptUsedRule = (["TestLanguage"],"expr"), _ptUsedIndex = 1, ...}),("y",RuleEnter {_pt = Seq {_pts = [RuleEnter {_pt = RuleEnter {_pt = Int {_ptInt = 6, ...}, _ptUsedRule = (["TestLanguage"],"int"), _ptUsedIndex = 0, ...}, _ptUsedRule = (["TestLanguage"],"expr"), _ptUsedIndex = 1, ...},RuleEnter {_pt = Literal {_ptToken = "+", ..., _ptHidden = False}, _ptUsedRule = (["TestLanguage"],"op"), _ptUsedIndex = 1, ...},RuleEnter {_pt = RuleEnter {_pt = RuleEnter {_pt = Int {_ptInt = 7, ...}, _ptUsedRule = (["TestLanguage"],"int"), _ptUsedIndex = 0, ...}, _ptUsedRule = (["TestLanguage"],"expr"), _ptUsedIndex = 1, ...}, _ptUsedRule = (["TestLanguage"],"exprSum"), _ptUsedIndex = 1, ...}], ...}, _ptUsedRule = (["TestLanguage"],"exprSum"), _ptUsedIndex = 0, ...})]) >>> tNot arg = resolveAndRun testLanguage (["TestLanguage"], "not") [createPT "expr" arg] & crash' & toParsable >>> tNot "True" "False" >>> tNot "False" "True" >>> let tNand a b = resolveAndRun testLanguage (["TestLanguage"], "nand") [createPT "expr" a, createPT "expr" b] & crash' & toParsable >>> tNand "False" "False" "True" >>> tNand "True" "False" "True" >>> tNand "False" "True" "True" >>> tNand "True" "True" "False" >>> let tOr a b = resolveAndRun testLanguage (["TestLanguage"], "or") [createPT "expr" a, createPT "expr" b] & crash' & toParsable >>> tOr "True" "True" "True" >>> tOr "True" "False" "True" >>> tOr "False" "True" "True" >>> tOr "False" "False" "False" -} type VariableStore' a = Map Name (ParseTree' a) type VariableStore = VariableStore' SyntFormIndex -------------------------- ABOUT RUNNING A FUNCTION ------------------------------------ {- This function is passed to the builtins, which select it when appropriate It provides the implementation of parsing a string at runtime -} parseDynamic :: LDScope -> String -> String -> Failable ParseTree parseDynamic lds contents fqnString = inMsg' "While using the builtin parsing-at-runtime function:" $ do let fqn' = fqnString & uncalate '.' let fqn = (init fqn', last fqn') resolvedFQN <- resolve lds syntaxCall fqn inMsg' ("While parsing "++showFQ resolvedFQN) $ parseTarget lds resolvedFQN "<runtime invocation>" contents {- | Resolves the function, executes it. The first arguments adds an annotation to the parsetree, based on the type of the parsetree -} resolveAndRun :: LDScope -> FQName -> [ParseTree] -> Failable ParseTree resolveAndRun lds fqn@(targetLD, name) args | fqn `M.member` Builtins.functions = do builtin <- checkExists' fqn Builtins.functions "Wut? We just made sure this builtin function has this key?" builtin (parseDynamic lds) args | otherwise = do ld <- checkExistsSugg' dots targetLD (get environment lds) ("The module "++dots targetLD++" was not found") let ld' = ld & get ldScope :: LanguageDef let msg = "The module "++dots targetLD++" does not have a function section and thus does not define "++name funcs <- ld' & get langFunctions & maybe (fail msg) return func <- checkExistsSuggDist' (show, levenshtein) name (get grouperDict funcs) $ "The module "++dots targetLD++" does not define the function "++show name runFunction lds ld' func args runFunction :: LDScope -> LanguageDef -> Function -> [ParseTree] -> Failable ParseTree runFunction lds ld func args = inMsg' ("While executing the function "++get funcName func++" with arguments "++ argumentsToString args) $ inLocation (get (funcDoc . miLoc) func) $ do let clauses = func & get funcClauses clauses & mapi |> flip (runClause lds ld) args & firstSuccess runClause :: LDScope -> LanguageDef -> (Int, FunctionClause) -> [ParseTree] -> Failable ParseTree runClause lds ld (i, FunctionClause pats result doc nm) args = inMsg' ("While trying clause "++ nm ++ "." ++ show i) $ inLocation (get miLoc doc) $ do store <- patternMatchAll lds M.empty pats args constructParseTree lds store result argumentsToString :: [ParseTree] -> String argumentsToString pts = pts |> toParsable |> take 20 & commas |> (\c -> if c == '\n' then '§' else c) ------------------------- ABOUT PARSETREE CONSTRUCTION/INTERPRETATION -------------------------------- evalExpression :: LDScope -> Expression -> Failable ParseTree evalExpression langs = constructParseTree langs M.empty constructParseTree :: LDScope -> VariableStore -> Expression -> Failable ParseTree constructParseTree _ vars (Var nm _ _) = checkExistsSuggDist' (show, levenshtein) nm vars ("No variable "++show nm++" is in scope here") constructParseTree _ _ DontCare{} = fail "Found a wildcard (_) in an expression context. Only use these as patterns!" constructParseTree _ _ (ParseTree pt b _) = do let a = b pt |> const a & return constructParseTree lds vars (FuncCall func args _ _) = do args' <- args |+> constructParseTree lds vars resolveAndRun lds func args' constructParseTree lds vars (Ascription expr expTp _ _) = do pt <- constructParseTree lds vars expr -- At first glance, it might look as if the typechecker ensures this correctenss and ascriptions are useless -- However, ascription might be used as a predicate on rules, so this must be checked after all let actTp = get (ptA . syntIndForm) pt let ld = get ldScope lds assertSugg' (isSubtypeOf ld actTp expTp) ("Ascription failed: unexpected type "++showFQ actTp++" of value "++toParsable pt++ "\nThis value is constructed by the expresson "++toParsable expr , "Use an expression which results in a "++showFQ expTp++" instead") return pt constructParseTree lds vars (Split exp1 exp2 _ _) = do pt1 <- constructParseTree lds vars exp1 pt2 <- constructParseTree lds vars exp2 let pt1' = bareInformation pt1 let pt2' = bareInformation pt2 assert' (pt1' == pt2') $ unlines ["When a split is used in an expression context, both generated results should be the same" , "First result: "++toParsable pt1' ,"Generated by: "++toParsable exp1 , "Second result: "++toParsable pt2' , "Generated by: "++toParsable exp2] return pt1 constructParseTree lds vars (SeqExp exprs b _) = do pts <- exprs |> constructParseTree lds vars & allGood return $ Seq pts unknownLocation b ------------------------ ABOUT PATTERN MATCHING --------------------------------------- patternMatchAll :: LDScope -> VariableStore -> [Expression] -> [ParseTree] -> Failable VariableStore patternMatchAll lds store [] [] = return store patternMatchAll lds store (expr:exprs) (arg:args) = inLocation (get expLocation expr) $ do assert' (length exprs == length args) $ "Number of arguments is incorrect: got "++show (length args)++" patterns, but got "++show (length exprs)++" arguments" store' <- patternMatch lds store expr arg mergedStores <- mergeStores [store, store'] patternMatchAll lds mergedStores exprs args patternMatch :: LDScope -> VariableStore -> Expression -> ParseTree -> Failable VariableStore patternMatch _ _ (Var nm _ _) pt = return $ M.singleton nm pt patternMatch _ _ (DontCare _ _) _ = return M.empty patternMatch _ _ (ParseTree expectedPT _ _) actPt = do let exp = expectedPT & bareInformation let act = actPt & bareInformation assert' (exp == act) $ unlines ["Argument does not match expected token" , "Expected: "++toParsable exp , "Got: "++toParsable act] return M.empty patternMatch lds vars (FuncCall funcName args b _) arg = inMsg' ("While running a function within a pattern, namely "++showFQ funcName) $ do argsPt <- args |+> constructParseTree lds vars expectedPT <- resolveAndRun lds funcName argsPt |> deAnnot patternMatch lds vars (ParseTree expectedPT b unknownLocation) arg patternMatch lds vars (Ascription expr expType _ _) re@RuleEnter{} = do let actType = re & mostSpecificRuleEnter & get ptUsedRule assert' (isSubtypeOf (get ldScope lds) actType expType) $ unlines ["Ascription failed" , "Expected something of type "++showFQ expType , "but got a parsetree of the form "++showFQ actType] patternMatch lds vars expr re patternMatch lds vars (Split exp1 exp2 _ _) pt = do store1 <- patternMatch lds vars exp1 pt vars' <- mergeStores [store1, vars] store2 <- patternMatch lds vars' exp2 pt mergeStores [store1, store2] patternMatch lds vars (SeqExp exprs _ _) (Seq pts _ _) = patternMatchAll lds vars exprs pts patternMatch lds vars expr (RuleEnter pt _ _ _ _) = patternMatch lds vars expr pt patternMatch _ _ expr pt = fail $ "Could not match pattern "++debug expr++" with expression "++debug pt mergeStores :: [VariableStore' b] -> Failable (VariableStore' b) mergeStores stores = do let stores' = stores ||>> return & M.unionsWith sameBareInfo stores' & M.toList |> sndEffect & allGood |> M.fromList sameBareInfo :: Failable (ParseTree' a) -> Failable (ParseTree' a) -> Failable (ParseTree' a) sameBareInfo expectedPt actPt = do exp <- expectedPt |> bareInformation act <- actPt |> bareInformation assert' (exp == act) $ unlines ["Variable store elements are not the same:" , "First instance: "++toParsable exp , "Other instance: "++toParsable act] actPt
pietervdvn/ALGT2
src/LanguageDef/Interpreter.hs
gpl-3.0
12,149
414
11
1,982
2,463
1,347
1,116
153
2
{-# LANGUAGE ScopedTypeVariables #-} import Control.Exception (SomeException) import Control.Monad.Catch (throwM, try) import Data.Functor (void) import Data.Monoid ((<>)) import System.Directory (doesFileExist) import RSCoin.Core (SecretKey, defaultSecretKeyPath, initLogging, keyGen, readSecretKey, readSecretKey, writePublicKey, writeSecretKey) import qualified RSCoin.Core.Types as T import qualified RSCoin.Mintette as M import qualified MintetteOptions as Opts main :: IO () main = do opts@Opts.Options{..} <- Opts.getOptions initLogging cloLogSeverity let ctxArg = if cloDefaultContext then M.CADefault else M.CACustomLocation cloConfigPath case cloCommand of Opts.Serve serveOpts -> mainServe ctxArg serveOpts opts Opts.DumpStatistics -> mainDumpStatistics ctxArg opts Opts.CreatePermissionKeypair -> mainCreatePermissionKeypair ctxArg opts Opts.AddToBank addToBankOpts -> mainAddToBank ctxArg addToBankOpts opts mainServe :: M.ContextArgument -> Opts.ServeOptions -> Opts.Options -> IO () mainServe ctxArg Opts.ServeOptions {..} Opts.Options {..} = do skEither <- try $ readSecretKey cloSecretKeyPath sk <- case skEither of Left (_ :: SomeException) | cloAutoCreateKey -> createKeypair cloSecretKeyPath Left err -> throwM err Right sk -> return sk let dbPath = if cloMemMode then Nothing else Just cloPath env = M.mkRuntimeEnv cloActionLogsLimit sk cloPermittedAddrs M.launchMintetteReal cloRebuildDB cloPort env dbPath ctxArg mainAddToBank :: M.ContextArgument -> Opts.AddToBankOptions -> Opts.Options -> IO () mainAddToBank ctxArg Opts.AddToBankOptions {..} Opts.Options {..} = do sk <- readSecretKey atboSecretKeyPath M.addToBank ctxArg sk $ T.Mintette atboMintetteHost atboMintettePort mainDumpStatistics :: M.ContextArgument -> Opts.Options -> IO () mainDumpStatistics ctxArg Opts.Options {..} = do M.dumpStorageStatistics cloRebuildDB cloPath ctxArg mainCreatePermissionKeypair :: M.ContextArgument -> Opts.Options -> IO () mainCreatePermissionKeypair _ Opts.Options {..} = do directory <- defaultSecretKeyPath void $ createKeypair directory -- TODO: should this go to RSCoin.Core.Crypto.Signing? createKeypair :: FilePath -> IO SecretKey createKeypair directory = do let fpSecret = directory let fpPublic = directory <> ".pub" putStrLn $ "Generating secret key at " ++ fpSecret putStrLn $ "Generating public key at " ++ fpPublic secretKeyExists <- doesFileExist fpSecret if secretKeyExists then do putStrLn "Secret key already exists, not overwriting." readSecretKey fpSecret else do (sk, pk) <- keyGen writePublicKey fpPublic pk writeSecretKey fpSecret sk putStrLn "Done." return sk
input-output-hk/rscoin-haskell
src/Mintette/Main.hs
gpl-3.0
3,139
1
13
849
764
376
388
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Implementation of the @Bruce@ binary protocol. -- -- cf. <https://github.com/tagged/bruce/blob/master/doc/sending_messages.md> module Network.Bruce.Protocol ( -- * Protocol Types Message (..) , Topic (..) , Timestamp (..) , Payload (..) , Partition (..) -- * Partial decoding, e.g. when reading from a socket , decodeSize , decodeBody ) where import Control.Applicative import Control.Monad import Data.ByteString.Lazy (ByteString) import Data.Int import Data.Maybe (fromMaybe) import Data.Serialize import Data.String import qualified Data.ByteString.Lazy as B ------------------------------------------------------------------------------- -- Types -- | A @bruce@ protocol message. data Message = Message { messageTopic :: !Topic , messageTimestamp :: !Timestamp , messagePayload :: !Payload , messagePartition :: !Partition , messageKey :: !(Maybe ByteString) } deriving (Eq, Show) instance Serialize Message where put = encodeMessage get = decodeMessage -- | The Kafka topic that the message is targeted at. newtype Topic = Topic { unTopic :: ByteString } deriving (Eq, IsString, Show) -- | The timestamp for the message, represented as milliseconds -- since the epoch (January 1 1970 12:00am UTC). newtype Timestamp = Timestamp { unTimestamp :: Int64 } deriving (Eq, Num, Ord, Show) -- | The message payload. newtype Payload = Payload { unPayload :: ByteString } deriving (Eq, IsString, Show) -- | The partition selection strategy for a 'Message'. -- ... data Partition = AnyPartition | PartitionKey !Int32 deriving (Eq, Show) ------------------------------------------------------------------------------- -- Encoding encodeMessage :: Putter Message encodeMessage m = let m' = runPutLazy (encodeBody m) in encodeSize m' >> putLazyByteString m' encodeSize :: Putter ByteString encodeSize = put . (+4) . len32 encodeBody :: Putter Message encodeBody m = do encodeApiKey msgType encodeApiVersion (Version 0) encodeFlags (Flags 0) encodePartition (messagePartition m) encodeTopic (messageTopic m) encodeTimestamp (messageTimestamp m) encodeKey (messageKey m) encodePayload (messagePayload m) where msgType = case messagePartition m of AnyPartition -> AnyPartitionType PartitionKey _ -> PartitionKeyType encodeApiKey :: Putter MessageType encodeApiKey AnyPartitionType = put (256 :: Int16) encodeApiKey PartitionKeyType = put (257 :: Int16) encodeApiVersion :: Putter Version encodeApiVersion (Version v) = put v encodeFlags :: Putter Flags encodeFlags (Flags f) = put f encodePartition :: Putter Partition encodePartition AnyPartition = return () encodePartition (PartitionKey k) = put k encodeTopic :: Putter Topic encodeTopic (Topic t) = put (len16 t) >> putLazyByteString t encodeTimestamp :: Putter Timestamp encodeTimestamp (Timestamp t) = put t encodeKey :: Putter (Maybe ByteString) encodeKey (Just k) = put (len32 k) >> putLazyByteString k encodeKey Nothing = put (0 :: Int32) encodePayload :: Putter Payload encodePayload (Payload p) = put (len32 p) >> putLazyByteString p ------------------------------------------------------------------------------- -- Decoding decodeMessage :: Get Message decodeMessage = label "message" $ do s <- decodeSize b <- getBytes (fromIntegral s) either fail return (runGet decodeBody b) -- | Decode an 'Int32' representing the size of a (following) message body. decodeSize :: Get Int32 decodeSize = label "size" $ subtract 4 <$> get decodeBody :: Get Message decodeBody = do ak <- decodeApiKey av <- decodeApiVersion _ <- decodeFlags pk <- case (ak, av) of (AnyPartitionType, Version 0) -> return Nothing (PartitionKeyType, Version 0) -> Just <$> get _ -> fail $ "Unexpected (key, version): " ++ show (ak, av) tp <- decodeTopic ts <- decodeTimestamp mk <- decodeKey pl <- decodePayload let pt = fromMaybe AnyPartition (PartitionKey <$> pk) return $ Message tp ts pl pt mk decodeApiKey :: Get MessageType decodeApiKey = label "api-key" $ do k <- get :: Get Int16 case k of 256 -> return AnyPartitionType 257 -> return PartitionKeyType _ -> fail $ "Unexpected message type: " ++ show k decodeApiVersion :: Get Version decodeApiVersion = label "api-version" $ Version <$> get decodeFlags :: Get Flags decodeFlags = label "flags" $ do f <- Flags <$> get unless (f == noFlags) $ fail $ "Unexpected flags: " ++ show f return f decodeTopic :: Get Topic decodeTopic = label "topic" $ do len <- get :: Get Int16 Topic <$> getLazyByteString (fromIntegral len) decodeTimestamp :: Get Timestamp decodeTimestamp = label "timestamp" $ Timestamp <$> get decodeKey :: Get (Maybe ByteString) decodeKey = label "key" $ do len <- get :: Get Int32 if len == 0 then return Nothing else Just <$> getLazyByteString (fromIntegral len) decodePayload :: Get Payload decodePayload = label "payload" $ do len <- get :: Get Int32 Payload <$> getLazyByteString (fromIntegral len) ------------------------------------------------------------------------------- -- Utilities data MessageType = AnyPartitionType | PartitionKeyType deriving (Eq, Show) newtype Version = Version Int16 deriving (Eq, Show) newtype Flags = Flags Int16 deriving (Eq, Show) noFlags :: Flags noFlags = Flags 0 len16 :: ByteString -> Int16 len16 = fromIntegral . B.length len32 :: ByteString -> Int32 len32 = fromIntegral . B.length
romanb/bruce-protocol
src/Network/Bruce/Protocol.hs
mpl-2.0
5,745
0
13
1,233
1,550
797
753
160
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.GamesManagement.Scores.ResetAll -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Resets all scores for all leaderboards for the currently authenticated -- players. This method is only accessible to whitelisted tester accounts -- for your application. -- -- /See:/ <https://developers.google.com/games/services Google Play Game Services Management API Reference> for @gamesManagement.scores.resetAll@. module Network.Google.Resource.GamesManagement.Scores.ResetAll ( -- * REST Resource ScoresResetAllResource -- * Creating a Request , scoresResetAll , ScoresResetAll ) where import Network.Google.GamesManagement.Types import Network.Google.Prelude -- | A resource alias for @gamesManagement.scores.resetAll@ method which the -- 'ScoresResetAll' request conforms to. type ScoresResetAllResource = "games" :> "v1management" :> "scores" :> "reset" :> QueryParam "alt" AltJSON :> Post '[JSON] PlayerScoreResetAllResponse -- | Resets all scores for all leaderboards for the currently authenticated -- players. This method is only accessible to whitelisted tester accounts -- for your application. -- -- /See:/ 'scoresResetAll' smart constructor. data ScoresResetAll = ScoresResetAll' deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ScoresResetAll' with the minimum fields required to make a request. -- scoresResetAll :: ScoresResetAll scoresResetAll = ScoresResetAll' instance GoogleRequest ScoresResetAll where type Rs ScoresResetAll = PlayerScoreResetAllResponse type Scopes ScoresResetAll = '["https://www.googleapis.com/auth/games", "https://www.googleapis.com/auth/plus.login"] requestClient ScoresResetAll'{} = go (Just AltJSON) gamesManagementService where go = buildClient (Proxy :: Proxy ScoresResetAllResource) mempty
rueshyna/gogol
gogol-games-management/gen/Network/Google/Resource/GamesManagement/Scores/ResetAll.hs
mpl-2.0
2,682
0
12
570
229
144
85
42
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.YouTube.Videos.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of videos that match the API request parameters. -- -- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.videos.list@. module Network.Google.Resource.YouTube.Videos.List ( -- * REST Resource VideosListResource -- * Creating a Request , videosList , VideosList -- * Request Lenses , vlChart , vlPart , vlRegionCode , vlLocale , vlMyRating , vlMaxHeight , vlHl , vlOnBehalfOfContentOwner , vlVideoCategoryId , vlMaxWidth , vlId , vlPageToken , vlMaxResults ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.videos.list@ method which the -- 'VideosList' request conforms to. type VideosListResource = "youtube" :> "v3" :> "videos" :> QueryParam "part" Text :> QueryParam "chart" VideosListChart :> QueryParam "regionCode" Text :> QueryParam "locale" Text :> QueryParam "myRating" VideosListMyRating :> QueryParam "maxHeight" (Textual Word32) :> QueryParam "hl" Text :> QueryParam "onBehalfOfContentOwner" Text :> QueryParam "videoCategoryId" Text :> QueryParam "maxWidth" (Textual Word32) :> QueryParam "id" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] VideoListResponse -- | Returns a list of videos that match the API request parameters. -- -- /See:/ 'videosList' smart constructor. data VideosList = VideosList' { _vlChart :: !(Maybe VideosListChart) , _vlPart :: !Text , _vlRegionCode :: !(Maybe Text) , _vlLocale :: !(Maybe Text) , _vlMyRating :: !(Maybe VideosListMyRating) , _vlMaxHeight :: !(Maybe (Textual Word32)) , _vlHl :: !(Maybe Text) , _vlOnBehalfOfContentOwner :: !(Maybe Text) , _vlVideoCategoryId :: !Text , _vlMaxWidth :: !(Maybe (Textual Word32)) , _vlId :: !(Maybe Text) , _vlPageToken :: !(Maybe Text) , _vlMaxResults :: !(Textual Word32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'VideosList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vlChart' -- -- * 'vlPart' -- -- * 'vlRegionCode' -- -- * 'vlLocale' -- -- * 'vlMyRating' -- -- * 'vlMaxHeight' -- -- * 'vlHl' -- -- * 'vlOnBehalfOfContentOwner' -- -- * 'vlVideoCategoryId' -- -- * 'vlMaxWidth' -- -- * 'vlId' -- -- * 'vlPageToken' -- -- * 'vlMaxResults' videosList :: Text -- ^ 'vlPart' -> VideosList videosList pVlPart_ = VideosList' { _vlChart = Nothing , _vlPart = pVlPart_ , _vlRegionCode = Nothing , _vlLocale = Nothing , _vlMyRating = Nothing , _vlMaxHeight = Nothing , _vlHl = Nothing , _vlOnBehalfOfContentOwner = Nothing , _vlVideoCategoryId = "0" , _vlMaxWidth = Nothing , _vlId = Nothing , _vlPageToken = Nothing , _vlMaxResults = 5 } -- | The chart parameter identifies the chart that you want to retrieve. vlChart :: Lens' VideosList (Maybe VideosListChart) vlChart = lens _vlChart (\ s a -> s{_vlChart = a}) -- | The part parameter specifies a comma-separated list of one or more video -- resource properties that the API response will include. If the parameter -- identifies a property that contains child properties, the child -- properties will be included in the response. For example, in a video -- resource, the snippet property contains the channelId, title, -- description, tags, and categoryId properties. As such, if you set -- part=snippet, the API response will contain all of those properties. vlPart :: Lens' VideosList Text vlPart = lens _vlPart (\ s a -> s{_vlPart = a}) -- | The regionCode parameter instructs the API to select a video chart -- available in the specified region. This parameter can only be used in -- conjunction with the chart parameter. The parameter value is an ISO -- 3166-1 alpha-2 country code. vlRegionCode :: Lens' VideosList (Maybe Text) vlRegionCode = lens _vlRegionCode (\ s a -> s{_vlRegionCode = a}) -- | DEPRECATED vlLocale :: Lens' VideosList (Maybe Text) vlLocale = lens _vlLocale (\ s a -> s{_vlLocale = a}) -- | Set this parameter\'s value to like or dislike to instruct the API to -- only return videos liked or disliked by the authenticated user. vlMyRating :: Lens' VideosList (Maybe VideosListMyRating) vlMyRating = lens _vlMyRating (\ s a -> s{_vlMyRating = a}) -- | The maxHeight parameter specifies a maximum height of the embedded -- player. If maxWidth is provided, maxHeight may not be reached in order -- to not violate the width request. vlMaxHeight :: Lens' VideosList (Maybe Word32) vlMaxHeight = lens _vlMaxHeight (\ s a -> s{_vlMaxHeight = a}) . mapping _Coerce -- | The hl parameter instructs the API to retrieve localized resource -- metadata for a specific application language that the YouTube website -- supports. The parameter value must be a language code included in the -- list returned by the i18nLanguages.list method. If localized resource -- details are available in that language, the resource\'s -- snippet.localized object will contain the localized values. However, if -- localized details are not available, the snippet.localized object will -- contain resource details in the resource\'s default language. vlHl :: Lens' VideosList (Maybe Text) vlHl = lens _vlHl (\ s a -> s{_vlHl = a}) -- | Note: This parameter is intended exclusively for YouTube content -- partners. The onBehalfOfContentOwner parameter indicates that the -- request\'s authorization credentials identify a YouTube CMS user who is -- acting on behalf of the content owner specified in the parameter value. -- This parameter is intended for YouTube content partners that own and -- manage many different YouTube channels. It allows content owners to -- authenticate once and get access to all their video and channel data, -- without having to provide authentication credentials for each individual -- channel. The CMS account that the user authenticates with must be linked -- to the specified YouTube content owner. vlOnBehalfOfContentOwner :: Lens' VideosList (Maybe Text) vlOnBehalfOfContentOwner = lens _vlOnBehalfOfContentOwner (\ s a -> s{_vlOnBehalfOfContentOwner = a}) -- | The videoCategoryId parameter identifies the video category for which -- the chart should be retrieved. This parameter can only be used in -- conjunction with the chart parameter. By default, charts are not -- restricted to a particular category. vlVideoCategoryId :: Lens' VideosList Text vlVideoCategoryId = lens _vlVideoCategoryId (\ s a -> s{_vlVideoCategoryId = a}) -- | The maxWidth parameter specifies a maximum width of the embedded player. -- If maxHeight is provided, maxWidth may not be reached in order to not -- violate the height request. vlMaxWidth :: Lens' VideosList (Maybe Word32) vlMaxWidth = lens _vlMaxWidth (\ s a -> s{_vlMaxWidth = a}) . mapping _Coerce -- | The id parameter specifies a comma-separated list of the YouTube video -- ID(s) for the resource(s) that are being retrieved. In a video resource, -- the id property specifies the video\'s ID. vlId :: Lens' VideosList (Maybe Text) vlId = lens _vlId (\ s a -> s{_vlId = a}) -- | The pageToken parameter identifies a specific page in the result set -- that should be returned. In an API response, the nextPageToken and -- prevPageToken properties identify other pages that could be retrieved. -- Note: This parameter is supported for use in conjunction with the -- myRating and chart parameters, but it is not supported for use in -- conjunction with the id parameter. vlPageToken :: Lens' VideosList (Maybe Text) vlPageToken = lens _vlPageToken (\ s a -> s{_vlPageToken = a}) -- | The maxResults parameter specifies the maximum number of items that -- should be returned in the result set. Note: This parameter is supported -- for use in conjunction with the myRating and chart parameters, but it is -- not supported for use in conjunction with the id parameter. vlMaxResults :: Lens' VideosList Word32 vlMaxResults = lens _vlMaxResults (\ s a -> s{_vlMaxResults = a}) . _Coerce instance GoogleRequest VideosList where type Rs VideosList = VideoListResponse type Scopes VideosList = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtubepartner"] requestClient VideosList'{..} = go (Just _vlPart) _vlChart _vlRegionCode _vlLocale _vlMyRating _vlMaxHeight _vlHl _vlOnBehalfOfContentOwner (Just _vlVideoCategoryId) _vlMaxWidth _vlId _vlPageToken (Just _vlMaxResults) (Just AltJSON) youTubeService where go = buildClient (Proxy :: Proxy VideosListResource) mempty
rueshyna/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/Videos/List.hs
mpl-2.0
10,442
0
24
2,592
1,362
796
566
172
1
{-# Language CPP, OverloadedStrings, NamedFieldPuns, RecordWildCards #-} module PrivateCloud.Cloud.DirTree ( makeTree , unrollTreeFiles ) where import Data.List import Data.Function import System.Directory.Tree #ifdef WINBUILD import System.Directory import System.Win32.File #else import System.Posix.Files #endif import PrivateCloud.Provider.Types unrollTreeFiles :: DirTree (Maybe LocalFileInfo) -> LocalFileList unrollTreeFiles tree = go (EntryName "") tree{name = ""} where go base File{name, file = Just f} = [(base <//> path2entry name, f)] go base Dir{..} = concatMap (go $ base <//> path2entry name) contents go _ _ = [] sortDirByName :: DirTree a -> DirTree a sortDirByName = transformDir sortD where sortD (Dir n cs) = Dir n (sortBy (compare `on` name) cs) sortD c = c makeTree :: FilePath -> IO (DirTree (Maybe LocalFileInfo)) makeTree root = do _ :/ tree <- readDirectoryWith makeFileInfo root pure $ sortDirByName tree makeFileInfo :: FilePath -> IO (Maybe LocalFileInfo) #ifdef WINBUILD makeFileInfo path = do isFile <- doesFileExist path if isFile then do mtime <- getModificationTime path size <- fadFileSize <$> getFileAttributesExStandard path pure $ Just LocalFileInfo { lfLength = size , lfModTime = utc2ts mtime } else pure Nothing #else makeFileInfo path = do st <- getFileStatus path pure $ if isRegularFile st then Just LocalFileInfo { lfLength = fromIntegral $ fileSize st , lfModTime = epoch2ts $ modificationTime st } else Nothing #endif
rblaze/private-cloud
src/PrivateCloud/Cloud/DirTree.hs
apache-2.0
1,685
0
14
433
420
218
202
30
3
module Parse.Location ( -- * Location Location(..) , Path -- * Located , HasLocation(..) , getLocation , getLine , getColumn , Located(..) , dislocate ) where import Prelude hiding (getLine) -- | An inhabitant of this type describes where a character is in a text file. data Location = MkLocation { -- | Path to the file. path :: Path , -- | Line number starting from one. line :: Int , -- | Column number starting from one. column :: Int } deriving (Read, Show) -- | A path in a file system. type Path = String class HasLocation a where -- | Get the associated 'Location'. locate :: a -> Location -- | This product type adds 'Location' information to another type. data Located a = MkLocated Location a deriving (Read, Show) instance Functor Located where fmap f (MkLocated a b) = MkLocated a (f b) instance HasLocation (Located a) where locate (MkLocated x _) = x dislocate :: Located a -> a dislocate (MkLocated _ x) = x getLocation :: (HasLocation a) => a -> Location getLocation = locate getColumn :: (HasLocation a) => a -> Int getColumn = column . locate getLine :: (HasLocation a) => a -> Int getLine = line . locate
edom/ptt
src/Parse/Location.hs
apache-2.0
1,283
0
8
366
319
184
135
35
1
{-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE GADTs #-} module Data.Predictor ( Occ(..) ) where import GHC.Prim (Constraint) import Data.Map as Map import Data.Semigroup hiding (All) type family All (p :: a -> Constraint) (as :: [a]) :: Constraint type instance All p '[] = () type instance All p (a ': as) = (p a, All p as) data Example :: [*] -> * where Done :: Example '[] Has :: a -> Example as -> Example (a ': as) Hasn't :: Example as -> Example (a ': as) instance All Show as => Show (Example as) where showsPrec d Done = showString "Done" showsPrec d (Has a as) = showParen (d > 10) $ showString "Has " . showsPrec 11 a . showChar ' ' . showsPrec 11 as showsPrec d (Hasn't as) = showParen (d > 10) $ showString "Hasn't " . showsPrec 11 as class Occurs t where occ :: t as -> Occ as instance Occurs Example where occ Done = Nil 1 occ (Has a as) = Occ 1 $ Map.singleton (Just a) (occ as) occ (Hasn't as) = Occ 1 $ Map.singleton Nothing (occ as) data Occ :: [*] -> * where Nil :: Int -> Occ '[] Occ :: Int -> Map (Maybe a) (Occ as) -> Occ (a ': as) instance Occurs Occ where occ = id instance Monoid (Occ as) => Semigroup (Occ as) where (<>) = mappend instance Monoid (Occ '[]) where mempty = Nil 0 mappend (Nil n) (Nil m) = Nil (n + m) instance (Ord a, Monoid (Occ as)) => Monoid (Occ (a ': as)) where mempty = Occ 0 Map.empty mappend (Occ n as) (Occ m bs) = Occ (n + m) (Map.unionWith mappend as bs) instance All Show as => Show (Occ as) where showsPrec d (Nil n) = showParen (d > 10) $ showString "Nil " . showsPrec 11 n showsPrec d (Occ n as) = showParen (d > 10) $ showString "Occ " . showsPrec 11 n . showString " $ " . showsPrec 1 as bob, nobody :: Example [String, Int] bob = Has "Bob" (Has 60 Done) nobody = Hasn't (Has 73 Done)
ekmett/predictors
src/Data/Predictor.hs
bsd-2-clause
2,077
0
12
472
928
480
448
-1
-1
{-# LANGUAGE ParallelListComp, TemplateHaskell, RankNTypes #-} {-| TemplateHaskell helper for Ganeti Haskell code. As TemplateHaskell require that splices be defined in a separate module, we combine all the TemplateHaskell functionality that HTools needs in this module (except the one for unittests). -} {- Copyright (C) 2011, 2012, 2013, 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.THH ( declareSADT , declareLADT , declareILADT , declareIADT , makeJSONInstance , deCamelCase , genOpID , genOpLowerStrip , genAllConstr , genAllOpIDs , PyValue(..) , PyValueEx(..) , OpCodeField(..) , OpCodeDescriptor(..) , genOpCode , genStrOfOp , genStrOfKey , genLuxiOp , Field (..) , simpleField , andRestArguments , withDoc , defaultField , notSerializeDefaultField , presentInForthcoming , optionalField , optionalNullSerField , makeOptional , renameField , customField , buildObject , buildObjectWithForthcoming , buildObjectSerialisation , buildParam , genException , excErrMsg , ssconfConstructorName ) where import Control.Arrow ((&&&), second) import Control.Applicative import Control.Lens.Type (Lens, Lens') import Control.Lens (lens, set, element) import Control.Monad import Control.Monad.Base () -- Needed to prevent spurious GHC linking errors. import Control.Monad.Fail (MonadFail) import Control.Monad.Writer (tell) import qualified Control.Monad.Trans as MT import Data.Attoparsec.Text () -- Needed to prevent spurious GHC 7.4 linking errors. -- See issue #683 and https://ghc.haskell.org/trac/ghc/ticket/4899 import Data.Char import Data.Function (on) import Data.List import Data.Maybe import qualified Data.Map as M import qualified Data.Semigroup as Sem import qualified Data.Set as S import qualified Data.Text as T import Language.Haskell.TH import Language.Haskell.TH.Syntax (lift) import qualified Text.JSON as JSON import Text.JSON.Pretty (pp_value) import Ganeti.JSON (readJSONWithDesc, fromObj, DictObject(..), ArrayObject(..), maybeFromObj, mkUsedKeys, showJSONtoDict, readJSONfromDict, branchOnField, addField, allUsedKeys) import Ganeti.PartialParams import Ganeti.PyValue import Ganeti.THH.PyType import Ganeti.THH.Compat -- * Exported types -- | Optional field information. data OptionalType = NotOptional -- ^ Field is not optional | OptionalOmitNull -- ^ Field is optional, null is not serialised | OptionalSerializeNull -- ^ Field is optional, null is serialised | AndRestArguments -- ^ Special field capturing all the remaining fields -- as plain JSON values deriving (Show, Eq) -- | Serialised field data type describing how to generate code for the field. -- Each field has a type, which isn't captured in the type of the data type, -- but is saved in the 'Q' monad in 'fieldType'. -- -- Let @t@ be a type we want to parametrize the field with. There are the -- following possible types of fields: -- -- [Mandatory with no default.] Then @fieldType@ holds @t@, -- @fieldDefault = Nothing@ and @fieldIsOptional = NotOptional@. -- -- [Field with a default value.] Then @fieldType@ holds @t@ and -- @fieldDefault = Just exp@ where @exp@ is an expression of type @t@ and -- @fieldIsOptional = NotOptional@. -- -- [Optional, no default value.] Then @fieldType@ holds @Maybe t@, -- @fieldDefault = Nothing@ and @fieldIsOptional@ is either -- 'OptionalOmitNull' or 'OptionalSerializeNull'. -- -- Optional fields with a default value are prohibited, as their main -- intention is to represent the information that a request didn't contain -- the field data. -- -- /Custom (de)serialization:/ -- Field can have custom (de)serialization functions that are stored in -- 'fieldRead' and 'fieldShow'. If they aren't provided, the default is to use -- 'readJSON' and 'showJSON' for the field's type @t@. If they are provided, -- the type of the contained deserializing expression must be -- -- @ -- [(String, JSON.JSValue)] -> JSON.JSValue -> JSON.Result t -- @ -- -- where the first argument carries the whole record in the case the -- deserializing function needs to process additional information. -- -- The type of the contained serializing experssion must be -- -- @ -- t -> (JSON.JSValue, [(String, JSON.JSValue)]) -- @ -- -- where the result can provide extra JSON fields to include in the output -- record (or just return @[]@ if they're not needed). -- -- Note that for optional fields the type appearing in the custom functions -- is still @t@. Therefore making a field optional doesn't change the -- functions. -- -- There is also a special type of optional field 'AndRestArguments' which -- allows to parse any additional arguments not covered by other fields. There -- can be at most one such special field and it's type must be -- @Map String JSON.JSValue@. See also 'andRestArguments'. data Field = Field { fieldName :: T.Text , fieldType :: Q Type -- ^ the type of the field, @t@ for non-optional fields, -- @Maybe t@ for optional ones. , fieldRead :: Maybe (Q Exp) -- ^ an optional custom deserialization function of type -- @[(String, JSON.JSValue)] -> JSON.JSValue -> -- JSON.Result t@ , fieldShow :: Maybe (Q Exp) -- ^ an optional custom serialization function of type -- @t -> (JSON.JSValue, [(String, JSON.JSValue)])@ , fieldExtraKeys :: [T.Text] -- ^ a list of extra keys added by 'fieldShow' , fieldDefault :: Maybe (Q Exp) -- ^ an optional default value of type @t@ , fieldSerializeDefault :: Bool -- ^ whether not presented default value will be -- serialized , fieldConstr :: Maybe T.Text , fieldIsOptional :: OptionalType -- ^ determines if a field is optional, and if yes, -- how , fieldDoc :: T.Text , fieldPresentInForthcoming :: Bool } -- | Generates a simple field. simpleField :: String -> Q Type -> Field simpleField fname ftype = Field { fieldName = T.pack fname , fieldType = ftype , fieldRead = Nothing , fieldShow = Nothing , fieldExtraKeys = [] , fieldDefault = Nothing , fieldSerializeDefault = True , fieldConstr = Nothing , fieldIsOptional = NotOptional , fieldDoc = T.pack "" , fieldPresentInForthcoming = False } -- | Generate an AndRestArguments catch-all field. andRestArguments :: String -> Field andRestArguments fname = Field { fieldName = T.pack fname , fieldType = [t| M.Map String JSON.JSValue |] , fieldRead = Nothing , fieldShow = Nothing , fieldExtraKeys = [] , fieldDefault = Nothing , fieldSerializeDefault = True , fieldConstr = Nothing , fieldIsOptional = AndRestArguments , fieldDoc = T.pack "" , fieldPresentInForthcoming = True } withDoc :: String -> Field -> Field withDoc doc field = field { fieldDoc = T.pack doc } -- | Sets the renamed constructor field. renameField :: String -> Field -> Field renameField constrName field = field { fieldConstr = Just $ T.pack constrName } -- | Sets the default value on a field (makes it optional with a -- default value). defaultField :: Q Exp -> Field -> Field defaultField defval field = field { fieldDefault = Just defval } -- | A defaultField which will be serialized only if it's value differs from -- a default value. notSerializeDefaultField :: Q Exp -> Field -> Field notSerializeDefaultField defval field = field { fieldDefault = Just defval , fieldSerializeDefault = False } -- | Mark a field as present in the forthcoming variant. presentInForthcoming :: Field -> Field presentInForthcoming field = field { fieldPresentInForthcoming = True } -- | Marks a field optional (turning its base type into a Maybe). optionalField :: Field -> Field optionalField field = field { fieldIsOptional = OptionalOmitNull } -- | Marks a field optional (turning its base type into a Maybe), but -- with 'Nothing' serialised explicitly as /null/. optionalNullSerField :: Field -> Field optionalNullSerField field = field { fieldIsOptional = OptionalSerializeNull } -- | Make a field optional, if it isn't already. makeOptional :: Field -> Field makeOptional field = if and [ fieldIsOptional field == NotOptional , isNothing $ fieldDefault field , not $ fieldPresentInForthcoming field ] then optionalField field else field -- | Sets custom functions on a field. customField :: Name -- ^ The name of the read function -> Name -- ^ The name of the show function -> [String] -- ^ The name of extra field keys -> Field -- ^ The original field -> Field -- ^ Updated field customField readfn showfn extra field = field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn) , fieldExtraKeys = (map T.pack extra) } -- | Computes the record name for a given field, based on either the -- string value in the JSON serialisation or the custom named if any -- exists. fieldRecordName :: Field -> String fieldRecordName (Field { fieldName = name, fieldConstr = alias }) = maybe (camelCase . T.unpack $ name) T.unpack alias -- | Computes the preferred variable name to use for the value of this -- field. If the field has a specific constructor name, then we use a -- first-letter-lowercased version of that; otherwise, we simply use -- the field name. See also 'fieldRecordName'. fieldVariable :: Field -> String fieldVariable f = case (fieldConstr f) of Just name -> ensureLower . T.unpack $ name _ -> map (\c -> if c == '-' then '_' else c) . T.unpack . fieldName $ f -- | Compute the actual field type (taking into account possible -- optional status). actualFieldType :: Field -> Q Type actualFieldType f | fieldIsOptional f `elem` [NotOptional, AndRestArguments] = t | otherwise = [t| Maybe $t |] where t = fieldType f -- | Checks that a given field is not optional (for object types or -- fields which should not allow this case). checkNonOptDef :: (MonadFail m) => Field -> m () checkNonOptDef field | fieldIsOptional field == OptionalOmitNull = failWith kOpt | fieldIsOptional field == OptionalSerializeNull = failWith kOpt | isJust (fieldDefault field) = failWith kDef | otherwise = return () where failWith kind = fail $ kind ++ " field " ++ name ++ " used in parameter declaration" name = T.unpack (fieldName field) kOpt = "Optional" kDef = "Default" -- | Construct a function that parses a field value. If the field has -- a custom 'fieldRead', it's applied to @o@ and used. Otherwise -- @JSON.readJSON@ is used. parseFn :: Field -- ^ The field definition -> Q Exp -- ^ The entire object in JSON object format -> Q Exp -- ^ The resulting function that parses a JSON message parseFn field o = let fnType = [t| JSON.JSValue -> JSON.Result $(fieldType field) |] expr = maybe [| readJSONWithDesc $(stringE . T.unpack $ fieldName field) |] (`appE` o) (fieldRead field) in sigE expr fnType -- | Produces the expression that will de-serialise a given -- field. Since some custom parsing functions might need to use the -- entire object, we do take and pass the object to any custom read -- functions. loadFn :: Field -- ^ The field definition -> Q Exp -- ^ The value of the field as existing in the JSON message -> Q Exp -- ^ The entire object in JSON object format -> Q Exp -- ^ Resulting expression loadFn field expr o = [| $expr >>= $(parseFn field o) |] -- | Just as 'loadFn', but for optional fields. loadFnOpt :: Field -- ^ The field definition -> Q Exp -- ^ The value of the field as existing in the JSON message -- as Maybe -> Q Exp -- ^ The entire object in JSON object format -> Q Exp -- ^ Resulting expression loadFnOpt field@(Field { fieldDefault = Just def }) expr o = case fieldIsOptional field of NotOptional -> [| $expr >>= maybe (return $def) $(parseFn field o) |] _ -> fail $ "Field " ++ (T.unpack . fieldName $ field) ++ ":\ \ A field can't be optional and\ \ have a default value at the same time." loadFnOpt field expr o = [| $expr >>= maybe (return Nothing) (liftM Just . $(parseFn field o)) |] -- * Internal types -- | A simple field, in constrast to the customisable 'Field' type. type SimpleField = (String, Q Type) -- | A definition for a single constructor for a simple object. type SimpleConstructor = (String, [SimpleField]) -- | A definition for ADTs with simple fields. type SimpleObject = [SimpleConstructor] -- | A type alias for an opcode constructor of a regular object. type OpCodeConstructor = (String, Q Type, String, [Field], String) -- | A type alias for a Luxi constructor of a regular object. type LuxiConstructor = (String, [Field]) -- * Helper functions -- | Ensure first letter is lowercase. -- -- Used to convert type name to function prefix, e.g. in @data Aa -> -- aaToRaw@. ensureLower :: String -> String ensureLower [] = [] ensureLower (x:xs) = toLower x:xs -- | Ensure first letter is uppercase. -- -- Used to convert constructor name to component ensureUpper :: String -> String ensureUpper [] = [] ensureUpper (x:xs) = toUpper x:xs -- | fromObj (Ganeti specific) as an expression, for reuse. fromObjE :: Q Exp fromObjE = varE 'fromObj -- | ToRaw function name. toRawName :: String -> Name toRawName = mkName . (++ "ToRaw") . ensureLower -- | FromRaw function name. fromRawName :: String -> Name fromRawName = mkName . (++ "FromRaw") . ensureLower -- | Converts a name to it's varE\/litE representations. reprE :: Either String Name -> Q Exp reprE = either stringE varE -- | Apply a constructor to a list of expressions appCons :: Name -> [Exp] -> Exp appCons cname = foldl AppE (ConE cname) -- | Apply a constructor to a list of applicative expressions appConsApp :: Name -> [Exp] -> Exp appConsApp cname = foldl (\accu e -> InfixE (Just accu) (VarE '(<*>)) (Just e)) (AppE (VarE 'pure) (ConE cname)) -- | Builds a field for a normal constructor. buildConsField :: Q Type -> StrictTypeQ buildConsField ftype = do ftype' <- ftype return (myNotStrict, ftype') -- | Builds a constructor based on a simple definition (not field-based). buildSimpleCons :: Name -> SimpleObject -> Q Dec buildSimpleCons tname cons = do decl_d <- mapM (\(cname, fields) -> do fields' <- mapM (buildConsField . snd) fields return $ NormalC (mkName cname) fields') cons return $ gntDataD [] tname [] decl_d [''Show, ''Eq] -- | Generate the save function for a given type. genSaveSimpleObj :: Name -- ^ Object type -> String -- ^ Function name -> SimpleObject -- ^ Object definition -> (SimpleConstructor -> Q Clause) -- ^ Constructor save fn -> Q (Dec, Dec) genSaveSimpleObj tname sname opdefs fn = do let sigt = AppT (AppT ArrowT (ConT tname)) (ConT ''JSON.JSValue) fname = mkName sname cclauses <- mapM fn opdefs return $ (SigD fname sigt, FunD fname cclauses) -- * Template code for simple raw type-equivalent ADTs -- | Generates a data type declaration. -- -- The type will have a fixed list of instances. strADTDecl :: Name -> [String] -> Dec strADTDecl name constructors = gntDataD [] name [] (map (flip NormalC [] . mkName) constructors) [''Show, ''Eq, ''Enum, ''Bounded, ''Ord] -- | Generates a toRaw function. -- -- This generates a simple function of the form: -- -- @ -- nameToRaw :: Name -> /traw/ -- nameToRaw Cons1 = var1 -- nameToRaw Cons2 = \"value2\" -- @ genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec] genToRaw traw fname tname constructors = do let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw) -- the body clauses, matching on the constructor and returning the -- raw value clauses <- mapM (\(c, v) -> clause [recP (mkName c) []] (normalB (reprE v)) []) constructors return [SigD fname sigt, FunD fname clauses] -- | Generates a fromRaw function. -- -- The function generated is monadic and can fail parsing the -- raw value. It is of the form: -- -- @ -- nameFromRaw :: (Monad m) => /traw/ -> m Name -- nameFromRaw s | s == var1 = Cons1 -- | s == \"value2\" = Cons2 -- | otherwise = fail /.../ -- @ genFromRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec] genFromRaw traw fname tname constructors = do -- signature of form (Monad m) => String -> m $name sigt <- [t| forall m. (Monad m, MonadFail m) => $(conT traw) -> m $(conT tname) |] -- clauses for a guarded pattern let varp = mkName "s" varpe = varE varp clauses <- mapM (\(c, v) -> do -- the clause match condition g <- normalG [| $varpe == $(reprE v) |] -- the clause result r <- [| return $(conE (mkName c)) |] return (g, r)) constructors -- the otherwise clause (fallback) oth_clause <- do let err = "Invalid string value for type " ++ (nameBase tname) ++ ": " g <- normalG [| otherwise |] r <- [|fail $ $(litE (stringL err)) ++ show $varpe |] return (g, r) let fun = FunD fname [Clause [VarP varp] (GuardedB (clauses++[oth_clause])) []] return [SigD fname sigt, fun] -- | Generates a data type from a given raw format. -- -- The format is expected to multiline. The first line contains the -- type name, and the rest of the lines must contain two words: the -- constructor name and then the string representation of the -- respective constructor. -- -- The function will generate the data type declaration, and then two -- functions: -- -- * /name/ToRaw, which converts the type to a raw type -- -- * /name/FromRaw, which (monadically) converts from a raw type to the type -- -- Note that this is basically just a custom show\/read instance, -- nothing else. declareADT :: (a -> Either String Name) -> Name -> String -> [(String, a)] -> Q [Dec] declareADT fn traw sname cons = do let name = mkName sname ddecl = strADTDecl name (map fst cons) -- process cons in the format expected by genToRaw cons' = map (second fn) cons toraw <- genToRaw traw (toRawName sname) name cons' fromraw <- genFromRaw traw (fromRawName sname) name cons' return $ ddecl:toraw ++ fromraw declareLADT :: Name -> String -> [(String, String)] -> Q [Dec] declareLADT = declareADT Left declareILADT :: String -> [(String, Int)] -> Q [Dec] declareILADT sname cons = do consNames <- sequence [ newName ('_':n) | (n, _) <- cons ] consFns <- concat <$> sequence [ do sig <- sigD n [t| Int |] let expr = litE (IntegerL (toInteger i)) fn <- funD n [clause [] (normalB expr) []] return [sig, fn] | n <- consNames | (_, i) <- cons ] let cons' = [ (n, n') | (n, _) <- cons | n' <- consNames ] (consFns ++) <$> declareADT Right ''Int sname cons' declareIADT :: String -> [(String, Name)] -> Q [Dec] declareIADT = declareADT Right ''Int declareSADT :: String -> [(String, Name)] -> Q [Dec] declareSADT = declareADT Right ''String -- | Creates the showJSON member of a JSON instance declaration. -- -- This will create what is the equivalent of: -- -- @ -- showJSON = showJSON . /name/ToRaw -- @ -- -- in an instance JSON /name/ declaration genShowJSON :: String -> Q Dec genShowJSON name = do body <- [| JSON.showJSON . $(varE (toRawName name)) |] return $ FunD 'JSON.showJSON [Clause [] (NormalB body) []] -- | Creates the readJSON member of a JSON instance declaration. -- -- This will create what is the equivalent of: -- -- @ -- readJSON s = case readJSON s of -- Ok s' -> /name/FromRaw s' -- Error e -> Error /description/ -- @ -- -- in an instance JSON /name/ declaration genReadJSON :: String -> Q Dec genReadJSON name = do let s = mkName "s" body <- [| $(varE (fromRawName name)) =<< readJSONWithDesc $(stringE name) $(varE s) |] return $ FunD 'JSON.readJSON [Clause [VarP s] (NormalB body) []] -- | Generates a JSON instance for a given type. -- -- This assumes that the /name/ToRaw and /name/FromRaw functions -- have been defined as by the 'declareSADT' function. makeJSONInstance :: Name -> Q [Dec] makeJSONInstance name = do let base = nameBase name showJ <- genShowJSON base readJ <- genReadJSON base return [gntInstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]] -- * Template code for opcodes -- | Transforms a CamelCase string into an_underscore_based_one. deCamelCase :: String -> String deCamelCase = intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b) -- | Transform an underscore_name into a CamelCase one. camelCase :: String -> String camelCase = concatMap (ensureUpper . drop 1) . groupBy (\_ b -> b /= '_' && b /= '-') . ('_':) -- | Computes the name of a given constructor. constructorName :: Con -> Q Name constructorName (NormalC name _) = return name constructorName (RecC name _) = return name constructorName x = fail $ "Unhandled constructor " ++ show x -- | Extract all constructor names from a given type. reifyConsNames :: Name -> Q [String] reifyConsNames name = do reify_result <- reify name case extractDataDConstructors reify_result of Just cons -> mapM (liftM nameBase . constructorName) cons _ -> fail $ "Unhandled name passed to reifyConsNames, expected\ \ type constructor but got '" ++ show reify_result ++ "'" -- | Builds the generic constructor-to-string function. -- -- This generates a simple function of the following form: -- -- @ -- fname (ConStructorOne {}) = trans_fun("ConStructorOne") -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo") -- @ -- -- This builds a custom list of name\/string pairs and then uses -- 'genToRaw' to actually generate the function. genConstrToStr :: (String -> Q String) -> Name -> String -> Q [Dec] genConstrToStr trans_fun name fname = do cnames <- reifyConsNames name svalues <- mapM (liftM Left . trans_fun) cnames genToRaw ''String (mkName fname) name $ zip cnames svalues -- | Constructor-to-string for OpCode. genOpID :: Name -> String -> Q [Dec] genOpID = genConstrToStr (return . deCamelCase) -- | Strips @Op@ from the constructor name, converts to lower-case -- and adds a given prefix. genOpLowerStrip :: String -> Name -> String -> Q [Dec] genOpLowerStrip prefix = genConstrToStr (liftM ((prefix ++) . map toLower . deCamelCase) . stripPrefixM "Op") where stripPrefixM :: String -> String -> Q String stripPrefixM pfx s = maybe (fail $ s ++ " doesn't start with " ++ pfx) return $ stripPrefix pfx s -- | Builds a list with all defined constructor names for a type. -- -- @ -- vstr :: String -- vstr = [...] -- @ -- -- Where the actual values of the string are the constructor names -- mapped via @trans_fun@. genAllConstr :: (String -> String) -> Name -> String -> Q [Dec] genAllConstr trans_fun name vstr = do cnames <- reifyConsNames name let svalues = sort $ map trans_fun cnames vname = mkName vstr sig = SigD vname (AppT ListT (ConT ''String)) body = NormalB (ListE (map (LitE . StringL) svalues)) return $ [sig, ValD (VarP vname) body []] -- | Generates a list of all defined opcode IDs. genAllOpIDs :: Name -> String -> Q [Dec] genAllOpIDs = genAllConstr deCamelCase -- * Python code generation data OpCodeField = OpCodeField { ocfName :: String , ocfType :: PyType , ocfDefl :: Maybe PyValueEx , ocfDoc :: String } -- | Transfers opcode data between the opcode description (through -- @genOpCode@) and the Python code generation functions. data OpCodeDescriptor = OpCodeDescriptor { ocdName :: String , ocdType :: PyType , ocdDoc :: String , ocdFields :: [OpCodeField] , ocdDescr :: String } -- | Optionally encapsulates default values in @PyValueEx@. -- -- @maybeApp exp typ@ returns a quoted expression that encapsulates -- the default value @exp@ of an opcode parameter cast to @typ@ in a -- @PyValueEx@, if @exp@ is @Just@. Otherwise, it returns a quoted -- expression with @Nothing@. maybeApp :: Maybe (Q Exp) -> Q Type -> Q Exp maybeApp Nothing _ = [| Nothing |] maybeApp (Just expr) typ = [| Just ($(conE (mkName "PyValueEx")) ($expr :: $typ)) |] -- | Generates a Python type according to whether the field is -- optional. -- -- The type of created expression is PyType. genPyType' :: OptionalType -> Q Type -> Q PyType genPyType' opt typ = typ >>= pyOptionalType (opt /= NotOptional) -- | Generates Python types from opcode parameters. genPyType :: Field -> Q PyType genPyType f = genPyType' (fieldIsOptional f) (fieldType f) -- | Generates Python default values from opcode parameters. genPyDefault :: Field -> Q Exp genPyDefault f = maybeApp (fieldDefault f) (fieldType f) pyField :: Field -> Q Exp pyField f = genPyType f >>= \t -> [| OpCodeField $(stringE . T.unpack . fieldName $ f) t $(genPyDefault f) $(stringE . T.unpack . fieldDoc $ f) |] -- | Generates a Haskell function call to "showPyClass" with the -- necessary information on how to build the Python class string. pyClass :: OpCodeConstructor -> Q Exp pyClass (consName, consType, consDoc, consFields, consDscField) = do let consName' = stringE consName consType' <- genPyType' NotOptional consType let consDoc' = stringE consDoc [| OpCodeDescriptor $consName' consType' $consDoc' $(listE $ map pyField consFields) consDscField |] -- | Generates a function called "pyClasses" that holds the list of -- all the opcode descriptors necessary for generating the Python -- opcodes. pyClasses :: [OpCodeConstructor] -> Q [Dec] pyClasses cons = do let name = mkName "pyClasses" sig = SigD name (AppT ListT (ConT ''OpCodeDescriptor)) fn <- FunD name <$> (:[]) <$> declClause cons return [sig, fn] where declClause c = clause [] (normalB (ListE <$> mapM pyClass c)) [] -- | Converts from an opcode constructor to a Luxi constructor. opcodeConsToLuxiCons :: OpCodeConstructor -> LuxiConstructor opcodeConsToLuxiCons (x, _, _, y, _) = (x, y) -- | Generates 'DictObject' instance for an op-code. genOpCodeDictObject :: Name -- ^ Type name to use -> (LuxiConstructor -> Q Clause) -- ^ saving function -> (LuxiConstructor -> Q Exp) -- ^ loading function -> [LuxiConstructor] -- ^ Constructors -> Q [Dec] genOpCodeDictObject tname savefn loadfn cons = do tdclauses <- genSaveOpCode cons savefn fdclauses <- genLoadOpCode cons loadfn return [ gntInstanceD [] (AppT (ConT ''DictObject) (ConT tname)) [ FunD 'toDict tdclauses , FunD 'fromDictWKeys fdclauses ]] -- | Generates the OpCode data type. -- -- This takes an opcode logical definition, and builds both the -- datatype and the JSON serialisation out of it. We can't use a -- generic serialisation since we need to be compatible with Ganeti's -- own, so we have a few quirks to work around. genOpCode :: String -- ^ Type name to use -> [OpCodeConstructor] -- ^ Constructor name and parameters -> Q [Dec] genOpCode name cons = do let tname = mkName name decl_d <- mapM (\(cname, _, _, fields, _) -> do -- we only need the type of the field, without Q fields' <- mapM (fieldTypeInfo "op") fields return $ RecC (mkName cname) fields') cons let declD = gntDataD [] tname [] decl_d [''Show, ''Eq] let (allfsig, allffn) = genAllOpFields "allOpFields" cons -- DictObject let luxiCons = map opcodeConsToLuxiCons cons dictObjInst <- genOpCodeDictObject tname saveConstructor loadOpConstructor luxiCons -- rest pyDecls <- pyClasses cons return $ [declD, allfsig, allffn] ++ dictObjInst ++ pyDecls -- | Generates the function pattern returning the list of fields for a -- given constructor. genOpConsFields :: OpCodeConstructor -> Clause genOpConsFields (cname, _, _, fields, _) = let op_id = deCamelCase cname fieldnames f = map T.unpack $ fieldName f:fieldExtraKeys f fvals = map (LitE . StringL) . sort . nub $ concatMap fieldnames fields in Clause [LitP (StringL op_id)] (NormalB $ ListE fvals) [] -- | Generates a list of all fields of an opcode constructor. genAllOpFields :: String -- ^ Function name -> [OpCodeConstructor] -- ^ Object definition -> (Dec, Dec) genAllOpFields sname opdefs = let cclauses = map genOpConsFields opdefs other = Clause [WildP] (NormalB (ListE [])) [] fname = mkName sname sigt = AppT (AppT ArrowT (ConT ''String)) (AppT ListT (ConT ''String)) in (SigD fname sigt, FunD fname (cclauses++[other])) -- | Generates the \"save\" clause for an entire opcode constructor. -- -- This matches the opcode with variables named the same as the -- constructor fields (just so that the spliced in code looks nicer), -- and passes those name plus the parameter definition to 'saveObjectField'. saveConstructor :: LuxiConstructor -- ^ The constructor -> Q Clause -- ^ Resulting clause saveConstructor (sname, fields) = do let cname = mkName sname fnames <- mapM (newName . fieldVariable) fields let pat = conP cname (map varP fnames) let felems = zipWith saveObjectField fnames fields -- now build the OP_ID serialisation opid = [| [( $(stringE "OP_ID"), JSON.showJSON $(stringE . deCamelCase $ sname) )] |] flist = listE (opid:felems) -- and finally convert all this to a json object flist' = [| concat $flist |] clause [pat] (normalB flist') [] -- | Generates the main save opcode function, serializing as a dictionary. -- -- This builds a per-constructor match clause that contains the -- respective constructor-serialisation code. genSaveOpCode :: [LuxiConstructor] -- ^ Object definition -> (LuxiConstructor -> Q Clause) -- ^ Constructor save fn -> Q [Clause] genSaveOpCode opdefs fn = mapM fn opdefs -- | Generates load code for a single constructor of the opcode data type. -- The type of the resulting expression is @WriterT UsedKeys J.Result a@. loadConstructor :: Name -> (Field -> Q Exp) -> [Field] -> Q Exp loadConstructor name loadfn fields = [| MT.lift $(appConsApp name <$> mapM loadfn fields) <* tell $(fieldsUsedKeysQ fields) |] -- | Generates load code for a single constructor of the opcode data type. loadOpConstructor :: LuxiConstructor -> Q Exp loadOpConstructor (sname, fields) = loadConstructor (mkName sname) (loadObjectField fields) fields -- | Generates the loadOpCode function. genLoadOpCode :: [LuxiConstructor] -> (LuxiConstructor -> Q Exp) -- ^ Constructor load fn -> Q [Clause] genLoadOpCode opdefs fn = do let objname = objVarName opidKey = "OP_ID" opid = mkName $ map toLower opidKey st <- bindS (varP opid) [| $fromObjE $(varE objname) $(stringE opidKey) |] -- the match results (per-constructor blocks) mexps <- mapM fn opdefs fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |] let mpats = map (\(me, op) -> let mp = LitP . StringL . deCamelCase . fst $ op in Match mp (NormalB me) [] ) $ zip mexps opdefs defmatch = Match WildP (NormalB fails) [] cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch] body = DoE [st, cst] -- include "OP_ID" to the list of used keys bodyAndOpId <- [| $(return body) <* tell (mkUsedKeys . S.singleton . T.pack $ opidKey) |] return [Clause [VarP objname] (NormalB bodyAndOpId) []] -- * Template code for luxi -- | Constructor-to-string for LuxiOp. genStrOfOp :: Name -> String -> Q [Dec] genStrOfOp = genConstrToStr return -- | Constructor-to-string for MsgKeys. genStrOfKey :: Name -> String -> Q [Dec] genStrOfKey = genConstrToStr (return . ensureLower) -- | Generates the LuxiOp data type. -- -- This takes a Luxi operation definition and builds both the -- datatype and the function transforming the arguments to JSON. -- We can't use anything less generic, because the way different -- operations are serialized differs on both parameter- and top-level. -- -- There are two things to be defined for each parameter: -- -- * name -- -- * type -- genLuxiOp :: String -> [LuxiConstructor] -> Q [Dec] genLuxiOp name cons = do let tname = mkName name decl_d <- mapM (\(cname, fields) -> do -- we only need the type of the field, without Q fields' <- mapM actualFieldType fields let fields'' = zip (repeat myNotStrict) fields' return $ NormalC (mkName cname) fields'') cons let declD = gntDataD [] (mkName name) [] decl_d [''Show, ''Eq] -- generate DictObject instance dictObjInst <- genOpCodeDictObject tname saveLuxiConstructor loadOpConstructor cons -- .. and use it to construct 'opToArgs' of 'toDict' -- (as we know that the output of 'toDict' is always in the proper order) opToArgsType <- [t| $(conT tname) -> JSON.JSValue |] opToArgsExp <- [| JSON.showJSON . map snd . toDict |] let opToArgsName = mkName "opToArgs" opToArgsDecs = [ SigD opToArgsName opToArgsType , ValD (VarP opToArgsName) (NormalB opToArgsExp) [] ] -- rest req_defs <- declareSADT "LuxiReq" . map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $ cons return $ [declD] ++ dictObjInst ++ opToArgsDecs ++ req_defs -- | Generates the \"save\" clause for entire LuxiOp constructor. saveLuxiConstructor :: LuxiConstructor -> Q Clause saveLuxiConstructor (sname, fields) = do let cname = mkName sname fnames <- mapM (newName . fieldVariable) fields let pat = conP cname (map varP fnames) let felems = zipWith saveObjectField fnames fields flist = [| concat $(listE felems) |] clause [pat] (normalB flist) [] -- * "Objects" functionality -- | Extract the field's declaration from a Field structure. fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type) fieldTypeInfo field_pfx fd = do t <- actualFieldType fd let n = mkName . (field_pfx ++) . fieldRecordName $ fd return (n, myNotStrict, t) -- | Build an object declaration. buildObject :: String -> String -> [Field] -> Q [Dec] buildObject sname field_pfx fields = do when (any ((==) AndRestArguments . fieldIsOptional) . drop 1 $ reverse fields) $ fail "Objects may have only one AndRestArguments field,\ \ and it must be the last one." let name = mkName sname fields_d <- mapM (fieldTypeInfo field_pfx) fields let decl_d = RecC name fields_d let declD = gntDataD [] name [] [decl_d] [''Show, ''Eq] ser_decls <- buildObjectSerialisation sname fields return $ declD:ser_decls -- | Build an accessor function for a field of an object -- that can have a forthcoming variant. buildAccessor :: Name -- ^ name of the forthcoming constructor -> String -- ^ prefix for the forthcoming field -> Name -- ^ name of the real constructor -> String -- ^ prefix for the real field -> Name -- ^ name of the generated accessor -> String -- ^ prefix of the generated accessor -> Field -- ^ field description -> Q [Dec] buildAccessor fnm fpfx rnm rpfx nm pfx field = do let optField = makeOptional field x <- newName "x" (rpfx_name, _, _) <- fieldTypeInfo rpfx field (fpfx_name, _, ftype) <- fieldTypeInfo fpfx optField (pfx_name, _, _) <- fieldTypeInfo pfx field let r_body_core = AppE (VarE rpfx_name) $ VarE x r_body = if fieldIsOptional field == fieldIsOptional optField then r_body_core else AppE (VarE 'return) r_body_core f_body = AppE (VarE fpfx_name) $ VarE x return $ [ SigD pfx_name $ ArrowT `AppT` ConT nm `AppT` ftype , FunD pfx_name [ Clause [ConP rnm [VarP x]] (NormalB r_body) [] , Clause [ConP fnm [VarP x]] (NormalB f_body) [] ]] -- | Build lense declartions for a field. -- -- If the type of the field is the same in -- the forthcoming and the real variant, the lens -- will be a simple lens (Lens' s a). -- -- Otherwise, the type will be (Lens s s (Maybe a) a). -- This is because the field in forthcoming variant -- has type (Maybe a), but the real variant has type a. buildLens :: (Name, Name) -- ^ names of the forthcoming constructors -> (Name, Name) -- ^ names of the real constructors -> Name -- ^ name of the type -> String -- ^ the field prefix -> Int -- ^ arity -> (Field, Int) -- ^ the Field to generate the lens for, and its -- position -> Q [Dec] buildLens (fnm, fdnm) (rnm, rdnm) nm pfx ar (field, i) = do let optField = makeOptional field isSimple = fieldIsOptional field == fieldIsOptional optField lensnm = mkName $ pfx ++ fieldRecordName field ++ "L" (accnm, _, ftype) <- fieldTypeInfo pfx field vars <- replicateM ar (newName "x") var <- newName "val" context <- newName "val" jE <- [| Just |] let body eJ cn cdn = NormalB . (ConE cn `AppE`) . foldl (\e (j, x) -> AppE e $ if i == j then if eJ then AppE jE (VarE var) else VarE var else VarE x) (ConE cdn) $ zip [0..] vars let setterE = LamE [VarP context, VarP var] $ CaseE (VarE context) [ Match (ConP fnm [ConP fdnm . set (element i) WildP $ map VarP vars]) (body (not isSimple) fnm fdnm) [] , Match (ConP rnm [ConP rdnm . set (element i) WildP $ map VarP vars]) (body False rnm rdnm) [] ] let lensD = ValD (VarP lensnm) (NormalB $ VarE 'lens `AppE` VarE accnm `AppE` setterE) [] if isSimple then return $ (SigD lensnm $ ConT ''Lens' `AppT` ConT nm `AppT` ftype) : lensD : [] else return $ (SigD lensnm $ ConT ''Lens `AppT` ConT nm `AppT` ConT nm `AppT` (ConT ''Maybe `AppT` ftype) `AppT` ftype) : lensD : [] -- | Build an object that can have a forthcoming variant. -- This will create 3 data types: two objects, prefixed by -- "Real" and "Forthcoming", respectively, and a sum type -- of those. The JSON representation of the latter will -- be a JSON object, dispatching on the "forthcoming" key. buildObjectWithForthcoming :: String -- ^ Name of the newly defined type -> String -- ^ base prefix for field names; for the real and forthcoming -- variant, with base prefix will be prefixed with "real" -- and forthcoming, respectively. -> [Field] -- ^ List of fields in the real version -> Q [Dec] buildObjectWithForthcoming sname field_pfx fields = do let capitalPrefix = ensureUpper field_pfx forth_nm = "Forthcoming" ++ sname forth_data_nm = forth_nm ++ "Data" forth_pfx = "forthcoming" ++ capitalPrefix real_nm = "Real" ++ sname real_data_nm = real_nm ++ "Data" real_pfx = "real" ++ capitalPrefix concreteDecls <- buildObject real_data_nm real_pfx fields forthcomingDecls <- buildObject forth_data_nm forth_pfx (map makeOptional fields) let name = mkName sname real_d = NormalC (mkName real_nm) [(myNotStrict, ConT (mkName real_data_nm))] forth_d = NormalC (mkName forth_nm) [(myNotStrict, ConT (mkName forth_data_nm))] let declD = gntDataD [] name [] [real_d, forth_d] [''Show, ''Eq] read_body <- [| branchOnField "forthcoming" (liftM $(conE $ mkName forth_nm) . JSON.readJSON) (liftM $(conE $ mkName real_nm) . JSON.readJSON) |] x <- newName "x" show_real_body <- [| JSON.showJSON $(varE x) |] show_forth_body <- [| addField ("forthcoming", JSON.JSBool True) $ JSON.showJSON $(varE x) |] let rdjson = FunD 'JSON.readJSON [Clause [] (NormalB read_body) []] shjson = FunD 'JSON.showJSON [ Clause [ConP (mkName real_nm) [VarP x]] (NormalB show_real_body) [] , Clause [ConP (mkName forth_nm) [VarP x]] (NormalB show_forth_body) [] ] instJSONdecl = gntInstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [rdjson, shjson] accessors <- liftM concat . flip mapM fields $ buildAccessor (mkName forth_nm) forth_pfx (mkName real_nm) real_pfx name field_pfx lenses <- liftM concat . flip mapM (zip fields [0..]) $ buildLens (mkName forth_nm, mkName forth_data_nm) (mkName real_nm, mkName real_data_nm) name field_pfx (length fields) xs <- newName "xs" fromDictWKeysbody <- [| if ("forthcoming", JSON.JSBool True) `elem` $(varE xs) then liftM $(conE $ mkName forth_nm) (fromDictWKeys $(varE xs)) else liftM $(conE $ mkName real_nm) (fromDictWKeys $(varE xs)) |] todictx_r <- [| toDict $(varE x) |] todictx_f <- [| ("forthcoming", JSON.JSBool True) : toDict $(varE x) |] let todict = FunD 'toDict [ Clause [ConP (mkName real_nm) [VarP x]] (NormalB todictx_r) [] , Clause [ConP (mkName forth_nm) [VarP x]] (NormalB todictx_f) [] ] fromdict = FunD 'fromDictWKeys [ Clause [VarP xs] (NormalB fromDictWKeysbody) [] ] instDict = gntInstanceD [] (AppT (ConT ''DictObject) (ConT name)) [todict, fromdict] instArray <- genArrayObjectInstance name (simpleField "forthcoming" [t| Bool |] : fields) let forthPredName = mkName $ field_pfx ++ "Forthcoming" let forthPredDecls = [ SigD forthPredName $ ArrowT `AppT` ConT name `AppT` ConT ''Bool , FunD forthPredName [ Clause [ConP (mkName real_nm) [WildP]] (NormalB $ ConE 'False) [] , Clause [ConP (mkName forth_nm) [WildP]] (NormalB $ ConE 'True) [] ] ] return $ concreteDecls ++ forthcomingDecls ++ [declD, instJSONdecl] ++ forthPredDecls ++ accessors ++ lenses ++ [instDict, instArray] -- | Generates an object definition: data type and its JSON instance. buildObjectSerialisation :: String -> [Field] -> Q [Dec] buildObjectSerialisation sname fields = do let name = mkName sname dictdecls <- genDictObject saveObjectField (loadObjectField fields) sname fields savedecls <- genSaveObject sname (loadsig, loadfn) <- genLoadObject sname shjson <- objectShowJSON sname rdjson <- objectReadJSON sname let instdecl = gntInstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [rdjson, shjson] return $ dictdecls ++ savedecls ++ [loadsig, loadfn, instdecl] -- | An internal name used for naming variables that hold the entire -- object of type @[(String,JSValue)]@. objVarName :: Name objVarName = mkName "_o" -- | Provides a default 'toJSArray' for 'ArrayObject' instance using its -- existing 'DictObject' instance. The keys are serialized in the order -- they're declared. The list must contain all keys possibly generated by -- 'toDict'. defaultToJSArray :: (DictObject a) => [String] -> a -> [JSON.JSValue] defaultToJSArray keys o = let m = M.fromList $ toDict o in map (fromMaybe JSON.JSNull . flip M.lookup m) keys -- | Provides a default 'fromJSArray' for 'ArrayObject' instance using its -- existing 'DictObject' instance. The fields are deserialized in the order -- they're declared. defaultFromJSArray :: (DictObject a) => [String] -> [JSON.JSValue] -> JSON.Result a defaultFromJSArray keys xs = do let xslen = length xs explen = length keys unless (xslen == explen) (fail $ "Expected " ++ show explen ++ " arguments, got " ++ show xslen) fromDict $ zip keys xs -- | Generates an additional 'ArrayObject' instance using its -- existing 'DictObject' instance. -- -- See 'defaultToJSArray' and 'defaultFromJSArray'. genArrayObjectInstance :: Name -> [Field] -> Q Dec genArrayObjectInstance name fields = do let fnames = fieldsKeys fields instanceD (return []) (appT (conT ''ArrayObject) (conT name)) [ valD (varP 'toJSArray) (normalB [| defaultToJSArray $(lift fnames) |]) [] , valD (varP 'fromJSArray) (normalB [| defaultFromJSArray fnames |]) [] ] -- | Generates 'DictObject' instance. genDictObject :: (Name -> Field -> Q Exp) -- ^ a saving function -> (Field -> Q Exp) -- ^ a loading function -> String -- ^ an object name -> [Field] -- ^ a list of fields -> Q [Dec] genDictObject save_fn load_fn sname fields = do let name = mkName sname -- newName fails in ghc 7.10 when used on keywords newName' "data" = newName "data_ghcBug10599" newName' "instance" = newName "instance_ghcBug10599" newName' "type" = newName "type_ghcBug10599" newName' s = newName s -- toDict fnames <- mapM (newName' . fieldVariable) fields let pat = conP name (map varP fnames) tdexp = [| concat $(listE $ zipWith save_fn fnames fields) |] tdclause <- clause [pat] (normalB tdexp) [] -- fromDict fdexp <- loadConstructor name load_fn fields let fdclause = Clause [VarP objVarName] (NormalB fdexp) [] -- the ArrayObject instance generated from DictObject arrdec <- genArrayObjectInstance name fields -- the final instance return $ [gntInstanceD [] (AppT (ConT ''DictObject) (ConT name)) [ FunD 'toDict [tdclause] , FunD 'fromDictWKeys [fdclause] ]] ++ [arrdec] -- | Generates the save object functionality. genSaveObject :: String -> Q [Dec] genSaveObject sname = do let fname = mkName ("save" ++ sname) sigt <- [t| $(conT $ mkName sname) -> JSON.JSValue |] cclause <- [| showJSONtoDict |] return [SigD fname sigt, ValD (VarP fname) (NormalB cclause) []] -- | Generates the code for saving an object's field, handling the -- various types of fields that we have. saveObjectField :: Name -> Field -> Q Exp saveObjectField fvar field = do let formatFn = fromMaybe [| JSON.showJSON &&& (const []) |] $ fieldShow field formatFnTyped = sigE formatFn [t| $(fieldType field) -> (JSON.JSValue, [(String, JSON.JSValue)]) |] let formatCode v = [| let (actual, extra) = $formatFnTyped $(v) in ($nameE, actual) : extra |] case fieldIsOptional field of OptionalOmitNull -> [| case $(fvarE) of Nothing -> [] Just v -> $(formatCode [| v |]) |] OptionalSerializeNull -> [| case $(fvarE) of Nothing -> [( $nameE, JSON.JSNull )] Just v -> $(formatCode [| v |]) |] NotOptional -> case (fieldDefault field, fieldSerializeDefault field) of (Just v, False) -> [| if $v /= $fvarE then $(formatCode fvarE) else [] |] -- If a default value exists and we shouldn't serialize -- default fields - serialize only if the value differs -- from the default one. _ -> formatCode fvarE AndRestArguments -> [| M.toList $(varE fvar) |] where nameE = stringE (T.unpack . fieldName $ field) fvarE = varE fvar -- | Generates the showJSON clause for a given object name. objectShowJSON :: String -> Q Dec objectShowJSON name = do body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |] return $ FunD 'JSON.showJSON [Clause [] (NormalB body) []] -- | Generates the load object functionality. genLoadObject :: String -> Q (Dec, Dec) genLoadObject sname = do let fname = mkName $ "load" ++ sname sigt <- [t| JSON.JSValue -> JSON.Result $(conT $ mkName sname) |] cclause <- [| readJSONfromDict |] return $ (SigD fname sigt, FunD fname [Clause [] (NormalB cclause) []]) -- | Generates code for loading an object's field. loadObjectField :: [Field] -> Field -> Q Exp loadObjectField allFields field = do let otherNames = fieldsDictKeysQ . filter (on (/=) fieldName field) $ allFields -- these are used in all patterns below let objvar = varE objVarName objfield = stringE (T.unpack . fieldName $ field) case (fieldDefault field, fieldIsOptional field) of -- Only non-optional fields without defaults must have a value; -- we treat both optional types the same, since -- 'maybeFromObj' can deal with both missing and null values -- appropriately (the same) (Nothing, NotOptional) -> loadFn field [| fromObj $objvar $objfield |] objvar -- AndRestArguments need not to be parsed at all, -- they're just extracted from the list of other fields. (Nothing, AndRestArguments) -> [| return . M.fromList . filter (not . (`S.member` $(otherNames)) . T.pack . fst) $ $objvar |] _ -> loadFnOpt field [| maybeFromObj $objvar $objfield |] objvar fieldsKeys :: [Field] -> [String] fieldsKeys fields = map T.unpack $ concatMap (liftA2 (:) fieldName fieldExtraKeys) fields -- | Generates the set of all used JSON dictionary keys for a list of fields -- The equivalent of S.fromList (map T.pack ["f1", "f2", "f3"] ) fieldsDictKeys :: [Field] -> Exp fieldsDictKeys fields = AppE (VarE 'S.fromList) . AppE (AppE (VarE 'map) (VarE 'T.pack)) . ListE . map (LitE . StringL) $ fieldsKeys fields -- | Generates the list of all used JSON dictionary keys for a list of fields fieldsDictKeysQ :: [Field] -> Q Exp fieldsDictKeysQ = return . fieldsDictKeys -- | Generates the list of all used JSON dictionary keys for a list of fields, -- depending on if any of them has 'AndRestArguments' flag. fieldsUsedKeysQ :: [Field] -> Q Exp fieldsUsedKeysQ fields | any ((==) AndRestArguments . fieldIsOptional) fields = [| allUsedKeys |] | otherwise = [| mkUsedKeys $(fieldsDictKeysQ fields) |] -- | Builds the readJSON instance for a given object name. objectReadJSON :: String -> Q Dec objectReadJSON name = do let s = mkName "s" body <- [| $(varE . mkName $ "load" ++ name) =<< readJSONWithDesc $(stringE name) $(varE s) |] return $ FunD 'JSON.readJSON [Clause [VarP s] (NormalB body) []] -- * Inheritable parameter tables implementation -- | Compute parameter type names. paramTypeNames :: String -> (String, String) paramTypeNames root = ("Filled" ++ root ++ "Params", "Partial" ++ root ++ "Params") -- | Compute the name of a full and a partial parameter field. paramFieldNames :: String -> Field -> (Name, Name) paramFieldNames field_pfx fd = let base = field_pfx ++ fieldRecordName fd in (mkName base, mkName (base ++ "P")) -- | Compute information about the type of a parameter field. paramFieldTypeInfo :: String -> Field -> VarStrictTypeQ paramFieldTypeInfo field_pfx fd = do t <- actualFieldType fd return (snd $ paramFieldNames field_pfx fd, myNotStrict, AppT (ConT ''Maybe) t) -- | Build a parameter declaration. -- -- This function builds two different data structures: a /filled/ one, -- in which all fields are required, and a /partial/ one, in which all -- fields are optional. Due to the current record syntax issues, the -- fields need to be named differrently for the two structures, so the -- partial ones get a /P/ suffix. -- Also generate a default value for the partial parameters. buildParam :: String -> String -> [Field] -> Q [Dec] buildParam sname field_pfx fields = do let (sname_f, sname_p) = paramTypeNames sname name_f = mkName sname_f name_p = mkName sname_p fields_f <- mapM (fieldTypeInfo field_pfx) fields fields_p <- mapM (paramFieldTypeInfo field_pfx) fields let decl_f = RecC name_f fields_f decl_p = RecC name_p fields_p let declF = gntDataD [] name_f [] [decl_f] [''Show, ''Eq] let declP = gntDataD [] name_p [] [decl_p] [''Show, ''Eq] ser_decls_f <- buildObjectSerialisation sname_f fields ser_decls_p <- buildPParamSerialisation sname_p fields fill_decls <- fillParam sname field_pfx fields return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls ++ buildParamAllFields sname fields -- | Builds a list of all fields of a parameter. buildParamAllFields :: String -> [Field] -> [Dec] buildParamAllFields sname fields = let vname = mkName ("all" ++ sname ++ "ParamFields") sig = SigD vname (AppT ListT (ConT ''String)) val = ListE $ map (LitE . StringL . T.unpack . fieldName) fields in [sig, ValD (VarP vname) (NormalB val) []] -- | Generates the serialisation for a partial parameter. buildPParamSerialisation :: String -> [Field] -> Q [Dec] buildPParamSerialisation sname fields = do let name = mkName sname dictdecls <- genDictObject savePParamField loadPParamField sname fields savedecls <- genSaveObject sname (loadsig, loadfn) <- genLoadObject sname shjson <- objectShowJSON sname rdjson <- objectReadJSON sname let instdecl = gntInstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [rdjson, shjson] return $ dictdecls ++ savedecls ++ [loadsig, loadfn, instdecl] -- | Generates code to save an optional parameter field. savePParamField :: Name -> Field -> Q Exp savePParamField fvar field = do checkNonOptDef field let actualVal = mkName "v" normalexpr <- saveObjectField actualVal field -- we have to construct the block here manually, because we can't -- splice-in-splice return $ CaseE (VarE fvar) [ Match (ConP 'Nothing []) (NormalB (ConE '[])) [] , Match (ConP 'Just [VarP actualVal]) (NormalB normalexpr) [] ] -- | Generates code to load an optional parameter field. loadPParamField :: Field -> Q Exp loadPParamField field = do checkNonOptDef field let name = fieldName field -- these are used in all patterns below let objvar = varE objVarName objfield = stringE . T.unpack $ name loadexp = [| $(varE 'maybeFromObj) $objvar $objfield |] loadFnOpt field loadexp objvar -- | Builds a function that executes the filling of partial parameter -- from a full copy (similar to Python's fillDict). fillParam :: String -> String -> [Field] -> Q [Dec] fillParam sname field_pfx fields = do let (sname_f, sname_p) = paramTypeNames sname name_f = mkName sname_f name_p = mkName sname_p let (fnames, pnames) = unzip $ map (paramFieldNames field_pfx) fields -- due to apparent bugs in some older GHC versions, we need to add these -- prefixes to avoid "binding shadows ..." errors fbinds <- mapM (newName . ("f_" ++) . nameBase) fnames let fConP = ConP name_f (map VarP fbinds) pbinds <- mapM (newName . ("p_" ++) . nameBase) pnames let pConP = ConP name_p (map VarP pbinds) -- PartialParams instance -------- -- fillParams let fromMaybeExp fn pn = AppE (AppE (VarE 'fromMaybe) (VarE fn)) (VarE pn) fupdates = appCons name_f $ zipWith fromMaybeExp fbinds pbinds fclause = Clause [fConP, pConP] (NormalB fupdates) [] -- toPartial let tpupdates = appCons name_p $ map (AppE (ConE 'Just) . VarE) fbinds tpclause = Clause [fConP] (NormalB tpupdates) [] -- toFilled let tfupdates = appConsApp name_f $ map VarE pbinds tfclause = Clause [pConP] (NormalB tfupdates) [] -- the instance let instType = AppT (AppT (ConT ''PartialParams) (ConT name_f)) (ConT name_p) -- Monoid instance for the partial part ---- -- mempty let memptyExp = appCons name_p $ map (const $ VarE 'empty) fields memptyClause = Clause [] (NormalB memptyExp) [] -- mappend pbinds2 <- mapM (newName . ("p2_" ++) . nameBase) pnames let pConP2 = ConP name_p (map VarP pbinds2) -- note the reversal of 'l' and 'r' in the call to <|> -- as we want the result to be the rightmost value let altExp = zipWith (\l r -> AppE (AppE (VarE '(<|>)) (VarE r)) (VarE l)) mappendExp = appCons name_p $ altExp pbinds pbinds2 mappendClause = Clause [pConP, pConP2] (NormalB mappendExp) [] mappendAlias = Clause [] (NormalB $ VarE '(Sem.<>)) [] let monoidType = AppT (ConT ''Monoid) (ConT name_p) let semigroupType = AppT (ConT ''Sem.Semigroup) (ConT name_p) -- the instances combined return [ gntInstanceD [] instType [ FunD 'fillParams [fclause] , FunD 'toPartial [tpclause] , FunD 'toFilled [tfclause] ] , gntInstanceD [] semigroupType [ FunD '(Sem.<>) [mappendClause] ] , gntInstanceD [] monoidType [ FunD 'mempty [memptyClause] , FunD 'mappend [mappendAlias] ]] -- * Template code for exceptions -- | Exception simple error message field. excErrMsg :: (String, Q Type) excErrMsg = ("errMsg", [t| String |]) -- | Builds an exception type definition. genException :: String -- ^ Name of new type -> SimpleObject -- ^ Constructor name and parameters -> Q [Dec] genException name cons = do let tname = mkName name declD <- buildSimpleCons tname cons (savesig, savefn) <- genSaveSimpleObj tname ("save" ++ name) cons $ uncurry saveExcCons (loadsig, loadfn) <- genLoadExc tname ("load" ++ name) cons return [declD, loadsig, loadfn, savesig, savefn] -- | Generates the \"save\" clause for an entire exception constructor. -- -- This matches the exception with variables named the same as the -- constructor fields (just so that the spliced in code looks nicer), -- and calls showJSON on it. saveExcCons :: String -- ^ The constructor name -> [SimpleField] -- ^ The parameter definitions for this -- constructor -> Q Clause -- ^ Resulting clause saveExcCons sname fields = do let cname = mkName sname fnames <- mapM (newName . fst) fields let pat = conP cname (map varP fnames) felems = if null fnames then conE '() -- otherwise, empty list has no type else listE $ map (\f -> [| JSON.showJSON $(varE f) |]) fnames let tup = tupE [ litE (stringL sname), felems ] clause [pat] (normalB [| JSON.showJSON $tup |]) [] -- | Generates load code for a single constructor of an exception. -- -- Generates the code (if there's only one argument, we will use a -- list, not a tuple: -- -- @ -- do -- (x1, x2, ...) <- readJSON args -- return $ Cons x1 x2 ... -- @ loadExcConstructor :: Name -> String -> [SimpleField] -> Q Exp loadExcConstructor inname sname fields = do let name = mkName sname f_names <- mapM (newName . fst) fields let read_args = AppE (VarE 'JSON.readJSON) (VarE inname) let binds = case f_names of [x] -> BindS (ListP [VarP x]) _ -> BindS (TupP (map VarP f_names)) cval = appCons name $ map VarE f_names return $ DoE [binds read_args, NoBindS (AppE (VarE 'return) cval)] {-| Generates the loadException function. This generates a quite complicated function, along the lines of: @ loadFn (JSArray [JSString name, args]) = case name of "A1" -> do (x1, x2, ...) <- readJSON args return $ A1 x1 x2 ... "a2" -> ... s -> fail $ "Unknown exception" ++ s loadFn v = fail $ "Expected array but got " ++ show v @ -} genLoadExc :: Name -> String -> SimpleObject -> Q (Dec, Dec) genLoadExc tname sname opdefs = do let fname = mkName sname exc_name <- newName "name" exc_args <- newName "args" exc_else <- newName "s" arg_else <- newName "v" fails <- [| fail $ "Unknown exception '" ++ $(varE exc_else) ++ "'" |] -- default match for unknown exception name let defmatch = Match (VarP exc_else) (NormalB fails) [] -- the match results (per-constructor blocks) str_matches <- mapM (\(s, params) -> do body_exp <- loadExcConstructor exc_args s params return $ Match (LitP (StringL s)) (NormalB body_exp) []) opdefs -- the first function clause; we can't use [| |] due to TH -- limitations, so we have to build the AST by hand let clause1 = Clause [ConP 'JSON.JSArray [ListP [ConP 'JSON.JSString [VarP exc_name], VarP exc_args]]] (NormalB (CaseE (AppE (VarE 'JSON.fromJSString) (VarE exc_name)) (str_matches ++ [defmatch]))) [] -- the fail expression for the second function clause let err = "Invalid exception: expected '(string, [args])' " ++ " but got " fail_type <- [| fail $ err ++ show (pp_value $(varE arg_else)) ++ "'" |] -- the second function clause let clause2 = Clause [VarP arg_else] (NormalB fail_type) [] sigt <- [t| JSON.JSValue -> JSON.Result $(conT tname) |] return $ (SigD fname sigt, FunD fname [clause1, clause2]) -- | Compute the ssconf constructor name from its file name. ssconfConstructorName :: String -> String ssconfConstructorName = camelCase . ("s_s_" ++)
ganeti/ganeti
src/Ganeti/THH.hs
bsd-2-clause
66,190
497
20
18,613
13,904
7,556
6,348
-1
-1
{-| Module: HaskHOL.Deductive Copyright: (c) Evan Austin 2015 LICENSE: BSD3 Maintainer: e.c.austin@gmail.com Stability: unstable Portability: unknown This module is the one to import for users looking to include the entirety of the deductive reasoning engine of the HaskHOL proof system. It re-exports all of the deductive sub-modules; additionally, it exports aliases to a theory context, quasi-quoter, and compile-time proof methods for users who are working only with these libraries. -} module HaskHOL.Deductive ( -- * Theory Context -- $ThryCtxt DeductiveType , DeductiveCtxt , ctxtDeductive , deductive -- * Re-exported Modules , module HaskHOL.Lib.Equal , module HaskHOL.Lib.Bool , module HaskHOL.Lib.DRule , module HaskHOL.Lib.Tactics , module HaskHOL.Lib.Itab , module HaskHOL.Lib.Simp , module HaskHOL.Lib.Theorems , module HaskHOL.Lib.IndDefs , module HaskHOL.Lib.Classic , module HaskHOL.Lib.Trivia , module HaskHOL.Lib.Canon , module HaskHOL.Lib.Meson , module HaskHOL.Lib.Quot , module HaskHOL.Lib.Misc , module HaskHOL.Lib.TypeQuant , module HaskHOL.Lib.TypeQuant.Context ) where import HaskHOL.Core import HaskHOL.Lib.Equal import HaskHOL.Lib.Bool import HaskHOL.Lib.DRule import HaskHOL.Lib.Tactics import HaskHOL.Lib.Itab import HaskHOL.Lib.Simp import HaskHOL.Lib.Theorems import HaskHOL.Lib.IndDefs import HaskHOL.Lib.Classic import HaskHOL.Lib.Trivia import HaskHOL.Lib.Canon import HaskHOL.Lib.Meson import HaskHOL.Lib.Quot import HaskHOL.Lib.Misc import HaskHOL.Lib.TypeQuant import HaskHOL.Lib.TypeQuant.Context {- $ThryCtxt See 'extendCtxt' in the "HaskHOL.Core.Ext" module for more information. -} {-| The theory context type for the deductive libraries. An alias to 'TypeQuantType'. -} type DeductiveType = TypeQuantType type DeductiveCtxt a = TypeQuantCtxt a {-| The theory context for the deductive libraries. An alias to 'ctxtTypeQuant'. -} {-# NOINLINE ctxtDeductive #-} ctxtDeductive :: TheoryPath DeductiveType ctxtDeductive = ctxtTypeQuant -- | The quasi-quoter for the deductive libraries. An alias to 'typeQuant'. deductive :: QuasiQuoter deductive = typeQuant
ecaustin/haskhol-deductive
src/HaskHOL/Deductive.hs
bsd-2-clause
2,258
0
5
413
283
194
89
46
1
-- | Pretty-print TOML. module Text.Toml.Pretty (ppr) where import Data.Aeson (encode, toJSON) import qualified Data.ByteString.Lazy.UTF8 as B import Data.Foldable import qualified Data.Map as M import Data.Text (Text) import Data.Time.ISO8601 import Text.Toml import Text.PrettyPrint.ANSI.Leijen -- | Pretty-prints TOML as JSON. -- -- Pretty printing this example document: -- -- @ -- # This is a TOML document. Boom. -- -- title = "TOML Example" -- -- [owner] -- name = "Tom Preston-Werner" -- organization = \"GitHub\" -- bio = "GitHub Cofounder & CEO\\nLikes tater tots and beer." -- dob = 1979-05-27T07:32:00Z # First class dates? Why not? -- -- [database] -- server = "192.168.1.1" -- ports = [ 8001, 8001, 8002 ] -- connection_max = 5000 -- enabled = true -- -- [[servers]] -- name = "alpha" -- ip = "10.0.0.1" -- dc = "eqdc10" -- -- [[servers]] -- name = "beta" -- ip = "10.0.0.2" -- dc = "eqdc10" -- -- [clients] -- data = [ ["gamma", "delta"], [1, 2] ] -- -- # Line breaks are OK when inside arrays -- hosts = [ -- "alpha", -- "omega" -- ] -- @ -- -- yields the JSON: -- -- @ -- { -- "clients": { -- "data": [["gamma", "delta"], [1, 2]], -- "hosts": ["alpha", "omega"] -- }, -- "database": { -- "connection_max": 5000, -- "enabled": true, -- "ports": [8001, 8001, 8002], -- "server": "192.168.1.1" -- }, -- "owner": { -- "bio": "GitHub Cofounder & CEO\\nLikes tater tots and beer.", -- "dob": "1979-05-27T07:32:00Z", -- "name": "Tom Preston-Werner", -- "organization": \"GitHub\" -- }, -- "servers": [ -- { -- "dc": "eqdc10", -- "ip": "10.0.0.1", -- "name": "alpha" -- }, -- { -- "dc": "eqdc10", -- "ip": "10.0.0.2", -- "name": "beta" -- } -- ], -- "title": "TOML Example" -- } -- @ -- -- (as a consequence of the internal structure of 'Map', the keys will -- always be in alphabetical order.) ppr :: Toml -> Doc ppr t = vsep [ lbrace , indent 2 (vcat (punctuate comma (map pprPair $ M.toList t))) , rbrace ] pprPair :: (Text, Value) -> Doc pprPair (k,v) = dullblue (pprString k) <> text ":" <+> pprValue v pprValue :: Value -> Doc pprValue (Table t) = ppr t pprValue (Tables ts) = vsep [ lbracket , indent 2 (vcat (punctuate comma $ map ppr $ toList ts)) , rbracket ] pprValue (Scalar s) = pprScalar s pprScalar :: Scalar -> Doc pprScalar (String t) = dullmagenta $ pprString t pprScalar (Decimal d) = dullgreen $ integer d pprScalar (Floating f) = dullgreen $ double f pprScalar (Bool True) = bold $ text "true" pprScalar (Bool False) = bold $ text "false" pprScalar (Date d) = dullyellow . text $ show (formatISO8601 d) pprScalar (List vs) = brackets $ hsep (punctuate comma . map pprScalar $ toList vs) pprString :: Text -> Doc pprString t = text (B.toString . encode $ toJSON t)
pikajude/toml
src/Text/Toml/Pretty.hs
bsd-2-clause
2,848
0
15
633
593
346
247
34
1
LevelPreds { lpredPre = NameT "p_galois'rows_width'P" [ 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" [] , TyCon "int" [] ] , lpredLoops = [ NameT "p_galois'rows_width'I1" [ 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" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] , NameT "p_galois'rows_width'I2" [ 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" [] , TyCon "int" [] , TyCon "int" [] , TyCon "int" [] , TyCon "addr" [] , TyCon "int" [] , TyCon "int" [] ] ] , lpredPost = NameT "p_galois'rows_width'Q" [ 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" [] , TyCon "int" [] ] , lpredCalls = fromList [] }
GaloisInc/verification-game
web-prover/demo-levels/rows_width/holes.hs
bsd-3-clause
2,601
0
13
1,030
1,065
534
531
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GLU.Quadrics -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : provisional -- Portability : portable -- -- This module corresponds to chapter 6 (Quadrics) of the GLU specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GLU.Quadrics ( QuadricNormal, QuadricTexture(..), QuadricOrientation(..), QuadricDrawStyle(..), QuadricStyle(..), Radius, Height, Angle, Slices, Stacks, Loops, QuadricPrimitive(..), renderQuadric ) where import Control.Monad ( unless ) import Foreign.Ptr ( Ptr, nullPtr, FunPtr, freeHaskellFunPtr ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLboolean, GLenum, GLint, GLdouble ) import Graphics.Rendering.OpenGL.GL.Colors ( ShadingModel(Smooth,Flat) ) import Graphics.Rendering.OpenGL.GL.Exception ( bracket ) import Graphics.Rendering.OpenGL.GL.GLboolean ( marshalGLboolean ) import Graphics.Rendering.OpenGL.GLU.ErrorsInternal ( recordErrorCode, recordOutOfMemory ) -------------------------------------------------------------------------------- data QuadricDrawStyle = PointStyle | LineStyle | FillStyle | SilhouetteStyle deriving ( Eq, Ord, Show ) marshalQuadricDrawStyle :: QuadricDrawStyle -> GLenum marshalQuadricDrawStyle x = case x of PointStyle -> 0x186aa LineStyle -> 0x186ab FillStyle -> 0x186ac SilhouetteStyle -> 0x186ad -------------------------------------------------------------------------------- data QuadricCallback = Error'2 deriving ( Eq, Ord, Show ) marshalQuadricCallback :: QuadricCallback -> GLenum marshalQuadricCallback x = case x of Error'2 -> 0x18707 -------------------------------------------------------------------------------- type QuadricNormal = Maybe ShadingModel marshalQuadricNormal :: QuadricNormal -> GLenum marshalQuadricNormal (Just Smooth) = 0x186a0 marshalQuadricNormal (Just Flat ) = 0x186a1 marshalQuadricNormal Nothing = 0x186a2 -------------------------------------------------------------------------------- data QuadricOrientation = Outside | Inside deriving ( Eq, Ord, Show ) marshalQuadricOrientation :: QuadricOrientation -> GLenum marshalQuadricOrientation x = case x of Outside -> 0x186b4 Inside -> 0x186b5 -------------------------------------------------------------------------------- data QuadricTexture = NoTextureCoordinates | GenerateTextureCoordinates deriving ( Eq,Ord ) marshalQuadricTexture :: QuadricTexture -> GLboolean marshalQuadricTexture NoTextureCoordinates = marshalGLboolean False marshalQuadricTexture GenerateTextureCoordinates = marshalGLboolean True -------------------------------------------------------------------------------- data QuadricStyle = QuadricStyle QuadricNormal QuadricTexture QuadricOrientation QuadricDrawStyle deriving ( Eq,Ord ) -------------------------------------------------------------------------------- type Radius = GLdouble type Height = GLdouble type Angle = GLdouble type Slices = GLint type Stacks = GLint type Loops = GLint -------------------------------------------------------------------------------- data QuadricPrimitive = Sphere Radius Slices Stacks | Cylinder Radius Radius Height Slices Stacks | Disk Radius Radius Slices Loops | PartialDisk Radius Radius Slices Loops Angle Angle deriving ( Eq, Ord ) -------------------------------------------------------------------------------- renderQuadric :: QuadricStyle -> QuadricPrimitive -> IO () renderQuadric style prim = do withQuadricObj recordOutOfMemory $ \quadricObj -> withErrorCallback quadricObj recordErrorCode $ do setStyle quadricObj style renderPrimitive quadricObj prim withQuadricObj :: IO a -> (QuadricObj -> IO a) -> IO a withQuadricObj failure success = bracket gluNewQuadric safeDeleteQuadric (\quadricObj -> if isNullQuadricObj quadricObj then failure else success quadricObj) withErrorCallback :: QuadricObj -> QuadricCallback' -> IO a -> IO a withErrorCallback quadricObj callback action = bracket (makeQuadricCallback callback) freeHaskellFunPtr $ \callbackPtr -> do gluQuadricCallback quadricObj (marshalQuadricCallback Error'2) callbackPtr action setStyle :: QuadricObj -> QuadricStyle -> IO () setStyle quadricObj (QuadricStyle n t o d) = do gluQuadricNormals quadricObj (marshalQuadricNormal n) gluQuadricTexture quadricObj (marshalQuadricTexture t) gluQuadricOrientation quadricObj (marshalQuadricOrientation o) gluQuadricDrawStyle quadricObj (marshalQuadricDrawStyle d) renderPrimitive :: QuadricObj -> QuadricPrimitive -> IO () renderPrimitive quadricObj (Sphere r s n) = gluSphere quadricObj r s n renderPrimitive quadricObj (Cylinder b t h s n) = gluCylinder quadricObj b t h s n renderPrimitive quadricObj (Disk i o s l) = gluDisk quadricObj i o s l renderPrimitive quadricObj (PartialDisk i o s l a w) = gluPartialDisk quadricObj i o s l a w -------------------------------------------------------------------------------- -- 'Char' is a fake here, any marshalable type would do newtype QuadricObj = QuadricObj (Ptr Char) deriving ( Eq ) isNullQuadricObj :: QuadricObj -> Bool isNullQuadricObj = (QuadricObj nullPtr ==) -------------------------------------------------------------------------------- foreign import CALLCONV unsafe "gluNewQuadric" gluNewQuadric :: IO QuadricObj safeDeleteQuadric :: QuadricObj -> IO () safeDeleteQuadric quadricObj = unless (isNullQuadricObj quadricObj) $ gluDeleteQuadric quadricObj foreign import CALLCONV unsafe "gluDeleteQuadric" gluDeleteQuadric :: QuadricObj -> IO () -------------------------------------------------------------------------------- type QuadricCallback' = GLenum -> IO () foreign import CALLCONV "wrapper" makeQuadricCallback :: QuadricCallback' -> IO (FunPtr QuadricCallback') foreign import CALLCONV unsafe "gluQuadricCallback" gluQuadricCallback :: QuadricObj -> GLenum -> FunPtr QuadricCallback' -> IO () -------------------------------------------------------------------------------- foreign import CALLCONV unsafe "gluQuadricNormals" gluQuadricNormals :: QuadricObj -> GLenum -> IO () foreign import CALLCONV unsafe "gluQuadricTexture" gluQuadricTexture :: QuadricObj -> GLboolean -> IO () foreign import CALLCONV unsafe "gluQuadricOrientation" gluQuadricOrientation :: QuadricObj -> GLenum -> IO () foreign import CALLCONV unsafe "gluQuadricDrawStyle" gluQuadricDrawStyle :: QuadricObj -> GLenum -> IO () -------------------------------------------------------------------------------- foreign import CALLCONV safe "gluSphere" gluSphere :: QuadricObj -> Radius -> Slices -> Stacks -> IO () foreign import CALLCONV safe "gluCylinder" gluCylinder :: QuadricObj -> Radius -> Radius -> Height -> Slices -> Stacks -> IO () foreign import CALLCONV safe "gluDisk" gluDisk :: QuadricObj -> Radius -> Radius -> Slices -> Loops -> IO () foreign import CALLCONV safe "gluPartialDisk" gluPartialDisk :: QuadricObj -> Radius -> Radius -> Slices -> Loops -> Angle -> Angle -> IO ()
FranklinChen/hugs98-plus-Sep2006
packages/OpenGL/Graphics/Rendering/OpenGL/GLU/Quadrics.hs
bsd-3-clause
7,510
48
13
1,200
1,570
840
730
-1
-1
module Text.Highlighter.Lexers.Modula2 (lexer) where import Text.Regex.PCRE.Light import Text.Highlighter.Types lexer :: Lexer lexer = Lexer { lName = "Modula-2" , lAliases = ["modula2", "m2"] , lExtensions = [".def", ".mod"] , lMimetypes = ["text/x-modula2"] , lStart = root' , lFlags = [multiline, dotall] } punctuation' :: TokenMatcher punctuation' = [ tok "[\\(\\)\\[\\]{},.:;|]" (Arbitrary "Punctuation") ] pragmas' :: TokenMatcher pragmas' = [ tok "\\(\\*\\$(.*?)\\*\\)" (Arbitrary "Comment" :. Arbitrary "Preproc") , tok "<\\*(.*?)\\*>" (Arbitrary "Comment" :. Arbitrary "Preproc") ] whitespace' :: TokenMatcher whitespace' = [ tok "\\n+" (Arbitrary "Text") , tok "\\s+" (Arbitrary "Text") ] numliterals' :: TokenMatcher numliterals' = [ tok "[01]+B" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Binary") , tok "[0-7]+B" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Oct") , tok "[0-7]+C" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Oct") , tok "[0-9A-F]+C" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Hex") , tok "[0-9A-F]+H" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Hex") , tok "[0-9]+\\.[0-9]+E[+-][0-9]+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Float") , tok "[0-9]+\\.[0-9]+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Float") , tok "[0-9]+" (Arbitrary "Literal" :. Arbitrary "Number" :. Arbitrary "Integer") ] operators' :: TokenMatcher operators' = [ tok "[*/+=#\126&<>\\^-]" (Arbitrary "Operator") , tok ":=" (Arbitrary "Operator") , tok "@" (Arbitrary "Operator") , tok "\\.\\." (Arbitrary "Operator") , tok "`" (Arbitrary "Operator") , tok "::" (Arbitrary "Operator") ] identifiers' :: TokenMatcher identifiers' = [ tok "([a-zA-Z_\\$][a-zA-Z0-9_\\$]*)" (Arbitrary "Name") ] root' :: TokenMatcher root' = [ anyOf whitespace' , anyOf comments' , anyOf pragmas' , anyOf identifiers' , anyOf numliterals' , anyOf strings' , anyOf operators' , anyOf punctuation' ] strings' :: TokenMatcher strings' = [ tok "'(\\\\\\\\|\\\\'|[^'])*'" (Arbitrary "Literal" :. Arbitrary "String") , tok "\"(\\\\\\\\|\\\\\"|[^\"])*\"" (Arbitrary "Literal" :. Arbitrary "String") ] comments' :: TokenMatcher comments' = [ tok "//.*?\\n" (Arbitrary "Comment" :. Arbitrary "Single") , tok "/\\*(.*?)\\*/" (Arbitrary "Comment" :. Arbitrary "Multiline") , tok "\\(\\*([^\\$].*?)\\*\\)" (Arbitrary "Comment" :. Arbitrary "Multiline") ]
chemist/highlighter
src/Text/Highlighter/Lexers/Modula2.hs
bsd-3-clause
2,626
0
10
522
744
385
359
62
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} {-| Module : Web.Mastodon.API.Accounts Description : Logic for generating API stuff related to accounts (based on arbitrary id) -} module Web.Mastodon.API.Accounts ( Accounts , accountsApi , getAccountByUid , verifyCredentials , getFollowersForUid , getFollowingForUid , getStatusesForUid , followUid , unfollowUid , blockUid , unblockUid , muteUid , unmuteUid , getRelationships , searchAccounts ) where import Control.Monad.Trans.Reader import Data.Proxy import qualified Data.Text as T import Servant.API import Servant.Client import Web.Mastodon.Auth import Web.Mastodon.Monad import Web.Mastodon.Types -- TODO: Re-export Auth (and maybe types) to avoid others having to import it when importing api? -- TODO: Int instead of Integer? type AccountsInsecure = "accounts" :> Capture "id" (Uid Account) :> Get '[JSON] Account :<|> "accounts" :> "verify_credentials" :> Get '[JSON] Account :<|> "accounts" :> Capture "id" (Uid Account) :> "followers" :> Get '[JSON] [Account] :<|> "accounts" :> Capture "id" (Uid Account) :> "following" :> Get '[JSON] [Account] :<|> "accounts" :> Capture "id" (Uid Account) :> "statuses" :> QueryFlag "only_media" :> QueryFlag "exclude_replies" :> Get '[JSON] [Status] :<|> "accounts" :> Capture "id" (Uid Account) :> "follow" :> Get '[JSON] Account :<|> "accounts" :> Capture "id" (Uid Account) :> "unfollow" :> Get '[JSON] Account :<|> "accounts" :> Capture "id" (Uid Account) :> "block" :> Get '[JSON] Account :<|> "accounts" :> Capture "id" (Uid Account) :> "unblock" :> Get '[JSON] Account :<|> "accounts" :> Capture "id" (Uid Account) :> "mute" :> Get '[JSON] Account :<|> "accounts" :> Capture "id" (Uid Account) :> "unmute" :> Get '[JSON] Account :<|> "accounts" :> "relationships" :> QueryParams "id" (Uid Account) :> Get '[JSON] [Relationship] :<|> "accounts" :> "search" :> QueryParam "q" T.Text :> QueryParam "limit" Integer :> Get '[JSON] [Account] -- | Secure Accounts API type type Accounts = AuthWrapper (AuthProtect MastodonAuth) AccountsInsecure accountsApi :: Proxy Accounts accountsApi = Proxy account_ :: Auth -> Uid Account -> ClientM Account verifyCredentials_ :: Auth -> ClientM Account followers_ :: Auth -> Uid Account -> ClientM [Account] following_ :: Auth -> Uid Account -> ClientM [Account] statuses_ :: Auth -> Uid Account -> Bool -> Bool -> ClientM [Status] follow_ :: Auth -> Uid Account -> ClientM Account unfollow_ :: Auth -> Uid Account -> ClientM Account block_ :: Auth -> Uid Account -> ClientM Account unblock_ :: Auth -> Uid Account -> ClientM Account mute_ :: Auth -> Uid Account -> ClientM Account unmute_ :: Auth -> Uid Account -> ClientM Account relationships_ :: Auth -> [Uid Account] -> ClientM [Relationship] search_ :: Auth -> Maybe T.Text -> Maybe Integer -> ClientM [Account] account_ :<|> verifyCredentials_ :<|> followers_ :<|> following_ :<|> statuses_ :<|> follow_ :<|> unfollow_ :<|> block_ :<|> unblock_ :<|> mute_ :<|> unmute_ :<|> relationships_ :<|> search_ = client accountsApi -- | Retrieve an @Account@ from an account id. getAccountByUid :: Uid Account -> Mastodon Account getAccountByUid aid = ReaderT $ \t -> account_ (tokenToAuth t) aid verifyCredentials :: Mastodon Account verifyCredentials = ReaderT $ \t -> verifyCredentials_ $ tokenToAuth t getFollowersForUid :: Uid Account -> Mastodon [Account] getFollowersForUid aid = ReaderT $ \t -> followers_ (tokenToAuth t) aid getFollowingForUid :: Uid Account -> Mastodon [Account] getFollowingForUid aid = ReaderT $ \t -> following_ (tokenToAuth t) aid getStatusesForUid :: Uid Account -> Bool -> Bool -> Mastodon [Status] getStatusesForUid aid onlyMedia noReplies = ReaderT $ \t -> statuses_ (tokenToAuth t) aid onlyMedia noReplies followUid :: Uid Account -> Mastodon Account followUid tid = ReaderT $ \t -> follow_ (tokenToAuth t) tid unfollowUid :: Uid Account -> Mastodon Account unfollowUid tid = ReaderT $ \t -> unfollow_ (tokenToAuth t) tid blockUid :: Uid Account -> Mastodon Account blockUid tid = ReaderT $ \t -> block_ (tokenToAuth t) tid unblockUid :: Uid Account -> Mastodon Account unblockUid tid = ReaderT $ \t -> unblock_ (tokenToAuth t) tid muteUid :: Uid Account -> Mastodon Account muteUid tid = ReaderT $ \t -> mute_ (tokenToAuth t) tid unmuteUid :: Uid Account -> Mastodon Account unmuteUid tid = ReaderT $ \t -> unmute_ (tokenToAuth t) tid getRelationships :: [Uid Account] -> Mastodon [Relationship] getRelationships tids = ReaderT $ \t -> relationships_ (tokenToAuth t) tids searchAccounts :: Maybe T.Text -> Maybe Integer -> Mastodon [Account] searchAccounts q i = ReaderT $ \t -> search_ (tokenToAuth t) q i
cmdd/mastodon-api
src/Web/Mastodon/API/Accounts.hs
bsd-3-clause
5,199
0
59
1,224
1,563
793
770
96
1
-- http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_4_A -- A / B Problem -- input: 3 2 -- output: 1 1 1.50000 import Control.Applicative import Data.Fixed main = do [a,b] <- map (read :: String -> Int) . words <$> getLine putStrLn $ show (a `div` b) ++ " " ++ show (a `mod` b) ++ " " ++ show ((realToFrac a) / (realToFrac b) :: Fixed E9)
ku00/aoj-haskell
src/ITP1_4_A.hs
bsd-3-clause
387
0
14
98
129
70
59
8
1
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Home where import Import -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getHomeR :: Handler RepHtml getHomeR = do defaultLayout $ do aDomId <- lift newIdent setTitle "Welcome" $(widgetFile "homepage") postHomeR :: Handler RepHtml postHomeR = do defaultLayout $ do aDomId <- lift newIdent setTitle "Welcome" $(widgetFile "homepage")
mkrauskopf/ouch-web
Handler/Home.hs
bsd-3-clause
760
0
12
170
109
54
55
15
1